| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740 |
- function Ade(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}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 i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)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(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var j_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function mc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rM={exports:{}},uv={};var S8;function jde(){if(S8)return uv;S8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,s){var o=null;if(s!==void 0&&(o=""+s),i.key!==void 0&&(o=""+i.key),"key"in i){s={};for(var l in i)l!=="key"&&(s[l]=i[l])}else s=i;return i=s.ref,{$$typeof:t,type:r,key:o,ref:i!==void 0?i:null,props:s}}return uv.Fragment=e,uv.jsx=n,uv.jsxs=n,uv}var _8;function Mde(){return _8||(_8=1,rM.exports=jde()),rM.exports}var a=Mde(),aM={exports:{}},Xn={};var k8;function Ede(){if(k8)return Xn;k8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=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"),d=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),m=Symbol.for("react.activity"),p=Symbol.iterator;function f(W){return W===null||typeof W!="object"?null:(W=p&&W[p]||W["@@iterator"],typeof W=="function"?W:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,g={};function b(W,re,ce){this.props=W,this.context=re,this.refs=g,this.updater=ce||x}b.prototype.isReactComponent={},b.prototype.setState=function(W,re){if(typeof W!="object"&&typeof W!="function"&&W!=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,W,re,"setState")},b.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function _(){}_.prototype=b.prototype;function C(W,re,ce){this.props=W,this.context=re,this.refs=g,this.updater=ce||x}var P=C.prototype=new _;P.constructor=C,v(P,b.prototype),P.isPureReactComponent=!0;var N=Array.isArray;function A(){}var T={H:null,A:null,T:null,S:null},F=Object.prototype.hasOwnProperty;function k(W,re,ce){var xe=ce.ref;return{$$typeof:t,type:W,key:re,ref:xe!==void 0?xe:null,props:ce}}function D(W,re){return k(W.type,re,W.props)}function H(W){return typeof W=="object"&&W!==null&&W.$$typeof===t}function z(W){var re={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(ce){return re[ce]})}var X=/\/+/g;function L(W,re){return typeof W=="object"&&W!==null&&W.key!=null?z(""+W.key):re.toString(36)}function ne(W){switch(W.status){case"fulfilled":return W.value;case"rejected":throw W.reason;default:switch(typeof W.status=="string"?W.then(A,A):(W.status="pending",W.then(function(re){W.status==="pending"&&(W.status="fulfilled",W.value=re)},function(re){W.status==="pending"&&(W.status="rejected",W.reason=re)})),W.status){case"fulfilled":return W.value;case"rejected":throw W.reason}}throw W}function ie(W,re,ce,xe,Ne){var $=typeof W;($==="undefined"||$==="boolean")&&(W=null);var Y=!1;if(W===null)Y=!0;else switch($){case"bigint":case"string":case"number":Y=!0;break;case"object":switch(W.$$typeof){case t:case e:Y=!0;break;case u:return Y=W._init,ie(Y(W._payload),re,ce,xe,Ne)}}if(Y)return Ne=Ne(W),Y=xe===""?"."+L(W,0):xe,N(Ne)?(ce="",Y!=null&&(ce=Y.replace(X,"$&/")+"/"),ie(Ne,re,ce,"",function(O){return O})):Ne!=null&&(H(Ne)&&(Ne=D(Ne,ce+(Ne.key==null||W&&W.key===Ne.key?"":(""+Ne.key).replace(X,"$&/")+"/")+Y)),re.push(Ne)),1;Y=0;var E=xe===""?".":xe+":";if(N(W))for(var j=0;j<W.length;j++)xe=W[j],$=E+L(xe,j),Y+=ie(xe,re,ce,$,Ne);else if(j=f(W),typeof j=="function")for(W=j.call(W),j=0;!(xe=W.next()).done;)xe=xe.value,$=E+L(xe,j++),Y+=ie(xe,re,ce,$,Ne);else if($==="object"){if(typeof W.then=="function")return ie(ne(W),re,ce,xe,Ne);throw re=String(W),Error("Objects are not valid as a React child (found: "+(re==="[object Object]"?"object with keys {"+Object.keys(W).join(", ")+"}":re)+"). If you meant to render a collection of children, use an array instead.")}return Y}function ee(W,re,ce){if(W==null)return W;var xe=[],Ne=0;return ie(W,xe,"","",function($){return re.call(ce,$,Ne++)}),xe}function ue(W){if(W._status===-1){var re=W._result;re=re(),re.then(function(ce){(W._status===0||W._status===-1)&&(W._status=1,W._result=ce)},function(ce){(W._status===0||W._status===-1)&&(W._status=2,W._result=ce)}),W._status===-1&&(W._status=0,W._result=re)}if(W._status===1)return W._result.default;throw W._result}var le=typeof reportError=="function"?reportError:function(W){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var re=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof W=="object"&&W!==null&&typeof W.message=="string"?String(W.message):String(W),error:W});if(!window.dispatchEvent(re))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",W);return}console.error(W)},oe={map:ee,forEach:function(W,re,ce){ee(W,function(){re.apply(this,arguments)},ce)},count:function(W){var re=0;return ee(W,function(){re++}),re},toArray:function(W){return ee(W,function(re){return re})||[]},only:function(W){if(!H(W))throw Error("React.Children.only expected to receive a single React element child.");return W}};return Xn.Activity=m,Xn.Children=oe,Xn.Component=b,Xn.Fragment=n,Xn.Profiler=i,Xn.PureComponent=C,Xn.StrictMode=r,Xn.Suspense=c,Xn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,Xn.__COMPILER_RUNTIME={__proto__:null,c:function(W){return T.H.useMemoCache(W)}},Xn.cache=function(W){return function(){return W.apply(null,arguments)}},Xn.cacheSignal=function(){return null},Xn.cloneElement=function(W,re,ce){if(W==null)throw Error("The argument must be a React element, but you passed "+W+".");var xe=v({},W.props),Ne=W.key;if(re!=null)for($ in re.key!==void 0&&(Ne=""+re.key),re)!F.call(re,$)||$==="key"||$==="__self"||$==="__source"||$==="ref"&&re.ref===void 0||(xe[$]=re[$]);var $=arguments.length-2;if($===1)xe.children=ce;else if(1<$){for(var Y=Array($),E=0;E<$;E++)Y[E]=arguments[E+2];xe.children=Y}return k(W.type,Ne,xe)},Xn.createContext=function(W){return W={$$typeof:o,_currentValue:W,_currentValue2:W,_threadCount:0,Provider:null,Consumer:null},W.Provider=W,W.Consumer={$$typeof:s,_context:W},W},Xn.createElement=function(W,re,ce){var xe,Ne={},$=null;if(re!=null)for(xe in re.key!==void 0&&($=""+re.key),re)F.call(re,xe)&&xe!=="key"&&xe!=="__self"&&xe!=="__source"&&(Ne[xe]=re[xe]);var Y=arguments.length-2;if(Y===1)Ne.children=ce;else if(1<Y){for(var E=Array(Y),j=0;j<Y;j++)E[j]=arguments[j+2];Ne.children=E}if(W&&W.defaultProps)for(xe in Y=W.defaultProps,Y)Ne[xe]===void 0&&(Ne[xe]=Y[xe]);return k(W,$,Ne)},Xn.createRef=function(){return{current:null}},Xn.forwardRef=function(W){return{$$typeof:l,render:W}},Xn.isValidElement=H,Xn.lazy=function(W){return{$$typeof:u,_payload:{_status:-1,_result:W},_init:ue}},Xn.memo=function(W,re){return{$$typeof:d,type:W,compare:re===void 0?null:re}},Xn.startTransition=function(W){var re=T.T,ce={};T.T=ce;try{var xe=W(),Ne=T.S;Ne!==null&&Ne(ce,xe),typeof xe=="object"&&xe!==null&&typeof xe.then=="function"&&xe.then(A,le)}catch($){le($)}finally{re!==null&&ce.types!==null&&(re.types=ce.types),T.T=re}},Xn.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},Xn.use=function(W){return T.H.use(W)},Xn.useActionState=function(W,re,ce){return T.H.useActionState(W,re,ce)},Xn.useCallback=function(W,re){return T.H.useCallback(W,re)},Xn.useContext=function(W){return T.H.useContext(W)},Xn.useDebugValue=function(){},Xn.useDeferredValue=function(W,re){return T.H.useDeferredValue(W,re)},Xn.useEffect=function(W,re){return T.H.useEffect(W,re)},Xn.useEffectEvent=function(W){return T.H.useEffectEvent(W)},Xn.useId=function(){return T.H.useId()},Xn.useImperativeHandle=function(W,re,ce){return T.H.useImperativeHandle(W,re,ce)},Xn.useInsertionEffect=function(W,re){return T.H.useInsertionEffect(W,re)},Xn.useLayoutEffect=function(W,re){return T.H.useLayoutEffect(W,re)},Xn.useMemo=function(W,re){return T.H.useMemo(W,re)},Xn.useOptimistic=function(W,re){return T.H.useOptimistic(W,re)},Xn.useReducer=function(W,re,ce){return T.H.useReducer(W,re,ce)},Xn.useRef=function(W){return T.H.useRef(W)},Xn.useState=function(W){return T.H.useState(W)},Xn.useSyncExternalStore=function(W,re,ce){return T.H.useSyncExternalStore(W,re,ce)},Xn.useTransition=function(){return T.H.useTransition()},Xn.version="19.2.4",Xn}var N8;function xg(){return N8||(N8=1,aM.exports=Ede()),aM.exports}var w=xg();const ea=mc(w),Dde=Ade({__proto__:null,default:ea},[w]);var iM={exports:{}},mv={},sM={exports:{}},oM={};var C8;function Fde(){return C8||(C8=1,(function(t){function e(ie,ee){var ue=ie.length;ie.push(ee);e:for(;0<ue;){var le=ue-1>>>1,oe=ie[le];if(0<i(oe,ee))ie[le]=ee,ie[ue]=oe,ue=le;else break e}}function n(ie){return ie.length===0?null:ie[0]}function r(ie){if(ie.length===0)return null;var ee=ie[0],ue=ie.pop();if(ue!==ee){ie[0]=ue;e:for(var le=0,oe=ie.length,W=oe>>>1;le<W;){var re=2*(le+1)-1,ce=ie[re],xe=re+1,Ne=ie[xe];if(0>i(ce,ue))xe<oe&&0>i(Ne,ce)?(ie[le]=Ne,ie[xe]=ue,le=xe):(ie[le]=ce,ie[re]=ue,le=re);else if(xe<oe&&0>i(Ne,ue))ie[le]=Ne,ie[xe]=ue,le=xe;else break e}}return ee}function i(ie,ee){var ue=ie.sortIndex-ee.sortIndex;return ue!==0?ue:ie.id-ee.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=[],d=[],u=1,m=null,p=3,f=!1,x=!1,v=!1,g=!1,b=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate<"u"?setImmediate:null;function P(ie){for(var ee=n(d);ee!==null;){if(ee.callback===null)r(d);else if(ee.startTime<=ie)r(d),ee.sortIndex=ee.expirationTime,e(c,ee);else break;ee=n(d)}}function N(ie){if(v=!1,P(ie),!x)if(n(c)!==null)x=!0,A||(A=!0,z());else{var ee=n(d);ee!==null&&ne(N,ee.startTime-ie)}}var A=!1,T=-1,F=5,k=-1;function D(){return g?!0:!(t.unstable_now()-k<F)}function H(){if(g=!1,A){var ie=t.unstable_now();k=ie;var ee=!0;try{e:{x=!1,v&&(v=!1,_(T),T=-1),f=!0;var ue=p;try{t:{for(P(ie),m=n(c);m!==null&&!(m.expirationTime>ie&&D());){var le=m.callback;if(typeof le=="function"){m.callback=null,p=m.priorityLevel;var oe=le(m.expirationTime<=ie);if(ie=t.unstable_now(),typeof oe=="function"){m.callback=oe,P(ie),ee=!0;break t}m===n(c)&&r(c),P(ie)}else r(c);m=n(c)}if(m!==null)ee=!0;else{var W=n(d);W!==null&&ne(N,W.startTime-ie),ee=!1}}break e}finally{m=null,p=ue,f=!1}ee=void 0}}finally{ee?z():A=!1}}}var z;if(typeof C=="function")z=function(){C(H)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,L=X.port2;X.port1.onmessage=H,z=function(){L.postMessage(null)}}else z=function(){b(H,0)};function ne(ie,ee){T=b(function(){ie(t.unstable_now())},ee)}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(ie){ie.callback=null},t.unstable_forceFrameRate=function(ie){0>ie||125<ie?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):F=0<ie?Math.floor(1e3/ie):5},t.unstable_getCurrentPriorityLevel=function(){return p},t.unstable_next=function(ie){switch(p){case 1:case 2:case 3:var ee=3;break;default:ee=p}var ue=p;p=ee;try{return ie()}finally{p=ue}},t.unstable_requestPaint=function(){g=!0},t.unstable_runWithPriority=function(ie,ee){switch(ie){case 1:case 2:case 3:case 4:case 5:break;default:ie=3}var ue=p;p=ie;try{return ee()}finally{p=ue}},t.unstable_scheduleCallback=function(ie,ee,ue){var le=t.unstable_now();switch(typeof ue=="object"&&ue!==null?(ue=ue.delay,ue=typeof ue=="number"&&0<ue?le+ue:le):ue=le,ie){case 1:var oe=-1;break;case 2:oe=250;break;case 5:oe=1073741823;break;case 4:oe=1e4;break;default:oe=5e3}return oe=ue+oe,ie={id:u++,callback:ee,priorityLevel:ie,startTime:ue,expirationTime:oe,sortIndex:-1},ue>le?(ie.sortIndex=ue,e(d,ie),n(c)===null&&ie===n(d)&&(v?(_(T),T=-1):v=!0,ne(N,ue-le))):(ie.sortIndex=oe,e(c,ie),x||f||(x=!0,A||(A=!0,z()))),ie},t.unstable_shouldYield=D,t.unstable_wrapCallback=function(ie){var ee=p;return function(){var ue=p;p=ee;try{return ie.apply(this,arguments)}finally{p=ue}}}})(oM)),oM}var P8;function Rde(){return P8||(P8=1,sM.exports=Fde()),sM.exports}var lM={exports:{}},ws={};var T8;function Lde(){if(T8)return ws;T8=1;var t=xg();function e(c){var d="https://react.dev/errors/"+c;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var u=2;u<arguments.length;u++)d+="&args[]="+encodeURIComponent(arguments[u])}return"Minified React error #"+c+"; visit "+d+" 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},i=Symbol.for("react.portal");function s(c,d,u){var m=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:m==null?null:""+m,children:c,containerInfo:d,implementation:u}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,d){if(c==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return ws.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,ws.createPortal=function(c,d){var u=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return s(c,d,null,u)},ws.flushSync=function(c){var d=o.T,u=r.p;try{if(o.T=null,r.p=2,c)return c()}finally{o.T=d,r.p=u,r.d.f()}},ws.preconnect=function(c,d){typeof c=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,r.d.C(c,d))},ws.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},ws.preinit=function(c,d){if(typeof c=="string"&&d&&typeof d.as=="string"){var u=d.as,m=l(u,d.crossOrigin),p=typeof d.integrity=="string"?d.integrity:void 0,f=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;u==="style"?r.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:m,integrity:p,fetchPriority:f}):u==="script"&&r.d.X(c,{crossOrigin:m,integrity:p,fetchPriority:f,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},ws.preinitModule=function(c,d){if(typeof c=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var u=l(d.as,d.crossOrigin);r.d.M(c,{crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&r.d.M(c)},ws.preload=function(c,d){if(typeof c=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var u=d.as,m=l(u,d.crossOrigin);r.d.L(c,u,{crossOrigin:m,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},ws.preloadModule=function(c,d){if(typeof c=="string")if(d){var u=l(d.as,d.crossOrigin);r.d.m(c,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else r.d.m(c)},ws.requestFormReset=function(c){r.d.r(c)},ws.unstable_batchedUpdates=function(c,d){return c(d)},ws.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},ws.useFormStatus=function(){return o.H.useHostTransitionStatus()},ws.version="19.2.4",ws}var A8;function MY(){if(A8)return lM.exports;A8=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(),lM.exports=Lde(),lM.exports}var j8;function Ode(){if(j8)return mv;j8=1;var t=Rde(),e=xg(),n=MY();function r(h){var y="https://react.dev/errors/"+h;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var S=2;S<arguments.length;S++)y+="&args[]="+encodeURIComponent(arguments[S])}return"Minified React error #"+h+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)}function s(h){var y=h,S=h;if(h.alternate)for(;y.return;)y=y.return;else{h=y;do y=h,(y.flags&4098)!==0&&(S=y.return),h=y.return;while(h)}return y.tag===3?S:null}function o(h){if(h.tag===13){var y=h.memoizedState;if(y===null&&(h=h.alternate,h!==null&&(y=h.memoizedState)),y!==null)return y.dehydrated}return null}function l(h){if(h.tag===31){var y=h.memoizedState;if(y===null&&(h=h.alternate,h!==null&&(y=h.memoizedState)),y!==null)return y.dehydrated}return null}function c(h){if(s(h)!==h)throw Error(r(188))}function d(h){var y=h.alternate;if(!y){if(y=s(h),y===null)throw Error(r(188));return y!==h?null:h}for(var S=h,M=y;;){var q=S.return;if(q===null)break;var Z=q.alternate;if(Z===null){if(M=q.return,M!==null){S=M;continue}break}if(q.child===Z.child){for(Z=q.child;Z;){if(Z===S)return c(q),h;if(Z===M)return c(q),y;Z=Z.sibling}throw Error(r(188))}if(S.return!==M.return)S=q,M=Z;else{for(var ke=!1,Ue=q.child;Ue;){if(Ue===S){ke=!0,S=q,M=Z;break}if(Ue===M){ke=!0,M=q,S=Z;break}Ue=Ue.sibling}if(!ke){for(Ue=Z.child;Ue;){if(Ue===S){ke=!0,S=Z,M=q;break}if(Ue===M){ke=!0,M=Z,S=q;break}Ue=Ue.sibling}if(!ke)throw Error(r(189))}}if(S.alternate!==M)throw Error(r(190))}if(S.tag!==3)throw Error(r(188));return S.stateNode.current===S?h:y}function u(h){var y=h.tag;if(y===5||y===26||y===27||y===6)return h;for(h=h.child;h!==null;){if(y=u(h),y!==null)return y;h=h.sibling}return null}var m=Object.assign,p=Symbol.for("react.element"),f=Symbol.for("react.transitional.element"),x=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),g=Symbol.for("react.strict_mode"),b=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),C=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),k=Symbol.for("react.activity"),D=Symbol.for("react.memo_cache_sentinel"),H=Symbol.iterator;function z(h){return h===null||typeof h!="object"?null:(h=H&&h[H]||h["@@iterator"],typeof h=="function"?h:null)}var X=Symbol.for("react.client.reference");function L(h){if(h==null)return null;if(typeof h=="function")return h.$$typeof===X?null:h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case v:return"Fragment";case b:return"Profiler";case g:return"StrictMode";case N:return"Suspense";case A:return"SuspenseList";case k:return"Activity"}if(typeof h=="object")switch(h.$$typeof){case x:return"Portal";case C:return h.displayName||"Context";case _:return(h._context.displayName||"Context")+".Consumer";case P:var y=h.render;return h=h.displayName,h||(h=y.displayName||y.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case T:return y=h.displayName||null,y!==null?y:L(h.type)||"Memo";case F:y=h._payload,h=h._init;try{return L(h(y))}catch{}}return null}var ne=Array.isArray,ie=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ue={pending:!1,data:null,method:null,action:null},le=[],oe=-1;function W(h){return{current:h}}function re(h){0>oe||(h.current=le[oe],le[oe]=null,oe--)}function ce(h,y){oe++,le[oe]=h.current,h.current=y}var xe=W(null),Ne=W(null),$=W(null),Y=W(null);function E(h,y){switch(ce($,y),ce(Ne,h),ce(xe,null),y.nodeType){case 9:case 11:h=(h=y.documentElement)&&(h=h.namespaceURI)?VB(h):0;break;default:if(h=y.tagName,y=y.namespaceURI)y=VB(y),h=GB(y,h);else switch(h){case"svg":h=1;break;case"math":h=2;break;default:h=0}}re(xe),ce(xe,h)}function j(){re(xe),re(Ne),re($)}function O(h){h.memoizedState!==null&&ce(Y,h);var y=xe.current,S=GB(y,h.type);y!==S&&(ce(Ne,h),ce(xe,S))}function K(h){Ne.current===h&&(re(xe),re(Ne)),Y.current===h&&(re(Y),ov._currentValue=ue)}var B,he;function I(h){if(B===void 0)try{throw Error()}catch(S){var y=S.stack.trim().match(/\n( *(at )?)/);B=y&&y[1]||"",he=-1<S.stack.indexOf(`
- at`)?" (<anonymous>)":-1<S.stack.indexOf("@")?"@unknown:0:0":""}return`
- `+B+h+he}var V=!1;function Q(h,y){if(!h||V)return"";V=!0;var S=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var M={DetermineComponentFrameRoot:function(){try{if(y){var It=function(){throw Error()};if(Object.defineProperty(It.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(It,[])}catch(Dt){var Ct=Dt}Reflect.construct(h,[],It)}else{try{It.call()}catch(Dt){Ct=Dt}h.call(It.prototype)}}else{try{throw Error()}catch(Dt){Ct=Dt}(It=h())&&typeof It.catch=="function"&&It.catch(function(){})}}catch(Dt){if(Dt&&Ct&&typeof Dt.stack=="string")return[Dt.stack,Ct.stack]}return[null,null]}};M.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var q=Object.getOwnPropertyDescriptor(M.DetermineComponentFrameRoot,"name");q&&q.configurable&&Object.defineProperty(M.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Z=M.DetermineComponentFrameRoot(),ke=Z[0],Ue=Z[1];if(ke&&Ue){var nt=ke.split(`
- `),Nt=Ue.split(`
- `);for(q=M=0;M<nt.length&&!nt[M].includes("DetermineComponentFrameRoot");)M++;for(;q<Nt.length&&!Nt[q].includes("DetermineComponentFrameRoot");)q++;if(M===nt.length||q===Nt.length)for(M=nt.length-1,q=Nt.length-1;1<=M&&0<=q&&nt[M]!==Nt[q];)q--;for(;1<=M&&0<=q;M--,q--)if(nt[M]!==Nt[q]){if(M!==1||q!==1)do if(M--,q--,0>q||nt[M]!==Nt[q]){var Lt=`
- `+nt[M].replace(" at new "," at ");return h.displayName&&Lt.includes("<anonymous>")&&(Lt=Lt.replace("<anonymous>",h.displayName)),Lt}while(1<=M&&0<=q);break}}}finally{V=!1,Error.prepareStackTrace=S}return(S=h?h.displayName||h.name:"")?I(S):""}function G(h,y){switch(h.tag){case 26:case 27:case 5:return I(h.type);case 16:return I("Lazy");case 13:return h.child!==y&&y!==null?I("Suspense Fallback"):I("Suspense");case 19:return I("SuspenseList");case 0:case 15:return Q(h.type,!1);case 11:return Q(h.type.render,!1);case 1:return Q(h.type,!0);case 31:return I("Activity");default:return""}}function J(h){try{var y="",S=null;do y+=G(h,S),S=h,h=h.return;while(h);return y}catch(M){return`
- Error generating stack: `+M.message+`
- `+M.stack}}var se=Object.prototype.hasOwnProperty,fe=t.unstable_scheduleCallback,pe=t.unstable_cancelCallback,de=t.unstable_shouldYield,U=t.unstable_requestPaint,R=t.unstable_now,ae=t.unstable_getCurrentPriorityLevel,_e=t.unstable_ImmediatePriority,Se=t.unstable_UserBlockingPriority,ye=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,ve=t.unstable_IdlePriority,je=t.log,Re=t.unstable_setDisableYieldValue,Ee=null,Te=null;function Me(h){if(typeof je=="function"&&Re(h),Te&&typeof Te.setStrictMode=="function")try{Te.setStrictMode(Ee,h)}catch{}}var Be=Math.clz32?Math.clz32:te,Ke=Math.log,tt=Math.LN2;function te(h){return h>>>=0,h===0?32:31-(Ke(h)/tt|0)|0}var Ie=256,be=262144,$e=4194304;function He(h){var y=h&42;if(y!==0)return y;switch(h&-h){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 h&261888;case 262144:case 524288:case 1048576:case 2097152:return h&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return h&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return h}}function ge(h,y,S){var M=h.pendingLanes;if(M===0)return 0;var q=0,Z=h.suspendedLanes,ke=h.pingedLanes;h=h.warmLanes;var Ue=M&134217727;return Ue!==0?(M=Ue&~Z,M!==0?q=He(M):(ke&=Ue,ke!==0?q=He(ke):S||(S=Ue&~h,S!==0&&(q=He(S))))):(Ue=M&~Z,Ue!==0?q=He(Ue):ke!==0?q=He(ke):S||(S=M&~h,S!==0&&(q=He(S)))),q===0?0:y!==0&&y!==q&&(y&Z)===0&&(Z=q&-q,S=y&-y,Z>=S||Z===32&&(S&4194048)!==0)?y:q}function Pe(h,y){return(h.pendingLanes&~(h.suspendedLanes&~h.pingedLanes)&y)===0}function qe(h,y){switch(h){case 1:case 2:case 4:case 8:case 64:return y+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 y+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 Ze(){var h=$e;return $e<<=1,($e&62914560)===0&&($e=4194304),h}function ut(h){for(var y=[],S=0;31>S;S++)y.push(h);return y}function vt(h,y){h.pendingLanes|=y,y!==268435456&&(h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0)}function wt(h,y,S,M,q,Z){var ke=h.pendingLanes;h.pendingLanes=S,h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0,h.expiredLanes&=S,h.entangledLanes&=S,h.errorRecoveryDisabledLanes&=S,h.shellSuspendCounter=0;var Ue=h.entanglements,nt=h.expirationTimes,Nt=h.hiddenUpdates;for(S=ke&~S;0<S;){var Lt=31-Be(S),It=1<<Lt;Ue[Lt]=0,nt[Lt]=-1;var Ct=Nt[Lt];if(Ct!==null)for(Nt[Lt]=null,Lt=0;Lt<Ct.length;Lt++){var Dt=Ct[Lt];Dt!==null&&(Dt.lane&=-536870913)}S&=~It}M!==0&&$t(h,M,0),Z!==0&&q===0&&h.tag!==0&&(h.suspendedLanes|=Z&~(ke&~y))}function $t(h,y,S){h.pendingLanes|=y,h.suspendedLanes&=~y;var M=31-Be(y);h.entangledLanes|=y,h.entanglements[M]=h.entanglements[M]|1073741824|S&261930}function Qt(h,y){var S=h.entangledLanes|=y;for(h=h.entanglements;S;){var M=31-Be(S),q=1<<M;q&y|h[M]&y&&(h[M]|=y),S&=~q}}function en(h,y){var S=y&-y;return S=(S&42)!==0?1:Xt(S),(S&(h.suspendedLanes|y))!==0?0:S}function Xt(h){switch(h){case 2:h=1;break;case 8:h=4;break;case 32:h=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:h=128;break;case 268435456:h=134217728;break;default:h=0}return h}function tn(h){return h&=-h,2<h?8<h?(h&134217727)!==0?32:268435456:8:2}function Ge(){var h=ee.p;return h!==0?h:(h=window.event,h===void 0?32:f8(h.type))}function Ft(h,y){var S=ee.p;try{return ee.p=h,y()}finally{ee.p=S}}var Yt=Math.random().toString(36).slice(2),Pt="__reactFiber$"+Yt,pt="__reactProps$"+Yt,Wt="__reactContainer$"+Yt,Ut="__reactEvents$"+Yt,ze="__reactListeners$"+Yt,st="__reactHandles$"+Yt,ht="__reactResources$"+Yt,rt="__reactMarker$"+Yt;function Le(h){delete h[Pt],delete h[pt],delete h[Ut],delete h[ze],delete h[st]}function Oe(h){var y=h[Pt];if(y)return y;for(var S=h.parentNode;S;){if(y=S[Wt]||S[Pt]){if(S=y.alternate,y.child!==null||S!==null&&S.child!==null)for(h=JB(h);h!==null;){if(S=h[Pt])return S;h=JB(h)}return y}h=S,S=h.parentNode}return null}function Ce(h){if(h=h[Pt]||h[Wt]){var y=h.tag;if(y===5||y===6||y===13||y===31||y===26||y===27||y===3)return h}return null}function We(h){var y=h.tag;if(y===5||y===26||y===27||y===6)return h.stateNode;throw Error(r(33))}function Je(h){var y=h[ht];return y||(y=h[ht]={hoistableStyles:new Map,hoistableScripts:new Map}),y}function Xe(h){h[rt]=!0}var Ye=new Set,St={};function et(h,y){jt(h,y),jt(h+"Capture",y)}function jt(h,y){for(St[h]=y,h=0;h<y.length;h++)Ye.add(y[h])}var bt=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]*$"),Ve={},gt={};function Et(h){return se.call(gt,h)?!0:se.call(Ve,h)?!1:bt.test(h)?gt[h]=!0:(Ve[h]=!0,!1)}function Gt(h,y,S){if(Et(y))if(S===null)h.removeAttribute(y);else{switch(typeof S){case"undefined":case"function":case"symbol":h.removeAttribute(y);return;case"boolean":var M=y.toLowerCase().slice(0,5);if(M!=="data-"&&M!=="aria-"){h.removeAttribute(y);return}}h.setAttribute(y,""+S)}}function on(h,y,S){if(S===null)h.removeAttribute(y);else{switch(typeof S){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(y);return}h.setAttribute(y,""+S)}}function fn(h,y,S,M){if(M===null)h.removeAttribute(S);else{switch(typeof M){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(S);return}h.setAttributeNS(y,S,""+M)}}function Ln(h){switch(typeof h){case"bigint":case"boolean":case"number":case"string":case"undefined":return h;case"object":return h;default:return""}}function yn(h){var y=h.type;return(h=h.nodeName)&&h.toLowerCase()==="input"&&(y==="checkbox"||y==="radio")}function hn(h,y,S){var M=Object.getOwnPropertyDescriptor(h.constructor.prototype,y);if(!h.hasOwnProperty(y)&&typeof M<"u"&&typeof M.get=="function"&&typeof M.set=="function"){var q=M.get,Z=M.set;return Object.defineProperty(h,y,{configurable:!0,get:function(){return q.call(this)},set:function(ke){S=""+ke,Z.call(this,ke)}}),Object.defineProperty(h,y,{enumerable:M.enumerable}),{getValue:function(){return S},setValue:function(ke){S=""+ke},stopTracking:function(){h._valueTracker=null,delete h[y]}}}}function xn(h){if(!h._valueTracker){var y=yn(h)?"checked":"value";h._valueTracker=hn(h,y,""+h[y])}}function Nn(h){if(!h)return!1;var y=h._valueTracker;if(!y)return!0;var S=y.getValue(),M="";return h&&(M=yn(h)?h.checked?"true":"false":h.value),h=M,h!==S?(y.setValue(h),!0):!1}function Pn(h){if(h=h||(typeof document<"u"?document:void 0),typeof h>"u")return null;try{return h.activeElement||h.body}catch{return h.body}}var Nr=/[\n"\\]/g;function Sn(h){return h.replace(Nr,function(y){return"\\"+y.charCodeAt(0).toString(16)+" "})}function Pa(h,y,S,M,q,Z,ke,Ue){h.name="",ke!=null&&typeof ke!="function"&&typeof ke!="symbol"&&typeof ke!="boolean"?h.type=ke:h.removeAttribute("type"),y!=null?ke==="number"?(y===0&&h.value===""||h.value!=y)&&(h.value=""+Ln(y)):h.value!==""+Ln(y)&&(h.value=""+Ln(y)):ke!=="submit"&&ke!=="reset"||h.removeAttribute("value"),y!=null?ya(h,ke,Ln(y)):S!=null?ya(h,ke,Ln(S)):M!=null&&h.removeAttribute("value"),q==null&&Z!=null&&(h.defaultChecked=!!Z),q!=null&&(h.checked=q&&typeof q!="function"&&typeof q!="symbol"),Ue!=null&&typeof Ue!="function"&&typeof Ue!="symbol"&&typeof Ue!="boolean"?h.name=""+Ln(Ue):h.removeAttribute("name")}function On(h,y,S,M,q,Z,ke,Ue){if(Z!=null&&typeof Z!="function"&&typeof Z!="symbol"&&typeof Z!="boolean"&&(h.type=Z),y!=null||S!=null){if(!(Z!=="submit"&&Z!=="reset"||y!=null)){xn(h);return}S=S!=null?""+Ln(S):"",y=y!=null?""+Ln(y):S,Ue||y===h.value||(h.value=y),h.defaultValue=y}M=M??q,M=typeof M!="function"&&typeof M!="symbol"&&!!M,h.checked=Ue?h.checked:!!M,h.defaultChecked=!!M,ke!=null&&typeof ke!="function"&&typeof ke!="symbol"&&typeof ke!="boolean"&&(h.name=ke),xn(h)}function ya(h,y,S){y==="number"&&Pn(h.ownerDocument)===h||h.defaultValue===""+S||(h.defaultValue=""+S)}function ua(h,y,S,M){if(h=h.options,y){y={};for(var q=0;q<S.length;q++)y["$"+S[q]]=!0;for(S=0;S<h.length;S++)q=y.hasOwnProperty("$"+h[S].value),h[S].selected!==q&&(h[S].selected=q),q&&M&&(h[S].defaultSelected=!0)}else{for(S=""+Ln(S),y=null,q=0;q<h.length;q++){if(h[q].value===S){h[q].selected=!0,M&&(h[q].defaultSelected=!0);return}y!==null||h[q].disabled||(y=h[q])}y!==null&&(y.selected=!0)}}function Zr(h,y,S){if(y!=null&&(y=""+Ln(y),y!==h.value&&(h.value=y),S==null)){h.defaultValue!==y&&(h.defaultValue=y);return}h.defaultValue=S!=null?""+Ln(S):""}function sa(h,y,S,M){if(y==null){if(M!=null){if(S!=null)throw Error(r(92));if(ne(M)){if(1<M.length)throw Error(r(93));M=M[0]}S=M}S==null&&(S=""),y=S}S=Ln(y),h.defaultValue=S,M=h.textContent,M===S&&M!==""&&M!==null&&(h.value=M),xn(h)}function Ta(h,y){if(y){var S=h.firstChild;if(S&&S===h.lastChild&&S.nodeType===3){S.nodeValue=y;return}}h.textContent=y}var Wi=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 _m(h,y,S){var M=y.indexOf("--")===0;S==null||typeof S=="boolean"||S===""?M?h.setProperty(y,""):y==="float"?h.cssFloat="":h[y]="":M?h.setProperty(y,S):typeof S!="number"||S===0||Wi.has(y)?y==="float"?h.cssFloat=S:h[y]=(""+S).trim():h[y]=S+"px"}function Vd(h,y,S){if(y!=null&&typeof y!="object")throw Error(r(62));if(h=h.style,S!=null){for(var M in S)!S.hasOwnProperty(M)||y!=null&&y.hasOwnProperty(M)||(M.indexOf("--")===0?h.setProperty(M,""):M==="float"?h.cssFloat="":h[M]="");for(var q in y)M=y[q],y.hasOwnProperty(q)&&S[q]!==M&&_m(h,q,M)}else for(var Z in y)y.hasOwnProperty(Z)&&_m(h,Z,y[Z])}function fl(h){if(h.indexOf("-")===-1)return!1;switch(h){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 xt=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"]]),Kn=/^[\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 Zn(h){return Kn.test(""+h)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":h}function qt(){}var Kc=null;function Ki(h){return h=h.target||h.srcElement||window,h.correspondingUseElement&&(h=h.correspondingUseElement),h.nodeType===3?h.parentNode:h}var gl=null,fc=null;function Qa(h){var y=Ce(h);if(y&&(h=y.stateNode)){var S=h[pt]||null;e:switch(h=y.stateNode,y.type){case"input":if(Pa(h,S.value,S.defaultValue,S.defaultValue,S.checked,S.defaultChecked,S.type,S.name),y=S.name,S.type==="radio"&&y!=null){for(S=h;S.parentNode;)S=S.parentNode;for(S=S.querySelectorAll('input[name="'+Sn(""+y)+'"][type="radio"]'),y=0;y<S.length;y++){var M=S[y];if(M!==h&&M.form===h.form){var q=M[pt]||null;if(!q)throw Error(r(90));Pa(M,q.value,q.defaultValue,q.defaultValue,q.checked,q.defaultChecked,q.type,q.name)}}for(y=0;y<S.length;y++)M=S[y],M.form===h.form&&Nn(M)}break e;case"textarea":Zr(h,S.value,S.defaultValue);break e;case"select":y=S.value,y!=null&&ua(h,!!S.multiple,y,!1)}}}var km=!1;function Cp(h,y,S){if(km)return h(y,S);km=!0;try{var M=h(y);return M}finally{if(km=!1,(gl!==null||fc!==null)&&(l_(),gl&&(y=gl,h=fc,fc=gl=null,Qa(y),h)))for(y=0;y<h.length;y++)Qa(h[y])}}function Gd(h,y){var S=h.stateNode;if(S===null)return null;var M=S[pt]||null;if(M===null)return null;S=M[y];e:switch(y){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(M=!M.disabled)||(h=h.type,M=!(h==="button"||h==="input"||h==="select"||h==="textarea")),h=!M;break e;default:h=!1}if(h)return null;if(S&&typeof S!="function")throw Error(r(231,y,typeof S));return S}var Xi=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Nm=!1;if(Xi)try{var vs={};Object.defineProperty(vs,"passive",{get:function(){Nm=!0}}),window.addEventListener("test",vs,vs),window.removeEventListener("test",vs,vs)}catch{Nm=!1}var Yi=null,zs=null,bl=null;function Za(){if(bl)return bl;var h,y=zs,S=y.length,M,q="value"in Yi?Yi.value:Yi.textContent,Z=q.length;for(h=0;h<S&&y[h]===q[h];h++);var ke=S-h;for(M=1;M<=ke&&y[S-M]===q[Z-M];M++);return bl=q.slice(h,1<M?1-M:void 0)}function xl(h){var y=h.keyCode;return"charCode"in h?(h=h.charCode,h===0&&y===13&&(h=13)):h=y,h===10&&(h=13),32<=h||h===13?h:0}function Wd(){return!0}function yl(){return!1}function xi(h){function y(S,M,q,Z,ke){this._reactName=S,this._targetInst=q,this.type=M,this.nativeEvent=Z,this.target=ke,this.currentTarget=null;for(var Ue in h)h.hasOwnProperty(Ue)&&(S=h[Ue],this[Ue]=S?S(Z):Z[Ue]);return this.isDefaultPrevented=(Z.defaultPrevented!=null?Z.defaultPrevented:Z.returnValue===!1)?Wd:yl,this.isPropagationStopped=yl,this}return m(y.prototype,{preventDefault:function(){this.defaultPrevented=!0;var S=this.nativeEvent;S&&(S.preventDefault?S.preventDefault():typeof S.returnValue!="unknown"&&(S.returnValue=!1),this.isDefaultPrevented=Wd)},stopPropagation:function(){var S=this.nativeEvent;S&&(S.stopPropagation?S.stopPropagation():typeof S.cancelBubble!="unknown"&&(S.cancelBubble=!0),this.isPropagationStopped=Wd)},persist:function(){},isPersistent:Wd}),y}var Us={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(h){return h.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},gc=xi(Us),Oo=m({},Us,{view:0,detail:0}),Pp=xi(Oo),vl,co,wl,Io=m({},Oo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Jt,button:0,buttons:0,relatedTarget:function(h){return h.relatedTarget===void 0?h.fromElement===h.srcElement?h.toElement:h.fromElement:h.relatedTarget},movementX:function(h){return"movementX"in h?h.movementX:(h!==wl&&(wl&&h.type==="mousemove"?(vl=h.screenX-wl.screenX,co=h.screenY-wl.screenY):co=vl=0,wl=h),vl)},movementY:function(h){return"movementY"in h?h.movementY:co}}),Xc=xi(Io),Cm=m({},Io,{dataTransfer:0}),uo=xi(Cm),mo=m({},Oo,{relatedTarget:0}),zo=xi(mo),Tg=m({},Us,{animationName:0,elapsedTime:0,pseudoElement:0}),kn=xi(Tg),Ay=m({},Us,{clipboardData:function(h){return"clipboardData"in h?h.clipboardData:window.clipboardData}}),Yc=xi(Ay),Ag=m({},Us,{data:0}),Pm=xi(Ag),jg={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},jy={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"},mt={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ht(h){var y=this.nativeEvent;return y.getModifierState?y.getModifierState(h):(h=mt[h])?!!y[h]:!1}function Jt(){return Ht}var ot=m({},Oo,{key:function(h){if(h.key){var y=jg[h.key]||h.key;if(y!=="Unidentified")return y}return h.type==="keypress"?(h=xl(h),h===13?"Enter":String.fromCharCode(h)):h.type==="keydown"||h.type==="keyup"?jy[h.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Jt,charCode:function(h){return h.type==="keypress"?xl(h):0},keyCode:function(h){return h.type==="keydown"||h.type==="keyup"?h.keyCode:0},which:function(h){return h.type==="keypress"?xl(h):h.type==="keydown"||h.type==="keyup"?h.keyCode:0}}),Bn=xi(ot),we=m({},Io,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),_t=xi(we),ln=m({},Oo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Jt}),mn=xi(ln),zt=m({},Us,{propertyName:0,elapsedTime:0,pseudoElement:0}),dn=xi(zt),mr=m({},Io,{deltaX:function(h){return"deltaX"in h?h.deltaX:"wheelDeltaX"in h?-h.wheelDeltaX:0},deltaY:function(h){return"deltaY"in h?h.deltaY:"wheelDeltaY"in h?-h.wheelDeltaY:"wheelDelta"in h?-h.wheelDelta:0},deltaZ:0,deltaMode:0}),Vn=xi(mr),yi=m({},Us,{newState:0,oldState:0}),Bs=xi(yi),Sl=[9,13,27,32],ma=Xi&&"CompositionEvent"in window,Ja=null;Xi&&"documentMode"in document&&(Ja=document.documentMode);var bc=Xi&&"TextEvent"in window&&!Ja,Qi=Xi&&(!ma||Ja&&8<Ja&&11>=Ja),ho=" ",xc=!1;function oa(h,y){switch(h){case"keyup":return Sl.indexOf(y.keyCode)!==-1;case"keydown":return y.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function po(h){return h=h.detail,typeof h=="object"&&"data"in h?h.data:null}var Qc=!1;function ha(h,y){switch(h){case"compositionend":return po(y);case"keypress":return y.which!==32?null:(xc=!0,ho);case"textInput":return h=y.data,h===ho&&xc?null:h;default:return null}}function Kd(h,y){if(Qc)return h==="compositionend"||!ma&&oa(h,y)?(h=Za(),bl=zs=Yi=null,Qc=!1,h):null;switch(h){case"paste":return null;case"keypress":if(!(y.ctrlKey||y.altKey||y.metaKey)||y.ctrlKey&&y.altKey){if(y.char&&1<y.char.length)return y.char;if(y.which)return String.fromCharCode(y.which)}return null;case"compositionend":return Qi&&y.locale!=="ko"?null:y.data;default:return null}}var Tp={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 In(h){var y=h&&h.nodeName&&h.nodeName.toLowerCase();return y==="input"?!!Tp[h.type]:y==="textarea"}function cA(h,y,S,M){gl?fc?fc.push(M):fc=[M]:gl=M,y=f_(y,"onChange"),0<y.length&&(S=new gc("onChange","change",null,S,M),h.push({event:S,listeners:y}))}var Tm=null,Zc=null;function CS(h){zB(h,0)}function Ap(h){var y=We(h);if(Nn(y))return h}function PS(h,y){if(h==="change")return y}var i5=!1;if(Xi){var dA;if(Xi){var uA="oninput"in document;if(!uA){var s5=document.createElement("div");s5.setAttribute("oninput","return;"),uA=typeof s5.oninput=="function"}dA=uA}else dA=!1;i5=dA&&(!document.documentMode||9<document.documentMode)}function o5(){Tm&&(Tm.detachEvent("onpropertychange",l5),Zc=Tm=null)}function l5(h){if(h.propertyName==="value"&&Ap(Zc)){var y=[];cA(y,Zc,h,Ki(h)),Cp(CS,y)}}function rce(h,y,S){h==="focusin"?(o5(),Tm=y,Zc=S,Tm.attachEvent("onpropertychange",l5)):h==="focusout"&&o5()}function ace(h){if(h==="selectionchange"||h==="keyup"||h==="keydown")return Ap(Zc)}function ice(h,y){if(h==="click")return Ap(y)}function sce(h,y){if(h==="input"||h==="change")return Ap(y)}function oce(h,y){return h===y&&(h!==0||1/h===1/y)||h!==h&&y!==y}var Uo=typeof Object.is=="function"?Object.is:oce;function My(h,y){if(Uo(h,y))return!0;if(typeof h!="object"||h===null||typeof y!="object"||y===null)return!1;var S=Object.keys(h),M=Object.keys(y);if(S.length!==M.length)return!1;for(M=0;M<S.length;M++){var q=S[M];if(!se.call(y,q)||!Uo(h[q],y[q]))return!1}return!0}function c5(h){for(;h&&h.firstChild;)h=h.firstChild;return h}function d5(h,y){var S=c5(h);h=0;for(var M;S;){if(S.nodeType===3){if(M=h+S.textContent.length,h<=y&&M>=y)return{node:S,offset:y-h};h=M}e:{for(;S;){if(S.nextSibling){S=S.nextSibling;break e}S=S.parentNode}S=void 0}S=c5(S)}}function u5(h,y){return h&&y?h===y?!0:h&&h.nodeType===3?!1:y&&y.nodeType===3?u5(h,y.parentNode):"contains"in h?h.contains(y):h.compareDocumentPosition?!!(h.compareDocumentPosition(y)&16):!1:!1}function m5(h){h=h!=null&&h.ownerDocument!=null&&h.ownerDocument.defaultView!=null?h.ownerDocument.defaultView:window;for(var y=Pn(h.document);y instanceof h.HTMLIFrameElement;){try{var S=typeof y.contentWindow.location.href=="string"}catch{S=!1}if(S)h=y.contentWindow;else break;y=Pn(h.document)}return y}function mA(h){var y=h&&h.nodeName&&h.nodeName.toLowerCase();return y&&(y==="input"&&(h.type==="text"||h.type==="search"||h.type==="tel"||h.type==="url"||h.type==="password")||y==="textarea"||h.contentEditable==="true")}var lce=Xi&&"documentMode"in document&&11>=document.documentMode,Mg=null,hA=null,Ey=null,pA=!1;function h5(h,y,S){var M=S.window===S?S.document:S.nodeType===9?S:S.ownerDocument;pA||Mg==null||Mg!==Pn(M)||(M=Mg,"selectionStart"in M&&mA(M)?M={start:M.selectionStart,end:M.selectionEnd}:(M=(M.ownerDocument&&M.ownerDocument.defaultView||window).getSelection(),M={anchorNode:M.anchorNode,anchorOffset:M.anchorOffset,focusNode:M.focusNode,focusOffset:M.focusOffset}),Ey&&My(Ey,M)||(Ey=M,M=f_(hA,"onSelect"),0<M.length&&(y=new gc("onSelect","select",null,y,S),h.push({event:y,listeners:M}),y.target=Mg)))}function jp(h,y){var S={};return S[h.toLowerCase()]=y.toLowerCase(),S["Webkit"+h]="webkit"+y,S["Moz"+h]="moz"+y,S}var Eg={animationend:jp("Animation","AnimationEnd"),animationiteration:jp("Animation","AnimationIteration"),animationstart:jp("Animation","AnimationStart"),transitionrun:jp("Transition","TransitionRun"),transitionstart:jp("Transition","TransitionStart"),transitioncancel:jp("Transition","TransitionCancel"),transitionend:jp("Transition","TransitionEnd")},fA={},p5={};Xi&&(p5=document.createElement("div").style,"AnimationEvent"in window||(delete Eg.animationend.animation,delete Eg.animationiteration.animation,delete Eg.animationstart.animation),"TransitionEvent"in window||delete Eg.transitionend.transition);function Mp(h){if(fA[h])return fA[h];if(!Eg[h])return h;var y=Eg[h],S;for(S in y)if(y.hasOwnProperty(S)&&S in p5)return fA[h]=y[S];return h}var f5=Mp("animationend"),g5=Mp("animationiteration"),b5=Mp("animationstart"),cce=Mp("transitionrun"),dce=Mp("transitionstart"),uce=Mp("transitioncancel"),x5=Mp("transitionend"),y5=new Map,gA="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(" ");gA.push("scrollEnd");function yc(h,y){y5.set(h,y),et(y,[h])}var TS=typeof reportError=="function"?reportError:function(h){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var y=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(y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",h);return}console.error(h)},_l=[],Dg=0,bA=0;function AS(){for(var h=Dg,y=bA=Dg=0;y<h;){var S=_l[y];_l[y++]=null;var M=_l[y];_l[y++]=null;var q=_l[y];_l[y++]=null;var Z=_l[y];if(_l[y++]=null,M!==null&&q!==null){var ke=M.pending;ke===null?q.next=q:(q.next=ke.next,ke.next=q),M.pending=q}Z!==0&&v5(S,q,Z)}}function jS(h,y,S,M){_l[Dg++]=h,_l[Dg++]=y,_l[Dg++]=S,_l[Dg++]=M,bA|=M,h.lanes|=M,h=h.alternate,h!==null&&(h.lanes|=M)}function xA(h,y,S,M){return jS(h,y,S,M),MS(h)}function Ep(h,y){return jS(h,null,null,y),MS(h)}function v5(h,y,S){h.lanes|=S;var M=h.alternate;M!==null&&(M.lanes|=S);for(var q=!1,Z=h.return;Z!==null;)Z.childLanes|=S,M=Z.alternate,M!==null&&(M.childLanes|=S),Z.tag===22&&(h=Z.stateNode,h===null||h._visibility&1||(q=!0)),h=Z,Z=Z.return;return h.tag===3?(Z=h.stateNode,q&&y!==null&&(q=31-Be(S),h=Z.hiddenUpdates,M=h[q],M===null?h[q]=[y]:M.push(y),y.lane=S|536870912),Z):null}function MS(h){if(50<ev)throw ev=0,Pj=null,Error(r(185));for(var y=h.return;y!==null;)h=y,y=h.return;return h.tag===3?h.stateNode:null}var Fg={};function mce(h,y,S,M){this.tag=h,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=y,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=M,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bo(h,y,S,M){return new mce(h,y,S,M)}function yA(h){return h=h.prototype,!(!h||!h.isReactComponent)}function Xd(h,y){var S=h.alternate;return S===null?(S=Bo(h.tag,y,h.key,h.mode),S.elementType=h.elementType,S.type=h.type,S.stateNode=h.stateNode,S.alternate=h,h.alternate=S):(S.pendingProps=y,S.type=h.type,S.flags=0,S.subtreeFlags=0,S.deletions=null),S.flags=h.flags&65011712,S.childLanes=h.childLanes,S.lanes=h.lanes,S.child=h.child,S.memoizedProps=h.memoizedProps,S.memoizedState=h.memoizedState,S.updateQueue=h.updateQueue,y=h.dependencies,S.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext},S.sibling=h.sibling,S.index=h.index,S.ref=h.ref,S.refCleanup=h.refCleanup,S}function w5(h,y){h.flags&=65011714;var S=h.alternate;return S===null?(h.childLanes=0,h.lanes=y,h.child=null,h.subtreeFlags=0,h.memoizedProps=null,h.memoizedState=null,h.updateQueue=null,h.dependencies=null,h.stateNode=null):(h.childLanes=S.childLanes,h.lanes=S.lanes,h.child=S.child,h.subtreeFlags=0,h.deletions=null,h.memoizedProps=S.memoizedProps,h.memoizedState=S.memoizedState,h.updateQueue=S.updateQueue,h.type=S.type,y=S.dependencies,h.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext}),h}function ES(h,y,S,M,q,Z){var ke=0;if(M=h,typeof h=="function")yA(h)&&(ke=1);else if(typeof h=="string")ke=bde(h,S,xe.current)?26:h==="html"||h==="head"||h==="body"?27:5;else e:switch(h){case k:return h=Bo(31,S,y,q),h.elementType=k,h.lanes=Z,h;case v:return Dp(S.children,q,Z,y);case g:ke=8,q|=24;break;case b:return h=Bo(12,S,y,q|2),h.elementType=b,h.lanes=Z,h;case N:return h=Bo(13,S,y,q),h.elementType=N,h.lanes=Z,h;case A:return h=Bo(19,S,y,q),h.elementType=A,h.lanes=Z,h;default:if(typeof h=="object"&&h!==null)switch(h.$$typeof){case C:ke=10;break e;case _:ke=9;break e;case P:ke=11;break e;case T:ke=14;break e;case F:ke=16,M=null;break e}ke=29,S=Error(r(130,h===null?"null":typeof h,"")),M=null}return y=Bo(ke,S,y,q),y.elementType=h,y.type=M,y.lanes=Z,y}function Dp(h,y,S,M){return h=Bo(7,h,M,y),h.lanes=S,h}function vA(h,y,S){return h=Bo(6,h,null,y),h.lanes=S,h}function S5(h){var y=Bo(18,null,null,0);return y.stateNode=h,y}function wA(h,y,S){return y=Bo(4,h.children!==null?h.children:[],h.key,y),y.lanes=S,y.stateNode={containerInfo:h.containerInfo,pendingChildren:null,implementation:h.implementation},y}var _5=new WeakMap;function kl(h,y){if(typeof h=="object"&&h!==null){var S=_5.get(h);return S!==void 0?S:(y={value:h,source:y,stack:J(y)},_5.set(h,y),y)}return{value:h,source:y,stack:J(y)}}var Rg=[],Lg=0,DS=null,Dy=0,Nl=[],Cl=0,Am=null,Jc=1,ed="";function Yd(h,y){Rg[Lg++]=Dy,Rg[Lg++]=DS,DS=h,Dy=y}function k5(h,y,S){Nl[Cl++]=Jc,Nl[Cl++]=ed,Nl[Cl++]=Am,Am=h;var M=Jc;h=ed;var q=32-Be(M)-1;M&=~(1<<q),S+=1;var Z=32-Be(y)+q;if(30<Z){var ke=q-q%5;Z=(M&(1<<ke)-1).toString(32),M>>=ke,q-=ke,Jc=1<<32-Be(y)+q|S<<q|M,ed=Z+h}else Jc=1<<Z|S<<q|M,ed=h}function SA(h){h.return!==null&&(Yd(h,1),k5(h,1,0))}function _A(h){for(;h===DS;)DS=Rg[--Lg],Rg[Lg]=null,Dy=Rg[--Lg],Rg[Lg]=null;for(;h===Am;)Am=Nl[--Cl],Nl[Cl]=null,ed=Nl[--Cl],Nl[Cl]=null,Jc=Nl[--Cl],Nl[Cl]=null}function N5(h,y){Nl[Cl++]=Jc,Nl[Cl++]=ed,Nl[Cl++]=Am,Jc=y.id,ed=y.overflow,Am=h}var Zi=null,pa=null,yr=!1,jm=null,Pl=!1,kA=Error(r(519));function Mm(h){var y=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Fy(kl(y,h)),kA}function C5(h){var y=h.stateNode,S=h.type,M=h.memoizedProps;switch(y[Pt]=h,y[pt]=M,S){case"dialog":pr("cancel",y),pr("close",y);break;case"iframe":case"object":case"embed":pr("load",y);break;case"video":case"audio":for(S=0;S<nv.length;S++)pr(nv[S],y);break;case"source":pr("error",y);break;case"img":case"image":case"link":pr("error",y),pr("load",y);break;case"details":pr("toggle",y);break;case"input":pr("invalid",y),On(y,M.value,M.defaultValue,M.checked,M.defaultChecked,M.type,M.name,!0);break;case"select":pr("invalid",y);break;case"textarea":pr("invalid",y),sa(y,M.value,M.defaultValue,M.children)}S=M.children,typeof S!="string"&&typeof S!="number"&&typeof S!="bigint"||y.textContent===""+S||M.suppressHydrationWarning===!0||qB(y.textContent,S)?(M.popover!=null&&(pr("beforetoggle",y),pr("toggle",y)),M.onScroll!=null&&pr("scroll",y),M.onScrollEnd!=null&&pr("scrollend",y),M.onClick!=null&&(y.onclick=qt),y=!0):y=!1,y||Mm(h,!0)}function P5(h){for(Zi=h.return;Zi;)switch(Zi.tag){case 5:case 31:case 13:Pl=!1;return;case 27:case 3:Pl=!0;return;default:Zi=Zi.return}}function Og(h){if(h!==Zi)return!1;if(!yr)return P5(h),yr=!0,!1;var y=h.tag,S;if((S=y!==3&&y!==27)&&((S=y===5)&&(S=h.type,S=!(S!=="form"&&S!=="button")||Hj(h.type,h.memoizedProps)),S=!S),S&&pa&&Mm(h),P5(h),y===13){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));pa=ZB(h)}else if(y===31){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));pa=ZB(h)}else y===27?(y=pa,Vm(h.type)?(h=Wj,Wj=null,pa=h):pa=y):pa=Zi?Al(h.stateNode.nextSibling):null;return!0}function Fp(){pa=Zi=null,yr=!1}function NA(){var h=jm;return h!==null&&(xo===null?xo=h:xo.push.apply(xo,h),jm=null),h}function Fy(h){jm===null?jm=[h]:jm.push(h)}var CA=W(null),Rp=null,Qd=null;function Em(h,y,S){ce(CA,y._currentValue),y._currentValue=S}function Zd(h){h._currentValue=CA.current,re(CA)}function PA(h,y,S){for(;h!==null;){var M=h.alternate;if((h.childLanes&y)!==y?(h.childLanes|=y,M!==null&&(M.childLanes|=y)):M!==null&&(M.childLanes&y)!==y&&(M.childLanes|=y),h===S)break;h=h.return}}function TA(h,y,S,M){var q=h.child;for(q!==null&&(q.return=h);q!==null;){var Z=q.dependencies;if(Z!==null){var ke=q.child;Z=Z.firstContext;e:for(;Z!==null;){var Ue=Z;Z=q;for(var nt=0;nt<y.length;nt++)if(Ue.context===y[nt]){Z.lanes|=S,Ue=Z.alternate,Ue!==null&&(Ue.lanes|=S),PA(Z.return,S,h),M||(ke=null);break e}Z=Ue.next}}else if(q.tag===18){if(ke=q.return,ke===null)throw Error(r(341));ke.lanes|=S,Z=ke.alternate,Z!==null&&(Z.lanes|=S),PA(ke,S,h),ke=null}else ke=q.child;if(ke!==null)ke.return=q;else for(ke=q;ke!==null;){if(ke===h){ke=null;break}if(q=ke.sibling,q!==null){q.return=ke.return,ke=q;break}ke=ke.return}q=ke}}function Ig(h,y,S,M){h=null;for(var q=y,Z=!1;q!==null;){if(!Z){if((q.flags&524288)!==0)Z=!0;else if((q.flags&262144)!==0)break}if(q.tag===10){var ke=q.alternate;if(ke===null)throw Error(r(387));if(ke=ke.memoizedProps,ke!==null){var Ue=q.type;Uo(q.pendingProps.value,ke.value)||(h!==null?h.push(Ue):h=[Ue])}}else if(q===Y.current){if(ke=q.alternate,ke===null)throw Error(r(387));ke.memoizedState.memoizedState!==q.memoizedState.memoizedState&&(h!==null?h.push(ov):h=[ov])}q=q.return}h!==null&&TA(y,h,S,M),y.flags|=262144}function FS(h){for(h=h.firstContext;h!==null;){if(!Uo(h.context._currentValue,h.memoizedValue))return!0;h=h.next}return!1}function Lp(h){Rp=h,Qd=null,h=h.dependencies,h!==null&&(h.firstContext=null)}function Ji(h){return T5(Rp,h)}function RS(h,y){return Rp===null&&Lp(h),T5(h,y)}function T5(h,y){var S=y._currentValue;if(y={context:y,memoizedValue:S,next:null},Qd===null){if(h===null)throw Error(r(308));Qd=y,h.dependencies={lanes:0,firstContext:y},h.flags|=524288}else Qd=Qd.next=y;return S}var hce=typeof AbortController<"u"?AbortController:function(){var h=[],y=this.signal={aborted:!1,addEventListener:function(S,M){h.push(M)}};this.abort=function(){y.aborted=!0,h.forEach(function(S){return S()})}},pce=t.unstable_scheduleCallback,fce=t.unstable_NormalPriority,ii={$$typeof:C,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function AA(){return{controller:new hce,data:new Map,refCount:0}}function Ry(h){h.refCount--,h.refCount===0&&pce(fce,function(){h.controller.abort()})}var Ly=null,jA=0,zg=0,Ug=null;function gce(h,y){if(Ly===null){var S=Ly=[];jA=0,zg=Dj(),Ug={status:"pending",value:void 0,then:function(M){S.push(M)}}}return jA++,y.then(A5,A5),y}function A5(){if(--jA===0&&Ly!==null){Ug!==null&&(Ug.status="fulfilled");var h=Ly;Ly=null,zg=0,Ug=null;for(var y=0;y<h.length;y++)(0,h[y])()}}function bce(h,y){var S=[],M={status:"pending",value:null,reason:null,then:function(q){S.push(q)}};return h.then(function(){M.status="fulfilled",M.value=y;for(var q=0;q<S.length;q++)(0,S[q])(y)},function(q){for(M.status="rejected",M.reason=q,q=0;q<S.length;q++)(0,S[q])(void 0)}),M}var j5=ie.S;ie.S=function(h,y){hB=R(),typeof y=="object"&&y!==null&&typeof y.then=="function"&&gce(h,y),j5!==null&&j5(h,y)};var Op=W(null);function MA(){var h=Op.current;return h!==null?h:Jr.pooledCache}function LS(h,y){y===null?ce(Op,Op.current):ce(Op,y.pool)}function M5(){var h=MA();return h===null?null:{parent:ii._currentValue,pool:h}}var Bg=Error(r(460)),EA=Error(r(474)),OS=Error(r(542)),IS={then:function(){}};function E5(h){return h=h.status,h==="fulfilled"||h==="rejected"}function D5(h,y,S){switch(S=h[S],S===void 0?h.push(y):S!==y&&(y.then(qt,qt),y=S),y.status){case"fulfilled":return y.value;case"rejected":throw h=y.reason,R5(h),h;default:if(typeof y.status=="string")y.then(qt,qt);else{if(h=Jr,h!==null&&100<h.shellSuspendCounter)throw Error(r(482));h=y,h.status="pending",h.then(function(M){if(y.status==="pending"){var q=y;q.status="fulfilled",q.value=M}},function(M){if(y.status==="pending"){var q=y;q.status="rejected",q.reason=M}})}switch(y.status){case"fulfilled":return y.value;case"rejected":throw h=y.reason,R5(h),h}throw zp=y,Bg}}function Ip(h){try{var y=h._init;return y(h._payload)}catch(S){throw S!==null&&typeof S=="object"&&typeof S.then=="function"?(zp=S,Bg):S}}var zp=null;function F5(){if(zp===null)throw Error(r(459));var h=zp;return zp=null,h}function R5(h){if(h===Bg||h===OS)throw Error(r(483))}var Hg=null,Oy=0;function zS(h){var y=Oy;return Oy+=1,Hg===null&&(Hg=[]),D5(Hg,h,y)}function Iy(h,y){y=y.props.ref,h.ref=y!==void 0?y:null}function US(h,y){throw y.$$typeof===p?Error(r(525)):(h=Object.prototype.toString.call(y),Error(r(31,h==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":h)))}function L5(h){function y(ft,lt){if(h){var kt=ft.deletions;kt===null?(ft.deletions=[lt],ft.flags|=16):kt.push(lt)}}function S(ft,lt){if(!h)return null;for(;lt!==null;)y(ft,lt),lt=lt.sibling;return null}function M(ft){for(var lt=new Map;ft!==null;)ft.key!==null?lt.set(ft.key,ft):lt.set(ft.index,ft),ft=ft.sibling;return lt}function q(ft,lt){return ft=Xd(ft,lt),ft.index=0,ft.sibling=null,ft}function Z(ft,lt,kt){return ft.index=kt,h?(kt=ft.alternate,kt!==null?(kt=kt.index,kt<lt?(ft.flags|=67108866,lt):kt):(ft.flags|=67108866,lt)):(ft.flags|=1048576,lt)}function ke(ft){return h&&ft.alternate===null&&(ft.flags|=67108866),ft}function Ue(ft,lt,kt,Ot){return lt===null||lt.tag!==6?(lt=vA(kt,ft.mode,Ot),lt.return=ft,lt):(lt=q(lt,kt),lt.return=ft,lt)}function nt(ft,lt,kt,Ot){var jn=kt.type;return jn===v?Lt(ft,lt,kt.props.children,Ot,kt.key):lt!==null&&(lt.elementType===jn||typeof jn=="object"&&jn!==null&&jn.$$typeof===F&&Ip(jn)===lt.type)?(lt=q(lt,kt.props),Iy(lt,kt),lt.return=ft,lt):(lt=ES(kt.type,kt.key,kt.props,null,ft.mode,Ot),Iy(lt,kt),lt.return=ft,lt)}function Nt(ft,lt,kt,Ot){return lt===null||lt.tag!==4||lt.stateNode.containerInfo!==kt.containerInfo||lt.stateNode.implementation!==kt.implementation?(lt=wA(kt,ft.mode,Ot),lt.return=ft,lt):(lt=q(lt,kt.children||[]),lt.return=ft,lt)}function Lt(ft,lt,kt,Ot,jn){return lt===null||lt.tag!==7?(lt=Dp(kt,ft.mode,Ot,jn),lt.return=ft,lt):(lt=q(lt,kt),lt.return=ft,lt)}function It(ft,lt,kt){if(typeof lt=="string"&<!==""||typeof lt=="number"||typeof lt=="bigint")return lt=vA(""+lt,ft.mode,kt),lt.return=ft,lt;if(typeof lt=="object"&<!==null){switch(lt.$$typeof){case f:return kt=ES(lt.type,lt.key,lt.props,null,ft.mode,kt),Iy(kt,lt),kt.return=ft,kt;case x:return lt=wA(lt,ft.mode,kt),lt.return=ft,lt;case F:return lt=Ip(lt),It(ft,lt,kt)}if(ne(lt)||z(lt))return lt=Dp(lt,ft.mode,kt,null),lt.return=ft,lt;if(typeof lt.then=="function")return It(ft,zS(lt),kt);if(lt.$$typeof===C)return It(ft,RS(ft,lt),kt);US(ft,lt)}return null}function Ct(ft,lt,kt,Ot){var jn=lt!==null?lt.key:null;if(typeof kt=="string"&&kt!==""||typeof kt=="number"||typeof kt=="bigint")return jn!==null?null:Ue(ft,lt,""+kt,Ot);if(typeof kt=="object"&&kt!==null){switch(kt.$$typeof){case f:return kt.key===jn?nt(ft,lt,kt,Ot):null;case x:return kt.key===jn?Nt(ft,lt,kt,Ot):null;case F:return kt=Ip(kt),Ct(ft,lt,kt,Ot)}if(ne(kt)||z(kt))return jn!==null?null:Lt(ft,lt,kt,Ot,null);if(typeof kt.then=="function")return Ct(ft,lt,zS(kt),Ot);if(kt.$$typeof===C)return Ct(ft,lt,RS(ft,kt),Ot);US(ft,kt)}return null}function Dt(ft,lt,kt,Ot,jn){if(typeof Ot=="string"&&Ot!==""||typeof Ot=="number"||typeof Ot=="bigint")return ft=ft.get(kt)||null,Ue(lt,ft,""+Ot,jn);if(typeof Ot=="object"&&Ot!==null){switch(Ot.$$typeof){case f:return ft=ft.get(Ot.key===null?kt:Ot.key)||null,nt(lt,ft,Ot,jn);case x:return ft=ft.get(Ot.key===null?kt:Ot.key)||null,Nt(lt,ft,Ot,jn);case F:return Ot=Ip(Ot),Dt(ft,lt,kt,Ot,jn)}if(ne(Ot)||z(Ot))return ft=ft.get(kt)||null,Lt(lt,ft,Ot,jn,null);if(typeof Ot.then=="function")return Dt(ft,lt,kt,zS(Ot),jn);if(Ot.$$typeof===C)return Dt(ft,lt,kt,RS(lt,Ot),jn);US(lt,Ot)}return null}function gn(ft,lt,kt,Ot){for(var jn=null,Cr=null,vn=lt,Jn=lt=0,br=null;vn!==null&&Jn<kt.length;Jn++){vn.index>Jn?(br=vn,vn=null):br=vn.sibling;var Pr=Ct(ft,vn,kt[Jn],Ot);if(Pr===null){vn===null&&(vn=br);break}h&&vn&&Pr.alternate===null&&y(ft,vn),lt=Z(Pr,lt,Jn),Cr===null?jn=Pr:Cr.sibling=Pr,Cr=Pr,vn=br}if(Jn===kt.length)return S(ft,vn),yr&&Yd(ft,Jn),jn;if(vn===null){for(;Jn<kt.length;Jn++)vn=It(ft,kt[Jn],Ot),vn!==null&&(lt=Z(vn,lt,Jn),Cr===null?jn=vn:Cr.sibling=vn,Cr=vn);return yr&&Yd(ft,Jn),jn}for(vn=M(vn);Jn<kt.length;Jn++)br=Dt(vn,ft,Jn,kt[Jn],Ot),br!==null&&(h&&br.alternate!==null&&vn.delete(br.key===null?Jn:br.key),lt=Z(br,lt,Jn),Cr===null?jn=br:Cr.sibling=br,Cr=br);return h&&vn.forEach(function(Ym){return y(ft,Ym)}),yr&&Yd(ft,Jn),jn}function Fn(ft,lt,kt,Ot){if(kt==null)throw Error(r(151));for(var jn=null,Cr=null,vn=lt,Jn=lt=0,br=null,Pr=kt.next();vn!==null&&!Pr.done;Jn++,Pr=kt.next()){vn.index>Jn?(br=vn,vn=null):br=vn.sibling;var Ym=Ct(ft,vn,Pr.value,Ot);if(Ym===null){vn===null&&(vn=br);break}h&&vn&&Ym.alternate===null&&y(ft,vn),lt=Z(Ym,lt,Jn),Cr===null?jn=Ym:Cr.sibling=Ym,Cr=Ym,vn=br}if(Pr.done)return S(ft,vn),yr&&Yd(ft,Jn),jn;if(vn===null){for(;!Pr.done;Jn++,Pr=kt.next())Pr=It(ft,Pr.value,Ot),Pr!==null&&(lt=Z(Pr,lt,Jn),Cr===null?jn=Pr:Cr.sibling=Pr,Cr=Pr);return yr&&Yd(ft,Jn),jn}for(vn=M(vn);!Pr.done;Jn++,Pr=kt.next())Pr=Dt(vn,ft,Jn,Pr.value,Ot),Pr!==null&&(h&&Pr.alternate!==null&&vn.delete(Pr.key===null?Jn:Pr.key),lt=Z(Pr,lt,Jn),Cr===null?jn=Pr:Cr.sibling=Pr,Cr=Pr);return h&&vn.forEach(function(Tde){return y(ft,Tde)}),yr&&Yd(ft,Jn),jn}function qr(ft,lt,kt,Ot){if(typeof kt=="object"&&kt!==null&&kt.type===v&&kt.key===null&&(kt=kt.props.children),typeof kt=="object"&&kt!==null){switch(kt.$$typeof){case f:e:{for(var jn=kt.key;lt!==null;){if(lt.key===jn){if(jn=kt.type,jn===v){if(lt.tag===7){S(ft,lt.sibling),Ot=q(lt,kt.props.children),Ot.return=ft,ft=Ot;break e}}else if(lt.elementType===jn||typeof jn=="object"&&jn!==null&&jn.$$typeof===F&&Ip(jn)===lt.type){S(ft,lt.sibling),Ot=q(lt,kt.props),Iy(Ot,kt),Ot.return=ft,ft=Ot;break e}S(ft,lt);break}else y(ft,lt);lt=lt.sibling}kt.type===v?(Ot=Dp(kt.props.children,ft.mode,Ot,kt.key),Ot.return=ft,ft=Ot):(Ot=ES(kt.type,kt.key,kt.props,null,ft.mode,Ot),Iy(Ot,kt),Ot.return=ft,ft=Ot)}return ke(ft);case x:e:{for(jn=kt.key;lt!==null;){if(lt.key===jn)if(lt.tag===4&<.stateNode.containerInfo===kt.containerInfo&<.stateNode.implementation===kt.implementation){S(ft,lt.sibling),Ot=q(lt,kt.children||[]),Ot.return=ft,ft=Ot;break e}else{S(ft,lt);break}else y(ft,lt);lt=lt.sibling}Ot=wA(kt,ft.mode,Ot),Ot.return=ft,ft=Ot}return ke(ft);case F:return kt=Ip(kt),qr(ft,lt,kt,Ot)}if(ne(kt))return gn(ft,lt,kt,Ot);if(z(kt)){if(jn=z(kt),typeof jn!="function")throw Error(r(150));return kt=jn.call(kt),Fn(ft,lt,kt,Ot)}if(typeof kt.then=="function")return qr(ft,lt,zS(kt),Ot);if(kt.$$typeof===C)return qr(ft,lt,RS(ft,kt),Ot);US(ft,kt)}return typeof kt=="string"&&kt!==""||typeof kt=="number"||typeof kt=="bigint"?(kt=""+kt,lt!==null&<.tag===6?(S(ft,lt.sibling),Ot=q(lt,kt),Ot.return=ft,ft=Ot):(S(ft,lt),Ot=vA(kt,ft.mode,Ot),Ot.return=ft,ft=Ot),ke(ft)):S(ft,lt)}return function(ft,lt,kt,Ot){try{Oy=0;var jn=qr(ft,lt,kt,Ot);return Hg=null,jn}catch(vn){if(vn===Bg||vn===OS)throw vn;var Cr=Bo(29,vn,null,ft.mode);return Cr.lanes=Ot,Cr.return=ft,Cr}}}var Up=L5(!0),O5=L5(!1),Dm=!1;function DA(h){h.updateQueue={baseState:h.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function FA(h,y){h=h.updateQueue,y.updateQueue===h&&(y.updateQueue={baseState:h.baseState,firstBaseUpdate:h.firstBaseUpdate,lastBaseUpdate:h.lastBaseUpdate,shared:h.shared,callbacks:null})}function Fm(h){return{lane:h,tag:0,payload:null,callback:null,next:null}}function Rm(h,y,S){var M=h.updateQueue;if(M===null)return null;if(M=M.shared,(Mr&2)!==0){var q=M.pending;return q===null?y.next=y:(y.next=q.next,q.next=y),M.pending=y,y=MS(h),v5(h,null,S),y}return jS(h,M,y,S),MS(h)}function zy(h,y,S){if(y=y.updateQueue,y!==null&&(y=y.shared,(S&4194048)!==0)){var M=y.lanes;M&=h.pendingLanes,S|=M,y.lanes=S,Qt(h,S)}}function RA(h,y){var S=h.updateQueue,M=h.alternate;if(M!==null&&(M=M.updateQueue,S===M)){var q=null,Z=null;if(S=S.firstBaseUpdate,S!==null){do{var ke={lane:S.lane,tag:S.tag,payload:S.payload,callback:null,next:null};Z===null?q=Z=ke:Z=Z.next=ke,S=S.next}while(S!==null);Z===null?q=Z=y:Z=Z.next=y}else q=Z=y;S={baseState:M.baseState,firstBaseUpdate:q,lastBaseUpdate:Z,shared:M.shared,callbacks:M.callbacks},h.updateQueue=S;return}h=S.lastBaseUpdate,h===null?S.firstBaseUpdate=y:h.next=y,S.lastBaseUpdate=y}var LA=!1;function Uy(){if(LA){var h=Ug;if(h!==null)throw h}}function By(h,y,S,M){LA=!1;var q=h.updateQueue;Dm=!1;var Z=q.firstBaseUpdate,ke=q.lastBaseUpdate,Ue=q.shared.pending;if(Ue!==null){q.shared.pending=null;var nt=Ue,Nt=nt.next;nt.next=null,ke===null?Z=Nt:ke.next=Nt,ke=nt;var Lt=h.alternate;Lt!==null&&(Lt=Lt.updateQueue,Ue=Lt.lastBaseUpdate,Ue!==ke&&(Ue===null?Lt.firstBaseUpdate=Nt:Ue.next=Nt,Lt.lastBaseUpdate=nt))}if(Z!==null){var It=q.baseState;ke=0,Lt=Nt=nt=null,Ue=Z;do{var Ct=Ue.lane&-536870913,Dt=Ct!==Ue.lane;if(Dt?(gr&Ct)===Ct:(M&Ct)===Ct){Ct!==0&&Ct===zg&&(LA=!0),Lt!==null&&(Lt=Lt.next={lane:0,tag:Ue.tag,payload:Ue.payload,callback:null,next:null});e:{var gn=h,Fn=Ue;Ct=y;var qr=S;switch(Fn.tag){case 1:if(gn=Fn.payload,typeof gn=="function"){It=gn.call(qr,It,Ct);break e}It=gn;break e;case 3:gn.flags=gn.flags&-65537|128;case 0:if(gn=Fn.payload,Ct=typeof gn=="function"?gn.call(qr,It,Ct):gn,Ct==null)break e;It=m({},It,Ct);break e;case 2:Dm=!0}}Ct=Ue.callback,Ct!==null&&(h.flags|=64,Dt&&(h.flags|=8192),Dt=q.callbacks,Dt===null?q.callbacks=[Ct]:Dt.push(Ct))}else Dt={lane:Ct,tag:Ue.tag,payload:Ue.payload,callback:Ue.callback,next:null},Lt===null?(Nt=Lt=Dt,nt=It):Lt=Lt.next=Dt,ke|=Ct;if(Ue=Ue.next,Ue===null){if(Ue=q.shared.pending,Ue===null)break;Dt=Ue,Ue=Dt.next,Dt.next=null,q.lastBaseUpdate=Dt,q.shared.pending=null}}while(!0);Lt===null&&(nt=It),q.baseState=nt,q.firstBaseUpdate=Nt,q.lastBaseUpdate=Lt,Z===null&&(q.shared.lanes=0),Um|=ke,h.lanes=ke,h.memoizedState=It}}function I5(h,y){if(typeof h!="function")throw Error(r(191,h));h.call(y)}function z5(h,y){var S=h.callbacks;if(S!==null)for(h.callbacks=null,h=0;h<S.length;h++)I5(S[h],y)}var qg=W(null),BS=W(0);function U5(h,y){h=ou,ce(BS,h),ce(qg,y),ou=h|y.baseLanes}function OA(){ce(BS,ou),ce(qg,qg.current)}function IA(){ou=BS.current,re(qg),re(BS)}var Ho=W(null),Tl=null;function Lm(h){var y=h.alternate;ce(ei,ei.current&1),ce(Ho,h),Tl===null&&(y===null||qg.current!==null||y.memoizedState!==null)&&(Tl=h)}function zA(h){ce(ei,ei.current),ce(Ho,h),Tl===null&&(Tl=h)}function B5(h){h.tag===22?(ce(ei,ei.current),ce(Ho,h),Tl===null&&(Tl=h)):Om()}function Om(){ce(ei,ei.current),ce(Ho,Ho.current)}function qo(h){re(Ho),Tl===h&&(Tl=null),re(ei)}var ei=W(0);function HS(h){for(var y=h;y!==null;){if(y.tag===13){var S=y.memoizedState;if(S!==null&&(S=S.dehydrated,S===null||Vj(S)||Gj(S)))return y}else if(y.tag===19&&(y.memoizedProps.revealOrder==="forwards"||y.memoizedProps.revealOrder==="backwards"||y.memoizedProps.revealOrder==="unstable_legacy-backwards"||y.memoizedProps.revealOrder==="together")){if((y.flags&128)!==0)return y}else if(y.child!==null){y.child.return=y,y=y.child;continue}if(y===h)break;for(;y.sibling===null;){if(y.return===null||y.return===h)return null;y=y.return}y.sibling.return=y.return,y=y.sibling}return null}var Jd=0,Yn=null,Br=null,si=null,qS=!1,$g=!1,Bp=!1,$S=0,Hy=0,Vg=null,xce=0;function La(){throw Error(r(321))}function UA(h,y){if(y===null)return!1;for(var S=0;S<y.length&&S<h.length;S++)if(!Uo(h[S],y[S]))return!1;return!0}function BA(h,y,S,M,q,Z){return Jd=Z,Yn=y,y.memoizedState=null,y.updateQueue=null,y.lanes=0,ie.H=h===null||h.memoizedState===null?kU:nj,Bp=!1,Z=S(M,q),Bp=!1,$g&&(Z=q5(y,S,M,q)),H5(h),Z}function H5(h){ie.H=Vy;var y=Br!==null&&Br.next!==null;if(Jd=0,si=Br=Yn=null,qS=!1,Hy=0,Vg=null,y)throw Error(r(300));h===null||oi||(h=h.dependencies,h!==null&&FS(h)&&(oi=!0))}function q5(h,y,S,M){Yn=h;var q=0;do{if($g&&(Vg=null),Hy=0,$g=!1,25<=q)throw Error(r(301));if(q+=1,si=Br=null,h.updateQueue!=null){var Z=h.updateQueue;Z.lastEffect=null,Z.events=null,Z.stores=null,Z.memoCache!=null&&(Z.memoCache.index=0)}ie.H=NU,Z=y(S,M)}while($g);return Z}function yce(){var h=ie.H,y=h.useState()[0];return y=typeof y.then=="function"?qy(y):y,h=h.useState()[0],(Br!==null?Br.memoizedState:null)!==h&&(Yn.flags|=1024),y}function HA(){var h=$S!==0;return $S=0,h}function qA(h,y,S){y.updateQueue=h.updateQueue,y.flags&=-2053,h.lanes&=~S}function $A(h){if(qS){for(h=h.memoizedState;h!==null;){var y=h.queue;y!==null&&(y.pending=null),h=h.next}qS=!1}Jd=0,si=Br=Yn=null,$g=!1,Hy=$S=0,Vg=null}function Hs(){var h={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return si===null?Yn.memoizedState=si=h:si=si.next=h,si}function ti(){if(Br===null){var h=Yn.alternate;h=h!==null?h.memoizedState:null}else h=Br.next;var y=si===null?Yn.memoizedState:si.next;if(y!==null)si=y,Br=h;else{if(h===null)throw Yn.alternate===null?Error(r(467)):Error(r(310));Br=h,h={memoizedState:Br.memoizedState,baseState:Br.baseState,baseQueue:Br.baseQueue,queue:Br.queue,next:null},si===null?Yn.memoizedState=si=h:si=si.next=h}return si}function VS(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function qy(h){var y=Hy;return Hy+=1,Vg===null&&(Vg=[]),h=D5(Vg,h,y),y=Yn,(si===null?y.memoizedState:si.next)===null&&(y=y.alternate,ie.H=y===null||y.memoizedState===null?kU:nj),h}function GS(h){if(h!==null&&typeof h=="object"){if(typeof h.then=="function")return qy(h);if(h.$$typeof===C)return Ji(h)}throw Error(r(438,String(h)))}function VA(h){var y=null,S=Yn.updateQueue;if(S!==null&&(y=S.memoCache),y==null){var M=Yn.alternate;M!==null&&(M=M.updateQueue,M!==null&&(M=M.memoCache,M!=null&&(y={data:M.data.map(function(q){return q.slice()}),index:0})))}if(y==null&&(y={data:[],index:0}),S===null&&(S=VS(),Yn.updateQueue=S),S.memoCache=y,S=y.data[y.index],S===void 0)for(S=y.data[y.index]=Array(h),M=0;M<h;M++)S[M]=D;return y.index++,S}function eu(h,y){return typeof y=="function"?y(h):y}function WS(h){var y=ti();return GA(y,Br,h)}function GA(h,y,S){var M=h.queue;if(M===null)throw Error(r(311));M.lastRenderedReducer=S;var q=h.baseQueue,Z=M.pending;if(Z!==null){if(q!==null){var ke=q.next;q.next=Z.next,Z.next=ke}y.baseQueue=q=Z,M.pending=null}if(Z=h.baseState,q===null)h.memoizedState=Z;else{y=q.next;var Ue=ke=null,nt=null,Nt=y,Lt=!1;do{var It=Nt.lane&-536870913;if(It!==Nt.lane?(gr&It)===It:(Jd&It)===It){var Ct=Nt.revertLane;if(Ct===0)nt!==null&&(nt=nt.next={lane:0,revertLane:0,gesture:null,action:Nt.action,hasEagerState:Nt.hasEagerState,eagerState:Nt.eagerState,next:null}),It===zg&&(Lt=!0);else if((Jd&Ct)===Ct){Nt=Nt.next,Ct===zg&&(Lt=!0);continue}else It={lane:0,revertLane:Nt.revertLane,gesture:null,action:Nt.action,hasEagerState:Nt.hasEagerState,eagerState:Nt.eagerState,next:null},nt===null?(Ue=nt=It,ke=Z):nt=nt.next=It,Yn.lanes|=Ct,Um|=Ct;It=Nt.action,Bp&&S(Z,It),Z=Nt.hasEagerState?Nt.eagerState:S(Z,It)}else Ct={lane:It,revertLane:Nt.revertLane,gesture:Nt.gesture,action:Nt.action,hasEagerState:Nt.hasEagerState,eagerState:Nt.eagerState,next:null},nt===null?(Ue=nt=Ct,ke=Z):nt=nt.next=Ct,Yn.lanes|=It,Um|=It;Nt=Nt.next}while(Nt!==null&&Nt!==y);if(nt===null?ke=Z:nt.next=Ue,!Uo(Z,h.memoizedState)&&(oi=!0,Lt&&(S=Ug,S!==null)))throw S;h.memoizedState=Z,h.baseState=ke,h.baseQueue=nt,M.lastRenderedState=Z}return q===null&&(M.lanes=0),[h.memoizedState,M.dispatch]}function WA(h){var y=ti(),S=y.queue;if(S===null)throw Error(r(311));S.lastRenderedReducer=h;var M=S.dispatch,q=S.pending,Z=y.memoizedState;if(q!==null){S.pending=null;var ke=q=q.next;do Z=h(Z,ke.action),ke=ke.next;while(ke!==q);Uo(Z,y.memoizedState)||(oi=!0),y.memoizedState=Z,y.baseQueue===null&&(y.baseState=Z),S.lastRenderedState=Z}return[Z,M]}function $5(h,y,S){var M=Yn,q=ti(),Z=yr;if(Z){if(S===void 0)throw Error(r(407));S=S()}else S=y();var ke=!Uo((Br||q).memoizedState,S);if(ke&&(q.memoizedState=S,oi=!0),q=q.queue,YA(W5.bind(null,M,q,h),[h]),q.getSnapshot!==y||ke||si!==null&&si.memoizedState.tag&1){if(M.flags|=2048,Gg(9,{destroy:void 0},G5.bind(null,M,q,S,y),null),Jr===null)throw Error(r(349));Z||(Jd&127)!==0||V5(M,y,S)}return S}function V5(h,y,S){h.flags|=16384,h={getSnapshot:y,value:S},y=Yn.updateQueue,y===null?(y=VS(),Yn.updateQueue=y,y.stores=[h]):(S=y.stores,S===null?y.stores=[h]:S.push(h))}function G5(h,y,S,M){y.value=S,y.getSnapshot=M,K5(y)&&X5(h)}function W5(h,y,S){return S(function(){K5(y)&&X5(h)})}function K5(h){var y=h.getSnapshot;h=h.value;try{var S=y();return!Uo(h,S)}catch{return!0}}function X5(h){var y=Ep(h,2);y!==null&&yo(y,h,2)}function KA(h){var y=Hs();if(typeof h=="function"){var S=h;if(h=S(),Bp){Me(!0);try{S()}finally{Me(!1)}}}return y.memoizedState=y.baseState=h,y.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:eu,lastRenderedState:h},y}function Y5(h,y,S,M){return h.baseState=S,GA(h,Br,typeof M=="function"?M:eu)}function vce(h,y,S,M,q){if(YS(h))throw Error(r(485));if(h=y.action,h!==null){var Z={payload:q,action:h,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(ke){Z.listeners.push(ke)}};ie.T!==null?S(!0):Z.isTransition=!1,M(Z),S=y.pending,S===null?(Z.next=y.pending=Z,Q5(y,Z)):(Z.next=S.next,y.pending=S.next=Z)}}function Q5(h,y){var S=y.action,M=y.payload,q=h.state;if(y.isTransition){var Z=ie.T,ke={};ie.T=ke;try{var Ue=S(q,M),nt=ie.S;nt!==null&&nt(ke,Ue),Z5(h,y,Ue)}catch(Nt){XA(h,y,Nt)}finally{Z!==null&&ke.types!==null&&(Z.types=ke.types),ie.T=Z}}else try{Z=S(q,M),Z5(h,y,Z)}catch(Nt){XA(h,y,Nt)}}function Z5(h,y,S){S!==null&&typeof S=="object"&&typeof S.then=="function"?S.then(function(M){J5(h,y,M)},function(M){return XA(h,y,M)}):J5(h,y,S)}function J5(h,y,S){y.status="fulfilled",y.value=S,eU(y),h.state=S,y=h.pending,y!==null&&(S=y.next,S===y?h.pending=null:(S=S.next,y.next=S,Q5(h,S)))}function XA(h,y,S){var M=h.pending;if(h.pending=null,M!==null){M=M.next;do y.status="rejected",y.reason=S,eU(y),y=y.next;while(y!==M)}h.action=null}function eU(h){h=h.listeners;for(var y=0;y<h.length;y++)(0,h[y])()}function tU(h,y){return y}function nU(h,y){if(yr){var S=Jr.formState;if(S!==null){e:{var M=Yn;if(yr){if(pa){t:{for(var q=pa,Z=Pl;q.nodeType!==8;){if(!Z){q=null;break t}if(q=Al(q.nextSibling),q===null){q=null;break t}}Z=q.data,q=Z==="F!"||Z==="F"?q:null}if(q){pa=Al(q.nextSibling),M=q.data==="F!";break e}}Mm(M)}M=!1}M&&(y=S[0])}}return S=Hs(),S.memoizedState=S.baseState=y,M={pending:null,lanes:0,dispatch:null,lastRenderedReducer:tU,lastRenderedState:y},S.queue=M,S=wU.bind(null,Yn,M),M.dispatch=S,M=KA(!1),Z=tj.bind(null,Yn,!1,M.queue),M=Hs(),q={state:y,dispatch:null,action:h,pending:null},M.queue=q,S=vce.bind(null,Yn,q,Z,S),q.dispatch=S,M.memoizedState=h,[y,S,!1]}function rU(h){var y=ti();return aU(y,Br,h)}function aU(h,y,S){if(y=GA(h,y,tU)[0],h=WS(eu)[0],typeof y=="object"&&y!==null&&typeof y.then=="function")try{var M=qy(y)}catch(ke){throw ke===Bg?OS:ke}else M=y;y=ti();var q=y.queue,Z=q.dispatch;return S!==y.memoizedState&&(Yn.flags|=2048,Gg(9,{destroy:void 0},wce.bind(null,q,S),null)),[M,Z,h]}function wce(h,y){h.action=y}function iU(h){var y=ti(),S=Br;if(S!==null)return aU(y,S,h);ti(),y=y.memoizedState,S=ti();var M=S.queue.dispatch;return S.memoizedState=h,[y,M,!1]}function Gg(h,y,S,M){return h={tag:h,create:S,deps:M,inst:y,next:null},y=Yn.updateQueue,y===null&&(y=VS(),Yn.updateQueue=y),S=y.lastEffect,S===null?y.lastEffect=h.next=h:(M=S.next,S.next=h,h.next=M,y.lastEffect=h),h}function sU(){return ti().memoizedState}function KS(h,y,S,M){var q=Hs();Yn.flags|=h,q.memoizedState=Gg(1|y,{destroy:void 0},S,M===void 0?null:M)}function XS(h,y,S,M){var q=ti();M=M===void 0?null:M;var Z=q.memoizedState.inst;Br!==null&&M!==null&&UA(M,Br.memoizedState.deps)?q.memoizedState=Gg(y,Z,S,M):(Yn.flags|=h,q.memoizedState=Gg(1|y,Z,S,M))}function oU(h,y){KS(8390656,8,h,y)}function YA(h,y){XS(2048,8,h,y)}function Sce(h){Yn.flags|=4;var y=Yn.updateQueue;if(y===null)y=VS(),Yn.updateQueue=y,y.events=[h];else{var S=y.events;S===null?y.events=[h]:S.push(h)}}function lU(h){var y=ti().memoizedState;return Sce({ref:y,nextImpl:h}),function(){if((Mr&2)!==0)throw Error(r(440));return y.impl.apply(void 0,arguments)}}function cU(h,y){return XS(4,2,h,y)}function dU(h,y){return XS(4,4,h,y)}function uU(h,y){if(typeof y=="function"){h=h();var S=y(h);return function(){typeof S=="function"?S():y(null)}}if(y!=null)return h=h(),y.current=h,function(){y.current=null}}function mU(h,y,S){S=S!=null?S.concat([h]):null,XS(4,4,uU.bind(null,y,h),S)}function QA(){}function hU(h,y){var S=ti();y=y===void 0?null:y;var M=S.memoizedState;return y!==null&&UA(y,M[1])?M[0]:(S.memoizedState=[h,y],h)}function pU(h,y){var S=ti();y=y===void 0?null:y;var M=S.memoizedState;if(y!==null&&UA(y,M[1]))return M[0];if(M=h(),Bp){Me(!0);try{h()}finally{Me(!1)}}return S.memoizedState=[M,y],M}function ZA(h,y,S){return S===void 0||(Jd&1073741824)!==0&&(gr&261930)===0?h.memoizedState=y:(h.memoizedState=S,h=fB(),Yn.lanes|=h,Um|=h,S)}function fU(h,y,S,M){return Uo(S,y)?S:qg.current!==null?(h=ZA(h,S,M),Uo(h,y)||(oi=!0),h):(Jd&42)===0||(Jd&1073741824)!==0&&(gr&261930)===0?(oi=!0,h.memoizedState=S):(h=fB(),Yn.lanes|=h,Um|=h,y)}function gU(h,y,S,M,q){var Z=ee.p;ee.p=Z!==0&&8>Z?Z:8;var ke=ie.T,Ue={};ie.T=Ue,tj(h,!1,y,S);try{var nt=q(),Nt=ie.S;if(Nt!==null&&Nt(Ue,nt),nt!==null&&typeof nt=="object"&&typeof nt.then=="function"){var Lt=bce(nt,M);$y(h,y,Lt,Go(h))}else $y(h,y,M,Go(h))}catch(It){$y(h,y,{then:function(){},status:"rejected",reason:It},Go())}finally{ee.p=Z,ke!==null&&Ue.types!==null&&(ke.types=Ue.types),ie.T=ke}}function _ce(){}function JA(h,y,S,M){if(h.tag!==5)throw Error(r(476));var q=bU(h).queue;gU(h,q,y,ue,S===null?_ce:function(){return xU(h),S(M)})}function bU(h){var y=h.memoizedState;if(y!==null)return y;y={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:eu,lastRenderedState:ue},next:null};var S={};return y.next={memoizedState:S,baseState:S,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:eu,lastRenderedState:S},next:null},h.memoizedState=y,h=h.alternate,h!==null&&(h.memoizedState=y),y}function xU(h){var y=bU(h);y.next===null&&(y=h.alternate.memoizedState),$y(h,y.next.queue,{},Go())}function ej(){return Ji(ov)}function yU(){return ti().memoizedState}function vU(){return ti().memoizedState}function kce(h){for(var y=h.return;y!==null;){switch(y.tag){case 24:case 3:var S=Go();h=Fm(S);var M=Rm(y,h,S);M!==null&&(yo(M,y,S),zy(M,y,S)),y={cache:AA()},h.payload=y;return}y=y.return}}function Nce(h,y,S){var M=Go();S={lane:M,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null},YS(h)?SU(y,S):(S=xA(h,y,S,M),S!==null&&(yo(S,h,M),_U(S,y,M)))}function wU(h,y,S){var M=Go();$y(h,y,S,M)}function $y(h,y,S,M){var q={lane:M,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null};if(YS(h))SU(y,q);else{var Z=h.alternate;if(h.lanes===0&&(Z===null||Z.lanes===0)&&(Z=y.lastRenderedReducer,Z!==null))try{var ke=y.lastRenderedState,Ue=Z(ke,S);if(q.hasEagerState=!0,q.eagerState=Ue,Uo(Ue,ke))return jS(h,y,q,0),Jr===null&&AS(),!1}catch{}if(S=xA(h,y,q,M),S!==null)return yo(S,h,M),_U(S,y,M),!0}return!1}function tj(h,y,S,M){if(M={lane:2,revertLane:Dj(),gesture:null,action:M,hasEagerState:!1,eagerState:null,next:null},YS(h)){if(y)throw Error(r(479))}else y=xA(h,S,M,2),y!==null&&yo(y,h,2)}function YS(h){var y=h.alternate;return h===Yn||y!==null&&y===Yn}function SU(h,y){$g=qS=!0;var S=h.pending;S===null?y.next=y:(y.next=S.next,S.next=y),h.pending=y}function _U(h,y,S){if((S&4194048)!==0){var M=y.lanes;M&=h.pendingLanes,S|=M,y.lanes=S,Qt(h,S)}}var Vy={readContext:Ji,use:GS,useCallback:La,useContext:La,useEffect:La,useImperativeHandle:La,useLayoutEffect:La,useInsertionEffect:La,useMemo:La,useReducer:La,useRef:La,useState:La,useDebugValue:La,useDeferredValue:La,useTransition:La,useSyncExternalStore:La,useId:La,useHostTransitionStatus:La,useFormState:La,useActionState:La,useOptimistic:La,useMemoCache:La,useCacheRefresh:La};Vy.useEffectEvent=La;var kU={readContext:Ji,use:GS,useCallback:function(h,y){return Hs().memoizedState=[h,y===void 0?null:y],h},useContext:Ji,useEffect:oU,useImperativeHandle:function(h,y,S){S=S!=null?S.concat([h]):null,KS(4194308,4,uU.bind(null,y,h),S)},useLayoutEffect:function(h,y){return KS(4194308,4,h,y)},useInsertionEffect:function(h,y){KS(4,2,h,y)},useMemo:function(h,y){var S=Hs();y=y===void 0?null:y;var M=h();if(Bp){Me(!0);try{h()}finally{Me(!1)}}return S.memoizedState=[M,y],M},useReducer:function(h,y,S){var M=Hs();if(S!==void 0){var q=S(y);if(Bp){Me(!0);try{S(y)}finally{Me(!1)}}}else q=y;return M.memoizedState=M.baseState=q,h={pending:null,lanes:0,dispatch:null,lastRenderedReducer:h,lastRenderedState:q},M.queue=h,h=h.dispatch=Nce.bind(null,Yn,h),[M.memoizedState,h]},useRef:function(h){var y=Hs();return h={current:h},y.memoizedState=h},useState:function(h){h=KA(h);var y=h.queue,S=wU.bind(null,Yn,y);return y.dispatch=S,[h.memoizedState,S]},useDebugValue:QA,useDeferredValue:function(h,y){var S=Hs();return ZA(S,h,y)},useTransition:function(){var h=KA(!1);return h=gU.bind(null,Yn,h.queue,!0,!1),Hs().memoizedState=h,[!1,h]},useSyncExternalStore:function(h,y,S){var M=Yn,q=Hs();if(yr){if(S===void 0)throw Error(r(407));S=S()}else{if(S=y(),Jr===null)throw Error(r(349));(gr&127)!==0||V5(M,y,S)}q.memoizedState=S;var Z={value:S,getSnapshot:y};return q.queue=Z,oU(W5.bind(null,M,Z,h),[h]),M.flags|=2048,Gg(9,{destroy:void 0},G5.bind(null,M,Z,S,y),null),S},useId:function(){var h=Hs(),y=Jr.identifierPrefix;if(yr){var S=ed,M=Jc;S=(M&~(1<<32-Be(M)-1)).toString(32)+S,y="_"+y+"R_"+S,S=$S++,0<S&&(y+="H"+S.toString(32)),y+="_"}else S=xce++,y="_"+y+"r_"+S.toString(32)+"_";return h.memoizedState=y},useHostTransitionStatus:ej,useFormState:nU,useActionState:nU,useOptimistic:function(h){var y=Hs();y.memoizedState=y.baseState=h;var S={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return y.queue=S,y=tj.bind(null,Yn,!0,S),S.dispatch=y,[h,y]},useMemoCache:VA,useCacheRefresh:function(){return Hs().memoizedState=kce.bind(null,Yn)},useEffectEvent:function(h){var y=Hs(),S={impl:h};return y.memoizedState=S,function(){if((Mr&2)!==0)throw Error(r(440));return S.impl.apply(void 0,arguments)}}},nj={readContext:Ji,use:GS,useCallback:hU,useContext:Ji,useEffect:YA,useImperativeHandle:mU,useInsertionEffect:cU,useLayoutEffect:dU,useMemo:pU,useReducer:WS,useRef:sU,useState:function(){return WS(eu)},useDebugValue:QA,useDeferredValue:function(h,y){var S=ti();return fU(S,Br.memoizedState,h,y)},useTransition:function(){var h=WS(eu)[0],y=ti().memoizedState;return[typeof h=="boolean"?h:qy(h),y]},useSyncExternalStore:$5,useId:yU,useHostTransitionStatus:ej,useFormState:rU,useActionState:rU,useOptimistic:function(h,y){var S=ti();return Y5(S,Br,h,y)},useMemoCache:VA,useCacheRefresh:vU};nj.useEffectEvent=lU;var NU={readContext:Ji,use:GS,useCallback:hU,useContext:Ji,useEffect:YA,useImperativeHandle:mU,useInsertionEffect:cU,useLayoutEffect:dU,useMemo:pU,useReducer:WA,useRef:sU,useState:function(){return WA(eu)},useDebugValue:QA,useDeferredValue:function(h,y){var S=ti();return Br===null?ZA(S,h,y):fU(S,Br.memoizedState,h,y)},useTransition:function(){var h=WA(eu)[0],y=ti().memoizedState;return[typeof h=="boolean"?h:qy(h),y]},useSyncExternalStore:$5,useId:yU,useHostTransitionStatus:ej,useFormState:iU,useActionState:iU,useOptimistic:function(h,y){var S=ti();return Br!==null?Y5(S,Br,h,y):(S.baseState=h,[h,S.queue.dispatch])},useMemoCache:VA,useCacheRefresh:vU};NU.useEffectEvent=lU;function rj(h,y,S,M){y=h.memoizedState,S=S(M,y),S=S==null?y:m({},y,S),h.memoizedState=S,h.lanes===0&&(h.updateQueue.baseState=S)}var aj={enqueueSetState:function(h,y,S){h=h._reactInternals;var M=Go(),q=Fm(M);q.payload=y,S!=null&&(q.callback=S),y=Rm(h,q,M),y!==null&&(yo(y,h,M),zy(y,h,M))},enqueueReplaceState:function(h,y,S){h=h._reactInternals;var M=Go(),q=Fm(M);q.tag=1,q.payload=y,S!=null&&(q.callback=S),y=Rm(h,q,M),y!==null&&(yo(y,h,M),zy(y,h,M))},enqueueForceUpdate:function(h,y){h=h._reactInternals;var S=Go(),M=Fm(S);M.tag=2,y!=null&&(M.callback=y),y=Rm(h,M,S),y!==null&&(yo(y,h,S),zy(y,h,S))}};function CU(h,y,S,M,q,Z,ke){return h=h.stateNode,typeof h.shouldComponentUpdate=="function"?h.shouldComponentUpdate(M,Z,ke):y.prototype&&y.prototype.isPureReactComponent?!My(S,M)||!My(q,Z):!0}function PU(h,y,S,M){h=y.state,typeof y.componentWillReceiveProps=="function"&&y.componentWillReceiveProps(S,M),typeof y.UNSAFE_componentWillReceiveProps=="function"&&y.UNSAFE_componentWillReceiveProps(S,M),y.state!==h&&aj.enqueueReplaceState(y,y.state,null)}function Hp(h,y){var S=y;if("ref"in y){S={};for(var M in y)M!=="ref"&&(S[M]=y[M])}if(h=h.defaultProps){S===y&&(S=m({},S));for(var q in h)S[q]===void 0&&(S[q]=h[q])}return S}function TU(h){TS(h)}function AU(h){console.error(h)}function jU(h){TS(h)}function QS(h,y){try{var S=h.onUncaughtError;S(y.value,{componentStack:y.stack})}catch(M){setTimeout(function(){throw M})}}function MU(h,y,S){try{var M=h.onCaughtError;M(S.value,{componentStack:S.stack,errorBoundary:y.tag===1?y.stateNode:null})}catch(q){setTimeout(function(){throw q})}}function ij(h,y,S){return S=Fm(S),S.tag=3,S.payload={element:null},S.callback=function(){QS(h,y)},S}function EU(h){return h=Fm(h),h.tag=3,h}function DU(h,y,S,M){var q=S.type.getDerivedStateFromError;if(typeof q=="function"){var Z=M.value;h.payload=function(){return q(Z)},h.callback=function(){MU(y,S,M)}}var ke=S.stateNode;ke!==null&&typeof ke.componentDidCatch=="function"&&(h.callback=function(){MU(y,S,M),typeof q!="function"&&(Bm===null?Bm=new Set([this]):Bm.add(this));var Ue=M.stack;this.componentDidCatch(M.value,{componentStack:Ue!==null?Ue:""})})}function Cce(h,y,S,M,q){if(S.flags|=32768,M!==null&&typeof M=="object"&&typeof M.then=="function"){if(y=S.alternate,y!==null&&Ig(y,S,q,!0),S=Ho.current,S!==null){switch(S.tag){case 31:case 13:return Tl===null?c_():S.alternate===null&&Oa===0&&(Oa=3),S.flags&=-257,S.flags|=65536,S.lanes=q,M===IS?S.flags|=16384:(y=S.updateQueue,y===null?S.updateQueue=new Set([M]):y.add(M),jj(h,M,q)),!1;case 22:return S.flags|=65536,M===IS?S.flags|=16384:(y=S.updateQueue,y===null?(y={transitions:null,markerInstances:null,retryQueue:new Set([M])},S.updateQueue=y):(S=y.retryQueue,S===null?y.retryQueue=new Set([M]):S.add(M)),jj(h,M,q)),!1}throw Error(r(435,S.tag))}return jj(h,M,q),c_(),!1}if(yr)return y=Ho.current,y!==null?((y.flags&65536)===0&&(y.flags|=256),y.flags|=65536,y.lanes=q,M!==kA&&(h=Error(r(422),{cause:M}),Fy(kl(h,S)))):(M!==kA&&(y=Error(r(423),{cause:M}),Fy(kl(y,S))),h=h.current.alternate,h.flags|=65536,q&=-q,h.lanes|=q,M=kl(M,S),q=ij(h.stateNode,M,q),RA(h,q),Oa!==4&&(Oa=2)),!1;var Z=Error(r(520),{cause:M});if(Z=kl(Z,S),Jy===null?Jy=[Z]:Jy.push(Z),Oa!==4&&(Oa=2),y===null)return!0;M=kl(M,S),S=y;do{switch(S.tag){case 3:return S.flags|=65536,h=q&-q,S.lanes|=h,h=ij(S.stateNode,M,h),RA(S,h),!1;case 1:if(y=S.type,Z=S.stateNode,(S.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||Z!==null&&typeof Z.componentDidCatch=="function"&&(Bm===null||!Bm.has(Z))))return S.flags|=65536,q&=-q,S.lanes|=q,q=EU(q),DU(q,h,S,M),RA(S,q),!1}S=S.return}while(S!==null);return!1}var sj=Error(r(461)),oi=!1;function es(h,y,S,M){y.child=h===null?O5(y,null,S,M):Up(y,h.child,S,M)}function FU(h,y,S,M,q){S=S.render;var Z=y.ref;if("ref"in M){var ke={};for(var Ue in M)Ue!=="ref"&&(ke[Ue]=M[Ue])}else ke=M;return Lp(y),M=BA(h,y,S,ke,Z,q),Ue=HA(),h!==null&&!oi?(qA(h,y,q),tu(h,y,q)):(yr&&Ue&&SA(y),y.flags|=1,es(h,y,M,q),y.child)}function RU(h,y,S,M,q){if(h===null){var Z=S.type;return typeof Z=="function"&&!yA(Z)&&Z.defaultProps===void 0&&S.compare===null?(y.tag=15,y.type=Z,LU(h,y,Z,M,q)):(h=ES(S.type,null,M,y,y.mode,q),h.ref=y.ref,h.return=y,y.child=h)}if(Z=h.child,!pj(h,q)){var ke=Z.memoizedProps;if(S=S.compare,S=S!==null?S:My,S(ke,M)&&h.ref===y.ref)return tu(h,y,q)}return y.flags|=1,h=Xd(Z,M),h.ref=y.ref,h.return=y,y.child=h}function LU(h,y,S,M,q){if(h!==null){var Z=h.memoizedProps;if(My(Z,M)&&h.ref===y.ref)if(oi=!1,y.pendingProps=M=Z,pj(h,q))(h.flags&131072)!==0&&(oi=!0);else return y.lanes=h.lanes,tu(h,y,q)}return oj(h,y,S,M,q)}function OU(h,y,S,M){var q=M.children,Z=h!==null?h.memoizedState:null;if(h===null&&y.stateNode===null&&(y.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),M.mode==="hidden"){if((y.flags&128)!==0){if(Z=Z!==null?Z.baseLanes|S:S,h!==null){for(M=y.child=h.child,q=0;M!==null;)q=q|M.lanes|M.childLanes,M=M.sibling;M=q&~Z}else M=0,y.child=null;return IU(h,y,Z,S,M)}if((S&536870912)!==0)y.memoizedState={baseLanes:0,cachePool:null},h!==null&&LS(y,Z!==null?Z.cachePool:null),Z!==null?U5(y,Z):OA(),B5(y);else return M=y.lanes=536870912,IU(h,y,Z!==null?Z.baseLanes|S:S,S,M)}else Z!==null?(LS(y,Z.cachePool),U5(y,Z),Om(),y.memoizedState=null):(h!==null&&LS(y,null),OA(),Om());return es(h,y,q,S),y.child}function Gy(h,y){return h!==null&&h.tag===22||y.stateNode!==null||(y.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),y.sibling}function IU(h,y,S,M,q){var Z=MA();return Z=Z===null?null:{parent:ii._currentValue,pool:Z},y.memoizedState={baseLanes:S,cachePool:Z},h!==null&&LS(y,null),OA(),B5(y),h!==null&&Ig(h,y,M,!0),y.childLanes=q,null}function ZS(h,y){return y=e_({mode:y.mode,children:y.children},h.mode),y.ref=h.ref,h.child=y,y.return=h,y}function zU(h,y,S){return Up(y,h.child,null,S),h=ZS(y,y.pendingProps),h.flags|=2,qo(y),y.memoizedState=null,h}function Pce(h,y,S){var M=y.pendingProps,q=(y.flags&128)!==0;if(y.flags&=-129,h===null){if(yr){if(M.mode==="hidden")return h=ZS(y,M),y.lanes=536870912,Gy(null,h);if(zA(y),(h=pa)?(h=QB(h,Pl),h=h!==null&&h.data==="&"?h:null,h!==null&&(y.memoizedState={dehydrated:h,treeContext:Am!==null?{id:Jc,overflow:ed}:null,retryLane:536870912,hydrationErrors:null},S=S5(h),S.return=y,y.child=S,Zi=y,pa=null)):h=null,h===null)throw Mm(y);return y.lanes=536870912,null}return ZS(y,M)}var Z=h.memoizedState;if(Z!==null){var ke=Z.dehydrated;if(zA(y),q)if(y.flags&256)y.flags&=-257,y=zU(h,y,S);else if(y.memoizedState!==null)y.child=h.child,y.flags|=128,y=null;else throw Error(r(558));else if(oi||Ig(h,y,S,!1),q=(S&h.childLanes)!==0,oi||q){if(M=Jr,M!==null&&(ke=en(M,S),ke!==0&&ke!==Z.retryLane))throw Z.retryLane=ke,Ep(h,ke),yo(M,h,ke),sj;c_(),y=zU(h,y,S)}else h=Z.treeContext,pa=Al(ke.nextSibling),Zi=y,yr=!0,jm=null,Pl=!1,h!==null&&N5(y,h),y=ZS(y,M),y.flags|=4096;return y}return h=Xd(h.child,{mode:M.mode,children:M.children}),h.ref=y.ref,y.child=h,h.return=y,h}function JS(h,y){var S=y.ref;if(S===null)h!==null&&h.ref!==null&&(y.flags|=4194816);else{if(typeof S!="function"&&typeof S!="object")throw Error(r(284));(h===null||h.ref!==S)&&(y.flags|=4194816)}}function oj(h,y,S,M,q){return Lp(y),S=BA(h,y,S,M,void 0,q),M=HA(),h!==null&&!oi?(qA(h,y,q),tu(h,y,q)):(yr&&M&&SA(y),y.flags|=1,es(h,y,S,q),y.child)}function UU(h,y,S,M,q,Z){return Lp(y),y.updateQueue=null,S=q5(y,M,S,q),H5(h),M=HA(),h!==null&&!oi?(qA(h,y,Z),tu(h,y,Z)):(yr&&M&&SA(y),y.flags|=1,es(h,y,S,Z),y.child)}function BU(h,y,S,M,q){if(Lp(y),y.stateNode===null){var Z=Fg,ke=S.contextType;typeof ke=="object"&&ke!==null&&(Z=Ji(ke)),Z=new S(M,Z),y.memoizedState=Z.state!==null&&Z.state!==void 0?Z.state:null,Z.updater=aj,y.stateNode=Z,Z._reactInternals=y,Z=y.stateNode,Z.props=M,Z.state=y.memoizedState,Z.refs={},DA(y),ke=S.contextType,Z.context=typeof ke=="object"&&ke!==null?Ji(ke):Fg,Z.state=y.memoizedState,ke=S.getDerivedStateFromProps,typeof ke=="function"&&(rj(y,S,ke,M),Z.state=y.memoizedState),typeof S.getDerivedStateFromProps=="function"||typeof Z.getSnapshotBeforeUpdate=="function"||typeof Z.UNSAFE_componentWillMount!="function"&&typeof Z.componentWillMount!="function"||(ke=Z.state,typeof Z.componentWillMount=="function"&&Z.componentWillMount(),typeof Z.UNSAFE_componentWillMount=="function"&&Z.UNSAFE_componentWillMount(),ke!==Z.state&&aj.enqueueReplaceState(Z,Z.state,null),By(y,M,Z,q),Uy(),Z.state=y.memoizedState),typeof Z.componentDidMount=="function"&&(y.flags|=4194308),M=!0}else if(h===null){Z=y.stateNode;var Ue=y.memoizedProps,nt=Hp(S,Ue);Z.props=nt;var Nt=Z.context,Lt=S.contextType;ke=Fg,typeof Lt=="object"&&Lt!==null&&(ke=Ji(Lt));var It=S.getDerivedStateFromProps;Lt=typeof It=="function"||typeof Z.getSnapshotBeforeUpdate=="function",Ue=y.pendingProps!==Ue,Lt||typeof Z.UNSAFE_componentWillReceiveProps!="function"&&typeof Z.componentWillReceiveProps!="function"||(Ue||Nt!==ke)&&PU(y,Z,M,ke),Dm=!1;var Ct=y.memoizedState;Z.state=Ct,By(y,M,Z,q),Uy(),Nt=y.memoizedState,Ue||Ct!==Nt||Dm?(typeof It=="function"&&(rj(y,S,It,M),Nt=y.memoizedState),(nt=Dm||CU(y,S,nt,M,Ct,Nt,ke))?(Lt||typeof Z.UNSAFE_componentWillMount!="function"&&typeof Z.componentWillMount!="function"||(typeof Z.componentWillMount=="function"&&Z.componentWillMount(),typeof Z.UNSAFE_componentWillMount=="function"&&Z.UNSAFE_componentWillMount()),typeof Z.componentDidMount=="function"&&(y.flags|=4194308)):(typeof Z.componentDidMount=="function"&&(y.flags|=4194308),y.memoizedProps=M,y.memoizedState=Nt),Z.props=M,Z.state=Nt,Z.context=ke,M=nt):(typeof Z.componentDidMount=="function"&&(y.flags|=4194308),M=!1)}else{Z=y.stateNode,FA(h,y),ke=y.memoizedProps,Lt=Hp(S,ke),Z.props=Lt,It=y.pendingProps,Ct=Z.context,Nt=S.contextType,nt=Fg,typeof Nt=="object"&&Nt!==null&&(nt=Ji(Nt)),Ue=S.getDerivedStateFromProps,(Nt=typeof Ue=="function"||typeof Z.getSnapshotBeforeUpdate=="function")||typeof Z.UNSAFE_componentWillReceiveProps!="function"&&typeof Z.componentWillReceiveProps!="function"||(ke!==It||Ct!==nt)&&PU(y,Z,M,nt),Dm=!1,Ct=y.memoizedState,Z.state=Ct,By(y,M,Z,q),Uy();var Dt=y.memoizedState;ke!==It||Ct!==Dt||Dm||h!==null&&h.dependencies!==null&&FS(h.dependencies)?(typeof Ue=="function"&&(rj(y,S,Ue,M),Dt=y.memoizedState),(Lt=Dm||CU(y,S,Lt,M,Ct,Dt,nt)||h!==null&&h.dependencies!==null&&FS(h.dependencies))?(Nt||typeof Z.UNSAFE_componentWillUpdate!="function"&&typeof Z.componentWillUpdate!="function"||(typeof Z.componentWillUpdate=="function"&&Z.componentWillUpdate(M,Dt,nt),typeof Z.UNSAFE_componentWillUpdate=="function"&&Z.UNSAFE_componentWillUpdate(M,Dt,nt)),typeof Z.componentDidUpdate=="function"&&(y.flags|=4),typeof Z.getSnapshotBeforeUpdate=="function"&&(y.flags|=1024)):(typeof Z.componentDidUpdate!="function"||ke===h.memoizedProps&&Ct===h.memoizedState||(y.flags|=4),typeof Z.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&Ct===h.memoizedState||(y.flags|=1024),y.memoizedProps=M,y.memoizedState=Dt),Z.props=M,Z.state=Dt,Z.context=nt,M=Lt):(typeof Z.componentDidUpdate!="function"||ke===h.memoizedProps&&Ct===h.memoizedState||(y.flags|=4),typeof Z.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&Ct===h.memoizedState||(y.flags|=1024),M=!1)}return Z=M,JS(h,y),M=(y.flags&128)!==0,Z||M?(Z=y.stateNode,S=M&&typeof S.getDerivedStateFromError!="function"?null:Z.render(),y.flags|=1,h!==null&&M?(y.child=Up(y,h.child,null,q),y.child=Up(y,null,S,q)):es(h,y,S,q),y.memoizedState=Z.state,h=y.child):h=tu(h,y,q),h}function HU(h,y,S,M){return Fp(),y.flags|=256,es(h,y,S,M),y.child}var lj={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function cj(h){return{baseLanes:h,cachePool:M5()}}function dj(h,y,S){return h=h!==null?h.childLanes&~S:0,y&&(h|=Vo),h}function qU(h,y,S){var M=y.pendingProps,q=!1,Z=(y.flags&128)!==0,ke;if((ke=Z)||(ke=h!==null&&h.memoizedState===null?!1:(ei.current&2)!==0),ke&&(q=!0,y.flags&=-129),ke=(y.flags&32)!==0,y.flags&=-33,h===null){if(yr){if(q?Lm(y):Om(),(h=pa)?(h=QB(h,Pl),h=h!==null&&h.data!=="&"?h:null,h!==null&&(y.memoizedState={dehydrated:h,treeContext:Am!==null?{id:Jc,overflow:ed}:null,retryLane:536870912,hydrationErrors:null},S=S5(h),S.return=y,y.child=S,Zi=y,pa=null)):h=null,h===null)throw Mm(y);return Gj(h)?y.lanes=32:y.lanes=536870912,null}var Ue=M.children;return M=M.fallback,q?(Om(),q=y.mode,Ue=e_({mode:"hidden",children:Ue},q),M=Dp(M,q,S,null),Ue.return=y,M.return=y,Ue.sibling=M,y.child=Ue,M=y.child,M.memoizedState=cj(S),M.childLanes=dj(h,ke,S),y.memoizedState=lj,Gy(null,M)):(Lm(y),uj(y,Ue))}var nt=h.memoizedState;if(nt!==null&&(Ue=nt.dehydrated,Ue!==null)){if(Z)y.flags&256?(Lm(y),y.flags&=-257,y=mj(h,y,S)):y.memoizedState!==null?(Om(),y.child=h.child,y.flags|=128,y=null):(Om(),Ue=M.fallback,q=y.mode,M=e_({mode:"visible",children:M.children},q),Ue=Dp(Ue,q,S,null),Ue.flags|=2,M.return=y,Ue.return=y,M.sibling=Ue,y.child=M,Up(y,h.child,null,S),M=y.child,M.memoizedState=cj(S),M.childLanes=dj(h,ke,S),y.memoizedState=lj,y=Gy(null,M));else if(Lm(y),Gj(Ue)){if(ke=Ue.nextSibling&&Ue.nextSibling.dataset,ke)var Nt=ke.dgst;ke=Nt,M=Error(r(419)),M.stack="",M.digest=ke,Fy({value:M,source:null,stack:null}),y=mj(h,y,S)}else if(oi||Ig(h,y,S,!1),ke=(S&h.childLanes)!==0,oi||ke){if(ke=Jr,ke!==null&&(M=en(ke,S),M!==0&&M!==nt.retryLane))throw nt.retryLane=M,Ep(h,M),yo(ke,h,M),sj;Vj(Ue)||c_(),y=mj(h,y,S)}else Vj(Ue)?(y.flags|=192,y.child=h.child,y=null):(h=nt.treeContext,pa=Al(Ue.nextSibling),Zi=y,yr=!0,jm=null,Pl=!1,h!==null&&N5(y,h),y=uj(y,M.children),y.flags|=4096);return y}return q?(Om(),Ue=M.fallback,q=y.mode,nt=h.child,Nt=nt.sibling,M=Xd(nt,{mode:"hidden",children:M.children}),M.subtreeFlags=nt.subtreeFlags&65011712,Nt!==null?Ue=Xd(Nt,Ue):(Ue=Dp(Ue,q,S,null),Ue.flags|=2),Ue.return=y,M.return=y,M.sibling=Ue,y.child=M,Gy(null,M),M=y.child,Ue=h.child.memoizedState,Ue===null?Ue=cj(S):(q=Ue.cachePool,q!==null?(nt=ii._currentValue,q=q.parent!==nt?{parent:nt,pool:nt}:q):q=M5(),Ue={baseLanes:Ue.baseLanes|S,cachePool:q}),M.memoizedState=Ue,M.childLanes=dj(h,ke,S),y.memoizedState=lj,Gy(h.child,M)):(Lm(y),S=h.child,h=S.sibling,S=Xd(S,{mode:"visible",children:M.children}),S.return=y,S.sibling=null,h!==null&&(ke=y.deletions,ke===null?(y.deletions=[h],y.flags|=16):ke.push(h)),y.child=S,y.memoizedState=null,S)}function uj(h,y){return y=e_({mode:"visible",children:y},h.mode),y.return=h,h.child=y}function e_(h,y){return h=Bo(22,h,null,y),h.lanes=0,h}function mj(h,y,S){return Up(y,h.child,null,S),h=uj(y,y.pendingProps.children),h.flags|=2,y.memoizedState=null,h}function $U(h,y,S){h.lanes|=y;var M=h.alternate;M!==null&&(M.lanes|=y),PA(h.return,y,S)}function hj(h,y,S,M,q,Z){var ke=h.memoizedState;ke===null?h.memoizedState={isBackwards:y,rendering:null,renderingStartTime:0,last:M,tail:S,tailMode:q,treeForkCount:Z}:(ke.isBackwards=y,ke.rendering=null,ke.renderingStartTime=0,ke.last=M,ke.tail=S,ke.tailMode=q,ke.treeForkCount=Z)}function VU(h,y,S){var M=y.pendingProps,q=M.revealOrder,Z=M.tail;M=M.children;var ke=ei.current,Ue=(ke&2)!==0;if(Ue?(ke=ke&1|2,y.flags|=128):ke&=1,ce(ei,ke),es(h,y,M,S),M=yr?Dy:0,!Ue&&h!==null&&(h.flags&128)!==0)e:for(h=y.child;h!==null;){if(h.tag===13)h.memoizedState!==null&&$U(h,S,y);else if(h.tag===19)$U(h,S,y);else if(h.child!==null){h.child.return=h,h=h.child;continue}if(h===y)break e;for(;h.sibling===null;){if(h.return===null||h.return===y)break e;h=h.return}h.sibling.return=h.return,h=h.sibling}switch(q){case"forwards":for(S=y.child,q=null;S!==null;)h=S.alternate,h!==null&&HS(h)===null&&(q=S),S=S.sibling;S=q,S===null?(q=y.child,y.child=null):(q=S.sibling,S.sibling=null),hj(y,!1,q,S,Z,M);break;case"backwards":case"unstable_legacy-backwards":for(S=null,q=y.child,y.child=null;q!==null;){if(h=q.alternate,h!==null&&HS(h)===null){y.child=q;break}h=q.sibling,q.sibling=S,S=q,q=h}hj(y,!0,S,null,Z,M);break;case"together":hj(y,!1,null,null,void 0,M);break;default:y.memoizedState=null}return y.child}function tu(h,y,S){if(h!==null&&(y.dependencies=h.dependencies),Um|=y.lanes,(S&y.childLanes)===0)if(h!==null){if(Ig(h,y,S,!1),(S&y.childLanes)===0)return null}else return null;if(h!==null&&y.child!==h.child)throw Error(r(153));if(y.child!==null){for(h=y.child,S=Xd(h,h.pendingProps),y.child=S,S.return=y;h.sibling!==null;)h=h.sibling,S=S.sibling=Xd(h,h.pendingProps),S.return=y;S.sibling=null}return y.child}function pj(h,y){return(h.lanes&y)!==0?!0:(h=h.dependencies,!!(h!==null&&FS(h)))}function Tce(h,y,S){switch(y.tag){case 3:E(y,y.stateNode.containerInfo),Em(y,ii,h.memoizedState.cache),Fp();break;case 27:case 5:O(y);break;case 4:E(y,y.stateNode.containerInfo);break;case 10:Em(y,y.type,y.memoizedProps.value);break;case 31:if(y.memoizedState!==null)return y.flags|=128,zA(y),null;break;case 13:var M=y.memoizedState;if(M!==null)return M.dehydrated!==null?(Lm(y),y.flags|=128,null):(S&y.child.childLanes)!==0?qU(h,y,S):(Lm(y),h=tu(h,y,S),h!==null?h.sibling:null);Lm(y);break;case 19:var q=(h.flags&128)!==0;if(M=(S&y.childLanes)!==0,M||(Ig(h,y,S,!1),M=(S&y.childLanes)!==0),q){if(M)return VU(h,y,S);y.flags|=128}if(q=y.memoizedState,q!==null&&(q.rendering=null,q.tail=null,q.lastEffect=null),ce(ei,ei.current),M)break;return null;case 22:return y.lanes=0,OU(h,y,S,y.pendingProps);case 24:Em(y,ii,h.memoizedState.cache)}return tu(h,y,S)}function GU(h,y,S){if(h!==null)if(h.memoizedProps!==y.pendingProps)oi=!0;else{if(!pj(h,S)&&(y.flags&128)===0)return oi=!1,Tce(h,y,S);oi=(h.flags&131072)!==0}else oi=!1,yr&&(y.flags&1048576)!==0&&k5(y,Dy,y.index);switch(y.lanes=0,y.tag){case 16:e:{var M=y.pendingProps;if(h=Ip(y.elementType),y.type=h,typeof h=="function")yA(h)?(M=Hp(h,M),y.tag=1,y=BU(null,y,h,M,S)):(y.tag=0,y=oj(null,y,h,M,S));else{if(h!=null){var q=h.$$typeof;if(q===P){y.tag=11,y=FU(null,y,h,M,S);break e}else if(q===T){y.tag=14,y=RU(null,y,h,M,S);break e}}throw y=L(h)||h,Error(r(306,y,""))}}return y;case 0:return oj(h,y,y.type,y.pendingProps,S);case 1:return M=y.type,q=Hp(M,y.pendingProps),BU(h,y,M,q,S);case 3:e:{if(E(y,y.stateNode.containerInfo),h===null)throw Error(r(387));M=y.pendingProps;var Z=y.memoizedState;q=Z.element,FA(h,y),By(y,M,null,S);var ke=y.memoizedState;if(M=ke.cache,Em(y,ii,M),M!==Z.cache&&TA(y,[ii],S,!0),Uy(),M=ke.element,Z.isDehydrated)if(Z={element:M,isDehydrated:!1,cache:ke.cache},y.updateQueue.baseState=Z,y.memoizedState=Z,y.flags&256){y=HU(h,y,M,S);break e}else if(M!==q){q=kl(Error(r(424)),y),Fy(q),y=HU(h,y,M,S);break e}else for(h=y.stateNode.containerInfo,h.nodeType===9?h=h.body:h=h.nodeName==="HTML"?h.ownerDocument.body:h,pa=Al(h.firstChild),Zi=y,yr=!0,jm=null,Pl=!0,S=O5(y,null,M,S),y.child=S;S;)S.flags=S.flags&-3|4096,S=S.sibling;else{if(Fp(),M===q){y=tu(h,y,S);break e}es(h,y,M,S)}y=y.child}return y;case 26:return JS(h,y),h===null?(S=r8(y.type,null,y.pendingProps,null))?y.memoizedState=S:yr||(S=y.type,h=y.pendingProps,M=g_($.current).createElement(S),M[Pt]=y,M[pt]=h,ts(M,S,h),Xe(M),y.stateNode=M):y.memoizedState=r8(y.type,h.memoizedProps,y.pendingProps,h.memoizedState),null;case 27:return O(y),h===null&&yr&&(M=y.stateNode=e8(y.type,y.pendingProps,$.current),Zi=y,Pl=!0,q=pa,Vm(y.type)?(Wj=q,pa=Al(M.firstChild)):pa=q),es(h,y,y.pendingProps.children,S),JS(h,y),h===null&&(y.flags|=4194304),y.child;case 5:return h===null&&yr&&((q=M=pa)&&(M=ade(M,y.type,y.pendingProps,Pl),M!==null?(y.stateNode=M,Zi=y,pa=Al(M.firstChild),Pl=!1,q=!0):q=!1),q||Mm(y)),O(y),q=y.type,Z=y.pendingProps,ke=h!==null?h.memoizedProps:null,M=Z.children,Hj(q,Z)?M=null:ke!==null&&Hj(q,ke)&&(y.flags|=32),y.memoizedState!==null&&(q=BA(h,y,yce,null,null,S),ov._currentValue=q),JS(h,y),es(h,y,M,S),y.child;case 6:return h===null&&yr&&((h=S=pa)&&(S=ide(S,y.pendingProps,Pl),S!==null?(y.stateNode=S,Zi=y,pa=null,h=!0):h=!1),h||Mm(y)),null;case 13:return qU(h,y,S);case 4:return E(y,y.stateNode.containerInfo),M=y.pendingProps,h===null?y.child=Up(y,null,M,S):es(h,y,M,S),y.child;case 11:return FU(h,y,y.type,y.pendingProps,S);case 7:return es(h,y,y.pendingProps,S),y.child;case 8:return es(h,y,y.pendingProps.children,S),y.child;case 12:return es(h,y,y.pendingProps.children,S),y.child;case 10:return M=y.pendingProps,Em(y,y.type,M.value),es(h,y,M.children,S),y.child;case 9:return q=y.type._context,M=y.pendingProps.children,Lp(y),q=Ji(q),M=M(q),y.flags|=1,es(h,y,M,S),y.child;case 14:return RU(h,y,y.type,y.pendingProps,S);case 15:return LU(h,y,y.type,y.pendingProps,S);case 19:return VU(h,y,S);case 31:return Pce(h,y,S);case 22:return OU(h,y,S,y.pendingProps);case 24:return Lp(y),M=Ji(ii),h===null?(q=MA(),q===null&&(q=Jr,Z=AA(),q.pooledCache=Z,Z.refCount++,Z!==null&&(q.pooledCacheLanes|=S),q=Z),y.memoizedState={parent:M,cache:q},DA(y),Em(y,ii,q)):((h.lanes&S)!==0&&(FA(h,y),By(y,null,null,S),Uy()),q=h.memoizedState,Z=y.memoizedState,q.parent!==M?(q={parent:M,cache:M},y.memoizedState=q,y.lanes===0&&(y.memoizedState=y.updateQueue.baseState=q),Em(y,ii,M)):(M=Z.cache,Em(y,ii,M),M!==q.cache&&TA(y,[ii],S,!0))),es(h,y,y.pendingProps.children,S),y.child;case 29:throw y.pendingProps}throw Error(r(156,y.tag))}function nu(h){h.flags|=4}function fj(h,y,S,M,q){if((y=(h.mode&32)!==0)&&(y=!1),y){if(h.flags|=16777216,(q&335544128)===q)if(h.stateNode.complete)h.flags|=8192;else if(yB())h.flags|=8192;else throw zp=IS,EA}else h.flags&=-16777217}function WU(h,y){if(y.type!=="stylesheet"||(y.state.loading&4)!==0)h.flags&=-16777217;else if(h.flags|=16777216,!l8(y))if(yB())h.flags|=8192;else throw zp=IS,EA}function t_(h,y){y!==null&&(h.flags|=4),h.flags&16384&&(y=h.tag!==22?Ze():536870912,h.lanes|=y,Yg|=y)}function Wy(h,y){if(!yr)switch(h.tailMode){case"hidden":y=h.tail;for(var S=null;y!==null;)y.alternate!==null&&(S=y),y=y.sibling;S===null?h.tail=null:S.sibling=null;break;case"collapsed":S=h.tail;for(var M=null;S!==null;)S.alternate!==null&&(M=S),S=S.sibling;M===null?y||h.tail===null?h.tail=null:h.tail.sibling=null:M.sibling=null}}function fa(h){var y=h.alternate!==null&&h.alternate.child===h.child,S=0,M=0;if(y)for(var q=h.child;q!==null;)S|=q.lanes|q.childLanes,M|=q.subtreeFlags&65011712,M|=q.flags&65011712,q.return=h,q=q.sibling;else for(q=h.child;q!==null;)S|=q.lanes|q.childLanes,M|=q.subtreeFlags,M|=q.flags,q.return=h,q=q.sibling;return h.subtreeFlags|=M,h.childLanes=S,y}function Ace(h,y,S){var M=y.pendingProps;switch(_A(y),y.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return fa(y),null;case 1:return fa(y),null;case 3:return S=y.stateNode,M=null,h!==null&&(M=h.memoizedState.cache),y.memoizedState.cache!==M&&(y.flags|=2048),Zd(ii),j(),S.pendingContext&&(S.context=S.pendingContext,S.pendingContext=null),(h===null||h.child===null)&&(Og(y)?nu(y):h===null||h.memoizedState.isDehydrated&&(y.flags&256)===0||(y.flags|=1024,NA())),fa(y),null;case 26:var q=y.type,Z=y.memoizedState;return h===null?(nu(y),Z!==null?(fa(y),WU(y,Z)):(fa(y),fj(y,q,null,M,S))):Z?Z!==h.memoizedState?(nu(y),fa(y),WU(y,Z)):(fa(y),y.flags&=-16777217):(h=h.memoizedProps,h!==M&&nu(y),fa(y),fj(y,q,h,M,S)),null;case 27:if(K(y),S=$.current,q=y.type,h!==null&&y.stateNode!=null)h.memoizedProps!==M&&nu(y);else{if(!M){if(y.stateNode===null)throw Error(r(166));return fa(y),null}h=xe.current,Og(y)?C5(y):(h=e8(q,M,S),y.stateNode=h,nu(y))}return fa(y),null;case 5:if(K(y),q=y.type,h!==null&&y.stateNode!=null)h.memoizedProps!==M&&nu(y);else{if(!M){if(y.stateNode===null)throw Error(r(166));return fa(y),null}if(Z=xe.current,Og(y))C5(y);else{var ke=g_($.current);switch(Z){case 1:Z=ke.createElementNS("http://www.w3.org/2000/svg",q);break;case 2:Z=ke.createElementNS("http://www.w3.org/1998/Math/MathML",q);break;default:switch(q){case"svg":Z=ke.createElementNS("http://www.w3.org/2000/svg",q);break;case"math":Z=ke.createElementNS("http://www.w3.org/1998/Math/MathML",q);break;case"script":Z=ke.createElement("div"),Z.innerHTML="<script><\/script>",Z=Z.removeChild(Z.firstChild);break;case"select":Z=typeof M.is=="string"?ke.createElement("select",{is:M.is}):ke.createElement("select"),M.multiple?Z.multiple=!0:M.size&&(Z.size=M.size);break;default:Z=typeof M.is=="string"?ke.createElement(q,{is:M.is}):ke.createElement(q)}}Z[Pt]=y,Z[pt]=M;e:for(ke=y.child;ke!==null;){if(ke.tag===5||ke.tag===6)Z.appendChild(ke.stateNode);else if(ke.tag!==4&&ke.tag!==27&&ke.child!==null){ke.child.return=ke,ke=ke.child;continue}if(ke===y)break e;for(;ke.sibling===null;){if(ke.return===null||ke.return===y)break e;ke=ke.return}ke.sibling.return=ke.return,ke=ke.sibling}y.stateNode=Z;e:switch(ts(Z,q,M),q){case"button":case"input":case"select":case"textarea":M=!!M.autoFocus;break e;case"img":M=!0;break e;default:M=!1}M&&nu(y)}}return fa(y),fj(y,y.type,h===null?null:h.memoizedProps,y.pendingProps,S),null;case 6:if(h&&y.stateNode!=null)h.memoizedProps!==M&&nu(y);else{if(typeof M!="string"&&y.stateNode===null)throw Error(r(166));if(h=$.current,Og(y)){if(h=y.stateNode,S=y.memoizedProps,M=null,q=Zi,q!==null)switch(q.tag){case 27:case 5:M=q.memoizedProps}h[Pt]=y,h=!!(h.nodeValue===S||M!==null&&M.suppressHydrationWarning===!0||qB(h.nodeValue,S)),h||Mm(y,!0)}else h=g_(h).createTextNode(M),h[Pt]=y,y.stateNode=h}return fa(y),null;case 31:if(S=y.memoizedState,h===null||h.memoizedState!==null){if(M=Og(y),S!==null){if(h===null){if(!M)throw Error(r(318));if(h=y.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(557));h[Pt]=y}else Fp(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;fa(y),h=!1}else S=NA(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=S),h=!0;if(!h)return y.flags&256?(qo(y),y):(qo(y),null);if((y.flags&128)!==0)throw Error(r(558))}return fa(y),null;case 13:if(M=y.memoizedState,h===null||h.memoizedState!==null&&h.memoizedState.dehydrated!==null){if(q=Og(y),M!==null&&M.dehydrated!==null){if(h===null){if(!q)throw Error(r(318));if(q=y.memoizedState,q=q!==null?q.dehydrated:null,!q)throw Error(r(317));q[Pt]=y}else Fp(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;fa(y),q=!1}else q=NA(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=q),q=!0;if(!q)return y.flags&256?(qo(y),y):(qo(y),null)}return qo(y),(y.flags&128)!==0?(y.lanes=S,y):(S=M!==null,h=h!==null&&h.memoizedState!==null,S&&(M=y.child,q=null,M.alternate!==null&&M.alternate.memoizedState!==null&&M.alternate.memoizedState.cachePool!==null&&(q=M.alternate.memoizedState.cachePool.pool),Z=null,M.memoizedState!==null&&M.memoizedState.cachePool!==null&&(Z=M.memoizedState.cachePool.pool),Z!==q&&(M.flags|=2048)),S!==h&&S&&(y.child.flags|=8192),t_(y,y.updateQueue),fa(y),null);case 4:return j(),h===null&&Oj(y.stateNode.containerInfo),fa(y),null;case 10:return Zd(y.type),fa(y),null;case 19:if(re(ei),M=y.memoizedState,M===null)return fa(y),null;if(q=(y.flags&128)!==0,Z=M.rendering,Z===null)if(q)Wy(M,!1);else{if(Oa!==0||h!==null&&(h.flags&128)!==0)for(h=y.child;h!==null;){if(Z=HS(h),Z!==null){for(y.flags|=128,Wy(M,!1),h=Z.updateQueue,y.updateQueue=h,t_(y,h),y.subtreeFlags=0,h=S,S=y.child;S!==null;)w5(S,h),S=S.sibling;return ce(ei,ei.current&1|2),yr&&Yd(y,M.treeForkCount),y.child}h=h.sibling}M.tail!==null&&R()>s_&&(y.flags|=128,q=!0,Wy(M,!1),y.lanes=4194304)}else{if(!q)if(h=HS(Z),h!==null){if(y.flags|=128,q=!0,h=h.updateQueue,y.updateQueue=h,t_(y,h),Wy(M,!0),M.tail===null&&M.tailMode==="hidden"&&!Z.alternate&&!yr)return fa(y),null}else 2*R()-M.renderingStartTime>s_&&S!==536870912&&(y.flags|=128,q=!0,Wy(M,!1),y.lanes=4194304);M.isBackwards?(Z.sibling=y.child,y.child=Z):(h=M.last,h!==null?h.sibling=Z:y.child=Z,M.last=Z)}return M.tail!==null?(h=M.tail,M.rendering=h,M.tail=h.sibling,M.renderingStartTime=R(),h.sibling=null,S=ei.current,ce(ei,q?S&1|2:S&1),yr&&Yd(y,M.treeForkCount),h):(fa(y),null);case 22:case 23:return qo(y),IA(),M=y.memoizedState!==null,h!==null?h.memoizedState!==null!==M&&(y.flags|=8192):M&&(y.flags|=8192),M?(S&536870912)!==0&&(y.flags&128)===0&&(fa(y),y.subtreeFlags&6&&(y.flags|=8192)):fa(y),S=y.updateQueue,S!==null&&t_(y,S.retryQueue),S=null,h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(S=h.memoizedState.cachePool.pool),M=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(M=y.memoizedState.cachePool.pool),M!==S&&(y.flags|=2048),h!==null&&re(Op),null;case 24:return S=null,h!==null&&(S=h.memoizedState.cache),y.memoizedState.cache!==S&&(y.flags|=2048),Zd(ii),fa(y),null;case 25:return null;case 30:return null}throw Error(r(156,y.tag))}function jce(h,y){switch(_A(y),y.tag){case 1:return h=y.flags,h&65536?(y.flags=h&-65537|128,y):null;case 3:return Zd(ii),j(),h=y.flags,(h&65536)!==0&&(h&128)===0?(y.flags=h&-65537|128,y):null;case 26:case 27:case 5:return K(y),null;case 31:if(y.memoizedState!==null){if(qo(y),y.alternate===null)throw Error(r(340));Fp()}return h=y.flags,h&65536?(y.flags=h&-65537|128,y):null;case 13:if(qo(y),h=y.memoizedState,h!==null&&h.dehydrated!==null){if(y.alternate===null)throw Error(r(340));Fp()}return h=y.flags,h&65536?(y.flags=h&-65537|128,y):null;case 19:return re(ei),null;case 4:return j(),null;case 10:return Zd(y.type),null;case 22:case 23:return qo(y),IA(),h!==null&&re(Op),h=y.flags,h&65536?(y.flags=h&-65537|128,y):null;case 24:return Zd(ii),null;case 25:return null;default:return null}}function KU(h,y){switch(_A(y),y.tag){case 3:Zd(ii),j();break;case 26:case 27:case 5:K(y);break;case 4:j();break;case 31:y.memoizedState!==null&&qo(y);break;case 13:qo(y);break;case 19:re(ei);break;case 10:Zd(y.type);break;case 22:case 23:qo(y),IA(),h!==null&&re(Op);break;case 24:Zd(ii)}}function Ky(h,y){try{var S=y.updateQueue,M=S!==null?S.lastEffect:null;if(M!==null){var q=M.next;S=q;do{if((S.tag&h)===h){M=void 0;var Z=S.create,ke=S.inst;M=Z(),ke.destroy=M}S=S.next}while(S!==q)}}catch(Ue){Or(y,y.return,Ue)}}function Im(h,y,S){try{var M=y.updateQueue,q=M!==null?M.lastEffect:null;if(q!==null){var Z=q.next;M=Z;do{if((M.tag&h)===h){var ke=M.inst,Ue=ke.destroy;if(Ue!==void 0){ke.destroy=void 0,q=y;var nt=S,Nt=Ue;try{Nt()}catch(Lt){Or(q,nt,Lt)}}}M=M.next}while(M!==Z)}}catch(Lt){Or(y,y.return,Lt)}}function XU(h){var y=h.updateQueue;if(y!==null){var S=h.stateNode;try{z5(y,S)}catch(M){Or(h,h.return,M)}}}function YU(h,y,S){S.props=Hp(h.type,h.memoizedProps),S.state=h.memoizedState;try{S.componentWillUnmount()}catch(M){Or(h,y,M)}}function Xy(h,y){try{var S=h.ref;if(S!==null){switch(h.tag){case 26:case 27:case 5:var M=h.stateNode;break;case 30:M=h.stateNode;break;default:M=h.stateNode}typeof S=="function"?h.refCleanup=S(M):S.current=M}}catch(q){Or(h,y,q)}}function td(h,y){var S=h.ref,M=h.refCleanup;if(S!==null)if(typeof M=="function")try{M()}catch(q){Or(h,y,q)}finally{h.refCleanup=null,h=h.alternate,h!=null&&(h.refCleanup=null)}else if(typeof S=="function")try{S(null)}catch(q){Or(h,y,q)}else S.current=null}function QU(h){var y=h.type,S=h.memoizedProps,M=h.stateNode;try{e:switch(y){case"button":case"input":case"select":case"textarea":S.autoFocus&&M.focus();break e;case"img":S.src?M.src=S.src:S.srcSet&&(M.srcset=S.srcSet)}}catch(q){Or(h,h.return,q)}}function gj(h,y,S){try{var M=h.stateNode;Zce(M,h.type,S,y),M[pt]=y}catch(q){Or(h,h.return,q)}}function ZU(h){return h.tag===5||h.tag===3||h.tag===26||h.tag===27&&Vm(h.type)||h.tag===4}function bj(h){e:for(;;){for(;h.sibling===null;){if(h.return===null||ZU(h.return))return null;h=h.return}for(h.sibling.return=h.return,h=h.sibling;h.tag!==5&&h.tag!==6&&h.tag!==18;){if(h.tag===27&&Vm(h.type)||h.flags&2||h.child===null||h.tag===4)continue e;h.child.return=h,h=h.child}if(!(h.flags&2))return h.stateNode}}function xj(h,y,S){var M=h.tag;if(M===5||M===6)h=h.stateNode,y?(S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S).insertBefore(h,y):(y=S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S,y.appendChild(h),S=S._reactRootContainer,S!=null||y.onclick!==null||(y.onclick=qt));else if(M!==4&&(M===27&&Vm(h.type)&&(S=h.stateNode,y=null),h=h.child,h!==null))for(xj(h,y,S),h=h.sibling;h!==null;)xj(h,y,S),h=h.sibling}function n_(h,y,S){var M=h.tag;if(M===5||M===6)h=h.stateNode,y?S.insertBefore(h,y):S.appendChild(h);else if(M!==4&&(M===27&&Vm(h.type)&&(S=h.stateNode),h=h.child,h!==null))for(n_(h,y,S),h=h.sibling;h!==null;)n_(h,y,S),h=h.sibling}function JU(h){var y=h.stateNode,S=h.memoizedProps;try{for(var M=h.type,q=y.attributes;q.length;)y.removeAttributeNode(q[0]);ts(y,M,S),y[Pt]=h,y[pt]=S}catch(Z){Or(h,h.return,Z)}}var ru=!1,li=!1,yj=!1,eB=typeof WeakSet=="function"?WeakSet:Set,Di=null;function Mce(h,y){if(h=h.containerInfo,Uj=__,h=m5(h),mA(h)){if("selectionStart"in h)var S={start:h.selectionStart,end:h.selectionEnd};else e:{S=(S=h.ownerDocument)&&S.defaultView||window;var M=S.getSelection&&S.getSelection();if(M&&M.rangeCount!==0){S=M.anchorNode;var q=M.anchorOffset,Z=M.focusNode;M=M.focusOffset;try{S.nodeType,Z.nodeType}catch{S=null;break e}var ke=0,Ue=-1,nt=-1,Nt=0,Lt=0,It=h,Ct=null;t:for(;;){for(var Dt;It!==S||q!==0&&It.nodeType!==3||(Ue=ke+q),It!==Z||M!==0&&It.nodeType!==3||(nt=ke+M),It.nodeType===3&&(ke+=It.nodeValue.length),(Dt=It.firstChild)!==null;)Ct=It,It=Dt;for(;;){if(It===h)break t;if(Ct===S&&++Nt===q&&(Ue=ke),Ct===Z&&++Lt===M&&(nt=ke),(Dt=It.nextSibling)!==null)break;It=Ct,Ct=It.parentNode}It=Dt}S=Ue===-1||nt===-1?null:{start:Ue,end:nt}}else S=null}S=S||{start:0,end:0}}else S=null;for(Bj={focusedElem:h,selectionRange:S},__=!1,Di=y;Di!==null;)if(y=Di,h=y.child,(y.subtreeFlags&1028)!==0&&h!==null)h.return=y,Di=h;else for(;Di!==null;){switch(y=Di,Z=y.alternate,h=y.flags,y.tag){case 0:if((h&4)!==0&&(h=y.updateQueue,h=h!==null?h.events:null,h!==null))for(S=0;S<h.length;S++)q=h[S],q.ref.impl=q.nextImpl;break;case 11:case 15:break;case 1:if((h&1024)!==0&&Z!==null){h=void 0,S=y,q=Z.memoizedProps,Z=Z.memoizedState,M=S.stateNode;try{var gn=Hp(S.type,q);h=M.getSnapshotBeforeUpdate(gn,Z),M.__reactInternalSnapshotBeforeUpdate=h}catch(Fn){Or(S,S.return,Fn)}}break;case 3:if((h&1024)!==0){if(h=y.stateNode.containerInfo,S=h.nodeType,S===9)$j(h);else if(S===1)switch(h.nodeName){case"HEAD":case"HTML":case"BODY":$j(h);break;default:h.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((h&1024)!==0)throw Error(r(163))}if(h=y.sibling,h!==null){h.return=y.return,Di=h;break}Di=y.return}}function tB(h,y,S){var M=S.flags;switch(S.tag){case 0:case 11:case 15:iu(h,S),M&4&&Ky(5,S);break;case 1:if(iu(h,S),M&4)if(h=S.stateNode,y===null)try{h.componentDidMount()}catch(ke){Or(S,S.return,ke)}else{var q=Hp(S.type,y.memoizedProps);y=y.memoizedState;try{h.componentDidUpdate(q,y,h.__reactInternalSnapshotBeforeUpdate)}catch(ke){Or(S,S.return,ke)}}M&64&&XU(S),M&512&&Xy(S,S.return);break;case 3:if(iu(h,S),M&64&&(h=S.updateQueue,h!==null)){if(y=null,S.child!==null)switch(S.child.tag){case 27:case 5:y=S.child.stateNode;break;case 1:y=S.child.stateNode}try{z5(h,y)}catch(ke){Or(S,S.return,ke)}}break;case 27:y===null&&M&4&&JU(S);case 26:case 5:iu(h,S),y===null&&M&4&&QU(S),M&512&&Xy(S,S.return);break;case 12:iu(h,S);break;case 31:iu(h,S),M&4&&aB(h,S);break;case 13:iu(h,S),M&4&&iB(h,S),M&64&&(h=S.memoizedState,h!==null&&(h=h.dehydrated,h!==null&&(S=Uce.bind(null,S),sde(h,S))));break;case 22:if(M=S.memoizedState!==null||ru,!M){y=y!==null&&y.memoizedState!==null||li,q=ru;var Z=li;ru=M,(li=y)&&!Z?su(h,S,(S.subtreeFlags&8772)!==0):iu(h,S),ru=q,li=Z}break;case 30:break;default:iu(h,S)}}function nB(h){var y=h.alternate;y!==null&&(h.alternate=null,nB(y)),h.child=null,h.deletions=null,h.sibling=null,h.tag===5&&(y=h.stateNode,y!==null&&Le(y)),h.stateNode=null,h.return=null,h.dependencies=null,h.memoizedProps=null,h.memoizedState=null,h.pendingProps=null,h.stateNode=null,h.updateQueue=null}var va=null,fo=!1;function au(h,y,S){for(S=S.child;S!==null;)rB(h,y,S),S=S.sibling}function rB(h,y,S){if(Te&&typeof Te.onCommitFiberUnmount=="function")try{Te.onCommitFiberUnmount(Ee,S)}catch{}switch(S.tag){case 26:li||td(S,y),au(h,y,S),S.memoizedState?S.memoizedState.count--:S.stateNode&&(S=S.stateNode,S.parentNode.removeChild(S));break;case 27:li||td(S,y);var M=va,q=fo;Vm(S.type)&&(va=S.stateNode,fo=!1),au(h,y,S),av(S.stateNode),va=M,fo=q;break;case 5:li||td(S,y);case 6:if(M=va,q=fo,va=null,au(h,y,S),va=M,fo=q,va!==null)if(fo)try{(va.nodeType===9?va.body:va.nodeName==="HTML"?va.ownerDocument.body:va).removeChild(S.stateNode)}catch(Z){Or(S,y,Z)}else try{va.removeChild(S.stateNode)}catch(Z){Or(S,y,Z)}break;case 18:va!==null&&(fo?(h=va,XB(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,S.stateNode),ab(h)):XB(va,S.stateNode));break;case 4:M=va,q=fo,va=S.stateNode.containerInfo,fo=!0,au(h,y,S),va=M,fo=q;break;case 0:case 11:case 14:case 15:Im(2,S,y),li||Im(4,S,y),au(h,y,S);break;case 1:li||(td(S,y),M=S.stateNode,typeof M.componentWillUnmount=="function"&&YU(S,y,M)),au(h,y,S);break;case 21:au(h,y,S);break;case 22:li=(M=li)||S.memoizedState!==null,au(h,y,S),li=M;break;default:au(h,y,S)}}function aB(h,y){if(y.memoizedState===null&&(h=y.alternate,h!==null&&(h=h.memoizedState,h!==null))){h=h.dehydrated;try{ab(h)}catch(S){Or(y,y.return,S)}}}function iB(h,y){if(y.memoizedState===null&&(h=y.alternate,h!==null&&(h=h.memoizedState,h!==null&&(h=h.dehydrated,h!==null))))try{ab(h)}catch(S){Or(y,y.return,S)}}function Ece(h){switch(h.tag){case 31:case 13:case 19:var y=h.stateNode;return y===null&&(y=h.stateNode=new eB),y;case 22:return h=h.stateNode,y=h._retryCache,y===null&&(y=h._retryCache=new eB),y;default:throw Error(r(435,h.tag))}}function r_(h,y){var S=Ece(h);y.forEach(function(M){if(!S.has(M)){S.add(M);var q=Bce.bind(null,h,M);M.then(q,q)}})}function go(h,y){var S=y.deletions;if(S!==null)for(var M=0;M<S.length;M++){var q=S[M],Z=h,ke=y,Ue=ke;e:for(;Ue!==null;){switch(Ue.tag){case 27:if(Vm(Ue.type)){va=Ue.stateNode,fo=!1;break e}break;case 5:va=Ue.stateNode,fo=!1;break e;case 3:case 4:va=Ue.stateNode.containerInfo,fo=!0;break e}Ue=Ue.return}if(va===null)throw Error(r(160));rB(Z,ke,q),va=null,fo=!1,Z=q.alternate,Z!==null&&(Z.return=null),q.return=null}if(y.subtreeFlags&13886)for(y=y.child;y!==null;)sB(y,h),y=y.sibling}var vc=null;function sB(h,y){var S=h.alternate,M=h.flags;switch(h.tag){case 0:case 11:case 14:case 15:go(y,h),bo(h),M&4&&(Im(3,h,h.return),Ky(3,h),Im(5,h,h.return));break;case 1:go(y,h),bo(h),M&512&&(li||S===null||td(S,S.return)),M&64&&ru&&(h=h.updateQueue,h!==null&&(M=h.callbacks,M!==null&&(S=h.shared.hiddenCallbacks,h.shared.hiddenCallbacks=S===null?M:S.concat(M))));break;case 26:var q=vc;if(go(y,h),bo(h),M&512&&(li||S===null||td(S,S.return)),M&4){var Z=S!==null?S.memoizedState:null;if(M=h.memoizedState,S===null)if(M===null)if(h.stateNode===null){e:{M=h.type,S=h.memoizedProps,q=q.ownerDocument||q;t:switch(M){case"title":Z=q.getElementsByTagName("title")[0],(!Z||Z[rt]||Z[Pt]||Z.namespaceURI==="http://www.w3.org/2000/svg"||Z.hasAttribute("itemprop"))&&(Z=q.createElement(M),q.head.insertBefore(Z,q.querySelector("head > title"))),ts(Z,M,S),Z[Pt]=h,Xe(Z),M=Z;break e;case"link":var ke=s8("link","href",q).get(M+(S.href||""));if(ke){for(var Ue=0;Ue<ke.length;Ue++)if(Z=ke[Ue],Z.getAttribute("href")===(S.href==null||S.href===""?null:S.href)&&Z.getAttribute("rel")===(S.rel==null?null:S.rel)&&Z.getAttribute("title")===(S.title==null?null:S.title)&&Z.getAttribute("crossorigin")===(S.crossOrigin==null?null:S.crossOrigin)){ke.splice(Ue,1);break t}}Z=q.createElement(M),ts(Z,M,S),q.head.appendChild(Z);break;case"meta":if(ke=s8("meta","content",q).get(M+(S.content||""))){for(Ue=0;Ue<ke.length;Ue++)if(Z=ke[Ue],Z.getAttribute("content")===(S.content==null?null:""+S.content)&&Z.getAttribute("name")===(S.name==null?null:S.name)&&Z.getAttribute("property")===(S.property==null?null:S.property)&&Z.getAttribute("http-equiv")===(S.httpEquiv==null?null:S.httpEquiv)&&Z.getAttribute("charset")===(S.charSet==null?null:S.charSet)){ke.splice(Ue,1);break t}}Z=q.createElement(M),ts(Z,M,S),q.head.appendChild(Z);break;default:throw Error(r(468,M))}Z[Pt]=h,Xe(Z),M=Z}h.stateNode=M}else o8(q,h.type,h.stateNode);else h.stateNode=i8(q,M,h.memoizedProps);else Z!==M?(Z===null?S.stateNode!==null&&(S=S.stateNode,S.parentNode.removeChild(S)):Z.count--,M===null?o8(q,h.type,h.stateNode):i8(q,M,h.memoizedProps)):M===null&&h.stateNode!==null&&gj(h,h.memoizedProps,S.memoizedProps)}break;case 27:go(y,h),bo(h),M&512&&(li||S===null||td(S,S.return)),S!==null&&M&4&&gj(h,h.memoizedProps,S.memoizedProps);break;case 5:if(go(y,h),bo(h),M&512&&(li||S===null||td(S,S.return)),h.flags&32){q=h.stateNode;try{Ta(q,"")}catch(gn){Or(h,h.return,gn)}}M&4&&h.stateNode!=null&&(q=h.memoizedProps,gj(h,q,S!==null?S.memoizedProps:q)),M&1024&&(yj=!0);break;case 6:if(go(y,h),bo(h),M&4){if(h.stateNode===null)throw Error(r(162));M=h.memoizedProps,S=h.stateNode;try{S.nodeValue=M}catch(gn){Or(h,h.return,gn)}}break;case 3:if(y_=null,q=vc,vc=b_(y.containerInfo),go(y,h),vc=q,bo(h),M&4&&S!==null&&S.memoizedState.isDehydrated)try{ab(y.containerInfo)}catch(gn){Or(h,h.return,gn)}yj&&(yj=!1,oB(h));break;case 4:M=vc,vc=b_(h.stateNode.containerInfo),go(y,h),bo(h),vc=M;break;case 12:go(y,h),bo(h);break;case 31:go(y,h),bo(h),M&4&&(M=h.updateQueue,M!==null&&(h.updateQueue=null,r_(h,M)));break;case 13:go(y,h),bo(h),h.child.flags&8192&&h.memoizedState!==null!=(S!==null&&S.memoizedState!==null)&&(i_=R()),M&4&&(M=h.updateQueue,M!==null&&(h.updateQueue=null,r_(h,M)));break;case 22:q=h.memoizedState!==null;var nt=S!==null&&S.memoizedState!==null,Nt=ru,Lt=li;if(ru=Nt||q,li=Lt||nt,go(y,h),li=Lt,ru=Nt,bo(h),M&8192)e:for(y=h.stateNode,y._visibility=q?y._visibility&-2:y._visibility|1,q&&(S===null||nt||ru||li||qp(h)),S=null,y=h;;){if(y.tag===5||y.tag===26){if(S===null){nt=S=y;try{if(Z=nt.stateNode,q)ke=Z.style,typeof ke.setProperty=="function"?ke.setProperty("display","none","important"):ke.display="none";else{Ue=nt.stateNode;var It=nt.memoizedProps.style,Ct=It!=null&&It.hasOwnProperty("display")?It.display:null;Ue.style.display=Ct==null||typeof Ct=="boolean"?"":(""+Ct).trim()}}catch(gn){Or(nt,nt.return,gn)}}}else if(y.tag===6){if(S===null){nt=y;try{nt.stateNode.nodeValue=q?"":nt.memoizedProps}catch(gn){Or(nt,nt.return,gn)}}}else if(y.tag===18){if(S===null){nt=y;try{var Dt=nt.stateNode;q?YB(Dt,!0):YB(nt.stateNode,!1)}catch(gn){Or(nt,nt.return,gn)}}}else if((y.tag!==22&&y.tag!==23||y.memoizedState===null||y===h)&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===h)break e;for(;y.sibling===null;){if(y.return===null||y.return===h)break e;S===y&&(S=null),y=y.return}S===y&&(S=null),y.sibling.return=y.return,y=y.sibling}M&4&&(M=h.updateQueue,M!==null&&(S=M.retryQueue,S!==null&&(M.retryQueue=null,r_(h,S))));break;case 19:go(y,h),bo(h),M&4&&(M=h.updateQueue,M!==null&&(h.updateQueue=null,r_(h,M)));break;case 30:break;case 21:break;default:go(y,h),bo(h)}}function bo(h){var y=h.flags;if(y&2){try{for(var S,M=h.return;M!==null;){if(ZU(M)){S=M;break}M=M.return}if(S==null)throw Error(r(160));switch(S.tag){case 27:var q=S.stateNode,Z=bj(h);n_(h,Z,q);break;case 5:var ke=S.stateNode;S.flags&32&&(Ta(ke,""),S.flags&=-33);var Ue=bj(h);n_(h,Ue,ke);break;case 3:case 4:var nt=S.stateNode.containerInfo,Nt=bj(h);xj(h,Nt,nt);break;default:throw Error(r(161))}}catch(Lt){Or(h,h.return,Lt)}h.flags&=-3}y&4096&&(h.flags&=-4097)}function oB(h){if(h.subtreeFlags&1024)for(h=h.child;h!==null;){var y=h;oB(y),y.tag===5&&y.flags&1024&&y.stateNode.reset(),h=h.sibling}}function iu(h,y){if(y.subtreeFlags&8772)for(y=y.child;y!==null;)tB(h,y.alternate,y),y=y.sibling}function qp(h){for(h=h.child;h!==null;){var y=h;switch(y.tag){case 0:case 11:case 14:case 15:Im(4,y,y.return),qp(y);break;case 1:td(y,y.return);var S=y.stateNode;typeof S.componentWillUnmount=="function"&&YU(y,y.return,S),qp(y);break;case 27:av(y.stateNode);case 26:case 5:td(y,y.return),qp(y);break;case 22:y.memoizedState===null&&qp(y);break;case 30:qp(y);break;default:qp(y)}h=h.sibling}}function su(h,y,S){for(S=S&&(y.subtreeFlags&8772)!==0,y=y.child;y!==null;){var M=y.alternate,q=h,Z=y,ke=Z.flags;switch(Z.tag){case 0:case 11:case 15:su(q,Z,S),Ky(4,Z);break;case 1:if(su(q,Z,S),M=Z,q=M.stateNode,typeof q.componentDidMount=="function")try{q.componentDidMount()}catch(Nt){Or(M,M.return,Nt)}if(M=Z,q=M.updateQueue,q!==null){var Ue=M.stateNode;try{var nt=q.shared.hiddenCallbacks;if(nt!==null)for(q.shared.hiddenCallbacks=null,q=0;q<nt.length;q++)I5(nt[q],Ue)}catch(Nt){Or(M,M.return,Nt)}}S&&ke&64&&XU(Z),Xy(Z,Z.return);break;case 27:JU(Z);case 26:case 5:su(q,Z,S),S&&M===null&&ke&4&&QU(Z),Xy(Z,Z.return);break;case 12:su(q,Z,S);break;case 31:su(q,Z,S),S&&ke&4&&aB(q,Z);break;case 13:su(q,Z,S),S&&ke&4&&iB(q,Z);break;case 22:Z.memoizedState===null&&su(q,Z,S),Xy(Z,Z.return);break;case 30:break;default:su(q,Z,S)}y=y.sibling}}function vj(h,y){var S=null;h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(S=h.memoizedState.cachePool.pool),h=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(h=y.memoizedState.cachePool.pool),h!==S&&(h!=null&&h.refCount++,S!=null&&Ry(S))}function wj(h,y){h=null,y.alternate!==null&&(h=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==h&&(y.refCount++,h!=null&&Ry(h))}function wc(h,y,S,M){if(y.subtreeFlags&10256)for(y=y.child;y!==null;)lB(h,y,S,M),y=y.sibling}function lB(h,y,S,M){var q=y.flags;switch(y.tag){case 0:case 11:case 15:wc(h,y,S,M),q&2048&&Ky(9,y);break;case 1:wc(h,y,S,M);break;case 3:wc(h,y,S,M),q&2048&&(h=null,y.alternate!==null&&(h=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==h&&(y.refCount++,h!=null&&Ry(h)));break;case 12:if(q&2048){wc(h,y,S,M),h=y.stateNode;try{var Z=y.memoizedProps,ke=Z.id,Ue=Z.onPostCommit;typeof Ue=="function"&&Ue(ke,y.alternate===null?"mount":"update",h.passiveEffectDuration,-0)}catch(nt){Or(y,y.return,nt)}}else wc(h,y,S,M);break;case 31:wc(h,y,S,M);break;case 13:wc(h,y,S,M);break;case 23:break;case 22:Z=y.stateNode,ke=y.alternate,y.memoizedState!==null?Z._visibility&2?wc(h,y,S,M):Yy(h,y):Z._visibility&2?wc(h,y,S,M):(Z._visibility|=2,Wg(h,y,S,M,(y.subtreeFlags&10256)!==0||!1)),q&2048&&vj(ke,y);break;case 24:wc(h,y,S,M),q&2048&&wj(y.alternate,y);break;default:wc(h,y,S,M)}}function Wg(h,y,S,M,q){for(q=q&&((y.subtreeFlags&10256)!==0||!1),y=y.child;y!==null;){var Z=h,ke=y,Ue=S,nt=M,Nt=ke.flags;switch(ke.tag){case 0:case 11:case 15:Wg(Z,ke,Ue,nt,q),Ky(8,ke);break;case 23:break;case 22:var Lt=ke.stateNode;ke.memoizedState!==null?Lt._visibility&2?Wg(Z,ke,Ue,nt,q):Yy(Z,ke):(Lt._visibility|=2,Wg(Z,ke,Ue,nt,q)),q&&Nt&2048&&vj(ke.alternate,ke);break;case 24:Wg(Z,ke,Ue,nt,q),q&&Nt&2048&&wj(ke.alternate,ke);break;default:Wg(Z,ke,Ue,nt,q)}y=y.sibling}}function Yy(h,y){if(y.subtreeFlags&10256)for(y=y.child;y!==null;){var S=h,M=y,q=M.flags;switch(M.tag){case 22:Yy(S,M),q&2048&&vj(M.alternate,M);break;case 24:Yy(S,M),q&2048&&wj(M.alternate,M);break;default:Yy(S,M)}y=y.sibling}}var Qy=8192;function Kg(h,y,S){if(h.subtreeFlags&Qy)for(h=h.child;h!==null;)cB(h,y,S),h=h.sibling}function cB(h,y,S){switch(h.tag){case 26:Kg(h,y,S),h.flags&Qy&&h.memoizedState!==null&&xde(S,vc,h.memoizedState,h.memoizedProps);break;case 5:Kg(h,y,S);break;case 3:case 4:var M=vc;vc=b_(h.stateNode.containerInfo),Kg(h,y,S),vc=M;break;case 22:h.memoizedState===null&&(M=h.alternate,M!==null&&M.memoizedState!==null?(M=Qy,Qy=16777216,Kg(h,y,S),Qy=M):Kg(h,y,S));break;default:Kg(h,y,S)}}function dB(h){var y=h.alternate;if(y!==null&&(h=y.child,h!==null)){y.child=null;do y=h.sibling,h.sibling=null,h=y;while(h!==null)}}function Zy(h){var y=h.deletions;if((h.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var M=y[S];Di=M,mB(M,h)}dB(h)}if(h.subtreeFlags&10256)for(h=h.child;h!==null;)uB(h),h=h.sibling}function uB(h){switch(h.tag){case 0:case 11:case 15:Zy(h),h.flags&2048&&Im(9,h,h.return);break;case 3:Zy(h);break;case 12:Zy(h);break;case 22:var y=h.stateNode;h.memoizedState!==null&&y._visibility&2&&(h.return===null||h.return.tag!==13)?(y._visibility&=-3,a_(h)):Zy(h);break;default:Zy(h)}}function a_(h){var y=h.deletions;if((h.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var M=y[S];Di=M,mB(M,h)}dB(h)}for(h=h.child;h!==null;){switch(y=h,y.tag){case 0:case 11:case 15:Im(8,y,y.return),a_(y);break;case 22:S=y.stateNode,S._visibility&2&&(S._visibility&=-3,a_(y));break;default:a_(y)}h=h.sibling}}function mB(h,y){for(;Di!==null;){var S=Di;switch(S.tag){case 0:case 11:case 15:Im(8,S,y);break;case 23:case 22:if(S.memoizedState!==null&&S.memoizedState.cachePool!==null){var M=S.memoizedState.cachePool.pool;M!=null&&M.refCount++}break;case 24:Ry(S.memoizedState.cache)}if(M=S.child,M!==null)M.return=S,Di=M;else e:for(S=h;Di!==null;){M=Di;var q=M.sibling,Z=M.return;if(nB(M),M===S){Di=null;break e}if(q!==null){q.return=Z,Di=q;break e}Di=Z}}}var Dce={getCacheForType:function(h){var y=Ji(ii),S=y.data.get(h);return S===void 0&&(S=h(),y.data.set(h,S)),S},cacheSignal:function(){return Ji(ii).controller.signal}},Fce=typeof WeakMap=="function"?WeakMap:Map,Mr=0,Jr=null,hr=null,gr=0,Lr=0,$o=null,zm=!1,Xg=!1,Sj=!1,ou=0,Oa=0,Um=0,$p=0,_j=0,Vo=0,Yg=0,Jy=null,xo=null,kj=!1,i_=0,hB=0,s_=1/0,o_=null,Bm=null,vi=0,Hm=null,Qg=null,lu=0,Nj=0,Cj=null,pB=null,ev=0,Pj=null;function Go(){return(Mr&2)!==0&&gr!==0?gr&-gr:ie.T!==null?Dj():Ge()}function fB(){if(Vo===0)if((gr&536870912)===0||yr){var h=be;be<<=1,(be&3932160)===0&&(be=262144),Vo=h}else Vo=536870912;return h=Ho.current,h!==null&&(h.flags|=32),Vo}function yo(h,y,S){(h===Jr&&(Lr===2||Lr===9)||h.cancelPendingCommit!==null)&&(Zg(h,0),qm(h,gr,Vo,!1)),vt(h,S),((Mr&2)===0||h!==Jr)&&(h===Jr&&((Mr&2)===0&&($p|=S),Oa===4&&qm(h,gr,Vo,!1)),nd(h))}function gB(h,y,S){if((Mr&6)!==0)throw Error(r(327));var M=!S&&(y&127)===0&&(y&h.expiredLanes)===0||Pe(h,y),q=M?Oce(h,y):Aj(h,y,!0),Z=M;do{if(q===0){Xg&&!M&&qm(h,y,0,!1);break}else{if(S=h.current.alternate,Z&&!Rce(S)){q=Aj(h,y,!1),Z=!1;continue}if(q===2){if(Z=y,h.errorRecoveryDisabledLanes&Z)var ke=0;else ke=h.pendingLanes&-536870913,ke=ke!==0?ke:ke&536870912?536870912:0;if(ke!==0){y=ke;e:{var Ue=h;q=Jy;var nt=Ue.current.memoizedState.isDehydrated;if(nt&&(Zg(Ue,ke).flags|=256),ke=Aj(Ue,ke,!1),ke!==2){if(Sj&&!nt){Ue.errorRecoveryDisabledLanes|=Z,$p|=Z,q=4;break e}Z=xo,xo=q,Z!==null&&(xo===null?xo=Z:xo.push.apply(xo,Z))}q=ke}if(Z=!1,q!==2)continue}}if(q===1){Zg(h,0),qm(h,y,0,!0);break}e:{switch(M=h,Z=q,Z){case 0:case 1:throw Error(r(345));case 4:if((y&4194048)!==y)break;case 6:qm(M,y,Vo,!zm);break e;case 2:xo=null;break;case 3:case 5:break;default:throw Error(r(329))}if((y&62914560)===y&&(q=i_+300-R(),10<q)){if(qm(M,y,Vo,!zm),ge(M,0,!0)!==0)break e;lu=y,M.timeoutHandle=WB(bB.bind(null,M,S,xo,o_,kj,y,Vo,$p,Yg,zm,Z,"Throttled",-0,0),q);break e}bB(M,S,xo,o_,kj,y,Vo,$p,Yg,zm,Z,null,-0,0)}}break}while(!0);nd(h)}function bB(h,y,S,M,q,Z,ke,Ue,nt,Nt,Lt,It,Ct,Dt){if(h.timeoutHandle=-1,It=y.subtreeFlags,It&8192||(It&16785408)===16785408){It={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:qt},cB(y,Z,It);var gn=(Z&62914560)===Z?i_-R():(Z&4194048)===Z?hB-R():0;if(gn=yde(It,gn),gn!==null){lu=Z,h.cancelPendingCommit=gn(NB.bind(null,h,y,Z,S,M,q,ke,Ue,nt,Lt,It,null,Ct,Dt)),qm(h,Z,ke,!Nt);return}}NB(h,y,Z,S,M,q,ke,Ue,nt)}function Rce(h){for(var y=h;;){var S=y.tag;if((S===0||S===11||S===15)&&y.flags&16384&&(S=y.updateQueue,S!==null&&(S=S.stores,S!==null)))for(var M=0;M<S.length;M++){var q=S[M],Z=q.getSnapshot;q=q.value;try{if(!Uo(Z(),q))return!1}catch{return!1}}if(S=y.child,y.subtreeFlags&16384&&S!==null)S.return=y,y=S;else{if(y===h)break;for(;y.sibling===null;){if(y.return===null||y.return===h)return!0;y=y.return}y.sibling.return=y.return,y=y.sibling}}return!0}function qm(h,y,S,M){y&=~_j,y&=~$p,h.suspendedLanes|=y,h.pingedLanes&=~y,M&&(h.warmLanes|=y),M=h.expirationTimes;for(var q=y;0<q;){var Z=31-Be(q),ke=1<<Z;M[Z]=-1,q&=~ke}S!==0&&$t(h,S,y)}function l_(){return(Mr&6)===0?(tv(0),!1):!0}function Tj(){if(hr!==null){if(Lr===0)var h=hr.return;else h=hr,Qd=Rp=null,$A(h),Hg=null,Oy=0,h=hr;for(;h!==null;)KU(h.alternate,h),h=h.return;hr=null}}function Zg(h,y){var S=h.timeoutHandle;S!==-1&&(h.timeoutHandle=-1,tde(S)),S=h.cancelPendingCommit,S!==null&&(h.cancelPendingCommit=null,S()),lu=0,Tj(),Jr=h,hr=S=Xd(h.current,null),gr=y,Lr=0,$o=null,zm=!1,Xg=Pe(h,y),Sj=!1,Yg=Vo=_j=$p=Um=Oa=0,xo=Jy=null,kj=!1,(y&8)!==0&&(y|=y&32);var M=h.entangledLanes;if(M!==0)for(h=h.entanglements,M&=y;0<M;){var q=31-Be(M),Z=1<<q;y|=h[q],M&=~Z}return ou=y,AS(),S}function xB(h,y){Yn=null,ie.H=Vy,y===Bg||y===OS?(y=F5(),Lr=3):y===EA?(y=F5(),Lr=4):Lr=y===sj?8:y!==null&&typeof y=="object"&&typeof y.then=="function"?6:1,$o=y,hr===null&&(Oa=1,QS(h,kl(y,h.current)))}function yB(){var h=Ho.current;return h===null?!0:(gr&4194048)===gr?Tl===null:(gr&62914560)===gr||(gr&536870912)!==0?h===Tl:!1}function vB(){var h=ie.H;return ie.H=Vy,h===null?Vy:h}function wB(){var h=ie.A;return ie.A=Dce,h}function c_(){Oa=4,zm||(gr&4194048)!==gr&&Ho.current!==null||(Xg=!0),(Um&134217727)===0&&($p&134217727)===0||Jr===null||qm(Jr,gr,Vo,!1)}function Aj(h,y,S){var M=Mr;Mr|=2;var q=vB(),Z=wB();(Jr!==h||gr!==y)&&(o_=null,Zg(h,y)),y=!1;var ke=Oa;e:do try{if(Lr!==0&&hr!==null){var Ue=hr,nt=$o;switch(Lr){case 8:Tj(),ke=6;break e;case 3:case 2:case 9:case 6:Ho.current===null&&(y=!0);var Nt=Lr;if(Lr=0,$o=null,Jg(h,Ue,nt,Nt),S&&Xg){ke=0;break e}break;default:Nt=Lr,Lr=0,$o=null,Jg(h,Ue,nt,Nt)}}Lce(),ke=Oa;break}catch(Lt){xB(h,Lt)}while(!0);return y&&h.shellSuspendCounter++,Qd=Rp=null,Mr=M,ie.H=q,ie.A=Z,hr===null&&(Jr=null,gr=0,AS()),ke}function Lce(){for(;hr!==null;)SB(hr)}function Oce(h,y){var S=Mr;Mr|=2;var M=vB(),q=wB();Jr!==h||gr!==y?(o_=null,s_=R()+500,Zg(h,y)):Xg=Pe(h,y);e:do try{if(Lr!==0&&hr!==null){y=hr;var Z=$o;t:switch(Lr){case 1:Lr=0,$o=null,Jg(h,y,Z,1);break;case 2:case 9:if(E5(Z)){Lr=0,$o=null,_B(y);break}y=function(){Lr!==2&&Lr!==9||Jr!==h||(Lr=7),nd(h)},Z.then(y,y);break e;case 3:Lr=7;break e;case 4:Lr=5;break e;case 7:E5(Z)?(Lr=0,$o=null,_B(y)):(Lr=0,$o=null,Jg(h,y,Z,7));break;case 5:var ke=null;switch(hr.tag){case 26:ke=hr.memoizedState;case 5:case 27:var Ue=hr;if(ke?l8(ke):Ue.stateNode.complete){Lr=0,$o=null;var nt=Ue.sibling;if(nt!==null)hr=nt;else{var Nt=Ue.return;Nt!==null?(hr=Nt,d_(Nt)):hr=null}break t}}Lr=0,$o=null,Jg(h,y,Z,5);break;case 6:Lr=0,$o=null,Jg(h,y,Z,6);break;case 8:Tj(),Oa=6;break e;default:throw Error(r(462))}}Ice();break}catch(Lt){xB(h,Lt)}while(!0);return Qd=Rp=null,ie.H=M,ie.A=q,Mr=S,hr!==null?0:(Jr=null,gr=0,AS(),Oa)}function Ice(){for(;hr!==null&&!de();)SB(hr)}function SB(h){var y=GU(h.alternate,h,ou);h.memoizedProps=h.pendingProps,y===null?d_(h):hr=y}function _B(h){var y=h,S=y.alternate;switch(y.tag){case 15:case 0:y=UU(S,y,y.pendingProps,y.type,void 0,gr);break;case 11:y=UU(S,y,y.pendingProps,y.type.render,y.ref,gr);break;case 5:$A(y);default:KU(S,y),y=hr=w5(y,ou),y=GU(S,y,ou)}h.memoizedProps=h.pendingProps,y===null?d_(h):hr=y}function Jg(h,y,S,M){Qd=Rp=null,$A(y),Hg=null,Oy=0;var q=y.return;try{if(Cce(h,q,y,S,gr)){Oa=1,QS(h,kl(S,h.current)),hr=null;return}}catch(Z){if(q!==null)throw hr=q,Z;Oa=1,QS(h,kl(S,h.current)),hr=null;return}y.flags&32768?(yr||M===1?h=!0:Xg||(gr&536870912)!==0?h=!1:(zm=h=!0,(M===2||M===9||M===3||M===6)&&(M=Ho.current,M!==null&&M.tag===13&&(M.flags|=16384))),kB(y,h)):d_(y)}function d_(h){var y=h;do{if((y.flags&32768)!==0){kB(y,zm);return}h=y.return;var S=Ace(y.alternate,y,ou);if(S!==null){hr=S;return}if(y=y.sibling,y!==null){hr=y;return}hr=y=h}while(y!==null);Oa===0&&(Oa=5)}function kB(h,y){do{var S=jce(h.alternate,h);if(S!==null){S.flags&=32767,hr=S;return}if(S=h.return,S!==null&&(S.flags|=32768,S.subtreeFlags=0,S.deletions=null),!y&&(h=h.sibling,h!==null)){hr=h;return}hr=h=S}while(h!==null);Oa=6,hr=null}function NB(h,y,S,M,q,Z,ke,Ue,nt){h.cancelPendingCommit=null;do u_();while(vi!==0);if((Mr&6)!==0)throw Error(r(327));if(y!==null){if(y===h.current)throw Error(r(177));if(Z=y.lanes|y.childLanes,Z|=bA,wt(h,S,Z,ke,Ue,nt),h===Jr&&(hr=Jr=null,gr=0),Qg=y,Hm=h,lu=S,Nj=Z,Cj=q,pB=M,(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?(h.callbackNode=null,h.callbackPriority=0,Hce(ye,function(){return jB(),null})):(h.callbackNode=null,h.callbackPriority=0),M=(y.flags&13878)!==0,(y.subtreeFlags&13878)!==0||M){M=ie.T,ie.T=null,q=ee.p,ee.p=2,ke=Mr,Mr|=4;try{Mce(h,y,S)}finally{Mr=ke,ee.p=q,ie.T=M}}vi=1,CB(),PB(),TB()}}function CB(){if(vi===1){vi=0;var h=Hm,y=Qg,S=(y.flags&13878)!==0;if((y.subtreeFlags&13878)!==0||S){S=ie.T,ie.T=null;var M=ee.p;ee.p=2;var q=Mr;Mr|=4;try{sB(y,h);var Z=Bj,ke=m5(h.containerInfo),Ue=Z.focusedElem,nt=Z.selectionRange;if(ke!==Ue&&Ue&&Ue.ownerDocument&&u5(Ue.ownerDocument.documentElement,Ue)){if(nt!==null&&mA(Ue)){var Nt=nt.start,Lt=nt.end;if(Lt===void 0&&(Lt=Nt),"selectionStart"in Ue)Ue.selectionStart=Nt,Ue.selectionEnd=Math.min(Lt,Ue.value.length);else{var It=Ue.ownerDocument||document,Ct=It&&It.defaultView||window;if(Ct.getSelection){var Dt=Ct.getSelection(),gn=Ue.textContent.length,Fn=Math.min(nt.start,gn),qr=nt.end===void 0?Fn:Math.min(nt.end,gn);!Dt.extend&&Fn>qr&&(ke=qr,qr=Fn,Fn=ke);var ft=d5(Ue,Fn),lt=d5(Ue,qr);if(ft&<&&(Dt.rangeCount!==1||Dt.anchorNode!==ft.node||Dt.anchorOffset!==ft.offset||Dt.focusNode!==lt.node||Dt.focusOffset!==lt.offset)){var kt=It.createRange();kt.setStart(ft.node,ft.offset),Dt.removeAllRanges(),Fn>qr?(Dt.addRange(kt),Dt.extend(lt.node,lt.offset)):(kt.setEnd(lt.node,lt.offset),Dt.addRange(kt))}}}}for(It=[],Dt=Ue;Dt=Dt.parentNode;)Dt.nodeType===1&&It.push({element:Dt,left:Dt.scrollLeft,top:Dt.scrollTop});for(typeof Ue.focus=="function"&&Ue.focus(),Ue=0;Ue<It.length;Ue++){var Ot=It[Ue];Ot.element.scrollLeft=Ot.left,Ot.element.scrollTop=Ot.top}}__=!!Uj,Bj=Uj=null}finally{Mr=q,ee.p=M,ie.T=S}}h.current=y,vi=2}}function PB(){if(vi===2){vi=0;var h=Hm,y=Qg,S=(y.flags&8772)!==0;if((y.subtreeFlags&8772)!==0||S){S=ie.T,ie.T=null;var M=ee.p;ee.p=2;var q=Mr;Mr|=4;try{tB(h,y.alternate,y)}finally{Mr=q,ee.p=M,ie.T=S}}vi=3}}function TB(){if(vi===4||vi===3){vi=0,U();var h=Hm,y=Qg,S=lu,M=pB;(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?vi=5:(vi=0,Qg=Hm=null,AB(h,h.pendingLanes));var q=h.pendingLanes;if(q===0&&(Bm=null),tn(S),y=y.stateNode,Te&&typeof Te.onCommitFiberRoot=="function")try{Te.onCommitFiberRoot(Ee,y,void 0,(y.current.flags&128)===128)}catch{}if(M!==null){y=ie.T,q=ee.p,ee.p=2,ie.T=null;try{for(var Z=h.onRecoverableError,ke=0;ke<M.length;ke++){var Ue=M[ke];Z(Ue.value,{componentStack:Ue.stack})}}finally{ie.T=y,ee.p=q}}(lu&3)!==0&&u_(),nd(h),q=h.pendingLanes,(S&261930)!==0&&(q&42)!==0?h===Pj?ev++:(ev=0,Pj=h):ev=0,tv(0)}}function AB(h,y){(h.pooledCacheLanes&=y)===0&&(y=h.pooledCache,y!=null&&(h.pooledCache=null,Ry(y)))}function u_(){return CB(),PB(),TB(),jB()}function jB(){if(vi!==5)return!1;var h=Hm,y=Nj;Nj=0;var S=tn(lu),M=ie.T,q=ee.p;try{ee.p=32>S?32:S,ie.T=null,S=Cj,Cj=null;var Z=Hm,ke=lu;if(vi=0,Qg=Hm=null,lu=0,(Mr&6)!==0)throw Error(r(331));var Ue=Mr;if(Mr|=4,uB(Z.current),lB(Z,Z.current,ke,S),Mr=Ue,tv(0,!1),Te&&typeof Te.onPostCommitFiberRoot=="function")try{Te.onPostCommitFiberRoot(Ee,Z)}catch{}return!0}finally{ee.p=q,ie.T=M,AB(h,y)}}function MB(h,y,S){y=kl(S,y),y=ij(h.stateNode,y,2),h=Rm(h,y,2),h!==null&&(vt(h,2),nd(h))}function Or(h,y,S){if(h.tag===3)MB(h,h,S);else for(;y!==null;){if(y.tag===3){MB(y,h,S);break}else if(y.tag===1){var M=y.stateNode;if(typeof y.type.getDerivedStateFromError=="function"||typeof M.componentDidCatch=="function"&&(Bm===null||!Bm.has(M))){h=kl(S,h),S=EU(2),M=Rm(y,S,2),M!==null&&(DU(S,M,y,h),vt(M,2),nd(M));break}}y=y.return}}function jj(h,y,S){var M=h.pingCache;if(M===null){M=h.pingCache=new Fce;var q=new Set;M.set(y,q)}else q=M.get(y),q===void 0&&(q=new Set,M.set(y,q));q.has(S)||(Sj=!0,q.add(S),h=zce.bind(null,h,y,S),y.then(h,h))}function zce(h,y,S){var M=h.pingCache;M!==null&&M.delete(y),h.pingedLanes|=h.suspendedLanes&S,h.warmLanes&=~S,Jr===h&&(gr&S)===S&&(Oa===4||Oa===3&&(gr&62914560)===gr&&300>R()-i_?(Mr&2)===0&&Zg(h,0):_j|=S,Yg===gr&&(Yg=0)),nd(h)}function EB(h,y){y===0&&(y=Ze()),h=Ep(h,y),h!==null&&(vt(h,y),nd(h))}function Uce(h){var y=h.memoizedState,S=0;y!==null&&(S=y.retryLane),EB(h,S)}function Bce(h,y){var S=0;switch(h.tag){case 31:case 13:var M=h.stateNode,q=h.memoizedState;q!==null&&(S=q.retryLane);break;case 19:M=h.stateNode;break;case 22:M=h.stateNode._retryCache;break;default:throw Error(r(314))}M!==null&&M.delete(y),EB(h,S)}function Hce(h,y){return fe(h,y)}var m_=null,eb=null,Mj=!1,h_=!1,Ej=!1,$m=0;function nd(h){h!==eb&&h.next===null&&(eb===null?m_=eb=h:eb=eb.next=h),h_=!0,Mj||(Mj=!0,$ce())}function tv(h,y){if(!Ej&&h_){Ej=!0;do for(var S=!1,M=m_;M!==null;){if(h!==0){var q=M.pendingLanes;if(q===0)var Z=0;else{var ke=M.suspendedLanes,Ue=M.pingedLanes;Z=(1<<31-Be(42|h)+1)-1,Z&=q&~(ke&~Ue),Z=Z&201326741?Z&201326741|1:Z?Z|2:0}Z!==0&&(S=!0,LB(M,Z))}else Z=gr,Z=ge(M,M===Jr?Z:0,M.cancelPendingCommit!==null||M.timeoutHandle!==-1),(Z&3)===0||Pe(M,Z)||(S=!0,LB(M,Z));M=M.next}while(S);Ej=!1}}function qce(){DB()}function DB(){h_=Mj=!1;var h=0;$m!==0&&ede()&&(h=$m);for(var y=R(),S=null,M=m_;M!==null;){var q=M.next,Z=FB(M,y);Z===0?(M.next=null,S===null?m_=q:S.next=q,q===null&&(eb=S)):(S=M,(h!==0||(Z&3)!==0)&&(h_=!0)),M=q}vi!==0&&vi!==5||tv(h),$m!==0&&($m=0)}function FB(h,y){for(var S=h.suspendedLanes,M=h.pingedLanes,q=h.expirationTimes,Z=h.pendingLanes&-62914561;0<Z;){var ke=31-Be(Z),Ue=1<<ke,nt=q[ke];nt===-1?((Ue&S)===0||(Ue&M)!==0)&&(q[ke]=qe(Ue,y)):nt<=y&&(h.expiredLanes|=Ue),Z&=~Ue}if(y=Jr,S=gr,S=ge(h,h===y?S:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),M=h.callbackNode,S===0||h===y&&(Lr===2||Lr===9)||h.cancelPendingCommit!==null)return M!==null&&M!==null&&pe(M),h.callbackNode=null,h.callbackPriority=0;if((S&3)===0||Pe(h,S)){if(y=S&-S,y===h.callbackPriority)return y;switch(M!==null&&pe(M),tn(S)){case 2:case 8:S=Se;break;case 32:S=ye;break;case 268435456:S=ve;break;default:S=ye}return M=RB.bind(null,h),S=fe(S,M),h.callbackPriority=y,h.callbackNode=S,y}return M!==null&&M!==null&&pe(M),h.callbackPriority=2,h.callbackNode=null,2}function RB(h,y){if(vi!==0&&vi!==5)return h.callbackNode=null,h.callbackPriority=0,null;var S=h.callbackNode;if(u_()&&h.callbackNode!==S)return null;var M=gr;return M=ge(h,h===Jr?M:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),M===0?null:(gB(h,M,y),FB(h,R()),h.callbackNode!=null&&h.callbackNode===S?RB.bind(null,h):null)}function LB(h,y){if(u_())return null;gB(h,y,!0)}function $ce(){nde(function(){(Mr&6)!==0?fe(_e,qce):DB()})}function Dj(){if($m===0){var h=zg;h===0&&(h=Ie,Ie<<=1,(Ie&261888)===0&&(Ie=256)),$m=h}return $m}function OB(h){return h==null||typeof h=="symbol"||typeof h=="boolean"?null:typeof h=="function"?h:Zn(""+h)}function IB(h,y){var S=y.ownerDocument.createElement("input");return S.name=y.name,S.value=y.value,h.id&&S.setAttribute("form",h.id),y.parentNode.insertBefore(S,y),h=new FormData(h),S.parentNode.removeChild(S),h}function Vce(h,y,S,M,q){if(y==="submit"&&S&&S.stateNode===q){var Z=OB((q[pt]||null).action),ke=M.submitter;ke&&(y=(y=ke[pt]||null)?OB(y.formAction):ke.getAttribute("formAction"),y!==null&&(Z=y,ke=null));var Ue=new gc("action","action",null,M,q);h.push({event:Ue,listeners:[{instance:null,listener:function(){if(M.defaultPrevented){if($m!==0){var nt=ke?IB(q,ke):new FormData(q);JA(S,{pending:!0,data:nt,method:q.method,action:Z},null,nt)}}else typeof Z=="function"&&(Ue.preventDefault(),nt=ke?IB(q,ke):new FormData(q),JA(S,{pending:!0,data:nt,method:q.method,action:Z},Z,nt))},currentTarget:q}]})}}for(var Fj=0;Fj<gA.length;Fj++){var Rj=gA[Fj],Gce=Rj.toLowerCase(),Wce=Rj[0].toUpperCase()+Rj.slice(1);yc(Gce,"on"+Wce)}yc(f5,"onAnimationEnd"),yc(g5,"onAnimationIteration"),yc(b5,"onAnimationStart"),yc("dblclick","onDoubleClick"),yc("focusin","onFocus"),yc("focusout","onBlur"),yc(cce,"onTransitionRun"),yc(dce,"onTransitionStart"),yc(uce,"onTransitionCancel"),yc(x5,"onTransitionEnd"),jt("onMouseEnter",["mouseout","mouseover"]),jt("onMouseLeave",["mouseout","mouseover"]),jt("onPointerEnter",["pointerout","pointerover"]),jt("onPointerLeave",["pointerout","pointerover"]),et("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),et("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),et("onBeforeInput",["compositionend","keypress","textInput","paste"]),et("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),et("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),et("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var nv="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(" "),Kce=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(nv));function zB(h,y){y=(y&4)!==0;for(var S=0;S<h.length;S++){var M=h[S],q=M.event;M=M.listeners;e:{var Z=void 0;if(y)for(var ke=M.length-1;0<=ke;ke--){var Ue=M[ke],nt=Ue.instance,Nt=Ue.currentTarget;if(Ue=Ue.listener,nt!==Z&&q.isPropagationStopped())break e;Z=Ue,q.currentTarget=Nt;try{Z(q)}catch(Lt){TS(Lt)}q.currentTarget=null,Z=nt}else for(ke=0;ke<M.length;ke++){if(Ue=M[ke],nt=Ue.instance,Nt=Ue.currentTarget,Ue=Ue.listener,nt!==Z&&q.isPropagationStopped())break e;Z=Ue,q.currentTarget=Nt;try{Z(q)}catch(Lt){TS(Lt)}q.currentTarget=null,Z=nt}}}}function pr(h,y){var S=y[Ut];S===void 0&&(S=y[Ut]=new Set);var M=h+"__bubble";S.has(M)||(UB(y,h,2,!1),S.add(M))}function Lj(h,y,S){var M=0;y&&(M|=4),UB(S,h,M,y)}var p_="_reactListening"+Math.random().toString(36).slice(2);function Oj(h){if(!h[p_]){h[p_]=!0,Ye.forEach(function(S){S!=="selectionchange"&&(Kce.has(S)||Lj(S,!1,h),Lj(S,!0,h))});var y=h.nodeType===9?h:h.ownerDocument;y===null||y[p_]||(y[p_]=!0,Lj("selectionchange",!1,y))}}function UB(h,y,S,M){switch(f8(y)){case 2:var q=Sde;break;case 8:q=_de;break;default:q=Zj}S=q.bind(null,y,S,h),q=void 0,!Nm||y!=="touchstart"&&y!=="touchmove"&&y!=="wheel"||(q=!0),M?q!==void 0?h.addEventListener(y,S,{capture:!0,passive:q}):h.addEventListener(y,S,!0):q!==void 0?h.addEventListener(y,S,{passive:q}):h.addEventListener(y,S,!1)}function Ij(h,y,S,M,q){var Z=M;if((y&1)===0&&(y&2)===0&&M!==null)e:for(;;){if(M===null)return;var ke=M.tag;if(ke===3||ke===4){var Ue=M.stateNode.containerInfo;if(Ue===q)break;if(ke===4)for(ke=M.return;ke!==null;){var nt=ke.tag;if((nt===3||nt===4)&&ke.stateNode.containerInfo===q)return;ke=ke.return}for(;Ue!==null;){if(ke=Oe(Ue),ke===null)return;if(nt=ke.tag,nt===5||nt===6||nt===26||nt===27){M=Z=ke;continue e}Ue=Ue.parentNode}}M=M.return}Cp(function(){var Nt=Z,Lt=Ki(S),It=[];e:{var Ct=y5.get(h);if(Ct!==void 0){var Dt=gc,gn=h;switch(h){case"keypress":if(xl(S)===0)break e;case"keydown":case"keyup":Dt=Bn;break;case"focusin":gn="focus",Dt=zo;break;case"focusout":gn="blur",Dt=zo;break;case"beforeblur":case"afterblur":Dt=zo;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":Dt=Xc;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Dt=uo;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Dt=mn;break;case f5:case g5:case b5:Dt=kn;break;case x5:Dt=dn;break;case"scroll":case"scrollend":Dt=Pp;break;case"wheel":Dt=Vn;break;case"copy":case"cut":case"paste":Dt=Yc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Dt=_t;break;case"toggle":case"beforetoggle":Dt=Bs}var Fn=(y&4)!==0,qr=!Fn&&(h==="scroll"||h==="scrollend"),ft=Fn?Ct!==null?Ct+"Capture":null:Ct;Fn=[];for(var lt=Nt,kt;lt!==null;){var Ot=lt;if(kt=Ot.stateNode,Ot=Ot.tag,Ot!==5&&Ot!==26&&Ot!==27||kt===null||ft===null||(Ot=Gd(lt,ft),Ot!=null&&Fn.push(rv(lt,Ot,kt))),qr)break;lt=lt.return}0<Fn.length&&(Ct=new Dt(Ct,gn,null,S,Lt),It.push({event:Ct,listeners:Fn}))}}if((y&7)===0){e:{if(Ct=h==="mouseover"||h==="pointerover",Dt=h==="mouseout"||h==="pointerout",Ct&&S!==Kc&&(gn=S.relatedTarget||S.fromElement)&&(Oe(gn)||gn[Wt]))break e;if((Dt||Ct)&&(Ct=Lt.window===Lt?Lt:(Ct=Lt.ownerDocument)?Ct.defaultView||Ct.parentWindow:window,Dt?(gn=S.relatedTarget||S.toElement,Dt=Nt,gn=gn?Oe(gn):null,gn!==null&&(qr=s(gn),Fn=gn.tag,gn!==qr||Fn!==5&&Fn!==27&&Fn!==6)&&(gn=null)):(Dt=null,gn=Nt),Dt!==gn)){if(Fn=Xc,Ot="onMouseLeave",ft="onMouseEnter",lt="mouse",(h==="pointerout"||h==="pointerover")&&(Fn=_t,Ot="onPointerLeave",ft="onPointerEnter",lt="pointer"),qr=Dt==null?Ct:We(Dt),kt=gn==null?Ct:We(gn),Ct=new Fn(Ot,lt+"leave",Dt,S,Lt),Ct.target=qr,Ct.relatedTarget=kt,Ot=null,Oe(Lt)===Nt&&(Fn=new Fn(ft,lt+"enter",gn,S,Lt),Fn.target=kt,Fn.relatedTarget=qr,Ot=Fn),qr=Ot,Dt&&gn)t:{for(Fn=Xce,ft=Dt,lt=gn,kt=0,Ot=ft;Ot;Ot=Fn(Ot))kt++;Ot=0;for(var jn=lt;jn;jn=Fn(jn))Ot++;for(;0<kt-Ot;)ft=Fn(ft),kt--;for(;0<Ot-kt;)lt=Fn(lt),Ot--;for(;kt--;){if(ft===lt||lt!==null&&ft===lt.alternate){Fn=ft;break t}ft=Fn(ft),lt=Fn(lt)}Fn=null}else Fn=null;Dt!==null&&BB(It,Ct,Dt,Fn,!1),gn!==null&&qr!==null&&BB(It,qr,gn,Fn,!0)}}e:{if(Ct=Nt?We(Nt):window,Dt=Ct.nodeName&&Ct.nodeName.toLowerCase(),Dt==="select"||Dt==="input"&&Ct.type==="file")var Cr=PS;else if(In(Ct))if(i5)Cr=sce;else{Cr=ace;var vn=rce}else Dt=Ct.nodeName,!Dt||Dt.toLowerCase()!=="input"||Ct.type!=="checkbox"&&Ct.type!=="radio"?Nt&&fl(Nt.elementType)&&(Cr=PS):Cr=ice;if(Cr&&(Cr=Cr(h,Nt))){cA(It,Cr,S,Lt);break e}vn&&vn(h,Ct,Nt),h==="focusout"&&Nt&&Ct.type==="number"&&Nt.memoizedProps.value!=null&&ya(Ct,"number",Ct.value)}switch(vn=Nt?We(Nt):window,h){case"focusin":(In(vn)||vn.contentEditable==="true")&&(Mg=vn,hA=Nt,Ey=null);break;case"focusout":Ey=hA=Mg=null;break;case"mousedown":pA=!0;break;case"contextmenu":case"mouseup":case"dragend":pA=!1,h5(It,S,Lt);break;case"selectionchange":if(lce)break;case"keydown":case"keyup":h5(It,S,Lt)}var Jn;if(ma)e:{switch(h){case"compositionstart":var br="onCompositionStart";break e;case"compositionend":br="onCompositionEnd";break e;case"compositionupdate":br="onCompositionUpdate";break e}br=void 0}else Qc?oa(h,S)&&(br="onCompositionEnd"):h==="keydown"&&S.keyCode===229&&(br="onCompositionStart");br&&(Qi&&S.locale!=="ko"&&(Qc||br!=="onCompositionStart"?br==="onCompositionEnd"&&Qc&&(Jn=Za()):(Yi=Lt,zs="value"in Yi?Yi.value:Yi.textContent,Qc=!0)),vn=f_(Nt,br),0<vn.length&&(br=new Pm(br,h,null,S,Lt),It.push({event:br,listeners:vn}),Jn?br.data=Jn:(Jn=po(S),Jn!==null&&(br.data=Jn)))),(Jn=bc?ha(h,S):Kd(h,S))&&(br=f_(Nt,"onBeforeInput"),0<br.length&&(vn=new Pm("onBeforeInput","beforeinput",null,S,Lt),It.push({event:vn,listeners:br}),vn.data=Jn)),Vce(It,h,Nt,S,Lt)}zB(It,y)})}function rv(h,y,S){return{instance:h,listener:y,currentTarget:S}}function f_(h,y){for(var S=y+"Capture",M=[];h!==null;){var q=h,Z=q.stateNode;if(q=q.tag,q!==5&&q!==26&&q!==27||Z===null||(q=Gd(h,S),q!=null&&M.unshift(rv(h,q,Z)),q=Gd(h,y),q!=null&&M.push(rv(h,q,Z))),h.tag===3)return M;h=h.return}return[]}function Xce(h){if(h===null)return null;do h=h.return;while(h&&h.tag!==5&&h.tag!==27);return h||null}function BB(h,y,S,M,q){for(var Z=y._reactName,ke=[];S!==null&&S!==M;){var Ue=S,nt=Ue.alternate,Nt=Ue.stateNode;if(Ue=Ue.tag,nt!==null&&nt===M)break;Ue!==5&&Ue!==26&&Ue!==27||Nt===null||(nt=Nt,q?(Nt=Gd(S,Z),Nt!=null&&ke.unshift(rv(S,Nt,nt))):q||(Nt=Gd(S,Z),Nt!=null&&ke.push(rv(S,Nt,nt)))),S=S.return}ke.length!==0&&h.push({event:y,listeners:ke})}var Yce=/\r\n?/g,Qce=/\u0000|\uFFFD/g;function HB(h){return(typeof h=="string"?h:""+h).replace(Yce,`
- `).replace(Qce,"")}function qB(h,y){return y=HB(y),HB(h)===y}function Hr(h,y,S,M,q,Z){switch(S){case"children":typeof M=="string"?y==="body"||y==="textarea"&&M===""||Ta(h,M):(typeof M=="number"||typeof M=="bigint")&&y!=="body"&&Ta(h,""+M);break;case"className":on(h,"class",M);break;case"tabIndex":on(h,"tabindex",M);break;case"dir":case"role":case"viewBox":case"width":case"height":on(h,S,M);break;case"style":Vd(h,M,Z);break;case"data":if(y!=="object"){on(h,"data",M);break}case"src":case"href":if(M===""&&(y!=="a"||S!=="href")){h.removeAttribute(S);break}if(M==null||typeof M=="function"||typeof M=="symbol"||typeof M=="boolean"){h.removeAttribute(S);break}M=Zn(""+M),h.setAttribute(S,M);break;case"action":case"formAction":if(typeof M=="function"){h.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 Z=="function"&&(S==="formAction"?(y!=="input"&&Hr(h,y,"name",q.name,q,null),Hr(h,y,"formEncType",q.formEncType,q,null),Hr(h,y,"formMethod",q.formMethod,q,null),Hr(h,y,"formTarget",q.formTarget,q,null)):(Hr(h,y,"encType",q.encType,q,null),Hr(h,y,"method",q.method,q,null),Hr(h,y,"target",q.target,q,null)));if(M==null||typeof M=="symbol"||typeof M=="boolean"){h.removeAttribute(S);break}M=Zn(""+M),h.setAttribute(S,M);break;case"onClick":M!=null&&(h.onclick=qt);break;case"onScroll":M!=null&&pr("scroll",h);break;case"onScrollEnd":M!=null&&pr("scrollend",h);break;case"dangerouslySetInnerHTML":if(M!=null){if(typeof M!="object"||!("__html"in M))throw Error(r(61));if(S=M.__html,S!=null){if(q.children!=null)throw Error(r(60));h.innerHTML=S}}break;case"multiple":h.multiple=M&&typeof M!="function"&&typeof M!="symbol";break;case"muted":h.muted=M&&typeof M!="function"&&typeof M!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(M==null||typeof M=="function"||typeof M=="boolean"||typeof M=="symbol"){h.removeAttribute("xlink:href");break}S=Zn(""+M),h.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":M!=null&&typeof M!="function"&&typeof M!="symbol"?h.setAttribute(S,""+M):h.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":M&&typeof M!="function"&&typeof M!="symbol"?h.setAttribute(S,""):h.removeAttribute(S);break;case"capture":case"download":M===!0?h.setAttribute(S,""):M!==!1&&M!=null&&typeof M!="function"&&typeof M!="symbol"?h.setAttribute(S,M):h.removeAttribute(S);break;case"cols":case"rows":case"size":case"span":M!=null&&typeof M!="function"&&typeof M!="symbol"&&!isNaN(M)&&1<=M?h.setAttribute(S,M):h.removeAttribute(S);break;case"rowSpan":case"start":M==null||typeof M=="function"||typeof M=="symbol"||isNaN(M)?h.removeAttribute(S):h.setAttribute(S,M);break;case"popover":pr("beforetoggle",h),pr("toggle",h),Gt(h,"popover",M);break;case"xlinkActuate":fn(h,"http://www.w3.org/1999/xlink","xlink:actuate",M);break;case"xlinkArcrole":fn(h,"http://www.w3.org/1999/xlink","xlink:arcrole",M);break;case"xlinkRole":fn(h,"http://www.w3.org/1999/xlink","xlink:role",M);break;case"xlinkShow":fn(h,"http://www.w3.org/1999/xlink","xlink:show",M);break;case"xlinkTitle":fn(h,"http://www.w3.org/1999/xlink","xlink:title",M);break;case"xlinkType":fn(h,"http://www.w3.org/1999/xlink","xlink:type",M);break;case"xmlBase":fn(h,"http://www.w3.org/XML/1998/namespace","xml:base",M);break;case"xmlLang":fn(h,"http://www.w3.org/XML/1998/namespace","xml:lang",M);break;case"xmlSpace":fn(h,"http://www.w3.org/XML/1998/namespace","xml:space",M);break;case"is":Gt(h,"is",M);break;case"innerText":case"textContent":break;default:(!(2<S.length)||S[0]!=="o"&&S[0]!=="O"||S[1]!=="n"&&S[1]!=="N")&&(S=xt.get(S)||S,Gt(h,S,M))}}function zj(h,y,S,M,q,Z){switch(S){case"style":Vd(h,M,Z);break;case"dangerouslySetInnerHTML":if(M!=null){if(typeof M!="object"||!("__html"in M))throw Error(r(61));if(S=M.__html,S!=null){if(q.children!=null)throw Error(r(60));h.innerHTML=S}}break;case"children":typeof M=="string"?Ta(h,M):(typeof M=="number"||typeof M=="bigint")&&Ta(h,""+M);break;case"onScroll":M!=null&&pr("scroll",h);break;case"onScrollEnd":M!=null&&pr("scrollend",h);break;case"onClick":M!=null&&(h.onclick=qt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!St.hasOwnProperty(S))e:{if(S[0]==="o"&&S[1]==="n"&&(q=S.endsWith("Capture"),y=S.slice(2,q?S.length-7:void 0),Z=h[pt]||null,Z=Z!=null?Z[S]:null,typeof Z=="function"&&h.removeEventListener(y,Z,q),typeof M=="function")){typeof Z!="function"&&Z!==null&&(S in h?h[S]=null:h.hasAttribute(S)&&h.removeAttribute(S)),h.addEventListener(y,M,q);break e}S in h?h[S]=M:M===!0?h.setAttribute(S,""):Gt(h,S,M)}}}function ts(h,y,S){switch(y){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":pr("error",h),pr("load",h);var M=!1,q=!1,Z;for(Z in S)if(S.hasOwnProperty(Z)){var ke=S[Z];if(ke!=null)switch(Z){case"src":M=!0;break;case"srcSet":q=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,y));default:Hr(h,y,Z,ke,S,null)}}q&&Hr(h,y,"srcSet",S.srcSet,S,null),M&&Hr(h,y,"src",S.src,S,null);return;case"input":pr("invalid",h);var Ue=Z=ke=q=null,nt=null,Nt=null;for(M in S)if(S.hasOwnProperty(M)){var Lt=S[M];if(Lt!=null)switch(M){case"name":q=Lt;break;case"type":ke=Lt;break;case"checked":nt=Lt;break;case"defaultChecked":Nt=Lt;break;case"value":Z=Lt;break;case"defaultValue":Ue=Lt;break;case"children":case"dangerouslySetInnerHTML":if(Lt!=null)throw Error(r(137,y));break;default:Hr(h,y,M,Lt,S,null)}}On(h,Z,Ue,nt,Nt,ke,q,!1);return;case"select":pr("invalid",h),M=ke=Z=null;for(q in S)if(S.hasOwnProperty(q)&&(Ue=S[q],Ue!=null))switch(q){case"value":Z=Ue;break;case"defaultValue":ke=Ue;break;case"multiple":M=Ue;default:Hr(h,y,q,Ue,S,null)}y=Z,S=ke,h.multiple=!!M,y!=null?ua(h,!!M,y,!1):S!=null&&ua(h,!!M,S,!0);return;case"textarea":pr("invalid",h),Z=q=M=null;for(ke in S)if(S.hasOwnProperty(ke)&&(Ue=S[ke],Ue!=null))switch(ke){case"value":M=Ue;break;case"defaultValue":q=Ue;break;case"children":Z=Ue;break;case"dangerouslySetInnerHTML":if(Ue!=null)throw Error(r(91));break;default:Hr(h,y,ke,Ue,S,null)}sa(h,M,q,Z);return;case"option":for(nt in S)S.hasOwnProperty(nt)&&(M=S[nt],M!=null)&&(nt==="selected"?h.selected=M&&typeof M!="function"&&typeof M!="symbol":Hr(h,y,nt,M,S,null));return;case"dialog":pr("beforetoggle",h),pr("toggle",h),pr("cancel",h),pr("close",h);break;case"iframe":case"object":pr("load",h);break;case"video":case"audio":for(M=0;M<nv.length;M++)pr(nv[M],h);break;case"image":pr("error",h),pr("load",h);break;case"details":pr("toggle",h);break;case"embed":case"source":case"link":pr("error",h),pr("load",h);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(Nt in S)if(S.hasOwnProperty(Nt)&&(M=S[Nt],M!=null))switch(Nt){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,y));default:Hr(h,y,Nt,M,S,null)}return;default:if(fl(y)){for(Lt in S)S.hasOwnProperty(Lt)&&(M=S[Lt],M!==void 0&&zj(h,y,Lt,M,S,void 0));return}}for(Ue in S)S.hasOwnProperty(Ue)&&(M=S[Ue],M!=null&&Hr(h,y,Ue,M,S,null))}function Zce(h,y,S,M){switch(y){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var q=null,Z=null,ke=null,Ue=null,nt=null,Nt=null,Lt=null;for(Dt in S){var It=S[Dt];if(S.hasOwnProperty(Dt)&&It!=null)switch(Dt){case"checked":break;case"value":break;case"defaultValue":nt=It;default:M.hasOwnProperty(Dt)||Hr(h,y,Dt,null,M,It)}}for(var Ct in M){var Dt=M[Ct];if(It=S[Ct],M.hasOwnProperty(Ct)&&(Dt!=null||It!=null))switch(Ct){case"type":Z=Dt;break;case"name":q=Dt;break;case"checked":Nt=Dt;break;case"defaultChecked":Lt=Dt;break;case"value":ke=Dt;break;case"defaultValue":Ue=Dt;break;case"children":case"dangerouslySetInnerHTML":if(Dt!=null)throw Error(r(137,y));break;default:Dt!==It&&Hr(h,y,Ct,Dt,M,It)}}Pa(h,ke,Ue,nt,Nt,Lt,Z,q);return;case"select":Dt=ke=Ue=Ct=null;for(Z in S)if(nt=S[Z],S.hasOwnProperty(Z)&&nt!=null)switch(Z){case"value":break;case"multiple":Dt=nt;default:M.hasOwnProperty(Z)||Hr(h,y,Z,null,M,nt)}for(q in M)if(Z=M[q],nt=S[q],M.hasOwnProperty(q)&&(Z!=null||nt!=null))switch(q){case"value":Ct=Z;break;case"defaultValue":Ue=Z;break;case"multiple":ke=Z;default:Z!==nt&&Hr(h,y,q,Z,M,nt)}y=Ue,S=ke,M=Dt,Ct!=null?ua(h,!!S,Ct,!1):!!M!=!!S&&(y!=null?ua(h,!!S,y,!0):ua(h,!!S,S?[]:"",!1));return;case"textarea":Dt=Ct=null;for(Ue in S)if(q=S[Ue],S.hasOwnProperty(Ue)&&q!=null&&!M.hasOwnProperty(Ue))switch(Ue){case"value":break;case"children":break;default:Hr(h,y,Ue,null,M,q)}for(ke in M)if(q=M[ke],Z=S[ke],M.hasOwnProperty(ke)&&(q!=null||Z!=null))switch(ke){case"value":Ct=q;break;case"defaultValue":Dt=q;break;case"children":break;case"dangerouslySetInnerHTML":if(q!=null)throw Error(r(91));break;default:q!==Z&&Hr(h,y,ke,q,M,Z)}Zr(h,Ct,Dt);return;case"option":for(var gn in S)Ct=S[gn],S.hasOwnProperty(gn)&&Ct!=null&&!M.hasOwnProperty(gn)&&(gn==="selected"?h.selected=!1:Hr(h,y,gn,null,M,Ct));for(nt in M)Ct=M[nt],Dt=S[nt],M.hasOwnProperty(nt)&&Ct!==Dt&&(Ct!=null||Dt!=null)&&(nt==="selected"?h.selected=Ct&&typeof Ct!="function"&&typeof Ct!="symbol":Hr(h,y,nt,Ct,M,Dt));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 Fn in S)Ct=S[Fn],S.hasOwnProperty(Fn)&&Ct!=null&&!M.hasOwnProperty(Fn)&&Hr(h,y,Fn,null,M,Ct);for(Nt in M)if(Ct=M[Nt],Dt=S[Nt],M.hasOwnProperty(Nt)&&Ct!==Dt&&(Ct!=null||Dt!=null))switch(Nt){case"children":case"dangerouslySetInnerHTML":if(Ct!=null)throw Error(r(137,y));break;default:Hr(h,y,Nt,Ct,M,Dt)}return;default:if(fl(y)){for(var qr in S)Ct=S[qr],S.hasOwnProperty(qr)&&Ct!==void 0&&!M.hasOwnProperty(qr)&&zj(h,y,qr,void 0,M,Ct);for(Lt in M)Ct=M[Lt],Dt=S[Lt],!M.hasOwnProperty(Lt)||Ct===Dt||Ct===void 0&&Dt===void 0||zj(h,y,Lt,Ct,M,Dt);return}}for(var ft in S)Ct=S[ft],S.hasOwnProperty(ft)&&Ct!=null&&!M.hasOwnProperty(ft)&&Hr(h,y,ft,null,M,Ct);for(It in M)Ct=M[It],Dt=S[It],!M.hasOwnProperty(It)||Ct===Dt||Ct==null&&Dt==null||Hr(h,y,It,Ct,M,Dt)}function $B(h){switch(h){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Jce(){if(typeof performance.getEntriesByType=="function"){for(var h=0,y=0,S=performance.getEntriesByType("resource"),M=0;M<S.length;M++){var q=S[M],Z=q.transferSize,ke=q.initiatorType,Ue=q.duration;if(Z&&Ue&&$B(ke)){for(ke=0,Ue=q.responseEnd,M+=1;M<S.length;M++){var nt=S[M],Nt=nt.startTime;if(Nt>Ue)break;var Lt=nt.transferSize,It=nt.initiatorType;Lt&&$B(It)&&(nt=nt.responseEnd,ke+=Lt*(nt<Ue?1:(Ue-Nt)/(nt-Nt)))}if(--M,y+=8*(Z+ke)/(q.duration/1e3),h++,10<h)break}}if(0<h)return y/h/1e6}return navigator.connection&&(h=navigator.connection.downlink,typeof h=="number")?h:5}var Uj=null,Bj=null;function g_(h){return h.nodeType===9?h:h.ownerDocument}function VB(h){switch(h){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function GB(h,y){if(h===0)switch(y){case"svg":return 1;case"math":return 2;default:return 0}return h===1&&y==="foreignObject"?0:h}function Hj(h,y){return h==="textarea"||h==="noscript"||typeof y.children=="string"||typeof y.children=="number"||typeof y.children=="bigint"||typeof y.dangerouslySetInnerHTML=="object"&&y.dangerouslySetInnerHTML!==null&&y.dangerouslySetInnerHTML.__html!=null}var qj=null;function ede(){var h=window.event;return h&&h.type==="popstate"?h===qj?!1:(qj=h,!0):(qj=null,!1)}var WB=typeof setTimeout=="function"?setTimeout:void 0,tde=typeof clearTimeout=="function"?clearTimeout:void 0,KB=typeof Promise=="function"?Promise:void 0,nde=typeof queueMicrotask=="function"?queueMicrotask:typeof KB<"u"?function(h){return KB.resolve(null).then(h).catch(rde)}:WB;function rde(h){setTimeout(function(){throw h})}function Vm(h){return h==="head"}function XB(h,y){var S=y,M=0;do{var q=S.nextSibling;if(h.removeChild(S),q&&q.nodeType===8)if(S=q.data,S==="/$"||S==="/&"){if(M===0){h.removeChild(q),ab(y);return}M--}else if(S==="$"||S==="$?"||S==="$~"||S==="$!"||S==="&")M++;else if(S==="html")av(h.ownerDocument.documentElement);else if(S==="head"){S=h.ownerDocument.head,av(S);for(var Z=S.firstChild;Z;){var ke=Z.nextSibling,Ue=Z.nodeName;Z[rt]||Ue==="SCRIPT"||Ue==="STYLE"||Ue==="LINK"&&Z.rel.toLowerCase()==="stylesheet"||S.removeChild(Z),Z=ke}}else S==="body"&&av(h.ownerDocument.body);S=q}while(S);ab(y)}function YB(h,y){var S=h;h=0;do{var M=S.nextSibling;if(S.nodeType===1?y?(S._stashedDisplay=S.style.display,S.style.display="none"):(S.style.display=S._stashedDisplay||"",S.getAttribute("style")===""&&S.removeAttribute("style")):S.nodeType===3&&(y?(S._stashedText=S.nodeValue,S.nodeValue=""):S.nodeValue=S._stashedText||""),M&&M.nodeType===8)if(S=M.data,S==="/$"){if(h===0)break;h--}else S!=="$"&&S!=="$?"&&S!=="$~"&&S!=="$!"||h++;S=M}while(S)}function $j(h){var y=h.firstChild;for(y&&y.nodeType===10&&(y=y.nextSibling);y;){var S=y;switch(y=y.nextSibling,S.nodeName){case"HTML":case"HEAD":case"BODY":$j(S),Le(S);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(S.rel.toLowerCase()==="stylesheet")continue}h.removeChild(S)}}function ade(h,y,S,M){for(;h.nodeType===1;){var q=S;if(h.nodeName.toLowerCase()!==y.toLowerCase()){if(!M&&(h.nodeName!=="INPUT"||h.type!=="hidden"))break}else if(M){if(!h[rt])switch(y){case"meta":if(!h.hasAttribute("itemprop"))break;return h;case"link":if(Z=h.getAttribute("rel"),Z==="stylesheet"&&h.hasAttribute("data-precedence"))break;if(Z!==q.rel||h.getAttribute("href")!==(q.href==null||q.href===""?null:q.href)||h.getAttribute("crossorigin")!==(q.crossOrigin==null?null:q.crossOrigin)||h.getAttribute("title")!==(q.title==null?null:q.title))break;return h;case"style":if(h.hasAttribute("data-precedence"))break;return h;case"script":if(Z=h.getAttribute("src"),(Z!==(q.src==null?null:q.src)||h.getAttribute("type")!==(q.type==null?null:q.type)||h.getAttribute("crossorigin")!==(q.crossOrigin==null?null:q.crossOrigin))&&Z&&h.hasAttribute("async")&&!h.hasAttribute("itemprop"))break;return h;default:return h}}else if(y==="input"&&h.type==="hidden"){var Z=q.name==null?null:""+q.name;if(q.type==="hidden"&&h.getAttribute("name")===Z)return h}else return h;if(h=Al(h.nextSibling),h===null)break}return null}function ide(h,y,S){if(y==="")return null;for(;h.nodeType!==3;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!S||(h=Al(h.nextSibling),h===null))return null;return h}function QB(h,y){for(;h.nodeType!==8;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!y||(h=Al(h.nextSibling),h===null))return null;return h}function Vj(h){return h.data==="$?"||h.data==="$~"}function Gj(h){return h.data==="$!"||h.data==="$?"&&h.ownerDocument.readyState!=="loading"}function sde(h,y){var S=h.ownerDocument;if(h.data==="$~")h._reactRetry=y;else if(h.data!=="$?"||S.readyState!=="loading")y();else{var M=function(){y(),S.removeEventListener("DOMContentLoaded",M)};S.addEventListener("DOMContentLoaded",M),h._reactRetry=M}}function Al(h){for(;h!=null;h=h.nextSibling){var y=h.nodeType;if(y===1||y===3)break;if(y===8){if(y=h.data,y==="$"||y==="$!"||y==="$?"||y==="$~"||y==="&"||y==="F!"||y==="F")break;if(y==="/$"||y==="/&")return null}}return h}var Wj=null;function ZB(h){h=h.nextSibling;for(var y=0;h;){if(h.nodeType===8){var S=h.data;if(S==="/$"||S==="/&"){if(y===0)return Al(h.nextSibling);y--}else S!=="$"&&S!=="$!"&&S!=="$?"&&S!=="$~"&&S!=="&"||y++}h=h.nextSibling}return null}function JB(h){h=h.previousSibling;for(var y=0;h;){if(h.nodeType===8){var S=h.data;if(S==="$"||S==="$!"||S==="$?"||S==="$~"||S==="&"){if(y===0)return h;y--}else S!=="/$"&&S!=="/&"||y++}h=h.previousSibling}return null}function e8(h,y,S){switch(y=g_(S),h){case"html":if(h=y.documentElement,!h)throw Error(r(452));return h;case"head":if(h=y.head,!h)throw Error(r(453));return h;case"body":if(h=y.body,!h)throw Error(r(454));return h;default:throw Error(r(451))}}function av(h){for(var y=h.attributes;y.length;)h.removeAttributeNode(y[0]);Le(h)}var jl=new Map,t8=new Set;function b_(h){return typeof h.getRootNode=="function"?h.getRootNode():h.nodeType===9?h:h.ownerDocument}var cu=ee.d;ee.d={f:ode,r:lde,D:cde,C:dde,L:ude,m:mde,X:pde,S:hde,M:fde};function ode(){var h=cu.f(),y=l_();return h||y}function lde(h){var y=Ce(h);y!==null&&y.tag===5&&y.type==="form"?xU(y):cu.r(h)}var tb=typeof document>"u"?null:document;function n8(h,y,S){var M=tb;if(M&&typeof y=="string"&&y){var q=Sn(y);q='link[rel="'+h+'"][href="'+q+'"]',typeof S=="string"&&(q+='[crossorigin="'+S+'"]'),t8.has(q)||(t8.add(q),h={rel:h,crossOrigin:S,href:y},M.querySelector(q)===null&&(y=M.createElement("link"),ts(y,"link",h),Xe(y),M.head.appendChild(y)))}}function cde(h){cu.D(h),n8("dns-prefetch",h,null)}function dde(h,y){cu.C(h,y),n8("preconnect",h,y)}function ude(h,y,S){cu.L(h,y,S);var M=tb;if(M&&h&&y){var q='link[rel="preload"][as="'+Sn(y)+'"]';y==="image"&&S&&S.imageSrcSet?(q+='[imagesrcset="'+Sn(S.imageSrcSet)+'"]',typeof S.imageSizes=="string"&&(q+='[imagesizes="'+Sn(S.imageSizes)+'"]')):q+='[href="'+Sn(h)+'"]';var Z=q;switch(y){case"style":Z=nb(h);break;case"script":Z=rb(h)}jl.has(Z)||(h=m({rel:"preload",href:y==="image"&&S&&S.imageSrcSet?void 0:h,as:y},S),jl.set(Z,h),M.querySelector(q)!==null||y==="style"&&M.querySelector(iv(Z))||y==="script"&&M.querySelector(sv(Z))||(y=M.createElement("link"),ts(y,"link",h),Xe(y),M.head.appendChild(y)))}}function mde(h,y){cu.m(h,y);var S=tb;if(S&&h){var M=y&&typeof y.as=="string"?y.as:"script",q='link[rel="modulepreload"][as="'+Sn(M)+'"][href="'+Sn(h)+'"]',Z=q;switch(M){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":Z=rb(h)}if(!jl.has(Z)&&(h=m({rel:"modulepreload",href:h},y),jl.set(Z,h),S.querySelector(q)===null)){switch(M){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(S.querySelector(sv(Z)))return}M=S.createElement("link"),ts(M,"link",h),Xe(M),S.head.appendChild(M)}}}function hde(h,y,S){cu.S(h,y,S);var M=tb;if(M&&h){var q=Je(M).hoistableStyles,Z=nb(h);y=y||"default";var ke=q.get(Z);if(!ke){var Ue={loading:0,preload:null};if(ke=M.querySelector(iv(Z)))Ue.loading=5;else{h=m({rel:"stylesheet",href:h,"data-precedence":y},S),(S=jl.get(Z))&&Kj(h,S);var nt=ke=M.createElement("link");Xe(nt),ts(nt,"link",h),nt._p=new Promise(function(Nt,Lt){nt.onload=Nt,nt.onerror=Lt}),nt.addEventListener("load",function(){Ue.loading|=1}),nt.addEventListener("error",function(){Ue.loading|=2}),Ue.loading|=4,x_(ke,y,M)}ke={type:"stylesheet",instance:ke,count:1,state:Ue},q.set(Z,ke)}}}function pde(h,y){cu.X(h,y);var S=tb;if(S&&h){var M=Je(S).hoistableScripts,q=rb(h),Z=M.get(q);Z||(Z=S.querySelector(sv(q)),Z||(h=m({src:h,async:!0},y),(y=jl.get(q))&&Xj(h,y),Z=S.createElement("script"),Xe(Z),ts(Z,"link",h),S.head.appendChild(Z)),Z={type:"script",instance:Z,count:1,state:null},M.set(q,Z))}}function fde(h,y){cu.M(h,y);var S=tb;if(S&&h){var M=Je(S).hoistableScripts,q=rb(h),Z=M.get(q);Z||(Z=S.querySelector(sv(q)),Z||(h=m({src:h,async:!0,type:"module"},y),(y=jl.get(q))&&Xj(h,y),Z=S.createElement("script"),Xe(Z),ts(Z,"link",h),S.head.appendChild(Z)),Z={type:"script",instance:Z,count:1,state:null},M.set(q,Z))}}function r8(h,y,S,M){var q=(q=$.current)?b_(q):null;if(!q)throw Error(r(446));switch(h){case"meta":case"title":return null;case"style":return typeof S.precedence=="string"&&typeof S.href=="string"?(y=nb(S.href),S=Je(q).hoistableStyles,M=S.get(y),M||(M={type:"style",instance:null,count:0,state:null},S.set(y,M)),M):{type:"void",instance:null,count:0,state:null};case"link":if(S.rel==="stylesheet"&&typeof S.href=="string"&&typeof S.precedence=="string"){h=nb(S.href);var Z=Je(q).hoistableStyles,ke=Z.get(h);if(ke||(q=q.ownerDocument||q,ke={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},Z.set(h,ke),(Z=q.querySelector(iv(h)))&&!Z._p&&(ke.instance=Z,ke.state.loading=5),jl.has(h)||(S={rel:"preload",as:"style",href:S.href,crossOrigin:S.crossOrigin,integrity:S.integrity,media:S.media,hrefLang:S.hrefLang,referrerPolicy:S.referrerPolicy},jl.set(h,S),Z||gde(q,h,S,ke.state))),y&&M===null)throw Error(r(528,""));return ke}if(y&&M!==null)throw Error(r(529,""));return null;case"script":return y=S.async,S=S.src,typeof S=="string"&&y&&typeof y!="function"&&typeof y!="symbol"?(y=rb(S),S=Je(q).hoistableScripts,M=S.get(y),M||(M={type:"script",instance:null,count:0,state:null},S.set(y,M)),M):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,h))}}function nb(h){return'href="'+Sn(h)+'"'}function iv(h){return'link[rel="stylesheet"]['+h+"]"}function a8(h){return m({},h,{"data-precedence":h.precedence,precedence:null})}function gde(h,y,S,M){h.querySelector('link[rel="preload"][as="style"]['+y+"]")?M.loading=1:(y=h.createElement("link"),M.preload=y,y.addEventListener("load",function(){return M.loading|=1}),y.addEventListener("error",function(){return M.loading|=2}),ts(y,"link",S),Xe(y),h.head.appendChild(y))}function rb(h){return'[src="'+Sn(h)+'"]'}function sv(h){return"script[async]"+h}function i8(h,y,S){if(y.count++,y.instance===null)switch(y.type){case"style":var M=h.querySelector('style[data-href~="'+Sn(S.href)+'"]');if(M)return y.instance=M,Xe(M),M;var q=m({},S,{"data-href":S.href,"data-precedence":S.precedence,href:null,precedence:null});return M=(h.ownerDocument||h).createElement("style"),Xe(M),ts(M,"style",q),x_(M,S.precedence,h),y.instance=M;case"stylesheet":q=nb(S.href);var Z=h.querySelector(iv(q));if(Z)return y.state.loading|=4,y.instance=Z,Xe(Z),Z;M=a8(S),(q=jl.get(q))&&Kj(M,q),Z=(h.ownerDocument||h).createElement("link"),Xe(Z);var ke=Z;return ke._p=new Promise(function(Ue,nt){ke.onload=Ue,ke.onerror=nt}),ts(Z,"link",M),y.state.loading|=4,x_(Z,S.precedence,h),y.instance=Z;case"script":return Z=rb(S.src),(q=h.querySelector(sv(Z)))?(y.instance=q,Xe(q),q):(M=S,(q=jl.get(Z))&&(M=m({},S),Xj(M,q)),h=h.ownerDocument||h,q=h.createElement("script"),Xe(q),ts(q,"link",M),h.head.appendChild(q),y.instance=q);case"void":return null;default:throw Error(r(443,y.type))}else y.type==="stylesheet"&&(y.state.loading&4)===0&&(M=y.instance,y.state.loading|=4,x_(M,S.precedence,h));return y.instance}function x_(h,y,S){for(var M=S.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),q=M.length?M[M.length-1]:null,Z=q,ke=0;ke<M.length;ke++){var Ue=M[ke];if(Ue.dataset.precedence===y)Z=Ue;else if(Z!==q)break}Z?Z.parentNode.insertBefore(h,Z.nextSibling):(y=S.nodeType===9?S.head:S,y.insertBefore(h,y.firstChild))}function Kj(h,y){h.crossOrigin==null&&(h.crossOrigin=y.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=y.referrerPolicy),h.title==null&&(h.title=y.title)}function Xj(h,y){h.crossOrigin==null&&(h.crossOrigin=y.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=y.referrerPolicy),h.integrity==null&&(h.integrity=y.integrity)}var y_=null;function s8(h,y,S){if(y_===null){var M=new Map,q=y_=new Map;q.set(S,M)}else q=y_,M=q.get(S),M||(M=new Map,q.set(S,M));if(M.has(h))return M;for(M.set(h,null),S=S.getElementsByTagName(h),q=0;q<S.length;q++){var Z=S[q];if(!(Z[rt]||Z[Pt]||h==="link"&&Z.getAttribute("rel")==="stylesheet")&&Z.namespaceURI!=="http://www.w3.org/2000/svg"){var ke=Z.getAttribute(y)||"";ke=h+ke;var Ue=M.get(ke);Ue?Ue.push(Z):M.set(ke,[Z])}}return M}function o8(h,y,S){h=h.ownerDocument||h,h.head.insertBefore(S,y==="title"?h.querySelector("head > title"):null)}function bde(h,y,S){if(S===1||y.itemProp!=null)return!1;switch(h){case"meta":case"title":return!0;case"style":if(typeof y.precedence!="string"||typeof y.href!="string"||y.href==="")break;return!0;case"link":if(typeof y.rel!="string"||typeof y.href!="string"||y.href===""||y.onLoad||y.onError)break;return y.rel==="stylesheet"?(h=y.disabled,typeof y.precedence=="string"&&h==null):!0;case"script":if(y.async&&typeof y.async!="function"&&typeof y.async!="symbol"&&!y.onLoad&&!y.onError&&y.src&&typeof y.src=="string")return!0}return!1}function l8(h){return!(h.type==="stylesheet"&&(h.state.loading&3)===0)}function xde(h,y,S,M){if(S.type==="stylesheet"&&(typeof M.media!="string"||matchMedia(M.media).matches!==!1)&&(S.state.loading&4)===0){if(S.instance===null){var q=nb(M.href),Z=y.querySelector(iv(q));if(Z){y=Z._p,y!==null&&typeof y=="object"&&typeof y.then=="function"&&(h.count++,h=v_.bind(h),y.then(h,h)),S.state.loading|=4,S.instance=Z,Xe(Z);return}Z=y.ownerDocument||y,M=a8(M),(q=jl.get(q))&&Kj(M,q),Z=Z.createElement("link"),Xe(Z);var ke=Z;ke._p=new Promise(function(Ue,nt){ke.onload=Ue,ke.onerror=nt}),ts(Z,"link",M),S.instance=Z}h.stylesheets===null&&(h.stylesheets=new Map),h.stylesheets.set(S,y),(y=S.state.preload)&&(S.state.loading&3)===0&&(h.count++,S=v_.bind(h),y.addEventListener("load",S),y.addEventListener("error",S))}}var Yj=0;function yde(h,y){return h.stylesheets&&h.count===0&&S_(h,h.stylesheets),0<h.count||0<h.imgCount?function(S){var M=setTimeout(function(){if(h.stylesheets&&S_(h,h.stylesheets),h.unsuspend){var Z=h.unsuspend;h.unsuspend=null,Z()}},6e4+y);0<h.imgBytes&&Yj===0&&(Yj=62500*Jce());var q=setTimeout(function(){if(h.waitingForImages=!1,h.count===0&&(h.stylesheets&&S_(h,h.stylesheets),h.unsuspend)){var Z=h.unsuspend;h.unsuspend=null,Z()}},(h.imgBytes>Yj?50:800)+y);return h.unsuspend=S,function(){h.unsuspend=null,clearTimeout(M),clearTimeout(q)}}:null}function v_(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)S_(this,this.stylesheets);else if(this.unsuspend){var h=this.unsuspend;this.unsuspend=null,h()}}}var w_=null;function S_(h,y){h.stylesheets=null,h.unsuspend!==null&&(h.count++,w_=new Map,y.forEach(vde,h),w_=null,v_.call(h))}function vde(h,y){if(!(y.state.loading&4)){var S=w_.get(h);if(S)var M=S.get(null);else{S=new Map,w_.set(h,S);for(var q=h.querySelectorAll("link[data-precedence],style[data-precedence]"),Z=0;Z<q.length;Z++){var ke=q[Z];(ke.nodeName==="LINK"||ke.getAttribute("media")!=="not all")&&(S.set(ke.dataset.precedence,ke),M=ke)}M&&S.set(null,M)}q=y.instance,ke=q.getAttribute("data-precedence"),Z=S.get(ke)||M,Z===M&&S.set(null,q),S.set(ke,q),this.count++,M=v_.bind(this),q.addEventListener("load",M),q.addEventListener("error",M),Z?Z.parentNode.insertBefore(q,Z.nextSibling):(h=h.nodeType===9?h.head:h,h.insertBefore(q,h.firstChild)),y.state.loading|=4}}var ov={$$typeof:C,Provider:null,Consumer:null,_currentValue:ue,_currentValue2:ue,_threadCount:0};function wde(h,y,S,M,q,Z,ke,Ue,nt){this.tag=1,this.containerInfo=h,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=ut(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ut(0),this.hiddenUpdates=ut(null),this.identifierPrefix=M,this.onUncaughtError=q,this.onCaughtError=Z,this.onRecoverableError=ke,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=nt,this.incompleteTransitions=new Map}function c8(h,y,S,M,q,Z,ke,Ue,nt,Nt,Lt,It){return h=new wde(h,y,S,ke,nt,Nt,Lt,It,Ue),y=1,Z===!0&&(y|=24),Z=Bo(3,null,null,y),h.current=Z,Z.stateNode=h,y=AA(),y.refCount++,h.pooledCache=y,y.refCount++,Z.memoizedState={element:M,isDehydrated:S,cache:y},DA(Z),h}function d8(h){return h?(h=Fg,h):Fg}function u8(h,y,S,M,q,Z){q=d8(q),M.context===null?M.context=q:M.pendingContext=q,M=Fm(y),M.payload={element:S},Z=Z===void 0?null:Z,Z!==null&&(M.callback=Z),S=Rm(h,M,y),S!==null&&(yo(S,h,y),zy(S,h,y))}function m8(h,y){if(h=h.memoizedState,h!==null&&h.dehydrated!==null){var S=h.retryLane;h.retryLane=S!==0&&S<y?S:y}}function Qj(h,y){m8(h,y),(h=h.alternate)&&m8(h,y)}function h8(h){if(h.tag===13||h.tag===31){var y=Ep(h,67108864);y!==null&&yo(y,h,67108864),Qj(h,67108864)}}function p8(h){if(h.tag===13||h.tag===31){var y=Go();y=Xt(y);var S=Ep(h,y);S!==null&&yo(S,h,y),Qj(h,y)}}var __=!0;function Sde(h,y,S,M){var q=ie.T;ie.T=null;var Z=ee.p;try{ee.p=2,Zj(h,y,S,M)}finally{ee.p=Z,ie.T=q}}function _de(h,y,S,M){var q=ie.T;ie.T=null;var Z=ee.p;try{ee.p=8,Zj(h,y,S,M)}finally{ee.p=Z,ie.T=q}}function Zj(h,y,S,M){if(__){var q=Jj(M);if(q===null)Ij(h,y,M,k_,S),g8(h,M);else if(Nde(q,h,y,S,M))M.stopPropagation();else if(g8(h,M),y&4&&-1<kde.indexOf(h)){for(;q!==null;){var Z=Ce(q);if(Z!==null)switch(Z.tag){case 3:if(Z=Z.stateNode,Z.current.memoizedState.isDehydrated){var ke=He(Z.pendingLanes);if(ke!==0){var Ue=Z;for(Ue.pendingLanes|=2,Ue.entangledLanes|=2;ke;){var nt=1<<31-Be(ke);Ue.entanglements[1]|=nt,ke&=~nt}nd(Z),(Mr&6)===0&&(s_=R()+500,tv(0))}}break;case 31:case 13:Ue=Ep(Z,2),Ue!==null&&yo(Ue,Z,2),l_(),Qj(Z,2)}if(Z=Jj(M),Z===null&&Ij(h,y,M,k_,S),Z===q)break;q=Z}q!==null&&M.stopPropagation()}else Ij(h,y,M,null,S)}}function Jj(h){return h=Ki(h),eM(h)}var k_=null;function eM(h){if(k_=null,h=Oe(h),h!==null){var y=s(h);if(y===null)h=null;else{var S=y.tag;if(S===13){if(h=o(y),h!==null)return h;h=null}else if(S===31){if(h=l(y),h!==null)return h;h=null}else if(S===3){if(y.stateNode.current.memoizedState.isDehydrated)return y.tag===3?y.stateNode.containerInfo:null;h=null}else y!==h&&(h=null)}}return k_=h,null}function f8(h){switch(h){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(ae()){case _e:return 2;case Se:return 8;case ye:case Ae:return 32;case ve:return 268435456;default:return 32}default:return 32}}var tM=!1,Gm=null,Wm=null,Km=null,lv=new Map,cv=new Map,Xm=[],kde="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 g8(h,y){switch(h){case"focusin":case"focusout":Gm=null;break;case"dragenter":case"dragleave":Wm=null;break;case"mouseover":case"mouseout":Km=null;break;case"pointerover":case"pointerout":lv.delete(y.pointerId);break;case"gotpointercapture":case"lostpointercapture":cv.delete(y.pointerId)}}function dv(h,y,S,M,q,Z){return h===null||h.nativeEvent!==Z?(h={blockedOn:y,domEventName:S,eventSystemFlags:M,nativeEvent:Z,targetContainers:[q]},y!==null&&(y=Ce(y),y!==null&&h8(y)),h):(h.eventSystemFlags|=M,y=h.targetContainers,q!==null&&y.indexOf(q)===-1&&y.push(q),h)}function Nde(h,y,S,M,q){switch(y){case"focusin":return Gm=dv(Gm,h,y,S,M,q),!0;case"dragenter":return Wm=dv(Wm,h,y,S,M,q),!0;case"mouseover":return Km=dv(Km,h,y,S,M,q),!0;case"pointerover":var Z=q.pointerId;return lv.set(Z,dv(lv.get(Z)||null,h,y,S,M,q)),!0;case"gotpointercapture":return Z=q.pointerId,cv.set(Z,dv(cv.get(Z)||null,h,y,S,M,q)),!0}return!1}function b8(h){var y=Oe(h.target);if(y!==null){var S=s(y);if(S!==null){if(y=S.tag,y===13){if(y=o(S),y!==null){h.blockedOn=y,Ft(h.priority,function(){p8(S)});return}}else if(y===31){if(y=l(S),y!==null){h.blockedOn=y,Ft(h.priority,function(){p8(S)});return}}else if(y===3&&S.stateNode.current.memoizedState.isDehydrated){h.blockedOn=S.tag===3?S.stateNode.containerInfo:null;return}}}h.blockedOn=null}function N_(h){if(h.blockedOn!==null)return!1;for(var y=h.targetContainers;0<y.length;){var S=Jj(h.nativeEvent);if(S===null){S=h.nativeEvent;var M=new S.constructor(S.type,S);Kc=M,S.target.dispatchEvent(M),Kc=null}else return y=Ce(S),y!==null&&h8(y),h.blockedOn=S,!1;y.shift()}return!0}function x8(h,y,S){N_(h)&&S.delete(y)}function Cde(){tM=!1,Gm!==null&&N_(Gm)&&(Gm=null),Wm!==null&&N_(Wm)&&(Wm=null),Km!==null&&N_(Km)&&(Km=null),lv.forEach(x8),cv.forEach(x8)}function C_(h,y){h.blockedOn===y&&(h.blockedOn=null,tM||(tM=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Cde)))}var P_=null;function y8(h){P_!==h&&(P_=h,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){P_===h&&(P_=null);for(var y=0;y<h.length;y+=3){var S=h[y],M=h[y+1],q=h[y+2];if(typeof M!="function"){if(eM(M||S)===null)continue;break}var Z=Ce(S);Z!==null&&(h.splice(y,3),y-=3,JA(Z,{pending:!0,data:q,method:S.method,action:M},M,q))}}))}function ab(h){function y(nt){return C_(nt,h)}Gm!==null&&C_(Gm,h),Wm!==null&&C_(Wm,h),Km!==null&&C_(Km,h),lv.forEach(y),cv.forEach(y);for(var S=0;S<Xm.length;S++){var M=Xm[S];M.blockedOn===h&&(M.blockedOn=null)}for(;0<Xm.length&&(S=Xm[0],S.blockedOn===null);)b8(S),S.blockedOn===null&&Xm.shift();if(S=(h.ownerDocument||h).$$reactFormReplay,S!=null)for(M=0;M<S.length;M+=3){var q=S[M],Z=S[M+1],ke=q[pt]||null;if(typeof Z=="function")ke||y8(S);else if(ke){var Ue=null;if(Z&&Z.hasAttribute("formAction")){if(q=Z,ke=Z[pt]||null)Ue=ke.formAction;else if(eM(q)!==null)continue}else Ue=ke.action;typeof Ue=="function"?S[M+1]=Ue:(S.splice(M,3),M-=3),y8(S)}}}function v8(){function h(Z){Z.canIntercept&&Z.info==="react-transition"&&Z.intercept({handler:function(){return new Promise(function(ke){return q=ke})},focusReset:"manual",scroll:"manual"})}function y(){q!==null&&(q(),q=null),M||setTimeout(S,20)}function S(){if(!M&&!navigation.transition){var Z=navigation.currentEntry;Z&&Z.url!=null&&navigation.navigate(Z.url,{state:Z.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var M=!1,q=null;return navigation.addEventListener("navigate",h),navigation.addEventListener("navigatesuccess",y),navigation.addEventListener("navigateerror",y),setTimeout(S,100),function(){M=!0,navigation.removeEventListener("navigate",h),navigation.removeEventListener("navigatesuccess",y),navigation.removeEventListener("navigateerror",y),q!==null&&(q(),q=null)}}}function nM(h){this._internalRoot=h}T_.prototype.render=nM.prototype.render=function(h){var y=this._internalRoot;if(y===null)throw Error(r(409));var S=y.current,M=Go();u8(S,M,h,y,null,null)},T_.prototype.unmount=nM.prototype.unmount=function(){var h=this._internalRoot;if(h!==null){this._internalRoot=null;var y=h.containerInfo;u8(h.current,2,null,h,null,null),l_(),y[Wt]=null}};function T_(h){this._internalRoot=h}T_.prototype.unstable_scheduleHydration=function(h){if(h){var y=Ge();h={blockedOn:null,target:h,priority:y};for(var S=0;S<Xm.length&&y!==0&&y<Xm[S].priority;S++);Xm.splice(S,0,h),S===0&&b8(h)}};var w8=e.version;if(w8!=="19.2.4")throw Error(r(527,w8,"19.2.4"));ee.findDOMNode=function(h){var y=h._reactInternals;if(y===void 0)throw typeof h.render=="function"?Error(r(188)):(h=Object.keys(h).join(","),Error(r(268,h)));return h=d(y),h=h!==null?u(h):null,h=h===null?null:h.stateNode,h};var Pde={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:ie,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var A_=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!A_.isDisabled&&A_.supportsFiber)try{Ee=A_.inject(Pde),Te=A_}catch{}}return mv.createRoot=function(h,y){if(!i(h))throw Error(r(299));var S=!1,M="",q=TU,Z=AU,ke=jU;return y!=null&&(y.unstable_strictMode===!0&&(S=!0),y.identifierPrefix!==void 0&&(M=y.identifierPrefix),y.onUncaughtError!==void 0&&(q=y.onUncaughtError),y.onCaughtError!==void 0&&(Z=y.onCaughtError),y.onRecoverableError!==void 0&&(ke=y.onRecoverableError)),y=c8(h,1,!1,null,null,S,M,null,q,Z,ke,v8),h[Wt]=y.current,Oj(h),new nM(y)},mv.hydrateRoot=function(h,y,S){if(!i(h))throw Error(r(299));var M=!1,q="",Z=TU,ke=AU,Ue=jU,nt=null;return S!=null&&(S.unstable_strictMode===!0&&(M=!0),S.identifierPrefix!==void 0&&(q=S.identifierPrefix),S.onUncaughtError!==void 0&&(Z=S.onUncaughtError),S.onCaughtError!==void 0&&(ke=S.onCaughtError),S.onRecoverableError!==void 0&&(Ue=S.onRecoverableError),S.formState!==void 0&&(nt=S.formState)),y=c8(h,1,!0,y,S??null,M,q,nt,Z,ke,Ue,v8),y.context=d8(null),S=y.current,M=Go(),M=Xt(M),q=Fm(M),q.callback=null,Rm(S,q,M),S=M,y.current.lanes=S,vt(y,S),nd(y),h[Wt]=y.current,Oj(h),new T_(y)},mv.version="19.2.4",mv}var M8;function Ide(){if(M8)return iM.exports;M8=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(),iM.exports=Ode(),iM.exports}var zde=Ide();const Hn=t=>typeof t=="string",hv=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},E8=t=>t==null?"":""+t,Ude=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},Bde=/###/g,D8=t=>t&&t.indexOf("###")>-1?t.replace(Bde,"."):t,F8=t=>!t||Hn(t),c0=(t,e,n)=>{const r=Hn(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(F8(t))return{};const s=D8(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return F8(t)?{}:{obj:t,k:D8(r[i])}},R8=(t,e,n)=>{const{obj:r,k:i}=c0(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),l=c0(t,o,Object);for(;l.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),l=c0(t,o,Object),l?.obj&&typeof l.obj[`${l.k}.${s}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${s}`]=n},Hde=(t,e,n,r)=>{const{obj:i,k:s}=c0(t,e,Object);i[s]=i[s]||[],i[s].push(n)},Zk=(t,e)=>{const{obj:n,k:r}=c0(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},qde=(t,e,n)=>{const r=Zk(t,n);return r!==void 0?r:Zk(e,n)},EY=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?Hn(t[r])||t[r]instanceof String||Hn(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):EY(t[r],e[r],n):t[r]=e[r]);return t},ib=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var $de={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Vde=t=>Hn(t)?t.replace(/[&<>"'\/]/g,e=>$de[e]):t;class Gde{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 Wde=[" ",",","?","!",";"],Kde=new Gde(20),Xde=(t,e,n)=>{e=e||"",n=n||"";const r=Wde.filter(o=>e.indexOf(o)<0&&n.indexOf(o)<0);if(r.length===0)return!0;const i=Kde.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!i.test(t);if(!s){const o=t.indexOf(n);o>0&&!i.test(t.substring(0,o))&&(s=!0)}return s},A3=(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 i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let o,l="";for(let c=s;c<r.length;++c)if(c!==s&&(l+=n),l+=r[c],o=i[l],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<r.length-1)continue;s+=c-s+1;break}i=o}return i},L0=t=>t?.replace("_","-"),Yde={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 Jk{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||Yde,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,i){return i&&!this.debug?null:(Hn(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Jk(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Jk(this.logger,e)}}var yd=new Jk;let kP=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+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(([i,s])=>{for(let o=0;o<s;o++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i.apply(i,[e,...n])})}};class L8 extends kP{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,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.indexOf(".")>-1?l=e.split("."):(l=[e,n],r&&(Array.isArray(r)?l.push(...r):Hn(r)&&s?l.push(...r.split(s)):l.push(r)));const c=Zk(this.data,l);return!c&&!n&&!r&&e.indexOf(".")>-1&&(e=l[0],n=l[1],r=l.slice(2).join(".")),c||!o||!Hn(r)?c:A3(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,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("."),i=n,n=l[1]),this.addNamespaces(n),R8(this.data,l,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(Hn(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,o={silent:!1,skipCopy:!1}){let l=[e,n];e.indexOf(".")>-1&&(l=e.split("."),i=r,r=n,n=l[1]),this.addNamespaces(n);let c=Zk(this.data,l)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?EY(c,r,s):c={...c,...r},R8(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(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var DY={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const FY=Symbol("i18next/PATH_KEY");function Qde(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===FY?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function j3(t,e){const{[FY]:n}=t(Qde());return n.join(e?.keySeparator??".")}const O8={},cM=t=>!Hn(t)&&typeof t!="boolean"&&typeof t!="number";class eN extends kP{constructor(e,n={}){super(),Ude(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=yd.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=cM(i.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 i=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&&!Xde(e,r,i);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:Hn(s)?[s]:s};const d=e.split(r);(r!==i||r===i&&this.options.ns.indexOf(d[0])>-1)&&(s=d.shift()),e=d.join(i)}return{key:e,namespaces:Hn(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=j3(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]);const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],i),d=c[c.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const m=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(m?.toLowerCase()==="cimode")return p?s?{res:`${d}${u}${l}`,usedKey:l,exactUsedKey:l,usedLng:m,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:`${d}${u}${l}`:s?{res:l,usedKey:l,exactUsedKey:l,usedLng:m,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:l;const f=this.resolve(e,i);let x=f?.res;const v=f?.usedKey||l,g=f?.exactUsedKey||l,b=["[object Number]","[object Function]","[object RegExp]"],_=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,C=!this.i18nFormat||this.i18nFormat.handleAsObject,P=i.count!==void 0&&!Hn(i.count),N=eN.hasDefaultValue(i),A=P?this.pluralResolver.getSuffix(m,i.count,i):"",T=i.ordinal&&P?this.pluralResolver.getSuffix(m,i.count,{ordinal:!1}):"",F=P&&!i.ordinal&&i.count===0,k=F&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${A}`]||i[`defaultValue${T}`]||i.defaultValue;let D=x;C&&!x&&N&&(D=k);const H=cM(D),z=Object.prototype.toString.apply(D);if(C&&D&&H&&b.indexOf(z)<0&&!(Hn(_)&&Array.isArray(D))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const X=this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,D,{...i,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return s?(f.res=X,f.usedParams=this.getUsedParamsDetails(i),f):X}if(o){const X=Array.isArray(D),L=X?[]:{},ne=X?g:v;for(const ie in D)if(Object.prototype.hasOwnProperty.call(D,ie)){const ee=`${ne}${o}${ie}`;N&&!x?L[ie]=this.translate(ee,{...i,defaultValue:cM(k)?k[ie]:void 0,joinArrays:!1,ns:c}):L[ie]=this.translate(ee,{...i,joinArrays:!1,ns:c}),L[ie]===ee&&(L[ie]=D[ie])}x=L}}else if(C&&Hn(_)&&Array.isArray(x))x=x.join(_),x&&(x=this.extendTranslation(x,e,i,r));else{let X=!1,L=!1;!this.isValidLookup(x)&&N&&(X=!0,x=k),this.isValidLookup(x)||(L=!0,x=l);const ie=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&L?void 0:x,ee=N&&k!==x&&this.options.updateMissing;if(L||X||ee){if(this.logger.log(ee?"updateKey":"missingKey",m,d,l,ee?k:x),o){const W=this.resolve(l,{...i,keySeparator:!1});W&&W.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 ue=[];const le=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&le&&le[0])for(let W=0;W<le.length;W++)ue.push(le[W]);else this.options.saveMissingTo==="all"?ue=this.languageUtils.toResolveHierarchy(i.lng||this.language):ue.push(i.lng||this.language);const oe=(W,re,ce)=>{const xe=N&&ce!==x?ce:ie;this.options.missingKeyHandler?this.options.missingKeyHandler(W,d,re,xe,ee,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(W,d,re,xe,ee,i),this.emit("missingKey",W,d,re,x)};this.options.saveMissing&&(this.options.saveMissingPlurals&&P?ue.forEach(W=>{const re=this.pluralResolver.getSuffixes(W,i);F&&i[`defaultValue${this.options.pluralSeparator}zero`]&&re.indexOf(`${this.options.pluralSeparator}zero`)<0&&re.push(`${this.options.pluralSeparator}zero`),re.forEach(ce=>{oe([W],l+ce,i[`defaultValue${ce}`]||k)})}):oe(ue,l,k))}x=this.extendTranslation(x,e,i,f,r),L&&x===l&&this.options.appendNamespaceToMissingKey&&(x=`${d}${u}${l}`),(L||X)&&this.options.parseMissingKeyHandler&&(x=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,X?x:void 0,i))}return s?(f.res=x,f.usedParams=this.getUsedParamsDetails(i),f):x}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=Hn(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(c){const m=e.match(this.interpolator.nestingRegexp);d=m&&m.length}let u=r.replace&&!Hn(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),c){const m=e.match(this.interpolator.nestingRegexp),p=m&&m.length;d<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...m)=>s?.[0]===m[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${m[0]} in key: ${n[0]}`),null):this.translate(...m,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,l=Hn(o)?[o]:o;return e!=null&&l?.length&&r.applyPostProcessor!==!1&&(e=DY.handle(l,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,o,l;return Hn(e)&&(e=[e]),e.forEach(c=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(c,n),u=d.key;i=u;let m=d.namespaces;this.options.fallbackNS&&(m=m.concat(this.options.fallbackNS));const p=n.count!==void 0&&!Hn(n.count),f=p&&!n.ordinal&&n.count===0,x=n.context!==void 0&&(Hn(n.context)||typeof n.context=="number")&&n.context!=="",v=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);m.forEach(g=>{this.isValidLookup(r)||(l=g,!O8[`${v[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(l)&&(O8[`${v[0]}-${g}`]=!0,this.logger.warn(`key "${i}" 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(b=>{if(this.isValidLookup(r))return;o=b;const _=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(_,u,b,g,n);else{let P;p&&(P=this.pluralResolver.getSuffix(b,n.count,n));const N=`${this.options.pluralSeparator}zero`,A=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&P.indexOf(A)===0&&_.push(u+P.replace(A,this.options.pluralSeparator)),_.push(u+P),f&&_.push(u+N)),x){const T=`${u}${this.options.contextSeparator||"_"}${n.context}`;_.push(T),p&&(n.ordinal&&P.indexOf(A)===0&&_.push(T+P.replace(A,this.options.pluralSeparator)),_.push(T+P),f&&_.push(T+N))}}let C;for(;C=_.pop();)this.isValidLookup(r)||(s=C,r=this.getResource(b,g,C,n))}))})}),{res:r,usedKey:i,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,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!Hn(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}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 I8{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=yd.create("languageUtils")}getScriptPartFromCode(e){if(e=L0(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=L0(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(Hn(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 i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;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)),Hn(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),i=[],s=o=>{o&&(this.isSupportedCode(o)?i.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return Hn(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))):Hn(e)&&s(this.formatLanguageCode(e)),r.forEach(o=>{i.indexOf(o)<0&&s(this.formatLanguageCode(o))}),i}}const z8={zero:0,one:1,two:2,few:3,many:4,other:5},U8={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Zde{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=yd.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=L0(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),U8;if(!e.match(/-|_/))return U8;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(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>z8[i]-z8[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const B8=(t,e,n,r=".",i=!0)=>{let s=qde(t,e,n);return!s&&i&&Hn(n)&&(s=A3(t,n,r),s===void 0&&(s=A3(e,n,r))),s},dM=t=>t.replace(/\$/g,"$$$$");class Jde{constructor(e={}){this.logger=yd.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:i,prefix:s,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:m,nestingPrefix:p,nestingPrefixEscaped:f,nestingSuffix:x,nestingSuffixEscaped:v,nestingOptionsSeparator:g,maxReplaces:b,alwaysFormat:_}=e.interpolation;this.escape=n!==void 0?n:Vde,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ib(s):o||"{{",this.suffix=l?ib(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":m||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=p?ib(p):f||ib("$t("),this.nestingSuffix=x?ib(x):v||ib(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=b||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,i){let s,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=f=>{if(f.indexOf(this.formatSeparator)<0){const b=B8(n,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,r,{...i,...n,interpolationkey:f}):b}const x=f.split(this.formatSeparator),v=x.shift().trim(),g=x.join(this.formatSeparator).trim();return this.format(B8(n,c,v,this.options.keySeparator,this.options.ignoreJSONStructure),g,r,{...i,...n,interpolationkey:v})};this.resetRegExp();const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,m=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>dM(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?dM(this.escape(f)):dM(f)}].forEach(f=>{for(l=0;s=f.regex.exec(e);){const x=s[1].trim();if(o=d(x),o===void 0)if(typeof u=="function"){const g=u(e,s,i);o=Hn(g)?g:""}else if(i&&Object.prototype.hasOwnProperty.call(i,x))o="";else if(m){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!Hn(o)&&!this.useRawValueToEscape&&(o=E8(o));const v=f.safeValue(o);if(e=e.replace(s[0],v),m?(f.regex.lastIndex+=o.length,f.regex.lastIndex-=s[0].length):f.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,o;const l=(c,d)=>{const u=this.nestingOptionsSeparator;if(c.indexOf(u)<0)return c;const m=c.split(new RegExp(`${u}[ ]*{`));let p=`{${m[1]}`;c=m[0],p=this.interpolate(p,o);const f=p.match(/'/g),x=p.match(/"/g);((f?.length??0)%2===0&&!x||x.length%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(v){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,v),`${c}${u}${p}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!Hn(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const d=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(d!==-1&&(c=i[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,d)),s=n(l.call(this,i[1].trim(),o),o),s&&i[0]===e&&!Hn(s))return s;Hn(s)||(s=E8(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((u,m)=>this.format(u,m,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const eue=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);e==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):e==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),d=c.join(":").trim().replace(/^'+|'+$/g,""),u=l.trim();n[u]||(n[u]=d),d==="false"&&(n[u]=!1),d==="true"&&(n[u]=!0),isNaN(d)||(n[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},H8=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=r+JSON.stringify(s);let l=e[o];return l||(l=t(L0(r),i),e[o]=l),l(n)}},tue=t=>(e,n,r)=>t(L0(n),r)(e);class nue{constructor(e={}){this.logger=yd.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?H8:tue;this.formats={number:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return l=>o.format(l)}),currency:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return l=>o.format(l)}),datetime:r((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return l=>o.format(l)}),relativetime:r((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return l=>o.format(l,s.range||"day")}),list:r((i,s)=>{const o=new Intl.ListFormat(i,{...s});return l=>o.format(l)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=H8(n)}format(e,n,r,i={}){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:d,formatOptions:u}=eue(c);if(this.formats[d]){let m=l;try{const p=i?.formatParams?.[i.interpolationkey]||{},f=p.locale||p.lng||i.locale||i.lng||r;m=this.formats[d](l,f,{...u,...i,...p})}catch(p){this.logger.warn(p)}return m}else this.logger.warn(`there was no format function for ${d}`);return l},e)}}const rue=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class aue extends kP{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=yd.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(e,n,r,i){const s={},o={},l={},c={};return e.forEach(d=>{let u=!0;n.forEach(m=>{const p=`${d}|${m}`;!r.reload&&this.store.hasResourceBundle(d,m)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?o[p]===void 0&&(o[p]=!0):(this.state[p]=1,u=!1,o[p]===void 0&&(o[p]=!0),s[p]===void 0&&(s[p]=!0),c[m]===void 0&&(c[m]=!0)))}),u||(l[d]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const i=e.split("|"),s=i[0],o=i[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=>{Hde(c.loaded,[s],o),rue(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(d=>{l[d]||(l[d]={});const u=c.loaded[d];u.length&&u.forEach(m=>{l[d][m]===void 0&&(l[d][m]=!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,i=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:i,wait:s,callback:o});return}this.readingCalls++;const l=(d,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const m=this.waitingReads.shift();this.read(m.lng,m.ns,m.fcName,m.tried,m.wait,m.callback)}if(d&&u&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,r,i+1,s*2,o)},s);return}o(d,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const d=c(e,n);d&&typeof d.then=="function"?d.then(u=>l(null,u)).catch(l):l(null,d)}catch(d){l(d)}return}return c(e,n,l)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();Hn(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Hn(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),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("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,o),!o&&l&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,l),this.loaded(e,o,l)})}saveMissing(e,n,r,i,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},d=this.backend.create.bind(this.backend);if(d.length<6)try{let u;d.length===5?u=d(e,n,r,i,c):u=d(e,n,r,i),u&&typeof u.then=="function"?u.then(m=>l(null,m)).catch(l):l(null,u)}catch(u){l(u)}else d(e,n,r,i,l,c)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const q8=()=>({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]),Hn(t[1])&&(e.defaultValue=t[1]),Hn(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}),$8=t=>(Hn(t.ns)&&(t.ns=[t.ns]),Hn(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Hn(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),M_=()=>{},iue=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class d0 extends kP{constructor(e={},n){if(super(),this.options=$8(e),this.services={},this.logger=yd,this.modules={external:[]},iue(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&&(Hn(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const r=q8();this.options={...r,...this.options,...$8(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 i=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?yd.init(i(this.modules.logger),this.options):yd.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=nue;const u=new I8(this.options);this.store=new L8(this.options.resources,this.options);const m=this.services;m.logger=yd,m.resourceStore=this.store,m.languageUtils=u,m.pluralResolver=new Zde(u,{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"),d&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(m.formatter=i(d),m.formatter.init&&m.formatter.init(m,this.options),this.options.interpolation.format=m.formatter.format.bind(m.formatter)),m.interpolator=new Jde(this.options),m.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},m.backendConnector=new aue(i(this.modules.backend),m.resourceStore,m,this.options),m.backendConnector.on("*",(f,...x)=>{this.emit(f,...x)}),this.modules.languageDetector&&(m.languageDetector=i(this.modules.languageDetector),m.languageDetector.init&&m.languageDetector.init(m,this.options.detection,this.options)),this.modules.i18nFormat&&(m.i18nFormat=i(this.modules.i18nFormat),m.i18nFormat.init&&m.i18nFormat.init(this)),this.translator=new eN(this.services,this.options),this.translator.on("*",(f,...x)=>{this.emit(f,...x)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,n||(n=M_),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[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(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const l=hv(),c=()=>{const d=(u,m)=>{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(m),n(u,m)};if(this.languages&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,n=M_){let r=n;const i=Hn(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.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(d=>{d!=="cimode"&&s.indexOf(d)<0&&s.push(d)})};i?o(i):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 i=hv();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=M_),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}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"&&DY.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=hv();this.emit("languageChanging",e);const i=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&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...d)=>this.t(...d)),n&&n(l,(...d)=>this.t(...d))},o=l=>{!e&&!l&&this.services.languageDetector&&(l=[]);const c=Hn(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(Hn(l)?[l]:l);d&&(this.language||i(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,u=>{s(u,d)})};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 i=(s,o,...l)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([s,o].concat(l)):c={...o},c.lng=c.lng||i.lng,c.lngs=c.lngs||i.lngs,c.ns=c.ns||i.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||r||i.keyPrefix);const d=this.options.keySeparator||".";let u;return c.keyPrefix&&Array.isArray(s)?u=s.map(m=>(typeof m=="function"&&(m=j3(m,{...this.options,...o})),`${c.keyPrefix}${d}${m}`)):(typeof s=="function"&&(s=j3(s,{...this.options,...o})),u=c.keyPrefix?`${c.keyPrefix}${d}${s}`:s),this.t(u,c)};return Hn(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=r,i}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],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const d=this.services.backendConnector.state[`${l}|${c}`];return d===-1||d===0||d===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)&&(!i||o(s,e)))}loadNamespaces(e,n){const r=hv();return this.options.ns?(Hn(e)&&(e=[e]),e.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=hv();Hn(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(o=>i.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=i.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 i=new Intl.Locale(e);if(i&&i.getTextInfo){const s=i.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 I8(q8());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 d0(e,n);return r.createInstance=d0.createInstance,r}cloneInstance(e={},n=M_){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new d0(i);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,d)=>(c[d]={...this.store.data[d]},c[d]=Object.keys(c[d]).reduce((u,m)=>(u[m]={...c[d][m]},u),c[d]),c),{});s.store=new L8(l,i),s.services.resourceStore=s.store}return s.translator=new eN(s.services,i),s.translator.on("*",(l,...c)=>{s.emit(l,...c)}),s.init(i,n),s.translator.options=i,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 lo=d0.createInstance();lo.createInstance;lo.dir;lo.init;lo.loadResources;lo.reloadResources;lo.use;lo.changeLanguage;lo.getFixedT;lo.t;lo.exists;lo.setDefaultNamespace;lo.hasLoadedNamespace;lo.loadNamespaces;lo.loadLanguages;const sue=(t,e,n,r)=>{const i=[n,{code:e,...r||{}}];if(t?.services?.logger?.forward)return t.services.logger.forward(i,"warn","react-i18next::",!0);$f(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),t?.services?.logger?.warn?t.services.logger.warn(...i):console?.warn&&console.warn(...i)},V8={},RY=(t,e,n,r)=>{$f(n)&&V8[n]||($f(n)&&(V8[n]=new Date),sue(t,e,n,r))},LY=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},M3=(t,e,n)=>{t.loadNamespaces(e,LY(t,n))},G8=(t,e,n,r)=>{if($f(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return M3(t,n,r);n.forEach(i=>{t.options.ns.indexOf(i)<0&&t.options.ns.push(i)}),t.loadLanguages(e,LY(t,r))},oue=(t,e,n={})=>!e.languages||!e.languages.length?(RY(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(r,i)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!i(r.isLanguageChangingTo,t))return!1}}),$f=t=>typeof t=="string",lue=t=>typeof t=="object"&&t!==null,cue=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,due={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},uue=t=>due[t],mue=t=>t.replace(cue,uue);let E3={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:mue,transDefaultProps:void 0};const hue=(t={})=>{E3={...E3,...t}},pue=()=>E3;let OY;const fue=t=>{OY=t},gue=()=>OY,bue={type:"3rdParty",init(t){hue(t.options.react),fue(t)}},xue=w.createContext();class yue{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var uM={exports:{}},mM={};var W8;function vue(){if(W8)return mM;W8=1;var t=xg();function e(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,i=t.useEffect,s=t.useLayoutEffect,o=t.useDebugValue;function l(m,p){var f=p(),x=r({inst:{value:f,getSnapshot:p}}),v=x[0].inst,g=x[1];return s(function(){v.value=f,v.getSnapshot=p,c(v)&&g({inst:v})},[m,f,p]),i(function(){return c(v)&&g({inst:v}),m(function(){c(v)&&g({inst:v})})},[m]),o(f),f}function c(m){var p=m.getSnapshot;m=m.value;try{var f=p();return!n(m,f)}catch{return!0}}function d(m,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return mM.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,mM}var K8;function IY(){return K8||(K8=1,uM.exports=vue()),uM.exports}var eO=IY();const wue=(t,e)=>$f(e)?e:lue(e)&&$f(e.defaultValue)?e.defaultValue:Array.isArray(t)?t[t.length-1]:t,Sue={t:wue,ready:!1},_ue=()=>()=>{},Rt=(t,e={})=>{const{i18n:n}=e,{i18n:r,defaultNS:i}=w.useContext(xue)||{},s=n||r||gue();s&&!s.reportNamespaces&&(s.reportNamespaces=new yue),s||RY(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=w.useMemo(()=>({...pue(),...s?.options?.react,...e}),[s,e]),{useSuspense:l,keyPrefix:c}=o,d=i||s?.options?.defaultNS,u=$f(d)?[d]:d||["translation"],m=w.useMemo(()=>u,u);s?.reportNamespaces?.addUsedNamespaces?.(m);const p=w.useRef(0),f=w.useCallback(k=>{if(!s)return _ue;const{bindI18n:D,bindI18nStore:H}=o,z=()=>{p.current+=1,k()};return D&&s.on(D,z),H&&s.store.on(H,z),()=>{D&&D.split(" ").forEach(X=>s.off(X,z)),H&&H.split(" ").forEach(X=>s.store.off(X,z))}},[s,o]),x=w.useRef(),v=w.useCallback(()=>{if(!s)return Sue;const k=!!(s.isInitialized||s.initializedStoreOnce)&&m.every(ne=>oue(ne,s,o)),D=e.lng||s.language,H=p.current,z=x.current;if(z&&z.ready===k&&z.lng===D&&z.keyPrefix===c&&z.revision===H)return z;const L={t:s.getFixedT(D,o.nsMode==="fallback"?m:m[0],c),ready:k,lng:D,keyPrefix:c,revision:H};return x.current=L,L},[s,m,c,o,e.lng]),[g,b]=w.useState(0),{t:_,ready:C}=eO.useSyncExternalStore(f,v,v);w.useEffect(()=>{if(s&&!C&&!l){const k=()=>b(D=>D+1);e.lng?G8(s,e.lng,m,k):M3(s,m,k)}},[s,e.lng,m,C,l,g]);const P=s||{},N=w.useRef(null),A=w.useRef(),T=k=>{const D=Object.getOwnPropertyDescriptors(k);D.__original&&delete D.__original;const H=Object.create(Object.getPrototypeOf(k),D);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:k,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},F=w.useMemo(()=>{const k=P,D=k?.language;let H=k;k&&(N.current&&N.current.__original===k?A.current!==D?(H=T(k),N.current=H,A.current=D):H=N.current:(H=T(k),N.current=H,A.current=D));const z=[_,H,C];return z.t=_,z.i18n=H,z.ready=C,z},[_,P,C,P.resolvedLanguage,P.language,P.languages]);if(s&&l&&!C)throw new Promise(k=>{const D=()=>k();e.lng?G8(s,e.lng,m,D):M3(s,m,D)});return F},{slice:kue,forEach:Nue}=[];function Cue(t){return Nue.call(kue.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Pue(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 X8=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Tue=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${i}`;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(!X8.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!X8.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},Y8={create(t,e,n,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+n*60*1e3)),r&&(i.domain=r),document.cookie=Tue(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let i=n[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var Aue={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return Y8.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&Y8.create(n,t,r,i,s)}},jue={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}},Mue={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const s=i.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=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let sb=null;const Q8=()=>{if(sb!==null)return sb;try{if(sb=typeof window<"u"&&window.localStorage!==null,!sb)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{sb=!1}return sb};var Eue={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&Q8())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&Q8()&&window.localStorage.setItem(n,t)}};let ob=null;const Z8=()=>{if(ob!==null)return ob;try{if(ob=typeof window<"u"&&window.sessionStorage!==null,!ob)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{ob=!1}return ob};var Due={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&Z8())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&Z8()&&window.sessionStorage.setItem(n,t)}},Fue={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},Rue={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}},Lue={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}},Oue={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 zY=!1;try{document.cookie,zY=!0}catch{}const UY=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];zY||UY.splice(1,1);const Iue=()=>({order:UY,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class BY{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=Cue(n,this.options||{},Iue()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Aue),this.addDetector(jue),this.addDetector(Eue),this.addDetector(Due),this.addDetector(Fue),this.addDetector(Rue),this.addDetector(Lue),this.addDetector(Oue),this.addDetector(Mue)}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 i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(r=>r!=null&&!Pue(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)}))}}BY.type="languageDetector";const zue={nav:{printers:"Printers",archives:"Archives",queue:"Queue",stats:"Statistics",profiles:"Profiles",maintenance:"Maintenance",projects:"Projects",inventory:"Filament",files:"File Manager",notifications:"Notifications",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",uploading:"Uploading...",uploadFailed:"Upload failed",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",back:"Back",copy:"Copy",copied:"Copied!",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",problem:"Problem",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",search:"Search printers...",noSearchResults:"No printers match your search or filters",filter:{allStatuses:"All statuses",allLocations:"All locations"},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",files:"Files",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",forceRefresh:"Force Refresh",forceRefreshSuccess:"Refresh requested",mqttDebug:"MQTT Debug",printerInformation:"Printer Information",copyToClipboard:"Copy",copied:"Copied!",state:"State",wifiSignalLabel:"WiFi Signal",developerMode:"Developer Mode",enabled:"Enabled",disabled:"Disabled",addedOn:"Added",sdCard:"SD Card",inserted:"Inserted",notInserted:"Not inserted",totalPrintHours:"Print Hours",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",missingSpoolAssignment:"Print started on {{printer}}. Missing spool assignment for: {{slots}}",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",failedToSetSpeed:"Failed to set print speed",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",noCamera:"You do not have permission to view cameras"},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"},bulk:{select:"Select",selectAll:"Select All",selectByLocation:"Select by Location",selected:"{{count}} selected",actions:{stop:"Stop",pause:"Pause",resume:"Resume",clearPlate:"Clear Bed",clearHMS:"Clear Notifications"},confirm:{stopTitle:"Stop {{count}} Prints",stopMessage:"This will cancel active prints on {{count}} printer(s). This action cannot be undone.",stopButton:"Stop All",pauseTitle:"Pause {{count}} Prints",pauseMessage:"This will pause active prints on {{count}} printer(s).",pauseButton:"Pause All",clearPlateTitle:"Clear {{count}} Print Beds",clearPlateMessage:"This will clear the print bed on {{count}} printer(s) and may trigger queued jobs.",clearPlateButton:"Clear All"},success:"{{action}} completed on {{count}} printer(s)",partial:"{{succeeded}} succeeded, {{failed}} failed",noneApplicable:"No selected printers are in the right state for this action",selectByState:"Select by State"},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"},drying:{start:"Start Drying",stop:"Stop Drying",temperature:"Temperature",duration:"Duration",hours:"hours",timeRemaining:"{{time}} left",active:"Drying",notSupported:"Drying not supported",powerRequired:"Connect AMS power adapter to enable drying",startingDrying:"Starting drying...",stoppingDrying:"Stopping drying...",rotateTray:"Rotate spool during drying"},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"},speed:{title:"Print Speed",silent:"Silent (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},airduct:{title:"Airduct Mode",cooling:"Cooling",heating:"Heating"},noSdCard:"No SD",door:{open:"Open",closed:"Closed"},fans:{partCooling:"Part Cooling Fan",auxiliary:"Auxiliary Fan",chamber:"Chamber Fan"},clickToViewHmsErrors:"Click to view HMS errors",estimatedCompletion:"Estimated completion time",plateNumber:"Plate {{number}}",slotOptions:"Slot options",amsPopup:{friendlyName:"AMS Name",friendlyNamePlaceholder:"e.g. AMS Friendly Name",serialNumber:"Serial Number",firmwareVersion:"Firmware",save:"Save",clear:"Clear",noEditPermission:"You do not have permission to rename AMS units"},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.",availableVersions:"Available versions",usable:"Usable",unavailable:"Unavailable",installed:"Installed",newerBadge:"newer",olderBadge:"older",currentBadge:"current"},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",incompatibleFile:"This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",dropNotPrintable:"Only .gcode and .gcode.3mf files can be printed",dropToPrint:"Drop to print",cannotPrint:"Printer busy"},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",originalPrintNotVisible:"Original print not visible - try clearing filters",noArchivesYet:"No archives yet",prints:"prints",pagination:{showing:"Showing",to:"to",of:"of",show:"Show",page:"Page",all:"All"},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",hideDuplicates:"Hide Duplicates",viewOriginalPrint:"Click to view original print (#{{id}})",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",queueSelectedPlates:"Queue {{count}} Plates",selectAllPlates:"Select All {{count}} Plates",deselectAll:"Deselect All",printQueued:"Print queued",itemsQueued:"{{count}} items queued",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.",sjf:{label:"SJF",tooltip:"Shortest Job First — scheduler prioritizes shorter prints"},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}}",quantity:"Quantity",quantityHint:"Creates {{count}} queue items",activeBatches:"Active Batches",batchProgress:"{{completed}} of {{total}} completed",cancelBatch:"Cancel Remaining",batchCancelled:"Remaining batch items cancelled",cancelBatchConfirmTitle:"Cancel Batch",cancelBatchConfirmMessage:"Cancel all remaining pending items in this batch?",batch:"Batch",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",gcodeInjection:"G-code"},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"},timeline:{listView:"List",timelineView:"Timeline",unassigned:"Unassigned",noData:"No scheduled prints for this day",allDoneBy:"All prints estimated done by {{time}}",staged:"Staged",filterAll:"Show All",filterPrinting:"Printing",filterQueued:"Queued",time:{anyMoment:"any moment",minutesLeft:"{{minutes}}m left",hoursLeft:"{{hours}}h left",hoursMinutesLeft:"{{hours}}h {{minutes}}m left"},day:{previous:"Previous day",next:"Next day",today:"Today"}},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",printStartedRemaining:"{{completed}} print(s) started, {{remaining}} more sending..."}},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",energyWarmingUpTooltip:"Energy tracking is still collecting hourly snapshots. Date-range totals will become accurate once at least one snapshot exists before the selected range. Early values may undercount.",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",noPrintDataInRange:"No print data in selected range",periodFilament:"Period Filament",periodCost:"Period Cost",avgPerPrint:"Avg per Print",usageOverTime:"Usage Over Time",filamentByWeight:"Weight",printDuration:"Print Duration",printerUtilization:"Printer Utilization",filamentSuccess:"Success by Material",printHabits:"Print Habits",printTimeOfDay:"Print Time of Day",colorDistribution:"Color Distribution",noColorData:"No color data available",records:"Records",longestPrint:"Longest Print",heaviestPrint:"Heaviest Print",mostExpensivePrint:"Most Expensive",busiestDay:"Busiest Day",successStreak:"Success Streak",streakPrint:"consecutive print",streakPrints:"{{count}} consecutive prints",printerStats:"Printer Stats",hours:"hours",avgPrints:"Avg. prints",noArchiveData:"No print data available",filamentByTime:"Time",avgWeight:"Avg. weight",avgTime:"Avg. time",filamentByPrints:"Prints",timeframe:{today:"Today","this-week":"This Week","this-month":"This Month","last-7":"Last 7 Days","last-30":"Last 30 Days","last-90":"Last 90 Days","this-year":"This Year","all-time":"All Time",custom:"Custom Range",from:"From",to:"To"},allUsers:"All Users",noUser:"No User (System)",filterByUser:"Filter by User"},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",lubricateSteelRods:"Lubricate Steel Rods",cleanSteelRods:"Clean Steel 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",queue:"Workflow",filament:"Filament",network:"Network",apiKeys:"API Keys",virtualPrinter:"Virtual Printer",spoolbuddy:"SpoolBuddy",failureDetection:"Failure Detection",users:"Authentication",backup:"Backup",emailAuth:"Email Authentication",ldap:"LDAP",twoFa:"Two-Factor Auth",oidc:"SSO / OIDC"},spoolbuddy:{infoTitle:"SpoolBuddy devices",infoBody:"SpoolBuddy kiosks register themselves automatically via heartbeat. Unregister a device here if it is no longer in use or if a stale duplicate was left behind by a daemon crash.",duplicatesTitle:"{{count}} devices registered",duplicatesBody:"Only the first registered device is used by the kiosk UI. If one of these is a stale duplicate from a crash, unregister it — an online device will re-register itself on its next heartbeat.",empty:"No SpoolBuddy devices registered yet.",online:"Online",offline:"Offline",unregister:"Unregister",unregisterSuccess:"Device unregistered",unregisterError:"Failed to unregister device",confirmTitle:"Unregister SpoolBuddy device?",confirmBody:'This will remove "{{hostname}}" ({{deviceId}}) from the database. If the device is online, it will re-register itself on its next heartbeat.',ipAddress:"IP address",firmware:"Firmware",lastSeen:"Last seen",daemonUptime:"Daemon uptime",systemUptime:"System uptime",never:"never",nfc:"NFC",scale:"Scale",cpuTemp:"CPU temp",memory:"Memory",disk:"Disk",update:"Update",updateConfirmTitle:"Update Spoolbuddy daemon?",updateConfirmBody:'Trigger a software update on "{{hostname}}"? The daemon will restart once the update is applied.',restartBrowser:"Restart Browser",restartBrowserConfirmTitle:"Restart kiosk browser?",restartBrowserConfirmBody:'Restart the kiosk browser on "{{hostname}}"? The display will blank briefly.',restartDaemon:"Restart Daemon",restartDaemonConfirmTitle:"Restart Spoolbuddy daemon?",restartDaemonConfirmBody:'Restart the Spoolbuddy daemon on "{{hostname}}"? The device will go offline for a few seconds.',reboot:"Reboot",rebootConfirmTitle:"Reboot device?",rebootConfirmBody:'Reboot "{{hostname}}"? The device will be offline for around a minute.',shutdown:"Shutdown",shutdownConfirmTitle:"Shutdown device?",shutdownConfirmBody:'Shutdown "{{hostname}}"? You will need physical access to power it back on.',commandConfirm:"Confirm",commandQueued:"Command queued",commandError:"Failed to send command"},ldap:{title:"LDAP Authentication",enabledDesc:"LDAP authentication is enabled",disabledDesc:"LDAP authentication is disabled",disabledHint:"Configure and save LDAP settings below, then enable.",enabled:"LDAP authentication enabled",disabled:"LDAP authentication disabled",feature1:"Users can login with LDAP credentials",feature2:"Local admin account remains as fallback",feature3:"LDAP groups are mapped to BamBuddy groups on login",serverConfig:"LDAP Server Configuration",serverUrl:"Server URL",serverUrlHint:"Use ldaps:// for SSL or ldap:// with StartTLS",security:"Security",securityHint:"StartTLS upgrades a plain connection to TLS. LDAPS uses TLS from the start.",bindDn:"Bind DN (Service Account)",bindPassword:"Bind Password",searchBase:"Search Base DN",userFilter:"User Search Filter",userFilterHint:"{username} is replaced with the login username. Use (uid={username}) for OpenLDAP.",autoProvision:"Auto-provision users",autoProvisionHint:"Automatically create a BamBuddy account on first LDAP login",defaultGroup:"Default group",defaultGroupNone:"— None (no fallback) —",defaultGroupHint:"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped LDAP group. Leave empty to leave unmapped users without permissions.",groupMapping:"Group Mapping (JSON)",groupMappingHint:"Map LDAP group DNs to BamBuddy groups. Available groups: ",testConnection:"Test Connection",settingsSaved:"LDAP settings saved",errors:{serverRequired:"LDAP server URL is required",searchBaseRequired:"Search base DN is required",enableAuthFirst:"Enable authentication first",configureLdapFirst:"Save LDAP settings first"}},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",enableAuthFirst:"Please enable authentication first to use email-based features."},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",userNotificationsEnabled:"User Notifications",userNotificationsEnabledDescription:"Enable the user notifications menu and email notifications for print job events. Requires Advanced Authentication.",userNotificationsDisabledHint:"Enable Advanced Authentication to use user notifications.",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.",filamentChecks:"Filament checks",disableFilamentWarnings:"Disable filament warnings",disableFilamentWarningsDesc:"Don't show warnings about insufficient filament when printing or queueing",preferLowestFilament:"Prefer lowest remaining filament",preferLowestFilamentDesc:"When multiple spools match, use the one with the least filament remaining",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)",fairAlsoDryingThreshold:"This threshold is also used to trigger auto-drying when enabled",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",defaultPrintOptions:"Default Print Options",defaultPrintOptionsDescription:"Set default values for print options when starting new prints. These can be overridden per print in the print dialog.",defaultBedLevelling:"Bed Levelling",defaultBedLevellingDesc:"Auto-level bed before print",defaultFlowCali:"Flow Calibration",defaultFlowCaliDesc:"Calibrate extrusion flow",defaultVibrationCali:"Vibration Calibration",defaultVibrationCaliDesc:"Reduce ringing artifacts",defaultLayerInspect:"First Layer Inspection",defaultLayerInspectDesc:"AI inspection of first layer",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Record timelapse video",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Plate-Clear Confirmation",requirePlateClear:"Require plate-clear confirmation",requirePlateClearDescription:"When enabled, the scheduler waits for per-printer plate-clear confirmation before starting queued prints on printers with finished jobs. Disable for farm workflows where plates are verified physically.",gcodeInjection:"G-code Injection",gcodeInjectionDescription:'Configure custom G-code to inject at the start and/or end of prints for auto-print systems like Farmloop, SwapMod, AutoClear, and Printflow 3D. Snippets are configured per printer model and applied when "Inject G-code" is enabled on a queue item.',gcodeInjectionNoPrinters:"No printers found. Add printers to configure G-code snippets.",gcodeStartLabel:"Start G-code",gcodeEndLabel:"End G-code",gcodeStartPlaceholder:"G-code prepended before the print starts...",gcodeEndPlaceholder:"G-code appended after the print ends...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Queue Auto-Drying",queueDryingDescription:"Automatically dry AMS filament when printer is idle between queued prints. Uses humidity threshold above to trigger drying.",queueDryingEnabled:"Enable auto-drying",queueDryingEnabledDescription:"Start AMS drying automatically when printer is idle and humidity is above threshold",queueDryingBlock:"Wait for drying to complete",queueDryingBlockDescription:"Block the print queue until drying finishes. When off, prints take priority over drying.",ambientDryingEnabled:"Ambient drying",ambientDryingEnabledDescription:"Automatically dry filament on idle printers when humidity exceeds threshold, even without queued prints.",dryingPresets:"Drying Presets",dryingPresetsDescription:"Temperature and duration per filament type. AMS 2 Pro uses lower temps, AMS-HT supports higher temps.",dryingFilament:"Filament",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",selectedCount:"{{count}} selected",deleteSelected:"Delete Selected",bulkDeleteConfirm:"Are you sure you want to delete {{count}} entries?",bulkDeleted:"Deleted {{count}} entries",bulkDeleteFailed:"Failed to delete entries"},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",selectedCount:"{{count}} selected",deleteSelected:"Delete Selected",bulkDeleteConfirm:"Are you sure you want to delete {{count}} colors?",bulkDeleted:"Deleted {{count}} colors",bulkDeleteFailed:"Failed to delete colors"},dateFormat:"Date Format",dateFormatUs:"US (MM/DD/YYYY)",dateFormatEu:"EU (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"Time Format",timeFormat12:"12-hour (3:30 PM)",timeFormat24:"24-hour (15:30)",defaultPrinter:"Default Printer",defaultPrinterDescription:"Pre-select this printer for uploads, reprints, and other operations.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Drag items in the sidebar to reorder. Reset to default order here.",setDefault:"Set Default",sidebarOrderSetDefaultHint:"Set default applies the current menu order to users who haven't customized theirs.",sidebarDefaultSet:"Default menu order has been set.",sidebarDefaultCleared:"Default menu order cleared.",sidebarDefaultFailed:"Failed to set default menu order.",reset:"Reset",darkMode:"Dark Mode",lightMode:"Light Mode",active:"(active)",background:"Background",accent:"Accent",style:"Style",bgNeutral:"Neutral",bgWarm:"Warm",bgCool:"Cool",bgOled:"OLED Black",bgSlate:"Slate Blue",bgForest:"Forest Green",accentGreen:"Green",accentTeal:"Teal",accentBlue:"Blue",accentOrange:"Orange",accentPurple:"Purple",accentRed:"Red",styleClassic:"Classic",styleGlow:"Glow",styleVibrant:"Vibrant",themeToggleHint:"Toggle between dark and light mode using the sun/moon icon in the sidebar.",autoArchivePrints:"Auto-archive prints",autoArchiveDescription:"Automatically save 3MF files when prints complete",saveThumbnailsDescription:"Extract and save preview images from 3MF files",captureFinishPhotoDescription:"Take a photo from printer camera when print completes",ffmpegNotInstalled:"ffmpeg not installed",ffmpegRequired:"Camera capture requires ffmpeg. Install it via <brew>brew install ffmpeg</brew> (macOS) or <apt>apt install ffmpeg</apt> (Linux).",camera:"Camera",cameraViewMode:"Camera View Mode",cameraOverlayDescription:"Camera opens in a resizable overlay on the main screen",cameraWindowDescription:"Camera opens in a separate browser window",externalCamerasDescription:"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.",cameraPlaceholderUsb:"Device path (/dev/video0)",cameraPlaceholderUrl:"Camera URL (rtsp://... or http://...)",cameraTypeMjpeg:"MJPEG Stream",cameraTypeRtsp:"RTSP Stream",cameraTypeSnapshot:"HTTP Snapshot",cameraTypeUsb:"USB Camera (V4L2)",cameraRotation:"Rotation",test:"Test",connected:"Connected",disconnected:"Disconnected",currency:"Currency",defaultFilamentCost:"Default filament cost (per kg)",electricityCost:"Electricity cost per kWh",energyDisplayMode:"Energy display mode",energyModePrintDescription:"Dashboard shows sum of energy used during prints",energyModeTotalDescription:"Dashboard shows lifetime energy from smart plugs",fileManager:"File Manager",createArchiveEntry:"Create Archive Entry When Printing",createArchiveEntryDescription:"When printing from File Manager, optionally create an archive entry",lowDiskSpaceWarning:"Low Disk Space Warning",lowDiskSpaceDescription:"Show warning when free disk space falls below this threshold",printerFirmware:"Printer Firmware",checkFirmwareDescription:"Check for printer firmware updates from Bambu Lab",bambuddySoftware:"Bambuddy Software",autoCheckDescription:"Automatically check for new versions on startup",checkNow:"Check now",updateAvailableVersion:"Update available: v{{version}}",releaseNotes:"Release Notes",updateViaDocker:"Update via Docker Compose:",installUpdate:"Install Update",latestVersionRunning:"You're running the latest version",failedToCheckUpdates:"Failed to check for updates: {{error}}",backupRestore:"Backup & Restore",backupRestoreDescription:"Export/import settings and configure GitHub backup",goToBackup:"Go to Backup",externalUrl:"External URL",externalUrlDescription:"The external URL where Bambuddy is accessible. Used for notification images and external integrations.",bambuddyUrl:"Bambuddy URL",externalUrlHint:"Include protocol and port (e.g., http://192.168.1.100:8000)",ftpRetry:"FTP Retry",ftpRetryDescription:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates.",autoRetryDescription:"Automatically retry failed FTP operations",retryAttempts:"Retry attempts",retryDelay:"Retry delay",connectionTimeout:"Connection timeout",time_one:"{{count}} time",time_other:"{{count}} times",second_one:"{{count}} second",second_other:"{{count}} seconds",nSeconds:"{{count}} seconds",increaseForWeakWifi:"Increase for printers with weak WiFi",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities.",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"Long-Lived Access Token",haTokenHint:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token",connectionSuccessful:"Connection Successful",connectionFailed:"Connection Failed",haConnectionSuccess:"Successfully connected to Home Assistant.",haConnectionFailed:"Failed to connect to Home Assistant.",mqttPublishing:"MQTT Publishing",mqttDescription:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems.",mqttEnableDescription:"Publish events to external MQTT broker",brokerHostname:"Broker hostname",port:"Port",usernameOptional:"Username (optional)",passwordOptional:"Password (optional)",topicPrefix:"Topic prefix",topicPrefixHint:"Topics will be: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Prometheus Metrics",prometheusEndpointDescription:"Expose printer metrics at <code>/api/v1/metrics</code> for Prometheus/Grafana monitoring.",bearerTokenOptional:"Bearer Token (optional)",bearerTokenHint:"If set, requests must include <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Connection status",metricsPrinterState:"Printer state (idle/printing/etc)",metricsPrintProgress:"Print progress 0-100%",metricsBedTemp:"Bed temperature",metricsNozzleTemp:"Nozzle temperature",metricsPrintsTotal:"Total prints by result",metricsMore:"...and more (layers, fans, queue, filament usage)",smartPlugsDescription:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers.",allOn:"All On",allOff:"All Off",addSmartPlug:"Add Smart Plug",energySummary:"Energy Summary",currentPower:"Current Power",plugsOnline:"{{reachable}}/{{total}} plugs online",today:"Today",yesterday:"Yesterday",total:"Total",enablePlugsForSummary:"Enable plugs to see energy summary",addNotificationProvider:"Add",systemBadge:"(System)",creating:"Creating...",changing:"Changing...",deleteUserAndItems:"Delete user AND their items",deleteUserKeepItems:"Delete user, keep items (become ownerless)",ok:"OK",twoFa:{totpTitle:"Authenticator App (TOTP)",totpDesc:"Use an authenticator app like Google Authenticator, Aegis or Authy.",emailOtpTitle:"Email OTP",emailOtpDesc:"Send a one-time code to {{email}} when you log in.",emailOtpNoEmail:"Add an email address to your account to enable this method.",addEmailFirst:"Your account has no email address. Ask an admin to add one before enabling Email OTP.",setupTotp:"Set up Authenticator App",setupAuthApp:"Set up Authenticator App",setupInstructions:"Scan the QR code below with your authenticator app, then confirm with a code.",manualEntry:"Can't scan? Enter this secret manually:",scannedContinue:"I've scanned the code — continue",enterCodeToConfirm:"Enter the 6-digit code from your authenticator app to confirm setup.",activate:"Activate",disableTotp:"Disable Authenticator",disableConfirmHint:"Enter a valid TOTP code or a backup code to disable the authenticator.",totpDisabled:"Authenticator app disabled.",emailOtpEnabled:"Email OTP enabled.",emailOtpDisabled:"Email OTP disabled.",smtpRequired:"Please configure and test SMTP settings first.",invalidCode:"Invalid code. Please try again.",enableEmailOtp:"Enable Email OTP",disableEmailOtp:"Disable Email OTP",emailSetupEnterCode:"A verification code has been sent to your email address. Enter it below to confirm you own this inbox.",verifyAndEnable:"Verify & Enable",emailDisablePasswordHint:"Enter your account password to confirm disabling email OTP.",passwordPlaceholder:"Enter your password",backupCodesTitle:"Save your backup codes",backupCodesWarning:"Save these codes somewhere safe. Each code can only be used once and they will not be shown again.",backupCodesRemaining:"{{count}} backup codes remaining",savedCodes:"I've saved my codes",regenBackup:"Regenerate Backup Codes",regenBackupHint:"Enter your current TOTP code to generate 10 new backup codes. All existing backup codes will be invalidated.",newBackupCodes:"New backup codes",linkedAccounts:"Linked SSO Accounts",linkedAccountsDesc:"These external identity providers are linked to your account.",oidcUnlinked:"Account unlinked."},oidc:{title:"SSO / OIDC Providers",desc:"Configure OpenID Connect providers to allow single sign-on via external identity providers.",addProvider:"Add Provider",newProvider:"New Provider",empty:"No OIDC providers configured yet.",created:"Provider created.",updated:"Provider updated.",deleted:"Provider deleted.",deleteTitle:"Delete Provider",deleteMessage:'Delete "{{name}}"? All linked user accounts will be disconnected.',form:{name:"Display Name",issuerUrl:"Issuer URL",clientId:"Client ID",clientSecret:"Client Secret",scopes:"Scopes",iconUrl:"Icon URL (optional)",enabled:"Enabled",autoCreate:"Auto-create users",autoCreateDesc:"Automatically create a local account on first login.",autoLink:"Auto-link existing accounts",autoLinkDesc:"Link existing local accounts by matching email on first login.",secretHint:"leave blank to keep current",secretPlaceholder:"new secret"}}},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",enterEmail:"Please enter your email address",oidcLoginFailed:"OIDC login failed",oidcErrors:{providerError:"The identity provider returned an error",missingParameters:"OIDC callback is missing required parameters",invalidState:"OIDC state is invalid or has already been used",stateExpired:"OIDC login session expired — please try again",providerNotFound:"OIDC provider not found",discoveryFailed:"Failed to fetch OIDC discovery document",invalidDiscovery:"OIDC discovery document is invalid",networkError:"Network error during OIDC token exchange",badResponse:"Unexpected response during OIDC token exchange",noIdToken:"OIDC provider did not return an ID token",validationFailed:"OIDC token validation failed",nonceMismatch:"OIDC nonce mismatch — possible replay attack",missingSubClaim:"OIDC token is missing the sub claim",noLinkedAccount:"No local account is linked to this OIDC identity",accountInactive:"Your account is inactive",userResolutionFailed:"Failed to resolve your account",internalError:"An internal error occurred during OIDC login",tokenExchangeFailed:"OIDC token exchange failed"},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",resetPassword:{title:"Set New Password",subtitle:"Enter and confirm your new password below.",newPassword:"New Password",newPasswordPlaceholder:"At least 8 characters",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Repeat new password",saving:"Saving…",submit:"Set New Password",backToLogin:"Back to login",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 8 characters",resetFailed:"Password reset failed. The link may have expired."},twoFA:{title:"Two-Factor Authentication",subtitle:"Your account is protected with 2FA. Enter the verification code below.",methodAuthenticator:"Authenticator App",methodEmail:"Email Code",methodBackup:"Backup Code",instructionsTotp:"Open your authenticator app and enter the 6-digit code for Bambuddy.",instructionsEmail:"A 6-digit code has been sent to your email address. It expires in 10 minutes.",instructionsEmailNotSent:"Click the button below to receive a verification code via email.",instructionsBackup:"Enter one of your 8-character backup recovery codes. Each code can only be used once.",sendCodeButton:"Send Code via Email",sendingCode:"Sending...",resendCode:"Resend code",codeLabel:"Verification Code",backupCodeLabel:"Backup Code",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"Verify",verifyingButton:"Verifying...",backToLogin:"← Back to login",orContinueWith:"or continue with",signInWith:"Sign in with {{provider}}",enterCode:"Please enter the verification code",sendCodeFailed:"Failed to send verification code",invalidCode:"Invalid code. Please try again."}},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:"Upload failed",zipFilesFailed:"{{count}} files 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",linkExternal:"Link External",linkExternalFolder:"Link External Folder",linkExternalFolderDescription:"Mount a host directory (NAS, USB, network share) into the File Manager. Files are not copied — they are accessed directly from the original path.",externalFolderNamePlaceholder:"e.g., NAS Prints",externalPath:"Host Path",externalPathHelp:"Absolute path to the directory on the Docker host. Must be bind-mounted into the container.",readOnly:"Read Only",readOnlyHelp:"prevents uploads and deletions",showHiddenFiles:"Show hidden files (dotfiles)",externalFolder:"External Folder",scanFolder:"Scan",toast:{folderCreated:"Folder created",folderDeleted:"Folder deleted",fileDeleted:"File deleted",filesDeleted:"Deleted {{count}} files",filesMoved:"Files moved",folderLinked:"Folder linked",folderUnlinked:"Folder unlinked",externalFolderLinked:"External folder linked and scanned",folderScanned:"Scan complete: {{added}} added, {{removed}} removed",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",totalCost:"Total Cost",total:"Total",includesBom:"incl. BOM",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.",noFiles:"No files in this folder.",print:"Print Now",addToQueue:"Add to Queue"},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",unlinkConfirmTitle:"Unlink Spool?",unlinkConfirmMessage:"This will disconnect the spool from Spoolman. The spool data in Spoolman will remain unchanged.",selectSpool:"Select Spool",noUnlinkedSpools:"No unlinked spools available",linkSuccess:"Spool linked to Spoolman successfully",linkFailed:"Failed to link spool",unlinkSuccess:"Spool unlinked from Spoolman successfully",unlinkFailed:"Failed to unlink 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",spoolName:"Spool",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...",showAllSpools:"Show all 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",weightCheck:"Weight Check",lastWeighed:"Last weighed",neverWeighed:"Never weighed",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)",lowStockThresholdError:"Threshold must be between 0.1 and 99.9",assignMismatchTitle:"Material mismatch",assignMismatchMessage:'The selected spool material "{{spoolMaterial}}" does not match the tray material "{{trayMaterial}}" for {{location}}. Assign anyway?',assignMismatchConfirm:"Assign Anyway",assignPartialMismatchMessage:'The spool material "{{spoolMaterial}}" is similar to but not exactly matching "{{trayMaterial}}" in {{location}}. Do you want to proceed?',assignProfileMismatchMessage:'The spool profile "{{spoolProfile}}" does not match the tray profile "{{trayProfile}}" in {{location}}. Do you want to proceed?'},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:",slotRemainingShort:" - {{grams}}g left",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",insufficientFilamentTitle:"Not enough filament",insufficientFilamentMessage:"Some assigned spools have less filament remaining than this print needs:",insufficientFilamentLine:"{{printer}} - {{slot}}: needs {{required}}g, remaining {{remaining}}g",printAnyway:"Print anyway",forceColorMatch:"Force color match",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Stagger to {{count}} printers",gcodeInjection:"Inject auto-print G-code"},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",githubBackup:"GitHub Backup",enabled:"Enabled",cloudLoginRequired:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup.",cloudLoginRequiredShort:"Cloud login required",githubDescription:"Automatically sync your profiles to a private GitHub repository for backup and version history.",repositoryUrl:"Repository URL",personalAccessToken:"Personal Access Token",tokenSaved:"(saved)",enterNewToken:"Enter new token to update",tokenHint:"Fine-grained token with Contents read/write permission",branch:"Branch",manualOnly:"Manual only",hourly:"Hourly",daily:"Daily",weekly:"Weekly",includeInBackup:"Include in backup",kProfiles:"K-Profiles",kProfilesDescription:"Pressure advance calibration from connected printers",noPrintersConnected:"No printers connected",printersConnected:"{{connected}}/{{total}} connected",cloudProfiles:"Cloud Profiles",cloudProfilesDescription:"Filament, printer, and process presets from Bambu Cloud",appSettings:"App Settings",appSettingsDescription:"Bambuddy configuration (complete database)",spoolInventory:"Spool Inventory",spoolInventoryDescription:"Filament spools, usage history, and cost tracking",printArchives:"Print Archives",printArchivesDescription:"Print history metadata (no gcode/3MF files)",lastBackupAt:"Last backup:",noBackupsYet:"No backups yet",next:"Next:",startingBackup:"Starting backup...",test:"Test",enableBackup:"Enable Backup",testConnection:"Test Connection",enterRepoUrl:"Enter repository URL",enterRepoAndToken:"Enter repository URL and access token",repoRequired:"Repository URL is required",tokenRequired:"Access token is required",githubBackupEnabled:"GitHub backup enabled",tokenUpdated:"Token updated",settingsSaved:"Settings saved",failedToSave:"Failed to save: {{message}}",backupCompleteFiles:"Backup complete - {{count}} files updated",backupSkippedNoChanges:"Backup skipped - no changes",backupFailed2:"Backup failed: {{message}}",clearedLogs:"Cleared {{count}} logs",failedToClearLogs:"Failed to clear logs: {{message}}",history:"History",clear:"Clear",date:"Date",status:"Status",commit:"Commit",localBackup:"Local Backup",localBackupDescription:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files.",downloadBackupLabel:"Download Backup",completeBackupZip:"Complete backup: database + all files (ZIP)",download:"Download",preparingBackup:"Preparing backup...",creatingArchive:"Creating backup archive... This may take a while for large archives.",downloadingFile:"Downloading backup file...",backupDownloaded:"Backup downloaded successfully",failedToCreateBackup:"Failed to create backup: {{message}}",restore:"Restore",restoreReplacesAll:"Restore replaces all data.",restoreReplacesAllDetail:"Your current database and files will be completely replaced. A restart is required after restore.",restoreConfirmTitle:"Restore Backup",restoreConfirmMessage:'Are you sure you want to restore from "{{filename}}"? This will completely replace your current database and all files. The application will need to be restarted after restore.',restoreConfirmButton:"Restore Backup",uploadingFile:"Uploading backup file...",backupRestoredRestart:"Backup restored. Please restart Bambuddy.",failedToRestore:"Failed to restore backup. Please check the file format.",reloadNow:"Reload Now",creatingBackup:"Creating Backup",restoringBackup:"Restoring Backup",preparing:"Preparing...",processing:"Processing...",doNotClosePage:"Please do not close this page or navigate away. This operation may take several minutes for large backups.",restoring:"Restoring...",restoreComplete:"Restore Complete",restoreFailed2:"Restore Failed",importSettings:"Import settings from a backup file",pleaseWaitRestoring:"Please wait while your data is being restored",selectBackupFile:"Click to select backup file (.json or .zip)",duplicateHandling:"How duplicate handling works:",matchPrinters:"Printers",matchPrintersBy:"matched by serial number",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"matched by IP address",matchNotificationProviders:"Notification Providers",matchNotificationProvidersBy:"matched by name",matchFilaments:"Filaments",matchFilamentsBy:"matched by name + type + brand",matchArchives:"Archives",matchArchivesBy:"matched by content hash (always skipped)",matchPendingUploads:"Pending Uploads",matchPendingUploadsBy:"matched by filename",matchSettingsTemplates:"Settings & Templates",matchSettingsTemplatesBy:"always overwritten",replaceExisting:"Replace existing data",keepExisting:"Keep existing data",overwriteDescription:"Overwrite items that already exist with backup data",keepDescription:"Only restore items that don't already exist",overwriteCaution:"Caution:",overwriteWarning:"Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security.",cancel:"Cancel",processingBackup:"Processing backup file...",itemsRestored:"Items Restored",itemsSkipped:"Items Skipped",restored:"Restored",skippedAlreadyExist:"Skipped (already exist)",filesCategory:"Files (3MF, thumbnails, etc.)",andMore:"...and {{count}} more",newApiKeysGenerated:"New API Keys Generated",keysShownOnce:"These keys are only shown once. Copy them now!",copy:"Copy",noDataFound:"No data was found to restore in the backup file.",close:"Close",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"Settings",notification_providers:"Notification Providers",notification_templates:"Notification Templates",smart_plugs:"Smart Plugs",printers:"Printers",filaments:"Filaments",maintenance_types:"Maintenance Types",archives:"Archives",projects:"Projects",pending_uploads:"Pending Uploads",external_links:"External Links",api_keys:"API Keys"}},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"},autoDispatch:{title:"Auto-dispatch",description:"Automatically start prints when added to queue. When off, prints wait for manual dispatch."},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",lubricateSteelRods:"Apply lubricant to steel rods for smooth motion",cleanSteelRods:"Clean steel 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"}},linkedTo:"Linked to:",monitorOnly:"Monitor Only",alerts:"Alerts",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Power",kwhToday:"kWh Today",settings:"Settings",automationSettings:"Automation Settings",showInSwitchbar:"Show in Switchbar",quickAccessSidebar:"Quick access from sidebar",enabled:"Enabled",enableAutomation:"Enable automation for this plug",autoOn:"Auto On",autoOnDescription:"Turn on when print starts",autoOff:"Auto Off",autoOffDescription:"Turn off when print completes (one-shot)",autoOffPersistent:"Keep Enabled",autoOffPersistentDescription:"Stay enabled between prints instead of one-shot",turnOffDelayMode:"Turn Off Delay Mode",time:"Time",temp:"Temp",delayMinutes:"Delay (minutes)",tempThreshold:"Temperature threshold (°C)",tempThresholdDescription:"Turns off when nozzle cools below this temperature",edit:"Edit",deleteConfirm:'Are you sure you want to delete "{{name}}"? This cannot be undone.',turnOnConfirm:'Are you sure you want to turn on "{{name}}"?',turnOffConfirm:'Are you sure you want to turn off "{{name}}"? This will cut power to the connected device.',failedToTurn:'Failed to turn {{action}} "{{name}}"',unknown:"Unknown",addTitle:"Add Smart Plug",editTitle:"Edit Smart Plug",stopScanning:"Stop Scanning",discoverTasmota:"Discover Tasmota Devices",foundDevices:"Found {{count}} device(s) - click to select:",noDevicesFound:"No Tasmota devices found on your network",haNotConfigured:"Home Assistant is not configured. Set it up in",haSettingsPath:"Settings → Network → Home Assistant",selectEntity:"Select Entity *",ipAddress:"IP Address *",nameLabel:"Name *",username:"Username",password:"Password",authHint:"Leave empty if your Tasmota device doesn't require authentication",linkToPrinter:"Link to Printer",noPrinter:"No printer (manual control only)",linkingDescription:"Linking enables automatic on/off when prints start/complete",powerAlerts:"Power Alerts",alertAbove:"Alert if above (W)",alertBelow:"Alert if below (W)",alertDescription:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction.",dailySchedule:"Daily Schedule",turnOnAt:"Turn On at",turnOffAt:"Turn Off at",scheduleDescription:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action.",showOnPrinterCard:"Show on Printer Card",displayOnPrinterCard:"Display button on printer card",connectedResult:"Connected!",deviceLabel:"Device: {{name}} - ",stateLabel:"State: {{state}}",test:"Test",delete:"Delete",save:"Save",add:"Add",cancel:"Cancel",failedToStartScan:"Failed to start scan",nameRequired:"Name is required",entityRequired:"Entity is required for Home Assistant plugs",mqttTopicRequired:"At least one MQTT topic must be configured for power, energy, or state monitoring",loadingEntities:"Loading entities...",loading:"Loading...",failedToLoadEntities:"Failed to load entities: {{error}}",noEntitiesMatching:'No entities found matching "{{search}}"',noEntitiesAvailable:"No entities available",searchingEntities:"Searching all entities ({{count}} found)",showingEntities:"Showing switch, light, input_boolean ({{count}} available)",energyMonitoringOptional:"Energy Monitoring (Optional)",energyMonitoringHint:"Search and select sensors that provide power/energy data.",powerSensorW:"Power Sensor (W)",energyTodayKwh:"Energy Today (kWh)",totalEnergyKwh:"Total Energy (kWh)",noMatchingSensors:"No matching sensors",none:"None",mqttNotConfigured:"MQTT broker not configured. Set broker address in",mqttSettingsPath:"Settings → Network → MQTT Publishing",mqttNotConfiguredSuffix:"(you don't need to enable publishing, just fill in the broker details).",mqttMonitorOnlyDescription:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system.",powerMonitoring:"Power Monitoring",energyMonitoring:"Energy Monitoring",stateMonitoring:"State Monitoring",optional:"optional",topic:"Topic",jsonPath:"JSON Path",multiplier:"Multiplier",onValue:"ON Value",mqttPowerHint:`JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.
- Use multiplier 0.001 for mW→W, 1000 for kW→W.`,mqttEnergyHint:`JSON path extracts value from JSON payload. Leave empty for raw values.
- Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh.`,mqttStateHint:`JSON path extracts value from JSON payload. Leave empty for raw values.
- ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"Power URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"Power Multiplier",restEnergyUrl:"Energy URL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Energy Multiplier",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"Separate URL for power data (uses Status URL if empty)",restEnergyUrlHint:"Separate URL for energy data (uses Status URL if empty)",restEnergyHint:"Each value can use its own URL or fall back to the Status URL. Use multipliers for unit conversion (e.g. 0.001 to convert Wh to kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"No switches in switchbar",enableSwitchbarHint:'Enable "Show in Switchbar" in Settings > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{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",homeassistant:"Persistent notifications in Home Assistant dashboard"},lastSuccess:"Last: {{date}}",error:"Error",printer:"Printer:",allPrinters:"All printers",sendTestNotification:"Send Test Notification",eventSettings:"Event Settings",enabled:"Enabled",sendFromProvider:"Send notifications from this provider",printEvents:"Print Events",printerStatus:"Printer Status",amsAlarms:"AMS Alarms",amsHtAlarms:"AMS-HT Alarms",printQueue:"Print Queue",start:"Start",plateCheck:"Plate Check",complete:"Complete",failed:"Failed",stopped:"Stopped",progress:"Progress",offline:"Offline",lowFilament:"Low Filament",maintenance:"Maintenance",amsHumidity:"AMS Humidity",amsTemp:"AMS Temp",amsHtHumidity:"AMS-HT Humidity",amsHtTemp:"AMS-HT Temp",bedCooled:"Bed Cooled",firstLayer:"First Layer",quiet:"Quiet",digest:"Digest {{time}}",printStarted:"Print Started",plateNotEmpty:"Plate Not Empty",plateNotEmptyDescription:"Objects detected before print",printCompleted:"Print Completed",bedCooledLabel:"Bed Cooled",bedCooledDescription:"Bed cooled below threshold after print",firstLayerCompleteLabel:"First Layer Complete",firstLayerCompleteDescription:"Notify with snapshot when first layer finishes",missingSpoolAssignmentLabel:"Missing Spool Assignment",missingSpoolAssignmentDescription:"Notify when print starts and required trays have no assigned spool",printFailed:"Print Failed",printStopped:"Print Stopped",progressMilestones:"Progress Milestones",progressMilestonesDescription:"Notify at 25%, 50%, 75%",printerOffline:"Printer Offline",printerError:"Printer Error",lowFilamentLabel:"Low Filament",maintenanceDue:"Maintenance Due",maintenanceDueDescription:"Notify when maintenance is needed",amsHumidityHigh:"AMS Humidity High",amsHumidityHighDescription:"Regular AMS humidity exceeds threshold",amsTemperatureHigh:"AMS Temperature High",amsTemperatureHighDescription:"Regular AMS temperature exceeds threshold",amsHtHumidityHigh:"AMS-HT Humidity High",amsHtHumidityHighDescription:"AMS-HT humidity exceeds threshold",amsHtTemperatureHigh:"AMS-HT Temperature High",amsHtTemperatureHighDescription:"AMS-HT temperature exceeds threshold",jobAdded:"Job Added",jobAddedDescription:"Job added to queue",jobAssigned:"Job Assigned",jobAssignedDescription:"Model-based job assigned to printer",jobStarted:"Job Started",jobStartedDescription:"Queue job started printing",jobWaiting:"Job Waiting",jobWaitingDescription:"Job waiting for filament or printer",jobSkipped:"Job Skipped",jobSkippedDescription:"Job skipped (previous failed)",jobFailed:"Job Failed",jobFailedDescription:"Job failed to start",queueComplete:"Queue Complete",queueCompleteDescription:"All queue jobs finished",quietHours:"Quiet Hours",noNotificationsDuring:"No notifications during these hours",editProviderToChangeQuietHours:"Edit provider to change quiet hours",dailyDigest:"Daily Digest",batchNotifications:"Batch notifications into a single daily summary",sendAt:"Send at {{time}}",editProviderToChangeDigestTime:"Edit provider to change digest time",edit:"Edit",deleteProvider:"Delete Notification Provider",deleteConfirm:'Are you sure you want to delete "{{name}}"? This cannot be undone.',delete:"Delete",addTitle:"Add Notification Provider",editTitle:"Edit Notification Provider",nameLabel:"Name *",namePlaceholder:"My Notifications",providerTypeLabel:"Provider Type *",configuration:"Configuration",testConfiguration:"Test Configuration",printerFilter:"Printer Filter",onlyFromPrinter:"Only send notifications for events from this printer",quietHoursDnd:"Quiet Hours (Do Not Disturb)",quietStart:"Start",quietEnd:"End",dailyDigestLabel:"Daily Digest",sendDigestAt:"Send digest at",digestCollected:"Events will be collected and sent as a single summary at this time",notificationEvents:"Notification Events",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(after print completes)",cancel:"Cancel",save:"Save",add:"Add",nameRequired:"Name is required",fieldRequired:"{{field}} is required",phoneNumber:"Phone Number",apiKey:"API Key",serverUrl:"Server URL",topic:"Topic",authToken:"Auth Token",userKey:"User Key",appToken:"App Token",priority:"Priority",botToken:"Bot Token",chatId:"Chat ID",smtpServer:"SMTP Server",smtpPort:"SMTP Port",security:"Security",authentication:"Authentication",username:"Username",password:"Password",fromEmail:"From Email",toEmail:"To Email",webhookUrl:"Webhook URL",payloadFormat:"Payload Format",authorization:"Authorization",titleFieldName:"Title Field Name",messageFieldName:"Message Field Name",editTemplate:"Edit Template: {{name}}",titleLabel:"Title",bodyLabel:"Body",titlePlaceholder:"Notification title...",bodyPlaceholder:"Notification body...",availableVariables:"Available Variables",clickToInsert:"Click to insert at cursor position in body",livePreview:"Live Preview",hide:"Hide",show:"Show",loadingPreview:"Loading preview...",enterTemplateContent:"Enter template content to see preview",titlePreview:"Title:",bodyPreview:"Body:",resetToDefault:"Reset to Default",titleRequired:"Title is required",bodyRequired:"Body is required",notificationLog:"Notification Log",showFailedOnly:"Failed only",last24Hours:"Last 24 hours",last7Days:"Last 7 days",last30Days:"Last 30 days",last90Days:"Last 90 days",justNow:"Just now",noFailedNotifications:"No failed notifications",noNotificationsLogged:"No notifications logged",unknownProvider:"Unknown Provider",logTitle:"Title",logMessage:"Message",logError:"Error",logProvider:"Provider: {{type}}",logTime:"Time: {{time}}",refresh:"Refresh",clearOld:"Clear Old",statsSummary:"Last {{days}} days:",statsNotifications:"notifications",statsSent:"{{count}} sent",statsFailed:"{{count}} failed",eventTypes:{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"},userEmail:{title:"Notifications",emailNotifications:"Email Notifications",emailNotificationsDesc:"Receive email notifications for your own print jobs. Emails are sent using the system SMTP settings configured in Advanced Authentication.",sendingTo:"Notifications will be sent to",noEmailWarning:"Your account does not have an email address. Contact an administrator to add one.",printJobNotifications:"Print Job Notifications",printJobNotificationsDesc:"Choose which events trigger email notifications for print jobs you submit.",printJobStarts:"Print Job Starts",printJobStartsDesc:"Get notified when your print job begins.",printJobFinishes:"Print Job Finishes",printJobFinishesDesc:"Get notified when your print job completes successfully.",printErrors:"Print Errors",printErrorsDesc:"Get notified when your print job fails or encounters an error.",printJobStops:"Print Job Stops",printJobStopsDesc:"Get notified when your print job is cancelled or stopped.",saveSuccess:"Notification preferences saved.",saveError:"Failed to save notification preferences."}},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",writeTag:"Write",settings:"Settings"},status:{nfcReady:"NFC Ready",nfcOff:"NFC Off",offline:"Offline",online:"Online",noPrinters:"No printers",deviceOffline:"Device Offline",waitingConnection:"Waiting for device connection...",systemReady:"System Ready",status:"Status"},dashboard:{readyToScan:"Ready to scan",idleMessage:"Place a spool on the scale to identify it",nfcHint:"NFC tag will be read automatically",device:"Device",syncWeight:"Sync Weight",weightSynced:"Synced!",unknownTag:"Unknown Tag",newTag:"New Tag Detected",onScale:"on scale",linkSpool:"Link to Spool",linkTagTitle:"Link Tag to Spool",linkTag:"Link Tag",selectSpool:"Select a spool to link this tag to:",noUntagged:"No spools without tags found",tagDetected:"Tag detected",noTag:"No tag",tagId:"Tag",grossWeight:"Gross weight",spoolSize:"Spool size",close:"Close",currentSpool:"Current Spool"},modal:{spoolDetected:"Spool Detected",assignToAms:"Assign to AMS",syncWeight:"Sync Weight",weightSynced:"Synced!",syncing:"Syncing...",newTagDetected:"New Tag Detected",addToInventory:"Add to Inventory",assignToAmsTitle:"Assign to AMS",selectSlot:"Select a slot",assign:"Assign",assigning:"Assigning...",assignSuccess:"Assigned!",assignError:"Failed to assign spool. Please try again.",noPrinterSelected:"Select a printer...",noAmsDetected:"No AMS detected on this printer",slot:"Slot"},weight:{noReading:"No reading",stable:"Stable",measuring:"Measuring...",tare:"Tare",calibrate:"Calibrate"},spool:{remaining:"Remaining",material:"Material",brand:"Brand",color:"Color",coreWeight:"Core",labelWeight:"Label",scaleWeight:"Scale",netWeight:"Net",lastUsed:"Last used"},ams:{noData:"No AMS detected",connectAms:"Connect an AMS to see filament slots",noPrinter:"No printer selected",selectPrinter:"Select a printer from the top bar",printerDisconnected:"Printer disconnected",humidity:"Humidity",level:"Level",active:"Active",slot:"Slot",empty:"Empty"},inventory:{search:"Search spools...",empty:"No spools in inventory",noResults:"No matching spools",spools:"spools",addSpool:"Add Spool"},settings:{tabDevice:"Device",tabDisplay:"Display",tabScale:"Scale",tabUpdates:"Updates",nfcReader:"NFC Reader",type:"Type",connection:"Connection",notConnected:"N/A",deviceInfo:"Device Info",hostname:"Host",uptime:"Uptime",systemConfig:"Backend & Auth",backendUrl:"Bambuddy Backend URL",apiToken:"API Token",apiTokenPlaceholder:"Enter API token",saveConfig:"Save Config",systemQueued:"Config queued.",nfcDiagnostic:"NFC Diagnostic",scaleDiagnostic:"Scale Diagnostic",readTagDiagnostic:"Read Tag Diagnostic",testNfc:"Test reader",testScale:"Test accuracy",testReadTag:"Read tag",systemFieldsRequired:"Backend URL is required.",brightness:"Brightness",saved:"Saved",noBacklight:"No DSI backlight detected. Brightness control requires a DSI display.",screenBlank:"Screen Blank Timeout",screenBlankDesc:"Screen turns off after inactivity. Touch to wake.",displayNote:"Brightness is applied as a software filter.",scaleCalibration:"Scale Calibration",currentWeight:"Current weight",tareOffset:"Tare",calFactor:"Factor",knownWeight:"Known weight",calStep1:"Remove all items from the scale and press Set Zero.",calStep2:"Place known weight on scale.",setZero:"Set Zero",calibrateNow:"Calibrate",calibrated:"Calibrated",tareSet:"Tare command sent. Waiting for device...",tareFailed:"Failed to send tare command",zeroSet:"Zero point set. Place known weight on scale.",calibrationDone:"Calibration complete!",calibrationFailed:"Calibration failed",lastCalibrated:"Last calibrated",stable:"Stable",settling:"Settling...",firmware:"Firmware",scale:"Scale",noDevice:"No SpoolBuddy device found",daemonVersion:"Daemon Version",currentVersion:"Current",versionPending:"Waiting for daemon...",checking:"Checking...",checkUpdates:"Check for Updates",updateAvailable:"Update available",updateInstructions:"Update via SSH: run the SpoolBuddy install script to upgrade.",upToDate:"Up to date",includeBeta:"Include beta versions"},writeTag:{tabExisting:"Existing Spool",tabNew:"New Spool",tabReplace:"Replace Tag",searchPlaceholder:"Search by material, color, brand...",noUntaggedSpools:"No spools without tags",noTaggedSpools:"No spools with tags",selectSpool:"Select a spool, then place a blank NTAG on the reader",placeTag:"Place an NTAG on the reader",tagReady:"Tag detected — ready to write",writeTag:"Write Tag",replaceTag:"Replace Tag",writing:"Writing tag...",waiting:"Waiting for SpoolBuddy...",writeSuccess:"Tag written successfully!",writeFailed:"Write failed",queueFailed:"Failed to queue write command",tryAgain:"Try Again",cancel:"Cancel",replaceWarning:"Old tag will be unlinked. New tag will replace it.",deviceOffline:"SpoolBuddy is offline",material:"Material",colorName:"Color Name",color:"Color",brand:"Brand",weight:"Weight (g)",createSpool:"Create Spool",creating:"Creating...",spoolCreated:"Spool created! Ready to write.",createFailed:"Failed to create spool"},quickMenu:{printerPower:"Printer Power",systemControls:"System",restartDaemon:"Restart Daemon",restartBrowser:"Restart Browser",reboot:"Reboot",shutdown:"Shutdown",swipeToClose:"Swipe down to close",confirmTitle:"Confirm",confirmShutdown:"Are you sure you want to shut down the SpoolBuddy? You will need physical access to turn it back on.",confirmReboot:"Are you sure you want to reboot the SpoolBuddy?",confirmRestartDaemon:"Restart the SpoolBuddy daemon? NFC and scale will be temporarily unavailable.",confirmRestartBrowser:"Restart the kiosk browser? The display will briefly go blank.",confirm:"Confirm",confirmPlugOn:"Turn on {{name}}?",confirmPlugOff:"Turn off {{name}}?",turnOn:"Turn On",turnOff:"Turn Off"}},bugReport:{title:"Report a Bug",description:"Description",descriptionPlaceholder:"What went wrong? Please describe the issue...",email:"Email (optional)",emailPlaceholder:"your@email.com",emailPrivacy:"If provided, your email will be included in a collapsed section of the GitHub issue so the maintainer can follow up.",screenshot:"Screenshot",uploadOrPaste:"Upload, paste, or drag an image",dataCollectedSummary:"What data is included in the report?",dataIncluded:"Included:",dataIncludedList:"App version, OS, architecture, Python version, database stats (counts only), printer models, nozzle counts, firmware versions, connectivity status, integration status (Spoolman, MQTT, HA), non-sensitive settings, network interface count, Docker details, dependency versions.",dataNeverIncluded:"Never included:",dataNeverIncludedList:"Printer names, serial numbers, access codes, passwords, IP addresses, email addresses, API keys, tokens, webhook URLs, hostnames, or usernames.",submit:"Submit",startLogging:"Start Debug Logging",stepEnableLogging:"Debug logging enabled",stepReproduce:"Reproduce the issue now",stepStopLogging:"Stop & submit report",stopAndSubmit:"Stop & Submit",maxDuration:"Auto-stops after {{minutes}} min",stoppingLogs:"Collecting logs & submitting...",submitting:"Submitting bug report...",submitSuccess:"Bug report submitted successfully!",submitFailed:"Failed to submit bug report",thankYou:"Thank you!",submitted:"Your bug report has been submitted.",viewIssue:"View Issue",unexpectedError:"An unexpected error occurred"},failureDetection:{title:"AI Failure Detection",description:"Monitor prints with a self-hosted Obico ML API and act on detected failures automatically.",mlUrl:"Obico ML API URL",mlUrlHint:"Base URL of your self-hosted Obico ml_api container (e.g. http://192.168.1.10:3333).",test:"Test",testSuccess:"ML API reachable and healthy.",testFailed:"Could not reach the ML API.",sensitivity:"Sensitivity",sensitivityLow:"Low (fewer false positives)",sensitivityMedium:"Medium (balanced)",sensitivityHigh:"High (detect early, more false positives)",sensitivityHint:"Adjusts the confidence thresholds that trigger warnings and failures.",action:"Action on detected failure",actionNotify:"Notify only",actionPause:"Pause print",actionPauseOff:"Pause and cut power",pollInterval:"Poll interval (seconds)",pollIntervalHint:"How often to check each printer while it is printing. Minimum 5s, maximum 120s.",externalUrlMissing:"External URL is not set.",externalUrlHint:"The ML API fetches the camera snapshot by URL. Set the External URL in General settings so the ML API container can reach Bambuddy.",perPrinterTitle:"Monitored Printers",perPrinterHint:"Choose which printers the detection service watches.",monitorAll:"Monitor all connected printers",statusTitle:"Status",serviceRunning:"Service running",thresholds:"Low / High thresholds",activePrinters:"Active prints",noActivePrints:"No prints currently running.",historyTitle:"Recent Detections",noHistory:"No detections yet."}},Uue={nav:{printers:"Drucker",archives:"Archiv",queue:"Warteschlange",stats:"Statistiken",profiles:"Profile",maintenance:"Wartung",projects:"Projekte",inventory:"Filament",files:"Dateimanager",notifications:"Benachrichtigungen",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",uploading:"Hochladen...",uploadFailed:"Hochladen fehlgeschlagen",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",back:"Zurück",copy:"Kopieren",copied:"Kopiert!",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",problem:"Problem",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",search:"Drucker suchen...",noSearchResults:"Keine Drucker entsprechen deiner Suche oder deinen Filtern",filter:{allStatuses:"Alle Status",allLocations:"Alle Standorte"},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",files:"Dateien",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",forceRefresh:"Aktualisierung erzwingen",forceRefreshSuccess:"Aktualisierung angefordert",mqttDebug:"MQTT-Debug",printerInformation:"Druckerinformationen",copyToClipboard:"Kopieren",copied:"Kopiert!",state:"Zustand",wifiSignalLabel:"WLAN-Signal",developerMode:"Entwicklermodus",enabled:"Aktiviert",disabled:"Deaktiviert",addedOn:"Hinzugefügt",sdCard:"SD-Karte",inserted:"Eingelegt",notInserted:"Nicht eingelegt",totalPrintHours:"Druckstunden",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",missingSpoolAssignment:"Druck gestartet auf {{printer}}. Fehlende Spulenzuordnung für: {{slots}}",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",failedToSetSpeed:"Druckgeschwindigkeit konnte nicht eingestellt 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",noCamera:"Sie haben keine Berechtigung, Kameras anzuzeigen"},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"},bulk:{select:"Auswählen",selectAll:"Alle auswählen",selectByLocation:"Nach Standort auswählen",selected:"{{count}} ausgewählt",actions:{stop:"Stoppen",pause:"Pausieren",resume:"Fortsetzen",clearPlate:"Druckbett leeren",clearHMS:"Benachrichtigungen löschen"},confirm:{stopTitle:"{{count}} Drucke stoppen",stopMessage:"Dies wird aktive Drucke auf {{count}} Drucker(n) abbrechen. Diese Aktion kann nicht rückgängig gemacht werden.",stopButton:"Alle stoppen",pauseTitle:"{{count}} Drucke pausieren",pauseMessage:"Dies wird aktive Drucke auf {{count}} Drucker(n) pausieren.",pauseButton:"Alle pausieren",clearPlateTitle:"{{count}} Druckbetten leeren",clearPlateMessage:"Dies wird das Druckbett auf {{count}} Drucker(n) leeren und kann wartende Aufträge starten.",clearPlateButton:"Alle leeren"},success:"{{action}} auf {{count}} Drucker(n) abgeschlossen",partial:"{{succeeded}} erfolgreich, {{failed}} fehlgeschlagen",noneApplicable:"Keine ausgewählten Drucker sind im richtigen Zustand für diese Aktion",selectByState:"Nach Status auswählen"},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"},drying:{start:"Trocknung starten",stop:"Trocknung stoppen",temperature:"Temperatur",duration:"Dauer",hours:"Stunden",timeRemaining:"{{time}} verbleibend",active:"Trocknung",notSupported:"Trocknung nicht unterstützt",powerRequired:"AMS-Netzteil anschließen, um Trocknung zu aktivieren",startingDrying:"Trocknung wird gestartet...",stoppingDrying:"Trocknung wird gestoppt...",rotateTray:"Spule während der Trocknung drehen"},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"},speed:{title:"Druckgeschwindigkeit",silent:"Leise (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},airduct:{title:"Luftkanal-Modus",cooling:"Kühlen",heating:"Heizen"},noSdCard:"Keine SD",door:{open:"Offen",closed:"Zu"},fans:{partCooling:"Bauteilkühlung",auxiliary:"Hilfsventilator",chamber:"Kammerventilator"},clickToViewHmsErrors:"Klicken, um HMS-Fehler anzuzeigen",estimatedCompletion:"Geschätzte Fertigstellungszeit",plateNumber:"Platte {{number}}",slotOptions:"Slot-Optionen",amsPopup:{friendlyName:"AMS-Name",friendlyNamePlaceholder:"z. B. AMS-Anzeigename",serialNumber:"Seriennummer",firmwareVersion:"Firmware",save:"Speichern",clear:"Löschen",noEditPermission:"Sie haben keine Berechtigung, AMS-Einheiten umzubenennen"},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.",availableVersions:"Verfügbare Versionen",usable:"Installierbar",unavailable:"Nicht verfügbar",installed:"Installiert",newerBadge:"neuer",olderBadge:"älter",currentBadge:"aktuell"},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",incompatibleFile:"Diese Datei wurde für {{slicedFor}} geslicet, aber dieser Drucker ist ein {{printerModel}}",dropNotPrintable:"Nur .gcode- und .gcode.3mf-Dateien können gedruckt werden",dropToPrint:"Zum Drucken ablegen",cannotPrint:"Drucker beschäftigt"},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",originalPrintNotVisible:"Ursprünglicher Druck nicht sichtbar - versuchen Sie, die Filter zu löschen",noArchivesYet:"Noch keine Archive",prints:"Drucke",pagination:{showing:"Zeige",to:"bis",of:"von",show:"Zeige",page:"Seite",all:"Alle"},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",hideDuplicates:"Duplikate ausblenden",viewOriginalPrint:"Klicken, um den ursprünglichen Druck anzuzeigen (#{{id}})",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",queueSelectedPlates:"{{count}} Platten in die Warteschlange",selectAllPlates:"Alle {{count}} Platten auswählen",deselectAll:"Alle abwählen",printQueued:"Druck in Warteschlange",itemsQueued:"{{count}} Einträge in Warteschlange",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.",sjf:{label:"SJF",tooltip:"Kürzester Auftrag zuerst — Scheduler bevorzugt kürzere Drucke"},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}}",quantity:"Menge",quantityHint:"Erstellt {{count}} Warteschlangeneinträge",activeBatches:"Aktive Stapel",batchProgress:"{{completed}} von {{total}} abgeschlossen",cancelBatch:"Verbleibende abbrechen",batchCancelled:"Verbleibende Stapeleinträge abgebrochen",cancelBatchConfirmTitle:"Stapel abbrechen",cancelBatchConfirmMessage:"Alle verbleibenden ausstehenden Einträge in diesem Stapel abbrechen?",batch:"Stapel",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",gcodeInjection:"G-code"},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"},timeline:{listView:"Liste",timelineView:"Zeitstrahl",unassigned:"Nicht zugewiesen",noData:"Keine geplanten Drucke für diesen Tag",allDoneBy:"Alle Drucke voraussichtlich fertig um {{time}}",staged:"Bereitgestellt",filterAll:"Alle anzeigen",filterPrinting:"Druckend",filterQueued:"Warteschlange",time:{anyMoment:"jeden Moment",minutesLeft:"{{minutes}}m übrig",hoursLeft:"{{hours}}h übrig",hoursMinutesLeft:"{{hours}}h {{minutes}}m übrig"},day:{previous:"Vorheriger Tag",next:"Nächster Tag",today:"Heute"}},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",printStartedRemaining:"{{completed}} Druck(e) gestartet, {{remaining}} weitere werden gesendet..."}},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",energyWarmingUpTooltip:"Die Energieerfassung sammelt noch stündliche Snapshots. Zeitraumwerte werden genau, sobald vor dem gewählten Bereich mindestens ein Snapshot vorliegt. Frühe Werte können zu niedrig sein.",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",noPrintDataInRange:"Keine Druckdaten im ausgewählten Zeitraum",periodFilament:"Filamentverbrauch",periodCost:"Kosten",avgPerPrint:"Durchschnitt pro Druck",usageOverTime:"Verbrauch im Zeitverlauf",filamentByWeight:"Gewicht",printDuration:"Druckdauer",printerUtilization:"Druckerauslastung",filamentSuccess:"Erfolg nach Material",printHabits:"Druckgewohnheiten",printTimeOfDay:"Druck-Tageszeit",colorDistribution:"Farbverteilung",noColorData:"Keine Farbdaten verfügbar",records:"Rekorde",longestPrint:"Längster Druck",heaviestPrint:"Schwerster Druck",mostExpensivePrint:"Teuerster Druck",busiestDay:"Aktivster Tag",successStreak:"Erfolgsserie",streakPrint:"aufeinanderfolgender Druck",streakPrints:"{{count}} aufeinanderfolgende Drucke",printerStats:"Druckerstatistiken",hours:"Stunden",avgPrints:"Ø Drucke",noArchiveData:"Keine Druckdaten verfügbar",filamentByTime:"Zeitverlauf",avgWeight:"Ø Gewicht",avgTime:"Ø Zeit",filamentByPrints:"Drucke",timeframe:{today:"Heute","this-week":"Diese Woche","this-month":"Dieser Monat","last-7":"Letzte 7 Tage","last-30":"Letzte 30 Tage","last-90":"Letzte 90 Tage","this-year":"Dieses Jahr","all-time":"Gesamt",custom:"Benutzerdefiniert",from:"Von",to:"Bis"},allUsers:"Alle Benutzer",noUser:"Kein Benutzer (System)",filterByUser:"Nach Benutzer filtern"},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",lubricateSteelRods:"Stahlstangen schmieren",cleanSteelRods:"Stahlstangen 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",queue:"Workflow",filament:"Filament",network:"Netzwerk",apiKeys:"API-Schlüssel",virtualPrinter:"Virtueller Drucker",spoolbuddy:"SpoolBuddy",failureDetection:"Fehlererkennung",users:"Authentifizierung",backup:"Sicherung",emailAuth:"E-Mail-Authentifizierung",ldap:"LDAP",twoFa:"Zwei-Faktor-Auth",oidc:"SSO / OIDC"},spoolbuddy:{infoTitle:"SpoolBuddy-Geräte",infoBody:"SpoolBuddy-Kioske registrieren sich automatisch per Heartbeat. Ein Gerät hier abmelden, wenn es nicht mehr verwendet wird oder wenn ein veralteter Eintrag nach einem Daemon-Absturz übrig geblieben ist.",duplicatesTitle:"{{count}} Geräte registriert",duplicatesBody:"Die Kiosk-Oberfläche verwendet nur das zuerst registrierte Gerät. Falls eines davon ein veralteter Doppeleintrag nach einem Absturz ist, kann es hier entfernt werden — ein laufendes Gerät registriert sich beim nächsten Heartbeat automatisch neu.",empty:"Noch keine SpoolBuddy-Geräte registriert.",online:"Online",offline:"Offline",unregister:"Abmelden",unregisterSuccess:"Gerät abgemeldet",unregisterError:"Gerät konnte nicht abgemeldet werden",confirmTitle:"SpoolBuddy-Gerät abmelden?",confirmBody:'Dies entfernt „{{hostname}}" ({{deviceId}}) aus der Datenbank. Ein laufendes Gerät registriert sich beim nächsten Heartbeat automatisch neu.',ipAddress:"IP-Adresse",firmware:"Firmware",lastSeen:"Zuletzt gesehen",daemonUptime:"Daemon-Laufzeit",systemUptime:"System-Laufzeit",never:"nie",nfc:"NFC",scale:"Waage",cpuTemp:"CPU-Temp.",memory:"Speicher",disk:"Festplatte",update:"Aktualisieren",updateConfirmTitle:"Spoolbuddy-Daemon aktualisieren?",updateConfirmBody:'Software-Update auf „{{hostname}}" auslösen? Der Daemon startet nach dem Update neu.',restartBrowser:"Browser neu starten",restartBrowserConfirmTitle:"Kiosk-Browser neu starten?",restartBrowserConfirmBody:'Kiosk-Browser auf „{{hostname}}" neu starten? Die Anzeige wird kurz schwarz.',restartDaemon:"Daemon neu starten",restartDaemonConfirmTitle:"Spoolbuddy-Daemon neu starten?",restartDaemonConfirmBody:'Spoolbuddy-Daemon auf „{{hostname}}" neu starten? Das Gerät ist für einige Sekunden offline.',reboot:"Neustart",rebootConfirmTitle:"Gerät neu starten?",rebootConfirmBody:'„{{hostname}}" neu starten? Das Gerät ist für etwa eine Minute offline.',shutdown:"Herunterfahren",shutdownConfirmTitle:"Gerät herunterfahren?",shutdownConfirmBody:'„{{hostname}}" herunterfahren? Physischer Zugriff ist nötig, um es wieder einzuschalten.',commandConfirm:"Bestätigen",commandQueued:"Befehl eingereiht",commandError:"Befehl konnte nicht gesendet werden"},ldap:{title:"LDAP-Authentifizierung",enabledDesc:"LDAP-Authentifizierung ist aktiviert",disabledDesc:"LDAP-Authentifizierung ist deaktiviert",disabledHint:"LDAP-Einstellungen unten konfigurieren und speichern, dann aktivieren.",enabled:"LDAP-Authentifizierung aktiviert",disabled:"LDAP-Authentifizierung deaktiviert",feature1:"Benutzer können sich mit LDAP-Anmeldedaten anmelden",feature2:"Lokales Admin-Konto bleibt als Fallback erhalten",feature3:"LDAP-Gruppen werden bei der Anmeldung BamBuddy-Gruppen zugeordnet",serverConfig:"LDAP-Server-Konfiguration",serverUrl:"Server-URL",serverUrlHint:"Verwenden Sie ldap:// für Standard oder ldaps:// für SSL-Verbindungen",security:"Sicherheit",securityHint:"StartTLS aktualisiert eine einfache Verbindung auf TLS. LDAPS verwendet TLS von Anfang an.",bindDn:"Bind-DN (Dienstkonto)",bindPassword:"Bind-Passwort",searchBase:"Such-Basis-DN",userFilter:"Benutzer-Suchfilter",userFilterHint:"{username} wird durch den Anmeldenamen ersetzt. Verwenden Sie (uid={username}) für OpenLDAP.",autoProvision:"Benutzer automatisch anlegen",autoProvisionHint:"Automatisch ein BamBuddy-Konto bei der ersten LDAP-Anmeldung erstellen",defaultGroup:"Standardgruppe",defaultGroupNone:"— Keine (kein Fallback) —",defaultGroupHint:"Fallback-Gruppe, die zugewiesen wird, wenn sich ein LDAP-Benutzer authentifiziert, aber in keiner zugeordneten LDAP-Gruppe enthalten ist. Leer lassen, um nicht zugeordnete Benutzer ohne Berechtigungen zu belassen.",groupMapping:"Gruppenzuordnung (JSON)",groupMappingHint:"LDAP-Gruppen-DNs BamBuddy-Gruppen zuordnen. Verfügbare Gruppen: ",testConnection:"Verbindung testen",settingsSaved:"LDAP-Einstellungen gespeichert",errors:{serverRequired:"LDAP-Server-URL ist erforderlich",searchBaseRequired:"Such-Basis-DN ist erforderlich",enableAuthFirst:"Authentifizierung zuerst aktivieren",configureLdapFirst:"LDAP-Einstellungen zuerst speichern"}},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",enableAuthFirst:"Bitte aktivieren Sie zuerst die Authentifizierung, um E-Mail-basierte Funktionen nutzen zu können."},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",userNotificationsEnabled:"Benutzerbenachrichtigungen",userNotificationsEnabledDescription:"Aktiviert das Benutzerbenachrichtigungsmenü und E-Mail-Benachrichtigungen für Druckereignisse. Erfordert Erweiterte Authentifizierung.",userNotificationsDisabledHint:"Erweiterte Authentifizierung aktivieren, um Benutzerbenachrichtigungen zu verwenden.",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.",filamentChecks:"Filament-Prüfungen",disableFilamentWarnings:"Filament-Warnungen deaktivieren",disableFilamentWarningsDesc:"Keine Warnungen über unzureichendes Filament beim Drucken oder Einreihen anzeigen",preferLowestFilament:"Niedrigsten Filamentrest bevorzugen",preferLowestFilamentDesc:"Bei mehreren passenden Spulen die mit dem geringsten Restfilament 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)",fairAlsoDryingThreshold:"Dieser Schwellenwert wird auch für die automatische Trocknung verwendet",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",defaultPrintOptions:"Standard-Druckoptionen",defaultPrintOptionsDescription:"Standardwerte für Druckoptionen bei neuen Drucken festlegen. Diese können im Druckdialog pro Druck überschrieben werden.",defaultBedLevelling:"Bett-Nivellierung",defaultBedLevellingDesc:"Bett vor dem Druck automatisch nivellieren",defaultFlowCali:"Fluss-Kalibrierung",defaultFlowCaliDesc:"Extrusionsfluss kalibrieren",defaultVibrationCali:"Vibrationskalibrierung",defaultVibrationCaliDesc:"Ringing-Artefakte reduzieren",defaultLayerInspect:"Erste-Schicht-Inspektion",defaultLayerInspectDesc:"KI-Inspektion der ersten Schicht",defaultTimelapse:"Zeitraffer",defaultTimelapseDesc:"Zeitraffervideo aufnehmen",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Druckplatte-Bestätigung",requirePlateClear:"Druckplatte-Bestätigung erforderlich",requirePlateClearDescription:"Wenn aktiviert, wartet der Scheduler auf eine Druckplatte-Bestätigung pro Drucker, bevor geplante Drucke auf Druckern mit abgeschlossenen Aufträgen gestartet werden. Deaktivieren Sie dies für Farm-Workflows, bei denen die Platten physisch überprüft werden.",gcodeInjection:"G-code Injection",gcodeInjectionDescription:'Konfigurieren Sie benutzerdefinierten G-code, der am Anfang und/oder Ende von Drucken für Auto-Print-Systeme wie Farmloop, SwapMod, AutoClear und Printflow 3D eingefügt wird. Snippets werden pro Druckermodell konfiguriert und angewendet, wenn "G-code einfügen" bei einem Warteschlangen-Element aktiviert ist.',gcodeInjectionNoPrinters:"Keine Drucker gefunden. Fügen Sie Drucker hinzu, um G-code-Snippets zu konfigurieren.",gcodeStartLabel:"Start G-code",gcodeEndLabel:"End G-code",gcodeStartPlaceholder:"G-code, der vor dem Druckstart eingefügt wird...",gcodeEndPlaceholder:"G-code, der nach dem Druckende angefügt wird...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Automatische Trocknung",queueDryingDescription:"AMS-Filament automatisch trocknen, wenn der Drucker zwischen Warteschlangen-Drucken im Leerlauf ist. Verwendet den Feuchtigkeitsschwellenwert oben.",queueDryingEnabled:"Automatische Trocknung aktivieren",queueDryingEnabledDescription:"AMS-Trocknung automatisch starten, wenn der Drucker im Leerlauf ist und die Feuchtigkeit über dem Schwellenwert liegt",queueDryingBlock:"Auf Trocknung warten",queueDryingBlockDescription:"Druckwarteschlange blockieren, bis die Trocknung abgeschlossen ist. Wenn aus, haben Drucke Vorrang.",ambientDryingEnabled:"Umgebungstrocknung",ambientDryingEnabledDescription:"Filament auf inaktiven Druckern automatisch trocknen, wenn die Luftfeuchtigkeit den Schwellenwert überschreitet — auch ohne Warteschlange.",dryingPresets:"Trocknungsvoreinstellungen",dryingPresetsDescription:"Temperatur und Dauer pro Filamenttyp. AMS 2 Pro verwendet niedrigere Temperaturen, AMS-HT unterstützt höhere.",dryingFilament:"Filament",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",selectedCount:"{{count}} ausgewählt",deleteSelected:"Ausgewählte löschen",bulkDeleteConfirm:"Möchten Sie {{count}} Einträge wirklich löschen?",bulkDeleted:"{{count}} Einträge gelöscht",bulkDeleteFailed:"Fehler beim Löschen der Einträge"},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",selectedCount:"{{count}} ausgewählt",deleteSelected:"Ausgewählte löschen",bulkDeleteConfirm:"Möchten Sie {{count}} Farben wirklich löschen?",bulkDeleted:"{{count}} Farben gelöscht",bulkDeleteFailed:"Fehler beim Löschen der Farben"},dateFormat:"Datumsformat",dateFormatUs:"US (MM/TT/JJJJ)",dateFormatEu:"EU (TT/MM/JJJJ)",dateFormatIso:"ISO (JJJJ-MM-TT)",timeFormat:"Zeitformat",timeFormat12:"12-Stunden (3:30 PM)",timeFormat24:"24-Stunden (15:30)",defaultPrinter:"Standarddrucker",defaultPrinterDescription:"Diesen Drucker für Uploads, Nachdrucke und andere Vorgänge vorauswählen.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Elemente in der Seitenleiste per Drag & Drop neu anordnen. Hier auf Standardreihenfolge zurücksetzen.",setDefault:"Standard setzen",sidebarOrderSetDefaultHint:"Standard setzen übernimmt die aktuelle Menüreihenfolge für Benutzer, die ihre noch nicht angepasst haben.",sidebarDefaultSet:"Standard-Menüreihenfolge wurde festgelegt.",sidebarDefaultCleared:"Standard-Menüreihenfolge gelöscht.",sidebarDefaultFailed:"Festlegen der Standard-Menüreihenfolge fehlgeschlagen.",reset:"Zurücksetzen",darkMode:"Dunkelmodus",lightMode:"Hellmodus",active:"(aktiv)",background:"Hintergrund",accent:"Akzent",style:"Stil",bgNeutral:"Neutral",bgWarm:"Warm",bgCool:"Kühl",bgOled:"OLED Schwarz",bgSlate:"Schieferblau",bgForest:"Waldgrün",accentGreen:"Grün",accentTeal:"Türkis",accentBlue:"Blau",accentOrange:"Orange",accentPurple:"Lila",accentRed:"Rot",styleClassic:"Klassisch",styleGlow:"Leuchtend",styleVibrant:"Lebendig",themeToggleHint:"Zwischen Hell- und Dunkelmodus mit dem Sonnen-/Mondsymbol in der Seitenleiste wechseln.",autoArchivePrints:"Drucke automatisch archivieren",autoArchiveDescription:"3MF-Dateien automatisch speichern, wenn Drucke abgeschlossen sind",saveThumbnailsDescription:"Vorschaubilder aus 3MF-Dateien extrahieren und speichern",captureFinishPhotoDescription:"Foto von der Druckerkamera aufnehmen, wenn der Druck abgeschlossen ist",ffmpegNotInstalled:"ffmpeg nicht installiert",ffmpegRequired:"Kameraaufnahme benötigt ffmpeg. Installieren über <brew>brew install ffmpeg</brew> (macOS) oder <apt>apt install ffmpeg</apt> (Linux).",camera:"Kamera",cameraViewMode:"Kamera-Ansichtsmodus",cameraOverlayDescription:"Kamera öffnet sich als größenveränderbares Overlay auf dem Hauptbildschirm",cameraWindowDescription:"Kamera öffnet sich in einem separaten Browserfenster",externalCamerasDescription:"Externe Kameras konfigurieren, um die eingebaute Druckerkamera zu ersetzen. Unterstützt MJPEG-Streams, RTSP, HTTP-Snapshots und USB-Kameras (V4L2). Wenn aktiviert, wird die externe Kamera für Live-Ansicht und Abschlussfotos verwendet.",cameraPlaceholderUsb:"Gerätepfad (/dev/video0)",cameraPlaceholderUrl:"Kamera-URL (rtsp://... oder http://...)",cameraTypeMjpeg:"MJPEG-Stream",cameraTypeRtsp:"RTSP-Stream",cameraTypeSnapshot:"HTTP-Snapshot",cameraTypeUsb:"USB-Kamera (V4L2)",cameraRotation:"Drehung",test:"Testen",connected:"Verbunden",disconnected:"Getrennt",currency:"Währung",defaultFilamentCost:"Standard-Filamentkosten (pro kg)",electricityCost:"Stromkosten pro kWh",energyDisplayMode:"Energieanzeige-Modus",energyModePrintDescription:"Dashboard zeigt Summe der während Drucken verbrauchten Energie",energyModeTotalDescription:"Dashboard zeigt Gesamtenergie der Smart Plugs",fileManager:"Dateimanager",createArchiveEntry:"Archiveintrag beim Drucken erstellen",createArchiveEntryDescription:"Beim Drucken aus dem Dateimanager optional einen Archiveintrag erstellen",lowDiskSpaceWarning:"Warnung bei wenig Speicherplatz",lowDiskSpaceDescription:"Warnung anzeigen, wenn freier Speicherplatz unter diesen Schwellenwert fällt",printerFirmware:"Drucker-Firmware",checkFirmwareDescription:"Nach Firmware-Updates von Bambu Lab suchen",bambuddySoftware:"Bambuddy Software",autoCheckDescription:"Automatisch beim Start nach neuen Versionen suchen",checkNow:"Jetzt prüfen",updateAvailableVersion:"Update verfügbar: v{{version}}",releaseNotes:"Versionshinweise",updateViaDocker:"Update über Docker Compose:",installUpdate:"Update installieren",latestVersionRunning:"Sie verwenden die neueste Version",failedToCheckUpdates:"Update-Prüfung fehlgeschlagen: {{error}}",backupRestore:"Sicherung & Wiederherstellung",backupRestoreDescription:"Einstellungen exportieren/importieren und GitHub-Backup konfigurieren",goToBackup:"Zur Sicherung",externalUrl:"Externe URL",externalUrlDescription:"Die externe URL, unter der Bambuddy erreichbar ist. Wird für Benachrichtigungsbilder und externe Integrationen verwendet.",bambuddyUrl:"Bambuddy-URL",externalUrlHint:"Protokoll und Port angeben (z.B. http://192.168.1.100:8000)",ftpRetry:"FTP-Wiederholung",ftpRetryDescription:"FTP-Operationen bei unzuverlässigem Drucker-WLAN wiederholen. Gilt für 3MF-Downloads, Druck-Uploads, Zeitraffer-Downloads und Firmware-Updates.",autoRetryDescription:"Fehlgeschlagene FTP-Operationen automatisch wiederholen",retryAttempts:"Wiederholungsversuche",retryDelay:"Wiederholungsverzögerung",connectionTimeout:"Verbindungs-Timeout",time_one:"{{count}} Mal",time_other:"{{count}} Mal",second_one:"{{count}} Sekunde",second_other:"{{count}} Sekunden",nSeconds:"{{count}} Sekunden",increaseForWeakWifi:"Erhöhen für Drucker mit schwachem WLAN",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Mit Home Assistant verbinden, um Smart Plugs über die HA REST-API zu steuern. Unterstützt Switch-, Light-, Input_Boolean- und Script-Entitäten.",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"Langlebiges Zugriffstoken",haTokenHint:"Token in HA erstellen: Profil → Langlebige Zugriffstoken → Token erstellen",connectionSuccessful:"Verbindung erfolgreich",connectionFailed:"Verbindung fehlgeschlagen",haConnectionSuccess:"Erfolgreich mit Home Assistant verbunden.",haConnectionFailed:"Verbindung zu Home Assistant fehlgeschlagen.",mqttPublishing:"MQTT-Veröffentlichung",mqttDescription:"BamBuddy-Ereignisse an einen externen MQTT-Broker zur Integration mit Node-RED, Home Assistant und anderen Automatisierungssystemen veröffentlichen.",mqttEnableDescription:"Ereignisse an externen MQTT-Broker veröffentlichen",brokerHostname:"Broker-Hostname",port:"Port",usernameOptional:"Benutzername (optional)",passwordOptional:"Passwort (optional)",topicPrefix:"Topic-Präfix",topicPrefixHint:"Topics werden sein: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Prometheus-Metriken",prometheusEndpointDescription:"Druckermetriken unter <code>/api/v1/metrics</code> für Prometheus/Grafana-Überwachung bereitstellen.",bearerTokenOptional:"Bearer-Token (optional)",bearerTokenHint:"Wenn gesetzt, müssen Anfragen <code>Authorization: Bearer <token></code> enthalten",metricsConnectionStatus:"Verbindungsstatus",metricsPrinterState:"Druckerstatus (idle/printing/etc)",metricsPrintProgress:"Druckfortschritt 0-100%",metricsBedTemp:"Betttemperatur",metricsNozzleTemp:"Düsentemperatur",metricsPrintsTotal:"Gesamtdrucke nach Ergebnis",metricsMore:"...und mehr (Schichten, Lüfter, Warteschlange, Filamentverbrauch)",smartPlugsDescription:"Smart Plugs (Tasmota oder Home Assistant) verbinden, um Stromsteuerung zu automatisieren und Energieverbrauch für Ihre Drucker zu verfolgen.",allOn:"Alle Ein",allOff:"Alle Aus",addSmartPlug:"Smart Plug hinzufügen",energySummary:"Energieübersicht",currentPower:"Aktuelle Leistung",plugsOnline:"{{reachable}}/{{total}} Plugs online",today:"Heute",yesterday:"Gestern",total:"Gesamt",enablePlugsForSummary:"Plugs aktivieren, um Energieübersicht zu sehen",addNotificationProvider:"Hinzufügen",systemBadge:"(System)",creating:"Erstellen...",changing:"Ändern...",deleteUserAndItems:"Benutzer UND dessen Elemente löschen",deleteUserKeepItems:"Benutzer löschen, Elemente behalten (werden herrenlos)",ok:"OK",twoFa:{totpTitle:"Authenticator-App (TOTP)",totpDesc:"Verwende eine Authenticator-App wie Google Authenticator, Aegis oder Authy.",emailOtpTitle:"E-Mail OTP",emailOtpDesc:"Sende einen Einmalcode an {{email}} beim Einloggen.",emailOtpNoEmail:"Füge eine E-Mail-Adresse zu deinem Konto hinzu, um diese Methode zu aktivieren.",addEmailFirst:"Dein Konto hat keine E-Mail-Adresse. Bitte einen Administrator, eine hinzuzufügen.",setupTotp:"Authenticator-App einrichten",setupAuthApp:"Authenticator-App einrichten",setupInstructions:"Scanne den QR-Code mit deiner Authenticator-App und bestätige mit einem Code.",manualEntry:"Kein Scanner? Gib dieses Secret manuell ein:",scannedContinue:"Code gescannt — weiter",enterCodeToConfirm:"Gib den 6-stelligen Code aus deiner Authenticator-App ein, um die Einrichtung zu bestätigen.",activate:"Aktivieren",disableTotp:"Authenticator deaktivieren",disableConfirmHint:"Gib einen gültigen TOTP-Code oder einen Backup-Code ein, um den Authenticator zu deaktivieren.",totpDisabled:"Authenticator-App deaktiviert.",emailOtpEnabled:"E-Mail OTP aktiviert.",emailOtpDisabled:"E-Mail OTP deaktiviert.",smtpRequired:"Bitte konfigurieren und testen Sie zuerst die SMTP-Einstellungen.",invalidCode:"Ungültiger Code. Bitte erneut versuchen.",enableEmailOtp:"E-Mail OTP aktivieren",disableEmailOtp:"E-Mail OTP deaktivieren",emailSetupEnterCode:"Ein Bestätigungscode wurde an Ihre E-Mail-Adresse gesendet. Geben Sie ihn unten ein, um zu bestätigen, dass Ihnen dieses Postfach gehört.",verifyAndEnable:"Verifizieren & Aktivieren",emailDisablePasswordHint:"Geben Sie Ihr Kontopasswort ein, um die Deaktivierung des E-Mail OTP zu bestätigen.",passwordPlaceholder:"Passwort eingeben",backupCodesTitle:"Backup-Codes sichern",backupCodesWarning:"Speichere diese Codes sicher. Jeder Code kann nur einmal verwendet werden und wird nicht erneut angezeigt.",backupCodesRemaining:"{{count}} Backup-Codes verbleibend",savedCodes:"Codes gespeichert",regenBackup:"Backup-Codes neu generieren",regenBackupHint:"Gib deinen aktuellen TOTP-Code ein, um 10 neue Backup-Codes zu generieren. Alle bestehenden Codes werden ungültig.",newBackupCodes:"Neue Backup-Codes",linkedAccounts:"Verknüpfte SSO-Konten",linkedAccountsDesc:"Diese externen Identitätsanbieter sind mit deinem Konto verknüpft.",oidcUnlinked:"Konto getrennt."},oidc:{title:"SSO / OIDC-Anbieter",desc:"Konfiguriere OpenID Connect-Anbieter für Single Sign-On.",addProvider:"Anbieter hinzufügen",newProvider:"Neuer Anbieter",empty:"Noch keine OIDC-Anbieter konfiguriert.",created:"Anbieter erstellt.",updated:"Anbieter aktualisiert.",deleted:"Anbieter gelöscht.",deleteTitle:"Anbieter löschen",deleteMessage:'"{{name}}" löschen? Alle verknüpften Benutzerkonten werden getrennt.',form:{name:"Anzeigename",issuerUrl:"Aussteller-URL",clientId:"Client-ID",clientSecret:"Client-Secret",scopes:"Scopes",iconUrl:"Symbol-URL (optional)",enabled:"Aktiviert",autoCreate:"Benutzer automatisch anlegen",autoCreateDesc:"Erstellt beim ersten Login automatisch ein lokales Konto.",autoLink:"Bestehende Konten automatisch verknüpfen",autoLinkDesc:"Verknüpft beim ersten Login vorhandene lokale Konten anhand der E-Mail-Adresse.",secretHint:"leer lassen zum Beibehalten",secretPlaceholder:"neues Secret"}}},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",enterEmail:"Bitte geben Sie Ihre E-Mail-Adresse ein",oidcLoginFailed:"OIDC-Anmeldung fehlgeschlagen",oidcErrors:{providerError:"Der Identity-Provider hat einen Fehler zurückgegeben",missingParameters:"Dem OIDC-Callback fehlen erforderliche Parameter",invalidState:"OIDC-State ist ungültig oder wurde bereits verwendet",stateExpired:"OIDC-Sitzung abgelaufen — bitte erneut versuchen",providerNotFound:"OIDC-Provider nicht gefunden",discoveryFailed:"OIDC-Discovery-Dokument konnte nicht abgerufen werden",invalidDiscovery:"OIDC-Discovery-Dokument ist ungültig",networkError:"Netzwerkfehler beim OIDC-Token-Austausch",badResponse:"Unerwartete Antwort beim OIDC-Token-Austausch",noIdToken:"OIDC-Provider hat kein ID-Token zurückgegeben",validationFailed:"OIDC-Token-Validierung fehlgeschlagen",nonceMismatch:"OIDC-Nonce stimmt nicht überein — möglicher Replay-Angriff",missingSubClaim:"OIDC-Token enthält keinen Sub-Claim",noLinkedAccount:"Kein lokales Konto mit dieser OIDC-Identität verknüpft",accountInactive:"Ihr Konto ist inaktiv",userResolutionFailed:"Ihr Konto konnte nicht aufgelöst werden",internalError:"Interner Fehler beim OIDC-Login",tokenExchangeFailed:"OIDC-Token-Austausch fehlgeschlagen"},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",resetPassword:{title:"Neues Passwort festlegen",subtitle:"Geben Sie unten Ihr neues Passwort ein und bestätigen Sie es.",newPassword:"Neues Passwort",newPasswordPlaceholder:"Mindestens 8 Zeichen",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Neues Passwort wiederholen",saving:"Wird gespeichert…",submit:"Neues Passwort festlegen",backToLogin:"Zurück zur Anmeldung",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 8 Zeichen lang sein",resetFailed:"Passwort zurücksetzen fehlgeschlagen. Der Link ist möglicherweise abgelaufen."},twoFA:{title:"Zwei-Faktor-Authentifizierung",subtitle:"Ihr Konto ist mit 2FA geschützt. Geben Sie unten den Bestätigungscode ein.",methodAuthenticator:"Authenticator-App",methodEmail:"E-Mail-Code",methodBackup:"Wiederherstellungscode",instructionsTotp:"Öffnen Sie Ihre Authenticator-App und geben Sie den 6-stelligen Code für Bambuddy ein.",instructionsEmail:"Ein 6-stelliger Code wurde an Ihre E-Mail-Adresse gesendet. Er ist 10 Minuten gültig.",instructionsEmailNotSent:"Klicken Sie unten, um einen Bestätigungscode per E-Mail zu erhalten.",instructionsBackup:"Geben Sie einen Ihrer 8-stelligen Wiederherstellungscodes ein. Jeder Code kann nur einmal verwendet werden.",sendCodeButton:"Code per E-Mail senden",sendingCode:"Wird gesendet...",resendCode:"Code erneut senden",codeLabel:"Bestätigungscode",backupCodeLabel:"Wiederherstellungscode",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"Bestätigen",verifyingButton:"Wird überprüft...",backToLogin:"← Zurück zur Anmeldung",orContinueWith:"oder anmelden mit",signInWith:"Anmelden mit {{provider}}",enterCode:"Bitte geben Sie den Bestätigungscode ein",sendCodeFailed:"Bestätigungscode konnte nicht gesendet werden",invalidCode:"Ungültiger Code. Bitte erneut versuchen."}},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:"Hochladen fehlgeschlagen",zipFilesFailed:"{{count}} Dateien 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",linkExternal:"Extern verknüpfen",linkExternalFolder:"Externen Ordner verknüpfen",linkExternalFolderDescription:"Ein Host-Verzeichnis (NAS, USB, Netzlaufwerk) in den Dateimanager einbinden. Dateien werden nicht kopiert — sie werden direkt vom Originalpfad gelesen.",externalFolderNamePlaceholder:"z.B. NAS-Drucke",externalPath:"Host-Pfad",externalPathHelp:"Absoluter Pfad zum Verzeichnis auf dem Docker-Host. Muss als Bind-Mount in den Container eingebunden sein.",readOnly:"Nur Lesen",readOnlyHelp:"verhindert Uploads und Löschungen",showHiddenFiles:"Versteckte Dateien anzeigen (Punkt-Dateien)",externalFolder:"Externer Ordner",scanFolder:"Scannen",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",externalFolderLinked:"Externer Ordner verknüpft und gescannt",folderScanned:"Scan abgeschlossen: {{added}} hinzugefügt, {{removed}} entfernt",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",totalCost:"Gesamtkosten",total:"Gesamt",includesBom:"inkl. Stückliste",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.",noFiles:"Keine Dateien in diesem Ordner.",print:"Jetzt drucken",addToQueue:"Zur Warteschlange"},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",unlinkConfirmTitle:"Spule entkoppeln?",unlinkConfirmMessage:"Dadurch wird die Spule von Spoolman getrennt. Die Spulendaten in Spoolman bleiben unverändert.",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",unlinkSuccess:"Spule erfolgreich von Spoolman getrennt",unlinkFailed:"Trennen der Spule von 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",spoolName:"Spule",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...",showAllSpools:"Alle Spulen anzeigen",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",weightCheck:"Gewichtskontrolle",lastWeighed:"Zuletzt gewogen",neverWeighed:"Nie gewogen",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)",lowStockThresholdError:"Der Schwellenwert muss zwischen 0.1 und 99.9 liegen",assignMismatchTitle:"Material stimmt nicht überein",assignMismatchMessage:'Das ausgewählte Spulenmaterial "{{spoolMaterial}}" stimmt nicht mit dem Tray-Material "{{trayMaterial}}" für {{location}} überein. Trotzdem zuweisen?',assignMismatchConfirm:"Trotzdem zuweisen",assignPartialMismatchMessage:'Das Spulenmaterial "{{spoolMaterial}}" ist ähnlich, stimmt aber nicht genau mit "{{trayMaterial}}" in {{location}} überein. Möchten Sie fortfahren?',assignProfileMismatchMessage:'Das Spulenprofil "{{spoolProfile}}" stimmt nicht mit dem Fachprofil "{{trayProfile}}" in {{location}} überein. Möchten Sie fortfahren?'},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:",slotRemainingShort:" - {{grams}}g übrig",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",insufficientFilamentTitle:"Nicht genug Filament",insufficientFilamentMessage:"Einige zugewiesene Spulen haben weniger Filament als dieser Druck benötigt:",insufficientFilamentLine:"{{printer}} - {{slot}}: benötigt {{required}}g, verbleibend {{remaining}}g",printAnyway:"Trotzdem drucken",forceColorMatch:"Farbe erzwingen",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Gestaffelt an {{count}} Drucker senden",gcodeInjection:"Auto-Print G-code einfügen"},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",githubBackup:"GitHub Backup",enabled:"Aktiviert",cloudLoginRequired:"Bambu Cloud Login erforderlich. Melden Sie sich unter Profile → Cloud-Profile an, um GitHub-Backup zu aktivieren.",cloudLoginRequiredShort:"Cloud-Login erforderlich",githubDescription:"Synchronisieren Sie Ihre Profile automatisch mit einem privaten GitHub-Repository für Backup und Versionsverlauf.",repositoryUrl:"Repository-URL",personalAccessToken:"Persönlicher Zugriffstoken",tokenSaved:"(gespeichert)",enterNewToken:"Neuen Token eingeben zum Aktualisieren",tokenHint:"Feingranularer Token mit Lese-/Schreibberechtigung für Inhalte",branch:"Branch",manualOnly:"Nur manuell",hourly:"Stündlich",daily:"Täglich",weekly:"Wöchentlich",includeInBackup:"In Sicherung einschließen",kProfiles:"K-Profile",kProfilesDescription:"Druckvorschub-Kalibrierung von verbundenen Druckern",noPrintersConnected:"Keine Drucker verbunden",printersConnected:"{{connected}}/{{total}} verbunden",cloudProfiles:"Cloud-Profile",cloudProfilesDescription:"Filament-, Drucker- und Prozessprofile aus der Bambu Cloud",appSettings:"App-Einstellungen",appSettingsDescription:"Bambuddy-Konfiguration (komplette Datenbank)",spoolInventory:"Spulenbestand",spoolInventoryDescription:"Filamentspulen, Nutzungsverlauf und Kostenverfolgung",printArchives:"Druckarchive",printArchivesDescription:"Druckverlauf-Metadaten (keine GCode/3MF-Dateien)",lastBackupAt:"Letzte Sicherung:",noBackupsYet:"Noch keine Sicherungen",next:"Nächste:",startingBackup:"Sicherung wird gestartet...",test:"Test",enableBackup:"Sicherung aktivieren",testConnection:"Verbindung testen",enterRepoUrl:"Repository-URL eingeben",enterRepoAndToken:"Repository-URL und Zugriffstoken eingeben",repoRequired:"Repository-URL ist erforderlich",tokenRequired:"Zugriffstoken ist erforderlich",githubBackupEnabled:"GitHub-Backup aktiviert",tokenUpdated:"Token aktualisiert",settingsSaved:"Einstellungen gespeichert",failedToSave:"Speichern fehlgeschlagen: {{message}}",backupCompleteFiles:"Sicherung abgeschlossen - {{count}} Dateien aktualisiert",backupSkippedNoChanges:"Sicherung übersprungen - keine Änderungen",backupFailed2:"Sicherung fehlgeschlagen: {{message}}",clearedLogs:"{{count}} Protokolle gelöscht",failedToClearLogs:"Protokolle löschen fehlgeschlagen: {{message}}",history:"Verlauf",clear:"Löschen",date:"Datum",status:"Status",commit:"Commit",localBackup:"Lokale Sicherung",localBackupDescription:"Erstellen Sie eine vollständige Sicherung Ihrer Bambuddy-Daten einschließlich Datenbank, Archive, Uploads und aller Dateien.",downloadBackupLabel:"Sicherung herunterladen",completeBackupZip:"Vollständige Sicherung: Datenbank + alle Dateien (ZIP)",download:"Herunterladen",preparingBackup:"Sicherung wird vorbereitet...",creatingArchive:"Sicherungsarchiv wird erstellt... Dies kann bei großen Archiven eine Weile dauern.",downloadingFile:"Sicherungsdatei wird heruntergeladen...",backupDownloaded:"Sicherung erfolgreich heruntergeladen",failedToCreateBackup:"Sicherung erstellen fehlgeschlagen: {{message}}",restore:"Wiederherstellen",restoreReplacesAll:"Wiederherstellung ersetzt alle Daten.",restoreReplacesAllDetail:"Ihre aktuelle Datenbank und Dateien werden vollständig ersetzt. Nach der Wiederherstellung ist ein Neustart erforderlich.",restoreConfirmTitle:"Sicherung wiederherstellen",restoreConfirmMessage:'Sind Sie sicher, dass Sie von "{{filename}}" wiederherstellen möchten? Dies ersetzt Ihre aktuelle Datenbank und alle Dateien vollständig. Die Anwendung muss nach der Wiederherstellung neu gestartet werden.',restoreConfirmButton:"Sicherung wiederherstellen",uploadingFile:"Sicherungsdatei wird hochgeladen...",backupRestoredRestart:"Sicherung wiederhergestellt. Bitte starten Sie Bambuddy neu.",failedToRestore:"Sicherung wiederherstellen fehlgeschlagen. Bitte überprüfen Sie das Dateiformat.",reloadNow:"Jetzt neu laden",creatingBackup:"Sicherung erstellen",restoringBackup:"Sicherung wiederherstellen",preparing:"Vorbereiten...",processing:"Verarbeiten...",doNotClosePage:"Bitte schließen Sie diese Seite nicht und navigieren Sie nicht weg. Dieser Vorgang kann bei großen Sicherungen mehrere Minuten dauern.",restoring:"Wiederherstellen...",restoreComplete:"Wiederherstellung abgeschlossen",restoreFailed2:"Wiederherstellung fehlgeschlagen",importSettings:"Einstellungen aus einer Sicherungsdatei importieren",pleaseWaitRestoring:"Bitte warten Sie, während Ihre Daten wiederhergestellt werden",selectBackupFile:"Klicken Sie, um eine Sicherungsdatei auszuwählen (.json oder .zip)",duplicateHandling:"So funktioniert die Duplikatbehandlung:",matchPrinters:"Drucker",matchPrintersBy:"abgeglichen nach Seriennummer",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"abgeglichen nach IP-Adresse",matchNotificationProviders:"Benachrichtigungsanbieter",matchNotificationProvidersBy:"abgeglichen nach Name",matchFilaments:"Filamente",matchFilamentsBy:"abgeglichen nach Name + Typ + Marke",matchArchives:"Archive",matchArchivesBy:"abgeglichen nach Inhaltshash (immer übersprungen)",matchPendingUploads:"Ausstehende Uploads",matchPendingUploadsBy:"abgeglichen nach Dateiname",matchSettingsTemplates:"Einstellungen & Vorlagen",matchSettingsTemplatesBy:"immer überschrieben",replaceExisting:"Vorhandene Daten ersetzen",keepExisting:"Vorhandene Daten behalten",overwriteDescription:"Bereits vorhandene Elemente mit Sicherungsdaten überschreiben",keepDescription:"Nur Elemente wiederherstellen, die noch nicht vorhanden sind",overwriteCaution:"Achtung:",overwriteWarning:"Das Überschreiben ersetzt Ihre aktuellen Konfigurationen durch Daten aus der Sicherung. Drucker-Zugangscodes werden aus Sicherheitsgründen nie überschrieben.",cancel:"Abbrechen",processingBackup:"Sicherungsdatei wird verarbeitet...",itemsRestored:"Wiederhergestellt",itemsSkipped:"Übersprungen",restored:"Wiederhergestellt",skippedAlreadyExist:"Übersprungen (bereits vorhanden)",filesCategory:"Dateien (3MF, Thumbnails, etc.)",andMore:"...und {{count}} weitere",newApiKeysGenerated:"Neue API-Schlüssel generiert",keysShownOnce:"Diese Schlüssel werden nur einmal angezeigt. Kopieren Sie sie jetzt!",copy:"Kopieren",noDataFound:"In der Sicherungsdatei wurden keine Daten zur Wiederherstellung gefunden.",close:"Schließen",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"Einstellungen",notification_providers:"Benachrichtigungsanbieter",notification_templates:"Benachrichtigungsvorlagen",smart_plugs:"Smart Plugs",printers:"Drucker",filaments:"Filamente",maintenance_types:"Wartungstypen",archives:"Archive",projects:"Projekte",pending_uploads:"Ausstehende Uploads",external_links:"Externe Links",api_keys:"API-Schlüssel"}},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"},autoDispatch:{title:"Automatisch starten",description:"Drucke automatisch starten, wenn sie zur Warteschlange hinzugefügt werden. Wenn deaktiviert, warten Drucke auf manuellen Start."},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",lubricateSteelRods:"Schmiermittel auf Stahlstangen für sanfte Bewegung auftragen",cleanSteelRods:"Stahlstangen 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"}},linkedTo:"Verbunden mit:",monitorOnly:"Nur Überwachung",alerts:"Alarme",scheduleOn:"Ein {{time}}",scheduleOff:"Aus {{time}}",on:"Ein",off:"Aus",power:"Leistung",kwhToday:"kWh Heute",settings:"Einstellungen",automationSettings:"Automatisierungseinstellungen",showInSwitchbar:"In Schaltleiste anzeigen",quickAccessSidebar:"Schnellzugriff über Seitenleiste",enabled:"Aktiviert",enableAutomation:"Automatisierung für diesen Stecker aktivieren",autoOn:"Auto Ein",autoOnDescription:"Einschalten wenn Druck startet",autoOff:"Auto Aus",autoOffDescription:"Ausschalten wenn Druck abgeschlossen (einmalig)",autoOffPersistent:"Aktiviert lassen",autoOffPersistentDescription:"Zwischen Drucken aktiviert bleiben statt einmalig",turnOffDelayMode:"Ausschaltverzögerungsmodus",time:"Zeit",temp:"Temp",delayMinutes:"Verzögerung (Minuten)",tempThreshold:"Temperaturschwelle (°C)",tempThresholdDescription:"Schaltet aus wenn die Düse unter diese Temperatur abkühlt",edit:"Bearbeiten",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen? Dies kann nicht rückgängig gemacht werden.',turnOnConfirm:'Möchten Sie "{{name}}" wirklich einschalten?',turnOffConfirm:'Möchten Sie "{{name}}" wirklich ausschalten? Dies unterbricht die Stromversorgung des angeschlossenen Geräts.',failedToTurn:'{{name}}" konnte nicht {{action}} werden',unknown:"Unbekannt",addTitle:"Smart Plug hinzufügen",editTitle:"Smart Plug bearbeiten",stopScanning:"Suche beenden",discoverTasmota:"Tasmota Geräte suchen",foundDevices:"{{count}} Gerät(e) gefunden - zum Auswählen klicken:",noDevicesFound:"Keine Tasmota Geräte in Ihrem Netzwerk gefunden",haNotConfigured:"Home Assistant ist nicht konfiguriert. Einrichtung unter",haSettingsPath:"Einstellungen → Netzwerk → Home Assistant",selectEntity:"Entität auswählen *",ipAddress:"IP-Adresse *",nameLabel:"Name *",username:"Benutzername",password:"Passwort",authHint:"Leer lassen, wenn Ihr Tasmota-Gerät keine Authentifizierung benötigt",linkToPrinter:"Mit Drucker verbinden",noPrinter:"Kein Drucker (nur manuelle Steuerung)",linkingDescription:"Verknüpfung ermöglicht automatisches Ein-/Ausschalten bei Druckstart/-ende",powerAlerts:"Leistungsalarme",alertAbove:"Alarm wenn über (W)",alertBelow:"Alarm wenn unter (W)",alertDescription:"Benachrichtigung wenn der Stromverbrauch diese Schwellenwerte überschreitet. Leer lassen um diese Richtung zu deaktivieren.",dailySchedule:"Tagesplan",turnOnAt:"Einschalten um",turnOffAt:"Ausschalten um",scheduleDescription:"Den Stecker automatisch täglich zu diesen Zeiten ein-/ausschalten. Leer lassen um diese Aktion zu überspringen.",showOnPrinterCard:"Auf Druckerkarte anzeigen",displayOnPrinterCard:"Schaltfläche auf Druckerkarte anzeigen",connectedResult:"Verbunden!",deviceLabel:"Gerät: {{name}} - ",stateLabel:"Status: {{state}}",test:"Test",delete:"Löschen",save:"Speichern",add:"Hinzufügen",cancel:"Abbrechen",failedToStartScan:"Suche konnte nicht gestartet werden",nameRequired:"Name ist erforderlich",entityRequired:"Entität ist für Home Assistant Stecker erforderlich",mqttTopicRequired:"Mindestens ein MQTT-Topic muss für Leistung, Energie oder Statusüberwachung konfiguriert sein",loadingEntities:"Entitäten werden geladen...",loading:"Laden...",failedToLoadEntities:"Entitäten konnten nicht geladen werden: {{error}}",noEntitiesMatching:'Keine Entitäten gefunden die "{{search}}" entsprechen',noEntitiesAvailable:"Keine Entitäten verfügbar",searchingEntities:"Alle Entitäten durchsuchen ({{count}} gefunden)",showingEntities:"Zeige switch, light, input_boolean ({{count}} verfügbar)",energyMonitoringOptional:"Energieüberwachung (Optional)",energyMonitoringHint:"Sensoren suchen und auswählen, die Leistungs-/Energiedaten liefern.",powerSensorW:"Leistungssensor (W)",energyTodayKwh:"Energie Heute (kWh)",totalEnergyKwh:"Gesamtenergie (kWh)",noMatchingSensors:"Keine passenden Sensoren",none:"Keine",mqttNotConfigured:"MQTT-Broker nicht konfiguriert. Broker-Adresse einstellen unter",mqttSettingsPath:"Einstellungen → Netzwerk → MQTT-Veröffentlichung",mqttNotConfiguredSuffix:"(Sie müssen die Veröffentlichung nicht aktivieren, nur die Broker-Details ausfüllen).",mqttMonitorOnlyDescription:"MQTT-Stecker empfangen Leistungs-/Energiedaten über MQTT-Abonnement. Ein-/Ausschalten ist nicht verfügbar - verwenden Sie Ihren MQTT-Broker oder Ihr Home-Automation-System.",powerMonitoring:"Leistungsüberwachung",energyMonitoring:"Energieüberwachung",stateMonitoring:"Statusüberwachung",optional:"optional",topic:"Topic",jsonPath:"JSON-Pfad",multiplier:"Multiplikator",onValue:"EIN-Wert",mqttPowerHint:`JSON-Pfad extrahiert Wert aus JSON-Payload (z.B. "power_l1"). Leer lassen wenn Topic rohe numerische Werte sendet.
- Multiplikator 0.001 für mW→W, 1000 für kW→W verwenden.`,mqttEnergyHint:`JSON-Pfad extrahiert Wert aus JSON-Payload. Leer lassen für rohe Werte.
- Multiplikator 0.001 für Wh→kWh, 1000 für MWh→kWh verwenden.`,mqttStateHint:`JSON-Pfad extrahiert Wert aus JSON-Payload. Leer lassen für rohe Werte.
- EIN-Wert: der genaue String der "EIN" bedeutet. Leer lassen für Auto-Erkennung (ON, true, 1).`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"Power URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"Power Multiplikator",restEnergyUrl:"Energie URL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Energie Multiplikator",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"Eigene URL für Leistungsdaten (nutzt Status URL wenn leer)",restEnergyUrlHint:"Eigene URL für Energiedaten (nutzt Status URL wenn leer)",restEnergyHint:"Jeder Wert kann eine eigene URL verwenden oder auf die Status URL zurückgreifen. Multiplikatoren für Einheitenumrechnung verwenden (z.B. 0.001 für Wh zu kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Keine Schalter in der Schaltleiste",enableSwitchbarHint:'"In Schaltleiste anzeigen" unter Einstellungen > Smart Plugs aktivieren'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-Mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTP-E-Mail-Benachrichtigungen",telegram:"Benachrichtigungen über Telegram-Bot",discord:"An Discord-Kanal per Webhook senden",ntfy:"Kostenlose, selbst-hostbare Push-Benachrichtigungen",pushover:"Einfache, zuverlässige Push-Benachrichtigungen",callmebot:"Kostenlose WhatsApp-Benachrichtigungen über CallMeBot",webhook:"Generischer HTTP-POST an beliebige URL",homeassistant:"Dauerhafte Benachrichtigungen im Home Assistant Dashboard"},lastSuccess:"Zuletzt: {{date}}",error:"Fehler",printer:"Drucker:",allPrinters:"Alle Drucker",sendTestNotification:"Testbenachrichtigung senden",eventSettings:"Ereigniseinstellungen",enabled:"Aktiviert",sendFromProvider:"Benachrichtigungen von diesem Anbieter senden",printEvents:"Druckereignisse",printerStatus:"Druckerstatus",amsAlarms:"AMS-Alarme",amsHtAlarms:"AMS-HT-Alarme",printQueue:"Druckwarteschlange",start:"Start",plateCheck:"Plattenkontrolle",complete:"Abgeschlossen",failed:"Fehlgeschlagen",stopped:"Gestoppt",progress:"Fortschritt",offline:"Offline",lowFilament:"Filament niedrig",maintenance:"Wartung",amsHumidity:"AMS-Feuchtigkeit",amsTemp:"AMS-Temperatur",amsHtHumidity:"AMS-HT-Feuchtigkeit",amsHtTemp:"AMS-HT-Temperatur",bedCooled:"Bett abgekühlt",firstLayer:"Erste Schicht",quiet:"Ruhe",digest:"Zusammenfassung {{time}}",printStarted:"Druck gestartet",plateNotEmpty:"Platte nicht leer",plateNotEmptyDescription:"Objekte vor dem Druck erkannt",printCompleted:"Druck abgeschlossen",bedCooledLabel:"Bett abgekühlt",bedCooledDescription:"Bett nach dem Druck unter Schwellenwert abgekühlt",firstLayerCompleteLabel:"Erste Schicht fertig",firstLayerCompleteDescription:"Benachrichtigung mit Foto nach erster Schicht",missingSpoolAssignmentLabel:"Fehlende Spulenzuordnung",missingSpoolAssignmentDescription:"Benachrichtigen, wenn ein Druck startet und benoetigte Schaechte keine zugeordnete Spule haben",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",progressMilestones:"Fortschrittsmeilensteine",progressMilestonesDescription:"Benachrichtigung bei 25%, 50%, 75%",printerOffline:"Drucker offline",printerError:"Druckerfehler",lowFilamentLabel:"Filament niedrig",maintenanceDue:"Wartung fällig",maintenanceDueDescription:"Benachrichtigen, wenn Wartung erforderlich ist",amsHumidityHigh:"AMS-Feuchtigkeit hoch",amsHumidityHighDescription:"Normale AMS-Feuchtigkeit überschreitet Schwellenwert",amsTemperatureHigh:"AMS-Temperatur hoch",amsTemperatureHighDescription:"Normale AMS-Temperatur überschreitet Schwellenwert",amsHtHumidityHigh:"AMS-HT-Feuchtigkeit hoch",amsHtHumidityHighDescription:"AMS-HT-Feuchtigkeit überschreitet Schwellenwert",amsHtTemperatureHigh:"AMS-HT-Temperatur hoch",amsHtTemperatureHighDescription:"AMS-HT-Temperatur überschreitet Schwellenwert",jobAdded:"Auftrag hinzugefügt",jobAddedDescription:"Auftrag zur Warteschlange hinzugefügt",jobAssigned:"Auftrag zugewiesen",jobAssignedDescription:"Modellbasierter Auftrag einem Drucker zugewiesen",jobStarted:"Auftrag gestartet",jobStartedDescription:"Warteschlangenauftrag hat Druck begonnen",jobWaiting:"Auftrag wartet",jobWaitingDescription:"Auftrag wartet auf Filament oder Drucker",jobSkipped:"Auftrag übersprungen",jobSkippedDescription:"Auftrag übersprungen (vorheriger fehlgeschlagen)",jobFailed:"Auftrag fehlgeschlagen",jobFailedDescription:"Auftrag konnte nicht gestartet werden",queueComplete:"Warteschlange abgeschlossen",queueCompleteDescription:"Alle Warteschlangenaufträge beendet",quietHours:"Ruhezeiten",noNotificationsDuring:"Keine Benachrichtigungen während dieser Zeiten",editProviderToChangeQuietHours:"Anbieter bearbeiten, um Ruhezeiten zu ändern",dailyDigest:"Tägliche Zusammenfassung",batchNotifications:"Benachrichtigungen zu einer täglichen Zusammenfassung bündeln",sendAt:"Senden um {{time}}",editProviderToChangeDigestTime:"Anbieter bearbeiten, um Zusammenfassungszeit zu ändern",edit:"Bearbeiten",deleteProvider:"Benachrichtigungsanbieter löschen",deleteConfirm:'Sind Sie sicher, dass Sie "{{name}}" löschen möchten? Dies kann nicht rückgängig gemacht werden.',delete:"Löschen",addTitle:"Benachrichtigungsanbieter hinzufügen",editTitle:"Benachrichtigungsanbieter bearbeiten",nameLabel:"Name *",namePlaceholder:"Meine Benachrichtigungen",providerTypeLabel:"Anbietertyp *",configuration:"Konfiguration",testConfiguration:"Konfiguration testen",printerFilter:"Druckerfilter",onlyFromPrinter:"Nur Benachrichtigungen für Ereignisse von diesem Drucker senden",quietHoursDnd:"Ruhezeiten (Nicht stören)",quietStart:"Start",quietEnd:"Ende",dailyDigestLabel:"Tägliche Zusammenfassung",sendDigestAt:"Zusammenfassung senden um",digestCollected:"Ereignisse werden gesammelt und als einzelne Zusammenfassung zu dieser Zeit gesendet",notificationEvents:"Benachrichtigungsereignisse",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(nach Druckabschluss)",cancel:"Abbrechen",save:"Speichern",add:"Hinzufügen",nameRequired:"Name ist erforderlich",fieldRequired:"{{field}} ist erforderlich",phoneNumber:"Telefonnummer",apiKey:"API-Schlüssel",serverUrl:"Server-URL",topic:"Thema",authToken:"Auth-Token",userKey:"Benutzerschlüssel",appToken:"App-Token",priority:"Priorität",botToken:"Bot-Token",chatId:"Chat-ID",smtpServer:"SMTP-Server",smtpPort:"SMTP-Port",security:"Sicherheit",authentication:"Authentifizierung",username:"Benutzername",password:"Passwort",fromEmail:"Absender-E-Mail",toEmail:"Empfänger-E-Mail",webhookUrl:"Webhook-URL",payloadFormat:"Payload-Format",authorization:"Autorisierung",titleFieldName:"Titel-Feldname",messageFieldName:"Nachrichten-Feldname",editTemplate:"Vorlage bearbeiten: {{name}}",titleLabel:"Titel",bodyLabel:"Inhalt",titlePlaceholder:"Benachrichtigungstitel...",bodyPlaceholder:"Benachrichtigungsinhalt...",availableVariables:"Verfügbare Variablen",clickToInsert:"Klicken, um an Cursorposition im Inhalt einzufügen",livePreview:"Live-Vorschau",hide:"Ausblenden",show:"Anzeigen",loadingPreview:"Vorschau wird geladen...",enterTemplateContent:"Vorlageninhalt eingeben, um Vorschau zu sehen",titlePreview:"Titel:",bodyPreview:"Inhalt:",resetToDefault:"Auf Standard zurücksetzen",titleRequired:"Titel ist erforderlich",bodyRequired:"Inhalt ist erforderlich",notificationLog:"Benachrichtigungsprotokoll",showFailedOnly:"Nur fehlgeschlagene",last24Hours:"Letzte 24 Stunden",last7Days:"Letzte 7 Tage",last30Days:"Letzte 30 Tage",last90Days:"Letzte 90 Tage",justNow:"Gerade eben",noFailedNotifications:"Keine fehlgeschlagenen Benachrichtigungen",noNotificationsLogged:"Keine Benachrichtigungen protokolliert",unknownProvider:"Unbekannter Anbieter",logTitle:"Titel",logMessage:"Nachricht",logError:"Fehler",logProvider:"Anbieter: {{type}}",logTime:"Zeit: {{time}}",refresh:"Aktualisieren",clearOld:"Alte löschen",statsSummary:"Letzte {{days}} Tage:",statsNotifications:"Benachrichtigungen",statsSent:"{{count}} gesendet",statsFailed:"{{count}} fehlgeschlagen",eventTypes:{print_start:"Druck gestartet",print_complete:"Druck abgeschlossen",print_failed:"Druck fehlgeschlagen",print_stopped:"Druck gestoppt",print_progress:"Fortschritt",printer_offline:"Drucker offline",printer_error:"Druckerfehler",filament_low:"Filament niedrig",maintenance_due:"Wartung fällig",test:"Test"},userEmail:{title:"Benachrichtigungen",emailNotifications:"E-Mail-Benachrichtigungen",emailNotificationsDesc:"Erhalten Sie E-Mail-Benachrichtigungen für Ihre eigenen Druckaufträge. E-Mails werden über die in der erweiterten Authentifizierung konfigurierten SMTP-Einstellungen gesendet.",sendingTo:"Benachrichtigungen werden gesendet an",noEmailWarning:"Ihr Konto hat keine E-Mail-Adresse. Wenden Sie sich an einen Administrator, um eine hinzuzufügen.",printJobNotifications:"Druckauftrags-Benachrichtigungen",printJobNotificationsDesc:"Wählen Sie aus, welche Ereignisse E-Mail-Benachrichtigungen für von Ihnen gesendete Druckaufträge auslösen.",printJobStarts:"Druckauftrag startet",printJobStartsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag beginnt.",printJobFinishes:"Druckauftrag fertig",printJobFinishesDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag erfolgreich abgeschlossen wurde.",printErrors:"Druckfehler",printErrorsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag fehlschlägt oder auf einen Fehler stößt.",printJobStops:"Druckauftrag gestoppt",printJobStopsDesc:"Benachrichtigt werden, wenn Ihr Druckauftrag abgebrochen oder gestoppt wird.",saveSuccess:"Benachrichtigungseinstellungen gespeichert.",saveError:"Benachrichtigungseinstellungen konnten nicht gespeichert werden."}},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",writeTag:"Schreiben",settings:"Einstellungen"},status:{nfcReady:"NFC bereit",nfcOff:"NFC aus",offline:"Offline",online:"Online",noPrinters:"Keine Drucker",deviceOffline:"Gerät offline",waitingConnection:"Warte auf Geräteverbindung...",systemReady:"System bereit",status:"Status"},dashboard:{readyToScan:"Bereit zum Scannen",idleMessage:"Spule auf die Waage legen zum Identifizieren",nfcHint:"NFC-Tag wird automatisch gelesen",device:"Gerät",syncWeight:"Gewicht sync.",weightSynced:"Synchronisiert!",unknownTag:"Unbekannter Tag",newTag:"Neuer Tag erkannt",onScale:"auf der Waage",linkSpool:"Mit Spule verknüpfen",linkTagTitle:"Tag mit Spule verknüpfen",linkTag:"Tag verknüpfen",selectSpool:"Spule zum Verknüpfen auswählen:",noUntagged:"Keine Spulen ohne Tags gefunden",tagDetected:"Tag erkannt",noTag:"Kein Tag",tagId:"Tag",grossWeight:"Bruttogewicht",spoolSize:"Spulengröße",close:"Schließen",currentSpool:"Aktuelle Spule"},modal:{spoolDetected:"Spule erkannt",assignToAms:"AMS zuweisen",syncWeight:"Gewicht sync.",weightSynced:"Synchronisiert!",syncing:"Synchronisiere...",newTagDetected:"Neuer Tag erkannt",addToInventory:"Zum Inventar hinzufügen",assignToAmsTitle:"AMS zuweisen",selectSlot:"Slot auswählen",assign:"Zuweisen",assigning:"Zuweisen...",assignSuccess:"Zugewiesen!",assignError:"Fehler beim Zuweisen. Bitte erneut versuchen.",noPrinterSelected:"Drucker auswählen...",noAmsDetected:"Kein AMS an diesem Drucker erkannt",slot:"Slot"},weight:{noReading:"Kein Messwert",stable:"Stabil",measuring:"Messen...",tare:"Tarieren",calibrate:"Kalibrieren"},spool:{remaining:"Verbleibend",material:"Material",brand:"Marke",color:"Farbe",coreWeight:"Kern",labelWeight:"Etikett",scaleWeight:"Waage",netWeight:"Netto",lastUsed:"Zuletzt verwendet"},ams:{noData:"Kein AMS erkannt",connectAms:"AMS anschließen um Filament-Slots zu sehen",noPrinter:"Kein Drucker ausgewählt",selectPrinter:"Drucker in der oberen Leiste auswählen",printerDisconnected:"Drucker getrennt",humidity:"Feuchtigkeit",level:"Stufe",active:"Aktiv",slot:"Slot",empty:"Leer"},inventory:{search:"Spulen suchen...",empty:"Keine Spulen im Inventar",noResults:"Keine passenden Spulen",spools:"Spulen",addSpool:"Spule hinzufügen"},settings:{tabDevice:"Gerät",tabDisplay:"Anzeige",tabScale:"Waage",tabUpdates:"Updates",nfcReader:"NFC-Leser",type:"Typ",connection:"Verbindung",notConnected:"N/A",deviceInfo:"Geräteinfo",hostname:"Host",uptime:"Betriebszeit",systemConfig:"Backend & Auth",backendUrl:"Bambuddy Backend URL",apiToken:"API-Token",apiTokenPlaceholder:"API-Token eingeben",saveConfig:"Konfiguration speichern",systemQueued:"Konfiguration in Warteschlange.",nfcDiagnostic:"NFC-Diagnose",scaleDiagnostic:"Waagen-Diagnose",readTagDiagnostic:"Tag-Lese-Diagnose",testNfc:"Leser testen",testScale:"Genauigkeit testen",testReadTag:"Tag lesen",systemFieldsRequired:"Backend-URL ist erforderlich.",brightness:"Helligkeit",saved:"Gespeichert",noBacklight:"Keine DSI-Hintergrundbeleuchtung erkannt. Helligkeitssteuerung erfordert ein DSI-Display.",screenBlank:"Bildschirm-Abschaltzeit",screenBlankDesc:"Bildschirm schaltet sich nach Inaktivität ab. Zum Aufwecken berühren.",displayNote:"Helligkeit wird als Software-Filter angewendet.",scaleCalibration:"Waagen-Kalibrierung",currentWeight:"Aktuelles Gewicht",tareOffset:"Tara",calFactor:"Faktor",knownWeight:"Bekanntes Gewicht",calStep1:"Alle Gegenstände von der Waage entfernen und Nullpunkt setzen.",calStep2:"Bekanntes Gewicht auf die Waage legen.",setZero:"Nullpunkt setzen",calibrateNow:"Kalibrieren",calibrated:"Kalibriert",tareSet:"Tara-Befehl gesendet. Warte auf Gerät...",tareFailed:"Tara-Befehl fehlgeschlagen",zeroSet:"Nullpunkt gesetzt. Bekanntes Gewicht auf die Waage legen.",calibrationDone:"Kalibrierung abgeschlossen!",calibrationFailed:"Kalibrierung fehlgeschlagen",lastCalibrated:"Zuletzt kalibriert",stable:"Stabil",settling:"Stabilisierung...",firmware:"Firmware",scale:"Waage",noDevice:"Kein SpoolBuddy-Gerät gefunden",daemonVersion:"Daemon-Version",currentVersion:"Aktuell",versionPending:"Warte auf Daemon...",checking:"Prüfe...",checkUpdates:"Nach Updates suchen",updateAvailable:"Update verfügbar",updateInstructions:"Update per SSH: SpoolBuddy-Installationsskript ausführen.",upToDate:"Aktuell",includeBeta:"Beta-Versionen einschließen"},writeTag:{tabExisting:"Vorhandene Spule",tabNew:"Neue Spule",tabReplace:"Tag ersetzen",searchPlaceholder:"Suche nach Material, Farbe, Marke...",noUntaggedSpools:"Keine Spulen ohne Tags",noTaggedSpools:"Keine Spulen mit Tags",selectSpool:"Spule auswählen, dann einen NTAG auf den Leser legen",placeTag:"NTAG auf den Leser legen",tagReady:"Tag erkannt — bereit zum Schreiben",writeTag:"Tag beschreiben",replaceTag:"Tag ersetzen",writing:"Tag wird beschrieben...",waiting:"Warte auf SpoolBuddy...",writeSuccess:"Tag erfolgreich beschrieben!",writeFailed:"Schreiben fehlgeschlagen",queueFailed:"Schreibbefehl konnte nicht eingereiht werden",tryAgain:"Erneut versuchen",cancel:"Abbrechen",replaceWarning:"Alter Tag wird getrennt. Neuer Tag ersetzt ihn.",deviceOffline:"SpoolBuddy ist offline",material:"Material",colorName:"Farbname",color:"Farbe",brand:"Marke",weight:"Gewicht (g)",createSpool:"Spule erstellen",creating:"Wird erstellt...",spoolCreated:"Spule erstellt! Bereit zum Schreiben.",createFailed:"Spule konnte nicht erstellt werden"},quickMenu:{printerPower:"Drucker-Strom",systemControls:"System",restartDaemon:"Daemon neustarten",restartBrowser:"Browser neustarten",reboot:"Neustart",shutdown:"Herunterfahren",swipeToClose:"Nach unten wischen zum Schließen",confirmTitle:"Bestätigen",confirmShutdown:"Möchten Sie das SpoolBuddy wirklich herunterfahren? Sie benötigen physischen Zugang, um es wieder einzuschalten.",confirmReboot:"Möchten Sie das SpoolBuddy wirklich neu starten?",confirmRestartDaemon:"SpoolBuddy-Daemon neustarten? NFC und Waage sind vorübergehend nicht verfügbar.",confirmRestartBrowser:"Kiosk-Browser neustarten? Das Display wird kurz schwarz.",confirm:"Bestätigen",confirmPlugOn:"{{name}} einschalten?",confirmPlugOff:"{{name}} ausschalten?",turnOn:"Einschalten",turnOff:"Ausschalten"}},bugReport:{title:"Fehler melden",description:"Beschreibung",descriptionPlaceholder:"Was ist schiefgelaufen? Bitte beschreiben Sie das Problem...",email:"E-Mail (optional)",emailPlaceholder:"ihre@email.de",emailPrivacy:"Falls angegeben, wird Ihre E-Mail in einem eingeklappten Abschnitt des GitHub-Issues aufgeführt, damit der Betreuer sich melden kann.",screenshot:"Screenshot",uploadOrPaste:"Bild hochladen, einfügen oder ziehen",dataCollectedSummary:"Welche Daten werden im Bericht gesendet?",dataIncluded:"Enthalten:",dataIncludedList:"App-Version, Betriebssystem, Architektur, Python-Version, Datenbankstatistiken (nur Anzahl), Druckermodelle, Düsenanzahl, Firmware-Versionen, Verbindungsstatus, Integrationsstatus (Spoolman, MQTT, HA), nicht-sensible Einstellungen, Netzwerkschnittstellenanzahl, Docker-Details, Abhängigkeitsversionen.",dataNeverIncluded:"Nie enthalten:",dataNeverIncludedList:"Druckernamen, Seriennummern, Zugangscodes, Passwörter, IP-Adressen, E-Mail-Adressen, API-Schlüssel, Tokens, Webhook-URLs, Hostnamen oder Benutzernamen.",submit:"Absenden",startLogging:"Debug-Protokollierung starten",stepEnableLogging:"Debug-Protokollierung aktiviert",stepReproduce:"Problem jetzt reproduzieren",stepStopLogging:"Stoppen & Bericht senden",stopAndSubmit:"Stoppen & Senden",maxDuration:"Stoppt automatisch nach {{minutes}} Min.",stoppingLogs:"Protokolle sammeln & senden...",submitting:"Fehlerbericht wird gesendet...",submitSuccess:"Fehlerbericht erfolgreich gesendet!",submitFailed:"Fehlerbericht konnte nicht gesendet werden",thankYou:"Vielen Dank!",submitted:"Ihr Fehlerbericht wurde eingereicht.",viewIssue:"Issue ansehen",unexpectedError:"Ein unerwarteter Fehler ist aufgetreten"},failureDetection:{title:"KI-Fehlererkennung",description:"Überwacht Drucke über eine selbst gehostete Obico-ML-API und reagiert automatisch auf erkannte Fehldrucke.",mlUrl:"Obico-ML-API-URL",mlUrlHint:"Basis-URL deines selbst gehosteten Obico-ml_api-Containers (z. B. http://192.168.1.10:3333).",test:"Testen",testSuccess:"ML-API erreichbar und funktionsfähig.",testFailed:"ML-API konnte nicht erreicht werden.",sensitivity:"Empfindlichkeit",sensitivityLow:"Niedrig (weniger Fehlalarme)",sensitivityMedium:"Mittel (ausgewogen)",sensitivityHigh:"Hoch (frühe Erkennung, mehr Fehlalarme)",sensitivityHint:"Passt die Konfidenz-Schwellwerte an, die Warnungen und Fehler auslösen.",action:"Aktion bei erkanntem Fehler",actionNotify:"Nur benachrichtigen",actionPause:"Druck pausieren",actionPauseOff:"Pausieren und Strom abschalten",pollInterval:"Prüfintervall (Sekunden)",pollIntervalHint:"Wie oft jeder Drucker während eines laufenden Drucks geprüft wird. Minimum 5 s, Maximum 120 s.",externalUrlMissing:"Externe URL ist nicht gesetzt.",externalUrlHint:"Die ML-API lädt das Kamerabild per URL. Setze die Externe URL in den allgemeinen Einstellungen, damit der ML-API-Container Bambuddy erreichen kann.",perPrinterTitle:"Überwachte Drucker",perPrinterHint:"Wähle, welche Drucker vom Erkennungsdienst überwacht werden.",monitorAll:"Alle verbundenen Drucker überwachen",statusTitle:"Status",serviceRunning:"Dienst läuft",thresholds:"Niedrig / Hoch-Schwellwerte",activePrinters:"Aktive Drucke",noActivePrints:"Derzeit laufen keine Drucke.",historyTitle:"Letzte Erkennungen",noHistory:"Noch keine Erkennungen."}},Bue={nav:{printers:"Imprimantes",archives:"Archives",queue:"File d'attente",stats:"Statistiques",profiles:"Profils",maintenance:"Maintenance",projects:"Projets",inventory:"Filament",files:"Gestionnaire de fichiers",notifications:"Notifications",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",uploading:"Téléversement...",uploadFailed:"Échec du téléversement",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",back:"Retour",copy:"Copier",copied:"Copié !",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",problem:"Problème",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",search:"Rechercher des imprimantes...",noSearchResults:"Aucune imprimante ne correspond à votre recherche ou à vos filtres",filter:{allStatuses:"Tous les statuts",allLocations:"Tous les emplacements"},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",files:"Fichiers",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",forceRefresh:"Forcer l'actualisation",forceRefreshSuccess:"Actualisation demandée",mqttDebug:"Débogage MQTT",printerInformation:"Informations imprimante",copyToClipboard:"Copier",copied:"Copié !",state:"État",wifiSignalLabel:"Signal WiFi",developerMode:"Mode développeur",enabled:"Activé",disabled:"Désactivé",addedOn:"Ajoutée le",sdCard:"Carte SD",inserted:"Insérée",notInserted:"Non insérée",totalPrintHours:"Heures d'impression",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",missingSpoolAssignment:"Impression démarrée sur {{printer}}. Attribution de bobine manquante pour : {{slots}}",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",failedToSetSpeed:"Échec du réglage de la vitesse",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",noCamera:"Pas d'autorisation pour les caméras"},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"},bulk:{select:"Sélectionner",selectAll:"Tout sélectionner",selectByLocation:"Sélectionner par emplacement",selected:"{{count}} sélectionné(s)",actions:{stop:"Arrêter",pause:"Pause",resume:"Reprendre",clearPlate:"Vider le plateau",clearHMS:"Effacer les notifications"},confirm:{stopTitle:"Arrêter {{count}} impressions",stopMessage:"Cela annulera les impressions actives sur {{count}} imprimante(s). Cette action est irréversible.",stopButton:"Tout arrêter",pauseTitle:"Mettre en pause {{count}} impressions",pauseMessage:"Cela mettra en pause les impressions actives sur {{count}} imprimante(s).",pauseButton:"Tout mettre en pause",clearPlateTitle:"Vider {{count}} plateaux",clearPlateMessage:"Cela videra le plateau sur {{count}} imprimante(s) et pourrait lancer les travaux en file d'attente.",clearPlateButton:"Tout vider"},success:"{{action}} terminé sur {{count}} imprimante(s)",partial:"{{succeeded}} réussi(s), {{failed}} échoué(s)",noneApplicable:"Aucune imprimante sélectionnée n'est dans le bon état pour cette action",selectByState:"Sélectionner par état"},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"},drying:{start:"Démarrer le séchage",stop:"Arrêter le séchage",temperature:"Température",duration:"Durée",hours:"heures",timeRemaining:"{{time}} restant",active:"Séchage",notSupported:"Séchage non pris en charge",powerRequired:"Brancher l'adaptateur secteur AMS pour activer le séchage",startingDrying:"Démarrage du séchage...",stoppingDrying:"Arrêt du séchage...",rotateTray:"Tourner la bobine pendant le séchage"},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"},speed:{title:"Vitesse d'impression",silent:"Silencieux (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},airduct:{title:"Mode conduit d'air",cooling:"Refroidissement",heating:"Chauffage"},noSdCard:"Pas de SD",door:{open:"Ouverte",closed:"Fermée"},fans:{partCooling:"Ventilateur pièce",auxiliary:"Ventilateur auxiliaire",chamber:"Ventilateur chambre"},clickToViewHmsErrors:"Cliquez pour voir les erreurs HMS",estimatedCompletion:"Fin estimée",plateNumber:"Plaque {{number}}",slotOptions:"Options du slot",amsPopup:{friendlyName:"Nom AMS",friendlyNamePlaceholder:"ex. Nom convivial AMS",serialNumber:"Numéro de série",firmwareVersion:"Firmware",save:"Enregistrer",clear:"Effacer",noEditPermission:"Vous n'avez pas la permission de renommer les unités AMS"},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",incompatibleFile:"Ce fichier a été tranché pour {{slicedFor}}, mais cette imprimante est une {{printerModel}}",dropNotPrintable:"Seuls les fichiers .gcode et .gcode.3mf peuvent être imprimés",dropToPrint:"Déposer pour imprimer",cannotPrint:"Imprimante occupée"},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",originalPrintNotVisible:"Impression d'origine non visible - essayez d'effacer les filtres",noArchivesYet:"Pas encore d'archive",prints:"impressions",pagination:{showing:"Affichage",to:"à",of:"sur",show:"Afficher",page:"Page",all:"Tout"},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",hideDuplicates:"Masquer les doublons",viewOriginalPrint:"Cliquez pour afficher l'impression originale (#{{id}})",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",timelapseRemoved:"Timelapse supprimé",failedRemoveTimelapse:"Échec de la suppression du timelapse",timelapseUploaded:"Timelapse importé : {{filename}}",failedUploadTimelapse:"Échec de l'importation du 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",uploadTimelapse:"Importer un timelapse",removeTimelapse:"Supprimer le 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}}" ?',removeTimelapse:"Supprimer le timelapse",removeTimelapseConfirm:'Êtes-vous sûr de vouloir supprimer la vidéo timelapse 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",queueSelectedPlates:"Ajouter {{count}} plaques à la file",selectAllPlates:"Sélectionner les {{count}} plaques",deselectAll:"Tout désélectionner",printQueued:"Impression ajoutée à la file",itemsQueued:"{{count}} éléments ajoutés à la file",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.",sjf:{label:"SJF",tooltip:"Travail le plus court en premier — le planificateur priorise les impressions plus courtes"},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}}",quantity:"Quantité",quantityHint:"Crée {{count}} éléments de file d'attente",activeBatches:"Lots actifs",batchProgress:"{{completed}} sur {{total}} terminés",cancelBatch:"Annuler les restants",batchCancelled:"Éléments restants du lot annulés",cancelBatchConfirmTitle:"Annuler le lot",cancelBatchConfirmMessage:"Annuler tous les éléments en attente restants dans ce lot ?",batch:"Lot",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",gcodeInjection:"G-code"},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"},timeline:{listView:"Liste",timelineView:"Chronologie",unassigned:"Non attribué",noData:"Aucune impression planifiée pour ce jour",allDoneBy:"Toutes les impressions terminées vers {{time}}",staged:"En attente",filterAll:"Tout afficher",filterPrinting:"En cours",filterQueued:"En file",time:{anyMoment:"imminent",minutesLeft:"{{minutes}}m restantes",hoursLeft:"{{hours}}h restantes",hoursMinutesLeft:"{{hours}}h {{minutes}}m restantes"},day:{previous:"Jour précédent",next:"Jour suivant",today:"Aujourd'hui"}},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",printStartedRemaining:"{{completed}} impression(s) lancée(s), {{remaining}} en cours d'envoi..."}},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",energyWarmingUpTooltip:"Le suivi énergétique collecte encore des instantanés horaires. Les totaux par période deviendront précis dès qu’un instantané existera avant la plage sélectionnée. Les premières valeurs peuvent être sous-estimées.",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",noPrintDataInRange:"Aucune donnée dans la période sélectionnée",periodFilament:"Filament utilisé",periodCost:"Coût",avgPerPrint:"Moy. par impression",usageOverTime:"Utilisation dans le temps",filamentByWeight:"Poids",printDuration:"Durée d'impression",printerUtilization:"Utilisation imprimante",filamentSuccess:"Succès par matériau",printHabits:"Habitudes d'impression",printTimeOfDay:"Heure d'impression",colorDistribution:"Distribution des couleurs",noColorData:"Aucune donnée de couleur disponible",records:"Records",longestPrint:"Plus longue impression",heaviestPrint:"Plus lourde impression",mostExpensivePrint:"Plus chère",busiestDay:"Jour le plus actif",successStreak:"Série de succès",streakPrint:"impression consécutive",streakPrints:"{{count}} impressions consécutives",printerStats:"Stats imprimante",hours:"heures",avgPrints:"Moy. impressions",noArchiveData:"Aucune donnée d'impression disponible",filamentByTime:"Temps",avgWeight:"Moy. poids",avgTime:"Moy. temps",filamentByPrints:"Impressions",timeframe:{today:"Aujourd'hui","this-week":"Cette semaine","this-month":"Ce mois","last-7":"7 derniers jours","last-30":"30 derniers jours","last-90":"90 derniers jours","this-year":"Cette année","all-time":"Tout",custom:"Personnalisé",from:"Du",to:"Au"},allUsers:"Tous les utilisateurs",noUser:"Aucun utilisateur (Système)",filterByUser:"Filtrer par utilisateur"},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",restoreDefaults:"Restaurer les tâches par défaut",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",lubricateSteelRods:"Lubrifier les tiges en acier",cleanSteelRods:"Nettoyer les tiges en acier",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é",defaultsRestored:"{{count}} tâche(s) par défaut restaurée(s)",printHoursUpdated:"Heures mises à jour",printerAssigned:"Imprimante assignée",printerRemoved:"Imprimante retirée",deleteTypeConfirm:'Supprimer "{{name}}" ?',deleteSystemTypeTitle:"Supprimer la tâche de maintenance par défaut ?",deleteSystemTypeMessage:'Êtes-vous sûr de vouloir supprimer la tâche de maintenance par défaut "{{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",queue:"Workflow",filament:"Filament",network:"Réseau",apiKeys:"Clés API",virtualPrinter:"Imprimante virtuelle",failureDetection:"Détection d'échec",users:"Authentification",backup:"Sauvegarde",emailAuth:"Authentification Email",ldap:"LDAP",twoFa:"Authentification 2FA",oidc:"SSO / OIDC"},ldap:{title:"Authentification LDAP",enabledDesc:"L'authentification LDAP est activée",disabledDesc:"L'authentification LDAP est désactivée",disabledHint:"Configurez et enregistrez les paramètres LDAP ci-dessous, puis activez.",enabled:"Authentification LDAP activée",disabled:"Authentification LDAP désactivée",feature1:"Les utilisateurs peuvent se connecter avec leurs identifiants LDAP",feature2:"Le compte administrateur local reste disponible en secours",feature3:"Les groupes LDAP sont associés aux groupes BamBuddy à la connexion",serverConfig:"Configuration du serveur LDAP",serverUrl:"URL du serveur",serverUrlHint:"Utilisez ldap:// pour standard ou ldaps:// pour les connexions SSL",security:"Sécurité",securityHint:"StartTLS met à niveau une connexion simple vers TLS. LDAPS utilise TLS dès le début.",bindDn:"DN de liaison (compte de service)",bindPassword:"Mot de passe de liaison",searchBase:"DN de base de recherche",userFilter:"Filtre de recherche utilisateur",userFilterHint:"{username} est remplacé par le nom d'utilisateur. Utilisez (uid={username}) pour OpenLDAP.",autoProvision:"Provisionnement automatique",autoProvisionHint:"Créer automatiquement un compte BamBuddy lors de la première connexion LDAP",defaultGroup:"Groupe par défaut",defaultGroupNone:"— Aucun (pas de repli) —",defaultGroupHint:"Groupe de repli attribué lorsqu'un utilisateur LDAP s'authentifie mais n'est dans aucun groupe LDAP mappé. Laissez vide pour laisser les utilisateurs non mappés sans autorisations.",groupMapping:"Mappage de groupes (JSON)",groupMappingHint:"Associer les DN de groupes LDAP aux groupes BamBuddy. Groupes disponibles : ",testConnection:"Tester la connexion",settingsSaved:"Paramètres LDAP enregistrés",errors:{serverRequired:"L'URL du serveur LDAP est requise",searchBaseRequired:"Le DN de base de recherche est requis",enableAuthFirst:"Activez d'abord l'authentification",configureLdapFirst:"Enregistrez d'abord les paramètres LDAP"}},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",enableAuthFirst:"Veuillez d'abord activer l'authentification pour utiliser les fonctionnalités basées sur le courrier électronique."},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",userNotificationsEnabled:"Notifications utilisateur",userNotificationsEnabledDescription:"Active le menu de notifications utilisateur et les notifications par e-mail pour les événements d'impression. Nécessite l'authentification avancée.",userNotificationsDisabledHint:"Activez l'authentification avancée pour utiliser les notifications utilisateur.",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.",filamentChecks:"Vérifications du filament",disableFilamentWarnings:"Désactiver les avertissements de filament",disableFilamentWarningsDesc:"Ne pas afficher les avertissements de filament insuffisant lors de l'impression ou de la mise en file d'attente",preferLowestFilament:"Préférer le filament le plus bas",preferLowestFilamentDesc:"Lorsque plusieurs bobines correspondent, utiliser celle avec le moins de filament restant",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)",fairAlsoDryingThreshold:"Ce seuil est aussi utilisé pour déclencher le séchage automatique",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.",defaultPrintOptions:"Options d'impression par défaut",defaultPrintOptionsDescription:"Définir les valeurs par défaut des options d'impression. Modifiables dans la boîte de dialogue d'impression.",defaultBedLevelling:"Nivellement du lit",defaultBedLevellingDesc:"Niveler automatiquement le lit avant l'impression",defaultFlowCali:"Calibration du flux",defaultFlowCaliDesc:"Calibrer le flux d'extrusion",defaultVibrationCali:"Calibration des vibrations",defaultVibrationCaliDesc:"Réduire les artefacts de ringing",defaultLayerInspect:"Inspection première couche",defaultLayerInspectDesc:"Inspection IA de la première couche",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Enregistrer une vidéo timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Confirmation de plateau libre",requirePlateClear:"Exiger la confirmation de plateau libre",requirePlateClearDescription:"Lorsque activé, le planificateur attend la confirmation de plateau libre par imprimante avant de lancer les impressions en file d'attente sur les imprimantes ayant terminé. Désactivez pour les workflows de ferme où les plateaux sont vérifiés physiquement.",gcodeInjection:"Injection de G-code",gcodeInjectionDescription:"Configurez du G-code personnalisé à injecter au début et/ou à la fin des impressions pour les systèmes d'auto-impression comme Farmloop, SwapMod, AutoClear et Printflow 3D. Les snippets sont configurés par modèle d'imprimante et appliqués lorsque « Injecter le G-code » est activé sur un élément de file d'attente.",gcodeInjectionNoPrinters:"Aucune imprimante trouvée. Ajoutez des imprimantes pour configurer les snippets G-code.",gcodeStartLabel:"G-code de début",gcodeEndLabel:"G-code de fin",gcodeStartPlaceholder:"G-code ajouté avant le début de l'impression...",gcodeEndPlaceholder:"G-code ajouté après la fin de l'impression...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Séchage automatique",queueDryingDescription:"Sécher automatiquement le filament AMS lorsque l'imprimante est inactive entre les impressions. Utilise le seuil d'humidité ci-dessus.",queueDryingEnabled:"Activer le séchage automatique",queueDryingEnabledDescription:"Démarrer le séchage AMS automatiquement lorsque l'imprimante est inactive et l'humidité dépasse le seuil",queueDryingBlock:"Attendre la fin du séchage",queueDryingBlockDescription:"Bloquer la file d'attente jusqu'à la fin du séchage. Désactivé, les impressions sont prioritaires.",ambientDryingEnabled:"Séchage ambiant",ambientDryingEnabledDescription:"Sécher automatiquement le filament sur les imprimantes inactives lorsque l'humidité dépasse le seuil, même sans impressions en file.",dryingPresets:"Préréglages de séchage",dryingPresetsDescription:"Température et durée par type de filament. AMS 2 Pro utilise des températures plus basses, AMS-HT supporte des températures plus élevées.",dryingFilament:"Filament",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",selectedCount:"{{count}} sélectionnés",deleteSelected:"Supprimer la sélection",bulkDeleteConfirm:"Supprimer {{count}} entrées ?",bulkDeleted:"{{count}} entrées supprimées",bulkDeleteFailed:"Échec de la suppression"},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",selectedCount:"{{count}} sélectionnés",deleteSelected:"Supprimer la sélection",bulkDeleteConfirm:"Supprimer {{count}} couleurs ?",bulkDeleted:"{{count}} couleurs supprimées",bulkDeleteFailed:"Échec de la suppression des couleurs"},dateFormat:"Format de date",dateFormatUs:"US (MM/JJ/AAAA)",dateFormatEu:"EU (JJ/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-JJ)",timeFormat:"Format horaire",timeFormat12:"12 heures (3:30 PM)",timeFormat24:"24 heures (15:30)",defaultPrinter:"Imprimante par défaut",defaultPrinterDescription:"Présélectionner cette imprimante pour les téléversements, réimpressions et autres opérations.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Glissez les éléments dans la barre latérale pour réorganiser. Réinitialiser l'ordre par défaut ici.",setDefault:"Définir par défaut",sidebarOrderSetDefaultHint:"Définir par défaut applique l'ordre actuel du menu aux utilisateurs qui n'ont pas encore personnalisé le leur.",sidebarDefaultSet:"L'ordre du menu par défaut a été défini.",sidebarDefaultCleared:"Ordre du menu par défaut effacé.",sidebarDefaultFailed:"Échec de la définition de l'ordre du menu par défaut.",reset:"Réinitialiser",darkMode:"Mode sombre",lightMode:"Mode clair",active:"(actif)",background:"Arrière-plan",accent:"Accent",style:"Style",bgNeutral:"Neutre",bgWarm:"Chaud",bgCool:"Froid",bgOled:"OLED Noir",bgSlate:"Bleu ardoise",bgForest:"Vert forêt",accentGreen:"Vert",accentTeal:"Sarcelle",accentBlue:"Bleu",accentOrange:"Orange",accentPurple:"Violet",accentRed:"Rouge",styleClassic:"Classique",styleGlow:"Lumineux",styleVibrant:"Vibrant",themeToggleHint:"Basculer entre le mode sombre et clair avec l'icône soleil/lune dans la barre latérale.",autoArchivePrints:"Archiver automatiquement les impressions",autoArchiveDescription:"Sauvegarder automatiquement les fichiers 3MF à la fin des impressions",saveThumbnailsDescription:"Extraire et sauvegarder les images d'aperçu des fichiers 3MF",captureFinishPhotoDescription:"Prendre une photo avec la caméra de l'imprimante à la fin de l'impression",ffmpegNotInstalled:"ffmpeg non installé",ffmpegRequired:"La capture caméra nécessite ffmpeg. Installez-le via <brew>brew install ffmpeg</brew> (macOS) ou <apt>apt install ffmpeg</apt> (Linux).",camera:"Caméra",cameraViewMode:"Mode d'affichage caméra",cameraOverlayDescription:"La caméra s'ouvre dans un overlay redimensionnable sur l'écran principal",cameraWindowDescription:"La caméra s'ouvre dans une fenêtre de navigateur séparée",externalCamerasDescription:"Configurer des caméras externes pour remplacer la caméra intégrée. Supporte les flux MJPEG, RTSP, snapshots HTTP et caméras USB (V4L2). Lorsqu'activée, la caméra externe est utilisée pour la vue en direct et les photos de fin.",cameraPlaceholderUsb:"Chemin du périphérique (/dev/video0)",cameraPlaceholderUrl:"URL caméra (rtsp://... ou http://...)",cameraTypeMjpeg:"Flux MJPEG",cameraTypeRtsp:"Flux RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Caméra USB (V4L2)",cameraRotation:"Rotation",test:"Tester",connected:"Connecté",disconnected:"Déconnecté",currency:"Devise",defaultFilamentCost:"Coût filament par défaut (par kg)",electricityCost:"Coût électricité par kWh",energyDisplayMode:"Mode d'affichage énergie",energyModePrintDescription:"Le tableau de bord affiche la somme de l'énergie utilisée pendant les impressions",energyModeTotalDescription:"Le tableau de bord affiche l'énergie totale des prises connectées",fileManager:"Gestionnaire de fichiers",createArchiveEntry:"Créer une entrée d'archive lors de l'impression",createArchiveEntryDescription:"Lors de l'impression depuis le gestionnaire de fichiers, créer optionnellement une entrée d'archive",lowDiskSpaceWarning:"Avertissement espace disque faible",lowDiskSpaceDescription:"Afficher un avertissement lorsque l'espace disque libre descend sous ce seuil",printerFirmware:"Firmware imprimante",checkFirmwareDescription:"Vérifier les mises à jour firmware de Bambu Lab",bambuddySoftware:"Logiciel Bambuddy",autoCheckDescription:"Vérifier automatiquement les nouvelles versions au démarrage",checkNow:"Vérifier maintenant",updateAvailableVersion:"Mise à jour disponible : v{{version}}",releaseNotes:"Notes de version",updateViaDocker:"Mettre à jour via Docker Compose :",installUpdate:"Installer la mise à jour",latestVersionRunning:"Vous utilisez la dernière version",failedToCheckUpdates:"Échec de la vérification des mises à jour : {{error}}",backupRestore:"Sauvegarde & Restauration",backupRestoreDescription:"Exporter/importer les paramètres et configurer la sauvegarde GitHub",goToBackup:"Aller à la sauvegarde",externalUrl:"URL externe",externalUrlDescription:"L'URL externe où Bambuddy est accessible. Utilisée pour les images de notification et les intégrations externes.",bambuddyUrl:"URL Bambuddy",externalUrlHint:"Inclure le protocole et le port (ex : http://192.168.1.100:8000)",ftpRetry:"Réessai FTP",ftpRetryDescription:"Réessayer les opérations FTP lorsque le WiFi de l'imprimante est instable. S'applique aux téléchargements 3MF, uploads d'impression, téléchargements timelapse et mises à jour firmware.",autoRetryDescription:"Réessayer automatiquement les opérations FTP échouées",retryAttempts:"Tentatives de réessai",retryDelay:"Délai de réessai",connectionTimeout:"Délai de connexion",time_one:"{{count}} fois",time_other:"{{count}} fois",second_one:"{{count}} seconde",second_other:"{{count}} secondes",nSeconds:"{{count}} secondes",increaseForWeakWifi:"Augmenter pour les imprimantes avec un WiFi faible",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Se connecter à Home Assistant pour contrôler les prises connectées via l'API REST HA. Supporte les entités switch, light, input_boolean et script.",homeAssistantUrl:"URL Home Assistant",longLivedAccessToken:"Token d'accès longue durée",haTokenHint:"Créer un token dans HA : Profil → Tokens d'accès longue durée → Créer un token",connectionSuccessful:"Connexion réussie",connectionFailed:"Connexion échouée",haConnectionSuccess:"Connexion à Home Assistant réussie.",haConnectionFailed:"Échec de la connexion à Home Assistant.",mqttPublishing:"Publication MQTT",mqttDescription:"Publier les événements BamBuddy vers un broker MQTT externe pour l'intégration avec Node-RED, Home Assistant et d'autres systèmes d'automatisation.",mqttEnableDescription:"Publier les événements vers un broker MQTT externe",brokerHostname:"Nom d'hôte du broker",port:"Port",usernameOptional:"Nom d'utilisateur (optionnel)",passwordOptional:"Mot de passe (optionnel)",topicPrefix:"Préfixe de topic",topicPrefixHint:"Les topics seront : {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Métriques Prometheus",prometheusEndpointDescription:"Exposer les métriques imprimante sur <code>/api/v1/metrics</code> pour la surveillance Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (optionnel)",bearerTokenHint:"Si défini, les requêtes doivent inclure <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"État de connexion",metricsPrinterState:"État imprimante (idle/printing/etc)",metricsPrintProgress:"Progression impression 0-100%",metricsBedTemp:"Température du plateau",metricsNozzleTemp:"Température de la buse",metricsPrintsTotal:"Total impressions par résultat",metricsMore:"...et plus (couches, ventilateurs, file d'attente, utilisation filament)",smartPlugsDescription:"Connecter des prises connectées (Tasmota ou Home Assistant) pour automatiser le contrôle de l'alimentation et suivre la consommation d'énergie de vos imprimantes.",allOn:"Tout allumer",allOff:"Tout éteindre",addSmartPlug:"Ajouter une prise",energySummary:"Résumé énergétique",currentPower:"Puissance actuelle",plugsOnline:"{{reachable}}/{{total}} prises en ligne",today:"Aujourd'hui",yesterday:"Hier",total:"Total",enablePlugsForSummary:"Activer les prises pour voir le résumé énergétique",addNotificationProvider:"Ajouter",systemBadge:"(Système)",creating:"Création...",changing:"Modification...",deleteUserAndItems:"Supprimer l'utilisateur ET ses éléments",deleteUserKeepItems:"Supprimer l'utilisateur, garder les éléments (deviennent sans propriétaire)",ok:"OK",twoFa:{totpTitle:"Application Authenticator (TOTP)",totpDesc:"Utilisez une application comme Google Authenticator, Aegis ou Authy.",emailOtpTitle:"OTP par e-mail",emailOtpDesc:"Envoyez un code à usage unique à {{email}} lors de la connexion.",emailOtpNoEmail:"Ajoutez une adresse e-mail à votre compte pour activer cette méthode.",addEmailFirst:"Votre compte n'a pas d'adresse e-mail. Demandez à un administrateur d'en ajouter une.",setupTotp:"Configurer l'application Authenticator",setupAuthApp:"Configurer l'application Authenticator",setupInstructions:"Scannez le QR code avec votre application authenticator, puis confirmez avec un code.",manualEntry:"Impossible de scanner ? Entrez ce secret manuellement :",scannedContinue:"Code scanné — continuer",enterCodeToConfirm:"Entrez le code à 6 chiffres de votre application authenticator pour confirmer.",activate:"Activer",disableTotp:"Désactiver l'Authenticator",disableConfirmHint:"Entrez un code TOTP valide ou un code de secours pour désactiver l'authenticator.",totpDisabled:"Application Authenticator désactivée.",emailOtpEnabled:"OTP par e-mail activé.",emailOtpDisabled:"OTP par e-mail désactivé.",smtpRequired:"Veuillez d'abord configurer et tester les paramètres SMTP.",invalidCode:"Code invalide. Veuillez réessayer.",enableEmailOtp:"Activer OTP par e-mail",disableEmailOtp:"Désactiver OTP par e-mail",emailSetupEnterCode:"Un code de vérification a été envoyé à votre adresse e-mail. Entrez-le ci-dessous pour confirmer que vous possédez cette boîte de réception.",verifyAndEnable:"Vérifier et activer",emailDisablePasswordHint:"Entrez le mot de passe de votre compte pour confirmer la désactivation de l'OTP par e-mail.",passwordPlaceholder:"Entrez votre mot de passe",backupCodesTitle:"Sauvegardez vos codes de secours",backupCodesWarning:"Conservez ces codes en lieu sûr. Chaque code ne peut être utilisé qu'une seule fois et ne sera plus affiché.",backupCodesRemaining:"{{count}} codes de secours restants",savedCodes:"Codes sauvegardés",regenBackup:"Régénérer les codes de secours",regenBackupHint:"Entrez votre code TOTP actuel pour générer 10 nouveaux codes de secours. Tous les codes existants seront invalidés.",newBackupCodes:"Nouveaux codes de secours",linkedAccounts:"Comptes SSO liés",linkedAccountsDesc:"Ces fournisseurs d'identité externes sont liés à votre compte.",oidcUnlinked:"Compte dissocié."},oidc:{title:"Fournisseurs SSO / OIDC",desc:"Configurez des fournisseurs OpenID Connect pour l'authentification unique.",addProvider:"Ajouter un fournisseur",newProvider:"Nouveau fournisseur",empty:"Aucun fournisseur OIDC configuré.",created:"Fournisseur créé.",updated:"Fournisseur mis à jour.",deleted:"Fournisseur supprimé.",deleteTitle:"Supprimer le fournisseur",deleteMessage:'Supprimer "{{name}}" ? Tous les comptes liés seront déconnectés.',form:{name:"Nom d'affichage",issuerUrl:"URL de l'émetteur",clientId:"ID client",clientSecret:"Secret client",scopes:"Scopes",iconUrl:"URL de l'icône (optionnel)",enabled:"Activé",autoCreate:"Créer les utilisateurs automatiquement",autoCreateDesc:"Crée automatiquement un compte local lors de la première connexion.",autoLink:"Lier automatiquement les comptes existants",autoLinkDesc:"Lie les comptes locaux existants par e-mail lors de la première connexion.",secretHint:"laisser vide pour conserver",secretPlaceholder:"nouveau secret"}}},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",enterEmail:"Veuillez entrer votre adresse e-mail",oidcLoginFailed:"Échec de la connexion OIDC",oidcErrors:{providerError:"Le fournisseur d'identité a renvoyé une erreur",missingParameters:"Il manque des paramètres requis dans le callback OIDC",invalidState:"L'état OIDC est invalide ou a déjà été utilisé",stateExpired:"La session OIDC a expiré — veuillez réessayer",providerNotFound:"Fournisseur OIDC introuvable",discoveryFailed:"Impossible de récupérer le document de découverte OIDC",invalidDiscovery:"Le document de découverte OIDC est invalide",networkError:"Erreur réseau lors de l'échange de jeton OIDC",badResponse:"Réponse inattendue lors de l'échange de jeton OIDC",noIdToken:"Le fournisseur OIDC n'a pas renvoyé de jeton d'identité",validationFailed:"La validation du jeton OIDC a échoué",nonceMismatch:"Le nonce OIDC ne correspond pas — possible attaque par rejeu",missingSubClaim:"Le jeton OIDC est dépourvu de la revendication sub",noLinkedAccount:"Aucun compte local est lié à cette identité OIDC",accountInactive:"Votre compte est inactif",userResolutionFailed:"Impossible de résoudre votre compte",internalError:"Une erreur interne est survenue lors de la connexion OIDC",tokenExchangeFailed:"L'échange de jeton OIDC a échoué"},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",twoFA:{title:"Authentification à deux facteurs",subtitle:"Votre compte est protégé par la 2FA. Saisissez le code de vérification ci-dessous.",methodAuthenticator:"Application d'authentification",methodEmail:"Code par e-mail",methodBackup:"Code de récupération",instructionsTotp:"Ouvrez votre application d'authentification et saisissez le code à 6 chiffres pour Bambuddy.",instructionsEmail:"Un code à 6 chiffres a été envoyé à votre adresse e-mail. Il est valable 10 minutes.",instructionsEmailNotSent:"Cliquez ci-dessous pour recevoir un code de vérification par e-mail.",instructionsBackup:"Saisissez l'un de vos codes de récupération à 8 caractères. Chaque code ne peut être utilisé qu'une seule fois.",sendCodeButton:"Envoyer le code par e-mail",sendingCode:"Envoi en cours...",resendCode:"Renvoyer le code",codeLabel:"Code de vérification",backupCodeLabel:"Code de récupération",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"Vérifier",verifyingButton:"Vérification en cours...",backToLogin:"← Retour à la connexion",orContinueWith:"ou continuer avec",signInWith:"Se connecter avec {{provider}}",enterCode:"Veuillez entrer le code de vérification",sendCodeFailed:"Échec de l'envoi du code de vérification",invalidCode:"Code invalide. Veuillez réessayer."}},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:"Échec du téléversement",zipFilesFailed:"{{count}} fichiers échoués",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",linkExternal:"Lier externe",linkExternalFolder:"Lier un dossier externe",linkExternalFolderDescription:"Monter un répertoire hôte (NAS, USB, partage réseau) dans le gestionnaire de fichiers. Les fichiers ne sont pas copiés — ils sont lus directement depuis le chemin d'origine.",externalFolderNamePlaceholder:"ex. Impressions NAS",externalPath:"Chemin hôte",externalPathHelp:"Chemin absolu du répertoire sur l'hôte Docker. Doit être monté en bind dans le conteneur.",readOnly:"Lecture seule",readOnlyHelp:"empêche les téléversements et suppressions",showHiddenFiles:"Afficher les fichiers cachés (fichiers point)",externalFolder:"Dossier externe",scanFolder:"Scanner",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é",externalFolderLinked:"Dossier externe lié et scanné",folderScanned:"Scan terminé : {{added}} ajoutés, {{removed}} supprimés",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",totalCost:"Coût Total",total:"Total",includesBom:"BOM incluse",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é.",noFiles:"Aucun fichier dans ce dossier.",print:"Imprimer maintenant",addToQueue:"Ajouter à la file"},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",unlinkConfirmTitle:"Dissocier la bobine?",unlinkConfirmMessage:"Cette opération déconnectera la bobine de Spoolman. Les données de la bobine dans Spoolman resteront inchangées.",selectSpool:"Choisir bobine",noUnlinkedSpools:"Pas de bobine libre",linkSuccess:"Lien réussi",linkFailed:"Échec lien",unlinkSuccess:"Bobine dissociée avec succès",unlinkFailed:"Échec de la dissociation de la bobine",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é",spoolName:"Bobine",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...",showAllSpools:"Afficher toutes les 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",weightCheck:"Vérification poids",lastWeighed:"Dernière pesée",neverWeighed:"Jamais pesé",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",groupSimilar:"Grouper",groupedSpools:"{{count}} bobines identiques",groupedRows:"lignes",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)",lowStockThresholdError:"Le seuil doit être compris entre 0.1 et 99.9",assignMismatchTitle:"Incompatibilité de matériau",assignMismatchMessage:'Le matériau de la bobine sélectionnée "{{spoolMaterial}}" ne correspond pas au matériau du plateau "{{trayMaterial}}" pour {{location}}. Assigner quand même ?',assignMismatchConfirm:"Assigner quand même",assignPartialMismatchMessage:'Le matériau de la bobine "{{spoolMaterial}}" est similaire, mais ne correspond pas exactement à "{{trayMaterial}}" dans {{location}}. Voulez-vous continuer ?',assignProfileMismatchMessage:'Le profil de la bobine "{{spoolProfile}}" ne correspond pas au profil du plateau "{{trayProfile}}" dans {{location}}. Voulez-vous continuer ?'},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 :",slotRemainingShort:" - {{grams}}g rest.",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",insufficientFilamentTitle:"Filament insuffisant",insufficientFilamentMessage:"Certaines bobines assignées ont moins de filament restant que nécessaire pour cette impression :",insufficientFilamentLine:"{{printer}} - {{slot}} : nécessite {{required}}g, restant {{remaining}}g",printAnyway:"Imprimer quand même",forceColorMatch:"Forcer correspondance des couleurs",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Échelonner sur {{count}} imprimantes",gcodeInjection:"Injecter le G-code auto-impression"},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",githubBackup:"Sauvegarde GitHub",enabled:"Activé",cloudLoginRequired:"Connexion Bambu Cloud requise. Connectez-vous sous Profils → Profils Cloud pour activer la sauvegarde GitHub.",cloudLoginRequiredShort:"Connexion Cloud requise",githubDescription:"Synchronisez automatiquement vos profils vers un dépôt GitHub privé pour la sauvegarde et l'historique des versions.",repositoryUrl:"URL du dépôt",personalAccessToken:"Jeton d'accès personnel",tokenSaved:"(enregistré)",enterNewToken:"Entrez un nouveau jeton pour mettre à jour",tokenHint:"Jeton à granularité fine avec permission de lecture/écriture du contenu",branch:"Branche",manualOnly:"Manuel uniquement",hourly:"Toutes les heures",daily:"Quotidien",weekly:"Hebdomadaire",includeInBackup:"Inclure dans la sauvegarde",kProfiles:"K-Profils",kProfilesDescription:"Calibration de l'avance de pression des imprimantes connectées",noPrintersConnected:"Aucune imprimante connectée",printersConnected:"{{connected}}/{{total}} connectées",cloudProfiles:"Profils Cloud",cloudProfilesDescription:"Préréglages de filament, imprimante et processus depuis Bambu Cloud",appSettings:"Paramètres de l'application",appSettingsDescription:"Configuration Bambuddy (base de données complète)",spoolInventory:"Inventaire des bobines",spoolInventoryDescription:"Bobines de filament, historique d'utilisation et suivi des coûts",printArchives:"Archives d'impression",printArchivesDescription:"Métadonnées de l'historique d'impression (pas de fichiers gcode/3MF)",lastBackupAt:"Dernière sauvegarde :",noBackupsYet:"Aucune sauvegarde pour l'instant",next:"Prochaine :",startingBackup:"Démarrage de la sauvegarde...",test:"Tester",enableBackup:"Activer la sauvegarde",testConnection:"Tester la connexion",enterRepoUrl:"Entrez l'URL du dépôt",enterRepoAndToken:"Entrez l'URL du dépôt et le jeton d'accès",repoRequired:"L'URL du dépôt est requise",tokenRequired:"Le jeton d'accès est requis",githubBackupEnabled:"Sauvegarde GitHub activée",tokenUpdated:"Jeton mis à jour",settingsSaved:"Paramètres enregistrés",failedToSave:"Échec de l'enregistrement : {{message}}",backupCompleteFiles:"Sauvegarde terminée - {{count}} fichiers mis à jour",backupSkippedNoChanges:"Sauvegarde ignorée - aucun changement",backupFailed2:"Échec de la sauvegarde : {{message}}",clearedLogs:"{{count}} journaux supprimés",failedToClearLogs:"Échec de la suppression des journaux : {{message}}",history:"Historique",clear:"Effacer",date:"Date",status:"Statut",commit:"Commit",localBackup:"Sauvegarde locale",localBackupDescription:"Créez une sauvegarde complète de vos données Bambuddy incluant la base de données, les archives, les téléchargements et tous les fichiers.",downloadBackupLabel:"Télécharger la sauvegarde",completeBackupZip:"Sauvegarde complète : base de données + tous les fichiers (ZIP)",download:"Télécharger",preparingBackup:"Préparation de la sauvegarde...",creatingArchive:"Création de l'archive de sauvegarde... Cela peut prendre un moment pour les archives volumineuses.",downloadingFile:"Téléchargement du fichier de sauvegarde...",backupDownloaded:"Sauvegarde téléchargée avec succès",failedToCreateBackup:"Échec de la création de la sauvegarde : {{message}}",restore:"Restaurer",restoreReplacesAll:"La restauration remplace toutes les données.",restoreReplacesAllDetail:"Votre base de données et vos fichiers actuels seront complètement remplacés. Un redémarrage est nécessaire après la restauration.",restoreConfirmTitle:"Restaurer la sauvegarde",restoreConfirmMessage:`Êtes-vous sûr de vouloir restaurer depuis "{{filename}}" ? Cela remplacera complètement votre base de données et tous vos fichiers. L'application devra être redémarrée après la restauration.`,restoreConfirmButton:"Restaurer la sauvegarde",uploadingFile:"Téléchargement du fichier de sauvegarde...",backupRestoredRestart:"Sauvegarde restaurée. Veuillez redémarrer Bambuddy.",failedToRestore:"Échec de la restauration. Veuillez vérifier le format du fichier.",reloadNow:"Recharger maintenant",creatingBackup:"Création de la sauvegarde",restoringBackup:"Restauration de la sauvegarde",preparing:"Préparation...",processing:"Traitement...",doNotClosePage:"Veuillez ne pas fermer cette page ni naviguer ailleurs. Cette opération peut prendre plusieurs minutes pour les sauvegardes volumineuses.",restoring:"Restauration...",restoreComplete:"Restauration terminée",restoreFailed2:"Échec de la restauration",importSettings:"Importer les paramètres depuis un fichier de sauvegarde",pleaseWaitRestoring:"Veuillez patienter pendant la restauration de vos données",selectBackupFile:"Cliquez pour sélectionner un fichier de sauvegarde (.json ou .zip)",duplicateHandling:"Comment fonctionne la gestion des doublons :",matchPrinters:"Imprimantes",matchPrintersBy:"correspondance par numéro de série",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"correspondance par adresse IP",matchNotificationProviders:"Fournisseurs de notifications",matchNotificationProvidersBy:"correspondance par nom",matchFilaments:"Filaments",matchFilamentsBy:"correspondance par nom + type + marque",matchArchives:"Archives",matchArchivesBy:"correspondance par hash de contenu (toujours ignoré)",matchPendingUploads:"Téléchargements en attente",matchPendingUploadsBy:"correspondance par nom de fichier",matchSettingsTemplates:"Paramètres et modèles",matchSettingsTemplatesBy:"toujours écrasés",replaceExisting:"Remplacer les données existantes",keepExisting:"Conserver les données existantes",overwriteDescription:"Écraser les éléments qui existent déjà avec les données de sauvegarde",keepDescription:"Restaurer uniquement les éléments qui n'existent pas encore",overwriteCaution:"Attention :",overwriteWarning:"L'écrasement remplacera vos configurations actuelles par les données de la sauvegarde. Les codes d'accès des imprimantes ne sont jamais écrasés pour des raisons de sécurité.",cancel:"Annuler",processingBackup:"Traitement du fichier de sauvegarde...",itemsRestored:"Éléments restaurés",itemsSkipped:"Éléments ignorés",restored:"Restaurés",skippedAlreadyExist:"Ignorés (existent déjà)",filesCategory:"Fichiers (3MF, miniatures, etc.)",andMore:"...et {{count}} de plus",newApiKeysGenerated:"Nouvelles clés API générées",keysShownOnce:"Ces clés ne sont affichées qu'une seule fois. Copiez-les maintenant !",copy:"Copier",noDataFound:"Aucune donnée à restaurer n'a été trouvée dans le fichier de sauvegarde.",close:"Fermer",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"Paramètres",notification_providers:"Fournisseurs de notifications",notification_templates:"Modèles de notifications",smart_plugs:"Smart Plugs",printers:"Imprimantes",filaments:"Filaments",maintenance_types:"Types de maintenance",archives:"Archives",projects:"Projets",pending_uploads:"Téléchargements en attente",external_links:"Liens externes",api_keys:"Clés API"}},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."},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"},autoDispatch:{title:"Lancement automatique",description:"Lancer automatiquement les impressions ajoutées à la file. Désactivé, les impressions attendent un lancement manuel."},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",bindIpRequired:"Veuillez d'abord définir une adresse IP",accessCodeEmpty:"Le code ne peut pas être vide",accessCodeLength:"Le code doit faire 8 caractères",created:"Imprimante virtuelle créée",failedToCreate:"Échec de la création de l'imprimante virtuelle",deleted:"Imprimante virtuelle supprimée",failedToDelete:"Échec de la suppression de l'imprimante virtuelle"},list:{title:"Imprimantes virtuelles",add:"Ajouter",addFirst:"Ajouter une imprimante virtuelle",empty:"Aucune imprimante virtuelle configurée. Ajoutez-en une pour commencer."},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."},addDialog:{title:"Ajouter une imprimante virtuelle",name:"Nom",hint:"Vous pourrez configurer le code d'accès, l'imprimante cible et d'autres paramètres après la création.",create:"Créer"},deleteConfirm:{title:"Supprimer l'imprimante virtuelle",message:'Êtes-vous sûr de vouloir supprimer "{{name}}" ? Cela arrêtera tous les services de cette imprimante.'}},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)",lubricateSteelRods:"Appliquer du lubrifiant sur les tiges en acier pour un mouvement fluide",cleanSteelRods:"Nettoyer les tiges en acier (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"}},linkedTo:"Lié à :",monitorOnly:"Surveillance uniquement",alerts:"Alertes",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Puissance",kwhToday:"kWh Aujourd'hui",settings:"Paramètres",automationSettings:"Paramètres d'automatisation",showInSwitchbar:"Afficher dans la barre de commutateurs",quickAccessSidebar:"Accès rapide depuis la barre latérale",enabled:"Activé",enableAutomation:"Activer l'automatisation pour cette prise",autoOn:"Auto On",autoOnDescription:"Allumer au démarrage de l'impression",autoOff:"Auto Off",autoOffDescription:"Éteindre à la fin de l'impression (unique)",autoOffPersistent:"Garder activé",autoOffPersistentDescription:"Rester activé entre les impressions au lieu d'une seule fois",turnOffDelayMode:"Mode de délai d'extinction",time:"Temps",temp:"Temp",delayMinutes:"Délai (minutes)",tempThreshold:"Seuil de température (°C)",tempThresholdDescription:"S'éteint lorsque la buse refroidit en dessous de cette température",edit:"Modifier",deleteConfirm:'Êtes-vous sûr de vouloir supprimer "{{name}}" ? Cette action est irréversible.',turnOnConfirm:'Êtes-vous sûr de vouloir allumer "{{name}}" ?',turnOffConfirm:`Êtes-vous sûr de vouloir éteindre "{{name}}" ? Cela coupera l'alimentation de l'appareil connecté.`,failedToTurn:'Impossible de {{action}} "{{name}}"',unknown:"Inconnu",addTitle:"Ajouter une prise connectée",editTitle:"Modifier la prise connectée",stopScanning:"Arrêter le scan",discoverTasmota:"Découvrir les appareils Tasmota",foundDevices:"{{count}} appareil(s) trouvé(s) - cliquez pour sélectionner :",noDevicesFound:"Aucun appareil Tasmota trouvé sur votre réseau",haNotConfigured:"Home Assistant n'est pas configuré. Configurez-le dans",haSettingsPath:"Paramètres → Réseau → Home Assistant",selectEntity:"Sélectionner l'entité *",ipAddress:"Adresse IP *",nameLabel:"Nom *",username:"Nom d'utilisateur",password:"Mot de passe",authHint:"Laissez vide si votre appareil Tasmota ne nécessite pas d'authentification",linkToPrinter:"Lier à l'imprimante",noPrinter:"Pas d'imprimante (contrôle manuel uniquement)",linkingDescription:"La liaison permet l'allumage/extinction automatique au début/fin de l'impression",powerAlerts:"Alertes de puissance",alertAbove:"Alerte si au-dessus (W)",alertBelow:"Alerte si en dessous (W)",alertDescription:"Recevoir une notification lorsque la consommation dépasse ces seuils. Laisser vide pour désactiver cette direction.",dailySchedule:"Planification quotidienne",turnOnAt:"Allumer à",turnOffAt:"Éteindre à",scheduleDescription:"Allumer/éteindre automatiquement la prise à ces heures chaque jour. Laisser vide pour ignorer cette action.",showOnPrinterCard:"Afficher sur la carte imprimante",displayOnPrinterCard:"Afficher le bouton sur la carte imprimante",connectedResult:"Connecté !",deviceLabel:"Appareil : {{name}} - ",stateLabel:"État : {{state}}",test:"Tester",delete:"Supprimer",save:"Enregistrer",add:"Ajouter",cancel:"Annuler",failedToStartScan:"Impossible de démarrer le scan",nameRequired:"Le nom est requis",entityRequired:"L'entité est requise pour les prises Home Assistant",mqttTopicRequired:"Au moins un topic MQTT doit être configuré pour la puissance, l'énergie ou la surveillance d'état",loadingEntities:"Chargement des entités...",loading:"Chargement...",failedToLoadEntities:"Échec du chargement des entités : {{error}}",noEntitiesMatching:'Aucune entité trouvée correspondant à "{{search}}"',noEntitiesAvailable:"Aucune entité disponible",searchingEntities:"Recherche de toutes les entités ({{count}} trouvées)",showingEntities:"Affichage switch, light, input_boolean ({{count}} disponibles)",energyMonitoringOptional:"Surveillance énergétique (Optionnel)",energyMonitoringHint:"Recherchez et sélectionnez les capteurs fournissant des données de puissance/énergie.",powerSensorW:"Capteur de puissance (W)",energyTodayKwh:"Énergie aujourd'hui (kWh)",totalEnergyKwh:"Énergie totale (kWh)",noMatchingSensors:"Aucun capteur correspondant",none:"Aucun",mqttNotConfigured:"Broker MQTT non configuré. Définissez l'adresse du broker dans",mqttSettingsPath:"Paramètres → Réseau → Publication MQTT",mqttNotConfiguredSuffix:"(vous n'avez pas besoin d'activer la publication, remplissez simplement les détails du broker).",mqttMonitorOnlyDescription:"Les prises MQTT reçoivent les données de puissance/énergie via un abonnement MQTT. Le contrôle on/off n'est pas disponible - utilisez votre broker MQTT ou système domotique.",powerMonitoring:"Surveillance de puissance",energyMonitoring:"Surveillance énergétique",stateMonitoring:"Surveillance d'état",optional:"optionnel",topic:"Topic",jsonPath:"Chemin JSON",multiplier:"Multiplicateur",onValue:"Valeur ON",mqttPowerHint:`Le chemin JSON extrait la valeur du payload JSON (ex: "power_l1"). Laisser vide si le topic publie des valeurs numériques brutes.
- Utiliser le multiplicateur 0.001 pour mW→W, 1000 pour kW→W.`,mqttEnergyHint:`Le chemin JSON extrait la valeur du payload JSON. Laisser vide pour les valeurs brutes.
- Utiliser le multiplicateur 0.001 pour Wh→kWh, 1000 pour MWh→kWh.`,mqttStateHint:`Le chemin JSON extrait la valeur du payload JSON. Laisser vide pour les valeurs brutes.
- Valeur ON : la chaîne exacte signifiant "ON". Laisser vide pour la détection auto (ON, true, 1).`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL de puissance",restPowerPath:"Power JSON Path",restPowerMultiplier:"Multiplicateur de puissance",restEnergyUrl:"URL d'énergie",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Multiplicateur d'énergie",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL séparée pour les données de puissance (utilise l'URL de statut si vide)",restEnergyUrlHint:"URL séparée pour les données d'énergie (utilise l'URL de statut si vide)",restEnergyHint:"Chaque valeur peut utiliser sa propre URL ou se rabattre sur l'URL de statut. Utilisez les multiplicateurs pour la conversion d'unités (ex : 0.001 pour convertir Wh en kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Aucun commutateur dans la barre",enableSwitchbarHint:'Activez "Afficher dans la barre de commutateurs" dans Paramètres > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notifications par e-mail SMTP",telegram:"Notifications via un bot Telegram",discord:"Envoyer vers un canal Discord via webhook",ntfy:"Notifications push gratuites, auto-hébergeables",pushover:"Notifications push simples et fiables",callmebot:"Notifications WhatsApp gratuites via CallMeBot",webhook:"POST HTTP générique vers n'importe quelle URL",homeassistant:"Notifications persistantes dans le tableau de bord Home Assistant"},lastSuccess:"Dernier : {{date}}",error:"Erreur",printer:"Imprimante :",allPrinters:"Toutes les imprimantes",sendTestNotification:"Envoyer une notification de test",eventSettings:"Paramètres des événements",enabled:"Activé",sendFromProvider:"Envoyer des notifications depuis ce fournisseur",printEvents:"Événements d'impression",printerStatus:"État de l'imprimante",amsAlarms:"Alarmes AMS",amsHtAlarms:"Alarmes AMS-HT",printQueue:"File d'attente d'impression",start:"Début",plateCheck:"Vérification du plateau",complete:"Terminé",failed:"Échoué",stopped:"Arrêté",progress:"Progression",offline:"Hors ligne",lowFilament:"Filament bas",maintenance:"Maintenance",amsHumidity:"Humidité AMS",amsTemp:"Temp. AMS",amsHtHumidity:"Humidité AMS-HT",amsHtTemp:"Temp. AMS-HT",bedCooled:"Plateau refroidi",firstLayer:"Première couche",quiet:"Silencieux",digest:"Résumé {{time}}",printStarted:"Impression démarrée",plateNotEmpty:"Plateau non vide",plateNotEmptyDescription:"Objets détectés avant l'impression",printCompleted:"Impression terminée",bedCooledLabel:"Plateau refroidi",bedCooledDescription:"Plateau refroidi sous le seuil après l'impression",firstLayerCompleteLabel:"Première couche terminée",firstLayerCompleteDescription:"Notification avec photo après la première couche",missingSpoolAssignmentLabel:"Affectation de bobine manquante",missingSpoolAssignmentDescription:"Notifier quand une impression démarre et que des bacs requis n'ont pas de bobine assignée",printFailed:"Impression échouée",printStopped:"Impression arrêtée",progressMilestones:"Jalons de progression",progressMilestonesDescription:"Notifier à 25 %, 50 %, 75 %",printerOffline:"Imprimante hors ligne",printerError:"Erreur de l'imprimante",lowFilamentLabel:"Filament bas",maintenanceDue:"Maintenance requise",maintenanceDueDescription:"Notifier lorsqu'une maintenance est nécessaire",amsHumidityHigh:"Humidité AMS élevée",amsHumidityHighDescription:"L'humidité de l'AMS standard dépasse le seuil",amsTemperatureHigh:"Température AMS élevée",amsTemperatureHighDescription:"La température de l'AMS standard dépasse le seuil",amsHtHumidityHigh:"Humidité AMS-HT élevée",amsHtHumidityHighDescription:"L'humidité de l'AMS-HT dépasse le seuil",amsHtTemperatureHigh:"Température AMS-HT élevée",amsHtTemperatureHighDescription:"La température de l'AMS-HT dépasse le seuil",jobAdded:"Tâche ajoutée",jobAddedDescription:"Tâche ajoutée à la file d'attente",jobAssigned:"Tâche assignée",jobAssignedDescription:"Tâche basée sur le modèle assignée à l'imprimante",jobStarted:"Tâche démarrée",jobStartedDescription:"La tâche de la file a commencé l'impression",jobWaiting:"Tâche en attente",jobWaitingDescription:"Tâche en attente de filament ou imprimante",jobSkipped:"Tâche ignorée",jobSkippedDescription:"Tâche ignorée (échec précédent)",jobFailed:"Tâche échouée",jobFailedDescription:"La tâche n'a pas pu démarrer",queueComplete:"File d'attente terminée",queueCompleteDescription:"Toutes les tâches de la file sont terminées",quietHours:"Heures silencieuses",noNotificationsDuring:"Aucune notification pendant ces heures",editProviderToChangeQuietHours:"Modifier le fournisseur pour changer les heures silencieuses",dailyDigest:"Résumé quotidien",batchNotifications:"Regrouper les notifications en un seul résumé quotidien",sendAt:"Envoyer à {{time}}",editProviderToChangeDigestTime:"Modifier le fournisseur pour changer l'heure du résumé",edit:"Modifier",deleteProvider:"Supprimer le fournisseur de notifications",deleteConfirm:"Êtes-vous sûr de vouloir supprimer « {{name}} » ? Cette action est irréversible.",delete:"Supprimer",addTitle:"Ajouter un fournisseur de notifications",editTitle:"Modifier le fournisseur de notifications",nameLabel:"Nom *",namePlaceholder:"Mes notifications",providerTypeLabel:"Type de fournisseur *",configuration:"Configuration",testConfiguration:"Tester la configuration",printerFilter:"Filtre d'imprimante",onlyFromPrinter:"Envoyer uniquement les notifications pour les événements de cette imprimante",quietHoursDnd:"Heures silencieuses (Ne pas déranger)",quietStart:"Début",quietEnd:"Fin",dailyDigestLabel:"Résumé quotidien",sendDigestAt:"Envoyer le résumé à",digestCollected:"Les événements seront collectés et envoyés en un seul résumé à cette heure",notificationEvents:"Événements de notification",progressPercent:"(25 %, 50 %, 75 %)",bedCooledAfterPrint:"(après la fin de l'impression)",cancel:"Annuler",save:"Enregistrer",add:"Ajouter",nameRequired:"Le nom est requis",fieldRequired:"{{field}} est requis",phoneNumber:"Numéro de téléphone",apiKey:"Clé API",serverUrl:"URL du serveur",topic:"Sujet",authToken:"Jeton d'authentification",userKey:"Clé utilisateur",appToken:"Jeton d'application",priority:"Priorité",botToken:"Jeton du bot",chatId:"ID du chat",smtpServer:"Serveur SMTP",smtpPort:"Port SMTP",security:"Sécurité",authentication:"Authentification",username:"Nom d'utilisateur",password:"Mot de passe",fromEmail:"E-mail expéditeur",toEmail:"E-mail destinataire",webhookUrl:"URL du webhook",payloadFormat:"Format du payload",authorization:"Autorisation",titleFieldName:"Nom du champ titre",messageFieldName:"Nom du champ message",editTemplate:"Modifier le modèle : {{name}}",titleLabel:"Titre",bodyLabel:"Corps",titlePlaceholder:"Titre de la notification...",bodyPlaceholder:"Corps de la notification...",availableVariables:"Variables disponibles",clickToInsert:"Cliquer pour insérer à la position du curseur dans le corps",livePreview:"Aperçu en direct",hide:"Masquer",show:"Afficher",loadingPreview:"Chargement de l'aperçu...",enterTemplateContent:"Saisir le contenu du modèle pour voir l'aperçu",titlePreview:"Titre :",bodyPreview:"Corps :",resetToDefault:"Réinitialiser par défaut",titleRequired:"Le titre est requis",bodyRequired:"Le corps est requis",notificationLog:"Journal des notifications",showFailedOnly:"Échecs uniquement",last24Hours:"Dernières 24 heures",last7Days:"7 derniers jours",last30Days:"30 derniers jours",last90Days:"90 derniers jours",justNow:"À l'instant",noFailedNotifications:"Aucune notification échouée",noNotificationsLogged:"Aucune notification enregistrée",unknownProvider:"Fournisseur inconnu",logTitle:"Titre",logMessage:"Message",logError:"Erreur",logProvider:"Fournisseur : {{type}}",logTime:"Heure : {{time}}",refresh:"Actualiser",clearOld:"Purger les anciens",statsSummary:"{{days}} derniers jours :",statsNotifications:"notifications",statsSent:"{{count}} envoyées",statsFailed:"{{count}} échouées",eventTypes:{print_start:"Impression démarrée",print_complete:"Impression terminée",print_failed:"Impression échouée",print_stopped:"Impression arrêtée",print_progress:"Progression",printer_offline:"Imprimante hors ligne",printer_error:"Erreur de l'imprimante",filament_low:"Filament bas",maintenance_due:"Maintenance requise",test:"Test"},userEmail:{title:"Notifications",emailNotifications:"Notifications par e-mail",emailNotificationsDesc:"Recevez des notifications par e-mail pour vos propres travaux d'impression. Les e-mails sont envoyés via les paramètres SMTP configurés dans l'authentification avancée.",sendingTo:"Les notifications seront envoyées à",noEmailWarning:"Votre compte n'a pas d'adresse e-mail. Contactez un administrateur pour en ajouter une.",printJobNotifications:"Notifications de travaux d'impression",printJobNotificationsDesc:"Choisissez quels événements déclenchent des notifications par e-mail pour les travaux d'impression que vous soumettez.",printJobStarts:"Démarrage du travail d'impression",printJobStartsDesc:"Être notifié quand votre travail d'impression commence.",printJobFinishes:"Fin du travail d'impression",printJobFinishesDesc:"Être notifié quand votre travail d'impression se termine avec succès.",printErrors:"Erreurs d'impression",printErrorsDesc:"Être notifié quand votre travail d'impression échoue ou rencontre une erreur.",printJobStops:"Travail d'impression arrêté",printJobStopsDesc:"Être notifié quand votre travail d'impression est annulé ou arrêté.",saveSuccess:"Préférences de notification sauvegardées.",saveError:"Impossible de sauvegarder les préférences de notification."}},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",writeTag:"Écrire",settings:"Paramètres"},status:{nfcReady:"NFC prêt",nfcOff:"NFC désactivé",offline:"Hors ligne",online:"En ligne",noPrinters:"Aucune imprimante",deviceOffline:"Appareil hors ligne",waitingConnection:"En attente de connexion...",systemReady:"Système prêt",status:"Statut"},dashboard:{readyToScan:"Prêt à scanner",idleMessage:"Placez une bobine sur la balance pour l'identifier",nfcHint:"Le tag NFC sera lu automatiquement",device:"Appareil",syncWeight:"Sync. poids",weightSynced:"Synchronisé !",unknownTag:"Tag inconnu",newTag:"Nouveau tag détecté",onScale:"sur la balance",linkSpool:"Lier à une bobine",linkTagTitle:"Lier le tag à une bobine",linkTag:"Lier le tag",selectSpool:"Sélectionnez une bobine à lier à ce tag :",noUntagged:"Aucune bobine sans tag trouvée",tagDetected:"Tag détecté",noTag:"Pas de tag",tagId:"Tag",grossWeight:"Poids brut",spoolSize:"Taille bobine",close:"Fermer",currentSpool:"Bobine actuelle"},modal:{spoolDetected:"Bobine détectée",assignToAms:"Assigner à l'AMS",syncWeight:"Synchroniser le poids",weightSynced:"Synchronisé !",syncing:"Synchronisation...",newTagDetected:"Nouveau tag détecté",addToInventory:"Ajouter à l'inventaire",assignToAmsTitle:"Assigner à l'AMS",selectSlot:"Sélectionner un emplacement",assign:"Assigner",assigning:"Attribution...",assignSuccess:"Assigné !",assignError:"Échec de l'attribution de la bobine. Veuillez réessayer.",noPrinterSelected:"Sélectionner une imprimante...",noAmsDetected:"Aucun AMS détecté sur cette imprimante",slot:"Emplacement"},weight:{noReading:"Pas de lecture",stable:"Stable",measuring:"Mesure...",tare:"Tarer",calibrate:"Calibrer"},spool:{remaining:"Restant",material:"Matériau",brand:"Marque",color:"Couleur",coreWeight:"Noyau",labelWeight:"Étiquette",scaleWeight:"Balance",netWeight:"Net",lastUsed:"Dernière utilisation"},ams:{noData:"Aucun AMS détecté",connectAms:"Connectez un AMS pour voir les slots",noPrinter:"Aucune imprimante sélectionnée",selectPrinter:"Sélectionnez une imprimante dans la barre supérieure",printerDisconnected:"Imprimante déconnectée",humidity:"Humidité",level:"Niveau",active:"Actif",slot:"Slot",empty:"Vide"},inventory:{search:"Rechercher des bobines...",empty:"Aucune bobine dans l'inventaire",noResults:"Aucune bobine correspondante",spools:"bobines",addSpool:"Ajouter une bobine"},settings:{tabDevice:"Appareil",tabDisplay:"Affichage",tabScale:"Balance",tabUpdates:"Mises à jour",nfcReader:"Lecteur NFC",type:"Type",connection:"Connexion",notConnected:"N/A",deviceInfo:"Info appareil",hostname:"Hôte",uptime:"Temps de fonctionnement",brightness:"Luminosité",saved:"Enregistré",noBacklight:"Aucun rétroéclairage DSI détecté. Le contrôle de luminosité nécessite un écran DSI.",screenBlank:"Délai d'extinction",screenBlankDesc:"L'écran s'éteint après inactivité. Touchez pour réveiller.",displayNote:"La luminosité est appliquée comme filtre logiciel.",scaleCalibration:"Calibration de la balance",currentWeight:"Poids actuel",tareOffset:"Tare",calFactor:"Facteur",knownWeight:"Poids connu",calStep1:"Retirez tout de la balance et appuyez sur Mettre à zéro.",calStep2:"Placez le poids connu sur la balance.",setZero:"Mettre à zéro",calibrateNow:"Calibrer",calibrated:"Calibré",tareSet:"Commande de tare envoyée. En attente de l'appareil...",tareFailed:"Échec de l'envoi de la commande de tare",zeroSet:"Point zéro défini. Placez le poids connu sur la balance.",calibrationDone:"Calibration terminée !",calibrationFailed:"Échec de la calibration",lastCalibrated:"Dernière calibration",stable:"Stable",settling:"Stabilisation...",firmware:"Firmware",scale:"Balance",noDevice:"Aucun appareil SpoolBuddy trouvé",daemonVersion:"Version du daemon",currentVersion:"Actuelle",versionPending:"En attente du daemon...",checking:"Vérification...",checkUpdates:"Vérifier les mises à jour",updateAvailable:"Mise à jour disponible",updateInstructions:"Mise à jour via SSH : exécutez le script d'installation SpoolBuddy.",upToDate:"À jour",includeBeta:"Inclure les versions bêta"},writeTag:{tabExisting:"Bobine existante",tabNew:"Nouvelle bobine",tabReplace:"Remplacer le tag",searchPlaceholder:"Rechercher par matériau, couleur, marque...",noUntaggedSpools:"Aucune bobine sans tag",noTaggedSpools:"Aucune bobine avec tag",selectSpool:"Sélectionnez une bobine, puis placez un NTAG sur le lecteur",placeTag:"Placez un NTAG sur le lecteur",tagReady:"Tag détecté — prêt à écrire",writeTag:"Écrire le tag",replaceTag:"Remplacer le tag",writing:"Écriture du tag...",waiting:"En attente de SpoolBuddy...",writeSuccess:"Tag écrit avec succès !",writeFailed:"Échec de l'écriture",queueFailed:"Impossible de mettre en file la commande d'écriture",tryAgain:"Réessayer",cancel:"Annuler",replaceWarning:"L'ancien tag sera dissocié. Le nouveau tag le remplacera.",deviceOffline:"SpoolBuddy est hors ligne",material:"Matériau",colorName:"Nom de la couleur",color:"Couleur",brand:"Marque",weight:"Poids (g)",createSpool:"Créer la bobine",creating:"Création...",spoolCreated:"Bobine créée ! Prêt à écrire.",createFailed:"Impossible de créer la bobine"},quickMenu:{printerPower:"Alimentation imprimante",systemControls:"Système",restartDaemon:"Redémarrer le daemon",restartBrowser:"Redémarrer le navigateur",reboot:"Redémarrer",shutdown:"Éteindre",swipeToClose:"Glisser vers le bas pour fermer",confirmTitle:"Confirmer",confirmShutdown:"Êtes-vous sûr de vouloir éteindre le SpoolBuddy ? Vous aurez besoin d'un accès physique pour le rallumer.",confirmReboot:"Êtes-vous sûr de vouloir redémarrer le SpoolBuddy ?",confirmRestartDaemon:"Redémarrer le daemon SpoolBuddy ? Le NFC et la balance seront temporairement indisponibles.",confirmRestartBrowser:"Redémarrer le navigateur kiosque ? L'écran sera brièvement noir.",confirm:"Confirmer",confirmPlugOn:"Allumer {{name}} ?",confirmPlugOff:"Éteindre {{name}} ?",turnOn:"Allumer",turnOff:"Éteindre"}},bugReport:{title:"Signaler un bug",description:"Description",descriptionPlaceholder:"Qu'est-ce qui n'a pas fonctionné ? Veuillez décrire le problème...",email:"E-mail (optionnel)",emailPlaceholder:"votre@email.fr",emailPrivacy:"Si fourni, votre e-mail sera inclus dans une section repliée de l'issue GitHub pour que le mainteneur puisse vous contacter.",screenshot:"Capture d'écran",uploadOrPaste:"Télécharger, coller ou glisser une image",dataCollectedSummary:"Quelles données sont incluses dans le rapport ?",dataIncluded:"Inclus :",dataIncludedList:"Version de l'app, OS, architecture, version Python, statistiques de base de données (compteurs uniquement), modèles d'imprimantes, nombre de buses, versions firmware, état de connexion, état des intégrations (Spoolman, MQTT, HA), paramètres non sensibles, nombre d'interfaces réseau, détails Docker, versions des dépendances.",dataNeverIncluded:"Jamais inclus :",dataNeverIncludedList:"Noms d'imprimantes, numéros de série, codes d'accès, mots de passe, adresses IP, adresses e-mail, clés API, tokens, URLs de webhook, noms d'hôtes ou noms d'utilisateurs.",submit:"Envoyer",startLogging:"Lancer la journalisation",stepEnableLogging:"Journalisation activée",stepReproduce:"Reproduisez le problème",stepStopLogging:"Arrêter & envoyer",stopAndSubmit:"Arrêter & Envoyer",maxDuration:"Arrêt auto après {{minutes}} min",stoppingLogs:"Collecte des journaux & envoi...",submitting:"Envoi du rapport de bug...",submitSuccess:"Rapport de bug envoyé avec succès !",submitFailed:"Échec de l'envoi du rapport de bug",thankYou:"Merci !",submitted:"Votre rapport de bug a été soumis.",viewIssue:"Voir l'issue",unexpectedError:"Une erreur inattendue est survenue"},failureDetection:{title:"Détection d'échec par IA",description:"Surveille les impressions via une API ML Obico auto-hébergée et agit automatiquement sur les échecs détectés.",mlUrl:"URL de l'API ML Obico",mlUrlHint:"URL de base de votre conteneur Obico ml_api auto-hébergé (ex. http://192.168.1.10:3333).",test:"Tester",testSuccess:"API ML accessible et fonctionnelle.",testFailed:"Impossible d'atteindre l'API ML.",sensitivity:"Sensibilité",sensitivityLow:"Basse (moins de faux positifs)",sensitivityMedium:"Moyenne (équilibrée)",sensitivityHigh:"Haute (détection précoce, plus de faux positifs)",sensitivityHint:"Ajuste les seuils de confiance qui déclenchent les avertissements et les échecs.",action:"Action sur échec détecté",actionNotify:"Notifier uniquement",actionPause:"Mettre en pause",actionPauseOff:"Pause et couper l'alimentation",pollInterval:"Intervalle de vérification (secondes)",pollIntervalHint:"Fréquence de vérification de chaque imprimante pendant l'impression. Minimum 5s, maximum 120s.",externalUrlMissing:"L'URL externe n'est pas définie.",externalUrlHint:"L'API ML récupère l'image de la caméra via URL. Définissez l'URL externe dans les paramètres généraux pour que le conteneur ML API puisse atteindre Bambuddy.",perPrinterTitle:"Imprimantes surveillées",perPrinterHint:"Choisissez quelles imprimantes le service de détection surveille.",monitorAll:"Surveiller toutes les imprimantes connectées",statusTitle:"Statut",serviceRunning:"Service en cours d'exécution",thresholds:"Seuils bas / haut",activePrinters:"Impressions actives",noActivePrints:"Aucune impression en cours.",historyTitle:"Détections récentes",noHistory:"Aucune détection pour le moment."}},Hue={nav:{printers:"プリンター",archives:"アーカイブ",queue:"キュー",stats:"統計",profiles:"プロファイル",maintenance:"メンテナンス",projects:"プロジェクト",inventory:"フィラメント",files:"ファイル管理",notifications:"通知",settings:"設定",system:"システム",collapseSidebar:"サイドバーを閉じる",expandSidebar:"サイドバーを開く",update:"アップデート",updateAvailable:"アップデートあり: v{{version}}",updateAvailableBanner:"バージョン {{version}} が利用可能です!",viewUpdate:"アップデートを表示",viewOnGithub:"GitHubで表示",keyboardShortcuts:"キーボードショートカット (?)",switchToLight:"ライトモードに切替",switchToDark:"ダークモードに切替",smartSwitches:"スマートスイッチ",logout:"ログアウト"},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:"アップロード",uploading:"アップロード中...",uploadFailed:"アップロード失敗",actions:"操作",status:"ステータス",name:"名前",description:"説明",date:"日付",time:"時間",hours:"時間",minutes:"分",seconds:"秒",days:"日",enable:"有効化",disable:"無効にする",permissions:"権限",noPrinters:"プリンターが登録されていません",noData:"データがありません",linkNotFound:"リンクが見つかりません",required:"必須",optional:"オプション",dismiss:"閉じる",apply:"適用",reset:"リセット",export:"エクスポート",import:"インポート",clear:"クリア",selectAll:"すべて選択",deselectAll:"すべて選択解除",noChange:"— 変更なし —",unchanged:"変更なし",unassigned:"未割当",unknown:"不明",unknownError:"不明なエラー",today:"今日",tomorrow:"明日",asap:"即時",overdue:"期限超過",now:"今すぐ",collapse:"折りたたむ",expand:"展開",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",addedBy:"{{username}}が追加",prints:"プリント",more:"もっと見る",ascending:"昇順",descending:"降順",back:"戻る",copy:"コピー",copied:"コピーしました!",printer:"プリンター",remove:"削除",type:"種類",print:"印刷",rename:"名前変更",move:"移動",create:"作成",duplicate:"複製",left:"左",right:"右"},printers:{title:"プリンター",addPrinter:"プリンターを追加",editPrinter:"プリンターを編集",deletePrinter:"プリンターを削除",printerName:"プリンター名",serialNumber:"シリアル番号",ipAddress:"IPアドレス / ホスト名",accessCode:"アクセスコード",model:"モデル",nozzleCount:"ノズル数",autoArchive:"自動アーカイブ",status:{available:"利用可能",idle:"待機中",printing:"印刷中",paused:"一時停止",offline:"オフライン",problem:"問題",error:"エラー",finished:"完了",unknown:"不明"},temperatures:{nozzle:"ノズル",bed:"ベッド",chamber:"チャンバー"},progress:"{{percent}}% 完了",timeRemaining:"残り {{time}}",deleteConfirm:"「{{name}}」を削除しますか?",maintenanceOk:"メンテナンス正常",maintenanceWarning:"{{count}}件の警告",maintenanceWarning_plural:"{{count}}件の警告",maintenanceDue:"{{count}}件のメンテナンス期限",maintenanceDue_plural:"{{count}}件の期限",sort:{name:"名前",status:"ステータス",model:"モデル",location:"ロケーション",ascending:"昇順で並べ替え",descending:"降順で並べ替え"},cardSize:{small:"小",medium:"中",large:"大",extraLarge:"特大"},hideOffline:"オフラインを非表示",nextAvailable:"次に完了",powerOn:"電源オン",offlinePrintersWithPlugs:"スマートプラグ付きオフラインプリンター",noPrintersConfigured:"プリンターが設定されていません",search:"プリンターを検索...",noSearchResults:"検索またはフィルターに一致するプリンターがありません",filter:{allStatuses:"すべてのステータス",allLocations:"すべての場所"},readyToPrint:"印刷可能",external:"外部",extL:"Ext-L",extR:"Ext-R",deleteArchives:"印刷アーカイブを削除",noLabel:"ラベルなし",printPreview:"印刷プレビュー",width:"幅",height:"高さ",noObjectsFound:"オブジェクトが見つかりません",objectsLoadedOnPrintStart:"オブジェクトは印刷開始時に読み込まれます",willBeSkipped:"スキップされます",name:"名前",serialCannotBeChanged:"シリアル番号は変更できません",locationHelp:"プリンターのグループ化とキュージョブのフィルタリングに使用",wifiSignal:{veryWeak:"非常に弱い",weak:"弱い",fair:"注意",good:"良好",excellent:"非常に良い"},maintenanceUpToDate:"すべてのメンテナンスが最新です",chamberLightOn:"チャンバーライトをオンにしました",chamberLightOff:"チャンバーライトをオフにしました",files:"ファイル",browseFiles:"プリンターのファイルを参照",autoOffAfterPrint:"印刷後に自動電源オフ",autoOffExecuted:"自動オフが実行されました - リセットするにはプリンターの電源を入れてください",hmsErrors:"クリックしてHMSエラーを表示",viewHmsErrors:"{{count}}件のHMSエラーを表示",resume:"再開",pause:"一時停止",stop:"停止",camera:"カメラ",skipObject:"オブジェクトスキップ",reconnect:"再接続",forceRefresh:"強制更新",forceRefreshSuccess:"更新をリクエストしました",mqttDebug:"MQTTデバッグ",printerInformation:"プリンター情報",copyToClipboard:"コピー",copied:"コピーしました!",state:"状態",wifiSignalLabel:"WiFi信号",developerMode:"開発者モード",enabled:"有効",disabled:"無効",addedOn:"追加日",sdCard:"SDカード",inserted:"挿入済み",notInserted:"未挿入",totalPrintHours:"印刷時間",activeNozzle:"アクティブ: {{side}}ノズル",nozzleRack:"ノズルラック",nozzleDocked:"ドッキング中",nozzleMounted:"マウント中",nozzleActive:"アクティブ",nozzleIdle:"アイドル",nozzleDiameter:"直径",nozzleType:"タイプ",nozzleStatus:"ステータス",nozzleFilament:"フィラメント",nozzleWear:"摩耗",nozzleMaxTemp:"最高温度",nozzleSerial:"シリアル",nozzleHardenedSteel:"焼入れ鋼",nozzleStainlessSteel:"ステンレス鋼",nozzleTungstenCarbide:"タングステンカーバイド",nozzleFlow:"フロー",nozzleHighFlow:"ハイフロー",nozzleStandardFlow:"スタンダード",firmwareUpdate:"ファームウェアアップデート",firmwareInstructions:"プリンターのタッチスクリーンで",firmwareNav:"に移動",settings:"設定",firmware:"ファームウェア",discoverPrinters:"プリンターを検出",searching:"検索中...",manualEntry:"手動入力",addFromCloud:"クラウドから追加",toast:{printerDeleted:"プリンターを削除しました",missingSpoolAssignment:"{{printer}}で印刷を開始しました。以下のスプール割り当てがありません: {{slots}}",printerAdded:"プリンターを追加しました",printerUpdated:"プリンターを更新しました",failedToDelete:"プリンターの削除に失敗しました",failedToAdd:"プリンターの追加に失敗しました",failedToUpdate:"プリンターの更新に失敗しました",commandSent:"コマンドを送信しました",failedToSendCommand:"コマンドの送信に失敗しました",turnedOn:"{{name}} の電源をオンにしました",failedToPowerOn:"{{name}} の電源オンに失敗しました",scriptTriggered:"スクリプトを実行しました",printStopped:"印刷を停止しました",printPaused:"印刷を一時停止しました",printResumed:"印刷を再開しました",referenceDeleted:"リファレンスを削除しました",detectionAreaSaved:"検出エリアを保存しました",failedToRunScript:"スクリプトの実行に失敗しました",failedToStopPrint:"印刷の停止に失敗しました",failedToPausePrint:"印刷の一時停止に失敗しました",failedToResumePrint:"印刷の再開に失敗しました",failedToControlChamberLight:"チャンバーライトの制御に失敗しました",failedToSetSpeed:"印刷速度の設定に失敗しました",failedToUpdateSetting:"設定の更新に失敗しました",failedToSkipObjects:"オブジェクトのスキップに失敗しました",failedToRereadRfid:"RFIDの再読み取りに失敗しました",failedToCheckPlate:"プレートの確認に失敗しました",failedToUpdateLabel:"ラベルの更新に失敗しました",failedToDeleteReference:"リファレンスの削除に失敗しました",failedToSaveDetectionArea:"検出エリアの保存に失敗しました",plateCheckEnabled:"プレートチェックを有効にしました",plateCheckDisabled:"プレートチェックを無効にしました",calibrationSaved:"キャリブレーションを保存しました!",calibrationFailed:"キャリブレーションに失敗しました",rfidRereadInitiated:"RFID再読み取りを開始しました"},connection:{connected:"接続中",offline:"オフライン"},queue:{inQueue:"キュー内",inQueue_plural:"{{count}}件がキュー内"},controls:"コントロール",rfid:{reread:"RFID再読み取り"},permission:{noAdd:"プリンターを追加する権限がありません",noEdit:"プリンターを編集する権限がありません",noDelete:"プリンターを削除する権限がありません",noControl:"プリンターを制御する権限がありません",noFiles:"このディレクトリにファイルがありません",noAmsRfid:"AMS RFIDを再読み取りする権限がありません",noSmartPlugControl:"スマートプラグを制御する権限がありません",noCamera:"カメラを表示する権限がありません"},modal:{addTitle:"プリンターを追加",editTitle:"プリンターを編集",myPrinter:"マイプリンター",selectModel:"モデルを選択...",locationGroup:"ロケーション / グループ",locationPlaceholder:"例: 工房、オフィス、地下室",autoArchiveLabel:"完了した印刷を自動アーカイブ",fromPrinterSettings:"プリンターの設定から取得",modelOptional:"モデル(任意)",saveChanges:"変更を保存"},skipObjects:{tooltip:"オブジェクトスキップ",onlyWhilePrinting:"オブジェクトスキップ(印刷中のみ)",requiresMultiple:"オブジェクトスキップ(2個以上必要)",title:"オブジェクトスキップ",matchIdsInfo:"プリンター画面のIDと照合してください",printerShowsIds:"プリンター画面にビルドプレート上のオブジェクトIDが表示されます",skipSelected:"選択をスキップ",skipping:"スキップ中...",noObjectsSelected:"オブジェクトが選択されていません",selectObjectsToSkip:"現在の印刷からスキップするオブジェクトを選択してください",skipped:"スキップ済み",objectsSkipped:"オブジェクトをスキップしました",activeCount:"{{count}}個アクティブ",waitForLayer:"オブジェクトをスキップするにはレイヤー2以降をお待ちください(現在レイヤー{{layer}})",skip:"スキップ",confirmTitle:"オブジェクトをスキップしますか?",confirmMessage:"「{{name}}」をスキップしますか?この操作は元に戻せません。"},confirm:{deleteTitle:"プリンターを削除",deleteMessage:"「{{name}}」を削除しますか?すべての接続設定が削除されます。",deleteArchivesNote:"このプリンターのすべての印刷履歴が完全に削除されます。",keepArchivesNote:"印刷履歴は保持されますが、このプリンターとの関連は解除されます。",stopTitle:"印刷を停止",stopMessage:"「{{name}}」の現在の印刷を停止しますか?印刷ジョブがキャンセルされます。",stopButton:"印刷を停止",pauseTitle:"印刷を一時停止",pauseMessage:"「{{name}}」の現在の印刷を一時停止しますか?",pauseButton:"印刷を一時停止",resumeTitle:"印刷を再開",resumeMessage:"「{{name}}」の印刷を再開しますか?",resumeButton:"印刷を再開",powerOnTitle:"プリンターの電源をオン",powerOnMessage:"「{{name}}」の電源をオンにしますか?",powerOnButton:"電源オン",powerOffTitle:"プリンターの電源をオフ",powerOffMessage:"「{{name}}」の電源をオフにしますか?",powerOffWarning:"警告: 「{{name}}」は現在印刷中です!電源をオフにしますか?印刷が中断され、プリンターが損傷する可能性があります。",powerOffButton:"電源オフ"},bulk:{select:"選択",selectAll:"すべて選択",selectByLocation:"場所で選択",selected:"{{count}}件選択中",actions:{stop:"停止",pause:"一時停止",resume:"再開",clearPlate:"ベッドをクリア",clearHMS:"通知をクリア"},confirm:{stopTitle:"{{count}}件の印刷を停止",stopMessage:"{{count}}台のプリンターのアクティブな印刷をキャンセルします。この操作は元に戻せません。",stopButton:"すべて停止",pauseTitle:"{{count}}件の印刷を一時停止",pauseMessage:"{{count}}台のプリンターのアクティブな印刷を一時停止します。",pauseButton:"すべて一時停止",clearPlateTitle:"{{count}}台のプリントベッドをクリア",clearPlateMessage:"{{count}}台のプリンターのプリントベッドをクリアし、キュー内のジョブが開始される場合があります。",clearPlateButton:"すべてクリア"},success:"{{count}}台のプリンターで{{action}}が完了",partial:"{{succeeded}}件成功、{{failed}}件失敗",noneApplicable:"選択したプリンターにこのアクションに適した状態のものがありません",selectByState:"ステータスで選択"},discovery:{title:"プリンター",searching:"検索中...",scanning:"スキャン中...",scanProgress:"スキャン中... {{scanned}}/{{total}}",foundPrinters:"{{count}}台のプリンターを検出",noPrintersFound:"プリンターが見つかりません",noPrintersFoundSubnet:"指定されたサブネットにプリンターが見つかりません。",noPrintersFoundNetwork:"ネットワーク上にプリンターが見つかりません。",allConfigured:"検出されたすべてのプリンターは既に設定済みです。",alreadyAdded:"追加済み",select:"選択",manualEntry:"手動入力",addFromCloud:"クラウドから追加",subnetToScan:"スキャンするサブネット",dockerNote:"Dockerを検出しました。プリンターのサブネットをCIDR表記で入力してください。docker-compose.ymlでnetwork_mode: hostが必要です。",scanSubnet:"サブネットをスキャンしてプリンターを検出",discoverNetwork:"ネットワーク上のプリンターを検出",scanningSubnet:"サブネットでBambuプリンターをスキャン中...",scanningNetwork:"ネットワークをスキャン中...",serialRequired:"シリアル番号が必要です",unknown:"不明",failedToStart:"印刷の開始に失敗しました"},drying:{start:"乾燥開始",stop:"乾燥停止",temperature:"温度",duration:"時間",hours:"時間",timeRemaining:"残り {{time}}",active:"乾燥中",notSupported:"乾燥非対応",powerRequired:"AMS電源アダプターを接続して乾燥を有効にしてください",startingDrying:"乾燥を開始しています...",stoppingDrying:"乾燥を停止しています...",rotateTray:"乾燥中にスプールを回転"},filaments:"フィラメント",openCameraOverlay:"カメラオーバーレイを開く",openCameraWindow:"カメラを新しいウィンドウで開く",firmwareUpdateAvailable:"ファームウェアアップデートあり: {{current}} → {{latest}}",firmwareUpToDate:"ファームウェア {{version}} — 最新",firmwareUpdateButton:"アップデート",plateDetection:{noPermission:"このページにアクセスする権限がありません。",enabledClick:"プレートチェック有効 - クリックして無効化",disabledClick:"プレートチェック無効 - クリックして有効化",manageCalibration:"プレート検出キャリブレーションを管理",calibrationRequired:"キャリブレーションが必要です",calibrationInstructions:"ビルドプレートが<strong>完全に空</strong>であることを確認してから、キャリブレーションをクリックしてください。",calibrationDescription:"キャリブレーションは空のプレートのリファレンス画像を撮影します。以降のチェックではこのリファレンスと比較してオブジェクトを検出します。",calibrationTip:"<strong>ヒント:</strong> 異なるプレート用に最大5つのキャリブレーションを保存できます。チェック時に最適なものが自動的に使用されます。",plateEmpty:"プレートは空のようです",objectsDetected:"オブジェクトを検出しました",confidence:"信頼度",difference:"差分",analysisPreview:"分析プレビュー:",analysisLegend:"緑の枠 = 検出エリア、赤のオーバーレイ = キャリブレーションとの差分",savedReferences:"保存済みリファレンス ({{count}}/{{max}})",deleteReference:"リファレンスを削除",labelPlaceholder:"ラベル...",clickToEdit:"{{label}} - クリックして編集",clickToAddLabel:"クリックしてラベルを追加"},speed:{title:"印刷速度",silent:"サイレント (50%)",standard:"スタンダード (100%)",sport:"スポーツ (124%)",ludicrous:"ルディクラス (166%)"},airduct:{title:"エアダクトモード",cooling:"冷却",heating:"加熱"},noSdCard:"SDなし",door:{open:"開",closed:"閉"},fans:{partCooling:"パーツ冷却ファン",auxiliary:"補助ファン",chamber:"チャンバーファン"},clickToViewHmsErrors:"クリックしてHMSエラーを表示",estimatedCompletion:"完了予定時刻",plateNumber:"プレート {{number}}",slotOptions:"スロットオプション",amsPopup:{friendlyName:"AMS名",friendlyNamePlaceholder:"例: AMS フレンドリー名",serialNumber:"シリアル番号",firmwareVersion:"ファームウェア",save:"保存",clear:"クリア",noEditPermission:"AMS ユニットの名前を変更する権限がありません"},firmwareModal:{title:"ファームウェアアップデート",titleUpToDate:"ファームウェア情報",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",releaseNotes:"リリースノート",checkingPrereqs:"前提条件を確認中...",sdCardReady:"SDカード準備完了。下をクリックしてファームウェアをアップロードしてください。",uploadedSuccess:"ファームウェアをSDカードにアップロードしました!",applyInstructions:"プリンターでアップデートを適用するには:",step1:"プリンターのタッチスクリーンで設定に移動",step2:"ファームウェアに移動",step3:"SDカードからアップデートを選択",step4:"アップデートには10〜20分かかります",done:"完了",starting:"開始中...",uploadFirmware:"ファームウェアをアップロード",uploadFailed:"アップロード開始に失敗しました: {{error}}",uploadedToast:"ファームウェアをアップロードしました!プリンター画面からアップデートを実行してください。"},accessCodePlaceholder:"プリンター設定から取得",roi:{title:"プリンター",xStart:"X開始",yStart:"Y開始",width:"幅",height:"高さ",instruction:"ビルドプレートに焦点を合わせるように検出エリアを調整してください。プレビューの緑の枠が現在のエリアを示しています。"},developerModeWarning:"開発者LANモードが有効になっていません: {{names}}。一部の機能が動作しない可能性があります。",howToEnable:"有効化方法",incompatibleFile:"このファイルは{{slicedFor}}用にスライスされていますが、このプリンターは{{printerModel}}です",dropNotPrintable:".gcodeおよび.gcode.3mfファイルのみ印刷できます",dropToPrint:"ドロップして印刷",cannotPrint:"プリンター使用中"},archives:{title:"印刷アーカイブ",searchPlaceholder:"アーカイブを検索...",filterByPrinter:"プリンターで絞り込み",filterByStatus:"ステータスで絞り込み",sortBy:"並べ替え",sortNewest:"新しい順",sortOldest:"古い順",sortName:"名前順",sortDuration:"時間順",sortLargest:"大きい順",sortSmallest:"小さい順",sortSize:"サイズ",noArchives:"アーカイブが見つかりません",noArchivesSearch:"検索条件に一致するアーカイブがありません",originalPrintNotVisible:"元の印刷が表示されていません - フィルターをクリアしてみてください",noArchivesYet:"アーカイブはまだありません",prints:"件",pagination:{showing:"表示中",to:"〜",of:"/",show:"表示",page:"ページ",all:"すべて"},loadingArchives:"アーカイブを読み込み中...",releaseToUpload:"ドロップしてアップロード",showAll:"すべて表示",showFavoritesOnly:"お気に入りのみ表示",gridView:"グリッド表示",listView:"リスト表示",calendarView:"カレンダー表示",logView:"印刷ログ",manageTags:"タグを管理",showFailedPrints:"失敗した印刷を表示",hideFailedPrints:"失敗した印刷を非表示",hideDuplicates:"重複を非表示",viewOriginalPrint:"クリックして元の印刷を表示 (#{{id}})",printTime:"印刷時間",filamentUsed:"フィラメント使用量",cost:"コスト",reprint:"再印刷",preview:"プレビュー",deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",favorite:"お気に入り",unfavorite:"お気に入りから削除",viewDetails:"詳細を表示",status:{completed:"完了",failed:"失敗",stopped:"中止"},toast:{source3mfAttached:"ソース3MFを添付しました: {{filename}}",failedUploadSource3mf:"ソース3MFのアップロードに失敗しました",source3mfRemoved:"ソース3MFを削除しました",failedRemoveSource3mf:"ソース3MFの削除に失敗しました",f3dAttached:"F3Dを添付しました: {{filename}}",failedUploadF3d:"F3Dのアップロードに失敗しました",f3dRemoved:"F3Dを削除しました",failedRemoveF3d:"F3Dの削除に失敗しました",timelapseAttached:"タイムラプスを添付しました: {{filename}}",timelapseAlreadyAttached:"タイムラプスは既に添付されています",noMatchingTimelapse:"一致するタイムラプスが見つかりません",failedScanTimelapse:"タイムラプスのスキャンに失敗しました",failedAttachTimelapse:"タイムラプスの添付に失敗しました",timelapseRemoved:"タイムラプスを削除しました",failedRemoveTimelapse:"タイムラプスの削除に失敗しました",timelapseUploaded:"タイムラプスをアップロードしました: {{filename}}",failedUploadTimelapse:"タイムラプスのアップロードに失敗しました",archiveDeleted:"アーカイブを削除しました",failedDeleteArchive:"アーカイブの削除に失敗しました",addedToFavorites:"お気に入りに追加しました",removedFromFavorites:"お気に入りから削除しました",projectUpdated:"プロジェクトを更新しました",failedUpdateProject:"プロジェクトの更新に失敗しました",linkCopied:"リンクをクリップボードにコピーしました",failedCopyLink:"リンクのコピーに失敗しました",photoDeleted:"写真を削除しました",failedDeletePhoto:"写真の削除に失敗しました",failedDeleteArchives:"アーカイブの削除に失敗しました",failedUpdateFavorites:"お気に入りの更新に失敗しました",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました"},menu:{print:"印刷",schedule:"スケジュール",openInBambuStudio:"スライサーで開く",slice:"スライス",externalLink:"外部リンク",viewOnMakerWorld:"MakerWorldで表示",preview3d:"3Dプレビュー",viewTimelapse:"タイムラプスを表示",scanForTimelapse:"タイムラプスをスキャン",uploadTimelapse:"タイムラプスをアップロード",removeTimelapse:"タイムラプスを削除",downloadSource3mf:"ソース3MFをダウンロード",uploadSource3mf:"ソース3MFをアップロード",replaceSource3mf:"ソース3MFを置換",removeSource3mf:"ソース3MFを削除",uploadF3d:"F3Dをアップロード",replaceF3d:"F3Dを置換",downloadF3d:"Fusion 360デザインファイルをダウンロード",removeF3d:"F3Dを削除",download:"ダウンロード",copyDownloadLink:"ダウンロードリンクをコピー",qrCode:"QRコード",viewPhotos:"{{count}}枚の写真を表示",viewPhotosCount:"写真を表示 ({{count}})",projectPage:"プロジェクトページ",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",edit:"編集",goToProject:"プロジェクトへ: {{name}}",addToProject:"プロジェクトに追加",removeFromProject:"プロジェクトから削除",loading:"アーカイブを読み込み中...",noProjectsAvailable:"利用可能なプロジェクトがありません",select:"選択",deselect:"選択解除",delete:"削除"},permission:{noReprint:"このアーカイブを再印刷する権限がありません",noAddToQueue:"キューに追加する権限がありません",noUpdateArchives:"アーカイブを更新する権限がありません",noUploadFiles:"ファイルをアップロードする権限がありません",noDownload:"アーカイブをダウンロードする権限がありません",noCopyLink:"ダウンロードリンクをコピーする権限がありません",noDelete:"このアーカイブを削除する権限がありません",noCreate:"アーカイブを作成する権限がありません"},card:{previousPlate:"前のプレート",nextPlate:"次のプレート",plateNumber:"プレート {{number}}",moreOptions:"その他のオプション",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",cancelled:"キャンセル",failed:"失敗",duplicate:"重複",duplicateTitle:"このモデルは以前印刷されています",openSource3mf:"ソース3MFをBambu Studioで開く(右クリックでオプション表示)",downloadF3d:"Fusion 360デザインファイルをダウンロード",viewTimelapse:"タイムラプスを表示",viewPhoto:"写真を表示",viewPhotos:"{{count}}枚の写真を表示",openFolder:"フォルダーを開く: {{name}}",slicedFile:"スライス済みファイル - 印刷可能",sourceFile:"ソースファイルのみ - AMSマッピング不可",gcode:"GCODE",source:"ソース",project:"プロジェクト",estimated:"推定: {{time}}",actual:"実際: {{time}}",accuracy:"精度: {{percent}}%",filament:"{{weight}}g",layer:"レイヤー",layers:"レイヤー",object:"{{count}}オブジェクト",objects:"{{count}}オブジェクト",slicedFor:"{{model}}用にスライス",uploadedBy:"アップロード者",noPermissionReprint:"再印刷する権限がありません",noFileForReprint:"3MFファイルがありません — 印刷記録時にプリンターからファイルをダウンロードできませんでした",noPermissionEdit:"プロファイルを編集する権限がありません",noPermissionDelete:"アーカイブを削除する権限がありません",reprint:"再印刷",schedulePrint:"印刷をスケジュール",schedule:"スケジュール",openInBambuStudio:"スライサーで開く",openInBambuStudioToSlice:"スライサーでスライス",slice:"スライス",externalLink:"外部リンク",makerWorld:"MakerWorld: {{designer}}",viewProject:"プロジェクトを表示",noExternalLink:"外部リンクなし",preview3d:"3Dプレビュー",download:"ダウンロード",edit:"編集",delete:"削除"},modal:{deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",deleteButton:"削除",removeSource3mf:"ソース3MFを削除",removeSource3mfConfirm:'"{{name}}"からソース3MFファイルを削除してもよろしいですか?元のスライサープロジェクトファイルが削除されます。',removeButton:"削除",removeF3d:"F3Dを削除",removeF3dConfirm:'"{{name}}"からFusion 360デザインファイルを削除してもよろしいですか?',removeTimelapse:"タイムラプスを削除",removeTimelapseConfirm:'"{{name}}"からタイムラプス動画を削除してもよろしいですか?',timelapse:"{{name}} - タイムラプス",selectTimelapse:"タイムラプスを選択",selectTimelapseDesc:"自動一致が見つかりませんでした。この印刷のタイムラプスを選択してください:",deleteArchives:"印刷アーカイブを削除",deleteArchivesConfirm:"{{count}}件のアーカイブを削除しますか?この操作は元に戻せません。",deleteCount:"{{count}}件を削除"},page:{title:"印刷アーカイブ",printsCount:"{{count}}回印刷",dropFilesHere:".3mfファイルをここにドロップ",releaseToUpload:"ドロップしてアップロード",only3mfSupported:".3mfファイルのみ対応しています",close:"閉じる",selected:"{{count}}件選択中",selectAll:"すべて選択",tags:"タグ",project:"プロジェクト",favorite:"お気に入り",delete:"削除",toggledFavorites:"{{count}}件のアーカイブのお気に入りを切替えました",failedUpdateFavorites:"お気に入りの更新に失敗しました",archivesDeleted:"{{count}}件のアーカイブを削除しました",failedDeleteArchives:"アーカイブの削除に失敗しました",photoDeleted:"写真を削除しました",failedDeletePhoto:"写真の削除に失敗しました"},list:{name:"名前",printer:"プリンター",date:"日付",size:"サイズ",actions:"操作",hasTimelapse:"タイムラプスあり"},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:"印刷ログの削除に失敗しました"}},queue:{title:"印刷キュー",subtitle:"印刷ジョブのスケジュールと管理",addToQueue:"キューに追加",print:"印刷",reprint:"再印刷",schedulePrint:"印刷をスケジュール",editQueueItem:"キューアイテムを編集",printToPrinters:"{{count}}台のプリンターで印刷",queueToPrinters:"{{count}}台のプリンターでキュー追加",queueSelectedPlates:"{{count}}プレートをキューに追加",selectAllPlates:"全{{count}}プレートを選択",deselectAll:"全て解除",printQueued:"キューに追加しました",itemsQueued:"{{count}}件をキューに追加しました",sending:"送信中...",sendingProgress:"送信中 {{current}}/{{total}}...",adding:"追加中...",addingProgress:"追加中 {{current}}/{{total}}...",savingProgress:"保存中 {{current}}/{{total}}...",clearQueue:"キューをクリア",clearHistory:"履歴をクリア",emptyQueue:"キューは空です",position:"順番",scheduledTime:"予定時刻",moveUp:"上に移動",moveDown:"下に移動",startNow:"今すぐ開始",printingInProgress:"印刷中...",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",itemCount:"{{count}}件",itemCount_plural:"{{count}}件のアイテム",dragToReorder:"ドラッグして並べ替え(ASAPのみ)",reorderHint:"順番はASAPアイテムのみに影響します。スケジュール済みアイテムは設定時刻に実行されます。",sjf:{label:"SJF",tooltip:"短いジョブ優先 — スケジューラーが短い印刷を優先します"},addedBy:"{{username}}が追加",nextInQueue:"次のキュー",clearPlate:"プレートをクリアして次を開始",clearPlateSuccess:"プレートをクリアしました — 次の印刷の準備完了",plateReady:"プレートをクリアしました — 次の印刷の準備完了",plateNumber:"プレート {{index}}",quantity:"数量",quantityHint:"{{count}}件のキューアイテムを作成",activeBatches:"アクティブなバッチ",batchProgress:"{{total}}件中{{completed}}件完了",cancelBatch:"残りをキャンセル",batchCancelled:"残りのバッチアイテムをキャンセルしました",cancelBatchConfirmTitle:"バッチをキャンセル",cancelBatchConfirmMessage:"このバッチの残りの保留中アイテムをすべてキャンセルしますか?",batch:"バッチ",sections:{currentlyPrinting:"印刷中",queued:"キュー中",history:"履歴"},status:{pending:"待機中",waiting:"待機中",printing:"印刷中",paused:"一時停止",completed:"完了",failed:"失敗",skipped:"スキップ",cancelled:"キャンセル済み"},summary:{printing:"印刷中",queued:"キュー中",totalTime:"キュー合計時間",totalWeight:"キュー合計重量",history:"履歴"},filter:{allPrinters:"すべてのプリンター",unassigned:"未割当",allStatus:"すべてのステータス",allLocations:"すべてのロケーション",any:"すべて"},sort:{byPosition:"順番で並べ替え",byName:"名前で並べ替え",byPrinter:"プリンターで並べ替え",bySchedule:"スケジュールで並べ替え",byDate:"日付で並べ替え",ascendingOldest:"昇順(古い順)",descendingNewest:"降順(新しい順)"},badges:{staged:"ステージ済み",requiresPrevious:"前の成功が必要",autoPowerOff:"自動電源オフ",gcodeInjection:"G-code"},empty:{title:"スケジュールされた印刷はありません",description:"アーカイブページのコンテキストメニューから「スケジュール」オプションを使用するか、ファイルをドラッグ&ドロップして始めましょう。"},time:{asap:"即時",overdue:"期限超過",now:"今すぐ",lessThanMinute:"1分以内",inMinutes:"{{count}}分後",inHours:"{{count}}時間後"},actions:{stopPrint:"印刷を停止",startPrint:"印刷を開始",requeue:"再キュー"},bulkEdit:{title:"{{count}}件のアイテムを編集",title_plural:"{{count}}件のアイテムを編集",description:"変更した設定のみが選択されたアイテムに適用されます。",printer:"プリンター",noChange:"— 変更なし —",queueOptions:"キューオプション",staged:"ステージ済み",autoPowerOff:"印刷後に自動電源オフ",requirePrevious:"前の成功を必要とする",printOptions:"印刷オプション",bedLevelling:"ベッドレベリング",flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",layerInspection:"第一層検査",timelapse:"タイムラプス",useAms:"AMS使用",applyChanges:"変更を適用",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",editSelected:"選択を編集",cancelSelected:"選択をキャンセル"},confirm:{cancelTitle:"スケジュール済み印刷をキャンセル",cancelMessage:"「{{name}}」をキャンセルしますか?",stopTitle:"印刷を停止",stopMessage:"現在の印刷「{{name}}」を停止しますか?プリンター上の印刷ジョブがキャンセルされます。",removeTitle:"履歴から削除",removeMessage:"「{{name}}」をキュー履歴から削除しますか?",clearHistoryTitle:"履歴をクリア",clearHistoryMessage:"{{count}}件の履歴をすべて削除しますか?",cancelButton:"印刷をキャンセル",stopButton:"印刷を停止",thisPrint:"この印刷",thisItem:"このアイテム"},toast:{cancelled:"キャンセル済み",cancelFailed:"アイテムのキャンセルに失敗しました",removed:"キューアイテムを削除しました",removeFailed:"プロジェクトからのアーカイブ削除に失敗しました",stopped:"印刷を停止しました",stopFailed:"印刷の停止に失敗しました",released:"印刷をキューにリリースしました",startFailed:"印刷の開始に失敗しました",reorderFailed:"キューの並べ替えに失敗しました",historyCleared:"{{count}}件の履歴をクリアしました",clearHistoryFailed:"履歴のクリアに失敗しました",updateFailed:"アイテムの更新に失敗しました",bulkCancelled:"{{count}}件のアイテムをキャンセルしました",bulkCancelFailed:"アイテムのキャンセルに失敗しました"},timeline:{listView:"リスト",timelineView:"タイムライン",unassigned:"未割当",noData:"この日の予定された印刷はありません",allDoneBy:"すべての印刷は {{time}} までに完了予定",staged:"ステージング",filterAll:"すべて表示",filterPrinting:"印刷中",filterQueued:"待機中",time:{anyMoment:"まもなく",minutesLeft:"残り{{minutes}}分",hoursLeft:"残り{{hours}}時間",hoursMinutesLeft:"残り{{hours}}時間{{minutes}}分"},day:{previous:"前日",next:"翌日",today:"今日"}},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}} 件成功",printStartedRemaining:"{{completed}} 件の印刷を開始、残り {{remaining}} 件送信中..."}},stats:{title:"統計",subtitle:"ウィジェットをドラッグして並べ替え。目のアイコンをクリックして非表示。",overview:"概要",totalPrints:"総印刷数",successRate:"成功率",totalPrintTime:"総印刷時間",printTime:"印刷時間",totalFilament:"総フィラメント使用量",filamentUsed:"フィラメント使用量",filamentCost:"フィラメントコスト",totalCost:"総コスト",energyUsed:"エネルギー使用量",energyCost:"エネルギーコスト",energyWarmingUpTooltip:"エネルギー追跡は毎時スナップショットを収集中です。選択範囲の前に少なくとも1つのスナップショットが存在すると、期間合計が正確になります。初期値は過小になる場合があります。",averagePrintTime:"平均印刷時間",printsPerDay:"1日あたりの印刷数",byPrinter:"プリンター別",printsByPrinter:"プリンター別印刷数",byMaterial:"素材別",byMonth:"月別",last7Days:"過去7日間",last30Days:"過去30日間",last90Days:"過去90日間",allTime:"全期間",quickStats:"クイック統計",printActivity:"印刷アクティビティ",filamentTypes:"フィラメントタイプ",filamentTrends:"フィラメントトレンド",failureAnalysis:"失敗分析",timeAccuracy:"時間精度",successful:"成功",failed:"失敗",perfectEstimate:"100% = 完全な推定",noTimeAccuracyData:"時間精度データがありません",noFilamentData:"フィラメントデータがありません",noPrinterData:"プリンターデータがありません",noPrintData:"印刷データがありません",noPrintDataLast30Days:"過去30日間の印刷データがありません",failureReasons:"失敗理由",topFailureReasons:"主な失敗理由",failedPrintsCount:"{{failed}} / {{total}} 件の印刷が失敗",lastWeekRate:"先週: {{rate}}%",resetLayout:"レイアウトをリセット",recalculateCosts:"コストを再計算",recalculateCostsHint:"現在のフィラメント価格ですべてのアーカイブコストを再計算",exportStats:"統計をエクスポート",exportAsCsv:"CSVでエクスポート",exportAsExcel:"Excelでエクスポート",hiddenCount:"{{count}}件非表示",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました",layoutReset:"レイアウトをリセットしました",recalculatedCosts:"{{count}}件のアーカイブのコストを再計算しました",recalculateFailed:"コストの再計算に失敗しました",loadingStats:"統計を読み込み中...",noPermissionResetLayout:"レイアウトをリセットする権限がありません",noPermissionRecalculate:"コストを再計算する権限がありません",noPrintDataInRange:"選択した期間にデータがありません",periodFilament:"フィラメント使用量",periodCost:"コスト",avgPerPrint:"1印刷あたりの平均",usageOverTime:"時間推移",filamentByWeight:"重量",printDuration:"印刷時間分布",printerUtilization:"プリンター稼働率",filamentSuccess:"素材別成功率",printHabits:"印刷習慣",printTimeOfDay:"時間帯別プリント",colorDistribution:"カラー分布",noColorData:"カラーデータがありません",records:"記録",longestPrint:"最長プリント",heaviestPrint:"最重プリント",mostExpensivePrint:"最高額",busiestDay:"最多プリント日",successStreak:"連続成功",streakPrint:"連続プリント",streakPrints:"{{count}}連続プリント",printerStats:"プリンター統計",hours:"時間",avgPrints:"平均印刷数",noArchiveData:"印刷データがありません",filamentByTime:"推移",avgWeight:"平均重量",avgTime:"平均時間",filamentByPrints:"印刷数",timeframe:{today:"今日","this-week":"今週","this-month":"今月","last-7":"過去7日間","last-30":"過去30日間","last-90":"過去90日間","this-year":"今年","all-time":"全期間",custom:"カスタム",from:"開始",to:"終了"},allUsers:"全ユーザー",noUser:"ユーザーなし(システム)",filterByUser:"ユーザーでフィルター"},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:"現在の時間",statusTab:"ステータス",settingsTab:"設定",overdueCount:"{{count}}件超過",dueSoonCount:"{{count}}件まもなく期限",dueSoon:"まもなく期限",allGood:"問題なし",overdueBy:"{{duration}}超過",dueIn:"あと{{duration}}",timeLeft:"残り{{duration}}",day:"1日",days:"日",week:"1週間",weeks:"{{count}}週間",month:"1ヶ月",months:"{{count}}ヶ月",year:"1年",maintenanceTypes:"メンテナンスタイプ",maintenanceTypesDescription:"システムタイプとカスタムメンテナンスタスク",addCustomType:"カスタムタイプを追加",restoreDefaults:"デフォルトタスクを復元",intervalType:"インターバルタイプ",intervalValue:"間隔 ({{type}})",icon:"アイコン",documentationLink:"ドキュメントリンク(任意)",assignToPrinters:"プリンターに割り当て",selectAtLeastOnePrinter:"プリンターを1台以上選択してください",addType:"タイプを追加",custom:"カスタム",printHours:"印刷時間",calendarDays:"カレンダー日数",exampleName:"例: HEPAフィルター交換",viewDocumentation:"ドキュメントを表示",timeBasedInterval:"時間ベースのインターバル",intervalOverrides:"インターバルのオーバーライド",intervalOverridesDescription:"特定のプリンターの間隔をカスタマイズ",assignedToPrinters:"割り当て済みプリンター:",noPrintersAssigned:"プリンター未割り当て",addPrinterShort:"追加:",printersAssignedClick:"{{count}}台のプリンターを割り当て済み - クリックして管理",removeFromPrinter:"このプリンターから削除",types:{lubricateCarbonRods:"カーボンロッドの潤滑",lubricateRails:"リニアレールの潤滑",cleanNozzle:"ノズル/ホットエンドの清掃",checkBelts:"ベルト張力の確認",cleanBuildPlate:"ビルドプレートの清掃",checkExtruder:"エクストルーダーギアの確認",checkCooling:"冷却ファンの確認",generalInspection:"総合点検",cleanCarbonRods:"カーボンロッドの清掃",lubricateSteelRods:"スチールロッドの潤滑",cleanSteelRods:"スチールロッドの清掃",cleanLinearRails:"リニアレールの清掃",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},maintenanceComplete:"メンテナンスを完了としてマークしました",typeUpdated:"メンテナンスタイプを更新しました",typeDeleted:"メンテナンスタイプを削除しました",defaultsRestored:"デフォルトタスクを{{count}}件復元しました",printHoursUpdated:"印刷時間を更新しました",printerAssigned:"プリンターを割り当てました",printerRemoved:"プリンターを削除しました",deleteTypeConfirm:"「{{name}}」を削除しますか?",deleteSystemTypeTitle:"デフォルトのメンテナンスタスクを削除しますか?",deleteSystemTypeMessage:"デフォルトのメンテナンスタスク「{{name}}」を削除してもよろしいですか?",noPermissionUpdate:"メンテナンス記録を更新する権限がありません",noPermissionPerform:"メンテナンスを実行する権限がありません",noPermissionEditTypes:"メンテナンスタイプを編集する権限がありません",noPermissionDeleteTypes:"メンテナンスタイプを削除する権限がありません",noPermissionEditHours:"メンテナンス時間を編集する権限がありません",noPermissionRemovePrinter:"プリンターの割り当てを解除する権限がありません",noPermissionAssignPrinter:"プリンターを割り当てる権限がありません",noPermissionEditIntervals:"メンテナンス間隔を編集する権限がありません",configureSettings:"メンテナンスタイプと間隔を設定"},settings:{title:"設定",general:"一般",tabs:{general:"一般",smartPlugs:"スマートプラグ",notifications:"通知",queue:"ワークフロー",filament:"フィラメント",network:"ネットワーク",apiKeys:"APIキー",virtualPrinter:"仮想プリンター",spoolbuddy:"SpoolBuddy",failureDetection:"失敗検出",users:"認証",backup:"バックアップ",emailAuth:"メール認証",ldap:"LDAP",twoFa:"二段階認証",oidc:"SSO / OIDC"},spoolbuddy:{infoTitle:"SpoolBuddy デバイス",infoBody:"SpoolBuddy キオスクはハートビートにより自動的に登録されます。使用されなくなった場合や、デーモンのクラッシュにより古い重複が残った場合は、ここでデバイスの登録を解除してください。",duplicatesTitle:"{{count}} 台のデバイスが登録されています",duplicatesBody:"キオスク UI は最初に登録されたデバイスのみを使用します。クラッシュによる古い重複がある場合は登録解除してください。オンラインのデバイスは次回のハートビートで自動的に再登録されます。",empty:"SpoolBuddy デバイスはまだ登録されていません。",online:"オンライン",offline:"オフライン",unregister:"登録解除",unregisterSuccess:"デバイスの登録を解除しました",unregisterError:"デバイスの登録解除に失敗しました",confirmTitle:"SpoolBuddy デバイスの登録を解除しますか?",confirmBody:"「{{hostname}}」({{deviceId}})をデータベースから削除します。デバイスがオンラインの場合、次回のハートビートで自動的に再登録されます。",ipAddress:"IPアドレス",firmware:"ファームウェア",lastSeen:"最終接続",daemonUptime:"デーモン稼働時間",systemUptime:"システム稼働時間",never:"なし",nfc:"NFC",scale:"計量器",cpuTemp:"CPU 温度",memory:"メモリ",disk:"ディスク"},ldap:{title:"LDAP認証",enabledDesc:"LDAP認証が有効です",disabledDesc:"LDAP認証が無効です",disabledHint:"以下のLDAP設定を構成して保存し、有効にしてください。",enabled:"LDAP認証を有効にしました",disabled:"LDAP認証を無効にしました",feature1:"LDAP資格情報でログインできます",feature2:"ローカル管理者アカウントはフォールバックとして残ります",feature3:"ログイン時にLDAPグループがBamBuddyグループにマッピングされます",serverConfig:"LDAPサーバー設定",serverUrl:"サーバーURL",serverUrlHint:"標準はldap://、SSL接続はldaps://を使用",security:"セキュリティ",securityHint:"StartTLSはプレーン接続をTLSにアップグレードします。LDAPSは最初からTLSを使用します。",bindDn:"バインドDN(サービスアカウント)",bindPassword:"バインドパスワード",searchBase:"検索ベースDN",userFilter:"ユーザー検索フィルター",userFilterHint:"{username}はログインユーザー名に置き換えられます。OpenLDAPの場合は(uid={username})を使用。",autoProvision:"ユーザー自動作成",autoProvisionHint:"初回LDAPログイン時にBamBuddyアカウントを自動作成",defaultGroup:"デフォルトグループ",defaultGroupNone:"— なし(フォールバックなし)—",defaultGroupHint:"LDAPユーザーが認証されたがマッピングされたLDAPグループに属していない場合に割り当てられるフォールバックグループ。空欄の場合、マッピングされていないユーザーは権限なしのままになります。",groupMapping:"グループマッピング(JSON)",groupMappingHint:"LDAPグループDNをBamBuddyグループにマッピング。利用可能なグループ: ",testConnection:"接続テスト",settingsSaved:"LDAP設定を保存しました",errors:{serverRequired:"LDAPサーバーURLは必須です",searchBaseRequired:"検索ベースDNは必須です",enableAuthFirst:"先に認証を有効にしてください",configureLdapFirst:"先にLDAP設定を保存してください"}},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設定を構成してテストしてください",enableAuthFirst:"メール関連機能をご利用いただくには、まず認証を有効にしてください。"},success:{settingsSaved:"SMTP設定を保存しました"},securityOptions:{starttls:"STARTTLS (ポート 587)",ssl:"SSL/TLS (ポート 465)",none:"なし (ポート 25)"},authOptions:{enabled:"有効",disabled:"無効"}},appearance:"外観",notifications:"通知",smartPlugs:"スマートプラグ",spoolman:"Spoolman",updates:"アップデート",language:"言語",languageDescription:"表示言語を選択してください",theme:"テーマ",themeLight:"ライト",themeDark:"ダーク",themeSystem:"システム設定に従う",defaultView:"デフォルト画面",defaultViewDescription:"アプリ起動時に表示するページ",checkForUpdates:"アップデートを確認",autoUpdate:"自動アップデート",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",upToDate:"最新です",updateAvailable:"アップデートあり",notificationLanguage:"通知の言語",notificationLanguageDescription:"プッシュ通知の言語",bedCooledThreshold:"ベッド冷却しきい値",bedCooledThresholdDescription:"印刷後にベッドが冷却されたと見なす温度",userNotificationsEnabled:"ユーザー通知",userNotificationsEnabledDescription:"ユーザー通知メニューと印刷ジョブイベントのメール通知を有効にします。高度な認証が必要です。",userNotificationsDisabledHint:"ユーザー通知を使用するには高度な認証を有効にしてください。",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:"電源オフ"},filamentTracking:"フィラメント追跡",filamentTrackingDesc:"フィラメントスプールの追跡方法を選択してください。内蔵インベントリまたは外部Spoolmanサーバーを使用できます。",filamentChecks:"フィラメントチェック",disableFilamentWarnings:"フィラメント警告を無効化",disableFilamentWarningsDesc:"印刷またはキュー追加時にフィラメント不足の警告を表示しない",preferLowestFilament:"残量が少ないフィラメントを優先",preferLowestFilamentDesc:"複数のスプールが一致する場合、残量が最も少ないものを使用します",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:"全プリンター",noDefaultPrinter:"デフォルトなし(毎回選択)",sidebarOrder:"サイドバーの順序",saveThumbnails:"サムネイルを保存",captureFinishPhoto:"完了写真を撮影",noPrintersConfigured:"プリンターが設定されていません",archiveMode:{always:"常にアーカイブを作成",never:"アーカイブを作成しない",ask:"毎回確認"},checkForUpdatesLabel:"アップデートを確認",checkPrinterFirmware:"プリンターファームウェアの確認",includeBetaUpdates:"ベータ版を含める",includeBetaUpdatesDesc:"アップデート確認時にベータ版およびプレリリース版を通知する",enableRetry:"リトライを有効化",homeAssistantDescription:"Home Assistantに接続してHA REST APIでスマートプラグを制御します。switch、light、input_booleanエンティティに対応しています。",environmentManagedLabel:"(環境変数で管理)",autoEnabledViaEnv:"環境変数により自動的に有効化されました",urlFromEnvReadOnly:"HA_URL環境変数で設定された値(読み取り専用)",tokenFromEnvReadOnly:"HA_TOKEN環境変数で設定された値(読み取り専用)",mqttConnectedTo:"接続先:",prometheusDescription:"プリンターデータをPrometheus形式で公開",noSmartPlugsTitle:"スマートプラグが設定されていません",noSmartPlugsDescription:"Tasmotaベースのスマートプラグを追加して、エネルギー消費を追跡し、電源制御を自動化します。",noProvidersTitle:"プロバイダーが設定されていません",noProvidersDescription:"アラートを受信するにはプロバイダーを追加してください。",noTemplatesAvailable:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを生成してください。",apiPermissionView:"プリンターステータスとキューを表示",apiPermissionEdit:"印刷キューにアイテムを追加・削除",apiKeysEmptyTitle:"APIキーがありません",apiKeysEmptyDescription:"外部サービスと連携するためのAPIキーを作成してください。",noUsersFound:"ユーザーが見つかりません",noGroupsFound:"グループが見つかりません",noGroupsAvailable:"利用可能なグループがありません",passwordsDoNotMatch:"パスワードが一致しません",systemGroupWarning:"システムグループ名は変更できません",authDisabledTitle:"認証が無効です",authDisabledFeature1:"システムへのアクセスにログインを要求",authDisabledFeature2:"グループベースの権限で複数ユーザーを作成",authDisabledFeature3:"50以上のきめ細かな権限でアクセスを制御",userHasCreated:"このユーザーは以下を作成しています:",userItemsQuestion:"これらのアイテムをどうしますか?",deleteUserConfirm:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。",actionCannotBeUndone:"この操作は元に戻せません",addFirstSmartPlug:"最初のスマートプラグを追加",providers:"プロバイダー",log:"ログ",testAll:"すべてテスト",testResults:"テスト結果",testPassedCount:"{{count}}件成功",testFailedCount:"{{count}}件失敗",messageTemplates:"メッセージテンプレート",messageTemplatesDescription:"各イベントの通知メッセージをカスタマイズ。",apiKeys:"APIキー",apiKeysDescription:"外部連携やWebhook用のAPIキーを作成します。",createKey:"キーを作成",apiKeyCreated:"APIキーを作成しました",apiKeyCopyWarning:"今すぐこのキーをコピーしてください - 再表示されません!",useInApiBrowser:"APIブラウザーで使用",createNewApiKey:"新しいAPIキーを作成",keyName:"キー名",keyNamePlaceholder:"例: Home Assistant, OctoPrint",readStatus:"ステータスの読み取り",readStatusDescription:"プリンターのステータスとキューを表示",manageQueue:"キューの管理",manageQueueDescription:"印刷キューへのアイテムの追加と削除",controlPrinter:"プリンターの制御",controlPrinterDescription:"印刷の一時停止、再開、停止",unnamedKey:"名前なしキー",lastUsed:"最終使用:",read:"読み取り",control:"制御",createFirstKey:"最初のキーを作成",webhookEndpoints:"Webhookエンドポイント",webhookApiKeyHint:"X-API-KeyヘッダーでAPIキーを使用してください。",webhook:{getAllStatus:"全プリンターステータスを取得",getSpecificStatus:"特定のプリンターステータスを取得",addToQueue:"印刷キューに追加",pausePrint:"印刷を一時停止",resumePrint:"印刷を再開",stopPrint:"印刷を停止"},apiBrowser:"APIブラウザ",apiBrowserDescription:"すべての利用可能なAPIエンドポイントを探索してテストします。",apiKeyForTesting:"テスト用APIキー",apiKeyPlaceholder:"CallMeBot APIキー",apiKeyHint:"このキーはX-API-Keyヘッダーとしてリクエストに送信されます。",deleteApiKeyTitle:"APIキーを削除",deleteApiKeyMessage:"このAPIキーを削除してもよろしいですか?このキーを使用しているすべての連携が動作しなくなります。",deleteKey:"キーを削除",amsDisplayThresholds:"AMS表示しきい値",amsThresholdsDescription:"AMS湿度と温度インジケーターの色しきい値を設定します。",humidity:"湿度",goodGreen:"良好(緑)≤",fairOrange:"普通(オレンジ)≤",aboveFairBad:"普通のしきい値以上は赤(悪い)で表示",fairAlsoDryingThreshold:"このしきい値は自動乾燥のトリガーにも使用されます",temperature:"温度",goodBlue:"良好(青)≤",aboveFairHot:"普通のしきい値以上は赤(高温)で表示",historyRetention:"履歴の保持",keepSensorHistory:"センサー履歴の保持期間",historyRetentionDescription:"古い湿度と温度データは自動的に削除されます",defaultPrintOptions:"デフォルト印刷オプション",defaultPrintOptionsDescription:"新しい印刷のデフォルト値を設定します。印刷ダイアログで個別に変更できます。",defaultBedLevelling:"ベッドレベリング",defaultBedLevellingDesc:"印刷前にベッドを自動レベリング",defaultFlowCali:"フローキャリブレーション",defaultFlowCaliDesc:"押出フローのキャリブレーション",defaultVibrationCali:"振動キャリブレーション",defaultVibrationCaliDesc:"リンギングアーティファクトを低減",defaultLayerInspect:"第1層検査",defaultLayerInspectDesc:"AIによる第1層の検査",defaultTimelapse:"タイムラプス",defaultTimelapseDesc:"タイムラプス動画を記録",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"プレートクリア確認",requirePlateClear:"プレートクリア確認を必須にする",requirePlateClearDescription:"有効にすると、スケジューラーは完了したプリンターでキューの印刷を開始する前に、プリンターごとのプレートクリア確認を待ちます。プレートを物理的に確認するファームワークフローでは無効にしてください。",gcodeInjection:"G-codeインジェクション",gcodeInjectionDescription:"Farmloop、SwapMod、AutoClear、Printflow 3Dなどの自動印刷システム用に、印刷の開始と終了時にカスタムG-codeを挿入します。スニペットはプリンターモデルごとに設定し、キューアイテム��「G-codeを挿入」を有効にすると適用されます。",gcodeInjectionNoPrinters:"プリンターが見つかりません。G-codeスニペットを設定するにはプリンターを追加してください。",gcodeStartLabel:"開始G-code",gcodeEndLabel:"終了G-code",gcodeStartPlaceholder:"印刷開始前に挿入されるG-code...",gcodeEndPlaceholder:"印刷終了後に追加されるG-code...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"自動乾燥",queueDryingDescription:"キュー印刷の合間にプリンターがアイドル状態の時、AMSフィラメントを自動的に乾燥します。上記の湿度しきい値を使用します。",queueDryingEnabled:"自動乾燥を有効にする",queueDryingEnabledDescription:"プリンターがアイドル状態で湿度がしきい値を超えた場合、AMS乾燥を自動的に開始",queueDryingBlock:"乾燥完了まで待機",queueDryingBlockDescription:"乾燥が完了するまで印刷キューをブロックします。オフの場合、印刷が優先されます。",ambientDryingEnabled:"常時乾燥",ambientDryingEnabledDescription:"キューに関係なく、アイドル状態のプリンターで湿度がしきい値を超えた場合に自動的にフィラメントを乾燥。",dryingPresets:"乾燥プリセット",dryingPresetsDescription:"フィラメントタイプごとの温度と時間。AMS 2 Proは低温、AMS-HTは高温に対応。",dryingFilament:"フィラメント",printModal:"印刷ダイアログ",expandCustomMapping:"カスタムマッピングをデフォルトで展開",expandCustomMappingDescription:"複数プリンターに印刷する際、プリンターごとのAMSマッピングを展開表示",authentication:"認証",authEnabledDescription:"ユーザー認証でインスタンスが保護されています",authDisabledDescription:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",authDisabledMessage:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",enableAuthentication:"認証を有効にする",currentUser:"現在のユーザー",changePassword:"パスワードを変更",admin:"管理者",users:"ユーザー",addUser:"ユーザーを追加",groups:"グループ",addGroup:"グループを追加",system:"システム",noDescription:"説明なし",userCount:"{{count}}人のユーザー",permissionCount:"{{count}}件の権限",createUser:"ユーザーを作成",username:"ユーザー名",enterUsername:"ユーザー名を入力",password:"パスワード",enterPassword:"パスワードを入力(6文字以上)",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",viewReleaseOnGitHub:"GitHubでリリースを表示",turnAllPlugsOn:"すべてのプラグをオン",turnAllPlugsOff:"すべてのプラグをオフ",clearNotificationLogs:"通知ログをクリア",clearLogsMessage:"30日以上前のすべての通知ログを完全に削除します。この操作は元に戻せません。",clearLogs:"通知ログを削除",resetUiPreferences:"UI設定をリセット",resetUiPreferencesMessage:"すべてのUI設定をデフォルトにリセットします:サイドバー順序、テーマ、ダッシュボードレイアウト、表示モード、ソート設定。プリンター、アーカイブ、サーバー設定は影響を受けません。クリア後にページがリロードされます。",resetPreferences:"設定をリセット",deleteGroupTitle:"グループを削除",deleteGroupMessage:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。",deleteGroup:"グループを削除",disableAuthenticationTitle:"認証を無効化",disableAuthenticationMessage:"認証を無効にしますか?Bambuddyインスタンスにログインなしでアクセスできるようになります。ユーザーはデータベースに残りますが、認証は無効になります。",disableAuthentication:"認証を無効化",configureBambuddy:"Bambuddyを設定",systemDefault:"システムデフォルト",archiveSettings:"アーカイブ設定",newWindow:"新しいウィンドウ",embeddedOverlay:"埋め込みオーバーレイ",preferredSlicer:"優先スライサー",preferredSlicerDescription:"ファイルを開くスライサーアプリケーションを選択",externalCameras:"外部カメラ",costTracking:"コスト追跡",printsOnly:"印刷のみ",totalConsumption:"総消費量",dataManagement:"データ管理",storageUsage:"ストレージ使用量",storageUsageDescription:"カテゴリ別のデータ使用量の内訳",storageUsageTotal:"合計",storageUsageErrors:"エラー",storageUsageOtherBreakdown:"その他(静的アセット、スクリプト、設定ファイルを含む)",storageUsageSystem:"システム",storageUsageData:"データ",storageUsageUnavailable:"ストレージ使用量情報は利用できません",clearNotificationLogsDescription:"30日以上前の通知ログを削除",resetUiPreferencesDescription:"サイドバー順序、テーマ、表示モード、レイアウト設定をリセット。プリンター、アーカイブ、設定は影響を受けません。",enableHomeAssistant:"Home Assistantを有効化",enableMqtt:"MQTTを有効化",useTls:"TLSを使用",enableMetricsEndpoint:"メトリクスエンドポイントを有効化",availableMetrics:"利用可能なメトリクス",editUser:"ユーザーを編集",deleteUserTitle:"ユーザーを削除",groupName:"グループ名",leaveEmptyForAnonymous:"匿名の場合は空のまま",leaveEmptyForNoAuth:"認証なしの場合は空のまま",enterNewPassword:"新しいパスワードを入力",confirmNewPassword:"新しいパスワードを確認",enterGroupName:"グループ名を入力",enterDescriptionOptional:"説明を入力(任意)",enterCurrentPassword:"現在のパスワードを入力",enterNewPasswordMin6:"新しいパスワードを入力(6文字以上)",toast:{keyCopied:"キーをクリップボードにコピーしました",copyFailed:"キーのコピーに失敗しました",keyAddedToBrowser:"キーをAPIブラウザに追加しました",clearLogsFailed:"ログの削除に失敗しました",uiPreferencesReset:"UI設定をリセットしました。更新中...",authDisabled:"認証を無効にしました",authDisableFailed:"認証の無効化に失敗しました",apiKeyCreated:"APIキーを作成しました",apiKeyDeleted:"APIキーを削除しました",userCreated:"ユーザーが正常に作成されました",userUpdated:"ユーザーが正常に更新されました",userDeleted:"ユーザーが正常に削除されました",groupCreated:"グループを作成しました",groupUpdated:"グループを更新しました",groupDeleted:"グループを削除しました",fillRequiredFields:"必須項目をすべて入力してください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です",enterGroupName:"グループ名を入力",settingsSaved:"設定を保存しました",cameraSettingsSaved:"カメラ設定を保存しました",enterCameraUrl:"カメラURLを入力してください",passwordChanged:"パスワードが正常に変更されました",connectionFailed:"接続失敗",testFailed:"テスト通知の送信に失敗しました",cameraConnected:"カメラ接続{{resolution}}"},testConnection:"接続テスト",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:"デフォルトにリセット",selectedCount:"{{count}}件選択中",deleteSelected:"選択を削除",bulkDeleteConfirm:"{{count}}件のエントリーを削除してもよろしいですか?",bulkDeleted:"{{count}}件のエントリーを削除しました",bulkDeleteFailed:"エントリーの削除に失敗しました"},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形式",selectedCount:"{{count}}件選択中",deleteSelected:"選択を削除",bulkDeleteConfirm:"{{count}}件のカラーを削除してもよろしいですか?",bulkDeleted:"{{count}}件のカラーを削除しました",bulkDeleteFailed:"カラーの削除に失敗しました"},dateFormat:"日付形式",dateFormatUs:"US (MM/DD/YYYY)",dateFormatEu:"EU (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"時刻形式",timeFormat12:"12時間制 (3:30 PM)",timeFormat24:"24時間制 (15:30)",defaultPrinter:"デフォルトプリンター",defaultPrinterDescription:"アップロード、再印刷、その他の操作でこのプリンターを事前選択します。",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"サイドバーの項目をドラッグして並べ替え。ここでデフォルトの順序にリセット。",setDefault:"デフォルト設定",sidebarOrderSetDefaultHint:"デフォルト設定は、まだカスタマイズしていないユーザーに現在のメニュー順序を適用します。",sidebarDefaultSet:"デフォルトメニュー順序を設定しました。",sidebarDefaultCleared:"デフォルトメニュー順序をクリアしました。",sidebarDefaultFailed:"デフォルトメニュー順序の設定に失敗しました。",reset:"リセット",darkMode:"ダークモード",lightMode:"ライトモード",active:"(アクティブ)",background:"背景",accent:"アクセント",style:"スタイル",bgNeutral:"ニュートラル",bgWarm:"ウォーム",bgCool:"クール",bgOled:"OLEDブラック",bgSlate:"スレートブルー",bgForest:"フォレストグリーン",accentGreen:"グリーン",accentTeal:"ティール",accentBlue:"ブルー",accentOrange:"オレンジ",accentPurple:"パープル",accentRed:"レッド",styleClassic:"クラシック",styleGlow:"グロー",styleVibrant:"ビビッド",themeToggleHint:"サイドバーの太陽/月アイコンでダークモードとライトモードを切り替えます。",autoArchivePrints:"印刷を自動アーカイブ",autoArchiveDescription:"印刷完了時に3MFファイルを自動保存",saveThumbnailsDescription:"3MFファイルからプレビュー画像を抽出して保存",captureFinishPhotoDescription:"印刷完了時にプリンターカメラから写真を撮影",ffmpegNotInstalled:"ffmpegがインストールされていません",ffmpegRequired:"カメラ撮影にはffmpegが必要です。<brew>brew install ffmpeg</brew>(macOS)または<apt>apt install ffmpeg</apt>(Linux)でインストールしてください。",camera:"カメラ",cameraViewMode:"カメラ表示モード",cameraOverlayDescription:"メイン画面上にリサイズ可能なオーバーレイでカメラを表示",cameraWindowDescription:"別のブラウザウィンドウでカメラを表示",externalCamerasDescription:"内蔵プリンターカメラの代わりに外部カメラを設定。MJPEGストリーム、RTSP、HTTPスナップショット、USBカメラ(V4L2)をサポート。有効にすると、ライブビューと完了写真に外部カメラが使用されます。",cameraPlaceholderUsb:"デバイスパス (/dev/video0)",cameraPlaceholderUrl:"カメラURL (rtsp://... または http://...)",cameraTypeMjpeg:"MJPEGストリーム",cameraTypeRtsp:"RTSPストリーム",cameraTypeSnapshot:"HTTPスナップショット",cameraTypeUsb:"USBカメラ (V4L2)",cameraRotation:"回転",test:"テスト",connected:"接続済み",disconnected:"未接続",currency:"通貨",defaultFilamentCost:"デフォルトフィラメントコスト(kg単価)",electricityCost:"電気料金(kWh単価)",energyDisplayMode:"エネルギー表示モード",energyModePrintDescription:"ダッシュボードに印刷中の消費エネルギーの合計を表示",energyModeTotalDescription:"ダッシュボードにスマートプラグの累計エネルギーを表示",fileManager:"ファイルマネージャー",createArchiveEntry:"印刷時にアーカイブエントリを作成",createArchiveEntryDescription:"ファイルマネージャーから印刷時に、オプションでアーカイブエントリを作成",lowDiskSpaceWarning:"ディスク容量不足の警告",lowDiskSpaceDescription:"空きディスク容量がこのしきい値を下回った場合に警告を表示",printerFirmware:"プリンターファームウェア",checkFirmwareDescription:"Bambu Labのプリンターファームウェア更新を確認",bambuddySoftware:"Bambuddyソフトウェア",autoCheckDescription:"起動時に自動的に新しいバージョンを確認",checkNow:"今すぐ確認",updateAvailableVersion:"アップデート利用可能: v{{version}}",releaseNotes:"リリースノート",updateViaDocker:"Docker Composeでアップデート:",installUpdate:"アップデートをインストール",latestVersionRunning:"最新バージョンを使用しています",failedToCheckUpdates:"アップデートの確認に失敗しました: {{error}}",backupRestore:"バックアップと復元",backupRestoreDescription:"設定のエクスポート/インポートとGitHubバックアップの設定",goToBackup:"バックアップへ",externalUrl:"外部URL",externalUrlDescription:"Bambuddyがアクセス可能な外部URL。通知画像や外部連携に使用されます。",bambuddyUrl:"Bambuddy URL",externalUrlHint:"プロトコルとポートを含めてください(例: http://192.168.1.100:8000)",ftpRetry:"FTPリトライ",ftpRetryDescription:"プリンターのWi-Fiが不安定な場合にFTP操作をリトライ。3MFダウンロード、印刷アップロード、タイムラプスダウンロード、ファームウェア更新に適用。",autoRetryDescription:"失敗したFTP操作を自動的にリトライ",retryAttempts:"リトライ回数",retryDelay:"リトライ遅延",connectionTimeout:"接続タイムアウト",time_one:"{{count}}回",time_other:"{{count}}回",second_one:"{{count}}秒",second_other:"{{count}}秒",nSeconds:"{{count}}秒",increaseForWeakWifi:"Wi-Fiが弱いプリンター用に増やしてください",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Home Assistantに接続してHA REST API経由でスマートプラグを制御。switch、light、input_boolean、scriptエンティティをサポート。",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"長期アクセストークン",haTokenHint:"HAでトークンを作成: プロフィール → 長期アクセストークン → トークンを作成",connectionSuccessful:"接続成功",connectionFailed:"接続失敗",haConnectionSuccess:"Home Assistantへの接続に成功しました。",haConnectionFailed:"Home Assistantへの接続に失敗しました。",mqttPublishing:"MQTTパブリッシュ",mqttDescription:"Node-RED、Home Assistant、その他の自動化システムとの統合のため、外部MQTTブローカーにBamBuddyイベントをパブリッシュ。",mqttEnableDescription:"外部MQTTブローカーにイベントをパブリッシュ",brokerHostname:"ブローカーホスト名",port:"ポート",usernameOptional:"ユーザー名(オプション)",passwordOptional:"パスワード(オプション)",topicPrefix:"トピックプレフィックス",topicPrefixHint:"トピック形式: {{prefix}}/printers/<serial>/status 等",prometheusMetrics:"Prometheusメトリクス",prometheusEndpointDescription:"Prometheus/Grafanaモニタリング用に<code>/api/v1/metrics</code>でプリンターメトリクスを公開。",bearerTokenOptional:"Bearerトークン(オプション)",bearerTokenHint:"設定時、リクエストに<code>Authorization: Bearer <token></code>が必要",metricsConnectionStatus:"接続状態",metricsPrinterState:"プリンター状態(idle/printing等)",metricsPrintProgress:"印刷進捗 0-100%",metricsBedTemp:"ベッド温度",metricsNozzleTemp:"ノズル温度",metricsPrintsTotal:"結果別の総印刷数",metricsMore:"...その他(レイヤー、ファン、キュー、フィラメント使用量)",smartPlugsDescription:"スマートプラグ(TasmotaまたはHome Assistant)を接続して、電源制御の自動化とプリンターのエネルギー使用量を追跡。",allOn:"すべてオン",allOff:"すべてオフ",addSmartPlug:"スマートプラグを追加",energySummary:"エネルギー概要",currentPower:"現在の消費電力",plugsOnline:"{{reachable}}/{{total}}プラグオンライン",today:"今日",yesterday:"昨日",total:"合計",enablePlugsForSummary:"プラグを有効にしてエネルギー概要を表示",addNotificationProvider:"追加",systemBadge:"(システム)",creating:"作成中...",changing:"変更中...",deleteUserAndItems:"ユーザーとそのアイテムを削除",deleteUserKeepItems:"ユーザーを削除、アイテムは保持(オーナーなしになります)",ok:"OK",twoFa:{totpTitle:"認証アプリ (TOTP)",totpDesc:"Google Authenticator、Aegis、Authyなどのアプリを使用します。",emailOtpTitle:"メールOTP",emailOtpDesc:"ログイン時に{{email}}にワンタイムコードを送信します。",emailOtpNoEmail:"この方法を有効にするには、アカウントにメールアドレスを追加してください。",addEmailFirst:"アカウントにメールアドレスがありません。管理者に追加を依頼してください。",setupTotp:"認証アプリを設定",setupAuthApp:"認証アプリを設定",setupInstructions:"認証アプリでQRコードをスキャンし、コードで確認してください。",manualEntry:"スキャンできない場合は、このシークレットを手動で入力してください:",scannedContinue:"コードをスキャンしました — 続ける",enterCodeToConfirm:"認証アプリの6桁のコードを入力して設定を確認してください。",activate:"有効化",disableTotp:"認証アプリを無効化",disableConfirmHint:"認証アプリを無効にするには、有効なTOTPコードまたはバックアップコードを入力してください。",totpDisabled:"認証アプリが無効化されました。",emailOtpEnabled:"メールOTPが有効化されました。",emailOtpDisabled:"メールOTPが無効化されました。",smtpRequired:"先にSMTP設定を構成してテストしてください。",invalidCode:"無効なコードです。もう一度お試しください。",enableEmailOtp:"メールOTPを有効化",disableEmailOtp:"メールOTPを無効化",emailSetupEnterCode:"確認コードがメールアドレスに送信されました。このメールボックスを所有していることを確認するために、以下に入力してください。",verifyAndEnable:"確認して有効化",emailDisablePasswordHint:"メールOTPの無効化を確認するには、アカウントのパスワードを入力してください。",passwordPlaceholder:"パスワードを入力してください",backupCodesTitle:"バックアップコードを保存",backupCodesWarning:"これらのコードを安全な場所に保存してください。各コードは一度しか使用できません。",backupCodesRemaining:"バックアップコード残り{{count}}個",savedCodes:"コードを保存しました",regenBackup:"バックアップコードを再生成",regenBackupHint:"現在のTOTPコードを入力して10個の新しいバックアップコードを生成します。",newBackupCodes:"新しいバックアップコード",linkedAccounts:"リンクされたSSOアカウント",linkedAccountsDesc:"これらの外部IDプロバイダーがあなたのアカウントにリンクされています。",oidcUnlinked:"アカウントのリンクを解除しました。"},oidc:{title:"SSO / OIDCプロバイダー",desc:"シングルサインオン用のOpenID Connectプロバイダーを設定します。",addProvider:"プロバイダーを追加",newProvider:"新しいプロバイダー",empty:"OIDCプロバイダーがまだ設定されていません。",created:"プロバイダーが作成されました。",updated:"プロバイダーが更新されました。",deleted:"プロバイダーが削除されました。",deleteTitle:"プロバイダーを削除",deleteMessage:'"{{name}}"を削除しますか?リンクされたすべてのユーザーアカウントが切断されます。',form:{name:"表示名",issuerUrl:"発行者URL",clientId:"クライアントID",clientSecret:"クライアントシークレット",scopes:"スコープ",iconUrl:"アイコンURL (任意)",enabled:"有効",autoCreate:"ユーザーを自動作成",autoCreateDesc:"初回ログイン時にローカルアカウントを自動的に作成します。",autoLink:"既存アカウントを自動リンク",autoLinkDesc:"初回ログイン時にメールアドレスで既存のローカルアカウントにリンクします。",secretHint:"空白のままで現在のものを維持",secretPlaceholder:"新しいシークレット"}}},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:"データの読み込みに失敗しました"},hmsErrors:{title:"エラー - {{name}}",noErrors:"エラーなし",viewOnWiki:"Bambu Lab Wikiで表示",clearInstructions:"プリンターでエラーをクリアするとここからも消えます。",clearErrors:"エラーをクリア",clearSuccess:"HMSエラーをクリアしました",clearFailed:"HMSエラーのクリアに失敗しました"},mqttDebug:{title:"MQTTデバッグログ",searchPlaceholder:"トピックまたはペイロードで検索...",noMessages:"まだメッセージが記録されていません",startLoggingHint:"「ログ開始」をクリックしてMQTTメッセージのキャプチャを開始",noMessagesMatch:"フィルターに一致するメッセージがありません",adjustFilterHint:"検索条件やフィルター条件を調整してみてください",incoming:"受信",outgoing:"送信",loggingStopped:"ログ記録停止",loggingActive:"ログ記録中 - メッセージは自動更新されます",startLogging:"ログ記録を開始",stopLogging:"ログ停止",clearLog:"ログをクリア",topic:"トピック",timestamp:"タイムスタンプ",direction:"方向",all:"すべて"},printerFiles:{title:"ファイル管理",storageUsed:"使用中:",storageFree:"空き:",filterPlaceholder:"ファイルを検索...",deleteButton:"削除",deleteFiles:"{{count}}件のファイルを削除",deleteFileConfirm:"このファイルを削除しますか?",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?元に戻せません。",noFiles:"このディレクトリにファイルがありません",loadingFiles:"ファイルを読み込み中...",failedToLoad:"ファイルの読み込みに失敗しました",toast:{filesDeleted:"{{count}}件のファイルを削除しました",deleteFailed:"削除に失敗: {{error}}"}},confirm:{delete:"削除しますか?",unsavedChanges:"保存されていない変更があります。このページを離れますか?",clearQueue:"キューをクリアしますか?"},login:{title:"Bambuddy ログイン",subtitle:"アカウントにサインイン",username:"ユーザー名",usernamePlaceholder:"ユーザー名を入力",usernameOrEmail:"ユーザー名またはメール",usernameOrEmailPlaceholder:"ユーザー名または @ メール",password:"パスワード",passwordPlaceholder:"パスワードを入力",signIn:"サインイン",signingIn:"ログイン中...",forgotPassword:"パスワードをお忘れですか?",loginSuccess:"ログインしました",loginFailed:"ログインに失敗しました",enterCredentials:"ユーザー名とパスワードを入力してください",enterEmail:"メールアドレスを入力してください",oidcLoginFailed:"OIDCログインに失敗しました",oidcErrors:{providerError:"IDプロバイダーがエラーを返しました",missingParameters:"OIDCコールバックに必須パラメーターがありません",invalidState:"OIDCの状態が無効か、すでに使用されています",stateExpired:"OIDCログインセッションが期限切れです。もう一度お試しください",providerNotFound:"OIDCプロバイダーが見つかりません",discoveryFailed:"OIDCディスカバリードキュメントの取得に失敗しました",invalidDiscovery:"OIDCディスカバリードキュメントが無効です",networkError:"OIDCトークン交換中にネットワークエラーが発生しました",badResponse:"OIDCトークン交換中に予期しない応答を受信しました",noIdToken:"OIDCプロバイダーがIDトークンを返しませんでした",validationFailed:"OIDCトークンの検証に失敗しました",nonceMismatch:"OIDCノンスが一致しません。リプレイ攻撃の可能性があります",missingSubClaim:"OIDCトークンにsubクレームがありません",noLinkedAccount:"このOIDCアイデンティティに関連付けられたローカルアカウントがありません",accountInactive:"あなたのアカウントは無効です",userResolutionFailed:"アカウントを解決できませんでした",internalError:"OIDCログイン中に内部エラーが発生しました",tokenExchangeFailed:"OIDCトークン交換に失敗しました"},forgotPasswordTitle:"パスワードを忘れた場合",forgotPasswordMessage:"パスワードを忘れた場合は、システム管理者に連絡してリセットしてもらってください。",forgotPasswordEmailMessage:"メールアドレスを入力すると、新しいパスワードを送信します。",emailAddress:"メールアドレス",emailPlaceholder:"your.email@example.com",cancel:"キャンセル",sending:"送信中...",sendResetEmail:"リセットメールを送信",howToReset:"パスワードのリセット方法:",resetStep1:"Bambuddy管理者に連絡",resetStep2:"ユーザー管理でパスワードリセットを依頼",resetStep3:"管理者が新しい仮パスワードを設定",resetStep4:"新しいパスワードでログインし、設定で変更",gotIt:"了解",twoFA:{title:"二段階認証",subtitle:"アカウントは二段階認証で保護されています。確認コードを入力してください。",methodAuthenticator:"認証アプリ",methodEmail:"メール認証",methodBackup:"バックアップコード",instructionsTotp:"認証アプリを開いて、Bambuddy用の6桁のコードを入力してください。",instructionsEmail:"6桁の確認コードをメールアドレスに送信しました。有効期限は10分です。",instructionsEmailNotSent:"下のボタンをクリックして、メールで確認コードを受け取ってください。",instructionsBackup:"8文字のバックアップコードをいずれか1つ入力してください。各コードは1回のみ使用可能です。",sendCodeButton:"メールでコードを送信する",sendingCode:"送信中...",resendCode:"コードを再送する",codeLabel:"確認コード",backupCodeLabel:"バックアップコード",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"確認する",verifyingButton:"確認中...",backToLogin:"← ログイン画面に戻る",orContinueWith:"または以下でログイン",signInWith:"{{provider}}でログイン",enterCode:"確認コードを入力してください",sendCodeFailed:"確認コードの送信に失敗しました",invalidCode:"無効なコードです。もう一度お試しください。"}},setup:{title:"Bambuddy セットアップ",subtitle:"Bambuddyインスタンスの認証を設定",enableAuth:"認証を有効化",adminAccount:"管理者アカウント",adminAccountDesc:"既に管理者ユーザーが存在する場合、既存の管理者アカウントを使用して認証が有効化されます。既存の管理者を使用する場合は下のフィールドを空のままにするか、新しい認証情報を入力して新しい管理者ユーザーを作成してください。",adminUsername:"管理者ユーザー名",adminPassword:"管理者パスワード",optionalIfAdminExists:"(管理者ユーザーが存在する場合は任意)",adminUsernamePlaceholder:"管理者ユーザー名を入力(任意)",adminPasswordPlaceholder:"管理者パスワードを入力(任意)",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",settingUp:"セットアップ中...",completeSetup:"セットアップを完了",toast:{authEnabledAdminCreated:"認証が有効になり、管理者ユーザーが作成されました",authEnabledExistingAdmins:"既存の管理者ユーザーを使用して認証が有効になりました",setupCompleted:"セットアップが完了しました",enterBothCredentials:"管理者のユーザー名とパスワードの両方を入力するか、既存の管理者を使用する場合は両方を空にしてください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です"}},changePassword:{title:"パスワードを変更",currentPassword:"現在のパスワード",currentPasswordPlaceholder:"現在のパスワードを入力",newPassword:"新しいパスワード",newPasswordPlaceholder:"新しいパスワードを入力(6文字以上)",confirmPassword:"新しいパスワード確認",confirmPasswordPlaceholder:"パスワードを確認",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です",changing:"変更中...",success:"パスワードを変更しました",failed:"パスワードの変更に失敗しました"},plateAlert:{title:"印刷が一時停止されました!",message:"ビルドプレート上にオブジェクトが検出されました。印刷が自動的に一時停止されました。プレートをクリアして印刷を再開してください。",understand:"了解"},camera:{title:"カメラビュー",invalidPrinterId:"無効なプリンターID",live:"ライブ",snapshot:"スナップショット",restartStream:"ストリームを再開",refreshSnapshot:"スナップショットを更新",fullscreen:"フルスクリーン",exitFullscreen:"フルスクリーンを終了",connectingToCamera:"カメラに接続中...",capturingSnapshot:"スナップショットを撮影中...",connectionLost:"接続が切断されました",connectionFailed:"カメラ接続に失敗しました",reconnecting:"{{countdown}}秒後に再接続... (試行 {{attempt}}/{{max}})",reconnectNow:"今すぐ再接続",cameraUnavailable:"カメラが利用できません",cameraUnavailableDesc:"プリンターの電源がオンで接続されていることを確認してください。",noCamera:"カメラがありません",retry:"再試行",cameraStream:"カメラストリーム",zoomOut:"ズームアウト",zoomIn:"ズームイン",resetZoom:"ズームをリセット",recording:"録画中",startRecording:"録画開始",stopRecording:"録画停止",chamberLight:"チャンバーライト切替"},groups:{title:"グループ管理",subtitle:"アクセス制御の権限グループを管理",backToSettings:"設定に戻る",createGroup:"グループを作成",noPermission:"このページにアクセスする権限がありません。",system:"システム",noDescription:"説明なし",usersCount:"{{count}}人のユーザー",permissionsCount:"{{count}}個の権限",edit:"編集",delete:"削除",toast:{created:"グループを作成しました",updated:"グループを更新しました",deleted:"アーカイブを削除しました",enterGroupName:"グループ名を入力"},modal:{editGroup:"グループを編集",createGroup:"グループを作成",cancel:"キャンセル",saving:"保存中...",creating:"作成中...",saveChanges:"変更を保存"},form:{groupName:"グループ名",groupNamePlaceholder:"グループ名を入力",systemGroupWarning:"システムグループ名は変更できません",description:"説明",descriptionPlaceholder:"説明を入力(任意)",permissions:"権限"},deleteModal:{title:"グループを削除",message:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。",confirm:"確認"},editor:{title:"グループを編集",createTitle:"グループを作成",search:"権限を検索...",selectAll:"すべて選択",clearAll:"すべて解除",permissionsSelected:"{{count}}件選択",noResults:"検索に一致する権限がありません"}},users:{title:"ユーザー管理",subtitle:"ユーザーとBambuddyインスタンスへのアクセスを管理",backToSettings:"設定に戻る",createUser:"ユーザーを作成",noPermission:"このページにアクセスする権限がありません。",admin:"管理者",noGroups:"グループなし",active:"アクティブ",inactive:"非アクティブ",edit:"編集",delete:"削除",system:"システム",noGroupsAvailable:"利用可能なグループがありません",table:{username:"ユーザー名",groups:"グループ",status:"ステータス",actions:"アクション"},toast:{created:"ユーザーを作成しました",updated:"ユーザーを更新しました",deleted:"アーカイブを削除しました",fillRequired:"必須項目をすべて入力してください",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です"},modal:{createUser:"ユーザーを作成",editUser:"ユーザーを編集",cancel:"キャンセル",creating:"作成中...",saving:"保存中...",saveChanges:"変更を保存",advancedAuthSubtitle:"高度な認証を使用"},form:{username:"ユーザー名",usernamePlaceholder:"ユーザー名を入力",email:"メール",emailPlaceholder:"user@example.com",password:"パスワード",passwordPlaceholder:"パスワードを入力",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",newPasswordPlaceholder:"新しいパスワードを入力",confirmNewPasswordPlaceholder:"新しいパスワードを確認",leaveBlankToKeep:"(現在のパスワードを維持する場合は空白)",groups:"グループ",optional:"オプション",autoGeneratedPassword:"安全なパスワードが自動的に生成され、ユーザーにメールで送信されます。",passwordManagedByAdvancedAuth:"パスワードは高度な認証によって管理されています。「パスワードのリセット」を使用して、メールで新しいパスワードをユーザーに送信してください。",resetPassword:"パスワードのリセット",resettingPassword:"パスワードをリセット中..."},deleteModal:{title:"ユーザーを削除",message:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。",confirm:"ユーザーを削除"}},streamOverlay:{title:"ストリームオーバーレイ",invalidPrinterId:"無効なプリンターID",cameraStream:"カメラストリーム",progress:"進捗",eta:"予想時間 {{minutes}} 分",printerIdle:"プリンター待機中",printerOffline:"プリンターオフライン",status:{printing:"印刷中",paused:"一時停止",finished:"完了",failed:"失敗",idle:"待機中",unknown:"不明"}},profiles:{title:"フィラメントプロファイル",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:"プリセットを更新しました"}},connectedAs:"接続中:",logout:"ログアウト",noLogoutPermission:"ログアウトする権限がありません",failedToLoad:"ファイルの読み込みに失敗しました",retry:"リトライ",time:{justNow:"たった今",minsAgo:"{{count}}分前",hoursAgo:"{{count}}時間前",daysAgo:"{{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:"戻る",loginButton:"ログイン",verifyButton:"認証",setTokenButton:"トークンを設定",useToken:"アクセストークンを使用",useEmail:"メールでログイン",toast:{loggedIn:"ログインしました",codeSent:"メールに認証コードを送信しました",enterTotp:"認証アプリのコードを入力してください",tokenSet:"トークンを設定しました"}},presets:{myPreset:"マイプリセット(編集可能)",duplicate:"複製",editable:"編集可能",failedToLoadDetails:"プリセットの詳細を読み込めませんでした",deleteConfirm:"このプロファイルを削除しますか?",deleteWarning:"「{{name}}」をBambu Cloudから完全に削除します。元に戻せません。",noDuplicatePermission:"プリセットを複製する権限がありません",noEditPermission:"プリセットを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",types:{filament:"フィラメント",printer:"プリンター",process:"プロセス"},toast:{deleted:"アーカイブを削除しました",created:"プリセットを作成しました",updated:"プリセットを更新しました",duplicated:"プリセットを複製しました",fieldAdded:'フィールド "{{key}}" を追加しました',exported:"プリセットをエクスポートしました"},baseLabel:"ベース: {{name}}",currentLabel:"現在: {{name}}",newPreset:"新規プリセット",editPreset:"プリセットを編集",duplicatePreset:"プリセットを複製",createNewPreset:"新しいプリセットを作成",customizeSettings:"新しいプリセットの設定をカスタマイズ",compareWithBase:"ベースプリセットと比較",compare:"比較",basePreset:"ベースプリセット",selectBasePreset:"ベースプリセットを選択...",presetName:"プリセット名",myCustomPreset:"カスタムプリセット",inheritsFrom:"継承元:",dropJsonToImport:"JSONファイルをドロップしてインポート",tabs:{common:"一般",allFields:"すべてのフィールド"},availableFields:"利用可能なフィールド",searchFieldsPlaceholder:"フィールドを検索...",noMatchingFields:"一致するフィールドがありません",allFieldsAdded:"すべてのフィールドが追加済みです",addCustomField:"カスタムフィールドを追加",yourOverrides:"オーバーライド一覧",noOverridesYet:"オーバーライドはまだありません",clickFieldsToAdd:"左のフィールドをクリックして追加",saveAsTemplate:"テンプレートとして保存",jsonTip:"ヒント: .jsonファイルをこのモーダルにドラッグ&ドロップして設定をインポート"},cloudView:{searchPlaceholder:"プリセットを検索...",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:"レイヤー",all:"すべて",myPresets:"マイプリセット",builtIn:"ビルトイン",process:"プロセス"},noTemplatesPermission:"テンプレートを管理する権限がありません",noRefreshPermission:"プロファイルを更新する権限がありません",noCreatePermission:"プロジェクトを作成する権限がありません"},templates:{title:"フィラメントプロファイル",noTemplates:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを作成してください。",createFirst:"プリセットエディタからテンプレートを作成",typeFilter:"タイプ:",deleteTitle:"テンプレートを削除",deleteWarning:"この操作は元に戻せません",deleteConfirm:"このプロファイルを削除しますか?",namePlaceholder:"テンプレート名",descriptionPlaceholder:"説明",settingsJson:"設定 (JSON)",fieldsCount:"{{count}}フィールド",shownInModals:"モーダルに表示",hiddenInModals:"モーダルで非表示",apply:"適用",toast:{deleted:"アーカイブを削除しました",updated:"テンプレートを更新しました",created:"テンプレートを作成しました",applied:"テンプレートを適用しました"}}},support:{debugLoggingActive:"デバッグログが有効です",manageLogs:"管理",collectItem7:"プリンター接続状態とファームウェアバージョン",collectItem8:"連携状態(Spoolman、MQTT、HA)",collectItem9:"ネットワークインターフェース(サブネットのみ)",collectItem10:"Pythonパッケージバージョン",collectItem11:"データベース健全性チェック",collectItem12:"Docker環境の詳細"},fileManager:{title:"ファイル管理",subtitle:"印刷ファイルの整理と管理",uploadFiles:"ファイルをアップロード",newFolder:"新しいフォルダ",folderName:"フォルダ名",folderNamePlaceholder:"例: 機能パーツ",renameFile:"ファイル名を変更",renameFolder:"フォルダ名を変更",moveFiles:"{{count}}件のファイルを移動",rootNoFolder:"ルート(フォルダなし)",current:"(現在)",linkFolder:"フォルダをリンク",linkFolderDescription:"「{{name}}」をプロジェクトまたはアーカイブにリンクしてすばやくアクセス。",project:"プロジェクト",archive:"アーカイブ",noProjectsFound:"プロジェクトが見つかりません",noArchivesFound:"アーカイブが見つかりません",unlink:"リンク解除",link:"リンク",dragDropFiles:"ファイルをここにドラッグ&ドロップ",dropFilesHere:"ここにファイルをドロップ",orClickToBrowse:"またはクリックして選択",allFileTypesSupported:"すべてのファイルタイプに対応。ZIPファイルは展開されます。",zipFilesDetected:"ZIPファイルを検出",zipExtractOptions:"ZIPファイルは展開されます。フォルダー構造の処理方法を選択:",preserveZipStructure:"ZIPのフォルダ構造を保持",createFolderFromZip:"ZIPファイル名からフォルダーを作成",stlThumbnailGeneration:"STLサムネイル生成",zipMayContainStl:"ZIPファイルにSTLファイルが含まれている場合があります。展開時にサムネイルを生成できます。",thumbnailsCanBeGenerated:"STLファイルのサムネイルを生成できます。大きなモデルは処理に時間がかかる場合があります。",generateThumbnailsForStl:"STLファイルのサムネイルを生成",threemfDetected:"3MFファイルを検出",threemfExtractionInfo:"プリンターモデル、素材、色、印刷設定は3MFファイルから自動的に抽出されます。",willBeExtracted:"• 展開予定",filesExtracted:"• {{count}}個のファイルを展開済み",uploadComplete:"アップロード完了: {{count}}個成功",uploadFailed:"アップロード失敗",zipFilesFailed:"{{count}}個のファイルが失敗",uploading:"アップロード中...",changeLink:"リンクを変更...",linkTo:"リンク先...",linkToProjectOrArchive:"プロジェクトまたはアーカイブにリンク",addToQueue:"キューに追加",schedulePrint:"印刷をスケジュール",generateThumbnail:"サムネイルを生成",generateThumbnails:"サムネイルを生成",generateThumbnailsForMissing:"サムネイルのないSTLファイルのサムネイルを生成",gridView:"グリッド表示",listView:"リスト表示",lowDiskSpaceWarning:"ディスク容量不足の警告",lowDiskSpaceDetails:"{{total}}中{{free}}の空き容量のみ。しきい値は設定で{{threshold}}GBに設定されています。",files:"ファイル",folders:"フォルダ",size:"サイズ",free:"空き:",allFiles:"すべてのファイル",wrap:"折り返し",enableTextWrapping:"テキスト折り返しを有効化",disableTextWrapping:"テキスト折り返しを無効化",dragToResizeTooltip:"ドラッグしてリサイズ、ダブルクリックでリセット",searchFiles:"ファイルを検索...",allTypes:"すべての種類",prints:"印刷回数",ascending:"昇順",descending:"降順",resultsCount:"{{total}}件中{{showing}}件",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",adding:"追加中...",loadingFiles:"ファイルを読み込み中...",folderIsEmpty:"フォルダーは空です",noFilesYet:"ファイルはまだありません",folderEmptyDescription:"ファイルをアップロードするか、このフォルダーにファイルを移動して開始しましょう。",noFilesDescription:"印刷関連ファイルの整理を始めるにはファイルをアップロードしてください。",noMatchingFiles:"一致するファイルがありません",noMatchingFilesDescription:"現在の検索またはフィルター条件に一致するファイルがありません。",clearFilters:"フィルターをクリア",printedCount:"{{count}}回印刷済み",uploadedBy:"アップロード者",deleteFolder:"フォルダを削除",deleteFile:"ファイルを削除",deleteFilesCount:"{{count}}件のファイルを削除",deleteFolderConfirm:"このフォルダを削除しますか?中のファイルもすべて削除されます。",deleteFileConfirm:"このファイルを削除しますか?",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?この操作は元に戻せません。",deleting:"削除中...",noPermissionRenameFolder:"フォルダー名を変更する権限がありません",noPermissionLinkFolder:"フォルダーをリンクする権限がありません",noPermissionDeleteFolder:"フォルダーを削除する権限がありません",noPermissionPrint:"印刷する権限がありません",noPermissionAddToQueue:"キューに追加する権限がありません",noPermissionDownload:"ファイルをダウンロードする権限がありません",noPermissionRenameFile:"このファイル名を変更する権限がありません",noPermissionGenerateThumbnail:"サムネイルを生成する権限がありません",noPermissionDeleteFile:"このファイルを削除する権限がありません",noPermissionCreateFolder:"フォルダーを作成する権限がありません",noPermissionUpload:"ファイルをアップロードする権限がありません",noPermissionMoveFiles:"ファイルを移動する権限がありません",noPermissionDeleteFiles:"ファイルを削除する権限がありません",linkExternal:"外部リンク",linkExternalFolder:"外部フォルダをリンク",linkExternalFolderDescription:"ホストディレクトリ(NAS、USB、ネットワーク共有)をファイルマネージャにマウントします。ファイルはコピーされず、元のパスから直接アクセスされます。",externalFolderNamePlaceholder:"例:NASプリント",externalPath:"ホストパス",externalPathHelp:"Dockerホスト上のディレクトリの絶対パス。コンテナにバインドマウントされている必要があります。",readOnly:"読み取り専用",readOnlyHelp:"アップロードと削除を防止",showHiddenFiles:"隠しファイルを表示(ドットファイル)",externalFolder:"外部フォルダ",scanFolder:"スキャン",toast:{folderCreated:"フォルダを作成しました",folderDeleted:"フォルダを削除しました",fileDeleted:"ファイルを削除しました",filesDeleted:"{{count}}件のファイルを削除しました",filesMoved:"ファイルを移動しました",folderLinked:"フォルダをリンクしました",folderUnlinked:"フォルダのリンクを解除しました",externalFolderLinked:"外部フォルダがリンクされスキャンされました",folderScanned:"スキャン完了:{{added}}件追加、{{removed}}件削除",addedToQueue:"{{count}}個のファイルをキューに追加しました",addedToQueuePartial:"{{added}}件追加、{{failed}}件失敗",failedToAddToQueue:"ファイルの追加に失敗: {{error}}",fileRenamed:"ファイル名を変更しました",folderRenamed:"フォルダ名を変更しました",thumbnailsGenerated:"{{count}}件のサムネイルを生成しました",thumbnailsGeneratedPartial:"{{succeeded}}件生成、{{failed}}件失敗",noStlMissingThumbnails:"サムネイルのないSTLファイルはありません",failedToGenerateThumbnails:"サムネイルの生成に失敗: {{error}}",thumbnailGenerated:"サムネイルを生成しました",failedToGenerateThumbnail:"サムネイルの生成に失敗: {{error}}"}},projects:{title:"プロジェクト",subtitle:"印刷プロジェクトを管理",newProject:"新規プロジェクト",editProject:"プロジェクトを編集",deleteProject:"プロジェクトを削除",projectName:"プロジェクト: {{name}}",description:"説明",noProjects:"プロジェクトはまだありません",noProjectsFiltered:"{{status}}のプロジェクトはありません",noProjectsFilteredHelp:"{{status}}のプロジェクトがありません。ステータスが変更されるとここに表示されます。",createFirst:"最初のプロジェクトを作成して、関連する印刷の整理、進捗管理、ビルドの管理を始めましょう。",createFirstButton:"最初のプロジェクトを作成",create:"作成",files:"ファイル",prints:"印刷",plates:"プレート",parts:"パーツ",lastModified:"最終更新日",deleteConfirm:"このプロジェクトを削除しますか?アーカイブとキューアイテムはリンク解除されますが、削除されません。",addFiles:"ファイルを追加",removeFile:"ファイルを削除",viewDetails:"詳細を表示",namePlaceholder:"プロジェクト名",descriptionPlaceholder:"プロジェクトの説明(任意)",color:"色",targetPlates:"目標プレート数",targetPlatesPlaceholder:"例: 10",targetPlatesHelp:"印刷ジョブの数",targetParts:"目標パーツ数",targetPartsPlaceholder:"例: 50",targetPartsHelp:"必要なオブジェクトの総数",tagsLabel:"タグ(カンマ区切り)",tagsPlaceholder:"カンマ区切りのタグ",dueDate:"期限",priority:"優先度",priorityLow:"低",priorityNormal:"通常",priorityHigh:"高",priorityUrgent:"緊急",statusActive:"進行中",statusCompleted:"完了",statusArchived:"アーカイブ済み",done:"完了",completed:"完了",failed:"失敗",inQueue:"キュー内",noPrintsYet:"印刷履歴なし",printJobs:"印刷ジョブ",partsPrinted:"印刷済みパーツ",failedParts:"失敗パーツ",import:"インポート",export:"エクスポート",importProject:"プロジェクトをインポート",exportAll:"すべてのプロジェクトをエクスポート",loading:"プロジェクトを読み込み中...",noEditPermission:"プロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",noCreatePermission:"プロジェクトを作成する権限がありません",noImportPermission:"プロジェクトをインポートする権限がありません",noExportPermission:"プロジェクトをエクスポートする権限がありません",toast:{created:"プロジェクトを作成しました",updated:"プロジェクトを更新しました",deleted:"アーカイブを削除しました",imported:"プロジェクトをインポートしました",multipleImported:"{{count}}件のプロジェクトをインポートしました",importFailed:"インポートに失敗しました",exported:"プロジェクトをエクスポートしました(メタデータのみ)"}},projectDetail:{notFound:"見つかりません",backToProjects:"プロジェクト一覧に戻る",export:"エクスポート",exportProject:"プロジェクトをエクスポート",noExportPermission:"プロジェクトをエクスポートする権限がありません",noEditPermission:"このプロジェクトを編集する権限がありません",partOf:"所属先",priorityLabel:"優先度",noPrints:"このプロジェクトにはまだ印刷がありません",status:{active:"進行中",completed:"完了",archived:"アーカイブ済み"},priority:{low:"低",normal:"通常",high:"高",urgent:"緊急"},dueDate:{overdue:"期限超過",today:"今日が期限",daysLeft:"残り{{count}}日"},progress:{platesProgress:"プレート進捗",partsProgress:"パーツ進捗",printJobs:"印刷ジョブ",parts:"パーツ",percentComplete:"% 完了",remaining:"残り"},stats:{printJobs:"印刷ジョブ",total:"合計",failed:"失敗",partsPrinted:"印刷済みパーツ",printTime:"印刷時間",filamentUsed:"フィラメント使用量"},cost:{title:"コスト追跡",filamentCost:"フィラメント",energy:"エネルギー",totalCost:"合計コスト",total:"合計",includesBom:"BOM含む",budget:"予算",remaining:"残り"},subProjects:{title:"サブプロジェクト ({{count}})"},notes:{title:"メモ",noEditPermission:"このプロジェクトを編集する権限がありません",placeholder:"このプロジェクトについてメモを追加...",empty:"<空>"},files:{title:"ファイル",linkFolders:"ファイルマネージャーからフォルダーをリンク",forQuickAccess:"してクイックアクセスできるようにします。",fileCount:"{{count}}ファイル",empty:"<空>",noFiles:"このフォルダにファイルはありません。",print:"今すぐ印刷",addToQueue:"キューに追加"},bom:{title:"部品表",acquired:"{{completed}}/{{total}} 取得済み",showAll:"すべて表示",hideDone:"完了を非表示",addPart:"パーツを追加",noAddPermission:"パーツを追加する権限がありません",partNamePlaceholder:"パーツ名",partName:"パーツ名",qty:"数量",price:"価格 ({{currency}})",sourcingUrlPlaceholder:"URL(任意)",remarksPlaceholder:"備考",deletePart:"パーツを削除",deleteConfirm:"「{{name}}」を削除しますか?",noUpdatePermission:"パーツを更新する権限がありません",noEditPermission:"このプロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",totalCost:"合計コスト",empty:"<空>"},timeline:{title:"アクティビティタイムライン",empty:"<空>"},template:{saveAsTemplate:"テンプレートとして保存",noCreatePermission:"プロジェクトを作成する権限がありません"},queue:{title:"印刷キュー",viewAll:"すべて表示",printing:"印刷中",queued:"キューに追加"},prints:{title:"印刷 ({{count}})"},toast:{projectUpdated:"プロジェクトを更新しました",partAdded:"パーツを追加しました",partRemoved:"パーツを削除しました",exportFailed:"エクスポートに失敗しました",projectExported:"プロジェクトがエクスポートされました",templateCreated:"プロジェクトからテンプレートを作成しました"}},system:{title:"システム情報",version:"バージョン",uptime:"稼働時間",cpuUsage:"CPU使用率",memoryUsage:"メモリ使用量",diskUsage:"ディスク使用量",networkInfo:"ネットワーク情報",logs:"ログ",debugMode:"デバッグモード",enableDebug:"デバッグログを有効化",disableDebug:"デバッグログを無効化",downloadLogs:"ログをダウンロード",clearLogs:"通知ログを削除",dockerInfo:"Docker情報",containerName:"コンテナ名",imageName:"イメージ名",platform:"プラットフォーム",architecture:"アーキテクチャ"},library:{title:"フィラメントライブラリ",addFilament:"フィラメントを追加",editFilament:"フィラメントを編集",deleteFilament:"フィラメントを削除",vendor:"メーカー",material:"素材",color:"色",kFactor:"K値",temperature:"温度",noFilaments:"ライブラリにフィラメントがありません",deleteConfirm:"このフィラメントを削除しますか?",importFromPrinter:"プリンターからインポート",exportToFile:"ファイルにエクスポート"},spoolman:{title:"Spoolman連携",enabled:"Spoolman有効",url:"Spoolman URL",connected:"接続中",disconnected:"未接続",testConnection:"接続テスト",sync:"同期",syncing:"同期中...",lastSync:"最終同期",linkToSpoolman:"Spoolmanに連携",openInSpoolman:"Spoolmanで開く",unlinkSpool:"スプールのリンクを解除",unlinkConfirmTitle:"スプールのリンクを解除しますか?",unlinkConfirmMessage:"これにより、スプールがSpoolmanから切断されます。Spoolman内のスプールデータは変更されません。",selectSpool:"スプールを選択",noUnlinkedSpools:"Spoolmanに未連携のスプールが見つかりません。",linkSuccess:"スプールをSpoolmanにリンクしました",linkFailed:"スプールのリンクに失敗しました",unlinkSuccess:"スプールをSpoolmanから解除しました",unlinkFailed:"スプールのリンク解除に失敗しました",spoolId:"スプールID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"残り",disableWeightSync:"AMS推定重量同期を無効化",disableWeightSyncDesc:"AMS推定値から残量を更新しません。AMSの割合ベースの推定よりもSpoolmanの使用量追跡を優先する場合に使用してください。新しいスプールは引き続きAMS推定値を初期重量として使用します。",reportPartialUsage:"失敗した印刷の部分使用量を報告",reportPartialUsageDesc:"印刷が失敗またはキャンセルされた場合、レイヤー進捗に基づいてその時点までの推定フィラメント使用量を報告します。"},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:"計測重量",spoolName:"スプール",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:"スプールを検索...",showAllSpools:"すべてのスプールを表示",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:"残り",weightCheck:"重量チェック",lastWeighed:"最終計量",neverWeighed:"未計量",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)",lowStockThresholdError:"しきい値は0.1から99.9の間でなければなりません",assignMismatchTitle:"材料の不一致",assignMismatchMessage:"選択したスプールの材料「{{spoolMaterial}}」は、{{location}} のトレイ材料「{{trayMaterial}}」と一致しません。割り当てますか?",assignMismatchConfirm:"強制的に割り当て",assignPartialMismatchMessage:"スプールの材料「{{spoolMaterial}}」は「{{trayMaterial}}」に似ていますが、{{location}} と完全には一致しません。続行しますか?",assignProfileMismatchMessage:"スプールのプロファイル「{{spoolProfile}}」は {{location}} のトレイプロファイル「{{trayProfile}}」と一致しません。続行しますか?"},timelapse:{title:"タイムラプス",create:"タイムラプスを作成",download:"ダウンロード",delete:"削除",preview:"プレビュー",frameRate:"フレームレート",quality:"品質",processing:"バックアップファイルを処理中...",noTimelapses:"利用可能なタイムラプスがありません"},ams:{title:"AMS",slot:"スロット",empty:"<空>",emptySlot:"空のスロット",unknown:"不明",humidity:"湿度",temperature:"温度",filamentType:"フィラメントタイプ",filamentColor:"色",remaining:"残り",history:"AMS履歴",noHistory:"メンテナンス履歴がありません",configureSlot:"フィラメントプロファイルとK値でスロットを設定",externalSpool:"外部スプール",profile:"プロファイル",kFactor:"K値",fill:"充填率",configure:"設定",used:"使用済み",remainingUnit:"残り"},printModal:{title:"印刷を開始",selectPrinter:"プリンターを選択",selectPlate:"プレートを選択",filamentMapping:"フィラメントマッピング",totalCost:"合計コスト:",slotRemainingShort:" - 残{{grams}}g",printSettings:"印刷設定",bedLeveling:"ベッドレベリング",flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",layerInspection:"第一層検査",timelapse:"タイムラプス",startPrint:"印刷を開始",addToQueue:"キューに追加",cancel:"キャンセル",noPrintersAvailable:"利用可能なプリンターがありません",printerBusy:"プリンターは使用中です",printerOffline:"プリンターはオフラインです",sameTypeDifferentColor:"同じ種類、異なる色",filamentTypeNotLoaded:"フィラメントタイプが未読み込み",openCalendar:"カレンダーを開く",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"左ノズル",rightNozzleTooltip:"右ノズル",filamentOverride:"フィラメントオーバーライド",filamentOverrideHint:"モデルベースの割り当てに使用するフィラメントをオプションで上書きします。スケジューラは元の3MF値ではなく、選択したフィラメントに基づいてマッチングします。",originalFilament:"オリジナル",overrideWith:"変更先",resetToOriginal:"オリジナルに戻す",insufficientFilamentTitle:"フィラメントが不足しています",insufficientFilamentMessage:"割り当てられたスプールの一部は、この印刷に必要な量より残量が少ないです:",insufficientFilamentLine:"{{printer}} - {{slot}}: 必要 {{required}}g、残り {{remaining}}g",printAnyway:"それでも印刷",forceColorMatch:"カラーマッチを強制",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"{{count}}台のプリンターに段階的に送信",gcodeInjection:"自動印刷G-codeを挿入"},backup:{title:"バックアップと復元",createBackup:"バックアップを作成",restoreBackup:"バックアップの復元",restoreDescription:"バックアップファイルからすべてのデータを置き換える",downloadBackup:"バックアップをダウンロード",uploadBackup:"バックアップをアップロード",lastBackup:"最終バックアップ",autoBackup:"自動バックアップ",backupNow:"今すぐバックアップ",restoreWarning:"警告: バックアップの復元は現在のすべてのデータを上書きします。",includeArchives:"アーカイブを含む",includeSettings:"設定を含む",includeProfiles:"プロファイルを含む",backupSuccess:"バックアップを作成しました",restoreSuccess:"バックアップを復元しました",backupFailed:"バックアップに失敗しました: {{error}}",restoreFailed:"復元に失敗しました",restoreNote:"復元中、仮想プリンターは停止されます",githubBackup:"GitHubバックアップ",enabled:"有効",cloudLoginRequired:"Bambu Cloudログインが必要です。GitHubバックアップを有効にするには、プロファイル → クラウドプロファイルからサインインしてください。",cloudLoginRequiredShort:"Cloudログインが必要",githubDescription:"プロファイルをプライベートGitHubリポジトリに自動的に同期し、バックアップとバージョン履歴を保持します。",repositoryUrl:"リポジトリURL",personalAccessToken:"個人アクセストークン",tokenSaved:"(保存済み)",enterNewToken:"新しいトークンを入力して更新",tokenHint:"Contents読み書き権限を持つきめ細かいトークン",branch:"ブランチ",manualOnly:"手動のみ",hourly:"毎時",daily:"毎日",weekly:"毎週",includeInBackup:"バックアップに含める",kProfiles:"Kプロファイル",kProfilesDescription:"接続されたプリンターからの圧力キャリブレーション",noPrintersConnected:"プリンターが接続されていません",printersConnected:"{{connected}}/{{total}} 接続済み",cloudProfiles:"クラウドプロファイル",cloudProfilesDescription:"Bambu Cloudからのフィラメント、プリンター、プロセスプリセット",appSettings:"アプリ設定",appSettingsDescription:"Bambuddy設定(データベース全体)",spoolInventory:"スプール在庫",spoolInventoryDescription:"フィラメントスプール、使用履歴、コスト追跡",printArchives:"印刷アーカイブ",printArchivesDescription:"印刷履歴メタデータ(gcode/3MFファイルなし)",lastBackupAt:"最終バックアップ:",noBackupsYet:"バックアップはまだありません",next:"次回:",startingBackup:"バックアップを開始しています...",test:"テスト",enableBackup:"バックアップを有効化",testConnection:"接続テスト",enterRepoUrl:"リポジトリURLを入力してください",enterRepoAndToken:"リポジトリURLとアクセストークンを入力してください",repoRequired:"リポジトリURLは必須です",tokenRequired:"アクセストークンは必須です",githubBackupEnabled:"GitHubバックアップが有効になりました",tokenUpdated:"トークンが更新されました",settingsSaved:"設定が保存されました",failedToSave:"保存に失敗しました: {{message}}",backupCompleteFiles:"バックアップ完了 - {{count}}ファイルが更新されました",backupSkippedNoChanges:"バックアップをスキップ - 変更なし",backupFailed2:"バックアップに失敗しました: {{message}}",clearedLogs:"{{count}}件のログを削除しました",failedToClearLogs:"ログの削除に失敗しました: {{message}}",history:"履歴",clear:"クリア",date:"日付",status:"ステータス",commit:"コミット",localBackup:"ローカルバックアップ",localBackupDescription:"データベース、アーカイブ、アップロード、すべてのファイルを含むBambuddyデータの完全なバックアップを作成します。",downloadBackupLabel:"バックアップをダウンロード",completeBackupZip:"完全バックアップ: データベース + 全ファイル (ZIP)",download:"ダウンロード",preparingBackup:"バックアップを準備しています...",creatingArchive:"バックアップアーカイブを作成しています...大きなアーカイブの場合、時間がかかることがあります。",downloadingFile:"バックアップファイルをダウンロードしています...",backupDownloaded:"バックアップのダウンロードが成功しました",failedToCreateBackup:"バックアップの作成に失敗しました: {{message}}",restore:"復元",restoreReplacesAll:"復元はすべてのデータを置き換えます。",restoreReplacesAllDetail:"現在のデータベースとファイルは完全に置き換えられます。復元後に再起動が必要です。",restoreConfirmTitle:"バックアップを復元",restoreConfirmMessage:'"{{filename}}"から復元してもよろしいですか?現在のデータベースとすべてのファイルが完全に置き換えられます。復元後にアプリケーションの再起動が必要です。',restoreConfirmButton:"バックアップを復元",uploadingFile:"バックアップファイルをアップロードしています...",backupRestoredRestart:"バックアップが復元されました。Bambuddyを再起動してください。",failedToRestore:"バックアップの復元に失敗しました。ファイル形式を確認してください。",reloadNow:"今すぐリロード",creatingBackup:"バックアップを作成中",restoringBackup:"バックアップを復元中",preparing:"準備中...",processing:"処理中...",doNotClosePage:"このページを閉じたり、移動しないでください。大きなバックアップの場合、この操作には数分かかることがあります。",restoring:"復元中...",restoreComplete:"復元完了",restoreFailed2:"復元失敗",importSettings:"バックアップファイルから設定をインポート",pleaseWaitRestoring:"データの復元中です。お待ちください",selectBackupFile:"クリックしてバックアップファイルを選択 (.jsonまたは.zip)",duplicateHandling:"重複処理の仕組み:",matchPrinters:"プリンター",matchPrintersBy:"シリアル番号で照合",matchSmartPlugs:"スマートプラグ",matchSmartPlugsBy:"IPアドレスで照合",matchNotificationProviders:"通知プロバイダー",matchNotificationProvidersBy:"名前で照合",matchFilaments:"フィラメント",matchFilamentsBy:"名前 + タイプ + ブランドで照合",matchArchives:"アーカイブ",matchArchivesBy:"コンテンツハッシュで照合(常にスキップ)",matchPendingUploads:"保留中のアップロード",matchPendingUploadsBy:"ファイル名で照合",matchSettingsTemplates:"設定とテンプレート",matchSettingsTemplatesBy:"常に上書き",replaceExisting:"既存のデータを置き換え",keepExisting:"既存のデータを保持",overwriteDescription:"既に存在する項目をバックアップデータで上書き",keepDescription:"まだ存在しない項目のみ復元",overwriteCaution:"注意:",overwriteWarning:"上書きすると、現在の設定がバックアップのデータで置き換えられます。プリンターのアクセスコードはセキュリティのため上書きされません。",cancel:"キャンセル",processingBackup:"バックアップファイルを処理しています...",itemsRestored:"復元済み",itemsSkipped:"スキップ済み",restored:"復元済み",skippedAlreadyExist:"スキップ(既に存在)",filesCategory:"ファイル(3MF、サムネイルなど)",andMore:"...他{{count}}件",newApiKeysGenerated:"新しいAPIキーが生成されました",keysShownOnce:"これらのキーは一度だけ表示されます。今すぐコピーしてください!",copy:"コピー",noDataFound:"バックアップファイルに復元するデータが見つかりませんでした。",close:"閉じる",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"設定",notification_providers:"通知プロバイダー",notification_templates:"通知テンプレート",smart_plugs:"スマートプラグ",printers:"プリンター",filaments:"フィラメント",maintenance_types:"メンテナンスタイプ",archives:"アーカイブ",projects:"プロジェクト",pending_uploads:"保留中のアップロード",external_links:"外部リンク",api_keys:"APIキー"}},tags:{title:"タグ",addTag:"タグを追加",editTag:"タグを編集",deleteTag:"タグを削除",tagName:"タグ名",tagColor:"タグの色",noTags:"タグがありません",deleteConfirm:"このタグを削除しますか?",manageTags:"タグを管理"},uploadModal:{title:"3MFファイルのアップロード",dragDrop:".3mfファイルをここにドラッグ&ドロップ",or:"または",browseFiles:"ファイルを参照",extractionInfo:"プリンターモデルは3MFファイルのメタデータから自動的に抽出されます。",uploaded:"アップロード済み",failed:"アップロードに失敗しました",uploading:"アップロード中...",upload:"アップロード",uploadFailed:"アップロード失敗"},editArchive:{title:"アーカイブを編集",name:"名前",namePlaceholder:"印刷名",printer:"プリンター",noPrinter:"プリンターなし",project:"プロジェクト",noProject:"プロジェクトなし",itemsPrinted:"印刷数",itemsPrintedHelp:"この印刷ジョブで製造したアイテム数",notes:"メモ",notesPlaceholder:"この印刷についてメモを追加...",externalLink:"外部リンク",externalLinkPlaceholder:"https://...",externalLinkHelp:"Printables、Thingiverse、その他のソースへのリンク",tags:"タグ",tagsPlaceholder:"タグを追加...",addMoreTags:"タグをさらに追加...",matchingTags:'"{{query}}" に一致',existingTags:"既存のタグ",clickToAdd:"(クリックして追加)",status:"ステータス",failureReason:"失敗理由",selectReason:"理由を選択...",photos:"印刷結果の写真",photosHelp:"+ をクリックして印刷結果の写真を追加",printResult:"印刷結果",saving:"保存中...",failureReasons:{adhesionFailure:"定着不良",spaghettiDetached:"スパゲッティ / 剥離",layerShift:"レイヤーシフト",cloggedNozzle:"ノズル詰まり",filamentRunout:"フィラメント切れ",warping:"反り",stringing:"糸引き",underExtrusion:"押出不足",powerFailure:"電源障害",userCancelled:"ユーザーによるキャンセル",other:"その他"},statuses:{completed:"完了",failed:"失敗",aborted:"キャンセル",printing:"印刷中"}},kProfiles:{title:"Kプロファイル",noPrintersConfigured:"プリンターが設定されていません",addPrinterInSettings:"Kプロファイルを管理するには設定でプリンターを追加してください",noActivePrinters:"アクティブなプリンターがありません",enablePrinterConnection:"Kプロファイルを表示するにはプリンター接続を有効にしてください",loadingProfiles:"Kプロファイルを読み込み中...",printerOffline:"プリンターオフライン",printerOfflineDesc:"選択したプリンターは接続されていません。電源を入れてKプロファイルを表示してください。",noMatchingProfiles:"一致するプロファイルなし",noMatchingProfilesDesc:"検索条件に一致するプロファイルがありません",noKProfiles:"Kプロファイルなし",noKProfilesDesc:"{{diameter}}mmノズル用の圧力キャリブレーションプロファイルが見つかりません",createFirstProfile:"最初のプロファイルを作成",printer:"プリンター",nozzle:"ノズル",refresh:"更新",addProfile:"K-プロファイルを追加",export:"エクスポート",import:"インポート",select:"選択",selectAll:"すべて選択",delete:"削除",searchPlaceholder:"名前またはフィラメントで検索...",allExtruders:"すべてのエクストルーダー",leftOnly:"左のみ",rightOnly:"右のみ",allFlow:"すべてのフロー",hfOnly:"HFのみ",sOnly:"Sのみ",sortName:"ソート: 名前",sortKValue:"ソート: K値",sortFilament:"ソート: フィラメント",leftExtruder:"左エクストルーダー",rightExtruder:"右エクストルーダー",modal:{addTitle:"Kプロファイルを追加",editTitle:"Kプロファイルを編集",profileName:"プロファイル名",profileNamePlaceholder:"マイPLAプロファイル",kValue:"K値",kValuePlaceholder:"0.020",kValueHelp:"一般的な範囲: PLA 0.01〜0.06、PETG 0.02〜0.10",filament:"フィラメント",selectFilament:"フィラメントを選択...",noFilamentsHelp:"フィラメントが見つかりません。Bambu Studioでまずプロファイルを作成してください。",flowType:"フロータイプ",highFlow:"ハイフロー",standard:"スタンダード",nozzleSize:"ノズルサイズ",extruder:"エクストルーダー",extruders:"エクストルーダー",left:"左",right:"右",notes:"メモ(ローカル保存)",notesPlaceholder:"このプロファイルのメモを追加...",notesHelp:"メモはBambuddyに保存され、プリンターには保存されません",syncing:"プリンターと同期中...",savingExtruder:"エクストルーダーに保存中 {{current}}/{{total}}...",pleaseWait:"お待ちください"},deleteConfirm:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"「{{name}}」をプリンターから削除しますか?"},bulkDelete:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"選択した{{count}}件のプロファイルをプリンターから削除しますか?"},toast:{profileSaved:"Kプロファイルを保存しました",profilesSaved:"Kプロファイルを{{count}}台のエクストルーダーに保存しました",selectAtLeastOneExtruder:"エクストルーダーを1つ以上選択してください",profileDeleted:"Kプロファイルを削除しました",profilesDeleted:"{{count}}件のプロファイルを削除しました",exportedProfiles:"{{count}}件のプロファイルをエクスポートしました",importedProfiles:"{{total}}件中{{imported}}件のプロファイルをインポートしました",noProfilesToExport:"エクスポートするプロファイルがありません",invalidFileFormat:"無効なファイル形式",failedToParseImport:"インポートファイルの解析に失敗しました",failedToSaveBatch:"Kプロファイルの保存に失敗しました",noteSaved:"メモを保存しました",failedToSaveNote:"メモの保存に失敗しました"},permission:{noRead:"プロファイルを更新する権限がありません",noCreate:"プロファイルを追加する権限がありません",noUpdate:"Kプロファイルを更新する権限がありません",noDelete:"Kプロファイルを削除する権限がありません",noExport:"プロファイルをエクスポートする権限がありません",noImport:"プロファイルをインポートする権限がありません"}},virtualPrinter:{title:"仮想プリンター",running:"稼働中",stopped:"停止",description:{default:"Bambu StudioとOrcaSlicerに表示される仮想プリンターを有効化。このプリンターに送信されたファイルは印刷せずに直接アーカイブされます。",proxy:"スライサーのトラフィックを実際のプリンターに転送するプロキシを有効化。任意のネットワーク経由でリモート印刷が可能です。"},enable:{title:"仮想プリンターを有効化",visibleInSlicer:"スライサーの検出リストに「Bambuddy」として表示",proxyingTo:"{{name}}にプロキシ中",notActive:"非アクティブ"},model:{title:"プリンターモデル",description:"エミュレートするプリンターモデルを選択。",restartWarning:"モデルを変更すると仮想プリンターが再起動されます"},accessCode:{title:"アクセスコード",isSet:"アクセスコードが設定されています",notSet:"アクセスコード未設定 - 有効化に必要です",placeholder:"8文字のコードを入力",placeholderChange:"新しいコードを入力して変更",hint:"正確に8文字必要です。スライサーの認証に使用されます。",charCount:"({{count}}/8)"},targetPrinter:{title:"ターゲットプリンター",configured:"プロキシターゲット設定済み",notConfigured:"ターゲットプリンター未選択 - プロキシモードに必要です",placeholder:"プリンターを選択...",hint:"スライサートラフィックの転送先プリンターを選択。プリンターはLANモードである必要があります。",noPrinters:"プリンターが設定されていません。プロキシモードを使用するにはまずプリンターを追加してください。"},remoteInterface:{title:"ネットワークインターフェース上書き",configured:"インターフェース上書き有効",optional:"オプション — 自動検出IPが間違っている場合に使用(複数NIC、Docker、VPNなど)",placeholder:"自動検出(デフォルト)...",hint:"SSDPで広告され、TLS証明書に使用されるIPアドレスを上書きします。Bambuddyに複数のネットワークインターフェースがある場合に便利です。"},mode:{title:"モード",archive:"アーカイブ",archiveDesc:"ファイルを即座にアーカイブ",review:"レビュー",reviewDesc:"アーカイブ前にレビュー",queue:"キュー",queueDesc:"アーカイブしてキューに追加",proxy:"プロキシ",proxyDesc:"実際のプリンターに転送"},autoDispatch:{title:"自動ディスパッチ",description:"キューに追加されたときに自動的に印刷を開始します。オフの場合、手動ディスパッチを待ちます。"},setupRequired:{title:"セットアップが必要です",description:"仮想プリンター機能を使用するには追加のシステム設定が必要です。ポートフォワーディング、ファイアウォールルール、プラットフォーム固有の設定が含まれます。",readGuide:"有効にする前にセットアップガイドをお読みください"},howItWorks:{title:"仕組み",step1:"同じLAN上では、仮想プリンターはスライサー(Bambu Studio / OrcaSlicer)に自動的に表示されます。他のネットワークからは、IPアドレスとアクセスコードで手動で追加してください。",step2:"アーカイブ、レビュー、キューモードでは、スライサーの「送信」ボタンを使用して3MFファイルをBambuddyにアップロードします。スライサーは「印刷成功」と表示しますが、ファイルは保存され、印刷はされません。",step3:"プロキシモードでは、仮想プリンターはすべてのトラフィックを実際のプリンターに転送します。直接接続されているかのように印刷がすぐに開始されます。"},status:{title:"ステータス詳細",printerName:"プリンター名",model:"モデル",serialNumber:"シリアル番号",mode:"モード",pendingFiles:"保留中のファイル",targetPrinter:"ターゲットプリンター",ftpPort:"FTPポート",mqttPort:"MQTTポート",ftpConnections:"FTP接続数",mqttConnections:"MQTT接続数"},toast:{updated:"仮想プリンター設定を更新しました",failedToUpdate:"設定の更新に失敗しました",accessCodeRequired:"先にアクセスコードを設定してください",targetPrinterRequired:"先にターゲットプリンターを選択してください",bindIpRequired:"先にバインドIPを設定してください",accessCodeEmpty:"アクセスコードは空にできません",accessCodeLength:"アクセスコードは8文字である必要があります",created:"仮想プリンターを作成しました",failedToCreate:"仮想プリンターの作成に失敗しました",deleted:"仮想プリンターを削除しました",failedToDelete:"仮想プリンターの削除に失敗しました"},list:{title:"仮想プリンター",add:"追加",addFirst:"仮想プリンターを追加",empty:"仮想プリンターが設定されていません。追加して始めましょう。"},bindIp:{title:"バインドインターフェース",placeholder:"インターフェースを選択...",hint:"この仮想プリンターがバインドするネットワークインターフェース。プリンターごとに一意である必要があります。"},proxy:{accessCodeHint:"プロキシモードでは、スライサーにターゲットプリンターのアクセスコードを使用してください。接続は実際のプリンターに透過的に転送されます。"},addDialog:{title:"仮想プリンターを追加",name:"名前",hint:"アクセスコード、ターゲットプリンター、その他の設定は作成後に設定できます。",create:"作成"},deleteConfirm:{title:"仮想プリンターを削除",message:"「{{name}}」を削除してもよろしいですか?このプリンターのすべてのサービスが停止されます。"}},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:"カーボンロッドの清掃",lubricateSteelRods:"スチールロッドに潤滑剤を塗布してスムーズな動きを確保",cleanSteelRods:"スチールロッドの清掃",cleanLinearRails:"リニアレールを拭いてほこりや汚れを除去",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},smartPlugs:{offline:"オフライン",admin:"管理",openPlugAdminPage:"プラグ管理ページを開く",deleteSmartPlug:"スマートプラグを削除",turnOnSmartPlug:"スマートプラグをオンにする",turnOffSmartPlug:"スマートプラグをオフにする",turnOn:"オンにする",turnOff:"オフにする",addSmartPlug:{scanningNetwork:"ネットワークをスキャン中...",chooseEntity:"エンティティを選択...",connectionFailed:"接続失敗",searchEntities:"エンティティを検索...",searchPowerSensors:"電力センサーを検索...",searchEnergySensors:"エネルギーセンサーを検索...",placeholders:{plugName:"リビングルームプラグ",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"電力トピックと同じ、または異なる"}},linkedTo:"リンク先:",monitorOnly:"監視のみ",alerts:"アラート",scheduleOn:"オン {{time}}",scheduleOff:"オフ {{time}}",on:"オン",off:"オフ",power:"電力",kwhToday:"本日のkWh",settings:"設定",automationSettings:"自動化設定",showInSwitchbar:"スイッチバーに表示",quickAccessSidebar:"サイドバーからクイックアクセス",enabled:"有効",enableAutomation:"このプラグの自動化を有効にする",autoOn:"自動オン",autoOnDescription:"印刷開始時にオンにする",autoOff:"自動オフ",autoOffDescription:"印刷完了時にオフにする(ワンショット)",autoOffPersistent:"有効のまま維持",autoOffPersistentDescription:"ワンショットではなく印刷間で有効のまま維持",turnOffDelayMode:"オフ遅延モード",time:"時間",temp:"温度",delayMinutes:"遅延(分)",tempThreshold:"温度しきい値(°C)",tempThresholdDescription:"ノズルがこの温度以下に冷却されるとオフになります",edit:"編集",deleteConfirm:'"{{name}}"を削除してもよろしいですか?この操作は取り消せません。',turnOnConfirm:'"{{name}}"をオンにしてもよろしいですか?',turnOffConfirm:'"{{name}}"をオフにしてもよろしいですか?接続されたデバイスの電源が切れます。',failedToTurn:'"{{name}}"を{{action}}できませんでした',unknown:"不明",addTitle:"スマートプラグを追加",editTitle:"スマートプラグを編集",stopScanning:"スキャン停止",discoverTasmota:"Tasmotaデバイスを検出",foundDevices:"{{count}}台のデバイスが見つかりました - クリックして選択:",noDevicesFound:"ネットワーク上にTasmotaデバイスが見つかりません",haNotConfigured:"Home Assistantが設定されていません。設定場所:",haSettingsPath:"設定 → ネットワーク → Home Assistant",selectEntity:"エンティティを選択 *",ipAddress:"IPアドレス *",nameLabel:"名前 *",username:"ユーザー名",password:"パスワード",authHint:"Tasmotaデバイスが認証を必要としない場合は空のままにしてください",linkToPrinter:"プリンターにリンク",noPrinter:"プリンターなし(手動制御のみ)",linkingDescription:"リンクすると印刷開始/完了時に自動でオン/オフできます",powerAlerts:"電力アラート",alertAbove:"上限アラート(W)",alertBelow:"下限アラート(W)",alertDescription:"電力消費がこれらのしきい値を超えた場合に通知します。無効にするには空のままにしてください。",dailySchedule:"デイリースケジュール",turnOnAt:"オンにする時刻",turnOffAt:"オフにする時刻",scheduleDescription:"毎日これらの時刻にプラグを自動的にオン/オフします。スキップするには空のままにしてください。",showOnPrinterCard:"プリンターカードに表示",displayOnPrinterCard:"プリンターカードにボタンを表示",connectedResult:"接続成功!",deviceLabel:"デバイス: {{name}} - ",stateLabel:"状態: {{state}}",test:"テスト",delete:"削除",save:"保存",add:"追加",cancel:"キャンセル",failedToStartScan:"スキャンを開始できませんでした",nameRequired:"名前は必須です",entityRequired:"Home AssistantプラグにはエンティティIDが必要です",mqttTopicRequired:"電力、エネルギー、または状態監視用に少なくとも1つのMQTTトピックを設定する必要があります",loadingEntities:"エンティティを読み込み中...",loading:"読み込み中...",failedToLoadEntities:"エンティティの読み込みに失敗しました: {{error}}",noEntitiesMatching:'"{{search}}"に一致するエンティティが見つかりません',noEntitiesAvailable:"利用可能なエンティティがありません",searchingEntities:"すべてのエンティティを検索中({{count}}件見つかりました)",showingEntities:"switch、light、input_booleanを表示({{count}}件利用可能)",energyMonitoringOptional:"エネルギー監視(オプション)",energyMonitoringHint:"電力/エネルギーデータを提供するセンサーを検索して選択します。",powerSensorW:"電力センサー(W)",energyTodayKwh:"本日のエネルギー(kWh)",totalEnergyKwh:"総エネルギー(kWh)",noMatchingSensors:"一致するセンサーがありません",none:"なし",mqttNotConfigured:"MQTTブローカーが設定されていません。ブローカーアドレスを設定してください:",mqttSettingsPath:"設定 → ネットワーク → MQTT配信",mqttNotConfiguredSuffix:"(配信を有効にする必要はありません。ブローカーの詳細を入力するだけです)。",mqttMonitorOnlyDescription:"MQTTプラグはMQTTサブスクリプション経由で電力/エネルギーデータを受信します。オン/オフ制御は利用できません - MQTTブローカーまたはホームオートメーションシステムを使用してください。",powerMonitoring:"電力監視",energyMonitoring:"エネルギー監視",stateMonitoring:"状態監視",optional:"オプション",topic:"トピック",jsonPath:"JSONパス",multiplier:"乗数",onValue:"ON値",mqttPowerHint:`JSONパスはJSONペイロードから値を抽出します(例: "power_l1")。トピックが生の数値を送信する場合は空のままにしてください。
- 乗数: mW→Wは0.001、kW→Wは1000を使用。`,mqttEnergyHint:`JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。
- 乗数: Wh→kWhは0.001、MWh→kWhは1000を使用。`,mqttStateHint:`JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。
- ON値: "ON"を意味する正確な文字列。自動検出(ON、true、1)の場合は空のままにしてください。`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"電力URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"電力乗数",restEnergyUrl:"エネルギーURL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"エネルギー乗数",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"電力データ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyUrlHint:"エネルギーデータ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyHint:"各値は個別のURLを使用するか、ステータスURLにフォールバックできます。乗数で単位変換が可能です(例:WhからkWhへの変換は0.001)。",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"スイッチバーにスイッチがありません",enableSwitchbarHint:"設定 > スマートプラグで「スイッチバーに表示」を有効にしてください"},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"メール",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTPメール通知",telegram:"Telegramボット経由の通知",discord:"Webhook経由でDiscordチャンネルに送信",ntfy:"無料のセルフホスト可能なプッシュ通知",pushover:"シンプルで信頼性の高いプッシュ通知",callmebot:"CallMeBot経由の無料WhatsApp通知",webhook:"任意のURLへの汎用HTTP POST",homeassistant:"Home Assistantダッシュボードの永続通知"},lastSuccess:"最終: {{date}}",error:"エラー",printer:"プリンター:",allPrinters:"すべてのプリンター",sendTestNotification:"テスト通知を送信",eventSettings:"イベント設定",enabled:"有効",sendFromProvider:"このプロバイダーから通知を送信",printEvents:"印刷イベント",printerStatus:"プリンターステータス",amsAlarms:"AMSアラーム",amsHtAlarms:"AMS-HTアラーム",printQueue:"印刷キュー",start:"開始",plateCheck:"プレートチェック",complete:"完了",failed:"失敗",stopped:"停止",progress:"進捗",offline:"オフライン",lowFilament:"フィラメント残量低下",maintenance:"メンテナンス",amsHumidity:"AMS湿度",amsTemp:"AMS温度",amsHtHumidity:"AMS-HT湿度",amsHtTemp:"AMS-HT温度",bedCooled:"ベッド冷却済み",firstLayer:"第1層完了",quiet:"静音",digest:"ダイジェスト {{time}}",printStarted:"印刷開始",plateNotEmpty:"プレートが空でない",plateNotEmptyDescription:"印刷前にオブジェクトが検出されました",printCompleted:"印刷完了",bedCooledLabel:"ベッド冷却済み",bedCooledDescription:"印刷後にベッドがしきい値以下に冷却",firstLayerCompleteLabel:"第1層完了",firstLayerCompleteDescription:"第1層完了時にスナップショット付きで通知",missingSpoolAssignmentLabel:"スプール割り当て不足",missingSpoolAssignmentDescription:"印刷開始時に必要トレイへスプールが未割り当ての場合に通知",printFailed:"印刷失敗",printStopped:"印刷停止",progressMilestones:"進捗マイルストーン",progressMilestonesDescription:"25%、50%、75%で通知",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",lowFilamentLabel:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",maintenanceDueDescription:"メンテナンスが必要な場合に通知",amsHumidityHigh:"AMS湿度高",amsHumidityHighDescription:"通常AMSの湿度がしきい値を超過",amsTemperatureHigh:"AMS温度高",amsTemperatureHighDescription:"通常AMSの温度がしきい値を超過",amsHtHumidityHigh:"AMS-HT湿度高",amsHtHumidityHighDescription:"AMS-HTの湿度がしきい値を超過",amsHtTemperatureHigh:"AMS-HT温度高",amsHtTemperatureHighDescription:"AMS-HTの温度がしきい値を超過",jobAdded:"ジョブ追加",jobAddedDescription:"キューにジョブが追加されました",jobAssigned:"ジョブ割り当て",jobAssignedDescription:"モデルベースのジョブがプリンターに割り当てられました",jobStarted:"ジョブ開始",jobStartedDescription:"キュージョブの印刷が開始されました",jobWaiting:"ジョブ待機中",jobWaitingDescription:"フィラメントまたはプリンター待ちのジョブ",jobSkipped:"ジョブスキップ",jobSkippedDescription:"ジョブがスキップされました(前のジョブが失敗)",jobFailed:"ジョブ失敗",jobFailedDescription:"ジョブの開始に失敗しました",queueComplete:"キュー完了",queueCompleteDescription:"すべてのキュージョブが完了しました",quietHours:"静音時間",noNotificationsDuring:"この時間帯は通知を送信しません",editProviderToChangeQuietHours:"プロバイダーを編集して静音時間を変更",dailyDigest:"デイリーダイジェスト",batchNotifications:"通知をまとめて1日のサマリーとして送信",sendAt:"{{time}}に送信",editProviderToChangeDigestTime:"プロバイダーを編集してダイジェスト時刻を変更",edit:"編集",deleteProvider:"通知プロバイダーを削除",deleteConfirm:'"{{name}}"を削除してもよろしいですか?この操作は取り消せません。',delete:"削除",addTitle:"通知プロバイダーを追加",editTitle:"通知プロバイダーを編集",nameLabel:"名前 *",namePlaceholder:"マイ通知",providerTypeLabel:"プロバイダータイプ *",configuration:"設定",testConfiguration:"設定をテスト",printerFilter:"プリンターフィルター",onlyFromPrinter:"このプリンターからのイベントのみ通知を送信",quietHoursDnd:"静音時間(おやすみモード)",quietStart:"開始",quietEnd:"終了",dailyDigestLabel:"デイリーダイジェスト",sendDigestAt:"ダイジェスト送信時刻",digestCollected:"イベントが収集され、この時刻にまとめて送信されます",notificationEvents:"通知イベント",progressPercent:"(25%、50%、75%)",bedCooledAfterPrint:"(印刷完了後)",cancel:"キャンセル",save:"保存",add:"追加",nameRequired:"名前は必須です",fieldRequired:"{{field}}は必須です",phoneNumber:"電話番号",apiKey:"APIキー",serverUrl:"サーバーURL",topic:"トピック",authToken:"認証トークン",userKey:"ユーザーキー",appToken:"アプリトークン",priority:"優先度",botToken:"ボットトークン",chatId:"チャットID",smtpServer:"SMTPサーバー",smtpPort:"SMTPポート",security:"セキュリティ",authentication:"認証",username:"ユーザー名",password:"パスワード",fromEmail:"送信元メール",toEmail:"宛先メール",webhookUrl:"Webhook URL",payloadFormat:"ペイロード形式",authorization:"認可",titleFieldName:"タイトルフィールド名",messageFieldName:"メッセージフィールド名",editTemplate:"テンプレートを編集: {{name}}",titleLabel:"タイトル",bodyLabel:"本文",titlePlaceholder:"通知タイトル...",bodyPlaceholder:"通知本文...",availableVariables:"利用可能な変数",clickToInsert:"クリックして本文のカーソル位置に挿入",livePreview:"ライブプレビュー",hide:"非表示",show:"表示",loadingPreview:"プレビューを読み込み中...",enterTemplateContent:"テンプレートの内容を入力するとプレビューが表示されます",titlePreview:"タイトル:",bodyPreview:"本文:",resetToDefault:"デフォルトにリセット",titleRequired:"タイトルは必須です",bodyRequired:"本文は必須です",notificationLog:"通知ログ",showFailedOnly:"失敗のみ",last24Hours:"過去24時間",last7Days:"過去7日間",last30Days:"過去30日間",last90Days:"過去90日間",justNow:"たった今",noFailedNotifications:"失敗した通知はありません",noNotificationsLogged:"記録された通知はありません",unknownProvider:"不明なプロバイダー",logTitle:"タイトル",logMessage:"メッセージ",logError:"エラー",logProvider:"プロバイダー: {{type}}",logTime:"時刻: {{time}}",refresh:"更新",clearOld:"古いものを削除",statsSummary:"過去{{days}}日間:",statsNotifications:"通知",statsSent:"{{count}}件送信",statsFailed:"{{count}}件失敗",eventTypes:{print_start:"印刷開始",print_complete:"印刷完了",print_failed:"印刷失敗",print_stopped:"印刷停止",print_progress:"進捗",printer_offline:"プリンターオフライン",printer_error:"プリンターエラー",filament_low:"フィラメント残量低下",maintenance_due:"メンテナンス期限",test:"テスト"},userEmail:{title:"通知",emailNotifications:"メール通知",emailNotificationsDesc:"自分の印刷ジョブに対してメール通知を受け取ります。メールは高度な認証で設定されたSMTP設定を使用して送信されます。",sendingTo:"通知の送信先",noEmailWarning:"アカウントにメールアドレスが設定されていません。管理者に連絡して追加してもらってください。",printJobNotifications:"印刷ジョブ通知",printJobNotificationsDesc:"送信した印刷ジョブのどのイベントでメール通知を送るかを選択します。",printJobStarts:"印刷ジョブ開始",printJobStartsDesc:"印刷ジョブが開始されたときに通知を受け取る。",printJobFinishes:"印刷ジョブ完了",printJobFinishesDesc:"印刷ジョブが正常に完了したときに通知を受け取る。",printErrors:"印刷エラー",printErrorsDesc:"印刷ジョブが失敗またはエラーが発生したときに通知を受け取る。",printJobStops:"印刷ジョブ停止",printJobStopsDesc:"印刷ジョブがキャンセルまたは停止されたときに通知を受け取る。",saveSuccess:"通知設定を保存しました。",saveError:"通知設定の保存に失敗しました。"}},richTextEditor:{bold:"太字",italic:"斜体",underline:"下線",bulletList:"箇条書きリスト",numberedList:"番号付きリスト",alignLeft:"左揃え",alignCenter:"中央揃え",alignRight:"右揃え",addLink:"リンクを追加",removeLink:"リンクを削除"},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キーを押すか外側をクリックして閉じます"},notificationLog:{title:"通知ログ",events:{printStarted:"印刷開始",printComplete:"印刷完了",printFailed:"印刷失敗",printStopped:"印刷停止",progress:"進捗",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",lowFilament:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",test:"テスト"},timeAgo:{justNow:"たった今",minutesAgo:"{{minutes}}分前",hoursAgo:"{{hours}}時間前"}},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}}カテゴリー選択済み"},pendingUploads:{placeholders:{notes:"この印刷に関するメモを追加..."},discardUpload:"アップロードを破棄",archiveAllUploads:"すべてのアップロードをアーカイブ",discardAllUploads:"すべてのアップロードを破棄",archive:"アーカイブ",timeAgo:{justNow:"たった今",minutesAgo:"{{minutes}}分前",hoursAgo:"{{hours}}時間前",daysAgo:"{{days}}日前"}},apiBrowser:{placeholders:{requestBody:"JSONリクエストボディ...",searchEndpoints:"エンドポイントを検索..."}},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:"スロットを設定"},githubBackup:{title:"GitHubバックアップ",history:"履歴",downloadBackup:"バックアップをダウンロード",restoreBackup:"バックアップを復元",noBackupsYet:"バックアップはまだありません"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"タグを検索...",renameTag:"タグ名を変更",deleteTag:"タグを削除"},notificationTemplates:{placeholders:{title:"通知タイトル...",body:"通知本文..."}},batchTag:{placeholders:{newTag:"新しいタグを入力..."}},photoGallery:{deletePhoto:"写真を削除"},filamentHoverCard:{copySpoolUuid:"スプールUUIDをコピー"},kProfilesView:{hasNote:"メモあり",copyProfile:"プロファイルをコピー"},layout:{openMenu:"メニューを開く",noPermissionSystemInfo:"システム情報を表示する権限がありません"},dashboard:{dragToReorder:"ドラッグして並べ替え",hideWidget:"ウィジェットを非表示"},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"}},logViewer:{searchPlaceholder:"メッセージまたはロガー名を検索...",noLogEntries:"ログエントリが見つかりません"},switchbarPopover:{noSwitchesInSwitchbar:"スイッチバーにスイッチがありません"},projectPageModal:{placeholders:{title:"タイトル",designer:"デザイナー",license:"ライセンス",description:"説明を入力...",profileTitle:"プロファイルタイトル",profileDescription:"プロファイルの説明..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"待機中",justNow:"たった今",now:"今すぐ",minsAgo:"{{count}}分前",inMins:"あと{{count}}分",hoursAgo:"{{count}}時間前",inHours:"あと{{count}}時間",daysAgo:"{{count}}日前",inDays:"あと{{count}}日"},spoolbuddy:{nav:{dashboard:"ダッシュボード",ams:"AMS",inventory:"インベントリ",writeTag:"書込み",settings:"設定"},status:{nfcReady:"NFC準備完了",nfcOff:"NFCオフ",offline:"オフライン",online:"オンライン",noPrinters:"プリンターなし",deviceOffline:"デバイスオフライン",waitingConnection:"デバイス接続を待っています...",systemReady:"システム準備完了",status:"ステータス"},dashboard:{readyToScan:"スキャン準備完了",idleMessage:"スプールを計量台に置いて識別します",nfcHint:"NFCタグは自動的に読み取られます",device:"デバイス",syncWeight:"重量同期",weightSynced:"同期完了!",unknownTag:"不明なタグ",newTag:"新しいタグを検出",onScale:"計量中",linkSpool:"スプールにリンク",linkTagTitle:"タグをスプールにリンク",linkTag:"タグをリンク",selectSpool:"このタグにリンクするスプールを選択:",noUntagged:"タグなしのスプールが見つかりません",tagDetected:"タグ検出",noTag:"タグなし",tagId:"タグ",grossWeight:"総重量",spoolSize:"スプールサイズ",close:"閉じる",currentSpool:"現在のスプール"},modal:{spoolDetected:"スプール検出",assignToAms:"AMSに割り当て",syncWeight:"重量同期",weightSynced:"同期完了!",syncing:"同期中...",newTagDetected:"新しいタグを検出",addToInventory:"インベントリに追加",assignToAmsTitle:"AMSに割り当て",selectSlot:"スロットを選択",assign:"割り当て",assigning:"割り当て中...",assignSuccess:"割り当て完了!",assignError:"スプールの割り当てに失敗しました。再試行してください。",noPrinterSelected:"プリンターを選択...",noAmsDetected:"このプリンターにAMSが検出されません",slot:"スロット"},weight:{noReading:"読み取りなし",stable:"安定",measuring:"計測中...",tare:"風袋引き",calibrate:"キャリブレーション"},spool:{remaining:"残量",material:"素材",brand:"ブランド",color:"色",coreWeight:"コア",labelWeight:"ラベル",scaleWeight:"計量",netWeight:"正味",lastUsed:"最終使用"},ams:{noData:"AMSが検出されません",connectAms:"AMSを接続してスロットを表示",noPrinter:"プリンター未選択",selectPrinter:"上部バーからプリンターを選択",printerDisconnected:"プリンター切断",humidity:"湿度",level:"レベル",active:"アクティブ",slot:"スロット",empty:"空"},inventory:{search:"スプールを検索...",empty:"インベントリにスプールがありません",noResults:"一致するスプールがありません",spools:"スプール",addSpool:"スプール追加"},settings:{tabDevice:"デバイス",tabDisplay:"ディスプレイ",tabScale:"計量",tabUpdates:"アップデート",nfcReader:"NFCリーダー",type:"タイプ",connection:"接続",notConnected:"N/A",deviceInfo:"デバイス情報",hostname:"ホスト",uptime:"稼働時間",brightness:"明るさ",saved:"保存済み",noBacklight:"DSIバックライトが検出されませんでした。明るさ制御にはDSIディスプレイが必要です。",screenBlank:"画面オフタイムアウト",screenBlankDesc:"操作がないと画面がオフになります。タッチで復帰。",displayNote:"明るさはソフトウェアフィルターとして適用されます。",scaleCalibration:"計量キャリブレーション",currentWeight:"現在の重量",tareOffset:"風袋",calFactor:"係数",knownWeight:"既知の重量",calStep1:"計量台からすべてのアイテムを取り除き、ゼロ設定を押してください。",calStep2:"既知の重量を計量台に置いてください。",setZero:"ゼロ設定",calibrateNow:"キャリブレーション",calibrated:"キャリブレーション済み",tareSet:"風袋コマンドを送信しました。デバイスを待っています...",tareFailed:"風袋コマンドの送信に失敗しました",zeroSet:"ゼロ点を設定しました。既知の重量を計量台に置いてください。",calibrationDone:"キャリブレーション完了!",calibrationFailed:"キャリブレーションに失敗しました",lastCalibrated:"最終キャリブレーション",stable:"安定",settling:"安定化中...",firmware:"ファームウェア",scale:"計量",noDevice:"SpoolBuddyデバイスが見つかりません",daemonVersion:"デーモンバージョン",currentVersion:"現在",versionPending:"デーモンを待っています...",checking:"確認中...",checkUpdates:"アップデートを確認",updateAvailable:"アップデートあり",updateInstructions:"SSH経由で更新:SpoolBuddyインストールスクリプトを実行してください。",upToDate:"最新です",includeBeta:"ベータ版を含む"},writeTag:{tabExisting:"既存のスプール",tabNew:"新規スプール",tabReplace:"タグ交換",searchPlaceholder:"素材、色、ブランドで検索...",noUntaggedSpools:"タグなしのスプールがありません",noTaggedSpools:"タグ付きのスプールがありません",selectSpool:"スプールを選択し、NTAGをリーダーに置いてください",placeTag:"NTAGをリーダーに置いてください",tagReady:"タグ検出 — 書込み準備完了",writeTag:"タグ書込み",replaceTag:"タグ交換",writing:"タグ書込み中...",waiting:"SpoolBuddyを待機中...",writeSuccess:"タグの書込みが完了しました!",writeFailed:"書込み失敗",queueFailed:"書込みコマンドのキューに失敗しました",tryAgain:"再試行",cancel:"キャンセル",replaceWarning:"古いタグのリンクが解除され、新しいタグに置き換わります。",deviceOffline:"SpoolBuddyはオフラインです",material:"素材",colorName:"色名",color:"色",brand:"ブランド",weight:"重量 (g)",createSpool:"スプール作成",creating:"作成中...",spoolCreated:"スプール作成完了!書込み準備ができました。",createFailed:"スプールの作成に失敗しました"},quickMenu:{printerPower:"プリンター電源",systemControls:"システム",restartDaemon:"デーモン再起動",restartBrowser:"ブラウザ再起動",reboot:"再起動",shutdown:"シャットダウン",swipeToClose:"下にスワイプして閉じる",confirmTitle:"確認",confirmShutdown:"SpoolBuddyをシャットダウンしますか?再起動するには物理的なアクセスが必要です。",confirmReboot:"SpoolBuddyを再起動しますか?",confirmRestartDaemon:"SpoolBuddyデーモンを再起動しますか?NFCとスケールが一時的に使用できなくなります。",confirmRestartBrowser:"キオスクブラウザを再起動しますか?画面が一時的に暗くなります。",confirm:"確認",confirmPlugOn:"{{name}}をオンにしますか?",confirmPlugOff:"{{name}}をオフにしますか?",turnOn:"オン",turnOff:"オフ"}},bugReport:{title:"バグを報告",description:"説明",descriptionPlaceholder:"何が問題でしたか?問題を説明してください...",email:"メールアドレス(任意)",emailPlaceholder:"your@email.com",emailPrivacy:"入力された場合、メールアドレスはGitHub Issueの折りたたみセクションに含まれ、メンテナーがフォローアップできるようになります。",screenshot:"スクリーンショット",uploadOrPaste:"画像をアップロード、貼り付け、またはドラッグ",dataCollectedSummary:"レポートに含まれるデータは?",dataIncluded:"含まれるもの:",dataIncludedList:"アプリバージョン、OS、アーキテクチャ、Pythonバージョン、データベース統計(件数のみ)、プリンターモデル、ノズル数、ファームウェアバージョン、接続状態、統合状態(Spoolman、MQTT、HA)、非機密設定、ネットワークインターフェース数、Docker詳細、依存関係バージョン。",dataNeverIncluded:"含まれないもの:",dataNeverIncludedList:"プリンター名、シリアル番号、アクセスコード、パスワード、IPアドレス、メールアドレス、APIキー、トークン、Webhook URL、ホスト名、ユーザー名。",submit:"送信",startLogging:"デバッグログ開始",stepEnableLogging:"デバッグログ有効",stepReproduce:"問題を再現してください",stepStopLogging:"停止してレポート送信",stopAndSubmit:"停止して送信",maxDuration:"{{minutes}}分後に自動停止",stoppingLogs:"ログ収集・送信中...",submitting:"バグレポートを送信中...",submitSuccess:"バグレポートが正常に送信されました!",submitFailed:"バグレポートの送信に失敗しました",thankYou:"ありがとうございます!",submitted:"バグレポートが送信されました。",viewIssue:"Issueを表示",unexpectedError:"予期しないエラーが発生しました"},failureDetection:{title:"AI 失敗検出",description:"セルフホストされた Obico ML API で印刷を監視し、検出された失敗に自動的に対応します。",mlUrl:"Obico ML API の URL",mlUrlHint:"セルフホストした Obico ml_api コンテナのベース URL (例: http://192.168.1.10:3333)。",test:"テスト",testSuccess:"ML API に接続でき、正常です。",testFailed:"ML API に接続できませんでした。",sensitivity:"感度",sensitivityLow:"低(誤検出が少ない)",sensitivityMedium:"中(バランス型)",sensitivityHigh:"高(早期検出、誤検出が増加)",sensitivityHint:"警告と失敗をトリガーする信頼度のしきい値を調整します。",action:"失敗検出時の動作",actionNotify:"通知のみ",actionPause:"印刷を一時停止",actionPauseOff:"一時停止して電源を切る",pollInterval:"ポーリング間隔(秒)",pollIntervalHint:"印刷中に各プリンターをチェックする頻度。最小 5 秒、最大 120 秒。",externalUrlMissing:"外部 URL が設定されていません。",externalUrlHint:"ML API は URL 経由でカメラ画像を取得します。ML API コンテナが Bambuddy に到達できるよう、一般設定で外部 URL を設定してください。",perPrinterTitle:"監視対象プリンター",perPrinterHint:"検出サービスが監視するプリンターを選択します。",monitorAll:"接続されているすべてのプリンターを監視",statusTitle:"ステータス",serviceRunning:"サービス稼働中",thresholds:"低 / 高しきい値",activePrinters:"アクティブな印刷",noActivePrints:"現在、実行中の印刷はありません。",historyTitle:"最近の検出",noHistory:"まだ検出はありません。"}},que={nav:{printers:"Stampanti",archives:"Archivi",queue:"Coda",stats:"Statistiche",profiles:"Profili",maintenance:"Manutenzione",projects:"Progetti",inventory:"Filamento",files:"File",notifications:"Notifiche",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",uploading:"Caricamento...",uploadFailed:"Caricamento fallito",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",export:"Esporta",import:"Importa",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",back:"Indietro",copy:"Copia",copied:"Copiato!",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",problem:"Problema",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",search:"Cerca stampanti...",noSearchResults:"Nessuna stampante corrisponde alla tua ricerca o ai tuoi filtri",filter:{allStatuses:"Tutti gli stati",allLocations:"Tutti i luoghi"},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",files:"File",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",forceRefresh:"Forza aggiornamento",forceRefreshSuccess:"Aggiornamento richiesto",mqttDebug:"Debug MQTT",printerInformation:"Informazioni stampante",copyToClipboard:"Copia",copied:"Copiato!",state:"Stato",wifiSignalLabel:"Segnale WiFi",developerMode:"Modalità sviluppatore",enabled:"Attivato",disabled:"Disattivato",addedOn:"Aggiunta il",sdCard:"Scheda SD",inserted:"Inserita",notInserted:"Non inserita",totalPrintHours:"Ore di stampa",activeNozzle:"Attivo: ugello {{nozzle}}",nozzleRack:"Rack Ugelli",nozzleDocked:"Agganciato",nozzleMounted:"Montato",nozzleActive:"Attivo",nozzleIdle:"Inattivo",nozzleDiameter:"Diametro",nozzleType:"Tipo",nozzleStatus:"Stato",nozzleFilament:"Filamento",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",missingSpoolAssignment:"Stampa avviata su {{printer}}. Mancano assegnazioni bobina per: {{slots}}",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",failedToSetSpeed:"Impossibile impostare la velocità di stampa",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",noCamera:"Non hai il permesso di visualizzare le telecamere"},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"},bulk:{select:"Seleziona",selectAll:"Seleziona tutto",selectByLocation:"Seleziona per posizione",selected:"{{count}} selezionato/i",actions:{stop:"Ferma",pause:"Pausa",resume:"Riprendi",clearPlate:"Svuota piano",clearHMS:"Cancella notifiche"},confirm:{stopTitle:"Ferma {{count}} stampe",stopMessage:"Questo annullerà le stampe attive su {{count}} stampante/i. Questa azione non può essere annullata.",stopButton:"Ferma tutte",pauseTitle:"Pausa {{count}} stampe",pauseMessage:"Questo metterà in pausa le stampe attive su {{count}} stampante/i.",pauseButton:"Pausa tutte",clearPlateTitle:"Svuota {{count}} piani di stampa",clearPlateMessage:"Questo svuoterà il piano di stampa su {{count}} stampante/i e potrebbe avviare i lavori in coda.",clearPlateButton:"Svuota tutti"},success:"{{action}} completato su {{count}} stampante/i",partial:"{{succeeded}} riuscito/i, {{failed}} fallito/i",noneApplicable:"Nessuna stampante selezionata è nello stato corretto per questa azione",selectByState:"Seleziona per stato"},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"},drying:{start:"Avvia essiccazione",stop:"Ferma essiccazione",temperature:"Temperatura",duration:"Durata",hours:"ore",timeRemaining:"{{time}} rimanente",active:"Essiccazione",notSupported:"Essiccazione non supportata",powerRequired:"Collegare l'alimentatore AMS per abilitare l'asciugatura",startingDrying:"Avvio essiccazione...",stoppingDrying:"Arresto essiccazione...",rotateTray:"Ruota la bobina durante l'essiccazione"},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"},speed:{title:"Velocità di stampa",silent:"Silenzioso (50%)",standard:"Standard (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},airduct:{title:"Modalità condotto d'aria",cooling:"Raffreddamento",heating:"Riscaldamento"},noSdCard:"Nessuna SD",door:{open:"Aperta",closed:"Chiusa"},fans:{partCooling:"Ventola raffreddamento parte",auxiliary:"Ventola ausiliaria",chamber:"Ventola camera"},clickToViewHmsErrors:"Clicca per vedere errori HMS",estimatedCompletion:"Tempo completamento stimato",plateNumber:"Piastra {{number}}",slotOptions:"Opzioni slot",amsPopup:{friendlyName:"Nome AMS",friendlyNamePlaceholder:"es. Nome AMS amichevole",serialNumber:"Numero di serie",firmwareVersion:"Firmware",save:"Salva",clear:"Cancella",noEditPermission:"Non hai il permesso di rinominare le unità AMS"},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",incompatibleFile:"Questo file è stato preparato per {{slicedFor}}, ma questa stampante è una {{printerModel}}",dropNotPrintable:"Solo i file .gcode e .gcode.3mf possono essere stampati",dropToPrint:"Rilascia per stampare",cannotPrint:"Stampante occupata"},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",originalPrintNotVisible:"Stampa originale non visibile - prova a rimuovere i filtri",noArchivesYet:"Nessun archivio ancora",prints:"stampe",pagination:{showing:"Mostrando",to:"a",of:"di",show:"Mostra",page:"Pagina",all:"Tutti"},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",hideDuplicates:"Nascondi duplicati",viewOriginalPrint:"Fai clic per visualizzare la stampa originale (#{{id}})",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",timelapseRemoved:"Timelapse rimosso",failedRemoveTimelapse:"Impossibile rimuovere il timelapse",timelapseUploaded:"Timelapse caricato: {{filename}}",failedUploadTimelapse:"Impossibile caricare il timelapse",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",uploadTimelapse:"Carica timelapse",removeTimelapse:"Rimuovi 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}}"?',removeTimelapse:"Rimuovi timelapse",removeTimelapseConfirm:'Sei sicuro di voler rimuovere il video timelapse 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",queueSelectedPlates:"Metti in coda {{count}} piastre",selectAllPlates:"Seleziona tutte le {{count}} piastre",deselectAll:"Deseleziona tutto",printQueued:"Stampa in coda",itemsQueued:"{{count}} elementi in coda",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.",sjf:{label:"SJF",tooltip:"Lavoro più breve prima — lo scheduler dà priorità alle stampe più brevi"},addedBy:"Aggiunto da {{name}}",nextInQueue:"Prossimo in coda",clearPlate:"Libera piatto e avvia il prossimo",clearPlateSuccess:"Piatto liberato — pronto per la prossima stampa",plateReady:"Piatto liberato — pronto per la prossima stampa",plateNumber:"Piatto {{index}}",quantity:"Quantità",quantityHint:"Crea {{count}} elementi in coda",activeBatches:"Lotti attivi",batchProgress:"{{completed}} di {{total}} completati",cancelBatch:"Annulla rimanenti",batchCancelled:"Elementi rimanenti del lotto annullati",cancelBatchConfirmTitle:"Annulla lotto",cancelBatchConfirmMessage:"Annullare tutti gli elementi in sospeso rimanenti in questo lotto?",batch:"Lotto",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",gcodeInjection:"G-code"},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"},timeline:{listView:"Lista",timelineView:"Cronologia",unassigned:"Non assegnato",noData:"Nessuna stampa programmata per questo giorno",allDoneBy:"Tutte le stampe completate entro le {{time}}",staged:"In attesa",filterAll:"Mostra tutto",filterPrinting:"In stampa",filterQueued:"In coda",time:{anyMoment:"a momenti",minutesLeft:"{{minutes}}m rimanenti",hoursLeft:"{{hours}}h rimanenti",hoursMinutesLeft:"{{hours}}h {{minutes}}m rimanenti"},day:{previous:"Giorno precedente",next:"Giorno successivo",today:"Oggi"}},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",printStartedRemaining:"{{completed}} stampa/e avviata/e, {{remaining}} in invio..."}},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",energyWarmingUpTooltip:"Il tracciamento energia sta ancora raccogliendo snapshot orari. I totali per intervallo diventeranno accurati quando esisterà almeno uno snapshot prima dell’intervallo selezionato. I primi valori potrebbero essere sottostimati.",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",noPrintDataInRange:"Nessun dato nel periodo selezionato",periodFilament:"Filamento utilizzato",periodCost:"Costo",avgPerPrint:"Media per stampa",usageOverTime:"Utilizzo nel tempo",filamentByWeight:"Peso",printDuration:"Durata stampa",printerUtilization:"Utilizzo stampante",filamentSuccess:"Successo per materiale",printHabits:"Abitudini di stampa",printTimeOfDay:"Ora di stampa",colorDistribution:"Distribuzione colori",noColorData:"Nessun dato colore disponibile",records:"Record",longestPrint:"Stampa più lunga",heaviestPrint:"Stampa più pesante",mostExpensivePrint:"Più costosa",busiestDay:"Giorno più attivo",successStreak:"Serie di successi",streakPrint:"stampa consecutiva",streakPrints:"{{count}} stampe consecutive",printerStats:"Statistiche stampante",hours:"ore",avgPrints:"Media stampe",noArchiveData:"Nessun dato di stampa disponibile",filamentByTime:"Tempo",avgWeight:"Media peso",avgTime:"Media tempo",filamentByPrints:"Stampe",timeframe:{today:"Oggi","this-week":"Questa settimana","this-month":"Questo mese","last-7":"Ultimi 7 giorni","last-30":"Ultimi 30 giorni","last-90":"Ultimi 90 giorni","this-year":"Quest'anno","all-time":"Tutto",custom:"Personalizzato",from:"Da",to:"A"},allUsers:"Tutti gli utenti",noUser:"Nessun utente (Sistema)",filterByUser:"Filtra per utente"},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",lubricateSteelRods:"Lubrifica aste in acciaio",cleanSteelRods:"Pulisci aste in acciaio",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",queue:"Workflow",filament:"Filamento",network:"Rete",apiKeys:"Chiavi API",virtualPrinter:"Stampante virtuale",failureDetection:"Rilevamento guasti",users:"Utenti",backup:"Backup",emailAuth:"Autenticazione Email",ldap:"LDAP",twoFa:"Autenticazione 2FA",oidc:"SSO / OIDC"},ldap:{title:"Autenticazione LDAP",enabledDesc:"L'autenticazione LDAP è attiva",disabledDesc:"L'autenticazione LDAP è disattivata",disabledHint:"Configura e salva le impostazioni LDAP qui sotto, poi attiva.",enabled:"Autenticazione LDAP attivata",disabled:"Autenticazione LDAP disattivata",feature1:"Gli utenti possono accedere con le credenziali LDAP",feature2:"L'account amministratore locale rimane come fallback",feature3:"I gruppi LDAP vengono mappati ai gruppi BamBuddy al login",serverConfig:"Configurazione server LDAP",serverUrl:"URL del server",serverUrlHint:"Usa ldap:// per standard o ldaps:// per connessioni SSL",security:"Sicurezza",securityHint:"StartTLS aggiorna una connessione semplice a TLS. LDAPS usa TLS fin dall'inizio.",bindDn:"Bind DN (account di servizio)",bindPassword:"Password Bind",searchBase:"Base DN di ricerca",userFilter:"Filtro di ricerca utente",userFilterHint:"{username} viene sostituito con il nome utente. Usa (uid={username}) per OpenLDAP.",autoProvision:"Provisioning automatico utenti",autoProvisionHint:"Crea automaticamente un account BamBuddy al primo accesso LDAP",defaultGroup:"Gruppo predefinito",defaultGroupNone:"— Nessuno (nessun fallback) —",defaultGroupHint:"Gruppo di fallback assegnato quando un utente LDAP si autentica ma non è presente in nessun gruppo LDAP mappato. Lascia vuoto per lasciare gli utenti non mappati senza autorizzazioni.",groupMapping:"Mappatura gruppi (JSON)",groupMappingHint:"Mappa i DN dei gruppi LDAP ai gruppi BamBuddy. Gruppi disponibili: ",testConnection:"Test connessione",settingsSaved:"Impostazioni LDAP salvate",errors:{serverRequired:"L'URL del server LDAP è obbligatorio",searchBaseRequired:"Il Base DN di ricerca è obbligatorio",enableAuthFirst:"Attiva prima l'autenticazione",configureLdapFirst:"Salva prima le impostazioni LDAP"}},email:{smtpSettings:"Configurazione SMTP",smtpHost:"Server SMTP",smtpPort:"Porta SMTP",security:"Sicurezza",authentication:"Autenticazione",username:"Nome utente",password:"Password",fromEmail:"Email mittente",fromName:"Nome mittente",testConnection:"Testa connessione SMTP",testRecipient:"Email destinatario test",sendTest:"Invia email di test",sending:"Invio...",save:"Salva impostazioni",saving:"Salvataggio...",advancedAuth:"Autenticazione avanzata",advancedAuthEnabled:"L'autenticazione avanzata è abilitata",advancedAuthEnabledDesc:"Le funzionalità di gestione utenti via email sono attive. I nuovi utenti riceveranno password generate automaticamente via email e potranno reimpostare la password tramite la funzione di recupero.",advancedAuthDisabled:"L'autenticazione avanzata è disabilitata",advancedAuthDisabledDesc:"Abilita l'autenticazione avanzata per attivare le funzionalità email per la gestione utenti.",enable:"Abilita",disable:"Disabilita",feature1:"Le password vengono generate automaticamente e inviate via email ai nuovi utenti",feature2:"Gli utenti possono accedere con nome utente o email",feature3:"La funzione di recupero password è disponibile",feature4:"Gli amministratori possono reimpostare le password utente via email",errors:{requiredFields:"Compilare tutti i campi obbligatori",usernameRequired:"Il nome utente è obbligatorio quando l'autenticazione è abilitata",enterTestEmail:"Inserire un indirizzo email di test",smtpServerAndEmail:"Compilare Server SMTP e Email mittente prima di testare",usernamePasswordRequired:"Nome utente e password sono obbligatori quando l'autenticazione è abilitata",configureSmtpFirst:"Configurare e testare le impostazioni SMTP prima",enableAuthFirst:"Per utilizzare le funzionalità basate sulla posta elettronica, è necessario prima abilitare l'autenticazione."},success:{settingsSaved:"Impostazioni SMTP salvate con successo"},securityOptions:{starttls:"STARTTLS (Porta 587)",ssl:"SSL/TLS (Porta 465)",none:"Nessuna (Porta 25)"},authOptions:{enabled:"Abilitata",disabled:"Disabilitata"}},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",userNotificationsEnabled:"Notifiche utente",userNotificationsEnabledDescription:"Abilita il menu notifiche utente e le notifiche e-mail per gli eventi di stampa. Richiede l'autenticazione avanzata.",userNotificationsDisabledHint:"Abilita l'autenticazione avanzata per usare le notifiche utente.",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"},filamentTracking:"Tracciamento filamento",filamentTrackingDesc:"Scegli come tracciare le bobine di filamento. Puoi usare l'inventario integrato o collegare un server Spoolman esterno.",filamentChecks:"Controlli filamento",disableFilamentWarnings:"Disabilita avvisi filamento",disableFilamentWarningsDesc:"Non mostrare avvisi per filamento insufficiente durante la stampa o l'accodamento",preferLowestFilament:"Preferisci il filamento con meno residuo",preferLowestFilamentDesc:"Quando più bobine corrispondono, usa quella con meno filamento rimanente",trackingModeBuiltIn:"Inventario integrato",trackingModeBuiltInDesc:"Riconoscimento RFID automatico e tracciamento dell'uso inclusi",trackingModeSpoolmanDesc:"Server esterno per la gestione del filamento",builtInFeatureRfid:"Rileva automaticamente le bobine Bambu Lab RFID nell'AMS",builtInFeatureUsage:"Traccia il consumo di filamento per stampa",builtInFeatureCatalog:"Gestisci bobine, colori e profili K-factor",builtInFeatureThirdParty:"Le bobine di terze parti possono essere assegnate alle bobine dell'inventario",amsSyncButton:"Sincronizza pesi dall'AMS",amsSyncTitle:"Sincronizza pesi bobine dall'AMS",amsSyncMessage:"Questo sovrascriverà tutti i pesi delle bobine dell'inventario con i valori attuali di percentuale rimanente dell'AMS dalle stampanti connesse. Usa questa funzione per recuperare dati di peso corrotti. Le stampanti devono essere online.",amsSyncing:"Sincronizzazione...",amsSyncSuccess:"{{synced}} bobina/e sincronizzata/e, {{skipped}} saltata/e",amsSyncError:"Impossibile sincronizzare i pesi dall'AMS",spoolmanUrl:"URL Spoolman",spoolmanUrlHint:"URL del server Spoolman (es. http://localhost:7912)",spoolmanConnected:"Connesso",spoolmanDisconnected:"Disconnesso",status:"Stato",connect:"Connetti",disconnect:"Disconnetti",howSyncWorks:"Come funziona la sincronizzazione",syncInfoRfidOnly:"Solo le bobine ufficiali Bambu Lab con RFID vengono sincronizzate",syncInfoAutoCreate:"Le nuove bobine vengono create automaticamente in Spoolman alla prima sincronizzazione",syncInfoThirdPartySkipped:"Le bobine non Bambu Lab (terze parti, ricaricate) vengono saltate",linkingExistingSpools:"Collegamento bobine esistenti",linkingExistingSpoolsDesc:`Per collegare le bobine Spoolman esistenti all'AMS, passa il mouse su uno slot AMS e clicca "Collega a Spoolman".`,syncMode:"Modalità sincronizzazione",syncModeAuto:"Automatica",syncModeManual:"Solo manuale",syncModeAutoDesc:"I dati AMS si sincronizzano automaticamente quando vengono rilevate modifiche",syncModeManualDesc:"Sincronizzazione solo quando attivata manualmente",syncAmsData:"Sincronizza dati AMS",syncAmsDataDesc:"Sincronizza manualmente i dati AMS della stampante su Spoolman",allPrinters:"Tutte le stampanti",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)",fairAlsoDryingThreshold:"Questa soglia viene usata anche per attivare l'asciugatura automatica",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",defaultPrintOptions:"Opzioni di stampa predefinite",defaultPrintOptionsDescription:"Imposta i valori predefiniti per le opzioni di stampa. Possono essere modificati nella finestra di stampa.",defaultBedLevelling:"Livellamento piatto",defaultBedLevellingDesc:"Livellamento automatico del piatto prima della stampa",defaultFlowCali:"Calibrazione flusso",defaultFlowCaliDesc:"Calibra il flusso di estrusione",defaultVibrationCali:"Calibrazione vibrazioni",defaultVibrationCaliDesc:"Riduce gli artefatti di ringing",defaultLayerInspect:"Ispezione primo strato",defaultLayerInspectDesc:"Ispezione IA del primo strato",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Registra un video timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Conferma piatto libero",requirePlateClear:"Richiedi conferma piatto libero",requirePlateClearDescription:"Quando abilitato, lo scheduler attende la conferma per stampante che il piatto è libero prima di avviare le stampe in coda su stampanti con lavori completati. Disabilitare per flussi di lavoro in farm dove i piatti vengono verificati fisicamente.",gcodeInjection:"Iniezione G-code",gcodeInjectionDescription:`Configura G-code personalizzato da iniettare all'inizio e/o alla fine delle stampe per sistemi di stampa automatica come Farmloop, SwapMod, AutoClear e Printflow 3D. Gli snippet sono configurati per modello di stampante e applicati quando "Inietta G-code" è abilitato su un elemento della coda.`,gcodeInjectionNoPrinters:"Nessuna stampante trovata. Aggiungi stampanti per configurare gli snippet G-code.",gcodeStartLabel:"G-code iniziale",gcodeEndLabel:"G-code finale",gcodeStartPlaceholder:"G-code inserito prima dell'inizio della stampa...",gcodeEndPlaceholder:"G-code aggiunto dopo la fine della stampa...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Asciugatura automatica",queueDryingDescription:"Asciugare automaticamente il filamento AMS quando la stampante è inattiva tra le stampe in coda. Usa la soglia di umidità sopra.",queueDryingEnabled:"Abilita asciugatura automatica",queueDryingEnabledDescription:"Avvia l'asciugatura AMS automaticamente quando la stampante è inattiva e l'umidità supera la soglia",queueDryingBlock:"Attendi completamento asciugatura",queueDryingBlockDescription:"Blocca la coda di stampa fino al completamento dell'asciugatura. Se disattivato, le stampe hanno priorità.",ambientDryingEnabled:"Asciugatura ambientale",ambientDryingEnabledDescription:"Asciuga automaticamente il filamento sulle stampanti inattive quando l'umidità supera la soglia, anche senza stampe in coda.",dryingPresets:"Preset di asciugatura",dryingPresetsDescription:"Temperatura e durata per tipo di filamento. AMS 2 Pro usa temperature più basse, AMS-HT supporta temperature più alte.",dryingFilament:"Filamento",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",catalog:{spoolCatalog:"Catalogo bobine",spoolCatalogDescription:"Pesi delle bobine vuote per marca/tipo. Utilizzato per la ricerca automatica del peso quando si aggiungono bobine.",searchCatalog:"Cerca nel catalogo...",addNewEntry:"Aggiungi nuova voce",namePlaceholder:"Nome (es. Bambu Lab - Plastica)",weight:"Peso",type:"Tipo",default:"Predefinito",custom:"Personalizzato",noMatch:"Nessuna voce corrisponde alla ricerca",empty:"Nessuna voce nel catalogo",deleteEntry:"Elimina voce",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',resetCatalog:"Ripristina catalogo",resetConfirm:"Ripristinare il catalogo ai valori predefiniti? Tutte le voci personalizzate verranno rimosse.",loadFailed:"Impossibile caricare il catalogo bobine",nameWeightRequired:"Nome e peso sono obbligatori",entryAdded:"Voce aggiunta",addFailed:"Impossibile aggiungere la voce",entryUpdated:"Voce aggiornata",updateFailed:"Impossibile aggiornare la voce",entryDeleted:"Voce eliminata",deleteFailed:"Impossibile eliminare la voce",resetSuccess:"Catalogo ripristinato ai valori predefiniti",resetFailed:"Impossibile ripristinare il catalogo",exported:"{{count}} voci esportate",imported:"{{added}} voci importate ({{skipped}} saltate)",importFailed:"Impossibile importare: formato JSON non valido",exportTooltip:"Esporta catalogo in JSON",importTooltip:"Importa catalogo da JSON",resetTooltip:"Ripristina valori predefiniti",selectedCount:"{{count}} selezionati",deleteSelected:"Elimina selezionati",bulkDeleteConfirm:"Eliminare {{count}} voci?",bulkDeleted:"{{count}} voci eliminate",bulkDeleteFailed:"Impossibile eliminare le voci"},colorCatalog:{title:"Catalogo colori",description:"Colori del filamento per produttore/materiale. Utilizzato per la ricerca automatica del colore quando si aggiungono bobine.",searchColors:"Cerca colori...",allManufacturers:"Tutti i produttori",addNewColor:"Aggiungi nuovo colore",manufacturer:"Produttore",colorName:"Nome colore",hex:"Hex",materialOptional:"Materiale (opzionale)",showing:"Visualizzazione di {{filtered}} su {{total}} colori",noMatch:"Nessun colore corrisponde alla ricerca",empty:"Nessun colore nel catalogo",deleteColor:"Elimina colore",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',resetCatalog:"Ripristina catalogo colori",resetConfirm:"Ripristinare il catalogo ai valori predefiniti? Tutti i colori personalizzati verranno rimossi.",sync:"Sincronizza",starting:"Avvio...",syncTooltip:"Sincronizza da FilamentColors.xyz (2000+ colori, potrebbe richiedere un minuto)",loadFailed:"Impossibile caricare il catalogo colori",fieldsRequired:"Produttore, nome colore e colore hex sono obbligatori",colorAdded:"Colore aggiunto",addFailed:"Impossibile aggiungere il colore",colorUpdated:"Colore aggiornato",updateFailed:"Impossibile aggiornare il colore",colorDeleted:"Colore eliminato",deleteFailed:"Impossibile eliminare il colore",resetSuccess:"Catalogo colori ripristinato ai valori predefiniti",resetFailed:"Impossibile ripristinare il catalogo",syncUpToDate:"Già aggiornato ({{count}} colori verificati)",syncComplete:"{{added}} nuovi colori aggiunti ({{skipped}} già esistenti)",syncError:"Errore di sincronizzazione",syncFailed:"Impossibile sincronizzare da FilamentColors.xyz",exported:"{{count}} colori esportati",imported:"{{added}} colori importati ({{skipped}} saltati)",importFailed:"Impossibile importare: formato JSON non valido",selectedCount:"{{count}} selezionati",deleteSelected:"Elimina selezionati",bulkDeleteConfirm:"Eliminare {{count}} colori?",bulkDeleted:"{{count}} colori eliminati",bulkDeleteFailed:"Impossibile eliminare i colori"},dateFormat:"Formato data",dateFormatUs:"US (MM/GG/AAAA)",dateFormatEu:"EU (GG/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-GG)",timeFormat:"Formato ora",timeFormat12:"12 ore (3:30 PM)",timeFormat24:"24 ore (15:30)",defaultPrinter:"Stampante predefinita",defaultPrinterDescription:"Preseleziona questa stampante per upload, ristampe e altre operazioni.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Trascina gli elementi nella barra laterale per riordinare. Ripristina l'ordine predefinito qui.",setDefault:"Imposta predefinito",sidebarOrderSetDefaultHint:"Imposta predefinito applica l'ordine attuale del menu agli utenti che non hanno ancora personalizzato il proprio.",sidebarDefaultSet:"L'ordine predefinito del menu è stato impostato.",sidebarDefaultCleared:"Ordine predefinito del menu cancellato.",sidebarDefaultFailed:"Impossibile impostare l'ordine predefinito del menu.",reset:"Ripristina",darkMode:"Modalità scura",lightMode:"Modalità chiara",active:"(attivo)",background:"Sfondo",accent:"Accento",style:"Stile",bgNeutral:"Neutro",bgWarm:"Caldo",bgCool:"Freddo",bgOled:"OLED Nero",bgSlate:"Blu ardesia",bgForest:"Verde foresta",accentGreen:"Verde",accentTeal:"Verde acqua",accentBlue:"Blu",accentOrange:"Arancione",accentPurple:"Viola",accentRed:"Rosso",styleClassic:"Classico",styleGlow:"Luminoso",styleVibrant:"Vibrante",themeToggleHint:"Passa tra modalità scura e chiara con l'icona sole/luna nella barra laterale.",autoArchivePrints:"Archiviazione automatica stampe",autoArchiveDescription:"Salva automaticamente i file 3MF al completamento delle stampe",saveThumbnailsDescription:"Estrai e salva le immagini di anteprima dai file 3MF",captureFinishPhotoDescription:"Scatta una foto dalla fotocamera della stampante al completamento della stampa",ffmpegNotInstalled:"ffmpeg non installato",ffmpegRequired:"L'acquisizione dalla fotocamera richiede ffmpeg. Installalo tramite <brew>brew install ffmpeg</brew> (macOS) o <apt>apt install ffmpeg</apt> (Linux).",camera:"Fotocamera",cameraViewMode:"Modalità visualizzazione fotocamera",cameraOverlayDescription:"La fotocamera si apre in un overlay ridimensionabile sulla schermata principale",cameraWindowDescription:"La fotocamera si apre in una finestra separata del browser",externalCamerasDescription:"Configura fotocamere esterne per sostituire la fotocamera integrata della stampante. Supporta stream MJPEG, RTSP, snapshot HTTP e fotocamere USB (V4L2). Quando abilitata, la fotocamera esterna viene usata per la vista in diretta e le foto di completamento.",cameraPlaceholderUsb:"Percorso dispositivo (/dev/video0)",cameraPlaceholderUrl:"URL fotocamera (rtsp://... o http://...)",cameraTypeMjpeg:"Stream MJPEG",cameraTypeRtsp:"Stream RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Fotocamera USB (V4L2)",cameraRotation:"Rotazione",test:"Test",connected:"Connesso",disconnected:"Disconnesso",currency:"Valuta",defaultFilamentCost:"Costo filamento predefinito (per kg)",electricityCost:"Costo elettricità per kWh",energyDisplayMode:"Modalità visualizzazione energia",energyModePrintDescription:"La dashboard mostra la somma dell'energia usata durante le stampe",energyModeTotalDescription:"La dashboard mostra l'energia totale dalle prese smart",fileManager:"Gestore file",createArchiveEntry:"Crea voce archivio durante la stampa",createArchiveEntryDescription:"Quando si stampa dal gestore file, crea opzionalmente una voce di archivio",lowDiskSpaceWarning:"Avviso spazio disco insufficiente",lowDiskSpaceDescription:"Mostra avviso quando lo spazio disco scende sotto questa soglia",printerFirmware:"Firmware stampante",checkFirmwareDescription:"Controlla aggiornamenti firmware da Bambu Lab",bambuddySoftware:"Software Bambuddy",autoCheckDescription:"Controlla automaticamente nuove versioni all'avvio",checkNow:"Controlla ora",updateAvailableVersion:"Aggiornamento disponibile: v{{version}}",releaseNotes:"Note di rilascio",updateViaDocker:"Aggiorna tramite Docker Compose:",installUpdate:"Installa aggiornamento",latestVersionRunning:"Stai usando l'ultima versione",failedToCheckUpdates:"Controllo aggiornamenti fallito: {{error}}",backupRestore:"Backup e ripristino",backupRestoreDescription:"Esporta/importa impostazioni e configura backup GitHub",goToBackup:"Vai al backup",externalUrl:"URL esterno",externalUrlDescription:"L'URL esterno dove Bambuddy è accessibile. Usato per immagini di notifica e integrazioni esterne.",bambuddyUrl:"URL Bambuddy",externalUrlHint:"Includi protocollo e porta (es. http://192.168.1.100:8000)",ftpRetry:"Riprova FTP",ftpRetryDescription:"Riprova le operazioni FTP quando il WiFi della stampante è instabile. Si applica a download 3MF, upload stampe, download timelapse e aggiornamenti firmware.",autoRetryDescription:"Riprova automaticamente le operazioni FTP fallite",retryAttempts:"Tentativi di ripetizione",retryDelay:"Ritardo ripetizione",connectionTimeout:"Timeout connessione",time_one:"{{count}} volta",time_other:"{{count}} volte",second_one:"{{count}} secondo",second_other:"{{count}} secondi",nSeconds:"{{count}} secondi",increaseForWeakWifi:"Aumenta per stampanti con WiFi debole",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Connetti a Home Assistant per controllare le prese smart tramite l'API REST HA. Supporta entità switch, light, input_boolean e script.",homeAssistantUrl:"URL Home Assistant",longLivedAccessToken:"Token di accesso a lunga durata",haTokenHint:"Crea un token in HA: Profilo → Token di accesso a lunga durata → Crea token",connectionSuccessful:"Connessione riuscita",connectionFailed:"Connessione fallita",haConnectionSuccess:"Connesso con successo a Home Assistant.",haConnectionFailed:"Connessione a Home Assistant fallita.",mqttPublishing:"Pubblicazione MQTT",mqttDescription:"Pubblica eventi BamBuddy su un broker MQTT esterno per l'integrazione con Node-RED, Home Assistant e altri sistemi di automazione.",mqttEnableDescription:"Pubblica eventi su broker MQTT esterno",brokerHostname:"Hostname broker",port:"Porta",usernameOptional:"Nome utente (opzionale)",passwordOptional:"Password (opzionale)",topicPrefix:"Prefisso topic",topicPrefixHint:"I topic saranno: {{prefix}}/printers/<serial>/status, ecc.",prometheusMetrics:"Metriche Prometheus",prometheusEndpointDescription:"Esponi metriche stampante su <code>/api/v1/metrics</code> per monitoraggio Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (opzionale)",bearerTokenHint:"Se impostato, le richieste devono includere <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Stato connessione",metricsPrinterState:"Stato stampante (idle/printing/ecc)",metricsPrintProgress:"Progresso stampa 0-100%",metricsBedTemp:"Temperatura piatto",metricsNozzleTemp:"Temperatura ugello",metricsPrintsTotal:"Stampe totali per risultato",metricsMore:"...e altro (strati, ventole, coda, consumo filamento)",smartPlugsDescription:"Connetti prese smart (Tasmota o Home Assistant) per automatizzare il controllo dell'alimentazione e monitorare il consumo energetico delle stampanti.",allOn:"Tutte accese",allOff:"Tutte spente",addSmartPlug:"Aggiungi presa smart",energySummary:"Riepilogo energia",currentPower:"Potenza attuale",plugsOnline:"{{reachable}}/{{total}} prese online",today:"Oggi",yesterday:"Ieri",total:"Totale",enablePlugsForSummary:"Abilita le prese per vedere il riepilogo energia",addNotificationProvider:"Aggiungi",systemBadge:"(Sistema)",creating:"Creazione...",changing:"Modifica...",deleteUserAndItems:"Elimina utente E i suoi elementi",deleteUserKeepItems:"Elimina utente, mantieni elementi (diventeranno senza proprietario)",ok:"OK",twoFa:{totpTitle:"App Authenticator (TOTP)",totpDesc:"Usa un'app come Google Authenticator, Aegis o Authy.",emailOtpTitle:"OTP via e-mail",emailOtpDesc:"Invia un codice monouso a {{email}} al momento del login.",emailOtpNoEmail:"Aggiungi un indirizzo e-mail al tuo account per abilitare questo metodo.",addEmailFirst:"Il tuo account non ha un indirizzo e-mail. Chiedi a un amministratore di aggiungerne uno.",setupTotp:"Configura app Authenticator",setupAuthApp:"Configura app Authenticator",setupInstructions:"Scansiona il codice QR con la tua app authenticator, poi conferma con un codice.",manualEntry:"Impossibile scansionare? Inserisci questo segreto manualmente:",scannedContinue:"Codice scansionato — continua",enterCodeToConfirm:"Inserisci il codice a 6 cifre dalla tua app authenticator per confermare.",activate:"Attiva",disableTotp:"Disabilita Authenticator",disableConfirmHint:"Inserisci un codice TOTP valido o un codice di backup per disabilitare l'authenticator.",totpDisabled:"App Authenticator disabilitata.",emailOtpEnabled:"OTP via e-mail abilitato.",emailOtpDisabled:"OTP via e-mail disabilitato.",smtpRequired:"Configura e testa prima le impostazioni SMTP.",invalidCode:"Codice non valido. Riprova.",enableEmailOtp:"Abilita OTP via e-mail",disableEmailOtp:"Disabilita OTP via e-mail",emailSetupEnterCode:"È stato inviato un codice di verifica al tuo indirizzo e-mail. Inseriscilo qui sotto per confermare che possiedi questa casella di posta.",verifyAndEnable:"Verifica e abilita",emailDisablePasswordHint:"Inserisci la password del tuo account per confermare la disabilitazione dell'OTP via e-mail.",passwordPlaceholder:"Inserisci la tua password",backupCodesTitle:"Salva i tuoi codici di backup",backupCodesWarning:"Conserva questi codici in un posto sicuro. Ogni codice può essere usato una sola volta.",backupCodesRemaining:"{{count}} codici di backup rimanenti",savedCodes:"Codici salvati",regenBackup:"Rigenera codici di backup",regenBackupHint:"Inserisci il tuo codice TOTP corrente per generare 10 nuovi codici di backup.",newBackupCodes:"Nuovi codici di backup",linkedAccounts:"Account SSO collegati",linkedAccountsDesc:"Questi provider di identità esterni sono collegati al tuo account.",oidcUnlinked:"Account scollegato."},oidc:{title:"Provider SSO / OIDC",desc:"Configura provider OpenID Connect per il single sign-on.",addProvider:"Aggiungi provider",newProvider:"Nuovo provider",empty:"Nessun provider OIDC configurato.",created:"Provider creato.",updated:"Provider aggiornato.",deleted:"Provider eliminato.",deleteTitle:"Elimina provider",deleteMessage:'Eliminare "{{name}}"? Tutti gli account collegati verranno disconnessi.',form:{name:"Nome visualizzato",issuerUrl:"URL emittente",clientId:"Client ID",clientSecret:"Client secret",scopes:"Scope",iconUrl:"URL icona (opzionale)",enabled:"Abilitato",autoCreate:"Crea utenti automaticamente",autoCreateDesc:"Crea automaticamente un account locale al primo accesso.",autoLink:"Collega automaticamente gli account esistenti",autoLinkDesc:"Collega gli account locali esistenti tramite email al primo accesso.",secretHint:"lascia vuoto per mantenere",secretPlaceholder:"nuovo segreto"}}},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",usernameOrEmail:"Nome utente o email",usernameOrEmailPlaceholder:"Nome utente o @ Email",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",enterEmail:"Inserisci il tuo indirizzo e-mail",oidcLoginFailed:"Accesso OIDC fallito",oidcErrors:{providerError:"Il provider di identità ha restituito un errore",missingParameters:"Parametri obbligatori mancanti nel callback OIDC",invalidState:"Lo stato OIDC non è valido o è già stato utilizzato",stateExpired:"La sessione OIDC è scaduta — riprovare",providerNotFound:"Provider OIDC non trovato",discoveryFailed:"Impossibile recuperare il documento di discovery OIDC",invalidDiscovery:"Il documento di discovery OIDC non è valido",networkError:"Errore di rete durante lo scambio di token OIDC",badResponse:"Risposta inattesa durante lo scambio di token OIDC",noIdToken:"Il provider OIDC non ha restituito un ID token",validationFailed:"La validazione del token OIDC non è riuscita",nonceMismatch:"Il nonce OIDC non corrisponde — possibile attacco di replay",missingSubClaim:"Il token OIDC è privo del claim sub",noLinkedAccount:"Nessun account locale è collegato a questa identità OIDC",accountInactive:"Il tuo account è inattivo",userResolutionFailed:"Impossibile risolvere il tuo account",internalError:"Si è verificato un errore interno durante il login OIDC",tokenExchangeFailed:"Lo scambio di token OIDC non è riuscito"},forgotPasswordTitle:"Password dimenticata",forgotPasswordMessage:"Se hai dimenticato la password, contatta il tuo amministratore di sistema per reimpostarla.",forgotPasswordEmailMessage:"Inserisci il tuo indirizzo email e ti invieremo una nuova password.",emailAddress:"Indirizzo email",emailPlaceholder:"tua.email@esempio.com",cancel:"Annulla",sending:"Invio...",sendResetEmail:"Invia email di reimpostazione",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",twoFA:{title:"Autenticazione a due fattori",subtitle:"Il tuo account è protetto da 2FA. Inserisci il codice di verifica qui sotto.",methodAuthenticator:"App di autenticazione",methodEmail:"Codice via e-mail",methodBackup:"Codice di recupero",instructionsTotp:"Apri la tua app di autenticazione e inserisci il codice a 6 cifre per Bambuddy.",instructionsEmail:"Un codice a 6 cifre è stato inviato al tuo indirizzo e-mail. È valido per 10 minuti.",instructionsEmailNotSent:"Clicca il pulsante qui sotto per ricevere un codice di verifica via e-mail.",instructionsBackup:"Inserisci uno dei tuoi codici di recupero a 8 caratteri. Ogni codice può essere utilizzato una sola volta.",sendCodeButton:"Invia codice via e-mail",sendingCode:"Invio in corso...",resendCode:"Invia nuovamente il codice",codeLabel:"Codice di verifica",backupCodeLabel:"Codice di recupero",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"Verifica",verifyingButton:"Verifica in corso...",backToLogin:"← Torna alla pagina di accesso",orContinueWith:"oppure accedi con",signInWith:"Accedi con {{provider}}",enterCode:"Inserisci il codice di verifica",sendCodeFailed:"Invio del codice di verifica non riuscito",invalidCode:"Codice non valido. Riprova."}},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",advancedAuthSubtitle:"con autenticazione avanzata"},form:{username:"Nome utente",usernamePlaceholder:"Inserisci nome utente",email:"Email",emailPlaceholder:"utente@esempio.com",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",optional:"opzionale",autoGeneratedPassword:"Una password sicura verrà generata automaticamente e inviata via email all'utente.",passwordManagedByAdvancedAuth:`La password è gestita dall'autenticazione avanzata. Usa "Reimposta password" per inviare una nuova password all'utente via email.`,resetPassword:"Reimposta password",resettingPassword:"Reimpostazione password..."},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:"Caricamento fallito",zipFilesFailed:"{{count}} file 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",linkExternal:"Collega esterno",linkExternalFolder:"Collega cartella esterna",linkExternalFolderDescription:"Monta una directory host (NAS, USB, condivisione di rete) nel File Manager. I file non vengono copiati — vengono letti direttamente dal percorso originale.",externalFolderNamePlaceholder:"es. Stampe NAS",externalPath:"Percorso host",externalPathHelp:"Percorso assoluto della directory sull'host Docker. Deve essere montato come bind nel container.",readOnly:"Sola lettura",readOnlyHelp:"impedisce caricamenti e cancellazioni",showHiddenFiles:"Mostra file nascosti (file punto)",externalFolder:"Cartella esterna",scanFolder:"Scansiona",toast:{folderCreated:"Cartella creata",folderDeleted:"Cartella eliminata",fileDeleted:"File eliminato",filesDeleted:"Eliminati {{count}} file",filesMoved:"File spostati",folderLinked:"Cartella collegata",folderUnlinked:"Cartella scollegata",externalFolderLinked:"Cartella esterna collegata e scansionata",folderScanned:"Scansione completata: {{added}} aggiunti, {{removed}} rimossi",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",totalCost:"Costo totale",total:"Totale",includesBom:"incl. distinta materiali",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.",noFiles:"Nessun file in questa cartella.",print:"Stampa ora",addToQueue:"Aggiungi alla coda"},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",unlinkConfirmTitle:"Scollegare bobina?",unlinkConfirmMessage:"Questo disconnetterà lo spool da Spoolman. I dati dello spool in Spoolman rimarranno invariati.",selectSpool:"Seleziona bobina",noUnlinkedSpools:"Nessuna bobina scollegata disponibile",linkSuccess:"Bobina collegata a Spoolman con successo",linkFailed:"Collegamento bobina fallito",unlinkSuccess:"Bobina scollegata da Spoolman con successo",unlinkFailed:"Impossibile scollegare la bobina",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",spoolName:"Bobina",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...",showAllSpools:"Mostra tutte le 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.",archiveConfirm:"Sei sicuro di voler archiviare questa bobina?",advancedSettings:"Impostazioni Avanzate",filamentInfoTab:"Info filamento",paProfileTab:"Profilo PA",filamentInfo:"Filamento",additional:"Aggiuntivo",loadingPresets:"Caricamento preset cloud...",cloudConnected:"Cloud connesso",cloudNotConnected:"Cloud non connesso (valori predefiniti)",recentColors:"Recenti",searchColors:"Cerca colori...",searchResults:"Risultati della ricerca",allColors:"Tutti i colori",commonColors:"Colori comuni",showLess:"Mostra meno",showAll:"Mostra tutto",noColorsFound:"Nessun colore corrisponde alla ricerca",noResults:"Nessun risultato trovato",selectMaterialFirst:"Selezionare prima un materiale nella scheda Info filamento.",noPrintersConfigured:"Nessuna stampante configurata. Aggiungi stampanti per usare i profili PA.",matchingFilter:"Corrispondenti",anyBrand:"Qualsiasi marca",anyVariant:"Qualsiasi variante",autoSelect:"Selezione automatica",matches:"corrispondenze",match:"corrispondenza",noMatches:"Nessuna corrispondenza",connected:"Connessa",offline:"Offline",printerOffline:"La stampante è offline. Connetti per visualizzare i profili di calibrazione.",noKProfilesMatch:"Nessun profilo K corrisponde al filamento selezionato.",leftNozzle:"Ugello sinistro",rightNozzle:"Ugello destro",profilesSelected:"profili di calibrazione selezionati",totalInventory:"Inventario totale",totalConsumed:"Totale consumato",byMaterial:"Per materiale",inPrinter:"In stampante",lowStock:"Scorta bassa",sinceTracking:"Dall'inizio del tracciamento",loadedInAms:"Caricato in AMS/Est",remaining:"Rimanente",weightCheck:"Controllo Peso",lastWeighed:"Ultima pesatura",neverWeighed:"Mai pesato",search:"Cerca bobine...",showing:"Visualizzazione",to:"a",of:"di",show:"Mostra",spools:"bobine",spool:"bobina",page:"Pagina",noSpoolsMatch:"Nessun risultato trovato",noSpoolsMatchDesc:"Prova a modificare la ricerca o i filtri per trovare quello che cerchi.",active:"Attive",archived:"Archiviate",all:"Tutte",used:"Usato",new:"Nuovo",clearFilters:"Cancella filtri",table:"Tabella",cards:"Schede",net:"Netto",groupSimilar:"Raggruppa",groupedSpools:"{{count}} bobine identiche",groupedRows:"righe",columns:"Colonne",configureColumns:"Configura colonne",configureColumnsDesc:"Trascina per riordinare le colonne o usa le frecce. Attiva/disattiva la visibilità con l'icona dell'occhio.",visible:"visibili",reset:"Ripristina",cancel:"Annulla",applyChanges:"Applica modifiche",moveUp:"Sposta su",moveDown:"Sposta giù",hideColumn:"Nascondi colonna",showColumn:"Mostra colonna",linkToSpool:"Collega a bobina",tagLinked:"Tag collegato alla bobina",tagLinkFailed:"Impossibile collegare il tag",tagAlreadyLinked:"Tag già collegato a un'altra bobina",unknownTag:"Tag RFID sconosciuto rilevato",usageHistory:"Cronologia utilizzo",noUsageHistory:"Nessun utilizzo registrato",printName:"Nome stampa",weightConsumed:"Peso consumato",clearHistory:"Cancella",historyCleared:"Cronologia utilizzo cancellata",fillSourceLabel:"(Inv)",lowStockThresholdError:"La soglia deve essere tra 0.1 e 99.9",assignMismatchTitle:"Materiale non corrispondente",assignMismatchMessage:'Il materiale della bobina selezionata "{{spoolMaterial}}" non corrisponde al materiale del vassoio "{{trayMaterial}}" per {{location}}. Assegnare comunque?',assignMismatchConfirm:"Assegna comunque",assignPartialMismatchMessage:'Il materiale della bobina "{{spoolMaterial}}" è simile ma non corrisponde esattamente a "{{trayMaterial}}" in {{location}}. Vuoi procedere?',assignProfileMismatchMessage:'Il profilo della bobina "{{spoolProfile}}" non corrisponde al profilo del vassoio "{{trayProfile}}" in {{location}}. Vuoi procedere?'},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:",slotRemainingShort:" - {{grams}}g rim.",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",sameTypeDifferentColor:"Stesso tipo, colore diverso",filamentTypeNotLoaded:"Tipo di filamento non caricato",openCalendar:"Apri calendario",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",insufficientFilamentTitle:"Filamento insufficiente",insufficientFilamentMessage:"Alcune bobine assegnate hanno meno filamento rimanente di quanto necessario per questa stampa:",insufficientFilamentLine:"{{printer}} - {{slot}}: necessita di {{required}}g, rimanenti {{remaining}}g",printAnyway:"Stampa comunque",forceColorMatch:"Forza corrispondenza colore",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Scagliona a {{count}} stampanti",gcodeInjection:"Inietta G-code auto-stampa"},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",githubBackup:"Backup GitHub",enabled:"Abilitato",cloudLoginRequired:"Accesso Bambu Cloud richiesto. Accedi in Profili → Profili Cloud per abilitare il backup GitHub.",cloudLoginRequiredShort:"Accesso Cloud richiesto",githubDescription:"Sincronizza automaticamente i tuoi profili con un repository GitHub privato per backup e cronologia delle versioni.",repositoryUrl:"URL del repository",personalAccessToken:"Token di accesso personale",tokenSaved:"(salvato)",enterNewToken:"Inserisci un nuovo token per aggiornare",tokenHint:"Token a grana fine con permesso di lettura/scrittura dei contenuti",branch:"Branch",manualOnly:"Solo manuale",hourly:"Ogni ora",daily:"Giornaliero",weekly:"Settimanale",includeInBackup:"Includi nel backup",kProfiles:"K-Profili",kProfilesDescription:"Calibrazione dell'avanzamento pressione dalle stampanti connesse",noPrintersConnected:"Nessuna stampante connessa",printersConnected:"{{connected}}/{{total}} connesse",cloudProfiles:"Profili Cloud",cloudProfilesDescription:"Preset di filamento, stampante e processo da Bambu Cloud",appSettings:"Impostazioni App",appSettingsDescription:"Configurazione Bambuddy (database completo)",spoolInventory:"Inventario bobine",spoolInventoryDescription:"Bobine di filamento, cronologia utilizzo e tracciamento costi",printArchives:"Archivi di stampa",printArchivesDescription:"Metadati della cronologia di stampa (nessun file gcode/3MF)",lastBackupAt:"Ultimo backup:",noBackupsYet:"Nessun backup ancora",next:"Prossimo:",startingBackup:"Avvio del backup...",test:"Test",enableBackup:"Abilita backup",testConnection:"Testa connessione",enterRepoUrl:"Inserisci l'URL del repository",enterRepoAndToken:"Inserisci l'URL del repository e il token di accesso",repoRequired:"L'URL del repository è obbligatorio",tokenRequired:"Il token di accesso è obbligatorio",githubBackupEnabled:"Backup GitHub abilitato",tokenUpdated:"Token aggiornato",settingsSaved:"Impostazioni salvate",failedToSave:"Salvataggio fallito: {{message}}",backupCompleteFiles:"Backup completato - {{count}} file aggiornati",backupSkippedNoChanges:"Backup saltato - nessuna modifica",backupFailed2:"Backup fallito: {{message}}",clearedLogs:"{{count}} log eliminati",failedToClearLogs:"Eliminazione log fallita: {{message}}",history:"Cronologia",clear:"Cancella",date:"Data",status:"Stato",commit:"Commit",localBackup:"Backup locale",localBackupDescription:"Crea un backup completo dei tuoi dati Bambuddy includendo database, archivi, upload e tutti i file.",downloadBackupLabel:"Scarica backup",completeBackupZip:"Backup completo: database + tutti i file (ZIP)",download:"Scarica",preparingBackup:"Preparazione del backup...",creatingArchive:"Creazione dell'archivio di backup... Potrebbe richiedere del tempo per archivi di grandi dimensioni.",downloadingFile:"Download del file di backup...",backupDownloaded:"Backup scaricato con successo",failedToCreateBackup:"Creazione del backup fallita: {{message}}",restore:"Ripristina",restoreReplacesAll:"Il ripristino sostituisce tutti i dati.",restoreReplacesAllDetail:"Il database e i file attuali verranno completamente sostituiti. È necessario un riavvio dopo il ripristino.",restoreConfirmTitle:"Ripristina backup",restoreConfirmMessage:`Sei sicuro di voler ripristinare da "{{filename}}"? Questo sostituirà completamente il tuo database e tutti i file. L'applicazione dovrà essere riavviata dopo il ripristino.`,restoreConfirmButton:"Ripristina backup",uploadingFile:"Caricamento del file di backup...",backupRestoredRestart:"Backup ripristinato. Riavvia Bambuddy.",failedToRestore:"Ripristino del backup fallito. Controlla il formato del file.",reloadNow:"Ricarica ora",creatingBackup:"Creazione del backup",restoringBackup:"Ripristino del backup",preparing:"Preparazione...",processing:"Elaborazione...",doNotClosePage:"Non chiudere questa pagina e non navigare altrove. Questa operazione potrebbe richiedere diversi minuti per backup di grandi dimensioni.",restoring:"Ripristino in corso...",restoreComplete:"Ripristino completato",restoreFailed2:"Ripristino fallito",importSettings:"Importa impostazioni da un file di backup",pleaseWaitRestoring:"Attendere durante il ripristino dei dati",selectBackupFile:"Clicca per selezionare un file di backup (.json o .zip)",duplicateHandling:"Come funziona la gestione dei duplicati:",matchPrinters:"Stampanti",matchPrintersBy:"corrispondenza per numero di serie",matchSmartPlugs:"Smart Plug",matchSmartPlugsBy:"corrispondenza per indirizzo IP",matchNotificationProviders:"Provider di notifica",matchNotificationProvidersBy:"corrispondenza per nome",matchFilaments:"Filamenti",matchFilamentsBy:"corrispondenza per nome + tipo + marca",matchArchives:"Archivi",matchArchivesBy:"corrispondenza per hash del contenuto (sempre saltato)",matchPendingUploads:"Upload in sospeso",matchPendingUploadsBy:"corrispondenza per nome file",matchSettingsTemplates:"Impostazioni e modelli",matchSettingsTemplatesBy:"sempre sovrascritti",replaceExisting:"Sostituisci dati esistenti",keepExisting:"Mantieni dati esistenti",overwriteDescription:"Sovrascrivi gli elementi già esistenti con i dati del backup",keepDescription:"Ripristina solo gli elementi che non esistono ancora",overwriteCaution:"Attenzione:",overwriteWarning:"La sovrascrittura sostituirà le configurazioni attuali con i dati del backup. I codici di accesso delle stampanti non vengono mai sovrascritti per sicurezza.",cancel:"Annulla",processingBackup:"Elaborazione del file di backup...",itemsRestored:"Elementi ripristinati",itemsSkipped:"Elementi saltati",restored:"Ripristinati",skippedAlreadyExist:"Saltati (già esistenti)",filesCategory:"File (3MF, miniature, ecc.)",andMore:"...e altri {{count}}",newApiKeysGenerated:"Nuove chiavi API generate",keysShownOnce:"Queste chiavi vengono mostrate solo una volta. Copiale ora!",copy:"Copia",noDataFound:"Nessun dato da ripristinare trovato nel file di backup.",close:"Chiudi",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"Impostazioni",notification_providers:"Provider di notifica",notification_templates:"Modelli di notifica",smart_plugs:"Smart Plug",printers:"Stampanti",filaments:"Filamenti",maintenance_types:"Tipi di manutenzione",archives:"Archivi",projects:"Progetti",pending_uploads:"Upload in sospeso",external_links:"Link esterni",api_keys:"Chiavi API"}},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."},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"},autoDispatch:{title:"Avvio automatico",description:"Avvia automaticamente le stampe aggiunte alla coda. Se disattivato, le stampe attendono l'avvio manuale."},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",bindIpRequired:"Impostare prima un indirizzo IP",accessCodeEmpty:"Il codice accesso non può essere vuoto",accessCodeLength:"Il codice accesso deve essere esattamente 8 caratteri",created:"Stampante virtuale creata",failedToCreate:"Impossibile creare la stampante virtuale",deleted:"Stampante virtuale eliminata",failedToDelete:"Impossibile eliminare la stampante virtuale"},list:{title:"Stampanti virtuali",add:"Aggiungi",addFirst:"Aggiungi stampante virtuale",empty:"Nessuna stampante virtuale configurata. Aggiungine una per iniziare."},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."},addDialog:{title:"Aggiungi stampante virtuale",name:"Nome",hint:"Potrai configurare il codice di accesso, la stampante di destinazione e altre impostazioni dopo la creazione.",create:"Crea"},deleteConfirm:{title:"Elimina stampante virtuale",message:'Sei sicuro di voler eliminare "{{name}}"? Tutti i servizi di questa stampante verranno interrotti.'}},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",lubricateSteelRods:"Applica lubrificante alle aste in acciaio per un movimento fluido",cleanSteelRods:"Pulisci le aste in acciaio 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)"},smartPlugs:{offline:"Offline",admin:"Amministrazione",openPlugAdminPage:"Apri pagina amministrazione presa",deleteSmartPlug:"Elimina presa smart",turnOnSmartPlug:"Accendi presa smart",turnOffSmartPlug:"Spegni presa smart",turnOn:"Accendi",turnOff:"Spegni",addSmartPlug:{scanningNetwork:"Scansione rete...",chooseEntity:"Scegli un'entità...",connectionFailed:"Connessione fallita",searchEntities:"Cerca entità...",searchPowerSensors:"Cerca sensori di potenza...",searchEnergySensors:"Cerca sensori di energia...",placeholders:{plugName:"Presa soggiorno",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Stesso del topic potenza, o diverso"}},linkedTo:"Collegato a:",monitorOnly:"Solo monitoraggio",alerts:"Avvisi",scheduleOn:"On {{time}}",scheduleOff:"Off {{time}}",on:"On",off:"Off",power:"Potenza",kwhToday:"kWh Oggi",settings:"Impostazioni",automationSettings:"Impostazioni automazione",showInSwitchbar:"Mostra nella barra interruttori",quickAccessSidebar:"Accesso rapido dalla barra laterale",enabled:"Abilitato",enableAutomation:"Abilita automazione per questa presa",autoOn:"Auto On",autoOnDescription:"Accendi quando inizia la stampa",autoOff:"Auto Off",autoOffDescription:"Spegni quando la stampa è completata (una tantum)",autoOffPersistent:"Mantieni attivo",autoOffPersistentDescription:"Resta attivo tra le stampe invece di una tantum",turnOffDelayMode:"Modalità ritardo spegnimento",time:"Tempo",temp:"Temp",delayMinutes:"Ritardo (minuti)",tempThreshold:"Soglia temperatura (°C)",tempThresholdDescription:"Si spegne quando l'ugello si raffredda sotto questa temperatura",edit:"Modifica",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"? Questa azione non può essere annullata.',turnOnConfirm:'Sei sicuro di voler accendere "{{name}}"?',turnOffConfirm:`Sei sicuro di voler spegnere "{{name}}"? Questo interromperà l'alimentazione del dispositivo collegato.`,failedToTurn:'Impossibile {{action}} "{{name}}"',unknown:"Sconosciuto",addTitle:"Aggiungi presa smart",editTitle:"Modifica presa smart",stopScanning:"Interrompi scansione",discoverTasmota:"Scopri dispositivi Tasmota",foundDevices:"{{count}} dispositivo/i trovato/i - clicca per selezionare:",noDevicesFound:"Nessun dispositivo Tasmota trovato nella rete",haNotConfigured:"Home Assistant non è configurato. Configuralo in",haSettingsPath:"Impostazioni → Rete → Home Assistant",selectEntity:"Seleziona entità *",ipAddress:"Indirizzo IP *",nameLabel:"Nome *",username:"Nome utente",password:"Password",authHint:"Lascia vuoto se il tuo dispositivo Tasmota non richiede autenticazione",linkToPrinter:"Collega alla stampante",noPrinter:"Nessuna stampante (solo controllo manuale)",linkingDescription:"Il collegamento abilita accensione/spegnimento automatico all'inizio/fine stampa",powerAlerts:"Avvisi potenza",alertAbove:"Avviso se sopra (W)",alertBelow:"Avviso se sotto (W)",alertDescription:"Ricevi notifiche quando il consumo supera queste soglie. Lascia vuoto per disabilitare quella direzione.",dailySchedule:"Programma giornaliero",turnOnAt:"Accendi alle",turnOffAt:"Spegni alle",scheduleDescription:"Accendi/spegni automaticamente la presa a questi orari ogni giorno. Lascia vuoto per saltare quell'azione.",showOnPrinterCard:"Mostra sulla scheda stampante",displayOnPrinterCard:"Mostra pulsante sulla scheda stampante",connectedResult:"Connesso!",deviceLabel:"Dispositivo: {{name}} - ",stateLabel:"Stato: {{state}}",test:"Test",delete:"Elimina",save:"Salva",add:"Aggiungi",cancel:"Annulla",failedToStartScan:"Impossibile avviare la scansione",nameRequired:"Il nome è obbligatorio",entityRequired:"L'entità è obbligatoria per le prese Home Assistant",mqttTopicRequired:"Almeno un topic MQTT deve essere configurato per potenza, energia o monitoraggio stato",loadingEntities:"Caricamento entità...",loading:"Caricamento...",failedToLoadEntities:"Impossibile caricare le entità: {{error}}",noEntitiesMatching:'Nessuna entità trovata corrispondente a "{{search}}"',noEntitiesAvailable:"Nessuna entità disponibile",searchingEntities:"Ricerca in tutte le entità ({{count}} trovate)",showingEntities:"Mostrando switch, light, input_boolean ({{count}} disponibili)",energyMonitoringOptional:"Monitoraggio energia (Opzionale)",energyMonitoringHint:"Cerca e seleziona i sensori che forniscono dati di potenza/energia.",powerSensorW:"Sensore potenza (W)",energyTodayKwh:"Energia oggi (kWh)",totalEnergyKwh:"Energia totale (kWh)",noMatchingSensors:"Nessun sensore corrispondente",none:"Nessuno",mqttNotConfigured:"Broker MQTT non configurato. Imposta l'indirizzo del broker in",mqttSettingsPath:"Impostazioni → Rete → Pubblicazione MQTT",mqttNotConfiguredSuffix:"(non è necessario abilitare la pubblicazione, basta inserire i dettagli del broker).",mqttMonitorOnlyDescription:"Le prese MQTT ricevono dati di potenza/energia tramite sottoscrizione MQTT. Il controllo on/off non è disponibile - usa il tuo broker MQTT o sistema domotico.",powerMonitoring:"Monitoraggio potenza",energyMonitoring:"Monitoraggio energia",stateMonitoring:"Monitoraggio stato",optional:"opzionale",topic:"Topic",jsonPath:"Percorso JSON",multiplier:"Moltiplicatore",onValue:"Valore ON",mqttPowerHint:`Il percorso JSON estrae il valore dal payload JSON (es. "power_l1"). Lascia vuoto se il topic pubblica valori numerici grezzi.
- Usa moltiplicatore 0.001 per mW→W, 1000 per kW→W.`,mqttEnergyHint:`Il percorso JSON estrae il valore dal payload JSON. Lascia vuoto per valori grezzi.
- Usa moltiplicatore 0.001 per Wh→kWh, 1000 per MWh→kWh.`,mqttStateHint:`Il percorso JSON estrae il valore dal payload JSON. Lascia vuoto per valori grezzi.
- Valore ON: la stringa esatta che significa "ON". Lascia vuoto per rilevamento auto (ON, true, 1).`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL potenza",restPowerPath:"Power JSON Path",restPowerMultiplier:"Moltiplicatore potenza",restEnergyUrl:"URL energia",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Moltiplicatore energia",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL separato per i dati di potenza (usa l'URL di stato se vuoto)",restEnergyUrlHint:"URL separato per i dati di energia (usa l'URL di stato se vuoto)",restEnergyHint:"Ogni valore può usare il proprio URL o ricadere sull'URL di stato. Usa i moltiplicatori per la conversione delle unità (es. 0.001 per convertire Wh in kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Nessun interruttore nella barra",enableSwitchbarHint:'Abilita "Mostra nella barra interruttori" in Impostazioni > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notifiche email tramite SMTP",telegram:"Notifiche tramite bot Telegram",discord:"Invia a un canale Discord tramite webhook",ntfy:"Notifiche push gratuite e self-hostabili",pushover:"Notifiche push semplici e affidabili",callmebot:"Notifiche WhatsApp gratuite tramite CallMeBot",webhook:"POST HTTP generico verso qualsiasi URL",homeassistant:"Notifiche persistenti nella dashboard di Home Assistant"},lastSuccess:"Ultimo: {{date}}",error:"Errore",printer:"Stampante:",allPrinters:"Tutte le stampanti",sendTestNotification:"Invia notifica di prova",eventSettings:"Impostazioni eventi",enabled:"Abilitato",sendFromProvider:"Invia notifiche da questo provider",printEvents:"Eventi di stampa",printerStatus:"Stato stampante",amsAlarms:"Allarmi AMS",amsHtAlarms:"Allarmi AMS-HT",printQueue:"Coda di stampa",start:"Avvio",plateCheck:"Controllo piatto",complete:"Completato",failed:"Fallito",stopped:"Interrotto",progress:"Avanzamento",offline:"Offline",lowFilament:"Filamento scarso",maintenance:"Manutenzione",amsHumidity:"Umidità AMS",amsTemp:"Temp AMS",amsHtHumidity:"Umidità AMS-HT",amsHtTemp:"Temp AMS-HT",bedCooled:"Piatto raffreddato",firstLayer:"Primo strato",quiet:"Silenzioso",digest:"Riepilogo {{time}}",printStarted:"Stampa avviata",plateNotEmpty:"Piatto non vuoto",plateNotEmptyDescription:"Oggetti rilevati prima della stampa",printCompleted:"Stampa completata",bedCooledLabel:"Piatto raffreddato",bedCooledDescription:"Piatto raffreddato sotto la soglia dopo la stampa",firstLayerCompleteLabel:"Primo strato completato",firstLayerCompleteDescription:"Notifica con foto al termine del primo strato",missingSpoolAssignmentLabel:"Assegnazione bobina mancante",missingSpoolAssignmentDescription:"Notifica quando una stampa parte e i vassoi richiesti non hanno una bobina assegnata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",progressMilestones:"Traguardi di avanzamento",progressMilestonesDescription:"Notifica al 25%, 50%, 75%",printerOffline:"Stampante offline",printerError:"Errore stampante",lowFilamentLabel:"Filamento scarso",maintenanceDue:"Manutenzione necessaria",maintenanceDueDescription:"Notifica quando è necessaria la manutenzione",amsHumidityHigh:"Umidità AMS elevata",amsHumidityHighDescription:"L'umidità dell'AMS standard supera la soglia",amsTemperatureHigh:"Temperatura AMS elevata",amsTemperatureHighDescription:"La temperatura dell'AMS standard supera la soglia",amsHtHumidityHigh:"Umidità AMS-HT elevata",amsHtHumidityHighDescription:"L'umidità dell'AMS-HT supera la soglia",amsHtTemperatureHigh:"Temperatura AMS-HT elevata",amsHtTemperatureHighDescription:"La temperatura dell'AMS-HT supera la soglia",jobAdded:"Lavoro aggiunto",jobAddedDescription:"Lavoro aggiunto alla coda",jobAssigned:"Lavoro assegnato",jobAssignedDescription:"Lavoro basato su modello assegnato alla stampante",jobStarted:"Lavoro avviato",jobStartedDescription:"Lavoro in coda avviato per la stampa",jobWaiting:"Lavoro in attesa",jobWaitingDescription:"Lavoro in attesa di filamento o stampante",jobSkipped:"Lavoro saltato",jobSkippedDescription:"Lavoro saltato (precedente fallito)",jobFailed:"Lavoro fallito",jobFailedDescription:"Avvio del lavoro fallito",queueComplete:"Coda completata",queueCompleteDescription:"Tutti i lavori in coda completati",quietHours:"Ore silenziose",noNotificationsDuring:"Nessuna notifica durante queste ore",editProviderToChangeQuietHours:"Modifica il provider per cambiare le ore silenziose",dailyDigest:"Riepilogo giornaliero",batchNotifications:"Raggruppa le notifiche in un unico riepilogo giornaliero",sendAt:"Invia alle {{time}}",editProviderToChangeDigestTime:"Modifica il provider per cambiare l'orario del riepilogo",edit:"Modifica",deleteProvider:"Elimina provider di notifica",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"? Questa azione non può essere annullata.',delete:"Elimina",addTitle:"Aggiungi provider di notifica",editTitle:"Modifica provider di notifica",nameLabel:"Nome *",namePlaceholder:"Le mie notifiche",providerTypeLabel:"Tipo di provider *",configuration:"Configurazione",testConfiguration:"Testa configurazione",printerFilter:"Filtro stampante",onlyFromPrinter:"Invia notifiche solo per eventi da questa stampante",quietHoursDnd:"Ore silenziose (Non disturbare)",quietStart:"Inizio",quietEnd:"Fine",dailyDigestLabel:"Riepilogo giornaliero",sendDigestAt:"Invia riepilogo alle",digestCollected:"Gli eventi verranno raccolti e inviati come riepilogo unico a quest'ora",notificationEvents:"Eventi di notifica",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(dopo il completamento della stampa)",cancel:"Annulla",save:"Salva",add:"Aggiungi",nameRequired:"Il nome è obbligatorio",fieldRequired:"{{field}} è obbligatorio",phoneNumber:"Numero di telefono",apiKey:"Chiave API",serverUrl:"URL del server",topic:"Argomento",authToken:"Token di autenticazione",userKey:"Chiave utente",appToken:"Token applicazione",priority:"Priorità",botToken:"Token del bot",chatId:"ID chat",smtpServer:"Server SMTP",smtpPort:"Porta SMTP",security:"Sicurezza",authentication:"Autenticazione",username:"Nome utente",password:"Password",fromEmail:"Email mittente",toEmail:"Email destinatario",webhookUrl:"URL webhook",payloadFormat:"Formato payload",authorization:"Autorizzazione",titleFieldName:"Nome campo titolo",messageFieldName:"Nome campo messaggio",editTemplate:"Modifica modello: {{name}}",titleLabel:"Titolo",bodyLabel:"Corpo",titlePlaceholder:"Titolo della notifica...",bodyPlaceholder:"Corpo della notifica...",availableVariables:"Variabili disponibili",clickToInsert:"Clicca per inserire alla posizione del cursore nel corpo",livePreview:"Anteprima live",hide:"Nascondi",show:"Mostra",loadingPreview:"Caricamento anteprima...",enterTemplateContent:"Inserisci il contenuto del modello per vedere l'anteprima",titlePreview:"Titolo:",bodyPreview:"Corpo:",resetToDefault:"Ripristina predefinito",titleRequired:"Il titolo è obbligatorio",bodyRequired:"Il corpo è obbligatorio",notificationLog:"Registro notifiche",showFailedOnly:"Solo fallite",last24Hours:"Ultime 24 ore",last7Days:"Ultimi 7 giorni",last30Days:"Ultimi 30 giorni",last90Days:"Ultimi 90 giorni",justNow:"Proprio ora",noFailedNotifications:"Nessuna notifica fallita",noNotificationsLogged:"Nessuna notifica registrata",unknownProvider:"Provider sconosciuto",logTitle:"Titolo",logMessage:"Messaggio",logError:"Errore",logProvider:"Provider: {{type}}",logTime:"Ora: {{time}}",refresh:"Aggiorna",clearOld:"Cancella vecchie",statsSummary:"Ultimi {{days}} giorni:",statsNotifications:"notifiche",statsSent:"{{count}} inviate",statsFailed:"{{count}} fallite",eventTypes:{print_start:"Stampa avviata",print_complete:"Stampa completata",print_failed:"Stampa fallita",print_stopped:"Stampa interrotta",print_progress:"Avanzamento",printer_offline:"Stampante offline",printer_error:"Errore stampante",filament_low:"Filamento scarso",maintenance_due:"Manutenzione necessaria",test:"Prova"},userEmail:{title:"Notifiche",emailNotifications:"Notifiche via e-mail",emailNotificationsDesc:"Ricevi notifiche via e-mail per i tuoi lavori di stampa. Le e-mail vengono inviate tramite le impostazioni SMTP configurate nell'autenticazione avanzata.",sendingTo:"Le notifiche verranno inviate a",noEmailWarning:"Il tuo account non ha un indirizzo e-mail. Contatta un amministratore per aggiungerne uno.",printJobNotifications:"Notifiche lavori di stampa",printJobNotificationsDesc:"Scegli quali eventi attivano le notifiche e-mail per i lavori di stampa che invii.",printJobStarts:"Inizio lavoro di stampa",printJobStartsDesc:"Ricevi una notifica quando il tuo lavoro di stampa inizia.",printJobFinishes:"Fine lavoro di stampa",printJobFinishesDesc:"Ricevi una notifica quando il tuo lavoro di stampa si completa correttamente.",printErrors:"Errori di stampa",printErrorsDesc:"Ricevi una notifica quando il tuo lavoro di stampa fallisce o incontra un errore.",printJobStops:"Lavoro di stampa interrotto",printJobStopsDesc:"Ricevi una notifica quando il tuo lavoro di stampa viene annullato o interrotto.",saveSuccess:"Preferenze di notifica salvate.",saveError:"Impossibile salvare le preferenze di notifica."}},richTextEditor:{bold:"Grassetto",italic:"Corsivo",underline:"Sottolineato",bulletList:"Elenco puntato",numberedList:"Elenco numerato",alignLeft:"Allinea a sinistra",alignCenter:"Allinea al centro",alignRight:"Allinea a destra",addLink:"Aggiungi link",removeLink:"Rimuovi link"},externalLinks:{noLinksConfigured:"Nessun link esterno configurato",deleteLink:"Elimina link",removeCustomIcon:"Rimuovi icona personalizzata",openInNewTab:"Apri in nuova scheda",placeholders:{linkName:"Il mio link"}},keyboardShortcuts:{title:"Scorciatoie da tastiera",navigation:"Navigazione",archivesSection:"Archivi",kProfilesSection:"Profili K",generalSection:"Generale",shortcuts:{goToPrinters:"Vai a Stampanti",goToArchives:"Vai ad Archivi",goToQueue:"Vai a Coda",goToStats:"Vai a Statistiche",goToProfiles:"Vai a Profili cloud",goToSettings:"Vai a Impostazioni",focusSearch:"Vai alla ricerca",openUploadModal:"Apri finestra di caricamento",clearSelection:"Cancella selezione / deseleziona input",contextMenu:"Menu contestuale sulle schede",refreshProfiles:"Aggiorna profili",newProfile:"Nuovo profilo",exitSelectionMode:"Esci dalla modalità selezione",showHelp:"Mostra questa guida"},footer:"Premi Esc o clicca fuori per chiudere"},notificationLog:{title:"Registro notifiche",events:{printStarted:"Stampa avviata",printComplete:"Stampa completata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",progress:"Avanzamento",printerOffline:"Stampante offline",printerError:"Errore stampante",lowFilament:"Filamento in esaurimento",maintenanceDue:"Manutenzione in scadenza",test:"Test"},timeAgo:{justNow:"Adesso",minutesAgo:"{{minutes}} min fa",hoursAgo:"{{hours}} ore fa"}},restoreBackup:{title:"Ripristina backup",restoring:"Ripristino...",restoreComplete:"Ripristino completato",restoreFailed:"Ripristino fallito",importSettings:"Importa impostazioni da un file di backup",pleaseWait:"Attendere il ripristino dei dati",clickToSelect:"Clicca per selezionare il file di backup (.json o .zip)",howDuplicateHandling:"Come funziona la gestione dei duplicati:",categories:{printers:"Stampanti",smartPlugs:"Prese smart",notificationProviders:"Provider di notifica",filaments:"Filamenti",archives:"Archivi",pendingUploads:"Caricamenti in sospeso",settingsTemplates:"Impostazioni e modelli"},matchingInfo:{printers:"abbinati per numero di serie",smartPlugs:"abbinati per indirizzo IP",notificationProviders:"abbinati per nome",filaments:"abbinati per nome + tipo + marca",archives:"abbinati per hash del contenuto",pendingUploads:"abbinati per nome file",settingsTemplates:"sempre sovrascritti"},replaceExisting:"Sostituisci dati esistenti",keepExisting:"Mantieni dati esistenti",replaceDescription:"Sovrascrivi gli elementi già esistenti con i dati del backup",keepDescription:"Ripristina solo gli elementi che non esistono già",caution:"Attenzione:",cautionText:"La sovrascrittura sostituirà le configurazioni attuali con i dati del backup. I codici di accesso delle stampanti non vengono mai sovrascritti per sicurezza.",itemsRestored:"Elementi ripristinati",itemsSkipped:"Elementi saltati",restored:"Ripristinati",skipped:"Saltati (già esistenti)",filesLabel:"File (3MF, miniature, ecc.)",newApiKeysGenerated:"Nuove chiavi API generate",newApiKeysWarning:"Queste chiavi vengono mostrate una sola volta. Copiale adesso!",processingBackup:"Elaborazione file di backup...",noDataFound:"Nessun dato trovato da ripristinare nel file di backup.",failedToRestore:"Impossibile ripristinare il backup. Verificare il formato del file."},backupExport:{title:"Esporta backup",selectData:"Seleziona i dati da includere",selectAll:"Seleziona tutto",selectNone:"Deseleziona tutto",categoryDescriptions:{settings:"Lingua, tema, preferenze di aggiornamento",notifications:"ntfy, Pushover, Discord, ecc.",templates:"Modelli di messaggi personalizzati",smartPlugs:"Configurazioni prese Tasmota",externalLinks:"Link della barra laterale a servizi esterni",printers:"Info stampanti (codici di accesso esclusi)",plateDetection:"Immagini di riferimento piatto vuoto",filaments:"Tipi di filamento e costi",maintenance:"Programmi di manutenzione personalizzati",archives:"Tutti i dati di stampa + file (3MF, miniature, foto)",projects:"Progetti, elementi BOM e allegati",pendingUploads:"Caricamenti della stampante virtuale in attesa di revisione",apiKeys:"Chiavi API webhook (nuove chiavi generate all'importazione)"},requiresPrinters:"Richiede la selezione di Stampanti",zipFileWarning:"Verrà creato un file ZIP.",zipFileDescription:"Include tutti i file 3MF, miniature, timelapse e foto. Potrebbe richiedere tempo e produrre un file di grandi dimensioni.",includeAccessCodes:"Includi codici di accesso",includeAccessCodesDescription:"Per il trasferimento su un'altra macchina",includeAccessCodesWarning:"I codici di accesso saranno inclusi in testo semplice. Mantieni sicuro questo file di backup!",categoriesSelected:"{{selectedCount}} categorie selezionate"},pendingUploads:{placeholders:{notes:"Aggiungi note su questa stampa..."},discardUpload:"Scarta caricamento",archiveAllUploads:"Archivia tutti i caricamenti",discardAllUploads:"Scarta tutti i caricamenti",archive:"Archivia",timeAgo:{justNow:"Adesso",minutesAgo:"{{minutes}} min fa",hoursAgo:"{{hours}} ore fa",daysAgo:"{{days}} giorni fa"}},apiBrowser:{placeholders:{requestBody:"Corpo della richiesta JSON...",searchEndpoints:"Cerca endpoint..."}},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"},githubBackup:{title:"Backup GitHub",history:"Cronologia",downloadBackup:"Scarica backup",restoreBackup:"Ripristina backup",noBackupsYet:"Nessun backup ancora"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Cerca tag...",renameTag:"Rinomina tag",deleteTag:"Elimina tag"},notificationTemplates:{placeholders:{title:"Titolo notifica...",body:"Corpo notifica..."}},batchTag:{placeholders:{newTag:"Inserisci nuovo tag..."}},photoGallery:{deletePhoto:"Elimina foto"},filamentHoverCard:{copySpoolUuid:"Copia UUID bobina"},kProfilesView:{hasNote:"Ha una nota",copyProfile:"Copia profilo"},layout:{openMenu:"Apri menu",noPermissionSystemInfo:"Non hai il permesso di visualizzare le informazioni di sistema"},dashboard:{dragToReorder:"Trascina per riordinare",hideWidget:"Nascondi widget"},notificationProviderCard:{deleteNotificationProvider:"Elimina provider di notifica"},fileManagerModal:{closeFileManager:"Chiudi gestore file",sortFiles:"Ordina file",goToParentFolder:"Vai alla cartella superiore",threeView:"Vista 3D"},embeddedCameraViewer:{refreshStream:"Aggiorna stream",close:"Chiudi",zoomOut:"Rimpicciolisci",resetZoom:"Reimposta zoom",zoomIn:"Ingrandisci",dragToResize:"Trascina per ridimensionare"},timelapseViewer:{skipBack5s:"Indietro 5s",skipForward5s:"Avanti 5s"},notificationProviders:{descriptions:{email:"Notifiche email via SMTP",telegram:"Notifiche tramite bot Telegram",discord:"Invia a canale Discord tramite webhook",ntfy:"Notifiche push gratuite e self-hostabili",pushover:"Notifiche push semplici e affidabili",callmebot:"Notifiche WhatsApp gratuite tramite CallMeBot",webhook:"POST HTTP generico a qualsiasi URL"}},logViewer:{searchPlaceholder:"Cerca messaggio o nome logger...",noLogEntries:"Nessuna voce di log trovata"},switchbarPopover:{noSwitchesInSwitchbar:"Nessun interruttore nella barra"},projectPageModal:{placeholders:{title:"Titolo",designer:"Designer",license:"Licenza",description:"Inserisci descrizione...",profileTitle:"Titolo profilo",profileDescription:"Descrizione profilo..."}},spoolmanSettings:{},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",writeTag:"Scrivi",settings:"Impostazioni"},status:{nfcReady:"NFC pronto",nfcOff:"NFC spento",offline:"Offline",online:"Online",noPrinters:"Nessuna stampante",deviceOffline:"Dispositivo offline",waitingConnection:"In attesa della connessione...",systemReady:"Sistema pronto",status:"Stato"},dashboard:{readyToScan:"Pronto per la scansione",idleMessage:"Posiziona una bobina sulla bilancia per identificarla",nfcHint:"Il tag NFC verrà letto automaticamente",device:"Dispositivo",syncWeight:"Sincronizza peso",weightSynced:"Sincronizzato!",unknownTag:"Tag sconosciuto",newTag:"Nuovo tag rilevato",onScale:"sulla bilancia",linkSpool:"Collega a bobina",linkTagTitle:"Collega tag a bobina",linkTag:"Collega tag",selectSpool:"Seleziona una bobina da collegare a questo tag:",noUntagged:"Nessuna bobina senza tag trovata",tagDetected:"Tag rilevato",noTag:"Nessun tag",tagId:"Tag",grossWeight:"Peso lordo",spoolSize:"Dimensione bobina",close:"Chiudi",currentSpool:"Bobina attuale"},modal:{spoolDetected:"Bobina rilevata",assignToAms:"Assegna all'AMS",syncWeight:"Sincronizza peso",weightSynced:"Sincronizzato!",syncing:"Sincronizzazione...",newTagDetected:"Nuovo tag rilevato",addToInventory:"Aggiungi all'inventario",assignToAmsTitle:"Assegna all'AMS",selectSlot:"Seleziona uno slot",assign:"Assegna",assigning:"Assegnazione...",assignSuccess:"Assegnato!",assignError:"Impossibile assegnare la bobina. Riprovare.",noPrinterSelected:"Seleziona una stampante...",noAmsDetected:"Nessun AMS rilevato su questa stampante",slot:"Slot"},weight:{noReading:"Nessuna lettura",stable:"Stabile",measuring:"Misurazione...",tare:"Tara",calibrate:"Calibra"},spool:{remaining:"Rimanente",material:"Materiale",brand:"Marca",color:"Colore",coreWeight:"Nucleo",labelWeight:"Etichetta",scaleWeight:"Bilancia",netWeight:"Netto",lastUsed:"Ultimo utilizzo"},ams:{noData:"Nessun AMS rilevato",connectAms:"Collega un AMS per vedere gli slot",noPrinter:"Nessuna stampante selezionata",selectPrinter:"Seleziona una stampante dalla barra superiore",printerDisconnected:"Stampante disconnessa",humidity:"Umidità",level:"Livello",active:"Attivo",slot:"Slot",empty:"Vuoto"},inventory:{search:"Cerca bobine...",empty:"Nessuna bobina nell'inventario",noResults:"Nessuna bobina corrispondente",spools:"bobine",addSpool:"Aggiungi bobina"},settings:{tabDevice:"Dispositivo",tabDisplay:"Display",tabScale:"Bilancia",tabUpdates:"Aggiornamenti",nfcReader:"Lettore NFC",type:"Tipo",connection:"Connessione",notConnected:"N/A",deviceInfo:"Info dispositivo",hostname:"Host",uptime:"Tempo di attività",brightness:"Luminosità",saved:"Salvato",noBacklight:"Nessuna retroilluminazione DSI rilevata. Il controllo luminosità richiede un display DSI.",screenBlank:"Timeout spegnimento schermo",screenBlankDesc:"Lo schermo si spegne dopo inattività. Tocca per riattivare.",displayNote:"La luminosità viene applicata come filtro software.",scaleCalibration:"Calibrazione bilancia",currentWeight:"Peso attuale",tareOffset:"Tara",calFactor:"Fattore",knownWeight:"Peso noto",calStep1:"Rimuovere tutto dalla bilancia e premere Imposta zero.",calStep2:"Posizionare il peso noto sulla bilancia.",setZero:"Imposta zero",calibrateNow:"Calibra",calibrated:"Calibrato",tareSet:"Comando tara inviato. In attesa del dispositivo...",tareFailed:"Invio comando tara fallito",zeroSet:"Punto zero impostato. Posizionare il peso noto sulla bilancia.",calibrationDone:"Calibrazione completata!",calibrationFailed:"Calibrazione fallita",lastCalibrated:"Ultima calibrazione",stable:"Stabile",settling:"Stabilizzazione...",firmware:"Firmware",scale:"Bilancia",noDevice:"Nessun dispositivo SpoolBuddy trovato",daemonVersion:"Versione daemon",currentVersion:"Attuale",versionPending:"In attesa del daemon...",checking:"Verifica...",checkUpdates:"Verifica aggiornamenti",updateAvailable:"Aggiornamento disponibile",updateInstructions:"Aggiorna via SSH: esegui lo script di installazione SpoolBuddy.",upToDate:"Aggiornato",includeBeta:"Includi versioni beta"},writeTag:{tabExisting:"Bobina esistente",tabNew:"Nuova bobina",tabReplace:"Sostituisci tag",searchPlaceholder:"Cerca per materiale, colore, marca...",noUntaggedSpools:"Nessuna bobina senza tag",noTaggedSpools:"Nessuna bobina con tag",selectSpool:"Seleziona una bobina, poi posiziona un NTAG sul lettore",placeTag:"Posiziona un NTAG sul lettore",tagReady:"Tag rilevato — pronto per la scrittura",writeTag:"Scrivi tag",replaceTag:"Sostituisci tag",writing:"Scrittura tag...",waiting:"In attesa di SpoolBuddy...",writeSuccess:"Tag scritto con successo!",writeFailed:"Scrittura fallita",queueFailed:"Impossibile accodare il comando di scrittura",tryAgain:"Riprova",cancel:"Annulla",replaceWarning:"Il vecchio tag verrà scollegato. Il nuovo tag lo sostituirà.",deviceOffline:"SpoolBuddy è offline",material:"Materiale",colorName:"Nome colore",color:"Colore",brand:"Marca",weight:"Peso (g)",createSpool:"Crea bobina",creating:"Creazione...",spoolCreated:"Bobina creata! Pronto per la scrittura.",createFailed:"Impossibile creare la bobina"},quickMenu:{printerPower:"Alimentazione stampante",systemControls:"Sistema",restartDaemon:"Riavvia daemon",restartBrowser:"Riavvia browser",reboot:"Riavvia",shutdown:"Spegni",swipeToClose:"Scorri verso il basso per chiudere",confirmTitle:"Conferma",confirmShutdown:"Sei sicuro di voler spegnere lo SpoolBuddy? Avrai bisogno di accesso fisico per riaccenderlo.",confirmReboot:"Sei sicuro di voler riavviare lo SpoolBuddy?",confirmRestartDaemon:"Riavviare il daemon SpoolBuddy? NFC e bilancia saranno temporaneamente non disponibili.",confirmRestartBrowser:"Riavviare il browser kiosk? Lo schermo diventerà brevemente nero.",confirm:"Conferma",confirmPlugOn:"Accendere {{name}}?",confirmPlugOff:"Spegnere {{name}}?",turnOn:"Accendi",turnOff:"Spegni"}},bugReport:{title:"Segnala un bug",description:"Descrizione",descriptionPlaceholder:"Cosa è andato storto? Descrivi il problema...",email:"Email (opzionale)",emailPlaceholder:"tua@email.it",emailPrivacy:"Se fornita, la tua email sarà inclusa in una sezione compressa dell'issue GitHub per permettere al manutentore di contattarti.",screenshot:"Screenshot",uploadOrPaste:"Carica, incolla o trascina un'immagine",dataCollectedSummary:"Quali dati sono inclusi nel report?",dataIncluded:"Inclusi:",dataIncludedList:"Versione app, OS, architettura, versione Python, statistiche database (solo conteggi), modelli stampante, numero ugelli, versioni firmware, stato connessione, stato integrazioni (Spoolman, MQTT, HA), impostazioni non sensibili, conteggio interfacce di rete, dettagli Docker, versioni dipendenze.",dataNeverIncluded:"Mai inclusi:",dataNeverIncludedList:"Nomi stampanti, numeri di serie, codici di accesso, password, indirizzi IP, indirizzi email, chiavi API, token, URL webhook, nomi host o nomi utente.",submit:"Invia",startLogging:"Avvia registrazione debug",stepEnableLogging:"Registrazione debug attivata",stepReproduce:"Riproduci il problema ora",stepStopLogging:"Ferma & invia rapporto",stopAndSubmit:"Ferma & Invia",maxDuration:"Arresto automatico dopo {{minutes}} min",stoppingLogs:"Raccolta log & invio...",submitting:"Invio segnalazione bug...",submitSuccess:"Segnalazione bug inviata con successo!",submitFailed:"Impossibile inviare la segnalazione bug",thankYou:"Grazie!",submitted:"La tua segnalazione bug è stata inviata.",viewIssue:"Vedi issue",unexpectedError:"Si è verificato un errore imprevisto"},failureDetection:{title:"Rilevamento guasti con IA",description:"Monitora le stampe tramite un'API ML Obico auto-ospitata e agisce automaticamente sui guasti rilevati.",mlUrl:"URL API ML Obico",mlUrlHint:"URL base del tuo container Obico ml_api auto-ospitato (es. http://192.168.1.10:3333).",test:"Prova",testSuccess:"API ML raggiungibile e funzionante.",testFailed:"Impossibile raggiungere l'API ML.",sensitivity:"Sensibilità",sensitivityLow:"Bassa (meno falsi positivi)",sensitivityMedium:"Media (bilanciata)",sensitivityHigh:"Alta (rilevamento precoce, più falsi positivi)",sensitivityHint:"Regola le soglie di confidenza che attivano avvisi e guasti.",action:"Azione al guasto rilevato",actionNotify:"Solo notifica",actionPause:"Metti in pausa",actionPauseOff:"Pausa e stacca corrente",pollInterval:"Intervallo di controllo (secondi)",pollIntervalHint:"Frequenza di controllo di ogni stampante durante la stampa. Minimo 5s, massimo 120s.",externalUrlMissing:"URL esterno non impostato.",externalUrlHint:"L'API ML recupera l'immagine della fotocamera tramite URL. Imposta l'URL esterno nelle impostazioni generali affinché il container ML API possa raggiungere Bambuddy.",perPrinterTitle:"Stampanti monitorate",perPrinterHint:"Scegli quali stampanti il servizio di rilevamento deve monitorare.",monitorAll:"Monitora tutte le stampanti connesse",statusTitle:"Stato",serviceRunning:"Servizio in esecuzione",thresholds:"Soglie bassa / alta",activePrinters:"Stampe attive",noActivePrints:"Nessuna stampa in corso.",historyTitle:"Rilevamenti recenti",noHistory:"Nessun rilevamento finora."}},$ue={nav:{printers:"Impressoras",archives:"Arquivos",queue:"Fila",stats:"Estatísticas",profiles:"Perfis",maintenance:"Manutenção",projects:"Projetos",inventory:"Inventário",files:"Gerenciador de Arquivos",notifications:"Notificações",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",uploading:"Enviando...",uploadFailed:"Falha no envio",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",back:"Voltar",copy:"Copiar",copied:"Copiado!",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",problem:"Problema",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",search:"Pesquisar impressoras...",noSearchResults:"Nenhuma impressora corresponde à sua pesquisa ou filtros",filter:{allStatuses:"Todos os status",allLocations:"Todos os locais"},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",files:"Arquivos",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",forceRefresh:"Forçar atualização",forceRefreshSuccess:"Atualização solicitada",mqttDebug:"Depuração MQTT",printerInformation:"Informações da impressora",copyToClipboard:"Copiar",copied:"Copiado!",state:"Estado",wifiSignalLabel:"Sinal WiFi",developerMode:"Modo desenvolvedor",enabled:"Ativado",disabled:"Desativado",addedOn:"Adicionada em",sdCard:"Cartão SD",inserted:"Inserido",notInserted:"Não inserido",totalPrintHours:"Horas de impressão",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",missingSpoolAssignment:"Impressão iniciada em {{printer}}. Atribuição de bobina ausente para: {{slots}}",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",failedToSetSpeed:"Falha ao definir a velocidade de impressão",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",noCamera:"Você não tem permissão para visualizar câmeras"},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"},bulk:{select:"Selecionar",selectAll:"Selecionar tudo",selectByLocation:"Selecionar por local",selected:"{{count}} selecionado(s)",actions:{stop:"Parar",pause:"Pausar",resume:"Retomar",clearPlate:"Limpar mesa",clearHMS:"Limpar notificações"},confirm:{stopTitle:"Parar {{count}} impressões",stopMessage:"Isso cancelará as impressões ativas em {{count}} impressora(s). Esta ação não pode ser desfeita.",stopButton:"Parar todas",pauseTitle:"Pausar {{count}} impressões",pauseMessage:"Isso pausará as impressões ativas em {{count}} impressora(s).",pauseButton:"Pausar todas",clearPlateTitle:"Limpar {{count}} mesas de impressão",clearPlateMessage:"Isso limpará a mesa de impressão em {{count}} impressora(s) e pode iniciar trabalhos na fila.",clearPlateButton:"Limpar todas"},success:"{{action}} concluído em {{count}} impressora(s)",partial:"{{succeeded}} bem-sucedido(s), {{failed}} falhou/falharam",noneApplicable:"Nenhuma impressora selecionada está no estado correto para esta ação",selectByState:"Selecionar por estado"},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"},drying:{start:"Iniciar secagem",stop:"Parar secagem",temperature:"Temperatura",duration:"Duração",hours:"horas",timeRemaining:"{{time}} restante",active:"Secagem",notSupported:"Secagem não suportada",powerRequired:"Conecte o adaptador de energia AMS para ativar a secagem",startingDrying:"Iniciando secagem...",stoppingDrying:"Parando secagem...",rotateTray:"Girar o carretel durante a secagem"},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"},speed:{title:"Velocidade de impressão",silent:"Silencioso (50%)",standard:"Padrão (100%)",sport:"Sport (124%)",ludicrous:"Ludicrous (166%)"},airduct:{title:"Modo do duto de ar",cooling:"Resfriamento",heating:"Aquecimento"},noSdCard:"Sem SD",door:{open:"Aberta",closed:"Fechada"},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",plateNumber:"Placa {{number}}",slotOptions:"Opções de slot",amsPopup:{friendlyName:"Nome do AMS",friendlyNamePlaceholder:"ex.: Nome amigável do AMS",serialNumber:"Número de série",firmwareVersion:"Firmware",save:"Salvar",clear:"Limpar",noEditPermission:"Você não tem permissão para renomear unidades AMS"},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",incompatibleFile:"Este arquivo foi fatiado para {{slicedFor}}, mas esta impressora é uma {{printerModel}}",dropNotPrintable:"Apenas arquivos .gcode e .gcode.3mf podem ser impressos",dropToPrint:"Solte para imprimir",cannotPrint:"Impressora ocupada"},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",originalPrintNotVisible:"Impressão original não visível - tente limpar os filtros",noArchivesYet:"Ainda não há arquivos",prints:"impressões",pagination:{showing:"Mostrando",to:"a",of:"de",show:"Mostrar",page:"Página",all:"Todos"},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",hideDuplicates:"Ocultar duplicados",viewOriginalPrint:"Clique para visualizar a impressão original (#{{id}})",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",queueSelectedPlates:"Adicionar {{count}} placas à fila",selectAllPlates:"Selecionar todas as {{count}} placas",deselectAll:"Desmarcar tudo",printQueued:"Impressão adicionada à fila",itemsQueued:"{{count}} itens adicionados à fila",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.",sjf:{label:"SJF",tooltip:"Trabalho mais curto primeiro — o agendador prioriza impressões mais curtas"},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}}",quantity:"Quantidade",quantityHint:"Cria {{count}} itens na fila",activeBatches:"Lotes ativos",batchProgress:"{{completed}} de {{total}} concluídos",cancelBatch:"Cancelar restantes",batchCancelled:"Itens restantes do lote cancelados",cancelBatchConfirmTitle:"Cancelar lote",cancelBatchConfirmMessage:"Cancelar todos os itens pendentes restantes neste lote?",batch:"Lote",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",gcodeInjection:"G-code"},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"},timeline:{listView:"Lista",timelineView:"Linha do tempo",unassigned:"Não atribuído",noData:"Nenhuma impressão agendada para este dia",allDoneBy:"Todas as impressões concluídas até {{time}}",staged:"Preparado",filterAll:"Mostrar tudo",filterPrinting:"Imprimindo",filterQueued:"Na fila",time:{anyMoment:"a qualquer momento",minutesLeft:"{{minutes}}m restantes",hoursLeft:"{{hours}}h restantes",hoursMinutesLeft:"{{hours}}h {{minutes}}m restantes"},day:{previous:"Dia anterior",next:"Próximo dia",today:"Hoje"}},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",printStartedRemaining:"{{completed}} impressão(ões) iniciada(s), {{remaining}} enviando..."}},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",energyWarmingUpTooltip:"O monitoramento de energia ainda está coletando snapshots por hora. Os totais por período ficarão precisos quando houver pelo menos um snapshot antes do intervalo selecionado. Valores iniciais podem ser subestimados.",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",noPrintDataInRange:"Sem dados no período selecionado",periodFilament:"Filamento usado",periodCost:"Custo",avgPerPrint:"Média por impressão",usageOverTime:"Uso ao longo do tempo",filamentByWeight:"Peso",printDuration:"Duração da impressão",printerUtilization:"Utilização da impressora",filamentSuccess:"Sucesso por material",printHabits:"Hábitos de impressão",printTimeOfDay:"Horário de impressão",colorDistribution:"Distribuição de cores",noColorData:"Nenhum dado de cor disponível",records:"Recordes",longestPrint:"Impressão mais longa",heaviestPrint:"Impressão mais pesada",mostExpensivePrint:"Mais cara",busiestDay:"Dia mais movimentado",successStreak:"Sequência de sucesso",streakPrint:"impressão consecutiva",streakPrints:"{{count}} impressões consecutivas",printerStats:"Estatísticas da impressora",hours:"horas",avgPrints:"Méd. impressões",noArchiveData:"Nenhum dado de impressão disponível",filamentByTime:"Tempo",avgWeight:"Méd. peso",avgTime:"Méd. tempo",filamentByPrints:"Impressões",timeframe:{today:"Hoje","this-week":"Esta semana","this-month":"Este mês","last-7":"Últimos 7 dias","last-30":"Últimos 30 dias","last-90":"Últimos 90 dias","this-year":"Este ano","all-time":"Todo o período",custom:"Personalizado",from:"De",to:"Até"},allUsers:"Todos os Usuários",noUser:"Sem Usuário (Sistema)",filterByUser:"Filtrar por Usuário"},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",lubricateSteelRods:"Lubrificar Barras de Aço",cleanSteelRods:"Limpar Barras de Aço",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",queue:"Workflow",filament:"Filamento",network:"Rede",apiKeys:"Chaves API",virtualPrinter:"Impressora Virtual",failureDetection:"Detecção de Falhas",users:"Autenticação",backup:"Backup",emailAuth:"Autenticação por Email",ldap:"LDAP",twoFa:"Autenticação 2FA",oidc:"SSO / OIDC"},ldap:{title:"Autenticação LDAP",enabledDesc:"A autenticação LDAP está ativada",disabledDesc:"A autenticação LDAP está desativada",disabledHint:"Configure e salve as configurações LDAP abaixo, depois ative.",enabled:"Autenticação LDAP ativada",disabled:"Autenticação LDAP desativada",feature1:"Usuários podem fazer login com credenciais LDAP",feature2:"A conta de administrador local permanece como fallback",feature3:"Grupos LDAP são mapeados para grupos BamBuddy no login",serverConfig:"Configuração do Servidor LDAP",serverUrl:"URL do servidor",serverUrlHint:"Use ldap:// para padrão ou ldaps:// para conexões SSL",security:"Segurança",securityHint:"StartTLS atualiza uma conexão simples para TLS. LDAPS usa TLS desde o início.",bindDn:"Bind DN (conta de serviço)",bindPassword:"Senha Bind",searchBase:"Base DN de pesquisa",userFilter:"Filtro de pesquisa de usuário",userFilterHint:"{username} é substituído pelo nome de usuário. Use (uid={username}) para OpenLDAP.",autoProvision:"Provisionamento automático de usuários",autoProvisionHint:"Criar automaticamente uma conta BamBuddy no primeiro login LDAP",defaultGroup:"Grupo padrão",defaultGroupNone:"— Nenhum (sem fallback) —",defaultGroupHint:"Grupo de fallback atribuído quando um usuário LDAP se autentica mas não está em nenhum grupo LDAP mapeado. Deixe vazio para manter usuários não mapeados sem permissões.",groupMapping:"Mapeamento de grupos (JSON)",groupMappingHint:"Mapear DNs de grupos LDAP para grupos BamBuddy. Grupos disponíveis: ",testConnection:"Testar conexão",settingsSaved:"Configurações LDAP salvas",errors:{serverRequired:"URL do servidor LDAP é obrigatória",searchBaseRequired:"Base DN de pesquisa é obrigatória",enableAuthFirst:"Ative a autenticação primeiro",configureLdapFirst:"Salve as configurações LDAP primeiro"}},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",enableAuthFirst:"Por favor, habilite a autenticação primeiro para usar os recursos baseados em e-mail."},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",userNotificationsEnabled:"Notificações do Usuário",userNotificationsEnabledDescription:"Ativa o menu de notificações do usuário e notificações por e-mail para eventos de impressão. Requer Autenticação Avançada.",userNotificationsDisabledHint:"Ative a Autenticação Avançada para usar as notificações do usuário.",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.",filamentChecks:"Verificações de filamento",disableFilamentWarnings:"Desativar avisos de filamento",disableFilamentWarningsDesc:"Não mostrar avisos sobre filamento insuficiente ao imprimir ou adicionar à fila",preferLowestFilament:"Preferir filamento com menor resto",preferLowestFilamentDesc:"Quando vários carretéis correspondem, usar o com menos filamento restante",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)",fairAlsoDryingThreshold:"Este limiar também é usado para acionar a secagem automática",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",defaultPrintOptions:"Opções de impressão padrão",defaultPrintOptionsDescription:"Defina valores padrão para opções de impressão. Podem ser alterados no diálogo de impressão.",defaultBedLevelling:"Nivelamento da mesa",defaultBedLevellingDesc:"Nivelar automaticamente a mesa antes da impressão",defaultFlowCali:"Calibração de fluxo",defaultFlowCaliDesc:"Calibrar fluxo de extrusão",defaultVibrationCali:"Calibração de vibração",defaultVibrationCaliDesc:"Reduzir artefatos de ringing",defaultLayerInspect:"Inspeção da primeira camada",defaultLayerInspectDesc:"Inspeção IA da primeira camada",defaultTimelapse:"Timelapse",defaultTimelapseDesc:"Gravar vídeo timelapse",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"Confirmação de placa livre",requirePlateClear:"Exigir confirmação de placa livre",requirePlateClearDescription:"Quando ativado, o agendador aguarda a confirmação de placa livre por impressora antes de iniciar impressões na fila em impressoras com trabalhos concluídos. Desative para fluxos de trabalho de fazenda onde as placas são verificadas fisicamente.",gcodeInjection:"Injeção de G-code",gcodeInjectionDescription:'Configure G-code personalizado para injetar no início e/ou no final das impressões para sistemas de impressão automática como Farmloop, SwapMod, AutoClear e Printflow 3D. Os snippets são configurados por modelo de impressora e aplicados quando "Injetar G-code" está ativado em um item da fila.',gcodeInjectionNoPrinters:"Nenhuma impressora encontrada. Adicione impressoras para configurar snippets de G-code.",gcodeStartLabel:"G-code inicial",gcodeEndLabel:"G-code final",gcodeStartPlaceholder:"G-code inserido antes do início da impressão...",gcodeEndPlaceholder:"G-code adicionado após o término da impressão...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"Secagem Automática",queueDryingDescription:"Secar automaticamente o filamento AMS quando a impressora estiver ociosa entre impressões na fila. Usa o limite de umidade acima.",queueDryingEnabled:"Ativar secagem automática",queueDryingEnabledDescription:"Iniciar secagem AMS automaticamente quando a impressora estiver ociosa e a umidade estiver acima do limite",queueDryingBlock:"Aguardar conclusão da secagem",queueDryingBlockDescription:"Bloquear a fila de impressão até a secagem terminar. Quando desativado, impressões têm prioridade.",ambientDryingEnabled:"Secagem ambiente",ambientDryingEnabledDescription:"Secar automaticamente o filamento em impressoras ociosas quando a umidade exceder o limite, mesmo sem impressões na fila.",dryingPresets:"Predefinições de secagem",dryingPresetsDescription:"Temperatura e duração por tipo de filamento. AMS 2 Pro usa temperaturas mais baixas, AMS-HT suporta temperaturas mais altas.",dryingFilament:"Filamento",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",selectedCount:"{{count}} selecionados",deleteSelected:"Excluir Selecionados",bulkDeleteConfirm:"Tem certeza de que deseja excluir {{count}} entradas?",bulkDeleted:"{{count}} entradas excluídas",bulkDeleteFailed:"Falha ao excluir entradas"},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",selectedCount:"{{count}} selecionados",deleteSelected:"Excluir Selecionados",bulkDeleteConfirm:"Tem certeza de que deseja excluir {{count}} cores?",bulkDeleted:"{{count}} cores excluídas",bulkDeleteFailed:"Falha ao excluir cores"},dateFormat:"Formato de data",dateFormatUs:"US (MM/DD/AAAA)",dateFormatEu:"EU (DD/MM/AAAA)",dateFormatIso:"ISO (AAAA-MM-DD)",timeFormat:"Formato de hora",timeFormat12:"12 horas (3:30 PM)",timeFormat24:"24 horas (15:30)",defaultPrinter:"Impressora padrão",defaultPrinterDescription:"Pré-selecionar esta impressora para uploads, reimpressões e outras operações.",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"Arraste itens na barra lateral para reordenar. Restaurar ordem padrão aqui.",setDefault:"Definir padrão",sidebarOrderSetDefaultHint:"Definir padrão aplica a ordem atual do menu aos usuários que ainda não personalizaram o seu.",sidebarDefaultSet:"Ordem padrão do menu foi definida.",sidebarDefaultCleared:"Ordem padrão do menu removida.",sidebarDefaultFailed:"Falha ao definir a ordem padrão do menu.",reset:"Redefinir",darkMode:"Modo escuro",lightMode:"Modo claro",active:"(ativo)",background:"Fundo",accent:"Destaque",style:"Estilo",bgNeutral:"Neutro",bgWarm:"Quente",bgCool:"Frio",bgOled:"OLED Preto",bgSlate:"Azul ardósia",bgForest:"Verde floresta",accentGreen:"Verde",accentTeal:"Azul-petróleo",accentBlue:"Azul",accentOrange:"Laranja",accentPurple:"Roxo",accentRed:"Vermelho",styleClassic:"Clássico",styleGlow:"Brilhante",styleVibrant:"Vibrante",themeToggleHint:"Alternar entre modo escuro e claro usando o ícone de sol/lua na barra lateral.",autoArchivePrints:"Arquivar impressões automaticamente",autoArchiveDescription:"Salvar automaticamente arquivos 3MF quando impressões forem concluídas",saveThumbnailsDescription:"Extrair e salvar imagens de pré-visualização dos arquivos 3MF",captureFinishPhotoDescription:"Tirar foto da câmera da impressora quando a impressão for concluída",ffmpegNotInstalled:"ffmpeg não instalado",ffmpegRequired:"A captura de câmera requer ffmpeg. Instale via <brew>brew install ffmpeg</brew> (macOS) ou <apt>apt install ffmpeg</apt> (Linux).",camera:"Câmera",cameraViewMode:"Modo de visualização da câmera",cameraOverlayDescription:"A câmera abre em uma sobreposição redimensionável na tela principal",cameraWindowDescription:"A câmera abre em uma janela separada do navegador",externalCamerasDescription:"Configure câmeras externas para substituir a câmera integrada da impressora. Suporta streams MJPEG, RTSP, snapshots HTTP e câmeras USB (V4L2). Quando habilitada, a câmera externa é usada para visualização ao vivo e fotos de conclusão.",cameraPlaceholderUsb:"Caminho do dispositivo (/dev/video0)",cameraPlaceholderUrl:"URL da câmera (rtsp://... ou http://...)",cameraTypeMjpeg:"Stream MJPEG",cameraTypeRtsp:"Stream RTSP",cameraTypeSnapshot:"Snapshot HTTP",cameraTypeUsb:"Câmera USB (V4L2)",cameraRotation:"Rotação",test:"Testar",connected:"Conectado",disconnected:"Desconectado",currency:"Moeda",defaultFilamentCost:"Custo padrão do filamento (por kg)",electricityCost:"Custo da eletricidade por kWh",energyDisplayMode:"Modo de exibição de energia",energyModePrintDescription:"O painel mostra a soma da energia usada durante as impressões",energyModeTotalDescription:"O painel mostra a energia total dos plugues inteligentes",fileManager:"Gerenciador de arquivos",createArchiveEntry:"Criar entrada de arquivo ao imprimir",createArchiveEntryDescription:"Ao imprimir pelo gerenciador de arquivos, criar opcionalmente uma entrada de arquivo",lowDiskSpaceWarning:"Aviso de pouco espaço em disco",lowDiskSpaceDescription:"Mostrar aviso quando o espaço livre em disco ficar abaixo deste limite",printerFirmware:"Firmware da impressora",checkFirmwareDescription:"Verificar atualizações de firmware da Bambu Lab",bambuddySoftware:"Software Bambuddy",autoCheckDescription:"Verificar automaticamente novas versões ao iniciar",checkNow:"Verificar agora",updateAvailableVersion:"Atualização disponível: v{{version}}",releaseNotes:"Notas da versão",updateViaDocker:"Atualizar via Docker Compose:",installUpdate:"Instalar atualização",latestVersionRunning:"Você está usando a versão mais recente",failedToCheckUpdates:"Falha ao verificar atualizações: {{error}}",backupRestore:"Backup e Restauração",backupRestoreDescription:"Exportar/importar configurações e configurar backup do GitHub",goToBackup:"Ir para backup",externalUrl:"URL externa",externalUrlDescription:"A URL externa onde o Bambuddy está acessível. Usada para imagens de notificação e integrações externas.",bambuddyUrl:"URL do Bambuddy",externalUrlHint:"Inclua protocolo e porta (ex: http://192.168.1.100:8000)",ftpRetry:"Tentativa FTP",ftpRetryDescription:"Tentar novamente operações FTP quando o WiFi da impressora é instável. Aplica-se a downloads 3MF, uploads de impressão, downloads de timelapse e atualizações de firmware.",autoRetryDescription:"Tentar novamente automaticamente operações FTP que falharam",retryAttempts:"Tentativas de reenvio",retryDelay:"Atraso entre tentativas",connectionTimeout:"Tempo limite de conexão",time_one:"{{count}} vez",time_other:"{{count}} vezes",second_one:"{{count}} segundo",second_other:"{{count}} segundos",nSeconds:"{{count}} segundos",increaseForWeakWifi:"Aumente para impressoras com WiFi fraco",homeAssistant:"Home Assistant",homeAssistantFullDescription:"Conecte ao Home Assistant para controlar plugues inteligentes via API REST do HA. Suporta entidades switch, light, input_boolean e script.",homeAssistantUrl:"URL do Home Assistant",longLivedAccessToken:"Token de acesso de longa duração",haTokenHint:"Crie um token no HA: Perfil → Tokens de acesso de longa duração → Criar token",connectionSuccessful:"Conexão bem-sucedida",connectionFailed:"Falha na conexão",haConnectionSuccess:"Conectado com sucesso ao Home Assistant.",haConnectionFailed:"Falha ao conectar ao Home Assistant.",mqttPublishing:"Publicação MQTT",mqttDescription:"Publique eventos do BamBuddy para um broker MQTT externo para integração com Node-RED, Home Assistant e outros sistemas de automação.",mqttEnableDescription:"Publicar eventos no broker MQTT externo",brokerHostname:"Hostname do broker",port:"Porta",usernameOptional:"Usuário (opcional)",passwordOptional:"Senha (opcional)",topicPrefix:"Prefixo do tópico",topicPrefixHint:"Os tópicos serão: {{prefix}}/printers/<serial>/status, etc.",prometheusMetrics:"Métricas Prometheus",prometheusEndpointDescription:"Expor métricas da impressora em <code>/api/v1/metrics</code> para monitoramento Prometheus/Grafana.",bearerTokenOptional:"Token Bearer (opcional)",bearerTokenHint:"Se definido, as requisições devem incluir <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"Status da conexão",metricsPrinterState:"Estado da impressora (idle/printing/etc)",metricsPrintProgress:"Progresso da impressão 0-100%",metricsBedTemp:"Temperatura da mesa",metricsNozzleTemp:"Temperatura do bico",metricsPrintsTotal:"Total de impressões por resultado",metricsMore:"...e mais (camadas, ventoinhas, fila, uso de filamento)",smartPlugsDescription:"Conecte plugues inteligentes (Tasmota ou Home Assistant) para automatizar o controle de energia e rastrear o consumo energético das suas impressoras.",allOn:"Ligar todos",allOff:"Desligar todos",addSmartPlug:"Adicionar plugue inteligente",energySummary:"Resumo de energia",currentPower:"Potência atual",plugsOnline:"{{reachable}}/{{total}} plugues online",today:"Hoje",yesterday:"Ontem",total:"Total",enablePlugsForSummary:"Habilite os plugues para ver o resumo de energia",addNotificationProvider:"Adicionar",systemBadge:"(Sistema)",creating:"Criando...",changing:"Alterando...",deleteUserAndItems:"Excluir usuário E seus itens",deleteUserKeepItems:"Excluir usuário, manter itens (ficarão sem dono)",ok:"OK",twoFa:{totpTitle:"App Autenticador (TOTP)",totpDesc:"Use um app como Google Authenticator, Aegis ou Authy.",emailOtpTitle:"OTP por e-mail",emailOtpDesc:"Envie um código único para {{email}} ao fazer login.",emailOtpNoEmail:"Adicione um endereço de e-mail à sua conta para ativar este método.",addEmailFirst:"Sua conta não tem endereço de e-mail. Peça a um administrador para adicionar um.",setupTotp:"Configurar App Autenticador",setupAuthApp:"Configurar App Autenticador",setupInstructions:"Escaneie o código QR com seu app autenticador e confirme com um código.",manualEntry:"Não consegue escanear? Digite este segredo manualmente:",scannedContinue:"Código escaneado — continuar",enterCodeToConfirm:"Digite o código de 6 dígitos do seu app autenticador para confirmar.",activate:"Ativar",disableTotp:"Desativar Autenticador",disableConfirmHint:"Digite um código TOTP válido ou um código de backup para desativar o autenticador.",totpDisabled:"App autenticador desativado.",emailOtpEnabled:"OTP por e-mail ativado.",emailOtpDisabled:"OTP por e-mail desativado.",smtpRequired:"Por favor, configure e teste as configurações SMTP primeiro.",invalidCode:"Código inválido. Por favor, tente novamente.",enableEmailOtp:"Ativar OTP por e-mail",disableEmailOtp:"Desativar OTP por e-mail",emailSetupEnterCode:"Um código de verificação foi enviado para o seu endereço de e-mail. Digite-o abaixo para confirmar que você possui esta caixa de entrada.",verifyAndEnable:"Verificar e Ativar",emailDisablePasswordHint:"Digite a senha da sua conta para confirmar a desativação do OTP por e-mail.",passwordPlaceholder:"Digite sua senha",backupCodesTitle:"Salve seus códigos de backup",backupCodesWarning:"Guarde estes códigos em lugar seguro. Cada código só pode ser usado uma vez.",backupCodesRemaining:"{{count}} códigos de backup restantes",savedCodes:"Códigos salvos",regenBackup:"Regenerar códigos de backup",regenBackupHint:"Digite seu código TOTP atual para gerar 10 novos códigos de backup.",newBackupCodes:"Novos códigos de backup",linkedAccounts:"Contas SSO vinculadas",linkedAccountsDesc:"Estes provedores de identidade externos estão vinculados à sua conta.",oidcUnlinked:"Conta desvinculada."},oidc:{title:"Provedores SSO / OIDC",desc:"Configure provedores OpenID Connect para login único.",addProvider:"Adicionar provedor",newProvider:"Novo provedor",empty:"Nenhum provedor OIDC configurado ainda.",created:"Provedor criado.",updated:"Provedor atualizado.",deleted:"Provedor excluído.",deleteTitle:"Excluir provedor",deleteMessage:'Excluir "{{name}}"? Todas as contas vinculadas serão desconectadas.',form:{name:"Nome de exibição",issuerUrl:"URL do emissor",clientId:"Client ID",clientSecret:"Client secret",scopes:"Escopos",iconUrl:"URL do ícone (opcional)",enabled:"Ativado",autoCreate:"Criar usuários automaticamente",autoCreateDesc:"Cria automaticamente uma conta local no primeiro login.",autoLink:"Vincular contas existentes automaticamente",autoLinkDesc:"Vincula contas locais existentes por e-mail no primeiro login.",secretHint:"deixe em branco para manter",secretPlaceholder:"novo segredo"}}},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",enterEmail:"Por favor, insira seu endereço de e-mail",oidcLoginFailed:"Falha no login OIDC",oidcErrors:{providerError:"O provedor de identidade retornou um erro",missingParameters:"Parâmetros obrigatórios ausentes no callback OIDC",invalidState:"Estado OIDC inválido ou já utilizado",stateExpired:"Sessão OIDC expirada — tente novamente",providerNotFound:"Provedor OIDC não encontrado",discoveryFailed:"Falha ao obter o documento de descoberta OIDC",invalidDiscovery:"Documento de descoberta OIDC inválido",networkError:"Erro de rede durante a troca de token OIDC",badResponse:"Resposta inesperada durante a troca de token OIDC",noIdToken:"O provedor OIDC não retornou um token de ID",validationFailed:"Falha na validação do token OIDC",nonceMismatch:"Nonce OIDC não corresponde — possível ataque de replay",missingSubClaim:"Token OIDC sem claim sub",noLinkedAccount:"Nenhuma conta local vinculada a esta identidade OIDC",accountInactive:"Sua conta está inativa",userResolutionFailed:"Falha ao resolver sua conta",internalError:"Erro interno durante o login OIDC",tokenExchangeFailed:"Falha na troca de token OIDC"},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",resetPassword:{title:"Definir nova senha",subtitle:"Digite e confirme sua nova senha abaixo.",newPassword:"Nova senha",newPasswordPlaceholder:"Pelo menos 8 caracteres",confirmPassword:"Confirmar senha",confirmPasswordPlaceholder:"Repetir nova senha",saving:"Salvando…",submit:"Definir nova senha",backToLogin:"Voltar para o login",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 8 caracteres",resetFailed:"Falha ao redefinir senha. O link pode ter expirado."},twoFA:{title:"Autenticação em dois fatores",subtitle:"Sua conta está protegida com 2FA. Insira o código de verificação abaixo.",methodAuthenticator:"Aplicativo autenticador",methodEmail:"Código por e-mail",methodBackup:"Código de recuperação",instructionsTotp:"Abra seu aplicativo autenticador e insira o código de 6 dígitos gerado para o Bambuddy.",instructionsEmail:"Um código de 6 dígitos foi enviado para o seu e-mail. Ele é válido por 10 minutos.",instructionsEmailNotSent:"Clique no botão abaixo para receber um código de verificação por e-mail.",instructionsBackup:"Insira um dos seus códigos de recuperação de 8 caracteres. Cada código só pode ser utilizado uma vez.",sendCodeButton:"Enviar código por e-mail",sendingCode:"Enviando...",resendCode:"Reenviar código",codeLabel:"Código de verificação",backupCodeLabel:"Código de recuperação",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"Verificar",verifyingButton:"Verificando...",backToLogin:"← Voltar para o login",orContinueWith:"ou entrar com",signInWith:"Entrar com {{provider}}",enterCode:"Por favor, insira o código de verificação",sendCodeFailed:"Falha ao enviar o código de verificação",invalidCode:"Código inválido. Por favor, tente novamente."}},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:"Falha no envio",zipFilesFailed:"{{count}} arquivos falharam",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",linkExternal:"Vincular externo",linkExternalFolder:"Vincular pasta externa",linkExternalFolderDescription:"Montar um diretório do host (NAS, USB, compartilhamento de rede) no Gerenciador de Arquivos. Os arquivos não são copiados — são acessados diretamente do caminho original.",externalFolderNamePlaceholder:"ex. Impressões NAS",externalPath:"Caminho do host",externalPathHelp:"Caminho absoluto do diretório no host Docker. Deve estar montado como bind no contêiner.",readOnly:"Somente leitura",readOnlyHelp:"impede uploads e exclusões",showHiddenFiles:"Mostrar arquivos ocultos (arquivos ponto)",externalFolder:"Pasta externa",scanFolder:"Escanear",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",externalFolderLinked:"Pasta externa vinculada e escaneada",folderScanned:"Escaneamento concluído: {{added}} adicionados, {{removed}} removidos",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",totalCost:"Custo Total",total:"Total",includesBom:"incl. lista de materiais",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.",noFiles:"Nenhum arquivo nesta pasta.",print:"Imprimir agora",addToQueue:"Adicionar à fila"},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",unlinkConfirmTitle:"Desvincular carretel?",unlinkConfirmMessage:"Isso desconectará o carretel do Spoolman. Os dados do carretel no Spoolman permanecerão inalterados.",selectSpool:"Selecionar Carretel",noUnlinkedSpools:"Nenhum carretel desvinculado disponível",linkSuccess:"Carretel vinculado ao Spoolman com sucesso",linkFailed:"Falha ao vincular carretel",unlinkSuccess:"Carretel desvinculado do Spoolman com sucesso",unlinkFailed:"Falha ao desvincular 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",spoolName:"Bobina",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...",showAllSpools:"Mostrar todos os 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",weightCheck:"Verificação de Peso",lastWeighed:"Última pesagem",neverWeighed:"Nunca pesado",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",groupSimilar:"Agrupar",groupedSpools:"{{count}} carretéis idênticos",groupedRows:"linhas",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)",lowStockThresholdError:"O limite deve estar entre 0.1 e 99.9",assignMismatchTitle:"Incompatibilidade de material",assignMismatchMessage:'O material do carretel selecionado "{{spoolMaterial}}" não corresponde ao material da bandeja "{{trayMaterial}}" para {{location}}. Atribuir mesmo assim?',assignMismatchConfirm:"Atribuir mesmo assim",assignPartialMismatchMessage:'O material do carretel "{{spoolMaterial}}" é semelhante, mas não corresponde exatamente a "{{trayMaterial}}" em {{location}}. Deseja prosseguir?',assignProfileMismatchMessage:'O perfil do carretel "{{spoolProfile}}" não corresponde ao perfil da bandeja "{{trayProfile}}" em {{location}}. Deseja prosseguir?'},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",used:"usado",remainingUnit:"restante"},printModal:{title:"Iniciar Impressão",selectPrinter:"Selecionar Impressora",selectPlate:"Selecionar Placa",filamentMapping:"Mapeamento de Filamento",totalCost:"Custo total:",slotRemainingShort:" - {{grams}}g rest.",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",insufficientFilamentTitle:"Filamento insuficiente",insufficientFilamentMessage:"Alguns dos carretéis atribuídos têm menos filamento restante do que o necessário para esta impressão:",insufficientFilamentLine:"{{printer}} - {{slot}}: necessário {{required}}g, restante {{remaining}}g",printAnyway:"Imprimir mesmo assim",forceColorMatch:"Forçar correspondência de cor",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Escalonar para {{count}} impressoras",gcodeInjection:"Injetar G-code de auto-impressão"},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",githubBackup:"Backup GitHub",enabled:"Ativado",cloudLoginRequired:"Login no Bambu Cloud necessário. Entre em Perfis → Perfis Cloud para ativar o backup GitHub.",cloudLoginRequiredShort:"Login Cloud necessário",githubDescription:"Sincronize automaticamente seus perfis com um repositório GitHub privado para backup e histórico de versões.",repositoryUrl:"URL do repositório",personalAccessToken:"Token de acesso pessoal",tokenSaved:"(salvo)",enterNewToken:"Digite um novo token para atualizar",tokenHint:"Token de granularidade fina com permissão de leitura/escrita de conteúdo",branch:"Branch",manualOnly:"Apenas manual",hourly:"A cada hora",daily:"Diário",weekly:"Semanal",includeInBackup:"Incluir no backup",kProfiles:"K-Perfis",kProfilesDescription:"Calibração de avanço de pressão das impressoras conectadas",noPrintersConnected:"Nenhuma impressora conectada",printersConnected:"{{connected}}/{{total}} conectadas",cloudProfiles:"Perfis Cloud",cloudProfilesDescription:"Predefinições de filamento, impressora e processo do Bambu Cloud",appSettings:"Configurações do App",appSettingsDescription:"Configuração do Bambuddy (banco de dados completo)",spoolInventory:"Inventário de bobinas",spoolInventoryDescription:"Bobinas de filamento, histórico de uso e rastreamento de custos",printArchives:"Arquivos de impressão",printArchivesDescription:"Metadados do histórico de impressão (sem arquivos gcode/3MF)",lastBackupAt:"Último backup:",noBackupsYet:"Nenhum backup ainda",next:"Próximo:",startingBackup:"Iniciando backup...",test:"Testar",enableBackup:"Ativar backup",testConnection:"Testar conexão",enterRepoUrl:"Digite a URL do repositório",enterRepoAndToken:"Digite a URL do repositório e o token de acesso",repoRequired:"A URL do repositório é obrigatória",tokenRequired:"O token de acesso é obrigatório",githubBackupEnabled:"Backup GitHub ativado",tokenUpdated:"Token atualizado",settingsSaved:"Configurações salvas",failedToSave:"Falha ao salvar: {{message}}",backupCompleteFiles:"Backup concluído - {{count}} arquivos atualizados",backupSkippedNoChanges:"Backup ignorado - sem alterações",backupFailed2:"Falha no backup: {{message}}",clearedLogs:"{{count}} logs removidos",failedToClearLogs:"Falha ao limpar logs: {{message}}",history:"Histórico",clear:"Limpar",date:"Data",status:"Status",commit:"Commit",localBackup:"Backup local",localBackupDescription:"Crie um backup completo dos seus dados do Bambuddy incluindo banco de dados, arquivos, uploads e todos os ficheiros.",downloadBackupLabel:"Baixar backup",completeBackupZip:"Backup completo: banco de dados + todos os arquivos (ZIP)",download:"Baixar",preparingBackup:"Preparando backup...",creatingArchive:"Criando arquivo de backup... Isso pode demorar para backups grandes.",downloadingFile:"Baixando arquivo de backup...",backupDownloaded:"Backup baixado com sucesso",failedToCreateBackup:"Falha ao criar backup: {{message}}",restore:"Restaurar",restoreReplacesAll:"A restauração substitui todos os dados.",restoreReplacesAllDetail:"Seu banco de dados e arquivos atuais serão completamente substituídos. É necessário reiniciar após a restauração.",restoreConfirmTitle:"Restaurar backup",restoreConfirmMessage:'Tem certeza de que deseja restaurar de "{{filename}}"? Isso substituirá completamente seu banco de dados e todos os arquivos. O aplicativo precisará ser reiniciado após a restauração.',restoreConfirmButton:"Restaurar backup",uploadingFile:"Enviando arquivo de backup...",backupRestoredRestart:"Backup restaurado. Por favor, reinicie o Bambuddy.",failedToRestore:"Falha ao restaurar backup. Verifique o formato do arquivo.",reloadNow:"Recarregar agora",creatingBackup:"Criando backup",restoringBackup:"Restaurando backup",preparing:"Preparando...",processing:"Processando...",doNotClosePage:"Por favor, não feche esta página nem navegue para outro lugar. Esta operação pode levar vários minutos para backups grandes.",restoring:"Restaurando...",restoreComplete:"Restauração concluída",restoreFailed2:"Falha na restauração",importSettings:"Importar configurações de um arquivo de backup",pleaseWaitRestoring:"Aguarde enquanto seus dados estão sendo restaurados",selectBackupFile:"Clique para selecionar um arquivo de backup (.json ou .zip)",duplicateHandling:"Como funciona o tratamento de duplicatas:",matchPrinters:"Impressoras",matchPrintersBy:"correspondência por número de série",matchSmartPlugs:"Smart Plugs",matchSmartPlugsBy:"correspondência por endereço IP",matchNotificationProviders:"Provedores de notificação",matchNotificationProvidersBy:"correspondência por nome",matchFilaments:"Filamentos",matchFilamentsBy:"correspondência por nome + tipo + marca",matchArchives:"Arquivos",matchArchivesBy:"correspondência por hash de conteúdo (sempre ignorado)",matchPendingUploads:"Uploads pendentes",matchPendingUploadsBy:"correspondência por nome do arquivo",matchSettingsTemplates:"Configurações e modelos",matchSettingsTemplatesBy:"sempre sobrescritos",replaceExisting:"Substituir dados existentes",keepExisting:"Manter dados existentes",overwriteDescription:"Sobrescrever itens que já existem com dados do backup",keepDescription:"Restaurar apenas itens que ainda não existem",overwriteCaution:"Cuidado:",overwriteWarning:"A sobrescrita substituirá suas configurações atuais pelos dados do backup. Códigos de acesso das impressoras nunca são sobrescritos por segurança.",cancel:"Cancelar",processingBackup:"Processando arquivo de backup...",itemsRestored:"Itens restaurados",itemsSkipped:"Itens ignorados",restored:"Restaurados",skippedAlreadyExist:"Ignorados (já existem)",filesCategory:"Arquivos (3MF, miniaturas, etc.)",andMore:"...e mais {{count}}",newApiKeysGenerated:"Novas chaves API geradas",keysShownOnce:"Estas chaves são exibidas apenas uma vez. Copie-as agora!",copy:"Copiar",noDataFound:"Nenhum dado para restaurar foi encontrado no arquivo de backup.",close:"Fechar",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"Configurações",notification_providers:"Provedores de notificação",notification_templates:"Modelos de notificação",smart_plugs:"Smart Plugs",printers:"Impressoras",filaments:"Filamentos",maintenance_types:"Tipos de manutenção",archives:"Arquivos",projects:"Projetos",pending_uploads:"Uploads pendentes",external_links:"Links externos",api_keys:"Chaves API"}},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"},autoDispatch:{title:"Envio automático",description:"Iniciar impressões automaticamente quando adicionadas à fila. Quando desativado, as impressões aguardam envio manual."},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",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"'},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",bindIpRequired:"Defina um IP de ligação primeiro",accessCodeEmpty:"O código de acesso não pode estar vazio",accessCodeLength:"O código de acesso deve ter exatamente 8 caracteres",created:"Impressora virtual criada",failedToCreate:"Falha ao criar impressora virtual",deleted:"Impressora virtual excluída",failedToDelete:"Falha ao excluir impressora virtual"},list:{title:"Impressoras Virtuais",add:"Adicionar",addFirst:"Adicionar Impressora Virtual",empty:"Nenhuma impressora virtual configurada. Adicione uma para começar."},bindIp:{title:"Interface de Rede",placeholder:"Selecionar interface...",hint:"Interface de rede para esta impressora virtual. Deve ser única por impressora."},proxy:{accessCodeHint:"No modo proxy, use o código de acesso da impressora alvo no slicer. A conexão é encaminhada de forma transparente para a impressora real."},addDialog:{title:"Adicionar Impressora Virtual",name:"Nome",hint:"Você pode configurar o código de acesso, impressora alvo e outras configurações após a criação.",create:"Criar"},deleteConfirm:{title:"Excluir Impressora Virtual",message:'Tem certeza que deseja excluir "{{name}}"? Isso irá parar todos os serviços desta impressora.'}},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",lubricateSteelRods:"Aplique lubrificante nas barras de aço para um movimento suave",cleanSteelRods:"Limpe as barras de aço 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"}},linkedTo:"Vinculado a:",monitorOnly:"Apenas monitoramento",alerts:"Alertas",scheduleOn:"Ligar {{time}}",scheduleOff:"Desligar {{time}}",on:"Ligado",off:"Desligado",power:"Potência",kwhToday:"kWh Hoje",settings:"Configurações",automationSettings:"Configurações de automação",showInSwitchbar:"Mostrar na barra de interruptores",quickAccessSidebar:"Acesso rápido pela barra lateral",enabled:"Ativado",enableAutomation:"Ativar automação para este plugue",autoOn:"Auto Ligar",autoOnDescription:"Ligar quando a impressão iniciar",autoOff:"Auto Desligar",autoOffDescription:"Desligar quando a impressão terminar (única vez)",autoOffPersistent:"Manter ativado",autoOffPersistentDescription:"Permanecer ativado entre impressões em vez de única vez",turnOffDelayMode:"Modo de atraso para desligar",time:"Tempo",temp:"Temp",delayMinutes:"Atraso (minutos)",tempThreshold:"Limite de temperatura (°C)",tempThresholdDescription:"Desliga quando o bico esfria abaixo desta temperatura",edit:"Editar",deleteConfirm:'Tem certeza que deseja excluir "{{name}}"? Esta ação não pode ser desfeita.',turnOnConfirm:'Tem certeza que deseja ligar "{{name}}"?',turnOffConfirm:'Tem certeza que deseja desligar "{{name}}"? Isso cortará a energia do dispositivo conectado.',failedToTurn:'Falha ao {{action}} "{{name}}"',unknown:"Desconhecido",addTitle:"Adicionar plugue inteligente",editTitle:"Editar plugue inteligente",stopScanning:"Parar varredura",discoverTasmota:"Descobrir dispositivos Tasmota",foundDevices:"{{count}} dispositivo(s) encontrado(s) - clique para selecionar:",noDevicesFound:"Nenhum dispositivo Tasmota encontrado na sua rede",haNotConfigured:"Home Assistant não está configurado. Configure em",haSettingsPath:"Configurações → Rede → Home Assistant",selectEntity:"Selecionar entidade *",ipAddress:"Endereço IP *",nameLabel:"Nome *",username:"Usuário",password:"Senha",authHint:"Deixe vazio se seu dispositivo Tasmota não requer autenticação",linkToPrinter:"Vincular à impressora",noPrinter:"Sem impressora (apenas controle manual)",linkingDescription:"A vinculação permite ligar/desligar automaticamente ao iniciar/terminar impressão",powerAlerts:"Alertas de potência",alertAbove:"Alertar se acima (W)",alertBelow:"Alertar se abaixo (W)",alertDescription:"Receba notificações quando o consumo de energia ultrapassar estes limites. Deixe vazio para desativar essa direção.",dailySchedule:"Programação diária",turnOnAt:"Ligar às",turnOffAt:"Desligar às",scheduleDescription:"Ligar/desligar automaticamente o plugue nestes horários diariamente. Deixe vazio para pular essa ação.",showOnPrinterCard:"Mostrar no cartão da impressora",displayOnPrinterCard:"Exibir botão no cartão da impressora",connectedResult:"Conectado!",deviceLabel:"Dispositivo: {{name}} - ",stateLabel:"Estado: {{state}}",test:"Testar",delete:"Excluir",save:"Salvar",add:"Adicionar",cancel:"Cancelar",failedToStartScan:"Falha ao iniciar varredura",nameRequired:"Nome é obrigatório",entityRequired:"Entidade é obrigatória para plugues Home Assistant",mqttTopicRequired:"Pelo menos um tópico MQTT deve ser configurado para potência, energia ou monitoramento de estado",loadingEntities:"Carregando entidades...",loading:"Carregando...",failedToLoadEntities:"Falha ao carregar entidades: {{error}}",noEntitiesMatching:'Nenhuma entidade encontrada correspondente a "{{search}}"',noEntitiesAvailable:"Nenhuma entidade disponível",searchingEntities:"Buscando todas as entidades ({{count}} encontradas)",showingEntities:"Mostrando switch, light, input_boolean ({{count}} disponíveis)",energyMonitoringOptional:"Monitoramento de energia (Opcional)",energyMonitoringHint:"Pesquise e selecione sensores que fornecem dados de potência/energia.",powerSensorW:"Sensor de potência (W)",energyTodayKwh:"Energia hoje (kWh)",totalEnergyKwh:"Energia total (kWh)",noMatchingSensors:"Nenhum sensor correspondente",none:"Nenhum",mqttNotConfigured:"Broker MQTT não configurado. Defina o endereço do broker em",mqttSettingsPath:"Configurações → Rede → Publicação MQTT",mqttNotConfiguredSuffix:"(você não precisa ativar a publicação, apenas preencha os detalhes do broker).",mqttMonitorOnlyDescription:"Plugues MQTT recebem dados de potência/energia via assinatura MQTT. O controle liga/desliga não está disponível - use seu broker MQTT ou sistema de automação residencial.",powerMonitoring:"Monitoramento de potência",energyMonitoring:"Monitoramento de energia",stateMonitoring:"Monitoramento de estado",optional:"opcional",topic:"Tópico",jsonPath:"Caminho JSON",multiplier:"Multiplicador",onValue:"Valor ON",mqttPowerHint:`O caminho JSON extrai o valor do payload JSON (ex: "power_l1"). Deixe vazio se o tópico publica valores numéricos brutos.
- Use multiplicador 0.001 para mW→W, 1000 para kW→W.`,mqttEnergyHint:`O caminho JSON extrai o valor do payload JSON. Deixe vazio para valores brutos.
- Use multiplicador 0.001 para Wh→kWh, 1000 para MWh→kWh.`,mqttStateHint:`O caminho JSON extrai o valor do payload JSON. Deixe vazio para valores brutos.
- Valor ON: a string exata que significa "ON". Deixe vazio para detecção automática (ON, true, 1).`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"URL de potência",restPowerPath:"Power JSON Path",restPowerMultiplier:"Multiplicador de potência",restEnergyUrl:"URL de energia",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"Multiplicador de energia",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"URL separada para dados de potência (usa a URL de status se vazio)",restEnergyUrlHint:"URL separada para dados de energia (usa a URL de status se vazio)",restEnergyHint:"Cada valor pode usar sua própria URL ou recorrer à URL de status. Use multiplicadores para conversão de unidades (ex: 0.001 para converter Wh em kWh).",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"Nenhum interruptor na barra",enableSwitchbarHint:'Ative "Mostrar na barra de interruptores" em Configurações > Smart Plugs'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"E-mail",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"Notificações por e-mail 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",homeassistant:"Notificações persistentes no painel do Home Assistant"},lastSuccess:"Último: {{date}}",error:"Erro",printer:"Impressora:",allPrinters:"Todas as impressoras",sendTestNotification:"Enviar Notificação de Teste",eventSettings:"Configurações de Eventos",enabled:"Ativado",sendFromProvider:"Enviar notificações deste provedor",printEvents:"Eventos de Impressão",printerStatus:"Status da Impressora",amsAlarms:"Alarmes do AMS",amsHtAlarms:"Alarmes do AMS-HT",printQueue:"Fila de Impressão",start:"Início",plateCheck:"Verificação da Mesa",complete:"Concluído",failed:"Falhou",stopped:"Parado",progress:"Progresso",offline:"Offline",lowFilament:"Filamento Baixo",maintenance:"Manutenção",amsHumidity:"Umidade do AMS",amsTemp:"Temp. do AMS",amsHtHumidity:"Umidade do AMS-HT",amsHtTemp:"Temp. do AMS-HT",bedCooled:"Mesa Resfriada",firstLayer:"Primeira camada",quiet:"Silencioso",digest:"Resumo {{time}}",printStarted:"Impressão Iniciada",plateNotEmpty:"Mesa Não Vazia",plateNotEmptyDescription:"Objetos detectados antes da impressão",printCompleted:"Impressão Concluída",bedCooledLabel:"Mesa Resfriada",bedCooledDescription:"Mesa resfriou abaixo do limite após a impressão",firstLayerCompleteLabel:"Primeira camada concluída",firstLayerCompleteDescription:"Notificar com foto quando a primeira camada terminar",missingSpoolAssignmentLabel:"Atribuição de bobina ausente",missingSpoolAssignmentDescription:"Notificar quando a impressão iniciar e bandejas necessárias não tiverem bobina atribuída",printFailed:"Impressão Falhou",printStopped:"Impressão Parada",progressMilestones:"Marcos de Progresso",progressMilestonesDescription:"Notificar em 25%, 50%, 75%",printerOffline:"Impressora Offline",printerError:"Erro da Impressora",lowFilamentLabel:"Filamento Baixo",maintenanceDue:"Manutenção Necessária",maintenanceDueDescription:"Notificar quando manutenção for necessária",amsHumidityHigh:"Umidade Alta do AMS",amsHumidityHighDescription:"Umidade do AMS regular excede o limite",amsTemperatureHigh:"Temperatura Alta do AMS",amsTemperatureHighDescription:"Temperatura do AMS regular excede o limite",amsHtHumidityHigh:"Umidade Alta do AMS-HT",amsHtHumidityHighDescription:"Umidade do AMS-HT excede o limite",amsHtTemperatureHigh:"Temperatura Alta do AMS-HT",amsHtTemperatureHighDescription:"Temperatura do AMS-HT excede o limite",jobAdded:"Trabalho Adicionado",jobAddedDescription:"Trabalho adicionado à fila",jobAssigned:"Trabalho Atribuído",jobAssignedDescription:"Trabalho baseado em modelo atribuído à impressora",jobStarted:"Trabalho Iniciado",jobStartedDescription:"Trabalho da fila começou a imprimir",jobWaiting:"Trabalho Aguardando",jobWaitingDescription:"Trabalho aguardando filamento ou impressora",jobSkipped:"Trabalho Pulado",jobSkippedDescription:"Trabalho pulado (anterior falhou)",jobFailed:"Trabalho Falhou",jobFailedDescription:"Trabalho falhou ao iniciar",queueComplete:"Fila Concluída",queueCompleteDescription:"Todos os trabalhos da fila finalizados",quietHours:"Horário de Silêncio",noNotificationsDuring:"Sem notificações durante essas horas",editProviderToChangeQuietHours:"Edite o provedor para alterar o horário de silêncio",dailyDigest:"Resumo Diário",batchNotifications:"Agrupar notificações em um único resumo diário",sendAt:"Enviar às {{time}}",editProviderToChangeDigestTime:"Edite o provedor para alterar o horário do resumo",edit:"Editar",deleteProvider:"Excluir Provedor de Notificação",deleteConfirm:'Tem certeza que deseja excluir "{{name}}"? Isso não pode ser desfeito.',delete:"Excluir",addTitle:"Adicionar Provedor de Notificação",editTitle:"Editar Provedor de Notificação",nameLabel:"Nome *",namePlaceholder:"Minhas Notificações",providerTypeLabel:"Tipo de Provedor *",configuration:"Configuração",testConfiguration:"Testar Configuração",printerFilter:"Filtro de Impressora",onlyFromPrinter:"Enviar notificações apenas para eventos desta impressora",quietHoursDnd:"Horário de Silêncio (Não Perturbe)",quietStart:"Início",quietEnd:"Fim",dailyDigestLabel:"Resumo Diário",sendDigestAt:"Enviar resumo às",digestCollected:"Os eventos serão coletados e enviados como um único resumo neste horário",notificationEvents:"Eventos de Notificação",progressPercent:"(25%, 50%, 75%)",bedCooledAfterPrint:"(após conclusão da impressão)",cancel:"Cancelar",save:"Salvar",add:"Adicionar",nameRequired:"Nome é obrigatório",fieldRequired:"{{field}} é obrigatório",phoneNumber:"Número de Telefone",apiKey:"Chave da API",serverUrl:"URL do Servidor",topic:"Tópico",authToken:"Token de Autenticação",userKey:"Chave do Usuário",appToken:"Token do Aplicativo",priority:"Prioridade",botToken:"Token do Bot",chatId:"ID do Chat",smtpServer:"Servidor SMTP",smtpPort:"Porta SMTP",security:"Segurança",authentication:"Autenticação",username:"Usuário",password:"Senha",fromEmail:"E-mail de Origem",toEmail:"E-mail de Destino",webhookUrl:"URL do Webhook",payloadFormat:"Formato do Payload",authorization:"Autorização",titleFieldName:"Nome do Campo de Título",messageFieldName:"Nome do Campo de Mensagem",editTemplate:"Editar Modelo: {{name}}",titleLabel:"Título",bodyLabel:"Corpo",titlePlaceholder:"Título da notificação...",bodyPlaceholder:"Corpo da notificação...",availableVariables:"Variáveis Disponíveis",clickToInsert:"Clique para inserir na posição do cursor no corpo",livePreview:"Pré-visualização ao Vivo",hide:"Ocultar",show:"Mostrar",loadingPreview:"Carregando pré-visualização...",enterTemplateContent:"Insira o conteúdo do modelo para ver a pré-visualização",titlePreview:"Título:",bodyPreview:"Corpo:",resetToDefault:"Restaurar Padrão",titleRequired:"Título é obrigatório",bodyRequired:"Corpo é obrigatório",notificationLog:"Registro de Notificações",showFailedOnly:"Apenas falhas",last24Hours:"Últimas 24 horas",last7Days:"Últimos 7 dias",last30Days:"Últimos 30 dias",last90Days:"Últimos 90 dias",justNow:"Agora mesmo",noFailedNotifications:"Nenhuma notificação com falha",noNotificationsLogged:"Nenhuma notificação registrada",unknownProvider:"Provedor Desconhecido",logTitle:"Título",logMessage:"Mensagem",logError:"Erro",logProvider:"Provedor: {{type}}",logTime:"Hora: {{time}}",refresh:"Atualizar",clearOld:"Limpar Antigos",statsSummary:"Últimos {{days}} dias:",statsNotifications:"notificações",statsSent:"{{count}} enviadas",statsFailed:"{{count}} com falha",eventTypes:{print_start:"Impressão Iniciada",print_complete:"Impressão Concluída",print_failed:"Impressão Falhou",print_stopped:"Impressão Parada",print_progress:"Progresso",printer_offline:"Impressora Offline",printer_error:"Erro da Impressora",filament_low:"Filamento Baixo",maintenance_due:"Manutenção Necessária",test:"Teste"},userEmail:{title:"Notificações",emailNotifications:"Notificações por E-mail",emailNotificationsDesc:"Receba notificações por e-mail para seus próprios trabalhos de impressão. Os e-mails são enviados usando as configurações SMTP definidas na Autenticação Avançada.",sendingTo:"As notificações serão enviadas para",noEmailWarning:"Sua conta não tem um endereço de e-mail. Entre em contato com um administrador para adicionar um.",printJobNotifications:"Notificações de Trabalhos de Impressão",printJobNotificationsDesc:"Escolha quais eventos acionam notificações por e-mail para os trabalhos de impressão que você envia.",printJobStarts:"Início do Trabalho de Impressão",printJobStartsDesc:"Ser notificado quando seu trabalho de impressão começar.",printJobFinishes:"Conclusão do Trabalho de Impressão",printJobFinishesDesc:"Ser notificado quando seu trabalho de impressão concluir com sucesso.",printErrors:"Erros de Impressão",printErrorsDesc:"Ser notificado quando seu trabalho de impressão falhar ou encontrar um erro.",printJobStops:"Trabalho de Impressão Parado",printJobStopsDesc:"Ser notificado quando seu trabalho de impressão for cancelado ou parado.",saveSuccess:"Preferências de notificação salvas.",saveError:"Falha ao salvar preferências de notificação."}},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:{},time:{unknown:"-",waiting:"Aguardando",justNow:"Agora mesmo",now:"Agora",minsAgo:"{{count}}min atrás",inMins:"em {{count}}min",hoursAgo:"{{count}}h atrás",inHours:"em {{count}}h",daysAgo:"{{count}}d atrás",inDays:"em {{count}}d"},spoolbuddy:{nav:{dashboard:"Painel",ams:"AMS",inventory:"Inventário",writeTag:"Escrever",settings:"Configurações"},status:{nfcReady:"NFC pronto",nfcOff:"NFC desligado",offline:"Offline",online:"Online",noPrinters:"Sem impressoras",deviceOffline:"Dispositivo offline",waitingConnection:"Aguardando conexão do dispositivo...",systemReady:"Sistema pronto",status:"Status"},dashboard:{readyToScan:"Pronto para escanear",idleMessage:"Coloque um carretel na balança para identificá-lo",nfcHint:"A tag NFC será lida automaticamente",device:"Dispositivo",syncWeight:"Sincronizar peso",weightSynced:"Sincronizado!",unknownTag:"Tag desconhecida",newTag:"Nova tag detectada",onScale:"na balança",linkSpool:"Vincular ao carretel",linkTagTitle:"Vincular tag ao carretel",linkTag:"Vincular tag",selectSpool:"Selecione um carretel para vincular a esta tag:",noUntagged:"Nenhum carretel sem tag encontrado",tagDetected:"Tag detectada",noTag:"Sem tag",tagId:"Tag",grossWeight:"Peso bruto",spoolSize:"Tamanho do carretel",close:"Fechar",currentSpool:"Carretel Atual"},modal:{spoolDetected:"Carretel Detectado",assignToAms:"Atribuir ao AMS",syncWeight:"Sincronizar Peso",weightSynced:"Sincronizado!",syncing:"Sincronizando...",newTagDetected:"Nova Tag Detectada",addToInventory:"Adicionar ao Inventário",assignToAmsTitle:"Atribuir ao AMS",selectSlot:"Selecionar um slot",assign:"Atribuir",assigning:"Atribuindo...",assignSuccess:"Atribuído!",assignError:"Falha ao atribuir carretel. Tente novamente.",noPrinterSelected:"Selecionar uma impressora...",noAmsDetected:"Nenhum AMS detectado nesta impressora",slot:"Slot"},weight:{noReading:"Sem leitura",stable:"Estável",measuring:"Medindo...",tare:"Tarar",calibrate:"Calibrar"},spool:{remaining:"Restante",material:"Material",brand:"Marca",color:"Cor",coreWeight:"Núcleo",labelWeight:"Rótulo",scaleWeight:"Balança",netWeight:"Líquido",lastUsed:"Último uso"},ams:{noData:"Nenhum AMS detectado",connectAms:"Conecte um AMS para ver os slots",noPrinter:"Nenhuma impressora selecionada",selectPrinter:"Selecione uma impressora na barra superior",printerDisconnected:"Impressora desconectada",humidity:"Umidade",level:"Nível",active:"Ativo",slot:"Slot",empty:"Vazio"},inventory:{search:"Buscar carretéis...",empty:"Nenhum carretel no inventário",noResults:"Nenhum carretel correspondente",spools:"carretéis",addSpool:"Adicionar carretel"},settings:{tabDevice:"Dispositivo",tabDisplay:"Tela",tabScale:"Balança",tabUpdates:"Atualizações",nfcReader:"Leitor NFC",type:"Tipo",connection:"Conexão",notConnected:"N/A",deviceInfo:"Info do dispositivo",hostname:"Host",uptime:"Tempo de atividade",brightness:"Brilho",saved:"Salvo",noBacklight:"Nenhuma retroiluminação DSI detectada. O controle de brilho requer uma tela DSI.",screenBlank:"Tempo para desligar tela",screenBlankDesc:"A tela desliga após inatividade. Toque para despertar.",displayNote:"O brilho é aplicado como filtro de software.",scaleCalibration:"Calibração da balança",currentWeight:"Peso atual",tareOffset:"Tara",calFactor:"Fator",knownWeight:"Peso conhecido",calStep1:"Remova todos os itens da balança e pressione Definir zero.",calStep2:"Coloque o peso conhecido na balança.",setZero:"Definir zero",calibrateNow:"Calibrar",calibrated:"Calibrado",tareSet:"Comando de tara enviado. Aguardando dispositivo...",tareFailed:"Falha ao enviar comando de tara",zeroSet:"Ponto zero definido. Coloque o peso conhecido na balança.",calibrationDone:"Calibração concluída!",calibrationFailed:"Falha na calibração",lastCalibrated:"Última calibração",stable:"Estável",settling:"Estabilizando...",firmware:"Firmware",scale:"Balança",noDevice:"Nenhum dispositivo SpoolBuddy encontrado",daemonVersion:"Versão do daemon",currentVersion:"Atual",versionPending:"Aguardando daemon...",checking:"Verificando...",checkUpdates:"Verificar atualizações",updateAvailable:"Atualização disponível",updateInstructions:"Atualize via SSH: execute o script de instalação do SpoolBuddy.",upToDate:"Atualizado",includeBeta:"Incluir versões beta"},writeTag:{tabExisting:"Bobina existente",tabNew:"Nova bobina",tabReplace:"Substituir tag",searchPlaceholder:"Buscar por material, cor, marca...",noUntaggedSpools:"Nenhuma bobina sem tag",noTaggedSpools:"Nenhuma bobina com tag",selectSpool:"Selecione uma bobina e coloque um NTAG no leitor",placeTag:"Coloque um NTAG no leitor",tagReady:"Tag detectado — pronto para gravar",writeTag:"Gravar Tag",replaceTag:"Substituir Tag",writing:"Gravando tag...",waiting:"Aguardando SpoolBuddy...",writeSuccess:"Tag gravado com sucesso!",writeFailed:"Falha na gravação",queueFailed:"Falha ao enfileirar comando de gravação",tryAgain:"Tentar novamente",cancel:"Cancelar",replaceWarning:"O tag antigo será desvinculado. O novo tag o substituirá.",deviceOffline:"SpoolBuddy está offline",material:"Material",colorName:"Nome da cor",color:"Cor",brand:"Marca",weight:"Peso (g)",createSpool:"Criar bobina",creating:"Criando...",spoolCreated:"Bobina criada! Pronto para gravar.",createFailed:"Falha ao criar bobina"},quickMenu:{printerPower:"Energia da impressora",systemControls:"Sistema",restartDaemon:"Reiniciar daemon",restartBrowser:"Reiniciar navegador",reboot:"Reiniciar",shutdown:"Desligar",swipeToClose:"Deslize para baixo para fechar",confirmTitle:"Confirmar",confirmShutdown:"Tem certeza de que deseja desligar o SpoolBuddy? Você precisará de acesso físico para ligá-lo novamente.",confirmReboot:"Tem certeza de que deseja reiniciar o SpoolBuddy?",confirmRestartDaemon:"Reiniciar o daemon do SpoolBuddy? NFC e balança ficarão temporariamente indisponíveis.",confirmRestartBrowser:"Reiniciar o navegador kiosk? A tela ficará brevemente preta.",confirm:"Confirmar",confirmPlugOn:"Ligar {{name}}?",confirmPlugOff:"Desligar {{name}}?",turnOn:"Ligar",turnOff:"Desligar"}},bugReport:{title:"Reportar um bug",description:"Descrição",descriptionPlaceholder:"O que deu errado? Por favor, descreva o problema...",email:"Email (opcional)",emailPlaceholder:"seu@email.com.br",emailPrivacy:"Se fornecido, seu email será incluído em uma seção recolhida da issue no GitHub para que o mantenedor possa entrar em contato.",screenshot:"Captura de tela",uploadOrPaste:"Enviar, colar ou arrastar uma imagem",dataCollectedSummary:"Quais dados são incluídos no relatório?",dataIncluded:"Incluídos:",dataIncludedList:"Versão do app, SO, arquitetura, versão Python, estatísticas do banco de dados (apenas contagens), modelos de impressora, quantidade de bicos, versões de firmware, status de conexão, status de integrações (Spoolman, MQTT, HA), configurações não sensíveis, contagem de interfaces de rede, detalhes Docker, versões de dependências.",dataNeverIncluded:"Nunca incluídos:",dataNeverIncludedList:"Nomes de impressoras, números de série, códigos de acesso, senhas, endereços IP, endereços de email, chaves de API, tokens, URLs de webhook, nomes de host ou nomes de usuário.",submit:"Enviar",startLogging:"Iniciar log de depuração",stepEnableLogging:"Log de depuração ativado",stepReproduce:"Reproduza o problema agora",stepStopLogging:"Parar & enviar relatório",stopAndSubmit:"Parar & Enviar",maxDuration:"Para automaticamente após {{minutes}} min",stoppingLogs:"Coletando logs & enviando...",submitting:"Enviando relatório de bug...",submitSuccess:"Relatório de bug enviado com sucesso!",submitFailed:"Falha ao enviar relatório de bug",thankYou:"Obrigado!",submitted:"Seu relatório de bug foi enviado.",viewIssue:"Ver issue",unexpectedError:"Ocorreu um erro inesperado"},failureDetection:{title:"Detecção de Falhas por IA",description:"Monitora impressões via API ML do Obico auto-hospedada e age automaticamente em falhas detectadas.",mlUrl:"URL da API ML do Obico",mlUrlHint:"URL base do seu contêiner Obico ml_api auto-hospedado (ex.: http://192.168.1.10:3333).",test:"Testar",testSuccess:"API ML acessível e operacional.",testFailed:"Não foi possível acessar a API ML.",sensitivity:"Sensibilidade",sensitivityLow:"Baixa (menos falsos positivos)",sensitivityMedium:"Média (equilibrada)",sensitivityHigh:"Alta (detecção precoce, mais falsos positivos)",sensitivityHint:"Ajusta os limiares de confiança que disparam avisos e falhas.",action:"Ação em falha detectada",actionNotify:"Apenas notificar",actionPause:"Pausar impressão",actionPauseOff:"Pausar e cortar energia",pollInterval:"Intervalo de verificação (segundos)",pollIntervalHint:"Frequência de verificação de cada impressora durante a impressão. Mínimo 5s, máximo 120s.",externalUrlMissing:"URL externa não configurada.",externalUrlHint:"A API ML busca a imagem da câmera por URL. Defina a URL externa nas configurações gerais para que o contêiner da API ML possa alcançar o Bambuddy.",perPrinterTitle:"Impressoras monitoradas",perPrinterHint:"Escolha quais impressoras o serviço de detecção monitora.",monitorAll:"Monitorar todas as impressoras conectadas",statusTitle:"Status",serviceRunning:"Serviço em execução",thresholds:"Limiares baixo / alto",activePrinters:"Impressões ativas",noActivePrints:"Nenhuma impressão em andamento.",historyTitle:"Detecções recentes",noHistory:"Nenhuma detecção ainda."}},Vue={nav:{printers:"打印机",archives:"归档",queue:"队列",stats:"统计",profiles:"配置文件",maintenance:"维护",projects:"项目",inventory:"耗材",files:"文件管理器",notifications:"通知",settings:"设置",system:"系统",collapseSidebar:"收起侧边栏",expandSidebar:"展开侧边栏",update:"更新",updateAvailable:"有可用更新:v{{version}}",updateAvailableBanner:"版本 {{version}} 已发布!",viewUpdate:"查看更新",viewOnGithub:"在 GitHub 上查看",keyboardShortcuts:"键盘快捷键 (?)",switchToLight:"切换到浅色模式",switchToDark:"切换到深色模式",smartSwitches:"智能开关",logout:"退出登录"},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:"上传",uploading:"上传中...",uploadFailed:"上传失败",actions:"操作",status:"状态",name:"名称",description:"描述",date:"日期",time:"时间",hours:"小时",minutes:"分钟",seconds:"秒",days:"天",enable:"启用",disable:"禁用",permissions:"权限",noPrinters:"未配置打印机",noData:"暂无数据",linkNotFound:"未找到链接",required:"必填",optional:"可选",dismiss:"关闭",apply:"应用",reset:"重置",export:"导出",import:"导入",clear:"清除",selectAll:"全选",deselectAll:"取消全选",noChange:"— 不更改 —",unchanged:"未更改",unassigned:"未分配",unknown:"未知",unknownError:"未知错误",today:"今天",tomorrow:"明天",asap:"尽快",overdue:"已逾期",now:"现在",collapse:"收起",expand:"展开",viewArchive:"查看归档",viewInFileManager:"在文件管理器中查看",addedBy:"由 {{username}} 添加",prints:"次打印",more:"还有 {{count}} 个",ascending:"升序",descending:"降序",back:"返回",copy:"复制",copied:"已复制!",printer:"打印机",remove:"移除",type:"类型",print:"打印",rename:"重命名",move:"移动",create:"创建",duplicate:"复制",left:"左",right:"右"},printers:{title:"打印机",addPrinter:"添加打印机",editPrinter:"编辑打印机",deletePrinter:"删除打印机",printerName:"打印机名称",serialNumber:"序列号",ipAddress:"IP 地址 / 主机名",accessCode:"访问码",model:"型号",nozzleCount:"喷嘴数量",autoArchive:"自动归档",status:{available:"可用",idle:"空闲",printing:"打印中",paused:"已暂停",offline:"离线",problem:"故障",error:"错误",finished:"已完成",unknown:"未知"},temperatures:{nozzle:"喷嘴",bed:"热床",chamber:"腔室"},progress:"{{percent}}% 完成",timeRemaining:"剩余 {{time}}",deleteConfirm:'确定要删除"{{name}}"吗?',maintenanceOk:"维护正常",maintenanceWarning:"{{count}} 个警告",maintenanceWarning_plural:"{{count}} 个警告",maintenanceDue:"{{count}} 个到期",maintenanceDue_plural:"{{count}} 个到期",sort:{name:"名称",status:"状态",model:"型号",location:"位置",ascending:"升序排列",descending:"降序排列"},cardSize:{small:"小卡片",medium:"中卡片",large:"大卡片",extraLarge:"超大卡片"},hideOffline:"隐藏离线",nextAvailable:"下一个可用",powerOn:"开机",offlinePrintersWithPlugs:"带智能插座的离线打印机",noPrintersConfigured:"尚未配置打印机",search:"搜索打印机...",noSearchResults:"没有打印机符合您的搜索或筛选条件",filter:{allStatuses:"所有状态",allLocations:"所有位置"},readyToPrint:"准备打印",external:"外部",extL:"外置左",extR:"外置右",deleteArchives:"删除打印归档",noLabel:"无标签",printPreview:"打印预览",width:"宽度",height:"高度",noObjectsFound:"未找到对象",objectsLoadedOnPrintStart:"对象在打印开始时加载",willBeSkipped:"将被跳过",name:"名称",serialCannotBeChanged:"序列号无法更改",locationHelp:"用于分组打印机和筛选队列任务",wifiSignal:{veryWeak:"非常弱",weak:"弱",fair:"一般",good:"良好",excellent:"优秀"},maintenanceUpToDate:"所有维护均已完成 - 点击查看",chamberLightOn:"打开腔室灯",chamberLightOff:"关闭腔室灯",files:"文件",browseFiles:"浏览打印机文件",autoOffAfterPrint:"打印后自动关机",autoOffExecuted:"已执行自动关机 - 开启打印机以重置",hmsErrors:"HMS 错误",viewHmsErrors:"查看 {{count}} 个 HMS 错误",resume:"继续",pause:"暂停",stop:"停止",camera:"摄像头",skipObject:"跳过对象",reconnect:"重新连接",forceRefresh:"强制刷新",forceRefreshSuccess:"已请求刷新",mqttDebug:"MQTT 调试",printerInformation:"打印机信息",copyToClipboard:"复制",copied:"已复制!",state:"状态",wifiSignalLabel:"WiFi 信号",developerMode:"开发者模式",enabled:"已启用",disabled:"已禁用",addedOn:"添加日期",sdCard:"SD 卡",inserted:"已插入",notInserted:"未插入",totalPrintHours:"打印时长",activeNozzle:"当前:{{nozzle}} 喷嘴",nozzleRack:"喷嘴架",nozzleDocked:"已停靠",nozzleMounted:"已安装",nozzleActive:"使用中",nozzleIdle:"空闲",nozzleDiameter:"直径",nozzleType:"类型",nozzleStatus:"状态",nozzleFilament:"耗材",nozzleWear:"磨损",nozzleMaxTemp:"最高温度",nozzleSerial:"序列号",nozzleHardenedSteel:"硬化钢",nozzleStainlessSteel:"不锈钢",nozzleTungstenCarbide:"碳化钨",nozzleFlow:"流量",nozzleHighFlow:"高流量",nozzleStandardFlow:"标准",firmwareUpdate:"固件更新",firmwareInstructions:"在打印机触摸屏上,前往",firmwareNav:"导航到",settings:"设置",firmware:"固件",discoverPrinters:"发现打印机",searching:"搜索中...",manualEntry:"手动输入",addFromCloud:"从云端添加",toast:{printerDeleted:"打印机已删除",missingSpoolAssignment:"已在{{printer}}上开始打印。以下料槽未分配耗材: {{slots}}",printerAdded:"打印机已添加",printerUpdated:"打印机已更新",failedToDelete:"删除打印机失败",failedToAdd:"添加打印机失败",failedToUpdate:"更新打印机失败",commandSent:"命令已发送",failedToSendCommand:"发送命令失败",turnedOn:"{{name}} 已开启",failedToPowerOn:"开启 {{name}} 失败",scriptTriggered:"脚本已触发",printStopped:"打印已停止",printPaused:"打印已暂停",printResumed:"打印已继续",referenceDeleted:"参考已删除",detectionAreaSaved:"检测区域已保存",failedToRunScript:"运行脚本失败",failedToStopPrint:"停止打印失败",failedToPausePrint:"暂停打印失败",failedToResumePrint:"继续打印失败",failedToControlChamberLight:"控制腔室灯失败",failedToSetSpeed:"设置打印速度失败",failedToUpdateSetting:"更新设置失败",failedToSkipObjects:"跳过对象失败",failedToRereadRfid:"重新读取 RFID 失败",failedToCheckPlate:"检查打印板失败",failedToUpdateLabel:"更新标签失败",failedToDeleteReference:"删除参考失败",failedToSaveDetectionArea:"保存检测区域失败",plateCheckEnabled:"打印板检查已启用",plateCheckDisabled:"打印板检查已禁用",calibrationSaved:"校准已保存!",calibrationFailed:"校准失败",rfidRereadInitiated:"已发起 RFID 重新读取"},connection:{connected:"已连接",offline:"离线"},queue:{inQueue:"队列中有 {{count}} 个打印任务",inQueue_plural:"队列中有 {{count}} 个打印任务"},controls:"控制",rfid:{reread:"重新读取 RFID"},permission:{noAdd:"您没有添加打印机的权限",noEdit:"您没有编辑打印机的权限",noDelete:"您没有删除打印机的权限",noControl:"您没有控制打印机的权限",noFiles:"您没有访问打印机文件的权限",noAmsRfid:"您没有重新读取 AMS RFID 的权限",noSmartPlugControl:"您没有控制智能插座的权限",noCamera:"您没有查看摄像头的权限"},modal:{addTitle:"添加打印机",editTitle:"编辑打印机",myPrinter:"我的打印机",selectModel:"选择型号...",locationGroup:"位置 / 分组(可选)",locationPlaceholder:"例如:工作室、办公室、地下室",autoArchiveLabel:"自动归档已完成的打印",fromPrinterSettings:"来自打印机设置",modelOptional:"型号(可选)",saveChanges:"保存更改"},skipObjects:{tooltip:"跳过对象",onlyWhilePrinting:"跳过对象(仅在打印时)",requiresMultiple:"跳过对象(需要2个以上对象)",title:"跳过对象",matchIdsInfo:"将 ID 与打印机显示屏上的 ID 进行对照",printerShowsIds:"打印机屏幕上显示构建板上对象的 ID",skipSelected:"跳过所选",skipping:"跳过中...",noObjectsSelected:"未选择对象",selectObjectsToSkip:"选择要从当前打印中跳过的对象",skipped:"已跳过",objectsSkipped:"对象已跳过",activeCount:"{{count}} 个活跃",waitForLayer:"等待第2层以上才能跳过对象(当前第 {{layer}} 层)",skip:"跳过",confirmTitle:"跳过对象?",confirmMessage:'确定要跳过"{{name}}"吗?此操作无法撤销。'},confirm:{deleteTitle:"删除打印机",deleteMessage:'确定要删除"{{name}}"吗?这将移除所有连接设置。',deleteArchivesNote:"此打印机的所有打印历史将被永久删除。",keepArchivesNote:"打印历史将保留,但不再与此打印机关联。",stopTitle:"停止打印",stopMessage:'确定要停止"{{name}}"上的当前打印吗?这将取消打印任务。',stopButton:"停止打印",pauseTitle:"暂停打印",pauseMessage:'确定要暂停"{{name}}"上的当前打印吗?',pauseButton:"暂停打印",resumeTitle:"继续打印",resumeMessage:'确定要继续"{{name}}"上的打印吗?',resumeButton:"继续打印",powerOnTitle:"开启打印机",powerOnMessage:'确定要打开"{{name}}"的电源吗?',powerOnButton:"开机",powerOffTitle:"关闭打印机",powerOffMessage:'确定要关闭"{{name}}"的电源吗?',powerOffWarning:'警告:"{{name}}"正在打印中!确定要关闭电源吗?这将中断打印并可能损坏打印机。',powerOffButton:"关机"},bulk:{select:"选择",selectAll:"全选",selectByLocation:"按位置选择",selected:"已选择{{count}}台",actions:{stop:"停止",pause:"暂停",resume:"继续",clearPlate:"清除打印床",clearHMS:"清除通知"},confirm:{stopTitle:"停止{{count}}个打印任务",stopMessage:"这将取消{{count}}台打印机上的活动打印任务。此操作无法撤销。",stopButton:"全部停止",pauseTitle:"暂停{{count}}个打印任务",pauseMessage:"这将暂停{{count}}台打印机上的活动打印任务。",pauseButton:"全部暂停",clearPlateTitle:"清除{{count}}个打印床",clearPlateMessage:"这将清除{{count}}台打印机的打印床,可能会触发队列中的任务。",clearPlateButton:"全部清除"},success:"{{action}}已在{{count}}台打印机上完成",partial:"{{succeeded}}成功,{{failed}}失败",noneApplicable:"没有选中的打印机处于适合此操作的状态",selectByState:"按状态选择"},discovery:{title:"发现打印机",searching:"搜索中...",scanning:"扫描中...",scanProgress:"扫描中... {{scanned}}/{{total}}",foundPrinters:"发现 {{count}} 台打印机",noPrintersFound:"未找到打印机",noPrintersFoundSubnet:"在指定子网中未找到打印机。",noPrintersFoundNetwork:"在网络上未找到打印机。",allConfigured:"所有发现的打印机已配置完毕。",alreadyAdded:"已添加",select:"选择",manualEntry:"手动输入",addFromCloud:"从云端添加",subnetToScan:"要扫描的子网",dockerNote:"检测到 Docker 环境。请以 CIDR 格式输入打印机所在子网。需要在 docker-compose.yml 中设置 network_mode: host。",scanSubnet:"扫描子网查找打印机",discoverNetwork:"在网络上发现打印机",scanningSubnet:"正在扫描子网查找拓竹打印机...",scanningNetwork:"正在扫描网络...",serialRequired:"需要序列号",unknown:"未知",failedToStart:"启动发现失败"},drying:{start:"开始干燥",stop:"停止干燥",temperature:"温度",duration:"时长",hours:"小时",timeRemaining:"剩余 {{time}}",active:"干燥中",notSupported:"不支持干燥",powerRequired:"连接AMS电源适配器以启用干燥",startingDrying:"正在启动干燥...",stoppingDrying:"正在停止干燥...",rotateTray:"干燥时旋转料盘"},filaments:"耗材",openCameraOverlay:"打开摄像头叠加层",openCameraWindow:"在新窗口中打开摄像头",firmwareUpdateAvailable:"固件更新可用:{{current}} → {{latest}}",firmwareUpToDate:"固件 {{version}} — 已是最新",firmwareUpdateButton:"更新",plateDetection:{noPermission:"您没有更新打印机的权限",enabledClick:"打印板检查已启用 - 点击禁用",disabledClick:"打印板检查已禁用 - 点击启用",manageCalibration:"管理打印板检测校准",calibrationRequired:"需要校准",calibrationInstructions:"请确保构建板<strong>完全空置</strong>,然后点击校准。",calibrationDescription:"校准会拍摄空置打印板的参考图像。后续检查将与此参考进行比较以检测物体。",calibrationTip:"<strong>提示:</strong>您最多可以为不同的打印板存储5个校准。系统会在检查时自动使用最佳匹配。",plateEmpty:"打印板似乎是空的",objectsDetected:"在打印板上检测到物体",confidence:"置信度",difference:"差异",analysisPreview:"分析预览:",analysisLegend:"绿色框 = 检测区域,红色覆盖 = 与校准的差异",savedReferences:"已保存的参考 ({{count}}/{{max}})",deleteReference:"删除参考",labelPlaceholder:"标签...",clickToEdit:"{{label}} - 点击编辑",clickToAddLabel:"点击添加标签"},speed:{title:"打印速度",silent:"静音 (50%)",standard:"标准 (100%)",sport:"运动 (124%)",ludicrous:"疯狂 (166%)"},airduct:{title:"风道模式",cooling:"制冷",heating:"加热"},noSdCard:"无SD",door:{open:"开",closed:"关"},fans:{partCooling:"零件冷却风扇",auxiliary:"辅助风扇",chamber:"腔室风扇"},clickToViewHmsErrors:"点击查看 HMS 错误",estimatedCompletion:"预计完成时间",plateNumber:"板 {{number}}",slotOptions:"槽位选项",amsPopup:{friendlyName:"AMS 名称",friendlyNamePlaceholder:"例如 AMS 友好名称",serialNumber:"序列号",firmwareVersion:"固件",save:"保存",clear:"清除",noEditPermission:"您没有重命名 AMS 单元的权限"},firmwareModal:{title:"固件更新",titleUpToDate:"固件信息",currentVersion:"当前版本:",latestVersion:"最新版本:",releaseNotes:"发布说明",checkingPrereqs:"正在检查前提条件...",sdCardReady:"SD 卡已就绪。点击下方上传固件。",uploadedSuccess:"固件已上传到 SD 卡!",applyInstructions:"在打印机上应用更新:",step1:"在打印机触摸屏上,前往<strong>设置</strong>",step2:"导航到<strong>固件</strong>",step3:"选择<strong>从 SD 卡更新</strong>",step4:"更新将需要 10-20 分钟",done:"完成",starting:"启动中...",uploadFirmware:"上传固件",uploadFailed:"上传启动失败:{{error}}",uploadedToast:"固件已上传!请在打印机屏幕上触发更新。"},accessCodePlaceholder:"留空以保持当前值",roi:{title:"检测区域 (ROI)",xStart:"X 起点",yStart:"Y 起点",width:"宽度",height:"高度",instruction:"调整检测区域以聚焦到构建板。预览中的绿色框显示当前区域。"},developerModeWarning:"以下打印机未启用开发者局域网模式:{{names}}。某些功能可能无法使用。",howToEnable:"如何启用",incompatibleFile:"此文件是为 {{slicedFor}} 切片的,但该打印机是 {{printerModel}}",dropNotPrintable:"只能打印 .gcode 和 .gcode.3mf 文件",dropToPrint:"拖放以打印",cannotPrint:"打印机忙碌"},archives:{title:"打印归档",searchPlaceholder:"搜索归档...",filterByPrinter:"按打印机筛选",filterByStatus:"按状态筛选",sortBy:"排序方式",sortNewest:"最新优先",sortOldest:"最旧优先",sortName:"名称",sortDuration:"时长",sortLargest:"最大优先",sortSmallest:"最小优先",sortSize:"大小",noArchives:"未找到归档",noArchivesSearch:"没有匹配搜索的归档",originalPrintNotVisible:"原始打印不可见 - 请尝试清除筛选条件",noArchivesYet:"暂无归档",prints:"条打印",pagination:{showing:"显示",to:"至",of:"共",show:"每页",page:"页",all:"全部"},loadingArchives:"加载归档中...",releaseToUpload:"释放以上传",showAll:"显示全部",showFavoritesOnly:"仅显示收藏",gridView:"网格视图",listView:"列表视图",calendarView:"日历视图",logView:"打印日志",manageTags:"管理标签",showFailedPrints:"显示失败的打印",hideFailedPrints:"隐藏失败的打印",hideDuplicates:"隐藏重复项",viewOriginalPrint:"点击查看原始打印 (#{{id}})",printTime:"打印时间",filamentUsed:"耗材用量",cost:"成本",reprint:"重新打印",preview:"预览",deleteArchive:"删除归档",deleteConfirm:"确定要删除此归档吗?",favorite:"收藏",unfavorite:"取消收藏",viewDetails:"查看详情",status:{completed:"已完成",failed:"失败",stopped:"已停止"},toast:{source3mfAttached:"源 3MF 已附加:{{filename}}",failedUploadSource3mf:"上传源 3MF 失败",source3mfRemoved:"源 3MF 已移除",failedRemoveSource3mf:"移除源 3MF 失败",f3dAttached:"F3D 已附加:{{filename}}",failedUploadF3d:"上传 F3D 失败",f3dRemoved:"F3D 已移除",failedRemoveF3d:"移除 F3D 失败",timelapseAttached:"延时摄影已附加:{{filename}}",timelapseAlreadyAttached:"延时摄影已附加",noMatchingTimelapse:"未找到匹配的延时摄影",failedScanTimelapse:"扫描延时摄影失败",failedAttachTimelapse:"附加延时摄影失败",timelapseRemoved:"延时摄影已移除",failedRemoveTimelapse:"移除延时摄影失败",timelapseUploaded:"延时摄影已上传:{{filename}}",failedUploadTimelapse:"上传延时摄影失败",archiveDeleted:"归档已删除",failedDeleteArchive:"删除归档失败",addedToFavorites:"已添加到收藏",removedFromFavorites:"已从收藏中移除",projectUpdated:"项目已更新",failedUpdateProject:"更新项目失败",linkCopied:"链接已复制到剪贴板",failedCopyLink:"复制链接失败",photoDeleted:"照片已删除",failedDeletePhoto:"删除照片失败",failedDeleteArchives:"删除归档失败",failedUpdateFavorites:"更新收藏失败",exportDownloaded:"导出已下载",exportFailed:"导出失败"},menu:{print:"打印",schedule:"排程",openInBambuStudio:"在切片软件中打开",slice:"切片",externalLink:"外部链接",viewOnMakerWorld:"在 MakerWorld 上查看",preview3d:"3D 预览",viewTimelapse:"查看延时摄影",scanForTimelapse:"扫描延时摄影",uploadTimelapse:"上传延时摄影",removeTimelapse:"移除延时摄影",downloadSource3mf:"下载源 3MF",uploadSource3mf:"上传源 3MF",replaceSource3mf:"替换源 3MF",removeSource3mf:"移除源 3MF",uploadF3d:"上传 F3D",replaceF3d:"替换 F3D",downloadF3d:"下载 F3D",removeF3d:"移除 F3D",download:"下载",copyDownloadLink:"复制下载链接",qrCode:"二维码",viewPhotos:"查看照片",viewPhotosCount:"查看照片 ({{count}})",projectPage:"项目页面",addToFavorites:"添加到收藏",removeFromFavorites:"从收藏中移除",edit:"编辑",goToProject:"前往项目:{{name}}",addToProject:"添加到项目",removeFromProject:"从项目中移除",loading:"加载中...",noProjectsAvailable:"无可用项目",select:"选择",deselect:"取消选择",delete:"删除"},permission:{noReprint:"您没有重新打印此归档的权限",noAddToQueue:"您没有添加到队列的权限",noUpdateArchives:"您没有更新归档的权限",noUploadFiles:"您没有上传文件的权限",noDownload:"您没有下载归档的权限",noCopyLink:"您没有复制下载链接的权限",noDelete:"您没有删除此归档的权限",noCreate:"您没有创建归档的权限"},card:{previousPlate:"上一个板",nextPlate:"下一个板",plateNumber:"板 {{index}}",moreOptions:"右键查看更多选项",addToFavorites:"添加到收藏",removeFromFavorites:"从收藏中移除",cancelled:"已取消",failed:"失败",duplicate:"重复",duplicateTitle:"此模型之前已打印过",openSource3mf:"在 Bambu Studio 中打开源 3MF(右键查看更多选项)",downloadF3d:"下载 Fusion 360 设计文件",viewTimelapse:"查看延时摄影",viewPhoto:"查看 1 张照片",viewPhotos:"查看 {{count}} 张照片",openFolder:"打开文件夹:{{name}}",slicedFile:"已切片文件 - 可以打印",sourceFile:"仅源文件 - 无 AMS 映射可用",gcode:"GCODE",source:"源文件",project:"项目:{{name}}",estimated:"预计:{{time}}",actual:"实际:{{time}}",accuracy:"准确度:{{percent}}%",filament:"{{weight}}g",layer:"{{count}} 层",layers:"{{count}} 层",object:"{{count}} 个对象",objects:"{{count}} 个对象",slicedFor:"为 {{model}} 切片",uploadedBy:"上传者",noPermissionReprint:"您没有重新打印的权限",noFileForReprint:"无可用的 3MF 文件 — 打印记录时无法从打印机下载该文件",noPermissionEdit:"您没有编辑归档的权限",noPermissionDelete:"您没有删除归档的权限",reprint:"重新打印",schedulePrint:"排程打印",schedule:"排程",openInBambuStudio:"在切片软件中打开",openInBambuStudioToSlice:"在切片软件中打开进行切片",slice:"切片",externalLink:"外部链接",makerWorld:"MakerWorld:{{designer}}",viewProject:"查看项目",noExternalLink:"无外部链接",preview3d:"3D 预览",download:"下载",edit:"编辑",delete:"删除"},modal:{deleteArchive:"删除归档",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',deleteButton:"删除",removeSource3mf:"移除源 3MF",removeSource3mfConfirm:'确定要从"{{name}}"中移除源 3MF 文件吗?这将删除原始切片项目文件。',removeButton:"移除",removeF3d:"移除 F3D",removeF3dConfirm:'确定要从"{{name}}"中移除 Fusion 360 设计文件吗?',removeTimelapse:"移除延时摄影",removeTimelapseConfirm:'确定要从"{{name}}"中移除延时摄影视频吗?',timelapse:"{{name}} - 延时摄影",selectTimelapse:"选择延时摄影",selectTimelapseDesc:"未找到自动匹配。请选择此打印的延时摄影:",deleteArchives:"删除归档",deleteArchivesConfirm:"确定要删除 {{count}} 个归档吗?此操作无法撤销。",deleteCount:"删除 {{count}} 个"},page:{title:"归档",printsCount:"{{filtered}} / {{total}} 次打印",dropFilesHere:"将 .3mf 文件拖放到此处",releaseToUpload:"释放以上传",only3mfSupported:"仅支持 .3mf 文件",close:"关闭",selected:"已选择 {{count}} 个",selectAll:"全选",tags:"标签",project:"项目",favorite:"收藏",delete:"删除",toggledFavorites:"已切换 {{count}} 个归档的收藏状态",failedUpdateFavorites:"更新收藏失败",archivesDeleted:"已删除 {{count}} 个归档",failedDeleteArchives:"删除归档失败",photoDeleted:"照片已删除",failedDeletePhoto:"删除照片失败"},list:{name:"名称",printer:"打印机",date:"日期",size:"大小",actions:"操作",hasTimelapse:"有延时摄影"},log:{date:"日期",printName:"打印名称",printer:"打印机",user:"用户",status:"状态",duration:"时长",filament:"耗材",allPrinters:"所有打印机",allUsers:"所有用户",allStatuses:"所有状态",cancelled:"已取消",skipped:"已跳过",dateFrom:"从",dateTo:"到",noEntries:"未找到打印日志条目",showing:"显示 {{count}} / {{total}} 条",rowsPerPage:"行数",page:"页",prev:"上一页",next:"下一页",clearLog:"清除日志",clearLogTitle:"清除打印日志",clearLogConfirm:"所有打印日志条目将被永久删除。归档和队列项目不受影响。此操作无法撤销。确定要继续吗?",clearLogButton:"全部清除",cleared:"已清除 {{count}} 条日志",clearFailed:"清除打印日志失败"}},queue:{title:"打印队列",subtitle:"排程和管理您的打印任务",addToQueue:"添加到队列",print:"打印",reprint:"重新打印",schedulePrint:"排程打印",editQueueItem:"编辑队列项目",printToPrinters:"打印到 {{count}} 台打印机",queueToPrinters:"排队到 {{count}} 台打印机",queueSelectedPlates:"将 {{count}} 个热床加入队列",selectAllPlates:"选择全部 {{count}} 个热床",deselectAll:"取消全选",printQueued:"已加入打印队列",itemsQueued:"{{count}} 个任务已加入队列",sending:"发送中...",sendingProgress:"发送中 {{current}}/{{total}}...",adding:"添加中...",addingProgress:"添加中 {{current}}/{{total}}...",savingProgress:"保存中 {{current}}/{{total}}...",clearQueue:"清空队列",clearHistory:"清除历史",emptyQueue:"队列为空",position:"位置",scheduledTime:"排程时间",moveUp:"上移",moveDown:"下移",startNow:"立即开始",printingInProgress:"打印进行中...",viewArchive:"查看归档",viewInFileManager:"在文件管理器中查看",itemCount:"{{count}} 个项目",itemCount_plural:"{{count}} 个项目",dragToReorder:"拖动以重新排序(仅限尽快)",reorderHint:'位置仅影响"尽快"项目。排程项目按设定时间运行。',sjf:{label:"SJF",tooltip:"最短任务优先 — 调度器优先处理较短的打印任务"},addedBy:"由 {{name}} 添加",nextInQueue:"队列中的下一个",clearPlate:"清理打印板并开始下一个",clearPlateSuccess:"打印板已清理 — 准备进行下一个打印",plateReady:"打印板已清理 — 准备进行下一个打印",plateNumber:"板 {{index}}",quantity:"数量",quantityHint:"创建 {{count}} 个队列项目",activeBatches:"活跃批次",batchProgress:"已完成 {{completed}}/{{total}}",cancelBatch:"取消剩余",batchCancelled:"已取消剩余批次项目",cancelBatchConfirmTitle:"取消批次",cancelBatchConfirmMessage:"取消此批次中所有剩余的待处理项目?",batch:"批次",sections:{currentlyPrinting:"正在打印",queued:"排队中",history:"历史"},status:{pending:"等待中",waiting:"等待中",printing:"打印中",paused:"已暂停",completed:"已完成",failed:"失败",skipped:"已跳过",cancelled:"已取消"},summary:{printing:"打印中",queued:"排队中",totalTime:"总队列时间",totalWeight:"总队列重量",history:"历史"},filter:{allPrinters:"所有打印机",unassigned:"未分配",allStatus:"所有状态",allLocations:"所有位置",any:"任意"},sort:{byPosition:"按位置排序",byName:"按名称排序",byPrinter:"按打印机排序",bySchedule:"按排程排序",byDate:"按日期排序",ascendingOldest:"升序(最旧优先)",descendingNewest:"降序(最新优先)"},badges:{staged:"已暂存",requiresPrevious:"需要前一个成功",autoPowerOff:"自动关机",gcodeInjection:"G-code"},empty:{title:"没有排程的打印",description:'从归档页面使用右键菜单中的"排程"选项来排程打印,或拖放文件开始。'},time:{asap:"尽快",overdue:"已逾期",now:"现在",lessThanMinute:"不到一分钟",inMinutes:"{{count}} 分钟后",inHours:"{{count}} 小时后"},actions:{stopPrint:"停止打印",startPrint:"开始打印",requeue:"重新排队"},bulkEdit:{title:"编辑 {{count}} 个项目",title_plural:"编辑 {{count}} 个项目",description:"仅更改的设置将应用于所选项目。",printer:"打印机",noChange:"— 不更改 —",queueOptions:"队列选项",staged:"暂存(手动开始)",autoPowerOff:"打印后自动关机",requirePrevious:"要求前一个成功",printOptions:"打印选项",bedLevelling:"热床调平",flowCalibration:"流量校准",vibrationCalibration:"振动校准",layerInspection:"首层检查",timelapse:"延时摄影",useAms:"使用 AMS",applyChanges:"应用更改",selectAll:"全选",deselectAll:"取消全选",selected:"已选择 {{count}} 个",editSelected:"编辑所选",cancelSelected:"取消所选"},confirm:{cancelTitle:"取消排程打印",cancelMessage:'确定要取消"{{name}}"吗?',stopTitle:"停止打印",stopMessage:'确定要停止当前打印"{{name}}"吗?这将取消打印机上的打印任务。',removeTitle:"从历史中移除",removeMessage:'确定要从队列历史中移除"{{name}}"吗?',clearHistoryTitle:"清除历史",clearHistoryMessage:"确定要从历史中移除所有 {{count}} 个项目吗?",cancelButton:"取消打印",stopButton:"停止打印",thisPrint:"此打印",thisItem:"此项目"},toast:{cancelled:"队列项目已取消",cancelFailed:"取消项目失败",removed:"队列项目已移除",removeFailed:"移除项目失败",stopped:"打印已停止",stopFailed:"停止打印失败",released:"打印已释放到队列",startFailed:"开始打印失败",reorderFailed:"重新排序队列失败",historyCleared:"已清除 {{count}} 条历史记录",clearHistoryFailed:"清除历史失败",updateFailed:"更新项目失败",bulkCancelled:"已取消 {{count}} 个项目",bulkCancelFailed:"批量取消项目失败"},timeline:{listView:"列表",timelineView:"时间线",unassigned:"未分配",noData:"当天没有计划的打印任务",allDoneBy:"所有打印预计在 {{time}} 前完成",staged:"暂存",filterAll:"全部显示",filterPrinting:"打印中",filterQueued:"排队中",time:{anyMoment:"即将完成",minutesLeft:"剩余{{minutes}}分钟",hoursLeft:"剩余{{hours}}小时",hoursMinutesLeft:"剩余{{hours}}小时{{minutes}}分钟"},day:{previous:"前一天",next:"后一天",today:"今天"}},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}} 成功",printStartedRemaining:"{{completed}} 个打印已开始,{{remaining}} 个正在发送..."}},stats:{title:"仪表板",subtitle:"拖动小部件以重新排列。点击眼睛图标隐藏。",overview:"概览",totalPrints:"总打印次数",successRate:"成功率",totalPrintTime:"总打印时间",printTime:"打印时间",totalFilament:"总耗材用量",filamentUsed:"耗材用量",filamentCost:"耗材成本",totalCost:"总成本",energyUsed:"能耗",energyCost:"能源成本",energyWarmingUpTooltip:"能耗追踪正在收集每小时快照。当所选范围之前至少存在一个快照时,时间段合计将变得准确。早期数值可能偏低。",averagePrintTime:"平均打印时间",printsPerDay:"每日打印次数",byPrinter:"按打印机",printsByPrinter:"各打印机打印次数",byMaterial:"按材料",byMonth:"按月份",last7Days:"最近 7 天",last30Days:"最近 30 天",last90Days:"最近 90 天",allTime:"全部时间",quickStats:"快速统计",printActivity:"打印活动",filamentTypes:"耗材类型",filamentTrends:"耗材趋势",failureAnalysis:"失败分析",timeAccuracy:"时间准确度",successful:"成功:",failed:"失败:",perfectEstimate:"100% = 完美估计",noTimeAccuracyData:"暂无时间准确度数据",noFilamentData:"暂无耗材数据",noPrinterData:"暂无打印机数据",noPrintData:"暂无打印数据",noPrintDataLast30Days:"最近 30 天无打印数据",failureReasons:"失败原因",topFailureReasons:"主要失败原因",failedPrintsCount:"{{failed}} / {{total}} 次打印失败",lastWeekRate:"上周:{{rate}}%",resetLayout:"重置布局",recalculateCosts:"重新计算成本",recalculateCostsHint:"使用当前耗材价格重新计算所有归档成本",exportStats:"导出统计",exportAsCsv:"导出为 CSV",exportAsExcel:"导出为 Excel",hiddenCount:"{{count}} 个已隐藏",exportDownloaded:"导出已下载",exportFailed:"导出失败",layoutReset:"布局已重置",recalculatedCosts:"已为 {{count}} 个归档重新计算成本",recalculateFailed:"重新计算成本失败",loadingStats:"加载统计数据中...",noPermissionResetLayout:"您没有重置布局的权限",noPermissionRecalculate:"您没有重新计算成本的权限",noPrintDataInRange:"所选范围内无打印数据",periodFilament:"期间耗材",periodCost:"期间成本",avgPerPrint:"每次打印平均",usageOverTime:"随时间的使用量",filamentByWeight:"重量",printDuration:"打印时长",printerUtilization:"打印机利用率",filamentSuccess:"按材料成功率",printHabits:"打印习惯",printTimeOfDay:"打印时段",colorDistribution:"颜色分布",noColorData:"暂无颜色数据",records:"记录",longestPrint:"最长打印",heaviestPrint:"最重打印",mostExpensivePrint:"最贵打印",busiestDay:"最忙碌的一天",successStreak:"连续成功",streakPrint:"连续打印",streakPrints:"{{count}} 次连续打印",printerStats:"打印机统计",hours:"小时",avgPrints:"平均打印",noArchiveData:"暂无打印数据",filamentByTime:"时间",avgWeight:"平均重量",avgTime:"平均时间",filamentByPrints:"打印次数",timeframe:{today:"今天","this-week":"本周","this-month":"本月","last-7":"最近 7 天","last-30":"最近 30 天","last-90":"最近 90 天","this-year":"今年","all-time":"全部时间",custom:"自定义范围",from:"从",to:"到"},allUsers:"所有用户",noUser:"无用户(系统)",filterByUser:"按用户筛选"},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:"当前小时数",statusTab:"状态",settingsTab:"设置",overdueCount:"{{count}} 个逾期",dueSoonCount:"{{count}} 个即将到期",dueSoon:"即将到期",allGood:"一切正常",overdueBy:"逾期 {{duration}}",dueIn:"{{duration}} 后到期",timeLeft:"剩余 {{duration}}",day:"1 天",days:"{{count}} 天",week:"1 周",weeks:"{{count}} 周",month:"1 个月",months:"{{count}} 个月",year:"1 年",maintenanceTypes:"维护类型",maintenanceTypesDescription:"系统类型和您的自定义维护任务",addCustomType:"添加自定义类型",restoreDefaults:"恢复默认任务",intervalType:"间隔类型",intervalValue:"间隔 ({{type}})",icon:"图标",documentationLink:"文档链接(可选)",assignToPrinters:"分配给打印机",selectAtLeastOnePrinter:"至少选择一台打印机",addType:"添加类型",custom:"自定义",printHours:"打印小时数",calendarDays:"日历天数",exampleName:"例如:更换 HEPA 过滤器",viewDocumentation:"查看文档",timeBasedInterval:"基于时间的间隔",intervalOverrides:"间隔覆盖",intervalOverridesDescription:"为特定打印机自定义间隔",assignedToPrinters:"已分配给打印机:",noPrintersAssigned:"未分配打印机",addPrinterShort:"添加:",printersAssignedClick:"已分配 {{count}} 台打印机 - 点击管理",removeFromPrinter:"从此打印机移除",types:{lubricateCarbonRods:"润滑碳纤维杆",lubricateRails:"润滑线性导轨",cleanNozzle:"清洁喷嘴/热端",checkBelts:"检查皮带张力",cleanBuildPlate:"清洁构建板",checkExtruder:"检查挤出机齿轮",checkCooling:"检查冷却风扇",generalInspection:"综合检查",cleanCarbonRods:"清洁碳纤维杆",lubricateSteelRods:"润滑钢杆",cleanSteelRods:"清洁钢杆",cleanLinearRails:"清洁线性导轨",checkPtfeTube:"检查 PTFE 管",replaceHepaFilter:"更换 HEPA 过滤器",replaceCarbonFilter:"更换活性炭过滤器",lubricateLeftNozzleRail:"润滑左喷嘴导轨"},maintenanceComplete:"维护已标记为完成",typeUpdated:"维护类型已更新",typeDeleted:"维护类型已删除",defaultsRestored:"已恢复 {{count}} 个默认任务",printHoursUpdated:"打印小时数已更新",printerAssigned:"打印机已分配",printerRemoved:"打印机已移除",deleteTypeConfirm:'删除"{{name}}"?',deleteSystemTypeTitle:"删除默认维护任务?",deleteSystemTypeMessage:'确定要删除默认维护任务"{{name}}"吗?',noPermissionUpdate:"您没有更新维护项目的权限",noPermissionPerform:"您没有执行维护的权限",noPermissionEditTypes:"您没有编辑维护类型的权限",noPermissionDeleteTypes:"您没有删除维护类型的权限",noPermissionEditHours:"您没有编辑打印时间的权限",noPermissionRemovePrinter:"您没有移除打印机分配的权限",noPermissionAssignPrinter:"您没有分配打印机的权限",noPermissionEditIntervals:"您没有编辑间隔的权限",configureSettings:"配置维护类型和间隔"},settings:{title:"设置",general:"通用",tabs:{general:"通用",smartPlugs:"智能插座",notifications:"通知",queue:"工作流",filament:"耗材",network:"网络",apiKeys:"API 密钥",virtualPrinter:"虚拟打印机",failureDetection:"故障检测",users:"身份验证",backup:"备份",emailAuth:"邮箱认证",ldap:"LDAP",twoFa:"双因素认证",oidc:"SSO / OIDC"},ldap:{title:"LDAP 认证",enabledDesc:"LDAP 认证已启用",disabledDesc:"LDAP 认证已禁用",disabledHint:"在下方配置并保存 LDAP 设置,然后启用。",enabled:"LDAP 认证已启用",disabled:"LDAP 认证已禁用",feature1:"用户可以使用 LDAP 凭据登录",feature2:"本地管理员帐户作为后备保留",feature3:"登录时 LDAP 组映射到 BamBuddy 组",serverConfig:"LDAP 服务器配置",serverUrl:"服务器 URL",serverUrlHint:"使用 ldap:// 进行标准连接或 ldaps:// 进行 SSL 连接",security:"安全",securityHint:"StartTLS 将普通连接升级为 TLS。LDAPS 从一开始就使用 TLS。",bindDn:"绑定 DN(服务帐户)",bindPassword:"绑定密码",searchBase:"搜索基础 DN",userFilter:"用户搜索过滤器",userFilterHint:"{username} 替换为登录用户名。OpenLDAP 使用 (uid={username})。",autoProvision:"自动创建用户",autoProvisionHint:"首次 LDAP 登录时自动创建 BamBuddy 帐户",defaultGroup:"默认组",defaultGroupNone:"— 无(无回退)—",defaultGroupHint:"当 LDAP 用户通过身份验证但不在任何已映射的 LDAP 组中时分配的回退组。留空以使未映射的用户没有权限。",groupMapping:"组映射(JSON)",groupMappingHint:"将 LDAP 组 DN 映射到 BamBuddy 组。可用组:",testConnection:"测试连接",settingsSaved:"LDAP 设置已保存",errors:{serverRequired:"LDAP 服务器 URL 为必填项",searchBaseRequired:"搜索基础 DN 为必填项",enableAuthFirst:"请先启用认证",configureLdapFirst:"请先保存 LDAP 设置"}},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 设置",enableAuthFirst:"请先启用身份验证才能使用基于电子邮件的功能。"},success:{settingsSaved:"SMTP 设置保存成功"},securityOptions:{starttls:"STARTTLS(端口 587)",ssl:"SSL/TLS(端口 465)",none:"无(端口 25)"},authOptions:{enabled:"已启用",disabled:"已禁用"}},appearance:"外观",notifications:"通知",smartPlugs:"智能插座",spoolman:"Spoolman",updates:"更新",language:"语言",languageDescription:"选择您的首选语言",theme:"主题",themeLight:"浅色",themeDark:"深色",themeSystem:"跟随系统",defaultView:"默认视图",defaultViewDescription:"打开应用时显示的页面",checkForUpdates:"检查更新",autoUpdate:"自动更新",currentVersion:"当前版本",latestVersion:"最新版本",upToDate:"已是最新版本",updateAvailable:"有可用更新",notificationLanguage:"通知语言",notificationLanguageDescription:"推送通知的语言",bedCooledThreshold:"热床冷却阈值",bedCooledThresholdDescription:"打印后热床被视为已冷却的温度",userNotificationsEnabled:"用户通知",userNotificationsEnabledDescription:"启用用户通知菜单和打印任务事件的邮件通知。需要高级身份验证。",userNotificationsDisabledHint:"请启用高级身份验证以使用用户通知。",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:"关闭"},filamentTracking:"耗材追踪",filamentTrackingDesc:"选择如何追踪您的耗材。您可以使用内置库存或连接外部 Spoolman 服务器。",filamentChecks:"耗材检查",disableFilamentWarnings:"禁用耗材警告",disableFilamentWarningsDesc:"在打印或加入队列时不显示耗材不足警告",preferLowestFilament:"优先使用剩余最少的耗材",preferLowestFilamentDesc:"当多个料盘匹配时,使用剩余耗材最少的那个",trackingModeBuiltIn:"内置库存",trackingModeBuiltInDesc:"包含 RFID 自动匹配和用量追踪",trackingModeSpoolmanDesc:"外部耗材管理服务器",builtInFeatureRfid:"自动检测 AMS 中的拓竹 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 的官方拓竹耗材",syncInfoAutoCreate:"首次同步时自动在 Spoolman 中创建新耗材",syncInfoThirdPartySkipped:"非拓竹耗材(第三方、重新填充的)将被跳过",linkingExistingSpools:"链接现有耗材",linkingExistingSpoolsDesc:'要将现有的 Spoolman 耗材链接到您的 AMS,请将鼠标悬停在 AMS 槽位上并点击"链接到 Spoolman"。',syncMode:"同步模式",syncModeAuto:"自动",syncModeManual:"仅手动",syncModeAutoDesc:"检测到更改时自动同步 AMS 数据",syncModeManualDesc:"仅在手动触发时同步",syncAmsData:"同步 AMS 数据",syncAmsDataDesc:"手动将打印机 AMS 数据同步到 Spoolman",allPrinters:"所有打印机",noDefaultPrinter:"无默认(每次询问)",sidebarOrder:"侧边栏顺序",saveThumbnails:"保存缩略图",captureFinishPhoto:"拍摄完成照片",noPrintersConfigured:"未配置打印机",archiveMode:{always:"始终创建归档条目",never:"从不创建归档条目",ask:"每次询问"},checkForUpdatesLabel:"检查更新",checkPrinterFirmware:"检查打印机固件",includeBetaUpdates:"包含测试版本",includeBetaUpdatesDesc:"检查更新时通知测试版和预发布版本",enableRetry:"启用重试",homeAssistantDescription:"通过 Home Assistant 控制智能插座",environmentManagedLabel:"(环境变量管理)",autoEnabledViaEnv:"通过环境变量自动启用",urlFromEnvReadOnly:"值由 HA_URL 环境变量设置(只读)",tokenFromEnvReadOnly:"值由 HA_TOKEN 环境变量设置(只读)",mqttConnectedTo:"已连接到",prometheusDescription:"以 Prometheus 格式暴露打印机数据",noSmartPlugsTitle:"未配置智能插座",noSmartPlugsDescription:"添加基于 Tasmota 的智能插座以追踪能耗并自动化电源控制。",noProvidersTitle:"未配置提供商",noProvidersDescription:"添加提供商以接收警报。",noTemplatesAvailable:"无可用模板。重启后端以加载默认模板。",apiPermissionView:"查看打印机状态和队列",apiPermissionEdit:"添加和移除打印队列中的项目",apiKeysEmptyTitle:"无 API 密钥",apiKeysEmptyDescription:"创建 API 密钥以与外部服务集成。",noUsersFound:"未找到用户",noGroupsFound:"未找到组",noGroupsAvailable:"无可用组",passwordsDoNotMatch:"密码不匹配",systemGroupWarning:"系统组名称不可更改",authDisabledTitle:"身份验证已禁用",authDisabledFeature1:"需要登录才能访问系统",authDisabledFeature2:"创建多个用户并基于组的权限管理",authDisabledFeature3:"使用 50+ 个细粒度权限控制访问",userHasCreated:"此用户已创建:",userItemsQuestion:"您想如何处理这些项目?",deleteUserConfirm:"确定要删除此用户吗?",actionCannotBeUndone:"此操作无法撤销。",addFirstSmartPlug:"添加您的第一个智能插座",providers:"提供商",log:"日志",testAll:"全部测试",testResults:"测试结果",testPassedCount:"{{count}} 个通过",testFailedCount:"{{count}} 个失败",messageTemplates:"消息模板",messageTemplatesDescription:"自定义每个事件的通知消息。",apiKeys:"API 密钥",apiKeysDescription:"创建 API 密钥用于外部集成和 Webhook。",createKey:"创建密钥",apiKeyCreated:"API 密钥创建成功",apiKeyCopyWarning:"请立即复制此密钥 - 它不会再次显示!",useInApiBrowser:"在 API 浏览器中使用",createNewApiKey:"创建新 API 密钥",keyName:"密钥名称",keyNamePlaceholder:"例如:Home Assistant、OctoPrint",readStatus:"读取状态",readStatusDescription:"查看打印机状态和队列",manageQueue:"管理队列",manageQueueDescription:"添加和移除打印队列中的项目",controlPrinter:"控制打印机",controlPrinterDescription:"暂停、继续和停止打印",unnamedKey:"未命名密钥",lastUsed:"上次使用",read:"读取",control:"控制",createFirstKey:"创建您的第一个密钥",webhookEndpoints:"Webhook 端点",webhookApiKeyHint:"在 X-API-Key 请求头中使用您的 API 密钥。",webhook:{getAllStatus:"获取所有打印机状态",getSpecificStatus:"获取特定打印机状态",addToQueue:"添加到打印队列",pausePrint:"暂停打印",resumePrint:"继续打印",stopPrint:"停止打印"},apiBrowser:"API 浏览器",apiBrowserDescription:"浏览和测试所有可用的 API 端点。",apiKeyForTesting:"测试用 API 密钥",apiKeyPlaceholder:"在此粘贴您的 API 密钥以测试需要认证的端点...",apiKeyHint:"此密钥将作为 X-API-Key 请求头随请求发送。",deleteApiKeyTitle:"删除 API 密钥",deleteApiKeyMessage:"确定要删除此 API 密钥吗?使用此密钥的所有集成将停止工作。",deleteKey:"删除密钥",amsDisplayThresholds:"AMS 显示阈值",amsThresholdsDescription:"配置 AMS 湿度和温度指示器的颜色阈值。",humidity:"湿度",goodGreen:"良好(绿色)",fairOrange:"一般(橙色)",aboveFairBad:"超过一般阈值显示为红色(差)",fairAlsoDryingThreshold:"此阈值也用于触发自动干燥",temperature:"温度",goodBlue:"良好(蓝色)",aboveFairHot:"超过一般阈值显示为红色(热)",historyRetention:"历史保留",keepSensorHistory:"保留传感器历史",historyRetentionDescription:"较旧的湿度和温度数据将被自动删除",defaultPrintOptions:"默认打印选项",defaultPrintOptionsDescription:"设置新打印的默认选项值。可在打印对话框中逐次覆盖。",defaultBedLevelling:"热床调平",defaultBedLevellingDesc:"打印前自动调平热床",defaultFlowCali:"流量校准",defaultFlowCaliDesc:"校准挤出流量",defaultVibrationCali:"振动校准",defaultVibrationCaliDesc:"减少振纹伪影",defaultLayerInspect:"首层检测",defaultLayerInspectDesc:"AI首层检测",defaultTimelapse:"延时摄影",defaultTimelapseDesc:"录制延时摄影视频",staggeredStart:"Staggered Start",staggeredStartDescription:"Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.",plateClear:"热床清空确认",requirePlateClear:"需要热床清空确认",requirePlateClearDescription:"启用后,调度器会在已完成打印的打印机上启动排队打印之前,等待每台打印机的热床清空确认。对于物理验证热床的农场工作流,请禁用此选项。",gcodeInjection:"G-code注入",gcodeInjectionDescription:'为Farmloop、SwapMod、AutoClear和Printflow 3D等自动打印系统配置自定义G-code,在打印开始和/或结束时注入。代码片段按打印机型号配置,在队列项目上启用"注入G-code"时应用。',gcodeInjectionNoPrinters:"未找到打印机。添加打印机以配置G-code代码片段。",gcodeStartLabel:"开始G-code",gcodeEndLabel:"结束G-code",gcodeStartPlaceholder:"在打印开始前插入的G-code...",gcodeEndPlaceholder:"在打印结束后追加的G-code...",staggerGroupSize:"Group size",staggerGroupSizeHelp:"Printers to start simultaneously per group",staggerInterval:"Interval (minutes)",staggerIntervalHelp:"Delay between each group starting",queueDrying:"自动干燥",queueDryingDescription:"在队列打印之间,打印机空闲时自动干燥AMS耗材。使用上方的湿度阈值触发干燥。",queueDryingEnabled:"启用自动干燥",queueDryingEnabledDescription:"当打印机空闲且湿度超过阈值时,自动启动AMS干燥",queueDryingBlock:"等待干燥完成",queueDryingBlockDescription:"阻止打印队列直到干燥完成。关闭时,打印优先于干燥。",ambientDryingEnabled:"环境干燥",ambientDryingEnabledDescription:"当空闲打印机的湿度超过阈值时自动干燥耗材,无需排队打印。",dryingPresets:"干燥预设",dryingPresetsDescription:"每种耗材类型的温度和时长。AMS 2 Pro使用较低温度,AMS-HT支持较高温度。",dryingFilament:"耗材",printModal:"打印对话框",expandCustomMapping:"默认展开自定义映射",expandCustomMappingDescription:"打印到多台打印机时,默认展开显示每台打印机的 AMS 映射",authentication:"身份验证",authEnabledDescription:"您的实例已通过用户身份验证保护",authDisabledDescription:"启用以要求登录并管理用户访问",authDisabledMessage:"启用身份验证以创建用户账户、管理权限并保护您的 Bambuddy 实例。",enableAuthentication:"启用身份验证",currentUser:"当前用户",changePassword:"修改密码",admin:"管理员",users:"用户",addUser:"添加用户",groups:"组",addGroup:"添加组",system:"系统",noDescription:"无描述",userCount:"{{count}} 个用户",permissionCount:"{{count}} 个权限",createUser:"创建用户",username:"用户名",enterUsername:"输入用户名",password:"密码",enterPassword:"输入密码(至少 6 个字符)",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认密码",viewReleaseOnGitHub:"在 GitHub 上查看发布",turnAllPlugsOn:"开启所有插座",turnAllPlugsOff:"关闭所有插座",clearNotificationLogs:"清除通知日志",clearLogsMessage:"这将永久删除所有 30 天前的通知日志。此操作无法撤销。",clearLogs:"清除日志",resetUiPreferences:"重置 UI 偏好",resetUiPreferencesMessage:"这将重置所有 UI 偏好为默认值:侧边栏顺序、主题、仪表板布局、视图模式和排序偏好。您的打印机、归档和服务器设置不会受到影响。清除后页面将重新加载。",resetPreferences:"重置偏好",deleteGroupTitle:"删除组",deleteGroupMessage:"确定要删除此组吗?此组中的用户将失去这些权限。",deleteGroup:"删除组",disableAuthenticationTitle:"禁用身份验证",disableAuthenticationMessage:"确定要禁用身份验证吗?这将使您的 Bambuddy 实例无需登录即可访问。所有用户将保留在数据库中但身份验证将被禁用。",disableAuthentication:"禁用身份验证",configureBambuddy:"配置 Bambuddy",systemDefault:"系统默认",archiveSettings:"归档设置",newWindow:"新窗口",embeddedOverlay:"嵌入式叠加层",preferredSlicer:"首选切片软件",preferredSlicerDescription:"选择要用于打开文件的切片软件",externalCameras:"外部摄像头",costTracking:"成本追踪",printsOnly:"仅打印",totalConsumption:"总消耗",dataManagement:"数据管理",storageUsage:"存储使用情况",storageUsageDescription:"按类别的数据使用情况明细",storageUsageTotal:"总计",storageUsageErrors:"错误",storageUsageOtherBreakdown:"其他(包括静态资源、脚本和配置文件)",storageUsageSystem:"系统",storageUsageData:"数据",storageUsageUnavailable:"存储使用信息不可用",clearNotificationLogsDescription:"删除 30 天前的通知日志",resetUiPreferencesDescription:"重置侧边栏顺序、主题、视图模式和布局偏好。打印机、归档和设置不受影响。",enableHomeAssistant:"启用 Home Assistant",enableMqtt:"启用 MQTT",useTls:"使用 TLS",enableMetricsEndpoint:"启用指标端点",availableMetrics:"可用指标",editUser:"编辑用户",deleteUserTitle:"删除用户",groupName:"组名称",leaveEmptyForAnonymous:"留空为匿名",leaveEmptyForNoAuth:"留空为无认证",enterNewPassword:"输入新密码",confirmNewPassword:"确认新密码",enterGroupName:"输入组名称",enterDescriptionOptional:"输入描述(可选)",enterCurrentPassword:"输入当前密码",enterNewPasswordMin6:"输入新密码(至少 6 个字符)",toast:{keyCopied:"密钥已复制到剪贴板",copyFailed:"复制密钥失败",keyAddedToBrowser:"密钥已添加到 API 浏览器",clearLogsFailed:"清除日志失败",uiPreferencesReset:"UI 偏好已重置。刷新中...",authDisabled:"身份验证已成功禁用",authDisableFailed:"禁用身份验证失败",apiKeyCreated:"API 密钥已创建",apiKeyDeleted:"API 密钥已删除",userCreated:"用户创建成功",userUpdated:"用户更新成功",userDeleted:"用户删除成功",groupCreated:"组创建成功",groupUpdated:"组更新成功",groupDeleted:"组删除成功",fillRequiredFields:"请填写所有必填字段",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符",enterGroupName:"请输入组名称",settingsSaved:"设置已保存",cameraSettingsSaved:"摄像头设置已保存",enterCameraUrl:"请输入摄像头 URL",passwordChanged:"密码修改成功",connectionFailed:"连接失败",testFailed:"测试失败",cameraConnected:"摄像头已连接{{resolution}}"},testConnection:"测试连接",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:"重置为默认值",selectedCount:"已选择 {{count}} 项",deleteSelected:"删除所选",bulkDeleteConfirm:"确定要删除 {{count}} 个条目吗?",bulkDeleted:"已删除 {{count}} 个条目",bulkDeleteFailed:"删除条目失败"},colorCatalog:{title:"颜色目录",description:"按制造商/材料的耗材颜色。用于添加耗材时的自动颜色查找。",searchColors:"搜索颜色...",allManufacturers:"所有制造商",addNewColor:"添加新颜色",manufacturer:"制造商",colorName:"颜色名称",hex:"十六进制",materialOptional:"材料(可选)",showing:"显示 {{filtered}} / {{total}} 种颜色",noMatch:"没有颜色匹配您的搜索",empty:"目录中没有颜色",deleteColor:"删除颜色",deleteConfirm:'确定要删除"{{name}}"吗?',resetCatalog:"重置颜色目录",resetConfirm:"重置目录为默认值?这将移除所有自定义颜色。",sync:"同步",starting:"启动中...",syncTooltip:"从 FilamentColors.xyz 同步(2000+ 种颜色,可能需要一分钟)",loadFailed:"加载颜色目录失败",fieldsRequired:"制造商、颜色名称和十六进制颜色为必填项",colorAdded:"颜色已添加",addFailed:"添加颜色失败",colorUpdated:"颜色已更新",updateFailed:"更新颜色失败",colorDeleted:"颜色已删除",deleteFailed:"删除颜色失败",resetSuccess:"颜色目录已重置为默认值",resetFailed:"重置目录失败",syncUpToDate:"已是最新(检查了 {{count}} 种颜色)",syncComplete:"添加了 {{added}} 种新颜色({{skipped}} 种已存在)",syncError:"同步错误",syncFailed:"从 FilamentColors.xyz 同步失败",exported:"已导出 {{count}} 种颜色",imported:"已导入 {{added}} 种颜色(跳过 {{skipped}} 种)",importFailed:"导入失败:无效的 JSON 格式",selectedCount:"已选择 {{count}} 项",deleteSelected:"删除所选",bulkDeleteConfirm:"确定要删除 {{count}} 种颜色吗?",bulkDeleted:"已删除 {{count}} 种颜色",bulkDeleteFailed:"删除颜色失败"},dateFormat:"日期格式",dateFormatUs:"美式 (MM/DD/YYYY)",dateFormatEu:"欧式 (DD/MM/YYYY)",dateFormatIso:"ISO (YYYY-MM-DD)",timeFormat:"时间格式",timeFormat12:"12小时制 (3:30 PM)",timeFormat24:"24小时制 (15:30)",defaultPrinter:"默认打印机",defaultPrinterDescription:"为上传、重印和其他操作预选此打印机。",slicerBambuStudio:"Bambu Studio",slicerOrcaSlicer:"OrcaSlicer",sidebarOrderDescription:"拖拽侧边栏项目以重新排序。在此处重置为默认顺序。",setDefault:"设为默认",sidebarOrderSetDefaultHint:"设为默认将当前菜单顺序应用于尚未自定义的用户。",sidebarDefaultSet:"已设置默认菜单顺序。",sidebarDefaultCleared:"已清除默认菜单顺序。",sidebarDefaultFailed:"设置默认菜单顺序失败。",reset:"重置",darkMode:"深色模式",lightMode:"浅色模式",active:"(当前)",background:"背景",accent:"强调色",style:"样式",bgNeutral:"中性",bgWarm:"暖色",bgCool:"冷色",bgOled:"OLED 纯黑",bgSlate:"石板蓝",bgForest:"森林绿",accentGreen:"绿色",accentTeal:"青色",accentBlue:"蓝色",accentOrange:"橙色",accentPurple:"紫色",accentRed:"红色",styleClassic:"经典",styleGlow:"发光",styleVibrant:"鲜艳",themeToggleHint:"使用侧边栏中的太阳/月亮图标在深色和浅色模式之间切换。",autoArchivePrints:"自动归档打印",autoArchiveDescription:"打印完成时自动保存3MF文件",saveThumbnailsDescription:"从3MF文件中提取并保存预览图像",captureFinishPhotoDescription:"打印完成时从打印机摄像头拍照",ffmpegNotInstalled:"未安装ffmpeg",ffmpegRequired:"摄像头捕获需要ffmpeg。通过 <brew>brew install ffmpeg</brew>(macOS)或 <apt>apt install ffmpeg</apt>(Linux)安装。",camera:"摄像头",cameraViewMode:"摄像头查看模式",cameraOverlayDescription:"摄像头在主屏幕上以可调大小的覆盖层打开",cameraWindowDescription:"摄像头在单独的浏览器窗口中打开",externalCamerasDescription:"配置外部摄像头以替换内置打印机摄像头。支持MJPEG流、RTSP、HTTP快照和USB摄像头(V4L2)。启用后,外部摄像头将用于实时查看和完成照片。",cameraPlaceholderUsb:"设备路径 (/dev/video0)",cameraPlaceholderUrl:"摄像头URL (rtsp://... 或 http://...)",cameraTypeMjpeg:"MJPEG 流",cameraTypeRtsp:"RTSP 流",cameraTypeSnapshot:"HTTP 快照",cameraTypeUsb:"USB 摄像头 (V4L2)",cameraRotation:"旋转",test:"测试",connected:"已连接",disconnected:"未连接",currency:"货币",defaultFilamentCost:"默认耗材成本(每公斤)",electricityCost:"每千瓦时电费",energyDisplayMode:"能源显示模式",energyModePrintDescription:"仪表板显示打印期间使用的能源总和",energyModeTotalDescription:"仪表板显示智能插座的累计能源",fileManager:"文件管理器",createArchiveEntry:"打印时创建归档条目",createArchiveEntryDescription:"从文件管理器打印时,可选择创建归档条目",lowDiskSpaceWarning:"磁盘空间不足警告",lowDiskSpaceDescription:"当可用磁盘空间低于此阈值时显示警告",printerFirmware:"打印机固件",checkFirmwareDescription:"检查Bambu Lab的打印机固件更新",bambuddySoftware:"Bambuddy 软件",autoCheckDescription:"启动时自动检查新版本",checkNow:"立即检查",updateAvailableVersion:"可用更新:v{{version}}",releaseNotes:"发布说明",updateViaDocker:"通过 Docker Compose 更新:",installUpdate:"安装更新",latestVersionRunning:"您正在运行最新版本",failedToCheckUpdates:"检查更新失败:{{error}}",backupRestore:"备份与恢复",backupRestoreDescription:"导出/导入设置并配置GitHub备份",goToBackup:"前往备份",externalUrl:"外部URL",externalUrlDescription:"Bambuddy可访问的外部URL。用于通知图像和外部集成。",bambuddyUrl:"Bambuddy URL",externalUrlHint:"包含协议和端口(例如:http://192.168.1.100:8000)",ftpRetry:"FTP重试",ftpRetryDescription:"当打印机WiFi不稳定时重试FTP操作。适用于3MF下载、打印上传、延时摄影下载和固件更新。",autoRetryDescription:"自动重试失败的FTP操作",retryAttempts:"重试次数",retryDelay:"重试延迟",connectionTimeout:"连接超时",time_one:"{{count}}次",time_other:"{{count}}次",second_one:"{{count}}秒",second_other:"{{count}}秒",nSeconds:"{{count}}秒",increaseForWeakWifi:"对WiFi信号弱的打印机增加此值",homeAssistant:"Home Assistant",homeAssistantFullDescription:"连接到Home Assistant,通过HA REST API控制智能插座。支持switch、light、input_boolean和script实体。",homeAssistantUrl:"Home Assistant URL",longLivedAccessToken:"长期访问令牌",haTokenHint:"在HA中创建令牌:个人资料 → 长期访问令牌 → 创建令牌",connectionSuccessful:"连接成功",connectionFailed:"连接失败",haConnectionSuccess:"已成功连接到Home Assistant。",haConnectionFailed:"连接Home Assistant失败。",mqttPublishing:"MQTT发布",mqttDescription:"将BamBuddy事件发布到外部MQTT代理,用于与Node-RED、Home Assistant和其他自动化系统集成。",mqttEnableDescription:"向外部MQTT代理发布事件",brokerHostname:"代理主机名",port:"端口",usernameOptional:"用户名(可选)",passwordOptional:"密码(可选)",topicPrefix:"主题前缀",topicPrefixHint:"主题格式:{{prefix}}/printers/<serial>/status 等",prometheusMetrics:"Prometheus 指标",prometheusEndpointDescription:"在 <code>/api/v1/metrics</code> 公开打印机指标,用于Prometheus/Grafana监控。",bearerTokenOptional:"Bearer令牌(可选)",bearerTokenHint:"设置后,请求必须包含 <code>Authorization: Bearer <token></code>",metricsConnectionStatus:"连接状态",metricsPrinterState:"打印机状态(空闲/打印中等)",metricsPrintProgress:"打印进度 0-100%",metricsBedTemp:"热床温度",metricsNozzleTemp:"喷嘴温度",metricsPrintsTotal:"按结果分类的总打印数",metricsMore:"...以及更多(层数、风扇、队列、耗材用量)",smartPlugsDescription:"连接智能插座(Tasmota或Home Assistant)以自动化电源控制并跟踪打印机的能源使用情况。",allOn:"全部开启",allOff:"全部关闭",addSmartPlug:"添加智能插座",energySummary:"能源概要",currentPower:"当前功率",plugsOnline:"{{reachable}}/{{total}} 个插座在线",today:"今天",yesterday:"昨天",total:"总计",enablePlugsForSummary:"启用插座以查看能源概要",addNotificationProvider:"添加",systemBadge:"(系统)",creating:"创建中...",changing:"修改中...",deleteUserAndItems:"删除用户及其所有项目",deleteUserKeepItems:"删除用户,保留项目(将变为无主项目)",ok:"确定",twoFa:{totpTitle:"身份验证器应用 (TOTP)",totpDesc:"使用 Google Authenticator、Aegis 或 Authy 等应用。",emailOtpTitle:"邮件 OTP",emailOtpDesc:"登录时向 {{email}} 发送一次性验证码。",emailOtpNoEmail:"请先为账户添加邮箱地址以启用此方式。",addEmailFirst:"您的账户没有邮箱地址,请联系管理员添加。",setupTotp:"设置身份验证器应用",setupAuthApp:"设置身份验证器应用",setupInstructions:"使用身份验证器应用扫描二维码,然后输入验证码确认。",manualEntry:"无法扫描?请手动输入此密钥:",scannedContinue:"已扫描 — 继续",enterCodeToConfirm:"请输入身份验证器应用中的6位验证码以确认设置。",activate:"激活",disableTotp:"停用身份验证器",disableConfirmHint:"请输入有效的 TOTP 码或备用码来停用身份验证器。",totpDisabled:"身份验证器应用已停用。",emailOtpEnabled:"邮件 OTP 已启用。",emailOtpDisabled:"邮件 OTP 已停用。",smtpRequired:"请先配置并测试SMTP设置。",invalidCode:"无效验证码,请重试。",enableEmailOtp:"启用邮件 OTP",disableEmailOtp:"停用邮件 OTP",emailSetupEnterCode:"验证码已发送至您的邮箱地址。请在下方输入以确认您拥有此邮箱。",verifyAndEnable:"验证并启用",emailDisablePasswordHint:"请输入您的账户密码以确认停用邮件 OTP。",passwordPlaceholder:"输入您的密码",backupCodesTitle:"保存备用码",backupCodesWarning:"请将这些码保存在安全的地方。每个码只能使用一次,且不会再次显示。",backupCodesRemaining:"剩余 {{count}} 个备用码",savedCodes:"已保存",regenBackup:"重新生成备用码",regenBackupHint:"输入当前 TOTP 码以生成 10 个新备用码,所有现有备用码将失效。",newBackupCodes:"新备用码",linkedAccounts:"已关联的 SSO 账户",linkedAccountsDesc:"以下外部身份提供商已与您的账户关联。",oidcUnlinked:"账户已解除关联。"},oidc:{title:"SSO / OIDC 提供商",desc:"配置 OpenID Connect 提供商以实现单点登录。",addProvider:"添加提供商",newProvider:"新提供商",empty:"尚未配置 OIDC 提供商。",created:"提供商已创建。",updated:"提供商已更新。",deleted:"提供商已删除。",deleteTitle:"删除提供商",deleteMessage:'删除"{{name}}"?所有关联账户将断开连接。',form:{name:"显示名称",issuerUrl:"颁发者 URL",clientId:"客户端 ID",clientSecret:"客户端密钥",scopes:"作用域",iconUrl:"图标 URL(可选)",enabled:"已启用",autoCreate:"自动创建用户",autoCreateDesc:"首次登录时自动创建本地账户。",autoLink:"自动关联已有账户",autoLinkDesc:"首次登录时通过邮箱匹配现有本地账户并自动关联。",secretHint:"留空以保留当前",secretPlaceholder:"新密钥"}}},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:"加载数据失败"},hmsErrors:{title:"错误 - {{name}}",noErrors:"无错误",viewOnWiki:"在拓竹 Wiki 上查看",clearInstructions:"在打印机上清除错误以在此处消除它们。",clearErrors:"清除错误",clearSuccess:"HMS 错误已清除",clearFailed:"清除 HMS 错误失败"},mqttDebug:{title:"MQTT 调试日志",searchPlaceholder:"搜索主题或负载...",noMessages:"尚未记录消息",startLoggingHint:'点击"开始记录"以开始捕获 MQTT 消息',noMessagesMatch:"没有消息匹配您的筛选条件",adjustFilterHint:"尝试调整您的搜索或筛选条件",incoming:"传入",outgoing:"传出",loggingStopped:"记录已停止",loggingActive:"记录中 - 消息将自动刷新",startLogging:"开始记录",stopLogging:"停止记录",clearLog:"清除日志",topic:"主题",timestamp:"时间戳",direction:"方向",all:"全部"},printerFiles:{title:"文件管理器",storageUsed:"已用:",storageFree:"剩余:",filterPlaceholder:"筛选文件...",deleteButton:"删除",deleteFiles:"删除 {{count}} 个文件",deleteFileConfirm:'删除"{{name}}"?此操作无法撤销。',deleteFilesConfirm:"删除 {{count}} 个选中的文件?此操作无法撤销。",noFiles:"打印机上没有文件",loadingFiles:"加载文件中...",failedToLoad:"加载文件失败",toast:{filesDeleted:"已删除 {{count}} 个文件",deleteFailed:"删除失败:{{error}}"}},confirm:{delete:"确定要删除吗?",unsavedChanges:"您有未保存的更改。确定要离开吗?",clearQueue:"确定要清空队列吗?"},login:{title:"Bambuddy 登录",subtitle:"登录您的账户",username:"用户名",usernamePlaceholder:"输入您的用户名",usernameOrEmail:"用户名或邮箱",usernameOrEmailPlaceholder:"用户名或 @ 邮箱",password:"密码",passwordPlaceholder:"输入您的密码",signIn:"登录",signingIn:"登录中...",forgotPassword:"忘记密码?",loginSuccess:"登录成功",loginFailed:"登录失败",enterCredentials:"请输入用户名和密码",enterEmail:"请输入您的电子邮件地址",oidcLoginFailed:"OIDC 登录失败",oidcErrors:{providerError:"身份提供商返回了一个错误",missingParameters:"OIDC 回调缺少必要参数",invalidState:"OIDC 状态无效或已被使用",stateExpired:"OIDC 登录会话已过期,请重试",providerNotFound:"未找到 OIDC 提供商",discoveryFailed:"无法获取 OIDC 发现文档",invalidDiscovery:"OIDC 发现文档无效",networkError:"OIDC 令牌交换时出现网络错误",badResponse:"OIDC 令牌交换时收到意外响应",noIdToken:"OIDC 提供商未返回 ID 令牌",validationFailed:"OIDC 令牌验证失败",nonceMismatch:"OIDC nonce 不匹配,可能存在重放攻击",missingSubClaim:"OIDC 令牌缺少 sub 声明",noLinkedAccount:"没有与此 OIDC 身份关联的本地帐户",accountInactive:"您的帐户已被停用",userResolutionFailed:"无法解析您的帐户",internalError:"OIDC 登录过程中发生内部错误",tokenExchangeFailed:"OIDC 令牌交换失败"},forgotPasswordTitle:"忘记密码",forgotPasswordMessage:"如果您忘记了密码,请联系系统管理员进行重置。",forgotPasswordEmailMessage:"输入您的邮箱地址,我们将向您发送新密码。",emailAddress:"邮箱地址",emailPlaceholder:"your.email@example.com",cancel:"取消",sending:"发送中...",sendResetEmail:"发送重置邮件",howToReset:"如何重置密码:",resetStep1:"联系您的 Bambuddy 管理员",resetStep2:"请他们在用户管理中重置您的密码",resetStep3:"他们可以为您设置一个临时密码",resetStep4:"使用新密码登录并在设置中修改密码",gotIt:"知道了",twoFA:{title:"两步验证",subtitle:"您的账户已启用两步验证。请在下方输入验证码。",methodAuthenticator:"身份验证器应用",methodEmail:"邮箱验证码",methodBackup:"备用恢复码",instructionsTotp:"请打开您的身份验证器应用,输入 Bambuddy 的 6 位验证码。",instructionsEmail:"6 位验证码已发送至您的邮箱,有效期为 10 分钟。",instructionsEmailNotSent:"点击下方按钮,通过邮件获取验证码。",instructionsBackup:"请输入您的一个 8 位备用恢复码。每个恢复码只能使用一次。",sendCodeButton:"发送邮箱验证码",sendingCode:"发送中...",resendCode:"重新发送验证码",codeLabel:"验证码",backupCodeLabel:"备用恢复码",codePlaceholder:"000000",backupCodePlaceholder:"XXXXXXXX",verifyButton:"验证",verifyingButton:"验证中...",backToLogin:"← 返回登录页面",orContinueWith:"或通过以下方式登录",signInWith:"使用 {{provider}} 登录",enterCode:"请输入验证码",sendCodeFailed:"验证码发送失败",invalidCode:"无效验证码,请重试。"}},setup:{title:"Bambuddy 设置",subtitle:"为您的 Bambuddy 实例配置身份验证",enableAuth:"启用身份验证",adminAccount:"管理员账户",adminAccountDesc:"如果管理员用户已存在,将使用现有管理员账户启用身份验证。如需使用现有管理员,请将下方字段留空,或输入新凭据创建新管理员用户。",adminUsername:"管理员用户名",adminPassword:"管理员密码",optionalIfAdminExists:"(如管理员用户已存在则为可选)",adminUsernamePlaceholder:"输入管理员用户名(可选)",adminPasswordPlaceholder:"输入管理员密码(可选)",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认管理员密码",settingUp:"设置中...",completeSetup:"完成设置",toast:{authEnabledAdminCreated:"身份验证已启用并创建了管理员用户",authEnabledExistingAdmins:"使用现有管理员用户启用了身份验证",setupCompleted:"设置完成",enterBothCredentials:"请输入管理员用户名和密码,或将两者留空以使用现有管理员用户",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符"}},changePassword:{title:"修改密码",currentPassword:"当前密码",currentPasswordPlaceholder:"输入当前密码",newPassword:"新密码",newPasswordPlaceholder:"输入新密码(至少 6 个字符)",confirmPassword:"确认新密码",confirmPasswordPlaceholder:"确认新密码",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符",changing:"修改中...",success:"密码修改成功",failed:"密码修改失败"},plateAlert:{title:"打印已暂停!",message:"在构建板上检测到物体。打印已自动暂停。请清理打印板并继续打印。",understand:"我知道了"},camera:{title:"摄像头视图",invalidPrinterId:"无效的打印机 ID",live:"实时",snapshot:"快照",restartStream:"重启流",refreshSnapshot:"刷新快照",fullscreen:"全屏",exitFullscreen:"退出全屏",connectingToCamera:"连接摄像头中...",capturingSnapshot:"拍摄快照中...",connectionLost:"连接已断开",connectionFailed:"摄像头连接失败",reconnecting:"{{countdown}} 秒后重新连接...(第 {{attempt}}/{{max}} 次尝试)",reconnectNow:"立即重新连接",cameraUnavailable:"摄像头不可用",cameraUnavailableDesc:"请确保打印机已通电并已连接。",noCamera:"无可用摄像头",retry:"重试",cameraStream:"摄像头流",zoomOut:"缩小",zoomIn:"放大",resetZoom:"重置缩放",recording:"录制中",startRecording:"开始录制",stopRecording:"停止录制",chamberLight:"切换腔室灯"},groups:{title:"组管理",subtitle:"管理访问控制的权限组",backToSettings:"返回设置",createGroup:"创建组",noPermission:"您没有访问此页面的权限。",system:"系统",noDescription:"无描述",usersCount:"{{count}} 个用户",permissionsCount:"{{count}} 个权限",edit:"编辑",delete:"删除",toast:{created:"组创建成功",updated:"组更新成功",deleted:"组删除成功",enterGroupName:"请输入组名称"},modal:{editGroup:"编辑组",createGroup:"创建组",cancel:"取消",saving:"保存中...",creating:"创建中...",saveChanges:"保存更改"},form:{groupName:"组名称",groupNamePlaceholder:"输入组名称",systemGroupWarning:"系统组名称不可更改",description:"描述",descriptionPlaceholder:"输入描述(可选)",permissions:"权限(已选 {{count}} 个)"},deleteModal:{title:"删除组",message:"确定要删除此组吗?此组中的用户将失去这些权限。",confirm:"删除组"},editor:{title:"编辑组",createTitle:"创建组",search:"搜索权限...",selectAll:"全选",clearAll:"清除全部",permissionsSelected:"已选 {{count}} 个",noResults:"没有权限匹配您的搜索"}},users:{title:"用户管理",subtitle:"管理用户及其对 Bambuddy 实例的访问",backToSettings:"返回设置",createUser:"创建用户",noPermission:"您没有访问此页面的权限。",admin:"管理员",noGroups:"无组",active:"活跃",inactive:"非活跃",edit:"编辑",delete:"删除",system:"系统",noGroupsAvailable:"无可用组",table:{username:"用户名",groups:"组",status:"状态",actions:"操作"},toast:{created:"用户创建成功",updated:"用户更新成功",deleted:"用户删除成功",fillRequired:"请填写所有必填字段",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 6 个字符"},modal:{createUser:"创建用户",editUser:"编辑用户",cancel:"取消",creating:"创建中...",saving:"保存中...",saveChanges:"保存更改",advancedAuthSubtitle:"使用高级认证"},form:{username:"用户名",usernamePlaceholder:"输入用户名",email:"邮箱",emailPlaceholder:"user@example.com",password:"密码",passwordPlaceholder:"输入密码",confirmPassword:"确认密码",confirmPasswordPlaceholder:"确认密码",newPasswordPlaceholder:"输入新密码",confirmNewPasswordPlaceholder:"确认新密码",leaveBlankToKeep:"留空以保持当前值",groups:"组",optional:"可选",autoGeneratedPassword:"将自动生成安全密码并通过邮件发送给用户。",passwordManagedByAdvancedAuth:'密码由高级认证管理。使用"重置密码"通过邮件向用户发送新密码。',resetPassword:"重置密码",resettingPassword:"重置密码中..."},deleteModal:{title:"删除用户",message:"确定要删除此用户吗?此操作无法撤销。",confirm:"删除用户"}},streamOverlay:{title:"流叠加层",invalidPrinterId:"无效的打印机 ID",cameraStream:"摄像头流",progress:"进度",eta:"预计完成时间",printerIdle:"打印机空闲",printerOffline:"打印机离线",status:{printing:"打印中",paused:"已暂停",finished:"已完成",failed:"失败",idle:"空闲",unknown:"未知"}},profiles:{title:"配置文件",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:"预设已更新"}},connectedAs:"已连接为",logout:"退出登录",noLogoutPermission:"您没有退出登录的权限",failedToLoad:"加载配置文件失败",retry:"重试",time:{justNow:"刚刚",minsAgo:"{{count}} 分钟前",hoursAgo:"{{count}} 小时前",daysAgo:"{{count}} 天前"},toast:{loggedOut:"已退出登录"},login:{title:"连接到拓竹云",subtitle:"跨设备同步您的切片预设",email:"邮箱",password:"密码",region:"地区",regionGlobal:"全球",regionChina:"中国",verificationCode:"验证码",totpCode:"验证器代码",checkEmail:"检查您的邮箱 ({{email}}) 获取 6 位验证码",enterTotpHint:"输入验证器应用中的 6 位代码",accessToken:"访问令牌",accessTokenHint:"粘贴您的拓竹访问令牌(来自 Bambu Studio)",back:"返回",loginButton:"登录",verifyButton:"验证",setTokenButton:"设置令牌",useToken:"改用访问令牌",useEmail:"改用邮箱登录",toast:{loggedIn:"登录成功",codeSent:"验证码已发送到您的邮箱",enterTotp:"输入验证器应用中的代码",tokenSet:"令牌设置成功"}},presets:{myPreset:"我的预设(可编辑)",duplicate:"复制",editable:"可编辑",failedToLoadDetails:"加载预设详情失败",deleteConfirm:"删除此预设?",deleteWarning:'这将从拓竹云中永久删除"{{name}}"。此操作无法撤销。',noDuplicatePermission:"您没有复制预设的权限",noEditPermission:"您没有编辑预设的权限",noDeletePermission:"您没有删除预设的权限",types:{filament:"耗材预设",printer:"打印机预设",process:"工艺预设"},toast:{deleted:"预设已删除",created:"预设已创建",updated:"预设已更新",duplicated:"预设已复制",fieldAdded:'字段"{{key}}"已添加',exported:"预设已导出"},baseLabel:"基础:{{name}}",currentLabel:"当前:{{name}}",newPreset:"新建预设",editPreset:"编辑预设",duplicatePreset:"复制预设",createNewPreset:"创建新预设",customizeSettings:"自定义新预设的设置",compareWithBase:"与基础预设比较",compare:"比较",basePreset:"基础预设",selectBasePreset:"选择基础预设...",presetName:"预设名称",myCustomPreset:"我的自定义预设",inheritsFrom:"继承自",dropJsonToImport:"拖放 JSON 以导入",tabs:{common:"常用",allFields:"所有字段"},availableFields:"可用字段",searchFieldsPlaceholder:"搜索字段...",noMatchingFields:"没有匹配的字段",allFieldsAdded:"所有字段已添加",addCustomField:"添加自定义字段",yourOverrides:"您的覆盖值",noOverridesYet:"暂无覆盖值",clickFieldsToAdd:"点击左侧的字段进行添加",saveAsTemplate:"保存为模板",jsonTip:"提示:将 .json 文件拖放到此对话框的任意位置以导入设置"},cloudView:{searchPlaceholder:"搜索预设...",templates:"模板",refresh:"刷新",newPreset:"新建预设",clearFilters:"清除筛选",compareMode:"比较模式",selectAnotherPreset:"选择另一个 {{type}} 预设",clickTwoPresets:"点击两个相同类型的预设进行比较",selectFirst:"1. 选择第一个",selectSecond:"2. 选择第二个",compareNow:"立即比较",lastSynced:"上次同步:",showingCount:"显示 {{showing}} / {{total}} 个预设",noPresetsFound:"未找到预设",columns:{filament:"耗材",process:"工艺",printer:"打印机"},noFilamentPresets:"无耗材预设",noProcessPresets:"无工艺预设",noPrinterPresets:"无打印机预设",filters:{type:"类型",owner:"所有者",printer:"打印机",nozzle:"喷嘴",filament:"耗材",layer:"层",all:"全部",myPresets:"我的预设",builtIn:"内置",process:"工艺"},noTemplatesPermission:"您没有管理模板的权限",noRefreshPermission:"您没有刷新配置文件的权限",noCreatePermission:"您没有创建预设的权限"},templates:{title:"快速模板",noTemplates:"暂无模板",createFirst:"从预设编辑器创建模板",typeFilter:"类型:",deleteTitle:"删除模板",deleteWarning:"此操作无法撤销",deleteConfirm:'确定要删除"{{name}}"吗?',namePlaceholder:"模板名称",descriptionPlaceholder:"描述",settingsJson:"设置 (JSON)",fieldsCount:"{{count}} 个字段",shownInModals:"在对话框中显示",hiddenInModals:"在对话框中隐藏",apply:"应用",toast:{deleted:"模板已删除",updated:"模板已更新",created:"模板已创建",applied:"模板已应用"}}},support:{debugLoggingActive:"调试日志记录已激活",manageLogs:"管理",collectItem7:"打印机连接和固件版本",collectItem8:"集成状态(Spoolman、MQTT、HA)",collectItem9:"网络接口(仅子网)",collectItem10:"Python 包版本",collectItem11:"数据库健康检查",collectItem12:"Docker 环境详情"},fileManager:{title:"文件管理器",subtitle:"组织和管理您的打印文件",uploadFiles:"上传文件",newFolder:"新建文件夹",folderName:"文件夹名称",folderNamePlaceholder:"例如:功能零件",renameFile:"重命名文件",renameFolder:"重命名文件夹",moveFiles:"移动 {{count}} 个文件",rootNoFolder:"根目录(无文件夹)",current:"当前",linkFolder:"链接文件夹",linkFolderDescription:'将"{{name}}"链接到项目或归档以便快速访问。',project:"项目",archive:"归档",noProjectsFound:"未找到项目",noArchivesFound:"未找到归档",unlink:"取消链接",link:"链接",dragDropFiles:"将文件拖放到此处",dropFilesHere:"将文件放在此处",orClickToBrowse:"或点击浏览",allFileTypesSupported:"支持所有文件类型。ZIP 文件将被解压。",zipFilesDetected:"检测到 ZIP 文件",zipExtractOptions:"ZIP 文件将被解压。选择如何处理文件夹结构:",preserveZipStructure:"保留 ZIP 中的文件夹结构",createFolderFromZip:"从 ZIP 文件名创建文件夹",stlThumbnailGeneration:"STL 缩略图生成",zipMayContainStl:"ZIP 文件可能包含 STL 文件。可以在解压时生成缩略图。",thumbnailsCanBeGenerated:"可以为 STL 文件生成缩略图。大型模型可能需要更长时间处理。",generateThumbnailsForStl:"为 STL 文件生成缩略图",threemfDetected:"检测到 3MF 文件",threemfExtractionInfo:"将自动从 3MF 文件中提取打印机型号、材料、颜色和打印设置。",willBeExtracted:"将被解压",filesExtracted:"已解压 {{count}} 个文件",uploadComplete:"上传完成:{{succeeded}} 个成功",uploadFailed:"{{count}} 个失败",zipFilesFailed:"{{count}} 个文件失败",uploading:"上传中...",changeLink:"更改链接...",linkTo:"链接到...",linkToProjectOrArchive:"链接到项目或归档",addToQueue:"添加到队列",schedulePrint:"排程",generateThumbnail:"生成缩略图",generateThumbnails:"生成缩略图",generateThumbnailsForMissing:"为缺少缩略图的 STL 文件生成缩略图",gridView:"网格视图",listView:"列表视图",lowDiskSpaceWarning:"磁盘空间不足警告",lowDiskSpaceDetails:"仅剩 {{free}}(总共 {{total}})。阈值设置为 {{threshold}} GB。",files:"文件",folders:"文件夹",size:"大小",free:"剩余",allFiles:"所有文件",wrap:"换行",enableTextWrapping:"启用文本换行",disableTextWrapping:"禁用文本换行",dragToResizeTooltip:"拖动调整大小,双击重置",searchFiles:"搜索文件...",allTypes:"所有类型",prints:"打印",ascending:"升序",descending:"降序",resultsCount:"{{showing}} / {{total}} 个文件",selectAll:"全选",deselectAll:"取消全选",selected:"已选择 {{count}} 个",adding:"添加中...",loadingFiles:"加载文件中...",folderIsEmpty:"文件夹为空",noFilesYet:"暂无文件",folderEmptyDescription:"上传文件或将文件移入此文件夹以开始使用。",noFilesDescription:"上传文件以开始组织您的打印相关文件。",noMatchingFiles:"没有匹配的文件",noMatchingFilesDescription:"没有文件匹配您当前的搜索或筛选条件。",clearFilters:"清除筛选",printedCount:"已打印 {{count}} 次",uploadedBy:"上传者",deleteFolder:"删除文件夹",deleteFile:"删除文件",deleteFilesCount:"删除 {{count}} 个文件",deleteFolderConfirm:"确定要删除此文件夹吗?其中的所有文件也将被删除。",deleteFileConfirm:"确定要删除此文件吗?",deleteFilesConfirm:"确定要删除 {{count}} 个选中的文件吗?此操作无法撤销。",deleting:"删除中...",noPermissionRenameFolder:"您没有重命名文件夹的权限",noPermissionLinkFolder:"您没有链接文件夹的权限",noPermissionDeleteFolder:"您没有删除文件夹的权限",noPermissionPrint:"您没有打印的权限",noPermissionAddToQueue:"您没有添加到队列的权限",noPermissionDownload:"您没有下载文件的权限",noPermissionRenameFile:"您没有重命名此文件的权限",noPermissionGenerateThumbnail:"您没有生成缩略图的权限",noPermissionDeleteFile:"您没有删除此文件的权限",noPermissionCreateFolder:"您没有创建文件夹的权限",noPermissionUpload:"您没有上传文件的权限",noPermissionMoveFiles:"您没有移动文件的权限",noPermissionDeleteFiles:"您没有删除文件的权限",linkExternal:"链接外部",linkExternalFolder:"链接外部文件夹",linkExternalFolderDescription:"将主机目录(NAS、USB、网络共享)挂载到文件管理器中。文件不会被复制——直接从原始路径访问。",externalFolderNamePlaceholder:"例如:NAS打印文件",externalPath:"主机路径",externalPathHelp:"Docker主机上目录的绝对路径。必须以绑定挂载方式挂载到容器中。",readOnly:"只读",readOnlyHelp:"防止上传和删除",showHiddenFiles:"显示隐藏文件(点文件)",externalFolder:"外部文件夹",scanFolder:"扫描",toast:{folderCreated:"文件夹已创建",folderDeleted:"文件夹已删除",fileDeleted:"文件已删除",filesDeleted:"已删除 {{count}} 个文件",filesMoved:"文件已移动",folderLinked:"文件夹已链接",folderUnlinked:"文件夹已取消链接",externalFolderLinked:"外部文件夹已链接并扫描",folderScanned:"扫描完成:添加 {{added}} 个,移除 {{removed}} 个",addedToQueue:"已将 {{count}} 个文件添加到队列",addedToQueuePartial:"已添加 {{added}} 个文件,{{failed}} 个失败",failedToAddToQueue:"添加文件失败:{{error}}",fileRenamed:"文件已重命名",folderRenamed:"文件夹已重命名",thumbnailsGenerated:"已生成 {{count}} 个缩略图",thumbnailsGeneratedPartial:"已生成 {{succeeded}} 个缩略图,{{failed}} 个失败",noStlMissingThumbnails:"没有缺少缩略图的 STL 文件",failedToGenerateThumbnails:"生成缩略图失败:{{error}}",thumbnailGenerated:"缩略图已生成",failedToGenerateThumbnail:"生成缩略图失败:{{error}}"}},projects:{title:"项目",subtitle:"组织和跟踪您的 3D 打印项目",newProject:"新建项目",editProject:"编辑项目",deleteProject:"删除项目",projectName:"项目名称",description:"描述",noProjects:"暂无项目",noProjectsFiltered:"没有{{status}}项目",noProjectsFilteredHelp:"您没有任何{{status}}项目。当项目状态更改时,它们将出现在这里。",createFirst:"创建您的第一个项目以开始组织相关打印、跟踪进度和管理构建。",createFirstButton:"创建您的第一个项目",create:"创建",files:"文件",prints:"打印",plates:"板",parts:"零件",lastModified:"最后修改",deleteConfirm:"确定要删除此项目吗?归档和队列项目将被取消链接但不会被删除。",addFiles:"添加文件",removeFile:"移除文件",viewDetails:"查看详情",namePlaceholder:"例如:Voron 2.4 构建",descriptionPlaceholder:"可选描述...",color:"颜色",targetPlates:"目标板数",targetPlatesPlaceholder:"例如:25",targetPlatesHelp:"打印任务数量",targetParts:"目标零件数",targetPartsPlaceholder:"例如:150",targetPartsHelp:"所需零件总数",tagsLabel:"标签(逗号分隔)",tagsPlaceholder:"例如:voron、功能件、礼物",dueDate:"截止日期",priority:"优先级",priorityLow:"低",priorityNormal:"普通",priorityHigh:"高",priorityUrgent:"紧急",statusActive:"进行中",statusCompleted:"已完成",statusArchived:"已归档",done:"完成",completed:"已完成",failed:"失败",inQueue:"队列中",noPrintsYet:"暂无打印",printJobs:"打印任务(板)",partsPrinted:"已打印零件",failedParts:"失败零件",import:"导入",export:"导出",importProject:"导入项目",exportAll:"导出所有项目",loading:"加载项目中...",noEditPermission:"您没有编辑项目的权限",noDeletePermission:"您没有删除项目的权限",noCreatePermission:"您没有创建项目的权限",noImportPermission:"您没有导入项目的权限",noExportPermission:"您没有导出项目的权限",toast:{created:"项目已创建",updated:"项目已更新",deleted:"项目已删除",imported:"项目已导入",multipleImported:"已导入 {{count}} 个项目",importFailed:"导入失败",exported:"项目已导出(仅元数据)"}},projectDetail:{notFound:"未找到项目",backToProjects:"返回项目",export:"导出",exportProject:"导出项目",noExportPermission:"您没有导出项目的权限",noEditPermission:"您没有编辑项目的权限",partOf:"属于:",priorityLabel:"优先级:",noPrints:"此项目暂无打印",status:{active:"进行中",completed:"已完成",archived:"已归档"},priority:{low:"低",normal:"普通",high:"高",urgent:"紧急"},dueDate:{overdue:"已逾期",today:"今天到期",daysLeft:"还有 {{count}} 天"},progress:{platesProgress:"板进度",partsProgress:"零件进度",printJobs:"打印任务",parts:"零件",percentComplete:"{{percent}}% 完成",remaining:"剩余 {{count}} 个"},stats:{printJobs:"打印任务",total:"总计",failed:"{{count}} 个失败",partsPrinted:"已打印 {{count}} 个零件",printTime:"打印时间",filamentUsed:"耗材用量"},cost:{title:"成本追踪",filamentCost:"耗材成本",energy:"能源",totalCost:"总成本",total:"总计",includesBom:"含物料清单",budget:"预算",remaining:"剩余"},subProjects:{title:"子项目 ({{count}})"},notes:{title:"备注",noEditPermission:"您没有编辑备注的权限",placeholder:"添加关于此项目的备注...",empty:"暂无备注。点击编辑添加备注。"},files:{title:"文件",linkFolders:"从文件管理器链接文件夹",forQuickAccess:"到此项目以便快速访问。",fileCount:"{{count}} 个文件",empty:"未链接文件夹。前往文件管理器将文件夹链接到此项目。",noFiles:"此文件夹中没有文件。",print:"立即打印",addToQueue:"加入队列"},bom:{title:"材料清单",acquired:"已获取 {{completed}}/{{total}}",showAll:"显示全部",hideDone:"隐藏已完成",addPart:"添加零件",noAddPermission:"您没有添加零件的权限",partNamePlaceholder:"零件名称(例如:M3x8 螺丝)",partName:"零件名称",qty:"数量",price:"价格 ({{currency}})",sourcingUrlPlaceholder:"采购链接(可选)",remarksPlaceholder:"备注(可选)",deletePart:"删除零件",deleteConfirm:'确定要删除"{{name}}"吗?',noUpdatePermission:"您没有更新零件的权限",noEditPermission:"您没有编辑零件的权限",noDeletePermission:"您没有删除零件的权限",totalCost:"总成本:",empty:"材料清单中没有零件。添加硬件、电子元件或其他组件以跟踪需要采购的物品。"},timeline:{title:"活动时间线",empty:"暂无活动。"},template:{saveAsTemplate:"保存为模板",noCreatePermission:"您没有创建模板的权限"},queue:{title:"队列",viewAll:"查看全部",printing:"{{count}} 个打印中",queued:"{{count}} 个排队中"},prints:{title:"打印 ({{count}})"},toast:{projectUpdated:"项目已更新",partAdded:"零件已添加",partRemoved:"零件已移除",exportFailed:"导出失败",projectExported:"项目已导出",templateCreated:"模板已创建"}},system:{title:"系统信息",version:"版本",uptime:"运行时间",cpuUsage:"CPU 使用率",memoryUsage:"内存使用率",diskUsage:"磁盘使用率",networkInfo:"网络信息",logs:"日志",debugMode:"调试模式",enableDebug:"启用调试日志",disableDebug:"禁用调试日志",downloadLogs:"下载日志",clearLogs:"清除日志",dockerInfo:"Docker 信息",containerName:"容器名称",imageName:"镜像名称",platform:"平台",architecture:"架构"},library:{title:"耗材库",addFilament:"添加耗材",editFilament:"编辑耗材",deleteFilament:"删除耗材",vendor:"厂商",material:"材料",color:"颜色",kFactor:"K 值",temperature:"温度",noFilaments:"耗材库中没有耗材",deleteConfirm:"确定要删除此耗材吗?",importFromPrinter:"从打印机导入",exportToFile:"导出到文件"},spoolman:{title:"Spoolman 集成",enabled:"Spoolman 已启用",url:"Spoolman URL",connected:"已连接",disconnected:"未连接",testConnection:"测试连接",sync:"同步",syncing:"同步中...",lastSync:"上次同步",linkToSpoolman:"链接到 Spoolman",openInSpoolman:"在 Spoolman 中打开",unlinkSpool:"取消链接耗材",unlinkConfirmTitle:"解开线轴?",unlinkConfirmMessage:"这将断开卷轴与 Spoolman 的连接。Spoolman 中的卷轴数据将保持不变。",selectSpool:"选择耗材",noUnlinkedSpools:"无未链接的耗材",linkSuccess:"耗材已成功链接到 Spoolman",linkFailed:"链接耗材失败",unlinkSuccess:"已成功从 Spoolman 取消链接耗材",unlinkFailed:"取消链接耗材失败",spoolId:"耗材 ID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"剩余",disableWeightSync:"禁用 AMS 估计重量同步",disableWeightSyncDesc:"不从 AMS 估计值更新剩余容量。如果您更喜欢 Spoolman 的用量追踪而非 AMS 百分比估计,请使用此选项。新耗材仍将使用 AMS 估计值作为初始重量。",reportPartialUsage:"报告失败打印的部分用量",reportPartialUsageDesc:"当打印失败或被取消时,根据层进度报告估计的耗材使用量。"},inventory:{title:"耗材库存",addSpool:"添加耗材",editSpool:"编辑耗材",material:"材料",selectMaterial:"选择材料...",subtype:"子类型",brand:"品牌",searchBrand:"搜索品牌...",useCustomBrand:'使用"{{brand}}"',useCustomMaterial:"使用自定义材料:{{material}}",colorName:"颜色名称",colorNamePlaceholder:"翡翠白、烈焰红...",color:"颜色",hexColor:"十六进制颜色",pickColor:"选择自定义颜色",labelWeight:"标签重量",coreWeight:"空盘重量",searchSpoolWeight:"搜索耗材重量...",weightUsed:"已使用",currentWeight:"剩余重量",measuredWeight:"称量重量",spoolName:"线轴",costPerKg:"每公斤成本",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:"分配耗材失败",assignMismatchTitle:"材料不匹配",assignMismatchMessage:'所选线轴材料 "{{spoolMaterial}}" 与 {{location}} 的料槽材料 "{{trayMaterial}}" 不匹配。仍要分配吗?',assignMismatchConfirm:"仍然分配",assignPartialMismatchMessage:'线轴材料 "{{spoolMaterial}}" 与 {{location}} 的 "{{trayMaterial}}" 相近但不完全一致。是否继续?',assignProfileMismatchMessage:'线轴配置 "{{spoolProfile}}" 与 {{location}} 的料槽配置 "{{trayProfile}}" 不一致。是否继续?',selectSpool:"选择要分配到此槽位的耗材",assigned:"已分配",assigning:"分配中...",searchSpools:"搜索耗材...",showAllSpools:"显示所有耗材",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:"未配置打印机。添加打印机以使用 PA 配置。",matchingFilter:"匹配",anyBrand:"任何品牌",anyVariant:"任何变体",autoSelect:"自动选择",matches:"匹配",match:"匹配",noMatches:"无匹配",connected:"已连接",offline:"离线",printerOffline:"打印机离线。连接后查看校准配置。",noKProfilesMatch:"没有 K 值配置匹配所选耗材。",leftNozzle:"左喷嘴",rightNozzle:"右喷嘴",profilesSelected:"个校准配置已选择",totalInventory:"总库存",totalConsumed:"总消耗",byMaterial:"按材料",inPrinter:"在打印机中",lowStock:"库存不足",sinceTracking:"自开始追踪",loadedInAms:"已装载到 AMS/外置",remaining:"剩余",weightCheck:"重量检查",lastWeighed:"上次称量",neverWeighed:"从未称量",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:"(库存)",lowStockThresholdError:"阈值必须在 0.1 到 99.9 之间"},timelapse:{title:"延时摄影",create:"创建延时摄影",download:"下载",delete:"删除",preview:"预览",frameRate:"帧率",quality:"质量",processing:"处理中...",noTimelapses:"无可用延时摄影"},ams:{title:"AMS",slot:"槽位",empty:"空",emptySlot:"空槽位",unknown:"未知",humidity:"湿度",temperature:"温度",filamentType:"耗材类型",filamentColor:"颜色",remaining:"剩余",history:"AMS 历史",noHistory:"无可用历史",configureSlot:"配置槽位",externalSpool:"外置耗材",profile:"配置",kFactor:"K 值",fill:"填充",configure:"配置",used:"已使用",remainingUnit:"剩余"},printModal:{title:"开始打印",selectPrinter:"选择打印机",selectPlate:"选择板",filamentMapping:"耗材映射",totalCost:"总成本:",slotRemainingShort:" - 剩余 {{grams}}g",printSettings:"打印设置",bedLeveling:"热床调平",flowCalibration:"流量校准",vibrationCalibration:"振动校准",layerInspection:"首层检查",timelapse:"延时摄影",startPrint:"开始打印",addToQueue:"添加到队列",cancel:"取消",noPrintersAvailable:"无可用打印机",printerBusy:"打印机忙碌",printerOffline:"打印机离线",sameTypeDifferentColor:"相同类型,不同颜色",filamentTypeNotLoaded:"耗材类型未装载",openCalendar:"打开日历",leftNozzle:"左",rightNozzle:"右",leftNozzleTooltip:"左喷嘴",rightNozzleTooltip:"右喷嘴",filamentOverride:"耗材覆盖",filamentOverrideHint:"可选覆盖用于基于模型的耗材分配。调度器将使用您选择的耗材而不是原始 3MF 值进行匹配。",originalFilament:"原始",overrideWith:"覆盖为",resetToOriginal:"恢复为原始",insufficientFilamentTitle:"耗材不足",insufficientFilamentMessage:"部分已分配线轴的剩余耗材少于本次打印所需:",insufficientFilamentLine:"{{printer}} - {{slot}}:需要 {{required}}g,剩余 {{remaining}}g",printAnyway:"仍然打印",forceColorMatch:"强制颜色匹配",staggerPrinterStarts:"Stagger printer starts",staggerGroupSize:"Group size",staggerInterval:"Interval (min)",staggerPreview:"{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",staggerLastGroup:"last group: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"分批发送到 {{count}} 台打印机",gcodeInjection:"注入自动打印G-code"},backup:{title:"备份与恢复",createBackup:"创建备份",restoreBackup:"恢复备份",restoreDescription:"从备份文件替换所有数据",downloadBackup:"下载备份",uploadBackup:"上传备份",lastBackup:"上次备份",autoBackup:"自动备份",backupNow:"立即备份",restoreWarning:"警告:恢复备份将覆盖所有当前数据。",includeArchives:"包含归档",includeSettings:"包含设置",includeProfiles:"包含配置文件",backupSuccess:"备份创建成功",restoreSuccess:"备份恢复成功",backupFailed:"备份失败",restoreFailed:"恢复失败",restoreNote:"恢复期间虚拟打印机将停止",githubBackup:"GitHub 备份",enabled:"已启用",cloudLoginRequired:"需要登录 Bambu Cloud。请在 配置文件 → 云配置文件 中登录以启用 GitHub 备份。",cloudLoginRequiredShort:"需要Cloud登录",githubDescription:"自动将您的配置文件同步到私有 GitHub 仓库以进行备份和版本历史记录。",repositoryUrl:"仓库 URL",personalAccessToken:"个人访问令牌",tokenSaved:"(已保存)",enterNewToken:"输入新令牌以更新",tokenHint:"具有内容读写权限的细粒度令牌",branch:"分支",manualOnly:"仅手动",hourly:"每小时",daily:"每天",weekly:"每周",includeInBackup:"包含在备份中",kProfiles:"K 配置文件",kProfilesDescription:"来自已连接打印机的压力推进校准",noPrintersConnected:"没有打印机连接",printersConnected:"{{connected}}/{{total}} 已连接",cloudProfiles:"云配置文件",cloudProfilesDescription:"来自 Bambu Cloud 的耗材、打印机和工艺预设",appSettings:"应用设置",appSettingsDescription:"Bambuddy 配置(完整数据库)",spoolInventory:"耗材库存",spoolInventoryDescription:"耗材卷轴、使用记录和成本追踪",printArchives:"打印档案",printArchivesDescription:"打印历史元数据(不含 gcode/3MF 文件)",lastBackupAt:"上次备份:",noBackupsYet:"尚无备份",next:"下次:",startingBackup:"正在启动备份...",test:"测试",enableBackup:"启用备份",testConnection:"测试连接",enterRepoUrl:"请输入仓库 URL",enterRepoAndToken:"请输入仓库 URL 和访问令牌",repoRequired:"仓库 URL 为必填项",tokenRequired:"访问令牌为必填项",githubBackupEnabled:"GitHub 备份已启用",tokenUpdated:"令牌已更新",settingsSaved:"设置已保存",failedToSave:"保存失败:{{message}}",backupCompleteFiles:"备份完成 - {{count}} 个文件已更新",backupSkippedNoChanges:"备份已跳过 - 无更改",backupFailed2:"备份失败:{{message}}",clearedLogs:"已清除 {{count}} 条日志",failedToClearLogs:"清除日志失败:{{message}}",history:"历史记录",clear:"清除",date:"日期",status:"状态",commit:"提交",localBackup:"本地备份",localBackupDescription:"创建 Bambuddy 数据的完整备份,包括数据库、档案、上传和所有文件。",downloadBackupLabel:"下载备份",completeBackupZip:"完整备份:数据库 + 所有文件(ZIP)",download:"下载",preparingBackup:"正在准备备份...",creatingArchive:"正在创建备份归档...对于大型归档可能需要一些时间。",downloadingFile:"正在下载备份文件...",backupDownloaded:"备份下载成功",failedToCreateBackup:"创建备份失败:{{message}}",restore:"恢复",restoreReplacesAll:"恢复将替换所有数据。",restoreReplacesAllDetail:"您当前的数据库和文件将被完全替换。恢复后需要重启。",restoreConfirmTitle:"恢复备份",restoreConfirmMessage:'您确定要从"{{filename}}"恢复吗?这将完全替换您当前的数据库和所有文件。恢复后需要重启应用程序。',restoreConfirmButton:"恢复备份",uploadingFile:"正在上传备份文件...",backupRestoredRestart:"备份已恢复。请重启 Bambuddy。",failedToRestore:"恢复备份失败。请检查文件格式。",reloadNow:"立即重新加载",creatingBackup:"正在创建备份",restoringBackup:"正在恢复备份",preparing:"准备中...",processing:"处理中...",doNotClosePage:"请不要关闭此页面或导航离开。对于大型备份,此操作可能需要几分钟。",restoring:"恢复中...",restoreComplete:"恢复完成",restoreFailed2:"恢复失败",importSettings:"从备份文件导入设置",pleaseWaitRestoring:"请等待数据恢复中",selectBackupFile:"点击选择备份文件(.json 或 .zip)",duplicateHandling:"重复项处理方式:",matchPrinters:"打印机",matchPrintersBy:"按序列号匹配",matchSmartPlugs:"智能插座",matchSmartPlugsBy:"按 IP 地址匹配",matchNotificationProviders:"通知提供者",matchNotificationProvidersBy:"按名称匹配",matchFilaments:"耗材",matchFilamentsBy:"按名称 + 类型 + 品牌匹配",matchArchives:"档案",matchArchivesBy:"按内容哈希匹配(始终跳过)",matchPendingUploads:"待上传",matchPendingUploadsBy:"按文件名匹配",matchSettingsTemplates:"设置和模板",matchSettingsTemplatesBy:"始终覆盖",replaceExisting:"替换现有数据",keepExisting:"保留现有数据",overwriteDescription:"用备份数据覆盖已存在的项目",keepDescription:"仅恢复尚不存在的项目",overwriteCaution:"注意:",overwriteWarning:"覆盖将用备份数据替换您当前的配置。出于安全考虑,打印机访问代码永远不会被覆盖。",cancel:"取消",processingBackup:"正在处理备份文件...",itemsRestored:"已恢复项目",itemsSkipped:"已跳过项目",restored:"已恢复",skippedAlreadyExist:"已跳过(已存在)",filesCategory:"文件(3MF、缩略图等)",andMore:"...还有 {{count}} 项",newApiKeysGenerated:"已生成新的 API 密钥",keysShownOnce:"这些密钥仅显示一次。请立即复制!",copy:"复制",noDataFound:"在备份文件中未找到可恢复的数据。",close:"关闭",scheduledBackup:"Scheduled Backups",scheduledBackupDescription:"Automatically create backup snapshots on a schedule. Output directory can be mounted to a NAS or external storage.",frequency:"Frequency",backupTime:"Time",retention:"Retention",retentionDescription:"Number of backups to keep",outputPath:"Output Path",outputPathPlaceholder:"Default: {{path}}",outputPathDescription:"Leave empty for default location",runNow:"Run Now",backupFiles:"Backup Files",noScheduledBackups:"No backups yet",deleteBackup:"Delete",deleteBackupConfirm:"Delete this backup file?",backupRunning:"Backup in progress...",scheduledBackupComplete:"Backup completed successfully",scheduledBackupFailed:"Backup failed",nextBackup:"Next backup",backupSize:"Size",utc:"UTC",defaultPathLabel:"Default:",categories:{settings:"设置",notification_providers:"通知提供者",notification_templates:"通知模板",smart_plugs:"智能插座",printers:"打印机",filaments:"耗材",maintenance_types:"维护类型",archives:"档案",projects:"项目",pending_uploads:"待上传",external_links:"外部链接",api_keys:"API 密钥"}},tags:{title:"标签",addTag:"添加标签",editTag:"编辑标签",deleteTag:"删除标签",tagName:"标签名称",tagColor:"标签颜色",noTags:"无标签",deleteConfirm:"确定要删除此标签吗?",manageTags:"管理标签"},uploadModal:{title:"上传 3MF 文件",dragDrop:"将 .3mf 文件拖放到此处",or:"或",browseFiles:"浏览文件",extractionInfo:"将从 3MF 文件元数据中自动提取打印机型号。",uploaded:"已上传",failed:"失败",uploading:"上传中...",upload:"上传",uploadFailed:"上传失败"},editArchive:{title:"编辑归档",name:"名称",namePlaceholder:"打印名称",printer:"打印机",noPrinter:"无打印机",project:"项目",noProject:"无项目",itemsPrinted:"打印数量",itemsPrintedHelp:"此打印任务中生产的物品数量",notes:"备注",notesPlaceholder:"添加关于此打印的备注...",externalLink:"外部链接",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"链接到 Printables、Thingiverse 或其他来源",tags:"标签",tagsPlaceholder:"添加标签...",addMoreTags:"添加更多标签...",matchingTags:'匹配"{{query}}"',existingTags:"现有标签",clickToAdd:"(点击添加)",status:"状态",failureReason:"失败原因",selectReason:"选择原因...",photos:"打印成品照片",photosHelp:"点击 + 添加打印成品照片",printResult:"打印成品",saving:"保存中...",failureReasons:{adhesionFailure:"附着力失败",spaghettiDetached:"拉丝 / 脱落",layerShift:"层偏移",cloggedNozzle:"喷嘴堵塞",filamentRunout:"耗材用完",warping:"翘曲",stringing:"拉丝",underExtrusion:"挤出不足",powerFailure:"断电",userCancelled:"用户取消",other:"其他"},statuses:{completed:"已完成",failed:"失败",aborted:"已取消",printing:"打印中"}},kProfiles:{title:"K 值配置",noPrintersConfigured:"未配置打印机",addPrinterInSettings:"在设置中添加打印机以管理 K 值配置",noActivePrinters:"无活跃打印机",enablePrinterConnection:"启用打印机连接以查看其 K 值配置",loadingProfiles:"加载 K 值配置中...",printerOffline:"打印机离线",printerOfflineDesc:"所选打印机未连接。开启电源以查看 K 值配置。",noMatchingProfiles:"无匹配的配置",noMatchingProfilesDesc:"没有配置匹配您的搜索条件",noKProfiles:"无 K 值配置",noKProfilesDesc:"未找到 {{diameter}}mm 喷嘴的压力推进配置",createFirstProfile:"创建第一个配置",printer:"打印机",nozzle:"喷嘴",refresh:"刷新",addProfile:"添加配置",export:"导出",import:"导入",select:"选择",selectAll:"全选",delete:"删除",searchPlaceholder:"按名称或耗材搜索...",allExtruders:"所有挤出机",leftOnly:"仅左侧",rightOnly:"仅右侧",allFlow:"所有流量",hfOnly:"仅高流量",sOnly:"仅标准",sortName:"排序:名称",sortKValue:"排序:K 值",sortFilament:"排序:耗材",leftExtruder:"左挤出机",rightExtruder:"右挤出机",modal:{addTitle:"添加 K 值配置",editTitle:"编辑 K 值配置",profileName:"配置名称",profileNamePlaceholder:"我的 PLA 配置",kValue:"K 值",kValuePlaceholder:"0.020",kValueHelp:"典型范围:PLA 0.01 - 0.06,PETG 0.02 - 0.10",filament:"耗材",selectFilament:"选择耗材...",noFilamentsHelp:"未找到耗材。请先在 Bambu Studio 中创建 K 值配置。",flowType:"流量类型",highFlow:"高流量",standard:"标准",nozzleSize:"喷嘴尺寸",extruder:"挤出机",extruders:"挤出机",left:"左",right:"右",notes:"备注(本地存储)",notesPlaceholder:"添加关于此配置的备注...",notesHelp:"备注保存在 Bambuddy 中,不在打印机上",syncing:"与打印机同步中...",savingExtruder:"保存到挤出机 {{current}}/{{total}}...",pleaseWait:"请稍候"},deleteConfirm:{title:"删除配置",cannotUndo:"此操作无法撤销",message:'确定要从打印机删除"{{name}}"吗?'},bulkDelete:{title:"删除配置",cannotUndo:"此操作无法撤销",message:"确定要从打印机删除 {{count}} 个选中的配置吗?"},toast:{profileSaved:"K 值配置已保存",profilesSaved:"K 值配置已保存到 {{count}} 个挤出机",selectAtLeastOneExtruder:"请至少选择一个挤出机",profileDeleted:"K 值配置已删除",profilesDeleted:"已删除 {{count}} 个配置",exportedProfiles:"已导出 {{count}} 个配置",importedProfiles:"已导入 {{count}} / {{total}} 个配置",noProfilesToExport:"无可导出的配置",invalidFileFormat:"无效的文件格式",failedToParseImport:"解析导入文件失败",failedToSaveBatch:"批量保存 K 值配置失败",noteSaved:"备注已保存",failedToSaveNote:"保存备注失败"},permission:{noRead:"您没有刷新配置的权限",noCreate:"您没有添加配置的权限",noUpdate:"您没有更新 K 值配置的权限",noDelete:"您没有删除 K 值配置的权限",noExport:"您没有导出配置的权限",noImport:"您没有导入配置的权限"}},virtualPrinter:{title:"虚拟打印机",running:"运行中",stopped:"已停止",description:{default:"启用虚拟打印机,使其在 Bambu Studio 和 OrcaSlicer 中可见。发送到此打印机的文件将直接归档而不打印。",proxy:"启用代理,将切片软件流量中继到真实打印机,允许在任何网络上远程打印。"},enable:{title:"启用虚拟打印机",visibleInSlicer:'在切片软件发现中显示为"Bambuddy"',proxyingTo:"代理到 {{name}}",notActive:"未激活"},model:{title:"打印机型号",description:"选择要模拟的打印机型号。",restartWarning:"更改型号将重启虚拟打印机"},accessCode:{title:"访问码",isSet:"访问码已设置",notSet:"未设置访问码 - 需要设置才能启用",placeholder:"输入 8 位字符代码",placeholderChange:"输入新代码以更改",hint:"必须恰好 8 个字符。切片软件使用此代码进行认证。",charCount:"({{count}}/8)"},targetPrinter:{title:"目标打印机",configured:"代理目标已配置",notConfigured:"未选择目标打印机 - 代理模式需要设置",placeholder:"选择打印机...",hint:"选择要将切片软件流量代理到的打印机。打印机必须处于局域网模式。",noPrinters:"未配置打印机。请先添加打印机以使用代理模式。"},remoteInterface:{title:"网络接口覆盖",configured:"接口覆盖已激活",optional:"可选 - 当自动检测的 IP 不正确时使用(例如多网卡、Docker、VPN)",placeholder:"自动检测(默认)...",hint:"覆盖通过 SSDP 广播并在 TLS 证书中使用的 IP 地址。在 Bambuddy 有多个网络接口时很有用。"},mode:{title:"模式",archive:"归档",archiveDesc:"立即归档文件",review:"审核",reviewDesc:"归档前审核",queue:"队列",queueDesc:"归档并添加到队列",proxy:"代理",proxyDesc:"中继到真实打印机"},autoDispatch:{title:"自动派发",description:"添加到队列时自动开始打印。关闭后,打印任务等待手动派发。"},setupRequired:{title:"需要设置",description:"虚拟打印机功能需要额外的系统配置才能工作。包括端口转发、防火墙规则和平台特定设置。",readGuide:"启用前请阅读设置指南"},howItWorks:{title:"工作原理",step1:"在同一局域网中,虚拟打印机会通过发现机制自动出现在您的切片软件(Bambu Studio / OrcaSlicer)中。从其他网络,通过 IP 地址和访问码手动添加。",step2:'在归档、审核和队列模式下,使用切片软件中的"发送"按钮将 3MF 文件上传到 Bambuddy。切片软件会显示"打印成功"— 文件已存储,未打印。',step3:"在代理模式下,虚拟打印机将所有流量中继到真实打印机 — 打印会立即开始,就像直接连接一样。"},status:{title:"状态详情",printerName:"打印机名称",model:"型号",serialNumber:"序列号",mode:"模式",pendingFiles:"待处理文件",targetPrinter:"目标打印机",ftpPort:"FTP 端口",mqttPort:"MQTT 端口",ftpConnections:"FTP 连接",mqttConnections:"MQTT 连接"},toast:{updated:"虚拟打印机设置已更新",failedToUpdate:"更新设置失败",accessCodeRequired:"请先设置访问码",targetPrinterRequired:"请先选择目标打印机",bindIpRequired:"请先设置绑定 IP",accessCodeEmpty:"访问码不能为空",accessCodeLength:"访问码必须恰好 8 个字符",created:"虚拟打印机已创建",failedToCreate:"创建虚拟打印机失败",deleted:"虚拟打印机已删除",failedToDelete:"删除虚拟打印机失败"},list:{title:"虚拟打印机",add:"添加",addFirst:"添加虚拟打印机",empty:"未配置虚拟打印机。添加一个以开始使用。"},bindIp:{title:"绑定接口",placeholder:"选择接口...",hint:"此虚拟打印机绑定的网络接口。每台打印机必须唯一。"},proxy:{accessCodeHint:"在代理模式下,在切片软件中使用目标打印机的访问码。连接会透明转发到真实打印机。"},addDialog:{title:"添加虚拟打印机",name:"名称",hint:"创建后可以配置访问码、目标打印机和其他设置。",create:"创建"},deleteConfirm:{title:"删除虚拟打印机",message:'确定要删除"{{name}}"吗?这将停止此打印机的所有服务。'}},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:"清洁碳纤维杆以减少摩擦",lubricateSteelRods:"在钢杆上涂抹润滑剂以确保顺畅运动",cleanSteelRods:"清洁钢杆以减少摩擦",cleanLinearRails:"擦拭线性导轨以清除灰尘和碎屑",checkPtfeTube:"检查 PTFE 管的磨损或损坏",replaceHepaFilter:"更换 HEPA 过滤器以保证空气质量",replaceCarbonFilter:"更换活性炭过滤器",lubricateLeftNozzleRail:"润滑左喷嘴导轨(H2 系列)"},smartPlugs:{offline:"离线",admin:"管理",openPlugAdminPage:"打开插座管理页面",deleteSmartPlug:"删除智能插座",turnOnSmartPlug:"开启智能插座",turnOffSmartPlug:"关闭智能插座",turnOn:"开启",turnOff:"关闭",addSmartPlug:{scanningNetwork:"扫描网络中...",chooseEntity:"选择实体...",connectionFailed:"连接失败",searchEntities:"搜索实体...",searchPowerSensors:"搜索功率传感器...",searchEnergySensors:"搜索能量传感器...",placeholders:{plugName:"客厅插座",mqttStateOnValue:"ON、true、1",mqttSameAsPower:"与功率主题相同,或不同"}},linkedTo:"关联到:",monitorOnly:"仅监控",alerts:"警报",scheduleOn:"开启 {{time}}",scheduleOff:"关闭 {{time}}",on:"开启",off:"关闭",power:"功率",kwhToday:"今日kWh",settings:"设置",automationSettings:"自动化设置",showInSwitchbar:"在开关栏显示",quickAccessSidebar:"从侧边栏快速访问",enabled:"已启用",enableAutomation:"为此插座启用自动化",autoOn:"自动开启",autoOnDescription:"打印开始时开启",autoOff:"自动关闭",autoOffDescription:"打印完成时关闭(一次性)",autoOffPersistent:"保持启用",autoOffPersistentDescription:"在打印之间保持启用而非一次性",turnOffDelayMode:"关闭延迟模式",time:"时间",temp:"温度",delayMinutes:"延迟(分钟)",tempThreshold:"温度阈值(°C)",tempThresholdDescription:"当喷嘴冷却到此温度以下时关闭",edit:"编辑",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',turnOnConfirm:'确定要开启"{{name}}"吗?',turnOffConfirm:'确定要关闭"{{name}}"吗?这将切断连接设备的电源。',failedToTurn:'无法{{action}}"{{name}}"',unknown:"未知",addTitle:"添加智能插座",editTitle:"编辑智能插座",stopScanning:"停止扫描",discoverTasmota:"发现Tasmota设备",foundDevices:"找到{{count}}个设备 - 点击选择:",noDevicesFound:"未在您的网络中找到Tasmota设备",haNotConfigured:"Home Assistant未配置。请在以下位置设置",haSettingsPath:"设置 → 网络 → Home Assistant",selectEntity:"选择实体 *",ipAddress:"IP地址 *",nameLabel:"名称 *",username:"用户名",password:"密码",authHint:"如果您的Tasmota设备不需要认证,请留空",linkToPrinter:"关联打印机",noPrinter:"无打印机(仅手动控制)",linkingDescription:"关联后可在打印开始/完成时自动开关",powerAlerts:"功率警报",alertAbove:"高于时警报(W)",alertBelow:"低于时警报(W)",alertDescription:"当电力消耗超过这些阈值时收到通知。留空以禁用该方向。",dailySchedule:"每日计划",turnOnAt:"开启时间",turnOffAt:"关闭时间",scheduleDescription:"每天在这些时间自动开关插座。留空以跳过该操作。",showOnPrinterCard:"在打印机卡片上显示",displayOnPrinterCard:"在打印机卡片上显示按钮",connectedResult:"已连接!",deviceLabel:"设备:{{name}} - ",stateLabel:"状态:{{state}}",test:"测试",delete:"删除",save:"保存",add:"添加",cancel:"取消",failedToStartScan:"无法开始扫描",nameRequired:"名称为必填项",entityRequired:"Home Assistant插座需要实体",mqttTopicRequired:"必须为功率、能源或状态监控配置至少一个MQTT主题",loadingEntities:"正在加载实体...",loading:"加载中...",failedToLoadEntities:"加载实体失败:{{error}}",noEntitiesMatching:'未找到匹配"{{search}}"的实体',noEntitiesAvailable:"无可用实体",searchingEntities:"搜索所有实体(找到{{count}}个)",showingEntities:"显示 switch、light、input_boolean({{count}}个可用)",energyMonitoringOptional:"能源监控(可选)",energyMonitoringHint:"搜索并选择提供功率/能源数据的传感器。",powerSensorW:"功率传感器(W)",energyTodayKwh:"今日能源(kWh)",totalEnergyKwh:"总能源(kWh)",noMatchingSensors:"无匹配的传感器",none:"无",mqttNotConfigured:"MQTT代理未配置。请在以下位置设置代理地址",mqttSettingsPath:"设置 → 网络 → MQTT发布",mqttNotConfiguredSuffix:"(您不需要启用发布,只需填写代理详细信息)。",mqttMonitorOnlyDescription:"MQTT插座通过MQTT订阅接收功率/能源数据。开关控制不可用 - 请使用您的MQTT代理或家庭自动化系统。",powerMonitoring:"功率监控",energyMonitoring:"能源监控",stateMonitoring:"状态监控",optional:"可选",topic:"主题",jsonPath:"JSON路径",multiplier:"乘数",onValue:"ON值",mqttPowerHint:`JSON路径从JSON负载中提取值(例如"power_l1")。如果主题发布原始数值,请留空。
- 乘数:mW→W使用0.001,kW→W使用1000。`,mqttEnergyHint:`JSON路径从JSON负载中提取值。原始值请留空。
- 乘数:Wh→kWh使用0.001,MWh→kWh使用1000。`,mqttStateHint:`JSON路径从JSON负载中提取值。原始值请留空。
- ON值:表示"ON"的确切字符串。留空以自动检测(ON、true、1)。`,restControl:"Control",restOnUrl:"Turn ON URL",restOffUrl:"Turn OFF URL",restOnBody:"ON Request Body",restOffBody:"OFF Request Body",restMethod:"HTTP Method",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status URL",restStatusPath:"State JSON Path",restStatusOnValue:"ON Value",restPowerUrl:"功率URL",restPowerPath:"Power JSON Path",restPowerMultiplier:"功率乘数",restEnergyUrl:"能耗URL",restEnergyPath:"Energy JSON Path",restEnergyMultiplier:"能耗乘数",restUrlRequired:"At least one URL (ON or OFF) is required for REST plugs",restHeadersHint:'e.g. {"Authorization": "Bearer your-token"}',restBodyHint:'e.g. ON, {"state": "on"}',restStatusHint:"URL to poll for current state",restPathHint:"e.g. state or data.power.status",restPowerUrlHint:"功率数据的独立URL(留空则使用状态URL)",restEnergyUrlHint:"能耗数据的独立URL(留空则使用状态URL)",restEnergyHint:"每个值可以使用独立的URL,或回退到状态URL。使用乘数进行单位转换(例如:0.001 将 Wh 转换为 kWh)。",testConnection:"Test Connection",connectionSuccess:"Connection successful",noSwitchesInSwitchbar:"开关栏中没有开关",enableSwitchbarHint:'在设置 > 智能插座中启用"在开关栏显示"'},notifications:{providerTypes:{callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"电子邮件",discord:"Discord",webhook:"Webhook",homeassistant:"Home Assistant"},providerDescriptions:{email:"SMTP 电子邮件通知",telegram:"通过 Telegram 机器人发送通知",discord:"通过 Webhook 发送到 Discord 频道",ntfy:"免费、可自托管的推送通知",pushover:"简单、可靠的推送通知",callmebot:"通过 CallMeBot 免费发送 WhatsApp 通知",webhook:"通用 HTTP POST 到任意 URL",homeassistant:"Home Assistant 仪表板中的持久通知"},lastSuccess:"上次:{{date}}",error:"错误",printer:"打印机:",allPrinters:"所有打印机",sendTestNotification:"发送测试通知",eventSettings:"事件设置",enabled:"已启用",sendFromProvider:"从此提供商发送通知",printEvents:"打印事件",printerStatus:"打印机状态",amsAlarms:"AMS 警报",amsHtAlarms:"AMS-HT 警报",printQueue:"打印队列",start:"开始",plateCheck:"热床检测",complete:"完成",failed:"失败",stopped:"已停止",progress:"进度",offline:"离线",lowFilament:"耗材不足",maintenance:"维护",amsHumidity:"AMS 湿度",amsTemp:"AMS 温度",amsHtHumidity:"AMS-HT 湿度",amsHtTemp:"AMS-HT 温度",bedCooled:"热床已冷却",firstLayer:"首层完成",quiet:"免打扰",digest:"摘要 {{time}}",printStarted:"打印已开始",plateNotEmpty:"热床非空",plateNotEmptyDescription:"打印前检测到物体",printCompleted:"打印已完成",bedCooledLabel:"热床已冷却",bedCooledDescription:"打印后热床温度降至阈值以下",firstLayerCompleteLabel:"首层打印完成",firstLayerCompleteDescription:"首层完成时发送带照片的通知",missingSpoolAssignmentLabel:"缺少料卷分配",missingSpoolAssignmentDescription:"当打印开始且所需料盘没有分配料卷时发送通知",printFailed:"打印失败",printStopped:"打印已停止",progressMilestones:"进度里程碑",progressMilestonesDescription:"在 25%、50%、75% 时通知",printerOffline:"打印机离线",printerError:"打印机错误",lowFilamentLabel:"耗材不足",maintenanceDue:"需要维护",maintenanceDueDescription:"需要维护时通知",amsHumidityHigh:"AMS 湿度过高",amsHumidityHighDescription:"普通 AMS 湿度超过阈值",amsTemperatureHigh:"AMS 温度过高",amsTemperatureHighDescription:"普通 AMS 温度超过阈值",amsHtHumidityHigh:"AMS-HT 湿度过高",amsHtHumidityHighDescription:"AMS-HT 湿度超过阈值",amsHtTemperatureHigh:"AMS-HT 温度过高",amsHtTemperatureHighDescription:"AMS-HT 温度超过阈值",jobAdded:"任务已添加",jobAddedDescription:"任务已添加到队列",jobAssigned:"任务已分配",jobAssignedDescription:"基于模型的任务已分配给打印机",jobStarted:"任务已开始",jobStartedDescription:"队列任务已开始打印",jobWaiting:"任务等待中",jobWaitingDescription:"任务正在等待耗材或打印机",jobSkipped:"任务已跳过",jobSkippedDescription:"任务已跳过(上一个失败)",jobFailed:"任务失败",jobFailedDescription:"任务启动失败",queueComplete:"队列已完成",queueCompleteDescription:"所有队列任务已完成",quietHours:"免打扰时段",noNotificationsDuring:"在此时段内不发送通知",editProviderToChangeQuietHours:"编辑提供商以更改免打扰时段",dailyDigest:"每日摘要",batchNotifications:"将通知汇总为每日摘要",sendAt:"发送于 {{time}}",editProviderToChangeDigestTime:"编辑提供商以更改摘要时间",edit:"编辑",deleteProvider:"删除通知提供商",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',delete:"删除",addTitle:"添加通知提供商",editTitle:"编辑通知提供商",nameLabel:"名称 *",namePlaceholder:"我的通知",providerTypeLabel:"提供商类型 *",configuration:"配置",testConfiguration:"测试配置",printerFilter:"打印机筛选",onlyFromPrinter:"仅发送来自此打印机的事件通知",quietHoursDnd:"免打扰时段",quietStart:"开始",quietEnd:"结束",dailyDigestLabel:"每日摘要",sendDigestAt:"发送摘要于",digestCollected:"事件将被收集并在此时间作为单条摘要发送",notificationEvents:"通知事件",progressPercent:"(25%、50%、75%)",bedCooledAfterPrint:"(打印完成后)",cancel:"取消",save:"保存",add:"添加",nameRequired:"名称为必填项",fieldRequired:"{{field}}为必填项",phoneNumber:"电话号码",apiKey:"API 密钥",serverUrl:"服务器 URL",topic:"主题",authToken:"认证令牌",userKey:"用户密钥",appToken:"应用令牌",priority:"优先级",botToken:"机器人令牌",chatId:"聊天 ID",smtpServer:"SMTP 服务器",smtpPort:"SMTP 端口",security:"安全",authentication:"认证",username:"用户名",password:"密码",fromEmail:"发件人邮箱",toEmail:"收件人邮箱",webhookUrl:"Webhook URL",payloadFormat:"负载格式",authorization:"授权",titleFieldName:"标题字段名",messageFieldName:"消息字段名",editTemplate:"编辑模板:{{name}}",titleLabel:"标题",bodyLabel:"正文",titlePlaceholder:"通知标题...",bodyPlaceholder:"通知正文...",availableVariables:"可用变量",clickToInsert:"点击插入到正文光标位置",livePreview:"实时预览",hide:"隐藏",show:"显示",loadingPreview:"加载预览中...",enterTemplateContent:"输入模板内容以查看预览",titlePreview:"标题:",bodyPreview:"正文:",resetToDefault:"恢复默认",titleRequired:"标题为必填项",bodyRequired:"正文为必填项",notificationLog:"通知日志",showFailedOnly:"仅显示失败",last24Hours:"最近 24 小时",last7Days:"最近 7 天",last30Days:"最近 30 天",last90Days:"最近 90 天",justNow:"刚刚",noFailedNotifications:"没有失败的通知",noNotificationsLogged:"没有通知记录",unknownProvider:"未知提供商",logTitle:"标题",logMessage:"消息",logError:"错误",logProvider:"提供商:{{type}}",logTime:"时间:{{time}}",refresh:"刷新",clearOld:"清除旧记录",statsSummary:"最近 {{days}} 天:",statsNotifications:"条通知",statsSent:"{{count}} 条已发送",statsFailed:"{{count}} 条失败",eventTypes:{print_start:"打印已开始",print_complete:"打印完成",print_failed:"打印失败",print_stopped:"打印已停止",print_progress:"进度",printer_offline:"打印机离线",printer_error:"打印机错误",filament_low:"耗材不足",maintenance_due:"需要维护",test:"测试"},userEmail:{title:"通知",emailNotifications:"邮件通知",emailNotificationsDesc:"接收您自己打印任务的邮件通知。邮件将通过高级身份验证中配置的 SMTP 设置发送。",sendingTo:"通知将发送至",noEmailWarning:"您的账户没有邮件地址。请联系管理员添加。",printJobNotifications:"打印任务通知",printJobNotificationsDesc:"选择哪些事件会触发您提交的打印任务的邮件通知。",printJobStarts:"打印任务开始",printJobStartsDesc:"当您的打印任务开始时收到通知。",printJobFinishes:"打印任务完成",printJobFinishesDesc:"当您的打印任务成功完成时收到通知。",printErrors:"打印错误",printErrorsDesc:"当您的打印任务失败或遇到错误时收到通知。",printJobStops:"打印任务停止",printJobStopsDesc:"当您的打印任务被取消或停止时收到通知。",saveSuccess:"通知偏好设置已保存。",saveError:"保存通知偏好设置失败。"}},richTextEditor:{bold:"粗体",italic:"斜体",underline:"下划线",bulletList:"无序列表",numberedList:"有序列表",alignLeft:"左对齐",alignCenter:"居中对齐",alignRight:"右对齐",addLink:"添加链接",removeLink:"移除链接"},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 或点击外部关闭"},notificationLog:{title:"通知日志",events:{printStarted:"打印开始",printComplete:"打印完成",printFailed:"打印失败",printStopped:"打印停止",progress:"进度",printerOffline:"打印机离线",printerError:"打印机错误",lowFilament:"耗材不足",maintenanceDue:"维护到期",test:"测试"},timeAgo:{justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前"}},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:"项目、材料清单和附件",pendingUploads:"虚拟打印机待审核的上传",apiKeys:"Webhook API 密钥(导入时生成新密钥)"},requiresPrinters:"需要选择打印机",zipFileWarning:"将创建 ZIP 文件。",zipFileDescription:"包括所有 3MF 文件、缩略图、延时摄影和照片。这可能需要一些时间并生成较大的文件。",includeAccessCodes:"包含访问码",includeAccessCodesDescription:"用于转移到另一台机器",includeAccessCodesWarning:"访问码将以明文形式包含。请妥善保管此备份文件!",categoriesSelected:"已选择 {{selectedCount}} 个类别"},pendingUploads:{placeholders:{notes:"添加关于此打印的备注..."},discardUpload:"丢弃上传",archiveAllUploads:"归档所有上传",discardAllUploads:"丢弃所有上传",archive:"归档",timeAgo:{justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前",daysAgo:"{{days}} 天前"}},apiBrowser:{placeholders:{requestBody:"JSON 请求体...",searchEndpoints:"搜索端点..."}},configureAmsSlot:{title:"配置 AMS 槽位",slotConfigured:"槽位已配置!",configuringSlot:"正在配置槽位:",slotLabel:"{{ams}} 槽位 {{slot}}",searchPresets:"搜索预设...",colorPlaceholder:"颜色名称或十六进制(例如:棕色、FF8800)",clearCustomColor:"清除自定义颜色",noCloudPresets:"无云端预设。登录拓竹云以同步。",noPresetsAvailable:"无可用预设。登录拓竹云或导入本地配置。",noMatchingPresets:"未找到匹配的预设。",custom:"自定义",builtin:"内置",settingsSentToPrinter:"设置已发送到打印机",filamentProfile:"耗材配置",kProfileLabel:"K 值配置(压力推进)",filteringFor:"筛选:{{material}}",noKProfile:"无 K 值配置(使用默认值 0.020)",noMatchingKProfiles:"未找到匹配的 K 值配置。将使用默认 K=0.020。",selectFilamentFirst:"请先选择耗材配置",kFromCalibration:"K={{value}}(来自打印机校准)",customColorLabel:"自定义颜色(可选)",presetColors:"{{name}} 颜色:",showLessColors:"显示更少颜色",showMoreColors:"显示更多颜色",clear:"清除",hexLabel:"十六进制:#{{hex}}",resetting:"重置中...",resetSlot:"重置槽位",cancel:"取消",configuring:"配置中...",configureSlot:"配置槽位"},githubBackup:{title:"GitHub 备份",history:"历史",downloadBackup:"下载备份",restoreBackup:"恢复备份",noBackupsYet:"暂无备份"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"搜索标签...",renameTag:"重命名标签",deleteTag:"删除标签"},notificationTemplates:{placeholders:{title:"通知标题...",body:"通知正文..."}},batchTag:{placeholders:{newTag:"输入新标签..."}},photoGallery:{deletePhoto:"删除照片"},filamentHoverCard:{copySpoolUuid:"复制耗材 UUID"},kProfilesView:{hasNote:"有备注",copyProfile:"复制配置"},layout:{openMenu:"打开菜单",noPermissionSystemInfo:"您没有查看系统信息的权限"},dashboard:{dragToReorder:"拖动以重新排列",hideWidget:"隐藏小部件"},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:"通用 HTTP POST 到任意 URL"}},logViewer:{searchPlaceholder:"搜索消息或日志名称...",noLogEntries:"未找到日志条目"},switchbarPopover:{noSwitchesInSwitchbar:"切换栏中没有开关"},projectPageModal:{placeholders:{title:"标题",designer:"设计师",license:"许可证",description:"输入描述...",profileTitle:"配置标题",profileDescription:"配置描述..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"等待中",justNow:"刚刚",now:"现在",minsAgo:"{{count}} 分钟前",inMins:"{{count}} 分钟后",hoursAgo:"{{count}} 小时前",inHours:"{{count}} 小时后",daysAgo:"{{count}} 天前",inDays:"{{count}} 天后"},spoolbuddy:{nav:{dashboard:"仪表板",ams:"AMS",inventory:"库存",writeTag:"写入",settings:"设置"},status:{nfcReady:"NFC 就绪",nfcOff:"NFC 关闭",offline:"离线",online:"在线",noPrinters:"无打印机",deviceOffline:"设备离线",waitingConnection:"等待设备连接...",systemReady:"系统就绪",status:"状态"},dashboard:{readyToScan:"准备扫描",idleMessage:"将耗材放在秤上以识别",nfcHint:"NFC 标签将自动读取",device:"设备",syncWeight:"同步重量",weightSynced:"已同步!",unknownTag:"未知标签",newTag:"检测到新标签",onScale:"在秤上",linkSpool:"链接到耗材",linkTagTitle:"将标签链接到耗材",linkTag:"链接标签",selectSpool:"选择要链接此标签的耗材:",noUntagged:"未找到没有标签的耗材",tagDetected:"检测到标签",noTag:"无标签",tagId:"标签",grossWeight:"毛重",spoolSize:"耗材盘尺寸",close:"关闭",currentSpool:"当前耗材"},modal:{spoolDetected:"检测到耗材",assignToAms:"分配到 AMS",syncWeight:"同步重量",weightSynced:"已同步!",syncing:"同步中...",newTagDetected:"检测到新标签",addToInventory:"添加到库存",assignToAmsTitle:"分配到 AMS",selectSlot:"选择槽位",assign:"分配",assigning:"分配中...",assignSuccess:"已分配!",assignError:"分配耗材失败。请重试。",noPrinterSelected:"选择打印机...",noAmsDetected:"此打印机未检测到 AMS",slot:"槽位"},weight:{noReading:"无读数",stable:"稳定",measuring:"测量中...",tare:"去皮",calibrate:"校准"},spool:{remaining:"剩余",material:"材料",brand:"品牌",color:"颜色",coreWeight:"空盘",labelWeight:"标签",scaleWeight:"秤重",netWeight:"净重",lastUsed:"上次使用"},ams:{noData:"未检测到 AMS",connectAms:"连接 AMS 以查看耗材槽位",noPrinter:"未选择打印机",selectPrinter:"从顶部栏选择打印机",printerDisconnected:"打印机已断开",humidity:"湿度",level:"余量",active:"活跃",slot:"槽位",empty:"空"},inventory:{search:"搜索耗材...",empty:"库存中没有耗材",noResults:"没有匹配的耗材",spools:"个耗材",addSpool:"添加耗材"},settings:{tabDevice:"设备",tabDisplay:"显示",tabScale:"秤",tabUpdates:"更新",nfcReader:"NFC 读卡器",type:"类型",connection:"连接",notConnected:"不适用",deviceInfo:"设备信息",hostname:"主机",uptime:"运行时间",brightness:"亮度",saved:"已保存",noBacklight:"未检测到 DSI 背光。亮度控制需要 DSI 显示屏。",screenBlank:"屏幕熄灭超时",screenBlankDesc:"不活动后屏幕关闭。触摸唤醒。",displayNote:"亮度作为软件滤镜应用。",scaleCalibration:"秤校准",currentWeight:"当前重量",tareOffset:"去皮",calFactor:"系数",knownWeight:"已知重量",calStep1:"移除秤上所有物品并按设置零点。",calStep2:"将已知重量放在秤上。",setZero:"设置零点",calibrateNow:"校准",calibrated:"已校准",tareSet:"去皮命令已发送。等待设备响应...",tareFailed:"发送去皮命令失败",zeroSet:"零点已设置。将已知重量放在秤上。",calibrationDone:"校准完成!",calibrationFailed:"校准失败",lastCalibrated:"上次校准",stable:"稳定",settling:"稳定中...",firmware:"固件",scale:"秤",noDevice:"未找到 SpoolBuddy 设备",daemonVersion:"守护进程版本",currentVersion:"当前",versionPending:"等待守护进程...",checking:"检查中...",checkUpdates:"检查更新",updateAvailable:"有可用更新",updateInstructions:"通过 SSH 更新:运行 SpoolBuddy 安装脚本进行升级。",upToDate:"已是最新",includeBeta:"包含测试版本"},writeTag:{tabExisting:"现有耗材",tabNew:"新耗材",tabReplace:"替换标签",searchPlaceholder:"按材料、颜色、品牌搜索...",noUntaggedSpools:"没有无标签的耗材",noTaggedSpools:"没有有标签的耗材",selectSpool:"选择一个耗材,然后将空白 NTAG 放在读卡器上",placeTag:"将 NTAG 放在读卡器上",tagReady:"检测到标签 — 准备写入",writeTag:"写入标签",replaceTag:"替换标签",writing:"写入标签中...",waiting:"等待 SpoolBuddy...",writeSuccess:"标签写入成功!",writeFailed:"写入失败",queueFailed:"排队写入命令失败",tryAgain:"重试",cancel:"取消",replaceWarning:"旧标签将被取消链接。新标签将替换它。",deviceOffline:"SpoolBuddy 离线",material:"材料",colorName:"颜色名称",color:"颜色",brand:"品牌",weight:"重量 (g)",createSpool:"创建耗材",creating:"创建中...",spoolCreated:"耗材已创建!准备写入。",createFailed:"创建耗材失败"},quickMenu:{printerPower:"打印机电源",systemControls:"系统",restartDaemon:"重启守护进程",restartBrowser:"重启浏览器",reboot:"重启",shutdown:"关机",swipeToClose:"向下滑动关闭",confirmTitle:"确认",confirmShutdown:"确定要关闭SpoolBuddy吗?您需要物理访问才能重新开启。",confirmReboot:"确定要重启SpoolBuddy吗?",confirmRestartDaemon:"重启SpoolBuddy守护进程?NFC和秤将暂时不可用。",confirmRestartBrowser:"重启kiosk浏览器?屏幕将短暂变黑。",confirm:"确认",confirmPlugOn:"开启 {{name}}?",confirmPlugOff:"关闭 {{name}}?",turnOn:"开启",turnOff:"关闭"}},bugReport:{title:"报告错误",description:"描述",descriptionPlaceholder:"出了什么问题?请描述问题...",email:"邮箱(可选)",emailPlaceholder:"your@email.com",emailPrivacy:"如果提供,您的邮箱将包含在GitHub Issue的折叠部分中,以便维护者后续跟进。",screenshot:"截图",uploadOrPaste:"上传、粘贴或拖拽图片",dataCollectedSummary:"报告中包含哪些数据?",dataIncluded:"包含:",dataIncludedList:"应用版本、操作系统、架构、Python版本、数据库统计(仅计数)、打印机型号、喷嘴数量、固件版本、连接状态、集成状态(Spoolman、MQTT、HA)、非敏感设置、网络接口数量、Docker详情、依赖版本。",dataNeverIncluded:"绝不包含:",dataNeverIncludedList:"打印机名称、序列号、访问代码、密码、IP地址、邮箱地址、API密钥、令牌、Webhook URL、主机名或用户名。",submit:"提交",startLogging:"开始调试日志",stepEnableLogging:"调试日志已启用",stepReproduce:"请现在重现问题",stepStopLogging:"停止并提交报告",stopAndSubmit:"停止并提交",maxDuration:"{{minutes}}分钟后自动停止",stoppingLogs:"正在收集日志并提交...",submitting:"正在提交错误报告...",submitSuccess:"错误报告提交成功!",submitFailed:"提交错误报告失败",thankYou:"谢谢!",submitted:"您的错误报告已提交。",viewIssue:"查看Issue",unexpectedError:"发生了意外错误"},failureDetection:{title:"AI 故障检测",description:"通过自托管的 Obico ML API 监控打印,并对检测到的故障自动采取行动。",mlUrl:"Obico ML API 地址",mlUrlHint:"您自托管的 Obico ml_api 容器的基础 URL(例如 http://192.168.1.10:3333)。",test:"测试",testSuccess:"ML API 可访问且正常。",testFailed:"无法访问 ML API。",sensitivity:"灵敏度",sensitivityLow:"低(减少误报)",sensitivityMedium:"中(平衡)",sensitivityHigh:"高(更早检测,更多误报)",sensitivityHint:"调整触发警告和故障的置信度阈值。",action:"检测到故障时的操作",actionNotify:"仅通知",actionPause:"暂停打印",actionPauseOff:"暂停并切断电源",pollInterval:"检查间隔(秒)",pollIntervalHint:"打印过程中每台打印机的检查频率。最小 5 秒,最大 120 秒。",externalUrlMissing:"未设置外部 URL。",externalUrlHint:"ML API 通过 URL 获取相机截图。请在常规设置中设置外部 URL,以便 ML API 容器可以访问 Bambuddy。",perPrinterTitle:"监控的打印机",perPrinterHint:"选择检测服务要监视哪些打印机。",monitorAll:"监控所有已连接的打印机",statusTitle:"状态",serviceRunning:"服务运行中",thresholds:"低 / 高阈值",activePrinters:"活动打印",noActivePrints:"当前没有正在进行的打印。",historyTitle:"最近检测",noHistory:"暂无检测记录。"}},Gue={en:{translation:zue},de:{translation:Uue},fr:{translation:Bue},ja:{translation:Hue},it:{translation:que},"pt-BR":{translation:$ue},"zh-CN":{translation:Vue}};lo.use(BY).use(bue).init({resources:Gue,fallbackLng:"en",supportedLngs:["en","de","fr","ja","it","pt-BR","zh-CN"],detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:"bambutrack_language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!1}});const J8=[{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)"},{code:"zh-CN",name:"Chinese (Simplified)",nativeName:"简体中文"}];var eH="popstate";function Wue(t={}){function e(r,i){let{pathname:s,search:o,hash:l}=r.location;return D3("",{pathname:s,search:o,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(r,i){return typeof i=="string"?i:O0(i)}return Xue(e,n,null,t)}function ka(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function rc(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function Kue(){return Math.random().toString(36).substring(2,10)}function tH(t,e){return{usr:t.state,key:t.key,idx:e}}function D3(t,e,n=null,r){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof e=="string"?ny(e):e,state:n,key:e&&e.key||r||Kue()}}function O0({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 ny(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 Xue(t,e,n,r={}){let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,l="POP",c=null,d=u();d==null&&(d=0,o.replaceState({...o.state,idx:d},""));function u(){return(o.state||{idx:null}).idx}function m(){l="POP";let g=u(),b=g==null?null:g-d;d=g,c&&c({action:l,location:v.location,delta:b})}function p(g,b){l="PUSH";let _=D3(v.location,g,b);d=u()+1;let C=tH(_,d),P=v.createHref(_);try{o.pushState(C,"",P)}catch(N){if(N instanceof DOMException&&N.name==="DataCloneError")throw N;i.location.assign(P)}s&&c&&c({action:l,location:v.location,delta:1})}function f(g,b){l="REPLACE";let _=D3(v.location,g,b);d=u();let C=tH(_,d),P=v.createHref(_);o.replaceState(C,"",P),s&&c&&c({action:l,location:v.location,delta:0})}function x(g){return Yue(g)}let v={get action(){return l},get location(){return t(i,o)},listen(g){if(c)throw new Error("A history only accepts one active listener");return i.addEventListener(eH,m),c=g,()=>{i.removeEventListener(eH,m),c=null}},createHref(g){return e(i,g)},createURL:x,encodeLocation(g){let b=x(g);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:p,replace:f,go(g){return o.go(g)}};return v}function Yue(t,e=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ka(n,"No window.location.(origin|href) available to create URL");let r=typeof t=="string"?t:O0(t);return r=r.replace(/ $/,"%20"),!e&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function HY(t,e,n="/"){return Que(t,e,n,!1)}function Que(t,e,n,r){let i=typeof e=="string"?ny(e):e,s=nm(i.pathname||"/",n);if(s==null)return null;let o=qY(t);Zue(o);let l=null;for(let c=0;l==null&&c<o.length;++c){let d=cme(s);l=ome(o[c],d,r)}return l}function qY(t,e=[],n=[],r="",i=!1){let s=(o,l,c=i,d)=>{let u={relativePath:d===void 0?o.path||"":d,caseSensitive:o.caseSensitive===!0,childrenIndex:l,route:o};if(u.relativePath.startsWith("/")){if(!u.relativePath.startsWith(r)&&c)return;ka(u.relativePath.startsWith(r),`Absolute route path "${u.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),u.relativePath=u.relativePath.slice(r.length)}let m=Wu([r,u.relativePath]),p=n.concat(u);o.children&&o.children.length>0&&(ka(o.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${m}".`),qY(o.children,e,p,m,c)),!(o.path==null&&!o.index)&&e.push({path:m,score:ime(m,o.index),routesMeta:p})};return t.forEach((o,l)=>{if(o.path===""||!o.path?.includes("?"))s(o,l);else for(let c of $Y(o.path))s(o,l,!0,c)}),e}function $Y(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=$Y(r.join("/")),l=[];return l.push(...o.map(c=>c===""?s:[s,c].join("/"))),i&&l.push(...o),l.map(c=>t.startsWith("/")&&c===""?"/":c)}function Zue(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:sme(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Jue=/^:[\w-]+$/,eme=3,tme=2,nme=1,rme=10,ame=-2,nH=t=>t==="*";function ime(t,e){let n=t.split("/"),r=n.length;return n.some(nH)&&(r+=ame),e&&(r+=tme),n.filter(i=>!nH(i)).reduce((i,s)=>i+(Jue.test(s)?eme:s===""?nme:rme),r)}function sme(t,e){return t.length===e.length&&t.slice(0,-1).every((r,i)=>r===e[i])?t[t.length-1]-e[e.length-1]:0}function ome(t,e,n=!1){let{routesMeta:r}=t,i={},s="/",o=[];for(let l=0;l<r.length;++l){let c=r[l],d=l===r.length-1,u=s==="/"?e:e.slice(s.length)||"/",m=tN({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},u),p=c.route;if(!m&&d&&n&&!r[r.length-1].route.index&&(m=tN({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},u)),!m)return null;Object.assign(i,m.params),o.push({params:i,pathname:Wu([s,m.pathname]),pathnameBase:hme(Wu([s,m.pathnameBase])),route:p}),m.pathnameBase!=="/"&&(s=Wu([s,m.pathnameBase]))}return o}function tN(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=lme(t.path,t.caseSensitive,t.end),i=e.match(n);if(!i)return null;let s=i[0],o=s.replace(/(.)\/+$/,"$1"),l=i.slice(1);return{params:r.reduce((d,{paramName:u,isOptional:m},p)=>{if(u==="*"){let x=l[p]||"";o=s.slice(0,s.length-x.length).replace(/(.)\/+$/,"$1")}const f=l[p];return m&&!f?d[u]=void 0:d[u]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:s,pathnameBase:o,pattern:t}}function lme(t,e=!1,n=!0){rc(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=[],i="^"+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:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function cme(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return rc(!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 nm(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 dme=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function ume(t,e="/"){let{pathname:n,search:r="",hash:i=""}=typeof t=="string"?ny(t):t,s;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?s=rH(n.substring(1),"/"):s=rH(n,e)):s=e,{pathname:s,search:pme(r),hash:fme(i)}}function rH(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function hM(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 mme(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function tO(t){let e=mme(t);return e.map((n,r)=>r===e.length-1?n.pathname:n.pathnameBase)}function nO(t,e,n,r=!1){let i;typeof t=="string"?i=ny(t):(i={...t},ka(!i.pathname||!i.pathname.includes("?"),hM("?","pathname","search",i)),ka(!i.pathname||!i.pathname.includes("#"),hM("#","pathname","hash",i)),ka(!i.search||!i.search.includes("#"),hM("#","search","hash",i)));let s=t===""||i.pathname==="",o=s?"/":i.pathname,l;if(o==null)l=n;else{let m=e.length-1;if(!r&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),m-=1;i.pathname=p.join("/")}l=m>=0?e[m]:"/"}let c=ume(i,l),d=o&&o!=="/"&&o.endsWith("/"),u=(s||o===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}var Wu=t=>t.join("/").replace(/\/\/+/g,"/"),hme=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),pme=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,fme=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,gme=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 bme(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function xme(t){return t.map(e=>e.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var VY=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function GY(t,e){let n=t;if(typeof n!="string"||!dme.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(VY)try{let s=new URL(window.location.href),o=n.startsWith("//")?new URL(s.protocol+n):new URL(n),l=nm(o.pathname,e);o.origin===s.origin&&l!=null?n=l+o.search+o.hash:i=!0}catch{rc(!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:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var WY=["POST","PUT","PATCH","DELETE"];new Set(WY);var yme=["GET",...WY];new Set(yme);var ry=w.createContext(null);ry.displayName="DataRouter";var NP=w.createContext(null);NP.displayName="DataRouterState";var vme=w.createContext(!1),KY=w.createContext({isTransitioning:!1});KY.displayName="ViewTransition";var wme=w.createContext(new Map);wme.displayName="Fetchers";var Sme=w.createContext(null);Sme.displayName="Await";var pl=w.createContext(null);pl.displayName="Navigation";var Mw=w.createContext(null);Mw.displayName="Location";var hc=w.createContext({outlet:null,matches:[],isDataRoute:!1});hc.displayName="Route";var rO=w.createContext(null);rO.displayName="RouteError";var XY="REACT_ROUTER_ERROR",_me="REDIRECT",kme="ROUTE_ERROR_RESPONSE";function Nme(t){if(t.startsWith(`${XY}:${_me}:{`))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 Cme(t){if(t.startsWith(`${XY}:${kme}:{`))try{let e=JSON.parse(t.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new gme(e.status,e.statusText,e.data)}catch{}}function Pme(t,{relative:e}={}){ka(ay(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=w.useContext(pl),{hash:i,pathname:s,search:o}=Dw(t,{relative:e}),l=s;return n!=="/"&&(l=s==="/"?n:Wu([n,s])),r.createHref({pathname:l,search:o,hash:i})}function ay(){return w.useContext(Mw)!=null}function $c(){return ka(ay(),"useLocation() may be used only in the context of a <Router> component."),w.useContext(Mw).location}var YY="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function QY(t){w.useContext(pl).static||w.useLayoutEffect(t)}function Do(){let{isDataRoute:t}=w.useContext(hc);return t?Bme():Tme()}function Tme(){ka(ay(),"useNavigate() may be used only in the context of a <Router> component.");let t=w.useContext(ry),{basename:e,navigator:n}=w.useContext(pl),{matches:r}=w.useContext(hc),{pathname:i}=$c(),s=JSON.stringify(tO(r)),o=w.useRef(!1);return QY(()=>{o.current=!0}),w.useCallback((c,d={})=>{if(rc(o.current,YY),!o.current)return;if(typeof c=="number"){n.go(c);return}let u=nO(c,JSON.parse(s),i,d.relative==="path");t==null&&e!=="/"&&(u.pathname=u.pathname==="/"?e:Wu([e,u.pathname])),(d.replace?n.replace:n.push)(u,d.state,d)},[e,n,s,i,t])}var ZY=w.createContext(null);function iy(){return w.useContext(ZY)}function Ame(t){let e=w.useContext(hc).outlet;return w.useMemo(()=>e&&w.createElement(ZY.Provider,{value:t},e),[e,t])}function Ew(){let{matches:t}=w.useContext(hc),e=t[t.length-1];return e?e.params:{}}function Dw(t,{relative:e}={}){let{matches:n}=w.useContext(hc),{pathname:r}=$c(),i=JSON.stringify(tO(n));return w.useMemo(()=>nO(t,JSON.parse(i),r,e==="path"),[t,i,r,e])}function jme(t,e){return JY(t,e)}function JY(t,e,n,r,i){ka(ay(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=w.useContext(pl),{matches:o}=w.useContext(hc),l=o[o.length-1],c=l?l.params:{},d=l?l.pathname:"/",u=l?l.pathnameBase:"/",m=l&&l.route;{let _=m&&m.path||"";tQ(d,!m||_.endsWith("*")||_.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${d}" (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.
- Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}/*`}">.`)}let p=$c(),f;if(e){let _=typeof e=="string"?ny(e):e;ka(u==="/"||_.pathname?.startsWith(u),`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 "${u}" but pathname "${_.pathname}" was given in the \`location\` prop.`),f=_}else f=p;let x=f.pathname||"/",v=x;if(u!=="/"){let _=u.replace(/^\//,"").split("/");v="/"+x.replace(/^\//,"").split("/").slice(_.length).join("/")}let g=HY(t,{pathname:v});rc(m||g!=null,`No routes matched location "${f.pathname}${f.search}${f.hash}" `),rc(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 "${f.pathname}${f.search}${f.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 b=Rme(g&&g.map(_=>Object.assign({},_,{params:Object.assign({},c,_.params),pathname:Wu([u,s.encodeLocation?s.encodeLocation(_.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?u:Wu([u,s.encodeLocation?s.encodeLocation(_.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathnameBase])})),o,n,r,i);return e&&b?w.createElement(Mw.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...f},navigationType:"POP"}},b):b}function Mme(){let t=Ume(),e=bme(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)",i={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:i},n):null,o)}var Eme=w.createElement(Mme,null),eQ=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=Cme(t.digest);n&&(t=n)}let e=t!==void 0?w.createElement(hc.Provider,{value:this.props.routeContext},w.createElement(rO.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?w.createElement(Dme,{error:t},e):e}};eQ.contextType=vme;var pM=new WeakMap;function Dme({children:t,error:e}){let{basename:n}=w.useContext(pl);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let r=Nme(e.digest);if(r){let i=pM.get(e);if(i)throw i;let s=GY(r.location,n);if(VY&&!pM.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 pM.set(e,o),o}return w.createElement("meta",{httpEquiv:"refresh",content:`0;url=${s.absoluteURL||s.to}`})}}return t}function Fme({routeContext:t,match:e,children:n}){let r=w.useContext(ry);return r&&r.static&&r.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=e.route.id),w.createElement(hc.Provider,{value:t},n)}function Rme(t,e=[],n=null,r=null,i=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 u=s.findIndex(m=>m.route.id&&o?.[m.route.id]!==void 0);ka(u>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,u+1))}let l=!1,c=-1;if(n)for(let u=0;u<s.length;u++){let m=s[u];if((m.route.HydrateFallback||m.route.hydrateFallbackElement)&&(c=u),m.route.id){let{loaderData:p,errors:f}=n,x=m.route.loader&&!p.hasOwnProperty(m.route.id)&&(!f||f[m.route.id]===void 0);if(m.route.lazy||x){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}let d=n&&r?(u,m)=>{r(u,{location:n.location,params:n.matches?.[0]?.params??{},unstable_pattern:xme(n.matches),errorInfo:m})}:void 0;return s.reduceRight((u,m,p)=>{let f,x=!1,v=null,g=null;n&&(f=o&&m.route.id?o[m.route.id]:void 0,v=m.route.errorElement||Eme,l&&(c<0&&p===0?(tQ("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),x=!0,g=null):c===p&&(x=!0,g=m.route.hydrateFallbackElement||null)));let b=e.concat(s.slice(0,p+1)),_=()=>{let C;return f?C=v:x?C=g:m.route.Component?C=w.createElement(m.route.Component,null):m.route.element?C=m.route.element:C=u,w.createElement(Fme,{match:m,routeContext:{outlet:u,matches:b,isDataRoute:n!=null},children:C})};return n&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?w.createElement(eQ,{location:n.location,revalidation:n.revalidation,component:v,error:f,children:_(),routeContext:{outlet:null,matches:b,isDataRoute:!0},onError:d}):_()},null)}function aO(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Lme(t){let e=w.useContext(ry);return ka(e,aO(t)),e}function Ome(t){let e=w.useContext(NP);return ka(e,aO(t)),e}function Ime(t){let e=w.useContext(hc);return ka(e,aO(t)),e}function iO(t){let e=Ime(t),n=e.matches[e.matches.length-1];return ka(n.route.id,`${t} can only be used on routes that contain a unique "id"`),n.route.id}function zme(){return iO("useRouteId")}function Ume(){let t=w.useContext(rO),e=Ome("useRouteError"),n=iO("useRouteError");return t!==void 0?t:e.errors?.[n]}function Bme(){let{router:t}=Lme("useNavigate"),e=iO("useNavigate"),n=w.useRef(!1);return QY(()=>{n.current=!0}),w.useCallback(async(i,s={})=>{rc(n.current,YY),n.current&&(typeof i=="number"?await t.navigate(i):await t.navigate(i,{fromRouteId:e,...s}))},[t,e])}var aH={};function tQ(t,e,n){!e&&!aH[t]&&(aH[t]=!0,rc(!1,n))}w.memo(Hme);function Hme({routes:t,future:e,state:n,onError:r}){return JY(t,void 0,n,r,e)}function Nx({to:t,replace:e,state:n,relative:r}){ka(ay(),"<Navigate> may be used only in the context of a <Router> component.");let{static:i}=w.useContext(pl);rc(!i,"<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(hc),{pathname:o}=$c(),l=Do(),c=nO(t,tO(s),o,r==="path"),d=JSON.stringify(c);return w.useEffect(()=>{l(JSON.parse(d),{replace:e,state:n,relative:r})},[l,d,r,e,n]),null}function nQ(t){return Ame(t.context)}function Er(t){ka(!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 qme({basename:t="/",children:e=null,location:n,navigationType:r="POP",navigator:i,static:s=!1,unstable_useTransitions:o}){ka(!ay(),"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:i,static:s,unstable_useTransitions:o,future:{}}),[l,i,s,o]);typeof n=="string"&&(n=ny(n));let{pathname:d="/",search:u="",hash:m="",state:p=null,key:f="default"}=n,x=w.useMemo(()=>{let v=nm(d,l);return v==null?null:{location:{pathname:v,search:u,hash:m,state:p,key:f},navigationType:r}},[l,d,u,m,p,f,r]);return rc(x!=null,`<Router basename="${l}"> is not able to match the URL "${d}${u}${m}" because it does not start with the basename, so the <Router> won't render anything.`),x==null?null:w.createElement(pl.Provider,{value:c},w.createElement(Mw.Provider,{children:e,value:x}))}function $me({children:t,location:e}){return jme(F3(t),e)}function F3(t,e=[]){let n=[];return w.Children.forEach(t,(r,i)=>{if(!w.isValidElement(r))return;let s=[...e,i];if(r.type===w.Fragment){n.push.apply(n,F3(r.props.children,s));return}ka(r.type===Er,`[${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>`),ka(!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=F3(r.props.children,s)),n.push(o)}),n}var Sk="get",_k="application/x-www-form-urlencoded";function CP(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function Vme(t){return CP(t)&&t.tagName.toLowerCase()==="button"}function Gme(t){return CP(t)&&t.tagName.toLowerCase()==="form"}function Wme(t){return CP(t)&&t.tagName.toLowerCase()==="input"}function Kme(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function Xme(t,e){return t.button===0&&(!e||e==="_self")&&!Kme(t)}function R3(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(i=>[n,i]):[[n,r]])},[]))}function Yme(t,e){let n=R3(t);return e&&e.forEach((r,i)=>{n.has(i)||e.getAll(i).forEach(s=>{n.append(i,s)})}),n}var E_=null;function Qme(){if(E_===null)try{new FormData(document.createElement("form"),0),E_=!1}catch{E_=!0}return E_}var Zme=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function fM(t){return t!=null&&!Zme.has(t)?(rc(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${_k}"`),null):t}function Jme(t,e){let n,r,i,s,o;if(Gme(t)){let l=t.getAttribute("action");r=l?nm(l,e):null,n=t.getAttribute("method")||Sk,i=fM(t.getAttribute("enctype"))||_k,s=new FormData(t)}else if(Vme(t)||Wme(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?nm(c,e):null,n=t.getAttribute("formmethod")||l.getAttribute("method")||Sk,i=fM(t.getAttribute("formenctype"))||fM(l.getAttribute("enctype"))||_k,s=new FormData(l,t),!Qme()){let{name:d,type:u,value:m}=t;if(u==="image"){let p=d?`${d}.`:"";s.append(`${p}x`,"0"),s.append(`${p}y`,"0")}else d&&s.append(d,m)}}else{if(CP(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Sk,r=null,i=_k,o=t}return s&&i==="text/plain"&&(o=s,s=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:s,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function sO(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function ehe(t,e,n,r){let i=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return n?i.pathname.endsWith("/")?i.pathname=`${i.pathname}_.${r}`:i.pathname=`${i.pathname}.${r}`:i.pathname==="/"?i.pathname=`_root.${r}`:e&&nm(i.pathname,e)==="/"?i.pathname=`${e.replace(/\/$/,"")}/_root.${r}`:i.pathname=`${i.pathname.replace(/\/$/,"")}.${r}`,i}async function the(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 nhe(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 rhe(t,e,n){let r=await Promise.all(t.map(async i=>{let s=e.routes[i.route.id];if(s){let o=await the(s,n);return o.links?o.links():[]}return[]}));return ohe(r.flat(1).filter(nhe).filter(i=>i.rel==="stylesheet"||i.rel==="preload").map(i=>i.rel==="stylesheet"?{...i,rel:"prefetch",as:"style"}:{...i,rel:"prefetch"}))}function iH(t,e,n,r,i,s){let o=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>n[d].pathname!==c.pathname||n[d].route.path?.endsWith("*")&&n[d].params["*"]!==c.params["*"];return s==="assets"?e.filter((c,d)=>o(c,d)||l(c,d)):s==="data"?e.filter((c,d)=>{let u=r.routes[c.route.id];if(!u||!u.hasLoader)return!1;if(o(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let m=c.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(t,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof m=="boolean")return m}return!0}):[]}function ahe(t,e,{includeHydrateFallback:n}={}){return ihe(t.map(r=>{let i=e.routes[r.route.id];if(!i)return[];let s=[i.module];return i.clientActionModule&&(s=s.concat(i.clientActionModule)),i.clientLoaderModule&&(s=s.concat(i.clientLoaderModule)),n&&i.hydrateFallbackModule&&(s=s.concat(i.hydrateFallbackModule)),i.imports&&(s=s.concat(i.imports)),s}).flat(1))}function ihe(t){return[...new Set(t)]}function she(t){let e={},n=Object.keys(t).sort();for(let r of n)e[r]=t[r];return e}function ohe(t,e){let n=new Set;return new Set(e),t.reduce((r,i)=>{let s=JSON.stringify(she(i));return n.has(s)||(n.add(s),r.push({key:s,link:i})),r},[])}function rQ(){let t=w.useContext(ry);return sO(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function lhe(){let t=w.useContext(NP);return sO(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var oO=w.createContext(void 0);oO.displayName="FrameworkContext";function aQ(){let t=w.useContext(oO);return sO(t,"You must render this element inside a <HydratedRouter> element"),t}function che(t,e){let n=w.useContext(oO),[r,i]=w.useState(!1),[s,o]=w.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:u,onTouchStart:m}=e,p=w.useRef(null);w.useEffect(()=>{if(t==="render"&&o(!0),t==="viewport"){let v=b=>{b.forEach(_=>{o(_.isIntersecting)})},g=new IntersectionObserver(v,{threshold:.5});return p.current&&g.observe(p.current),()=>{g.disconnect()}}},[t]),w.useEffect(()=>{if(r){let v=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(v)}}},[r]);let f=()=>{i(!0)},x=()=>{i(!1),o(!1)};return n?t!=="intent"?[s,p,{}]:[s,p,{onFocus:pv(l,f),onBlur:pv(c,x),onMouseEnter:pv(d,f),onMouseLeave:pv(u,x),onTouchStart:pv(m,f)}]:[!1,p,{}]}function pv(t,e){return n=>{t&&t(n),n.defaultPrevented||e(n)}}function dhe({page:t,...e}){let{router:n}=rQ(),r=w.useMemo(()=>HY(n.routes,t,n.basename),[n.routes,t,n.basename]);return r?w.createElement(mhe,{page:t,matches:r,...e}):null}function uhe(t){let{manifest:e,routeModules:n}=aQ(),[r,i]=w.useState([]);return w.useEffect(()=>{let s=!1;return rhe(t,e,n).then(o=>{s||i(o)}),()=>{s=!0}},[t,e,n]),r}function mhe({page:t,matches:e,...n}){let r=$c(),{future:i,manifest:s,routeModules:o}=aQ(),{basename:l}=rQ(),{loaderData:c,matches:d}=lhe(),u=w.useMemo(()=>iH(t,e,d,s,r,"data"),[t,e,d,s,r]),m=w.useMemo(()=>iH(t,e,d,s,r,"assets"),[t,e,d,s,r]),p=w.useMemo(()=>{if(t===r.pathname+r.search+r.hash)return[];let v=new Set,g=!1;if(e.forEach(_=>{let C=s.routes[_.route.id];!C||!C.hasLoader||(!u.some(P=>P.route.id===_.route.id)&&_.route.id in c&&o[_.route.id]?.shouldRevalidate||C.hasClientLoader?g=!0:v.add(_.route.id))}),v.size===0)return[];let b=ehe(t,l,i.unstable_trailingSlashAwareDataRequests,"data");return g&&v.size>0&&b.searchParams.set("_routes",e.filter(_=>v.has(_.route.id)).map(_=>_.route.id).join(",")),[b.pathname+b.search]},[l,i.unstable_trailingSlashAwareDataRequests,c,r,s,u,e,t,o]),f=w.useMemo(()=>ahe(m,s),[m,s]),x=uhe(m);return w.createElement(w.Fragment,null,p.map(v=>w.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),f.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 hhe(...t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var phe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{phe&&(window.__reactRouterVersion="7.13.0")}catch{}function fhe({basename:t,children:e,unstable_useTransitions:n,window:r}){let i=w.useRef();i.current==null&&(i.current=Wue({window:r,v5Compat:!0}));let s=i.current,[o,l]=w.useState({action:s.action,location:s.location}),c=w.useCallback(d=>{n===!1?l(d):w.startTransition(()=>l(d))},[n]);return w.useLayoutEffect(()=>s.listen(c),[s,c]),w.createElement(qme,{basename:t,children:e,location:o.location,navigationType:o.action,navigator:s,unstable_useTransitions:n})}var iQ=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,_o=w.forwardRef(function({onClick:e,discover:n="render",prefetch:r="none",relative:i,reloadDocument:s,replace:o,state:l,target:c,to:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},x){let{basename:v,unstable_useTransitions:g}=w.useContext(pl),b=typeof d=="string"&&iQ.test(d),_=GY(d,v);d=_.to;let C=Pme(d,{relative:i}),[P,N,A]=che(r,f),T=xhe(d,{replace:o,state:l,target:c,preventScrollReset:u,relative:i,viewTransition:m,unstable_defaultShouldRevalidate:p,unstable_useTransitions:g});function F(D){e&&e(D),D.defaultPrevented||T(D)}let k=w.createElement("a",{...f,...A,href:_.absoluteURL||C,onClick:_.isExternal||s?e:F,ref:hhe(x,N),target:c,"data-discover":!b&&n==="render"?"true":void 0});return P&&!b?w.createElement(w.Fragment,null,k,w.createElement(dhe,{page:C})):k});_o.displayName="Link";var nx=w.forwardRef(function({"aria-current":e="page",caseSensitive:n=!1,className:r="",end:i=!1,style:s,to:o,viewTransition:l,children:c,...d},u){let m=Dw(o,{relative:d.relative}),p=$c(),f=w.useContext(NP),{navigator:x,basename:v}=w.useContext(pl),g=f!=null&&_he(m)&&l===!0,b=x.encodeLocation?x.encodeLocation(m).pathname:m.pathname,_=p.pathname,C=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;n||(_=_.toLowerCase(),C=C?C.toLowerCase():null,b=b.toLowerCase()),C&&v&&(C=nm(C,v)||C);const P=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let N=_===b||!i&&_.startsWith(b)&&_.charAt(P)==="/",A=C!=null&&(C===b||!i&&C.startsWith(b)&&C.charAt(b.length)==="/"),T={isActive:N,isPending:A,isTransitioning:g},F=N?e:void 0,k;typeof r=="function"?k=r(T):k=[r,N?"active":null,A?"pending":null,g?"transitioning":null].filter(Boolean).join(" ");let D=typeof s=="function"?s(T):s;return w.createElement(_o,{...d,"aria-current":F,className:k,ref:u,style:D,to:o,viewTransition:l},typeof c=="function"?c(T):c)});nx.displayName="NavLink";var ghe=w.forwardRef(({discover:t="render",fetcherKey:e,navigate:n,reloadDocument:r,replace:i,state:s,method:o=Sk,action:l,onSubmit:c,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},x)=>{let{unstable_useTransitions:v}=w.useContext(pl),g=whe(),b=She(l,{relative:d}),_=o.toLowerCase()==="get"?"get":"post",C=typeof l=="string"&&iQ.test(l),P=N=>{if(c&&c(N),N.defaultPrevented)return;N.preventDefault();let A=N.nativeEvent.submitter,T=A?.getAttribute("formmethod")||o,F=()=>g(A||N.currentTarget,{fetcherKey:e,method:T,navigate:n,replace:i,state:s,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p});v&&n!==!1?w.startTransition(()=>F()):F()};return w.createElement("form",{ref:x,method:_,action:b,onSubmit:r?c:P,...f,"data-discover":!C&&t==="render"?"true":void 0})});ghe.displayName="Form";function bhe(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function sQ(t){let e=w.useContext(ry);return ka(e,bhe(t)),e}function xhe(t,{target:e,replace:n,state:r,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l,unstable_useTransitions:c}={}){let d=Do(),u=$c(),m=Dw(t,{relative:s});return w.useCallback(p=>{if(Xme(p,e)){p.preventDefault();let f=n!==void 0?n:O0(u)===O0(m),x=()=>d(t,{replace:f,state:r,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l});c?w.startTransition(()=>x()):x()}},[u,d,m,n,r,e,t,i,s,o,l,c])}function PP(t){rc(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(R3(t)),n=w.useRef(!1),r=$c(),i=w.useMemo(()=>Yme(r.search,n.current?null:e.current),[r.search]),s=Do(),o=w.useCallback((l,c)=>{const d=R3(typeof l=="function"?l(new URLSearchParams(i)):l);n.current=!0,s("?"+d,c)},[s,i]);return[i,o]}var yhe=0,vhe=()=>`__${String(++yhe)}__`;function whe(){let{router:t}=sQ("useSubmit"),{basename:e}=w.useContext(pl),n=zme(),r=t.fetch,i=t.navigate;return w.useCallback(async(s,o={})=>{let{action:l,method:c,encType:d,formData:u,body:m}=Jme(s,e);if(o.navigate===!1){let p=o.fetcherKey||vhe();await r(p,n,o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:u,body:m,formMethod:o.method||c,formEncType:o.encType||d,flushSync:o.flushSync})}else await i(o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:u,body:m,formMethod:o.method||c,formEncType:o.encType||d,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[r,i,e,n])}function She(t,{relative:e}={}){let{basename:n}=w.useContext(pl),r=w.useContext(hc);ka(r,"useFormAction must be used inside a RouteContext");let[i]=r.matches.slice(-1),s={...Dw(t||".",{relative:e})},o=$c();if(t==null){s.search=o.search;let l=new URLSearchParams(s.search),c=l.getAll("index");if(c.some(u=>u==="")){l.delete("index"),c.filter(m=>m).forEach(m=>l.append("index",m));let u=l.toString();s.search=u?`?${u}`:""}}return(!t||t===".")&&i.route.index&&(s.search=s.search?s.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(s.pathname=s.pathname==="/"?n:Wu([n,s.pathname])),O0(s)}function _he(t,{relative:e}={}){let n=w.useContext(KY);ka(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=sQ("useViewTransitionState"),i=Dw(t,{relative:e});if(!n.isTransitioning)return!1;let s=nm(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=nm(n.nextLocation.pathname,r)||n.nextLocation.pathname;return tN(i.pathname,o)!=null||tN(i.pathname,s)!=null}var Ou=MY();const khe=mc(Ou);var yg=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(){}},Nhe={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Che=class{#t=Nhe;#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)}},xf=new Che;function Phe(t){setTimeout(t,0)}var Vf=typeof window>"u"||"Deno"in globalThis;function As(){}function The(t,e){return typeof t=="function"?t(e):t}function L3(t){return typeof t=="number"&&t>=0&&t!==1/0}function oQ(t,e){return Math.max(t+(e||0)-Date.now(),0)}function zh(t,e){return typeof t=="function"?t(e):t}function Ul(t,e){return typeof t=="function"?t(e):t}function sH(t,e){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:l}=t;if(o){if(r){if(e.queryHash!==lO(o,e.options))return!1}else if(!I0(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||i&&i!==e.state.fetchStatus||s&&!s(e))}function oH(t,e){const{exact:n,status:r,predicate:i,mutationKey:s}=t;if(s){if(!e.options.mutationKey)return!1;if(n){if(Gf(e.options.mutationKey)!==Gf(s))return!1}else if(!I0(e.options.mutationKey,s))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function lO(t,e){return(e?.queryKeyHashFn||Gf)(t)}function Gf(t){return JSON.stringify(t,(e,n)=>O3(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function I0(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>I0(t[n],e[n])):!1}var Ahe=Object.prototype.hasOwnProperty;function cO(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=lH(t)&&lH(e);if(!r&&!(O3(t)&&O3(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 d=0;for(let u=0;u<l;u++){const m=r?u:o[u],p=t[m],f=e[m];if(p===f){c[m]=p,(r?u<s:Ahe.call(t,m))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){c[m]=f;continue}const x=cO(p,f,n+1);c[m]=x,x===p&&d++}return s===l&&d===s?t:c}function z0(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 lH(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function O3(t){if(!cH(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!cH(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function cH(t){return Object.prototype.toString.call(t)==="[object Object]"}function jhe(t){return new Promise(e=>{xf.setTimeout(e,t)})}function I3(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?cO(t,e):e}function Mhe(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function Ehe(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var dO=Symbol();function lQ(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===dO?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function uO(t,e){return typeof t=="function"?t(...e):!!t}function Dhe(t,e,n){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??=e(),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),t}var Fhe=class extends yg{#t;#e;#n;constructor(){super(),this.#n=t=>{if(!Vf&&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"}},mO=new Fhe;function z3(){let t,e;const n=new Promise((i,s)=>{t=i,e=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},n.reject=i=>{r({status:"rejected",reason:i}),e(i)},n}var Rhe=Phe;function Lhe(){let t=[],e=0,n=l=>{l()},r=l=>{l()},i=Rhe;const s=l=>{e?t.push(l):i(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&i(()=>{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=>{i=l}}}var $a=Lhe(),Ohe=class extends yg{#t=!0;#e;#n;constructor(){super(),this.#n=t=>{if(!Vf&&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}},nN=new Ohe;function Ihe(t){return Math.min(1e3*2**t,3e4)}function cQ(t){return(t??"online")==="online"?nN.isOnline():!0}var U3=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function dQ(t){let e=!1,n=0,r;const i=z3(),s=()=>i.status!=="pending",o=v=>{if(!s()){const g=new U3(v);p(g),t.onCancel?.(g)}},l=()=>{e=!0},c=()=>{e=!1},d=()=>mO.isFocused()&&(t.networkMode==="always"||nN.isOnline())&&t.canRun(),u=()=>cQ(t.networkMode)&&t.canRun(),m=v=>{s()||(r?.(),i.resolve(v))},p=v=>{s()||(r?.(),i.reject(v))},f=()=>new Promise(v=>{r=g=>{(s()||d())&&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(b){v=Promise.reject(b)}Promise.resolve(v).then(m).catch(b=>{if(s())return;const _=t.retry??(Vf?0:3),C=t.retryDelay??Ihe,P=typeof C=="function"?C(n,b):C,N=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,b);if(e||!N){p(b);return}n++,t.onFail?.(n,b),jhe(P).then(()=>d()?void 0:f()).then(()=>{e?p(b):x()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:c,canStart:u,start:()=>(u()?x():f().then(x),i)}}var uQ=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),L3(this.gcTime)&&(this.#t=xf.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Vf?1/0:300*1e3))}clearGcTimeout(){this.#t&&(xf.clearTimeout(this.#t),this.#t=void 0)}},zhe=class extends uQ{#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=uH(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=uH(this.options);e.data!==void 0&&(this.setState(dH(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){const n=I3(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(As).catch(As):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(t=>Ul(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===dO||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>zh(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:!oQ(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)})},i=()=>{const l=lQ(this.options,e),d=(()=>{const u={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(u),u})();return this.#o=!1,this.options.persister?this.options.persister(l,d,this):l(d)},o=(()=>{const l={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:i};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=dQ({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof U3&&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 U3){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,...mQ(n.data,this.options),fetchMeta:t.meta??null};case"success":const r={...n,...dH(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 i=t.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=e(this.state),$a.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function mQ(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:cQ(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function dH(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function uH(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 hO=class extends yg{constructor(t,e){super(),this.options=e,this.#t=t,this.#s=null,this.#o=z3(),this.bindMethods(),this.setOptions(e)}#t;#e=void 0;#n=void 0;#a=void 0;#r;#i;#o;#s;#p;#u;#m;#c;#d;#l;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),mH(this.#e,this.options)?this.#f():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return B3(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return B3(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 Ul(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&&!z0(this.options,e)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&hH(this.#e,n,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#e!==n||Ul(this.options.enabled,this.#e)!==Ul(e.enabled,this.#e)||zh(this.options.staleTime,this.#e)!==zh(e.staleTime,this.#e))&&this.#g();const i=this.#b();r&&(this.#e!==n||Ul(this.options.enabled,this.#e)!==Ul(e.enabled,this.#e)||i!==this.#l)&&this.#x(i)}getOptimisticResult(t){const e=this.#t.getQueryCache().build(this.#t,t),n=this.createResult(e,t);return Bhe(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.#h.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.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#f(t){this.#S();let e=this.#e.fetch(this.options,t);return t?.throwOnError||(e=e.catch(As)),e}#g(){this.#v();const t=zh(this.options.staleTime,this.#e);if(Vf||this.#a.isStale||!L3(t))return;const n=oQ(this.#a.dataUpdatedAt,t)+1;this.#c=xf.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,!(Vf||Ul(this.options.enabled,this.#e)===!1||!L3(this.#l)||this.#l===0)&&(this.#d=xf.setInterval(()=>{(this.options.refetchIntervalInBackground||mO.isFocused())&&this.#f()},this.#l))}#y(){this.#g(),this.#x(this.#b())}#v(){this.#c&&(xf.clearTimeout(this.#c),this.#c=void 0)}#w(){this.#d&&(xf.clearInterval(this.#d),this.#d=void 0)}createResult(t,e){const n=this.#e,r=this.options,i=this.#a,s=this.#r,o=this.#i,c=t!==n?t.state:this.#n,{state:d}=t;let u={...d},m=!1,p;if(e._optimisticResults){const F=this.hasListeners(),k=!F&&mH(t,e),D=F&&hH(t,n,e,r);(k||D)&&(u={...u,...mQ(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:x,status:v}=u;p=u.data;let g=!1;if(e.placeholderData!==void 0&&p===void 0&&v==="pending"){let F;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(F=i.data,g=!0):F=typeof e.placeholderData=="function"?e.placeholderData(this.#m?.state.data,this.#m):e.placeholderData,F!==void 0&&(v="success",p=I3(i?.data,F,e),m=!0)}if(e.select&&p!==void 0&&!g)if(i&&p===s?.data&&e.select===this.#p)p=this.#u;else try{this.#p=e.select,p=e.select(p),p=I3(i?.data,p,e),this.#u=p,this.#s=null}catch(F){this.#s=F}this.#s&&(f=this.#s,p=this.#u,x=Date.now(),v="error");const b=u.fetchStatus==="fetching",_=v==="pending",C=v==="error",P=_&&b,N=p!==void 0,T={status:v,fetchStatus:u.fetchStatus,isPending:_,isSuccess:v==="success",isError:C,isInitialLoading:P,isLoading:P,data:p,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:x,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:b,isRefetching:b&&!_,isLoadingError:C&&!N,isPaused:u.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:C&&N,isStale:pO(t,e),refetch:this.refetch,promise:this.#o,isEnabled:Ul(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const F=T.data!==void 0,k=T.status==="error"&&!F,D=X=>{k?X.reject(T.error):F&&X.resolve(T.data)},H=()=>{const X=this.#o=T.promise=z3();D(X)},z=this.#o;switch(z.status){case"pending":t.queryHash===n.queryHash&&D(z);break;case"fulfilled":(k||T.data!==z.value)&&H();break;case"rejected":(!k||T.error!==z.reason)&&H();break}}return T}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.#m=this.#e),z0(e,t))return;this.#a=e;const n=()=>{if(!t)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#h.size)return!0;const s=new Set(i??this.#h);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){$a.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#a)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Uhe(t,e){return Ul(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function mH(t,e){return Uhe(t,e)||t.state.data!==void 0&&B3(t,e,e.refetchOnMount)}function B3(t,e,n){if(Ul(e.enabled,t)!==!1&&zh(e.staleTime,t)!=="static"){const r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&pO(t,e)}return!1}function hH(t,e,n,r){return(t!==e||Ul(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&pO(t,n)}function pO(t,e){return Ul(e.enabled,t)!==!1&&t.isStaleByTime(zh(e.staleTime,t))}function Bhe(t,e){return!z0(t.getCurrentResult(),e)}function pH(t){return{onFetch:(e,n)=>{const r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,s=e.state.data?.pages||[],o=e.state.data?.pageParams||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let u=!1;const m=x=>{Dhe(x,()=>e.signal,()=>u=!0)},p=lQ(e.options,e.fetchOptions),f=async(x,v,g)=>{if(u)return Promise.reject();if(v==null&&x.pages.length)return Promise.resolve(x);const _=(()=>{const A={client:e.client,queryKey:e.queryKey,pageParam:v,direction:g?"backward":"forward",meta:e.options.meta};return m(A),A})(),C=await p(_),{maxPages:P}=e.options,N=g?Ehe:Mhe;return{pages:N(x.pages,C,P),pageParams:N(x.pageParams,v,P)}};if(i&&s.length){const x=i==="backward",v=x?Hhe:fH,g={pages:s,pageParams:o},b=v(r,g);l=await f(g,b,x)}else{const x=t??s.length;do{const v=c===0?o[0]??r.initialPageParam:fH(r,l);if(c>0&&v==null)break;l=await f(l,v),c++}while(c<x)}return l};e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=d}}}function fH(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 Hhe(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}var qhe=class extends uQ{#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||hQ(),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=dQ({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",i=!this.#a.canStart();try{if(r)e();else{this.#r({type:"pending",variables:t,isPaused:i}),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:i})}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),$a.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function hQ(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var $he=class extends yg{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 qhe({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=D_(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=D_(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=D_(t);if(typeof e=="string"){const r=this.#e.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){const e=D_(t);return typeof e=="string"?this.#e.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){$a.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=>oH(e,n))}findAll(t={}){return this.getAll().filter(e=>oH(t,e))}notify(t){$a.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){const t=this.getAll().filter(e=>e.state.isPaused);return $a.batch(()=>Promise.all(t.map(e=>e.continue().catch(As))))}};function D_(t){return t.options.scope?.id}var Vhe=class extends yg{#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),z0(this.options,n)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&Gf(n.mutationKey)!==Gf(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??hQ();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){$a.batch(()=>{if(this.#a&&this.hasListeners()){const n=this.#e.variables,r=this.#e.context,i={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,n,r,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(e.data,null,n,r,i)}catch(s){Promise.reject(s)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,n,r,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(void 0,e.error,n,r,i)}catch(s){Promise.reject(s)}}}this.listeners.forEach(n=>{n(this.#e)})})}};function gH(t,e){const n=new Set(e);return t.filter(r=>!n.has(r))}function Ghe(t,e,n){const r=t.slice(0);return r[e]=n,r}var Whe=class extends yg{#t;#e;#n;#a;#r;#i;#o;#s;#p;#u=[];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,$a.batch(()=>{const n=this.#r,r=this.#d(this.#n);r.forEach(u=>u.observer.setOptions(u.defaultedQueryOptions));const i=r.map(u=>u.observer),s=i.map(u=>u.getCurrentResult()),o=n.length!==i.length,l=i.some((u,m)=>u!==n[m]),c=o||l,d=c?!0:s.some((u,m)=>{const p=this.#e[m];return!p||!z0(u,p)});!c&&!d||(c&&(this.#u=r,this.#r=i),this.#e=s,this.hasListeners()&&(c&&(gH(n,i).forEach(u=>{u.destroy()}),gH(i,n).forEach(u=>{u.subscribe(m=>{this.#l(u,m)})})),this.#h()))})}getCurrentResult(){return this.#e}getQueries(){return this.#r.map(t=>t.getCurrentQuery())}getObservers(){return this.#r}getOptimisticResult(t,e){const n=this.#d(t),r=n.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions)),i=n.map(s=>s.defaultedQueryOptions.queryHash);return[r,s=>this.#c(s??r,e,i),()=>this.#m(r,n)]}#m(t,e){return e.map((n,r)=>{const i=t[r];return n.defaultedQueryOptions.notifyOnChangeProps?i:n.observer.trackResult(i,s=>{e.forEach(o=>{o.observer.trackProp(s)})})})}#c(t,e,n){if(e){const r=this.#p,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((s,o)=>s!==r[o]));return(!this.#i||this.#e!==this.#s||i||e!==this.#o)&&(this.#o=e,this.#s=this.#e,n!==void 0&&(this.#p=n),this.#i=cO(this.#i,e(t))),this.#i}return t}#d(t){const e=new Map;this.#r.forEach(r=>{const i=r.options.queryHash;if(!i)return;const s=e.get(i);s?s.push(r):e.set(i,[r])});const n=[];return t.forEach(r=>{const i=this.#t.defaultQueryOptions(r),o=e.get(i.queryHash)?.shift()??new hO(this.#t,i);n.push({defaultedQueryOptions:i,observer:o})}),n}#l(t,e){const n=this.#r.indexOf(t);n!==-1&&(this.#e=Ghe(this.#e,n,e),this.#h())}#h(){if(this.hasListeners()){const t=this.#i,e=this.#m(this.#e,this.#u),n=this.#c(e,this.#a?.combine);t!==n&&$a.batch(()=>{this.listeners.forEach(r=>{r(this.#e)})})}}},Khe=class extends yg{constructor(t={}){super(),this.config=t,this.#t=new Map}#t;build(t,e,n){const r=e.queryKey,i=e.queryHash??lO(r,e);let s=this.get(i);return s||(s=new zhe({client:t,queryKey:r,queryHash:i,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(){$a.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=>sH(e,n))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter(n=>sH(t,n)):e}notify(t){$a.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){$a.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){$a.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Xhe=class{#t;#e;#n;#a;#r;#i;#o;#s;constructor(t={}){this.#t=t.queryCache||new Khe,this.#e=t.mutationCache||new $he,this.#n=t.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=mO.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=nN.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(zh(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=The(e,s);if(o!==void 0)return this.#t.build(this,r).setData(o,{...n,manual:!0})}setQueriesData(t,e,n){return $a.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;$a.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=this.#t;return $a.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=$a.batch(()=>this.#t.findAll(t).map(i=>i.cancel(n)));return Promise.all(r).then(As).catch(As)}invalidateQueries(t,e={}){return $a.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=$a.batch(()=>this.#t.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(As)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(As)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=this.#t.build(this,e);return n.isStaleByTime(zh(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(As).catch(As)}fetchInfiniteQuery(t){return t.behavior=pH(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(As).catch(As)}ensureInfiniteQueryData(t){return t.behavior=pH(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return nN.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(Gf(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#a.values()],n={};return e.forEach(r=>{I0(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){this.#r.set(Gf(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#r.values()],n={};return e.forEach(r=>{I0(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=lO(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===dO&&(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()}},pQ=w.createContext(void 0),sn=t=>{const e=w.useContext(pQ);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},Yhe=({client:t,children:e})=>(w.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),a.jsx(pQ.Provider,{value:t,children:e})),fQ=w.createContext(!1),gQ=()=>w.useContext(fQ);fQ.Provider;function Qhe(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var Zhe=w.createContext(Qhe()),bQ=()=>w.useContext(Zhe),xQ=(t,e,n)=>{const r=n?.state.error&&typeof t.throwOnError=="function"?uO(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},yQ=t=>{w.useEffect(()=>{t.clearReset()},[t])},vQ=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||uO(n,[t.error,r])),wQ=t=>{if(t.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},SQ=(t,e)=>t.isLoading&&t.isFetching&&!e,H3=(t,e)=>t?.suspense&&e.isPending,rN=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function fp({queries:t,...e},n){const r=sn(),i=gQ(),s=bQ(),o=w.useMemo(()=>t.map(v=>{const g=r.defaultQueryOptions(v);return g._optimisticResults=i?"isRestoring":"optimistic",g}),[t,r,i]);o.forEach(v=>{wQ(v);const g=r.getQueryCache().get(v.queryHash);xQ(v,s,g)}),yQ(s);const[l]=w.useState(()=>new Whe(r,o,e)),[c,d,u]=l.getOptimisticResult(o,e.combine),m=!i&&e.subscribed!==!1;w.useSyncExternalStore(w.useCallback(v=>m?l.subscribe($a.batchCalls(v)):As,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),w.useEffect(()=>{l.setQueries(o,e)},[o,e,l]);const f=c.some((v,g)=>H3(o[g],v))?c.flatMap((v,g)=>{const b=o[g];if(b){const _=new hO(r,b);if(H3(b,v))return rN(b,_,s);SQ(v,i)&&rN(b,_,s)}return[]}):[];if(f.length>0)throw Promise.all(f);const x=c.find((v,g)=>{const b=o[g];return b&&vQ({result:v,errorResetBoundary:s,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(x?.error)throw x.error;return d(u())}function Jhe(t,e,n){const r=gQ(),i=bQ(),s=sn(),o=s.defaultQueryOptions(t);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=s.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",wQ(o),xQ(o,i,l),yQ(i);const c=!s.getQueryCache().get(o.queryHash),[d]=w.useState(()=>new e(s,o)),u=d.getOptimisticResult(o),m=!r&&t.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(p=>{const f=m?d.subscribe($a.batchCalls(p)):As;return d.updateResult(),f},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),w.useEffect(()=>{d.setOptions(o)},[o,d]),H3(o,u))throw rN(o,d,i);if(vQ({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw u.error;return s.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!Vf&&SQ(u,r)&&(c?rN(o,d,i):l?.promise)?.catch(As).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?u:d.trackResult(u)}function Qe(t,e){return Jhe(t,hO)}function it(t,e){const n=sn(),[r]=w.useState(()=>new Vhe(n,t));w.useEffect(()=>{r.setOptions(t)},[r,t]);const i=w.useSyncExternalStore(w.useCallback(o=>r.subscribe($a.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),s=w.useCallback((o,l)=>{r.mutate(o,l).catch(As)},[r]);if(i.error&&uO(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:s,mutateAsync:i.mutate}}const epe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),tpe=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase()),bH=t=>{const e=tpe(t);return e.charAt(0).toUpperCase()+e.slice(1)},_Q=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim(),npe=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var rpe={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 ape=w.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i="",children:s,iconNode:o,...l},c)=>w.createElement("svg",{ref:c,...rpe,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:_Q("lucide",i),...!s&&!npe(l)&&{"aria-hidden":"true"},...l},[...o.map(([d,u])=>w.createElement(d,u)),...Array.isArray(s)?s:[s]]));const at=(t,e)=>{const n=w.forwardRef(({className:r,...i},s)=>w.createElement(ape,{ref:s,iconNode:e,className:_Q(`lucide-${epe(bH(t))}`,`lucide-${t}`,r),...i}));return n.displayName=bH(t),n};const ipe=[["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"}]],spe=at("air-vent",ipe);const ope=[["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"}]],Qs=at("archive",ope);const lpe=[["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"}]],cpe=at("arrow-down-wide-narrow",lpe);const dpe=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Cx=at("arrow-down",dpe);const upe=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],kQ=at("arrow-left",upe);const mpe=[["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"}]],q3=at("arrow-right-left",mpe);const hpe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],$3=at("arrow-right",hpe);const ppe=[["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"}]],fO=at("arrow-up-down",ppe);const fpe=[["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"}]],gpe=at("arrow-up-narrow-wide",fpe);const bpe=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Wf=at("arrow-up",bpe);const xpe=[["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"}]],ype=at("beaker",xpe);const vpe=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],wpe=at("bell-off",vpe);const Spe=[["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"}]],Uh=at("bell",Spe);const _pe=[["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"}]],kpe=at("bold",_pe);const Npe=[["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"}]],Cpe=at("book",Npe);const Ppe=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Tpe=at("bookmark",Ppe);const Ape=[["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"}]],mi=at("box",Ape);const jpe=[["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"}]],NQ=at("briefcase",jpe);const Mpe=[["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"}]],Px=at("bug",Mpe);const Epe=[["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"}]],gO=at("cable",Epe);const Dpe=[["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"}]],Fpe=at("calculator",Dpe);const Rpe=[["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"}]],Lpe=at("calendar-days",Rpe);const Ope=[["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M21 12.598V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8.5",key:"1glfrc"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]],Ipe=at("calendar-plus",Ope);const zpe=[["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"}]],Yr=at("calendar",zpe);const Upe=[["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"}]],Tx=at("camera",Upe);const Bpe=[["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"}]],Hpe=at("chart-column",Bpe);const qpe=[["path",{d:"M6 5h12",key:"fvfigv"}],["path",{d:"M4 12h10",key:"oujl3d"}],["path",{d:"M12 19h8",key:"baeox8"}]],$pe=at("chart-no-axes-gantt",qpe);const Vpe=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Rr=at("check",Vpe);const Gpe=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Un=at("chevron-down",Gpe);const Wpe=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Ka=at("chevron-right",Wpe);const Kpe=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],dl=at("chevron-left",Kpe);const Xpe=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ac=at("chevron-up",Xpe);const Ype=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],bO=at("chevrons-left",Ype);const Qpe=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],xO=at("chevrons-right",Qpe);const Zpe=[["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"}]],Wa=at("circle-alert",Zpe);const Jpe=[["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"}]],gM=at("circle-arrow-up",Jpe);const efe=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],xr=at("circle-check-big",efe);const tfe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],nl=at("circle-check",tfe);const nfe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],rfe=at("circle-dot",nfe);const afe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],ife=at("circle-stop",afe);const sfe=[["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"}]],Na=at("circle-x",sfe);const ofe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],U0=at("circle",ofe);const lfe=[["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"}]],cfe=at("clipboard-list",lfe);const dfe=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Qn=at("clock",dfe);const ufe=[["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"}]],mfe=at("cloud-off",ufe);const hfe=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],sy=at("cloud",hfe);const pfe=[["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"}]],ffe=at("code-xml",pfe);const gfe=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],oy=at("code",gfe);const bfe=[["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"}]],xfe=at("coffee",bfe);const yfe=[["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"}]],vfe=at("coins",yfe);const wfe=[["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"}]],Sfe=at("cog",wfe);const _fe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],kfe=at("columns-2",_fe);const Nfe=[["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"}]],Cfe=at("compass",Nfe);const Pfe=[["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"}]],Fs=at("copy",Pfe);const Tfe=[["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"}]],Kv=at("cpu",Tfe);const Afe=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]],jfe=at("cylinder",Afe);const Mfe=[["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"}]],Kl=at("database",Mfe);const Efe=[["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"}]],Dfe=at("disc-3",Efe);const Ffe=[["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"}]],aN=at("dollar-sign",Ffe);const Rfe=[["path",{d:"M10 12h.01",key:"1kxr2c"}],["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}]],Lfe=at("door-closed",Rfe);const Ofe=[["path",{d:"M11 20H2",key:"nlcfvz"}],["path",{d:"M11 4.562v16.157a1 1 0 0 0 1.242.97L19 20V5.562a2 2 0 0 0-1.515-1.94l-4-1A2 2 0 0 0 11 4.561z",key:"au4z13"}],["path",{d:"M11 4H8a2 2 0 0 0-2 2v14",key:"74r1mk"}],["path",{d:"M14 12h.01",key:"1jfl7z"}],["path",{d:"M22 20h-3",key:"vhrsz"}]],Ife=at("door-open",Ofe);const zfe=[["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"}]],ca=at("download",zfe);const Ufe=[["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"}]],TP=at("droplet",Ufe);const Bfe=[["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"}]],yO=at("droplets",Bfe);const Hfe=[["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"}]],Bh=at("ellipsis-vertical",Hfe);const qfe=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]],bM=at("equal",qfe);const $fe=[["path",{d:"M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21",key:"g5wo59"}],["path",{d:"m5.082 11.09 8.828 8.828",key:"1wx5vj"}]],Vfe=at("eraser",$fe);const Gfe=[["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"}]],na=at("external-link",Gfe);const Wfe=[["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"}]],vg=at("eye-off",Wfe);const Kfe=[["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"}]],ul=at("eye",Kfe);const Xfe=[["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"}]],CQ=at("fan",Xfe);const Yfe=[["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"}]],Hh=at("file-box",Yfe);const Qfe=[["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"}]],iN=at("file-code",Qfe);const Zfe=[["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"}]],Jfe=at("file-exclamation-point",Zfe);const ege=[["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"}]],sN=at("file-spreadsheet",ege);const tge=[["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=at("file-text",tge);const nge=[["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"}]],AP=at("file",nge);const rge=[["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"}]],qh=at("film",rge);const age=[["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"}]],Au=at("flame",age);const ige=[["circle",{cx:"15",cy:"19",r:"2",key:"u2pros"}],["path",{d:"M20.9 19.8A2 2 0 0 0 22 18V8a2 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 2h5.1",key:"1jj40k"}],["path",{d:"M15 11v-1",key:"cntcp"}],["path",{d:"M15 17v-2",key:"1279jj"}]],sge=at("folder-archive",ige);const oge=[["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"}]],Es=at("folder-kanban",oge);const lge=[["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"}]],Uc=at("folder-open",lge);const cge=[["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"}]],dge=at("folder-plus",cge);const uge=[["path",{d:"M2 9.35V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"y8kt7d"}],["path",{d:"m8 16 3-3-3-3",key:"rlqrt1"}]],oN=at("folder-symlink",uge);const mge=[["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"}]],hge=at("folder-tree",mge);const pge=[["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"}]],PQ=at("folder",pge);const fge=[["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"}]],gge=at("fullscreen",fge);const bge=[["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"}]],jP=at("funnel",bge);const xge=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Fw=at("gauge",xge);const yge=[["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"}]],vge=at("gift",yge);const wge=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],TQ=at("git-branch",wge);const Sge=[["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"}]],dx=at("git-compare",Sge);const _ge=[["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"}]],V3=at("github",_ge);const kge=[["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"}]],rl=at("globe",kge);const Nge=[["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"}]],$h=at("grip-vertical",Nge);const Cge=[["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"}]],Pge=at("group",Cge);const Tge=[["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"}]],AQ=at("hand",Tge);const Age=[["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"}]],rp=at("hard-drive",Age);const jge=[["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"}]],Mge=at("hash",jge);const Ege=[["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"}]],Dge=at("headphones",Ege);const Fge=[["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"}]],Rge=at("heart",Fge);const Lge=[["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"}]],B0=at("history",Lge);const Oge=[["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"}]],Rw=at("house",Oge);const Ige=[["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"}]],rm=at("image",Ige);const zge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],fs=at("info",zge);const Uge=[["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"}]],Bge=at("italic",Uge);const Hge=[["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"}]],Ws=at("key",Hge);const qge=[["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"}]],G3=at("keyboard",qge);const $ge=[["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"}]],aa=at("layers",$ge);const Vge=[["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"}]],Lw=at("layout-grid",Vge);const Gge=[["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"}]],Wge=at("link-2-off",Gge);const Kge=[["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"}]],Ku=at("link-2",Kge);const Xge=[["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"}]],ly=at("link",Xge);const Yge=[["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"}]],lN=at("list-ordered",Yge);const Qge=[["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"}]],W3=at("list-todo",Qge);const Zge=[["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"}]],Ow=at("list",Zge);const Jge=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],dt=at("loader-circle",Jge);const ebe=[["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"}]],u0=at("lock-open",ebe);const tbe=[["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"}]],pd=at("lock",tbe);const nbe=[["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"}]],xH=at("log-in",nbe);const rbe=[["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"}]],K3=at("log-out",rbe);const abe=[["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"}]],am=at("mail",abe);const ibe=[["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"}]],sbe=at("map",ibe);const obe=[["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"}]],MP=at("maximize-2",obe);const lbe=[["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"}]],cbe=at("maximize",lbe);const dbe=[["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"}]],ube=at("memory-stick",dbe);const mbe=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],hbe=at("menu",mbe);const pbe=[["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"}]],vO=at("minimize-2",pbe);const fbe=[["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"}]],jQ=at("minimize",fbe);const gbe=[["path",{d:"M5 12h14",key:"1ays0h"}]],cN=at("minus",gbe);const bbe=[["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"}]],wO=at("monitor",bbe);const xbe=[["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"}]],dN=at("moon",xbe);const ybe=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],vbe=at("move-right",ybe);const wbe=[["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"}]],X3=at("music",wbe);const Sbe=[["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"}]],ja=at("package",Sbe);const _be=[["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"}]],Iw=at("palette",_be);const kbe=[["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"}]],zw=at("pause",kbe);const Nbe=[["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"}]],Kf=at("pen-line",Nbe);const Cbe=[["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"}]],Iu=at("pen",Cbe);const Pbe=[["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"}]],ai=at("pencil",Pbe);const Tbe=[["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"}]],Abe=at("phone",Tbe);const jbe=[["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"}]],$i=at("play",jbe);const Mbe=[["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"}]],Ql=at("plug",Mbe);const Ebe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],or=at("plus",Ebe);const Dbe=[["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"}]],Uw=at("power-off",Dbe);const Fbe=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Ud=at("power",Fbe);const Rbe=[["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"}]],Ar=at("printer",Rbe);const Lbe=[["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"}]],MQ=at("qr-code",Lbe);const Obe=[["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"}]],SO=at("radio",Obe);const Ibe=[["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"}]],cr=at("refresh-cw",Ibe);const zbe=[["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"}]],eo=at("rotate-ccw",zbe);const Ube=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],H0=at("rotate-cw",Ube);const Bbe=[["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"}]],Hbe=at("ruler",Bbe);const qbe=[["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"}]],gs=at("save",qbe);const $be=[["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"}]],EQ=at("scale",$be);const Vbe=[["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:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]],DQ=at("scan-eye",Vbe);const Gbe=[["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"}]],uN=at("scan-search",Gbe);const Wbe=[["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"}]],Kbe=at("scissors",Wbe);const Xbe=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],kr=at("search",Xbe);const Ybe=[["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"}]],Bw=at("send",Ybe);const Qbe=[["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"}]],sf=at("server",Qbe);const Zbe=[["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"}]],jd=at("settings-2",Zbe);const Jbe=[["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"}]],Hw=at("settings",Jbe);const exe=[["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"}]],txe=at("shield-alert",exe);const nxe=[["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:"m9 12 2 2 4-4",key:"dzmm74"}]],yH=at("shield-check",nxe);const rxe=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]],vH=at("shield-off",rxe);const axe=[["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"}]],Du=at("shield",axe);const ixe=[["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"}]],FQ=at("shopping-cart",ixe);const sxe=[["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"}]],RQ=at("signal",sxe);const oxe=[["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"}]],lxe=at("skip-back",oxe);const cxe=[["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"}]],EP=at("skip-forward",cxe);const dxe=[["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"}]],wH=at("sliders-vertical",dxe);const uxe=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Y3=at("smartphone",uxe);const mxe=[["path",{d:"M2 13a6 6 0 1 0 12 0 4 4 0 1 0-8 0 2 2 0 0 0 4 0",key:"hneq2s"}],["circle",{cx:"10",cy:"13",r:"8",key:"194lz3"}],["path",{d:"M2 21h12c4.4 0 8-3.6 8-8V7a2 2 0 1 0-4 0v6",key:"ixqyt7"}],["path",{d:"M18 3 19.1 5.2",key:"9tjm43"}],["path",{d:"M22 3 20.9 5.2",key:"j3odrs"}]],hxe=at("snail",mxe);const pxe=[["path",{d:"m10 20-1.25-2.5L6 18",key:"18frcb"}],["path",{d:"M10 4 8.75 6.5 6 6",key:"7mghy3"}],["path",{d:"m14 20 1.25-2.5L18 18",key:"1chtki"}],["path",{d:"m14 4 1.25 2.5L18 6",key:"1b4wsy"}],["path",{d:"m17 21-3-6h-4",key:"15hhxa"}],["path",{d:"m17 3-3 6 1.5 3",key:"11697g"}],["path",{d:"M2 12h6.5L10 9",key:"kv9z4n"}],["path",{d:"m20 10-1.5 2 1.5 2",key:"1swlpi"}],["path",{d:"M22 12h-6.5L14 15",key:"1mxi28"}],["path",{d:"m4 10 1.5 2L4 14",key:"k9enpj"}],["path",{d:"m7 21 3-6-1.5-3",key:"j8hb9u"}],["path",{d:"m7 3 3 6h4",key:"1otusx"}]],SH=at("snowflake",pxe);const fxe=[["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"}]],Ax=at("sparkles",fxe);const gxe=[["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"}]],xs=at("square-check-big",gxe);const bxe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]],xxe=at("square-minus",bxe);const yxe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],to=at("square",yxe);const vxe=[["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"}]],Xf=at("star",vxe);const wxe=[["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"}]],LQ=at("sticky-note",wxe);const Sxe=[["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"}]],_H=at("sun",Sxe);const _xe=[["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"}]],kxe=at("table-properties",_xe);const Nxe=[["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"}]],im=at("tag",Nxe);const Cxe=[["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"}]],OQ=at("target",Cxe);const Pxe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],IQ=at("terminal",Pxe);const Txe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],Axe=at("text-align-center",Txe);const jxe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],Mxe=at("text-align-end",jxe);const Exe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],Dxe=at("text-align-start",Exe);const Fxe=[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]],qw=at("thermometer",Fxe);const Rxe=[["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"}]],vd=at("timer",Rxe);const Lxe=[["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"}]],rn=at("trash-2",Lxe);const Oxe=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],_O=at("trending-down",Oxe);const Ixe=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Q3=at("trending-up",Ixe);const zxe=[["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"}]],Rn=at("triangle-alert",zxe);const Uxe=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],Bxe=at("underline",Uxe);const Hxe=[["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"}]],ap=at("unlink",Hxe);const qxe=[["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"}]],Ma=at("upload",qxe);const $xe=[["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"}]],sm=at("user",$xe);const Vxe=[["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"}]],Fu=at("users",Vxe);const Gxe=[["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"}]],kO=at("video",Gxe);const Wxe=[["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"}]],Kxe=at("volume-2",Wxe);const Xxe=[["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"}]],Yxe=at("volume-x",Xxe);const Qxe=[["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"}]],zQ=at("wand-sparkles",Qxe);const Zxe=[["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"}]],UQ=at("weight",Zxe);const Jxe=[["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"}]],Md=at("wifi-off",Jxe);const eye=[["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"}]],Vh=at("wifi",eye);const tye=[["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"}]],BQ=at("wind",tye);const nye=[["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"}]],Yf=at("wrench",nye);const rye=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Bt=at("x",rye);const aye=[["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"}]],NO=at("zoom-in",aye);const iye=[["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"}]],ic=at("zap",iye);const sye=[["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"}]],CO=at("zoom-out",sye),Cn="/api/v1";let Tn=sessionStorage.getItem("auth_token")??localStorage.getItem("auth_token");function mh(t,e=!1){Tn=t,t?(sessionStorage.setItem("auth_token",t),e&&localStorage.setItem("auth_token",t)):(sessionStorage.removeItem("auth_token"),localStorage.removeItem("auth_token"))}function om(){return Tn}let mN=null;function kH(t){mN=t}function oye(){return mN}function za(t){if(!mN)return t;const e=t.includes("?")?"&":"?";return`${t}${e}token=${encodeURIComponent(mN)}`}function of(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 De(t,e={}){const n={"Content-Type":"application/json",...e.headers};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}${t}`,{...e,cache:"no-store",credentials:"include",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(d=>l.includes(d))&&mh(null),new Error(l)}const i=r.headers.get("content-length");if(!(r.status===204||i==="0"))return await r.json()}const me={getAuthStatus:()=>De("/auth/status"),setupAuth:t=>De("/auth/setup",{method:"POST",body:JSON.stringify(t)}),login:t=>De("/auth/login",{method:"POST",body:JSON.stringify(t)}),logout:()=>De("/auth/logout",{method:"POST"}),getCurrentUser:()=>De("/auth/me"),disableAuth:()=>De("/auth/disable",{method:"POST"}),testSMTP:t=>De("/auth/smtp/test",{method:"POST",body:JSON.stringify(t)}),getSMTPSettings:()=>De("/auth/smtp"),saveSMTPSettings:t=>De("/auth/smtp",{method:"POST",body:JSON.stringify(t)}),enableAdvancedAuth:()=>De("/auth/advanced-auth/enable",{method:"POST"}),disableAdvancedAuth:()=>De("/auth/advanced-auth/disable",{method:"POST"}),getAdvancedAuthStatus:()=>De("/auth/advanced-auth/status"),getLDAPStatus:()=>De("/auth/ldap/status"),testLDAP:()=>De("/auth/ldap/test",{method:"POST"}),forgotPassword:t=>De("/auth/forgot-password",{method:"POST",body:JSON.stringify(t)}),forgotPasswordConfirm:(t,e)=>De("/auth/forgot-password/confirm",{method:"POST",body:JSON.stringify({token:t,new_password:e})}),resetUserPassword:t=>De("/auth/reset-password",{method:"POST",body:JSON.stringify(t)}),get2FAStatus:()=>De("/auth/2fa/status"),setupTOTP:()=>De("/auth/2fa/totp/setup",{method:"POST"}),enableTOTP:t=>De("/auth/2fa/totp/enable",{method:"POST",body:JSON.stringify({code:t})}),disableTOTP:t=>De("/auth/2fa/totp/disable",{method:"POST",body:JSON.stringify({code:t})}),regenerateBackupCodes:t=>De("/auth/2fa/totp/regenerate-backup-codes",{method:"POST",body:JSON.stringify({code:t})}),enableEmailOTP:()=>De("/auth/2fa/email/enable",{method:"POST"}),confirmEnableEmailOTP:(t,e)=>De("/auth/2fa/email/enable/confirm",{method:"POST",body:JSON.stringify({setup_token:t,code:e})}),disableEmailOTP:t=>De("/auth/2fa/email/disable",{method:"POST",body:JSON.stringify({password:t})}),sendEmailOTP:t=>De("/auth/2fa/email/send",{method:"POST",body:JSON.stringify({pre_auth_token:t})}),verify2FA:t=>De("/auth/2fa/verify",{method:"POST",body:JSON.stringify(t)}),admin2FADisable:t=>De(`/auth/2fa/admin/${t}`,{method:"DELETE"}),getOIDCProviders:()=>De("/auth/oidc/providers"),getOIDCProvidersAll:()=>De("/auth/oidc/providers/all"),createOIDCProvider:t=>De("/auth/oidc/providers",{method:"POST",body:JSON.stringify(t)}),updateOIDCProvider:(t,e)=>De(`/auth/oidc/providers/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteOIDCProvider:t=>De(`/auth/oidc/providers/${t}`,{method:"DELETE"}),getOIDCAuthorizeUrl:t=>De(`/auth/oidc/authorize/${t}`),exchangeOIDCToken:t=>De("/auth/oidc/exchange",{method:"POST",body:JSON.stringify({oidc_token:t})}),getOIDCLinks:()=>De("/auth/oidc/links"),deleteOIDCLink:t=>De(`/auth/oidc/links/${t}`,{method:"DELETE"}),getUsers:()=>De("/users/"),getUser:t=>De(`/users/${t}`),createUser:t=>De("/users/",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>De(`/users/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:(t,e=!1)=>De(`/users/${t}?delete_items=${e}`,{method:"DELETE"}),getUserItemsCount:t=>De(`/users/${t}/items-count`),changePassword:(t,e)=>De("/users/me/change-password",{method:"POST",body:JSON.stringify({current_password:t,new_password:e})}),getUserEmailPreferences:()=>De("/user-notifications/preferences"),updateUserEmailPreferences:t=>De("/user-notifications/preferences",{method:"PUT",body:JSON.stringify(t)}),getPermissions:()=>De("/groups/permissions"),getGroups:()=>De("/groups/"),getGroup:t=>De(`/groups/${t}`),createGroup:t=>De("/groups/",{method:"POST",body:JSON.stringify(t)}),updateGroup:(t,e)=>De(`/groups/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteGroup:t=>De(`/groups/${t}`,{method:"DELETE"}),addUserToGroup:(t,e)=>De(`/groups/${t}/users/${e}`,{method:"POST"}),removeUserFromGroup:(t,e)=>De(`/groups/${t}/users/${e}`,{method:"DELETE"}),getPrinters:()=>De("/printers/"),getPrinter:t=>De(`/printers/${t}`),createPrinter:t=>De("/printers/",{method:"POST",body:JSON.stringify(t)}),updatePrinter:(t,e)=>De(`/printers/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deletePrinter:(t,e=!0)=>De(`/printers/${t}?delete_archives=${e}`,{method:"DELETE"}),getDeveloperModeWarnings:()=>De("/printers/developer-mode-warnings"),getAvailableFilaments:(t,e)=>{const n=new URLSearchParams({model:t});return e&&n.set("location",e),De(`/printers/available-filaments?${n}`)},getPrinterStatus:t=>De(`/printers/${t}/status`),refreshPrinterStatus:t=>De(`/printers/${t}/refresh-status`,{method:"POST"}),connectPrinter:t=>De(`/printers/${t}/connect`,{method:"POST"}),disconnectPrinter:t=>De(`/printers/${t}/disconnect`,{method:"POST"}),testExternalCamera:(t,e,n)=>De(`/printers/${t}/camera/external/test?url=${encodeURIComponent(e)}&camera_type=${encodeURIComponent(n)}`,{method:"POST"}),stopPrint:t=>De(`/printers/${t}/print/stop`,{method:"POST"}),pausePrint:t=>De(`/printers/${t}/print/pause`,{method:"POST"}),resumePrint:t=>De(`/printers/${t}/print/resume`,{method:"POST"}),clearPlate:t=>De(`/printers/${t}/clear-plate`,{method:"POST"}),getCurrentPrintUser:t=>De(`/printers/${t}/current-print-user`),setPrintSpeed:(t,e)=>De(`/printers/${t}/print-speed?mode=${e}`,{method:"POST"}),setAirductMode:(t,e)=>De(`/printers/${t}/airduct-mode?mode=${e}`,{method:"POST"}),setChamberLight:(t,e)=>De(`/printers/${t}/chamber-light?on=${e}`,{method:"POST"}),startDrying:(t,e,n,r,i="",s=!1)=>De(`/printers/${t}/drying/start?ams_id=${e}&temp=${n}&duration=${r}&filament=${encodeURIComponent(i)}&rotate_tray=${s}`,{method:"POST"}),stopDrying:(t,e)=>De(`/printers/${t}/drying/stop?ams_id=${e}`,{method:"POST"}),getPrintableObjects:t=>De(`/printers/${t}/print/objects`),skipObjects:(t,e)=>De(`/printers/${t}/print/skip-objects`,{method:"POST",body:JSON.stringify(e)}),clearHMSErrors:t=>De(`/printers/${t}/hms/clear`,{method:"POST"}),refreshAmsSlot:(t,e,n)=>De(`/printers/${t}/ams/${e}/slot/${n}/refresh`,{method:"POST"}),enableMQTTLogging:t=>De(`/printers/${t}/logging/enable`,{method:"POST"}),disableMQTTLogging:t=>De(`/printers/${t}/logging/disable`,{method:"POST"}),getMQTTLogs:t=>De(`/printers/${t}/logging`),clearMQTTLogs:t=>De(`/printers/${t}/logging`,{method:"DELETE"}),getPrinterFiles:(t,e="/")=>De(`/printers/${t}/files?path=${encodeURIComponent(e)}`),getPrinterFileDownloadUrl:(t,e)=>`${Cn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,getPrinterFileGcodeUrl:(t,e)=>`${Cn}/printers/${t}/files/gcode?path=${encodeURIComponent(e)}`,getPrinterFilePlates:(t,e)=>De(`/printers/${t}/files/plates?path=${encodeURIComponent(e)}`),getPrinterFilePlateThumbnail:(t,e,n)=>za(`${Cn}/printers/${t}/files/plate-thumbnail/${e}?path=${encodeURIComponent(n)}`),downloadPrinterFile:async(t,e)=>{const n={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=of(i)||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"};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/printers/${t}/files/download-zip`,{method:"POST",headers:n,body:JSON.stringify({paths:e})});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${r.status}`)}return r.blob()},deletePrinterFile:(t,e)=>De(`/printers/${t}/files?path=${encodeURIComponent(e)}`,{method:"DELETE"}),getPrinterStorage:t=>De(`/printers/${t}/storage`),getArchives:(t,e,n=1e4,r=0,i,s)=>{const o=new URLSearchParams;return t&&o.set("printer_id",String(t)),e&&o.set("project_id",String(e)),o.set("limit",String(n)),o.set("offset",String(r)),i&&o.set("date_from",i),s&&o.set("date_to",s),De(`/archives/?${o}`)},getArchivesSlim:(t,e,n)=>{const r=new URLSearchParams;t&&r.set("date_from",t),e&&r.set("date_to",e),n!==void 0&&r.set("created_by_id",String(n));const i=r.toString();return De(`/archives/slim${i?`?${i}`:""}`)},getArchive:t=>De(`/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)),De(`/archives/search?${n}`)},rebuildSearchIndex:()=>De("/archives/search/rebuild-index",{method:"POST"}),updateArchive:(t,e)=>De(`/archives/${t}`,{method:"PATCH",body:JSON.stringify(e)}),toggleFavorite:t=>De(`/archives/${t}/favorite`,{method:"POST"}),deleteArchive:t=>De(`/archives/${t}`,{method:"DELETE"}),getArchiveStats:t=>{const e=new URLSearchParams;t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.createdById!==void 0&&e.set("created_by_id",String(t.createdById));const n=e.toString();return De(`/archives/stats${n?`?${n}`:""}`)},getTags:()=>De("/archives/tags"),renameTag:(t,e)=>De(`/archives/tags/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({new_name:e})}),deleteTag:t=>De(`/archives/tags/${encodeURIComponent(t)}`,{method:"DELETE"}),recalculateCosts:()=>De("/archives/recalculate-costs",{method:"POST"}),getFailureAnalysis:t=>{const e=new URLSearchParams;t?.days&&e.set("days",String(t.days)),t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.projectId&&e.set("project_id",String(t.projectId)),t?.createdById!==void 0&&e.set("created_by_id",String(t.createdById));const n=e.toString();return De(`/archives/analysis/failures${n?`?${n}`:""}`)},compareArchives:t=>De(`/archives/compare?archive_ids=${t.join(",")}`),findSimilarArchives:(t,e=10)=>De(`/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={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/archives/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"archives_export.xlsx":"archives_export.csv";if(i){const l=i.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)),t?.createdById!==void 0&&e.set("created_by_id",String(t.createdById));const n={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/archives/stats/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"stats_export.xlsx":"stats_export.csv";if(i){const l=i.match(/filename="?([^"]+)"?/);l&&(s=l[1])}return{blob:await r.blob(),filename:s}},getArchiveDuplicates:t=>De(`/archives/${t}/duplicates`),backfillContentHashes:()=>De("/archives/backfill-hashes",{method:"POST"}),getArchiveThumbnail:t=>za(`${Cn}/archives/${t}/thumbnail?v=${Date.now()}`),getArchivePlateThumbnail:(t,e)=>za(`${Cn}/archives/${t}/plate-thumbnail/${e}`),getArchiveDownload:t=>`${Cn}/archives/${t}/download`,downloadArchive:async(t,e)=>{const n={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/archives/${t}/download`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=of(i)||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=>`${Cn}/archives/${t}/gcode`,getArchivePlatePreview:t=>za(`${Cn}/archives/${t}/plate-preview`),getArchiveTimelapse:t=>za(`${Cn}/archives/${t}/timelapse?v=${Date.now()}`),scanArchiveTimelapse:t=>De(`/archives/${t}/timelapse/scan`,{method:"POST"}),selectArchiveTimelapse:(t,e)=>De(`/archives/${t}/timelapse/select?filename=${encodeURIComponent(e)}`,{method:"POST"}),deleteArchiveTimelapse:t=>De(`/archives/${t}/timelapse`,{method:"DELETE"}),uploadArchiveTimelapse:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/archives/${t}/timelapse/upload`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},getTimelapseInfo:t=>De(`/archives/${t}/timelapse/info`),getTimelapseThumbnails:(t,e=10)=>De(`/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 i={};Tn&&(i.Authorization=`Bearer ${Tn}`);const s=await fetch(`${Cn}/archives/${t}/timelapse/process`,{method:"POST",headers:i,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)=>za(`${Cn}/archives/${t}/photos/${encodeURIComponent(e)}`),uploadArchivePhoto:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/archives/${t}/photos`,{headers:r,method:"POST",body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteArchivePhoto:(t,e)=>De(`/archives/${t}/photos/${encodeURIComponent(e)}`,{method:"DELETE"}),getSource3mfDownloadUrl:t=>`${Cn}/archives/${t}/source`,downloadSource3mf:async t=>{const e={};Tn&&(e.Authorization=`Bearer ${Tn}`);const n=await fetch(`${Cn}/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"),i=of(r)||`source_${t}.3mf`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(o)},getSource3mfForSlicer:(t,e)=>{const n=e.replace(/[/\\?#]/g,"_");return`${Cn}/archives/${t}/source/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createSourceSlicerToken:t=>De(`/archives/${t}/source-slicer-token`,{method:"POST"}),getSourceSlicerDownloadUrl:(t,e,n)=>{const r=n.replace(/[/\\?#]/g,"_");return`${Cn}/archives/${t}/source-dl/${e}/${encodeURIComponent(r.endsWith(".3mf")?r:r+".3mf")}`},uploadSource3mf:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/archives/${t}/source`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteSource3mf:t=>De(`/archives/${t}/source`,{method:"DELETE"}),getF3dDownloadUrl:t=>`${Cn}/archives/${t}/f3d`,downloadF3d:async t=>{const e={};Tn&&(e.Authorization=`Bearer ${Tn}`);const n=await fetch(`${Cn}/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"),i=of(r)||`archive_${t}.f3d`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=i,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={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/archives/${t}/f3d`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteF3d:t=>De(`/archives/${t}/f3d`,{method:"DELETE"}),getArchiveQRCodeUrl:(t,e=200)=>za(`${Cn}/archives/${t}/qrcode?size=${e}`),getArchiveCapabilities:t=>De(`/archives/${t}/capabilities`),getArchiveProjectPage:t=>De(`/archives/${t}/project-page`),updateArchiveProjectPage:(t,e)=>De(`/archives/${t}/project-page`,{method:"PATCH",body:JSON.stringify(e)}),getArchiveProjectImageUrl:(t,e)=>za(`${Cn}/archives/${t}/project-image/${encodeURIComponent(e)}`),getArchiveForSlicer:(t,e)=>{const n=e.replace(/[/\\?#]/g,"_");return`${Cn}/archives/${t}/file/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createArchiveSlicerToken:t=>De(`/archives/${t}/slicer-token`,{method:"POST"}),getArchiveSlicerDownloadUrl:(t,e,n)=>{const r=n.replace(/[/\\?#]/g,"_");return`${Cn}/archives/${t}/dl/${e}/${encodeURIComponent(r.endsWith(".3mf")?r:r+".3mf")}`},getArchivePlates:t=>De(`/archives/${t}/plates`),getArchiveFilamentRequirements:(t,e)=>De(`/archives/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),reprintArchive:(t,e,n)=>De(`/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?`${Cn}/archives/upload?printer_id=${e}`:`${Cn}/archives/upload`,i={};Tn&&(i.Authorization=`Bearer ${Tn}`);const s=await fetch(r,{method:"POST",headers:i,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?`${Cn}/archives/upload-bulk?printer_id=${e}`:`${Cn}/archives/upload-bulk`,i={};Tn&&(i.Authorization=`Bearer ${Tn}`);const s=await fetch(r,{method:"POST",headers:i,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)),De(`/print-log/?${e}`)},getPrintLogThumbnail:t=>za(`${Cn}/print-log/${t}/thumbnail`),clearPrintLog:()=>De("/print-log/",{method:"DELETE"}),getSettings:()=>De("/settings/"),getDefaultSidebarOrder:()=>De("/settings/default-sidebar-order"),updateSettings:t=>De("/settings/",{method:"PUT",body:JSON.stringify(t)}),getMQTTStatus:()=>De("/settings/mqtt/status"),resetSettings:()=>De("/settings/reset",{method:"POST"}),exportBackup:async()=>{const t=`${Cn}/settings/backup`,e={};Tn&&(e.Authorization=`Bearer ${Tn}`);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 i="bambuddy-backup.zip";if(r){const o=r.match(/filename=([^;]+)/);o&&(i=o[1].trim())}return{blob:await n.blob(),filename:i}},importBackup:async t=>{const e=new FormData;e.append("file",t);const n=`${Cn}/settings/restore`,r={};return Tn&&(r.Authorization=`Bearer ${Tn}`),(await fetch(n,{method:"POST",headers:r,body:e})).json()},checkFfmpeg:()=>De("/settings/check-ffmpeg"),getNetworkInterfaces:()=>De("/settings/network-interfaces"),getCloudStatus:()=>De("/cloud/status"),cloudLogin:(t,e,n="global")=>De("/cloud/login",{method:"POST",body:JSON.stringify({email:t,password:e,region:n})}),cloudVerify:(t,e,n)=>De("/cloud/verify",{method:"POST",body:JSON.stringify({email:t,code:e,tfa_key:n})}),cloudSetToken:t=>De("/cloud/token",{method:"POST",body:JSON.stringify({access_token:t})}),cloudLogout:()=>De("/cloud/logout",{method:"POST"}),getCloudSettings:(t="02.04.00.70")=>De(`/cloud/settings?version=${t}`),getBuiltinFilaments:()=>De("/cloud/builtin-filaments"),getFilamentIdMap:()=>De("/cloud/filament-id-map"),getCloudSettingDetail:t=>De(`/cloud/settings/${t}`),createCloudSetting:t=>De("/cloud/settings",{method:"POST",body:JSON.stringify(t)}),updateCloudSetting:(t,e)=>De(`/cloud/settings/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCloudSetting:t=>De(`/cloud/settings/${t}`,{method:"DELETE"}),getCloudDevices:()=>De("/cloud/devices"),getCloudFields:t=>De(`/cloud/fields/${t}`),getAllCloudFields:()=>De("/cloud/fields"),getFilamentInfo:t=>De("/cloud/filament-info",{method:"POST",body:JSON.stringify(t)}),getSmartPlugs:()=>De("/smart-plugs/"),getSmartPlug:t=>De(`/smart-plugs/${t}`),getSmartPlugByPrinter:t=>De(`/smart-plugs/by-printer/${t}`),getScriptPlugsByPrinter:t=>De(`/smart-plugs/by-printer/${t}/scripts`),createSmartPlug:t=>De("/smart-plugs/",{method:"POST",body:JSON.stringify(t)}),updateSmartPlug:(t,e)=>De(`/smart-plugs/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSmartPlug:t=>De(`/smart-plugs/${t}`,{method:"DELETE"}),controlSmartPlug:(t,e)=>De(`/smart-plugs/${t}/control`,{method:"POST",body:JSON.stringify({action:e})}),getSmartPlugStatus:t=>De(`/smart-plugs/${t}/status`),testSmartPlugConnection:(t,e,n)=>De("/smart-plugs/test-connection",{method:"POST",body:JSON.stringify({ip_address:t,username:e,password:n})}),startTasmotaScan:()=>De("/smart-plugs/discover/scan",{method:"POST"}),getTasmotaScanStatus:()=>De("/smart-plugs/discover/status"),stopTasmotaScan:()=>De("/smart-plugs/discover/stop",{method:"POST"}),getDiscoveredTasmotaDevices:()=>De("/smart-plugs/discover/devices"),testHAConnection:(t,e)=>De("/smart-plugs/ha/test-connection",{method:"POST",body:JSON.stringify({url:t,token:e})}),getHAEntities:t=>{const e=t?`?search=${encodeURIComponent(t)}`:"";return De(`/smart-plugs/ha/entities${e}`)},getHASensorEntities:()=>De("/smart-plugs/ha/sensors"),testRESTConnection:(t,e="GET",n)=>De("/smart-plugs/rest/test-connection",{method:"POST",body:JSON.stringify({url:t,method:e,headers:n})}),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),De(`/queue/?${r}`)},getQueueItem:t=>De(`/queue/${t}`),addToQueue:t=>De("/queue/",{method:"POST",body:JSON.stringify(t)}),updateQueueItem:(t,e)=>De(`/queue/${t}`,{method:"PATCH",body:JSON.stringify(e)}),removeFromQueue:t=>De(`/queue/${t}`,{method:"DELETE"}),reorderQueue:t=>De("/queue/reorder",{method:"POST",body:JSON.stringify({items:t})}),cancelQueueItem:t=>De(`/queue/${t}/cancel`,{method:"POST"}),stopQueueItem:t=>De(`/queue/${t}/stop`,{method:"POST"}),startQueueItem:t=>De(`/queue/${t}/start`,{method:"POST"}),bulkUpdateQueue:t=>De("/queue/bulk",{method:"PATCH",body:JSON.stringify(t)}),getBatches:t=>{const e=t?`?status=${t}`:"";return De(`/queue/batches${e}`)},getBatch:t=>De(`/queue/batches/${t}`),cancelBatch:t=>De(`/queue/batches/${t}`,{method:"DELETE"}),getKProfiles:(t,e="0.4")=>De(`/printers/${t}/kprofiles/?nozzle_diameter=${e}`),setKProfile:(t,e)=>De(`/printers/${t}/kprofiles/`,{method:"POST",body:JSON.stringify(e)}),deleteKProfile:(t,e)=>De(`/printers/${t}/kprofiles/`,{method:"DELETE",body:JSON.stringify(e)}),setKProfilesBatch:(t,e)=>De(`/printers/${t}/kprofiles/batch`,{method:"POST",body:JSON.stringify(e)}),getKProfileNotes:t=>De(`/printers/${t}/kprofiles/notes`),setKProfileNote:(t,e,n)=>De(`/printers/${t}/kprofiles/notes`,{method:"PUT",body:JSON.stringify({setting_id:e,note:n})}),deleteKProfileNote:(t,e)=>De(`/printers/${t}/kprofiles/notes/${encodeURIComponent(e)}`,{method:"DELETE"}),getSlotPresets:t=>De(`/printers/${t}/slot-presets`),getSlotPreset:(t,e,n)=>De(`/printers/${t}/slot-presets/${e}/${n}`),saveSlotPreset:(t,e,n,r,i,s="cloud")=>De(`/printers/${t}/slot-presets/${e}/${n}?preset_id=${encodeURIComponent(r)}&preset_name=${encodeURIComponent(i)}&preset_source=${encodeURIComponent(s)}`,{method:"PUT"}),deleteSlotPreset:(t,e,n)=>De(`/printers/${t}/slot-presets/${e}/${n}`,{method:"DELETE"}),getAmsLabels:t=>De(`/printers/${t}/ams-labels`),saveAmsLabel:(t,e,n,r="")=>De(`/printers/${t}/ams-labels/${e}`,{method:"PUT",body:JSON.stringify({label:n,ams_serial:r})}),deleteAmsLabel:(t,e,n="")=>De(`/printers/${t}/ams-labels/${e}?ams_serial=${encodeURIComponent(n)}`,{method:"DELETE"}),configureAmsSlot:(t,e,n,r)=>{const i=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&&i.set("setting_id",r.setting_id),r.kprofile_filament_id&&i.set("kprofile_filament_id",r.kprofile_filament_id),r.kprofile_setting_id&&i.set("kprofile_setting_id",r.kprofile_setting_id),r.k_value!==void 0&&r.k_value>0&&i.set("k_value",r.k_value.toString()),De(`/printers/${t}/slots/${e}/${n}/configure?${i}`,{method:"POST"})},resetAmsSlot:(t,e,n)=>De(`/printers/${t}/ams/${e}/tray/${n}/reset`,{method:"POST"}),listFilaments:()=>De("/filament-catalog/"),getFilament:t=>De(`/filament-catalog/${t}`),getFilamentsByType:t=>De(`/filament-catalog/by-type/${t}`),getNotificationProviders:()=>De("/notifications/"),getNotificationProvider:t=>De(`/notifications/${t}`),createNotificationProvider:t=>De("/notifications/",{method:"POST",body:JSON.stringify(t)}),updateNotificationProvider:(t,e)=>De(`/notifications/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteNotificationProvider:t=>De(`/notifications/${t}`,{method:"DELETE"}),testNotificationProvider:t=>De(`/notifications/${t}/test`,{method:"POST"}),testNotificationConfig:t=>De("/notifications/test-config",{method:"POST",body:JSON.stringify(t)}),testAllNotificationProviders:()=>De("/notifications/test-all",{method:"POST"}),getNotificationTemplates:()=>De("/notification-templates"),getNotificationTemplate:t=>De(`/notification-templates/${t}`),updateNotificationTemplate:(t,e)=>De(`/notification-templates/${t}`,{method:"PUT",body:JSON.stringify(e)}),resetNotificationTemplate:t=>De(`/notification-templates/${t}/reset`,{method:"POST"}),getTemplateVariables:()=>De("/notification-templates/variables"),previewTemplate:t=>De("/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)),De(`/notifications/logs?${e}`)},getNotificationLogStats:(t=7)=>De(`/notifications/logs/stats?days=${t}`),clearNotificationLogs:(t=30)=>De(`/notifications/logs?older_than_days=${t}`,{method:"DELETE"}),getSpoolmanStatus:()=>De("/spoolman/status"),connectSpoolman:()=>De("/spoolman/connect",{method:"POST"}),disconnectSpoolman:()=>De("/spoolman/disconnect",{method:"POST"}),syncPrinterAms:t=>De(`/spoolman/sync/${t}`,{method:"POST"}),syncAllPrintersAms:()=>De("/spoolman/sync-all",{method:"POST"}),getSpoolmanSpools:()=>De("/spoolman/spools"),getSpoolmanFilaments:()=>De("/spoolman/filaments"),getUnlinkedSpools:()=>De("/spoolman/spools/unlinked"),getLinkedSpools:()=>De("/spoolman/spools/linked"),linkSpool:(t,e)=>De(`/spoolman/spools/${t}/link`,{method:"POST",body:JSON.stringify({spool_tag:e.spoolTag,printer_id:e.printerId,ams_id:e.amsId,tray_id:e.trayId})}),unlinkSpool:t=>De(`/spoolman/spools/${t}/unlink`,{method:"POST"}),getSpoolmanSettings:()=>De("/settings/spoolman"),updateSpoolmanSettings:t=>De("/settings/spoolman",{method:"PUT",body:JSON.stringify(t)}),getSpools:(t=!1)=>De(`/inventory/spools?include_archived=${t}`),getSpool:t=>De(`/inventory/spools/${t}`),createSpool:t=>De("/inventory/spools",{method:"POST",body:JSON.stringify(t)}),bulkCreateSpools:(t,e)=>De("/inventory/spools/bulk",{method:"POST",body:JSON.stringify({spool:t,quantity:e})}),updateSpool:(t,e)=>De(`/inventory/spools/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSpool:t=>De(`/inventory/spools/${t}`,{method:"DELETE"}),archiveSpool:t=>De(`/inventory/spools/${t}/archive`,{method:"POST"}),restoreSpool:t=>De(`/inventory/spools/${t}/restore`,{method:"POST"}),getSpoolKProfiles:t=>De(`/inventory/spools/${t}/k-profiles`),saveSpoolKProfiles:(t,e)=>De(`/inventory/spools/${t}/k-profiles`,{method:"PUT",body:JSON.stringify(e)}),getAssignments:t=>De(`/inventory/assignments${t?`?printer_id=${t}`:""}`),assignSpool:t=>De("/inventory/assignments",{method:"POST",body:JSON.stringify(t)}),unassignSpool:(t,e,n)=>De(`/inventory/assignments/${t}/${e}/${n}`,{method:"DELETE"}),getSpoolCatalog:()=>De("/inventory/catalog"),addCatalogEntry:t=>De("/inventory/catalog",{method:"POST",body:JSON.stringify(t)}),updateCatalogEntry:(t,e)=>De(`/inventory/catalog/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCatalogEntry:t=>De(`/inventory/catalog/${t}`,{method:"DELETE"}),bulkDeleteCatalogEntries:t=>De("/inventory/catalog/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetSpoolCatalog:()=>De("/inventory/catalog/reset",{method:"POST"}),getColorCatalog:()=>De("/inventory/colors"),getColorNameMap:()=>De("/inventory/colors/map"),addColorEntry:t=>De("/inventory/colors",{method:"POST",body:JSON.stringify(t)}),updateColorEntry:(t,e)=>De(`/inventory/colors/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteColorEntry:t=>De(`/inventory/colors/${t}`,{method:"DELETE"}),bulkDeleteColorEntries:t=>De("/inventory/colors/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetColorCatalog:()=>De("/inventory/colors/reset",{method:"POST"}),lookupColor:(t,e,n)=>De(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(t)}&color_name=${encodeURIComponent(e)}${n?`&material=${encodeURIComponent(n)}`:""}`),searchColors:(t,e)=>De(`/inventory/colors/search?${t?`manufacturer=${encodeURIComponent(t)}`:""}${t&&e?"&":""}${e?`material=${encodeURIComponent(e)}`:""}`),linkTagToSpool:(t,e)=>De(`/inventory/spools/${t}/link-tag`,{method:"PATCH",body:JSON.stringify(e)}),getSpoolUsageHistory:(t,e=50)=>De(`/inventory/spools/${t}/usage?limit=${e}`),getAllUsageHistory:(t=100,e)=>De(`/inventory/usage?limit=${t}${e?`&printer_id=${e}`:""}`),clearSpoolUsageHistory:t=>De(`/inventory/spools/${t}/usage`,{method:"DELETE"}),syncWeightsFromAms:()=>De("/inventory/sync-ams-weights",{method:"POST"}),getFilamentPresets:()=>De("/cloud/filaments"),getVersion:()=>De("/updates/version"),checkForUpdates:()=>De("/updates/check"),applyUpdate:()=>De("/updates/apply",{method:"POST"}),getUpdateStatus:()=>De("/updates/status"),getMaintenanceTypes:()=>De("/maintenance/types"),createMaintenanceType:t=>De("/maintenance/types",{method:"POST",body:JSON.stringify(t)}),updateMaintenanceType:(t,e)=>De(`/maintenance/types/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteMaintenanceType:t=>De(`/maintenance/types/${t}`,{method:"DELETE"}),restoreDefaultMaintenanceTypes:()=>De("/maintenance/types/restore-defaults",{method:"POST"}),getMaintenanceOverview:()=>De("/maintenance/overview"),getPrinterMaintenance:t=>De(`/maintenance/printers/${t}`),updateMaintenanceItem:(t,e)=>De(`/maintenance/items/${t}`,{method:"PATCH",body:JSON.stringify(e)}),performMaintenance:(t,e)=>De(`/maintenance/items/${t}/perform`,{method:"POST",body:JSON.stringify({notes:e})}),getMaintenanceHistory:t=>De(`/maintenance/items/${t}/history`),getMaintenanceSummary:()=>De("/maintenance/summary"),setPrinterHours:(t,e)=>De(`/maintenance/printers/${t}/hours?total_hours=${e}`,{method:"PATCH"}),assignMaintenanceType:(t,e)=>De(`/maintenance/printers/${t}/assign/${e}`,{method:"POST"}),removeMaintenanceItem:t=>De(`/maintenance/items/${t}`,{method:"DELETE"}),getCameraStreamToken:()=>De("/printers/camera/stream-token",{method:"POST"}),getCameraStreamUrl:(t,e=10)=>za(`${Cn}/printers/${t}/camera/stream?fps=${e}`),getCameraSnapshotUrl:t=>za(`${Cn}/printers/${t}/camera/snapshot`),testCameraConnection:t=>De(`/printers/${t}/camera/test`),getCameraStatus:t=>De(`/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)),De(`/printers/${t}/camera/check-plate?${n.toString()}`)},getPlateDetectionStatus:t=>De(`/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)),De(`/printers/${t}/camera/plate-detection/calibrate?${n.toString()}`,{method:"POST"})},deletePlateCalibration:t=>De(`/printers/${t}/camera/plate-detection/calibrate`,{method:"DELETE"}),getPlateReferences:t=>De(`/printers/${t}/camera/plate-detection/references`),getPlateReferenceThumbnailUrl:(t,e)=>za(`${Cn}/printers/${t}/camera/plate-detection/references/${e}/thumbnail`),updatePlateReferenceLabel:(t,e,n)=>{const r=new URLSearchParams;return r.set("label",n),De(`/printers/${t}/camera/plate-detection/references/${e}?${r.toString()}`,{method:"PUT"})},deletePlateReference:(t,e)=>De(`/printers/${t}/camera/plate-detection/references/${e}`,{method:"DELETE"}),getExternalLinks:()=>De("/external-links/"),getExternalLink:t=>De(`/external-links/${t}`),createExternalLink:t=>De("/external-links/",{method:"POST",body:JSON.stringify(t)}),updateExternalLink:(t,e)=>De(`/external-links/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteExternalLink:t=>De(`/external-links/${t}`,{method:"DELETE"}),reorderExternalLinks:t=>De("/external-links/reorder",{method:"PUT",body:JSON.stringify({ids:t})}),uploadExternalLinkIcon:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/external-links/${t}/icon`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteExternalLinkIcon:t=>De(`/external-links/${t}/icon`,{method:"DELETE"}),getExternalLinkIconUrl:t=>za(`${Cn}/external-links/${t}/icon`),getProjects:t=>{const e=new URLSearchParams;return t&&e.set("status",t),De(`/projects/?${e}`)},getProject:t=>De(`/projects/${t}`),createProject:t=>De("/projects/",{method:"POST",body:JSON.stringify(t)}),updateProject:(t,e)=>De(`/projects/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>De(`/projects/${t}`,{method:"DELETE"}),getProjectArchives:(t,e=100,n=0)=>De(`/projects/${t}/archives?limit=${e}&offset=${n}`),addArchivesToProject:(t,e)=>De(`/projects/${t}/add-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),removeArchivesFromProject:(t,e)=>De(`/projects/${t}/remove-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),addQueueItemsToProject:(t,e)=>De(`/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={};Tn&&(r.Authorization=`Bearer ${Tn}`);const i=await fetch(`${Cn}/projects/${t}/attachments`,{method:"POST",headers:r,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},getProjectAttachmentUrl:(t,e)=>`${Cn}/projects/${t}/attachments/${encodeURIComponent(e)}`,deleteProjectAttachment:(t,e)=>De(`/projects/${t}/attachments/${encodeURIComponent(e)}`,{method:"DELETE"}),getProjectBOM:t=>De(`/projects/${t}/bom`),createBOMItem:(t,e)=>De(`/projects/${t}/bom`,{method:"POST",body:JSON.stringify(e)}),updateBOMItem:(t,e,n)=>De(`/projects/${t}/bom/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteBOMItem:(t,e)=>De(`/projects/${t}/bom/${e}`,{method:"DELETE"}),getTemplates:()=>De("/projects/templates/"),createTemplateFromProject:t=>De(`/projects/${t}/create-template`,{method:"POST"}),createProjectFromTemplate:(t,e)=>De(`/projects/from-template/${t}${e?`?name=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getProjectTimeline:(t,e=50)=>De(`/projects/${t}/timeline?limit=${e}`),exportProjectJson:t=>De(`/projects/${t}/export?format=json`),importProject:t=>De("/projects/import",{method:"POST",body:JSON.stringify(t)}),importProjectFile:async t=>{const e=new FormData;e.append("file",t);const n={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/projects/import/file`,{method:"POST",headers:n,body:e});if(!r.ok){const i=await r.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${r.status}`)}return r.json()},exportProjectZip:async t=>{const e={};Tn&&(e.Authorization=`Bearer ${Tn}`);const n=await fetch(`${Cn}/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"),i=of(r)||`project_${t}.zip`;return{blob:await n.blob(),filename:i}},getAPIKeys:()=>De("/api-keys/"),createAPIKey:t=>De("/api-keys/",{method:"POST",body:JSON.stringify(t)}),updateAPIKey:(t,e)=>De(`/api-keys/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteAPIKey:t=>De(`/api-keys/${t}`,{method:"DELETE"}),getAMSHistory:(t,e,n=24)=>De(`/ams-history/${t}/${e}?hours=${n}`),getSystemInfo:()=>De("/system/info"),getStorageUsage:t=>{const e=new URLSearchParams;t?.refresh&&e.set("refresh","true");const n=e.toString();return De(`/system/storage-usage${n?`?${n}`:""}`)},getLibraryFolders:()=>De("/library/folders"),createLibraryFolder:t=>De("/library/folders",{method:"POST",body:JSON.stringify(t)}),updateLibraryFolder:(t,e)=>De(`/library/folders/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFolder:t=>De(`/library/folders/${t}`,{method:"DELETE"}),createExternalFolder:t=>De("/library/folders/external",{method:"POST",body:JSON.stringify(t)}),scanExternalFolder:t=>De(`/library/folders/${t}/scan`,{method:"POST"}),getLibraryFoldersByProject:t=>De(`/library/folders/by-project/${t}`),getLibraryFoldersByArchive:t=>De(`/library/folders/by-archive/${t}`),getLibraryFiles:(t,e=!0,n)=>{const r=new URLSearchParams;return t!=null&&r.set("folder_id",String(t)),n!==void 0&&r.set("project_id",String(n)),r.set("include_root",String(e)),De(`/library/files?${r}`)},getLibraryFile:t=>De(`/library/files/${t}`),uploadLibraryFile:async(t,e,n=!0)=>{const r=new FormData;r.append("file",t);const i=new URLSearchParams;e&&i.set("folder_id",String(e)),i.set("generate_stl_thumbnails",String(n));const s={};Tn&&(s.Authorization=`Bearer ${Tn}`);const o=await fetch(`${Cn}/library/files?${i}`,{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,i=!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(i));const l={};Tn&&(l.Authorization=`Bearer ${Tn}`);const c=await fetch(`${Cn}/library/files/extract-zip?${o}`,{method:"POST",headers:l,body:s});if(!c.ok){const d=await c.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${c.status}`)}return c.json()},updateLibraryFile:(t,e)=>De(`/library/files/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFile:t=>De(`/library/files/${t}`,{method:"DELETE"}),getLibraryFileDownloadUrl:t=>`${Cn}/library/files/${t}/download`,createLibrarySlicerToken:t=>De(`/library/files/${t}/slicer-token`,{method:"POST"}),getLibrarySlicerDownloadUrl:(t,e,n)=>`${Cn}/library/files/${t}/dl/${e}/${encodeURIComponent(n)}`,downloadLibraryFile:async(t,e)=>{const n={};Tn&&(n.Authorization=`Bearer ${Tn}`);const r=await fetch(`${Cn}/library/files/${t}/download`,{headers:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${r.status}`)}const i=r.headers.get("Content-Disposition"),s=of(i)||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=>za(`${Cn}/library/files/${t}/thumbnail`),getLibraryFilePlateThumbnail:(t,e)=>za(`${Cn}/library/files/${t}/plate-thumbnail/${e}`),getLibraryFileGcodeUrl:t=>`${Cn}/library/files/${t}/gcode`,moveLibraryFiles:(t,e)=>De("/library/files/move",{method:"POST",body:JSON.stringify({file_ids:t,folder_id:e})}),bulkDeleteLibrary:(t,e)=>De("/library/bulk-delete",{method:"POST",body:JSON.stringify({file_ids:t,folder_ids:e})}),getLibraryStats:()=>De("/library/stats"),batchGenerateStlThumbnails:t=>De("/library/generate-stl-thumbnails",{method:"POST",body:JSON.stringify(t)}),addLibraryFilesToQueue:t=>De("/library/files/add-to-queue",{method:"POST",body:JSON.stringify({file_ids:t})}),printLibraryFile:(t,e,n)=>De(`/library/files/${t}/print?printer_id=${e}`,{method:"POST",body:n?JSON.stringify(n):void 0}),cancelBackgroundDispatchJob:t=>De(`/background-dispatch/${t}`,{method:"DELETE"}),getLibraryFilePlates:t=>De(`/library/files/${t}/plates`),getLibraryFileFilamentRequirements:(t,e)=>De(`/library/files/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),getGitHubBackupConfig:()=>De("/github-backup/config"),saveGitHubBackupConfig:t=>De("/github-backup/config",{method:"POST",body:JSON.stringify(t)}),updateGitHubBackupConfig:t=>De("/github-backup/config",{method:"PATCH",body:JSON.stringify(t)}),deleteGitHubBackupConfig:()=>De("/github-backup/config",{method:"DELETE"}),testGitHubConnection:(t,e)=>De(`/github-backup/test?repo_url=${encodeURIComponent(t)}&token=${encodeURIComponent(e)}`,{method:"POST"}),testGitHubStoredConnection:()=>De("/github-backup/test-stored",{method:"POST"}),triggerGitHubBackup:()=>De("/github-backup/run",{method:"POST"}),getGitHubBackupStatus:()=>De("/github-backup/status"),getGitHubBackupLogs:(t=50)=>De(`/github-backup/logs?limit=${t}`),clearGitHubBackupLogs:(t=10)=>De(`/github-backup/logs?keep_last=${t}`,{method:"DELETE"}),getLocalBackupStatus:()=>De("/local-backup/status"),triggerLocalBackup:()=>De("/local-backup/run",{method:"POST"}),getLocalBackups:()=>De("/local-backup/backups"),downloadLocalBackup:async t=>{const e=await fetch(`${Cn}/local-backup/backups/${encodeURIComponent(t)}/download`,{headers:Tn?{Authorization:`Bearer ${Tn}`}:{}});if(!e.ok)throw new Error("Download failed");return{blob:await e.blob(),filename:t}},restoreLocalBackup:t=>De(`/local-backup/backups/${encodeURIComponent(t)}/restore`,{method:"POST"}),deleteLocalBackup:t=>De(`/local-backup/backups/${encodeURIComponent(t)}`,{method:"DELETE"}),getObicoStatus:()=>De("/obico/status"),testObicoConnection:t=>De("/obico/test-connection",{method:"POST",body:JSON.stringify({url:t})}),getLocalPresets:()=>De("/local-presets/"),getLocalPresetDetail:t=>De(`/local-presets/${t}`),importLocalPresets:t=>fetch(`${Cn}/local-presets/import`,{method:"POST",headers:Tn?{Authorization:`Bearer ${Tn}`}:{},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=>De("/local-presets/",{method:"POST",body:JSON.stringify(t)}),updateLocalPreset:(t,e)=>De(`/local-presets/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLocalPreset:t=>De(`/local-presets/${t}`,{method:"DELETE"}),refreshBaseProfileCache:()=>De("/local-presets/base-cache/refresh",{method:"POST"})},rd={getInfo:()=>De("/discovery/info"),getStatus:()=>De("/discovery/status"),startDiscovery:(t=10)=>De(`/discovery/start?duration=${t}`,{method:"POST"}),stopDiscovery:()=>De("/discovery/stop",{method:"POST"}),getDiscoveredPrinters:()=>De("/discovery/printers"),startSubnetScan:(t,e=1)=>De("/discovery/scan",{method:"POST",body:JSON.stringify({subnet:t,timeout:e})}),getScanStatus:()=>De("/discovery/scan/status"),stopSubnetScan:()=>De("/discovery/scan/stop",{method:"POST"})},lye={getSettings:()=>De("/settings/virtual-printer")},hN={list:()=>De("/virtual-printers"),get:t=>De(`/virtual-printers/${t}`),create:t=>De("/virtual-printers",{method:"POST",body:JSON.stringify(t)}),update:(t,e)=>De(`/virtual-printers/${t}`,{method:"PUT",body:JSON.stringify(e)}),remove:t=>De(`/virtual-printers/${t}`,{method:"DELETE"})},Xb={list:()=>De("/pending-uploads/"),getCount:()=>De("/pending-uploads/count"),get:t=>De(`/pending-uploads/${t}`),archive:(t,e)=>De(`/pending-uploads/${t}/archive`,{method:"POST",body:JSON.stringify(e||{})}),discard:t=>De(`/pending-uploads/${t}`,{method:"DELETE"}),archiveAll:()=>De("/pending-uploads/archive-all",{method:"POST"}),discardAll:()=>De("/pending-uploads/discard-all",{method:"DELETE"})},kk={checkUpdates:()=>De("/firmware/updates"),checkPrinterUpdate:t=>De(`/firmware/updates/${t}`),prepareUpload:(t,e)=>De(`/firmware/updates/${t}/prepare${e?`?version=${encodeURIComponent(e)}`:""}`),startUpload:(t,e)=>De(`/firmware/updates/${t}/upload${e?`?version=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getUploadStatus:t=>De(`/firmware/updates/${t}/upload/status`)},ux={getDebugLoggingState:()=>De("/support/debug-logging"),setDebugLogging:t=>De("/support/debug-logging",{method:"POST",body:JSON.stringify({enabled:t})}),downloadSupportBundle:async()=>{const t={};Tn&&(t.Authorization=`Bearer ${Tn}`);const e=await fetch(`${Cn}/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=of(n)||"bambuddy-support.zip",i=await e.blob(),s=window.URL.createObjectURL(i),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 De(`/support/logs${n?`?${n}`:""}`)},clearLogs:()=>De("/support/logs",{method:"DELETE"})},Ur={getDevices:()=>De("/spoolbuddy/devices"),deleteDevice:t=>De(`/spoolbuddy/devices/${t}`,{method:"DELETE"}),tare:t=>De(`/spoolbuddy/devices/${t}/calibration/tare`,{method:"POST",body:"{}"}),getCalibration:t=>De(`/spoolbuddy/devices/${t}/calibration`),setCalibrationFactor:(t,e,n,r)=>De(`/spoolbuddy/devices/${t}/calibration/set-factor`,{method:"POST",body:JSON.stringify({known_weight_grams:e,raw_adc:n,tare_raw_adc:r})}),updateSpoolWeight:(t,e)=>De("/spoolbuddy/scale/update-spool-weight",{method:"POST",body:JSON.stringify({spool_id:t,weight_grams:e})}),updateDisplay:(t,e,n)=>De(`/spoolbuddy/devices/${t}/display`,{method:"PUT",body:JSON.stringify({brightness:e,blank_timeout:n})}),updateSystemConfig:(t,e,n)=>De(`/spoolbuddy/devices/${t}/system/config`,{method:"POST",body:JSON.stringify({backend_url:e,...n?{api_key:n}:{}})}),checkDaemonUpdate:t=>De(`/spoolbuddy/devices/${t}/update-check`),triggerUpdate:t=>De(`/spoolbuddy/devices/${t}/update`,{method:"POST",body:"{}"}),getSSHPublicKey:()=>De("/spoolbuddy/ssh/public-key"),writeTag:(t,e)=>De("/spoolbuddy/nfc/write-tag",{method:"POST",body:JSON.stringify({device_id:t,spool_id:e})}),cancelWrite:t=>De(`/spoolbuddy/devices/${t}/cancel-write`,{method:"POST",body:"{}"}),systemCommand:(t,e)=>De(`/spoolbuddy/devices/${t}/system/command`,{method:"POST",body:JSON.stringify({command:e})}),queueDiagnostics:(t,e)=>De(`/spoolbuddy/diagnostics/${t}/run?diagnostic=${e}`,{method:"POST",body:"{}"}),getDiagnosticResult:(t,e)=>De(`/spoolbuddy/diagnostics/${t}/result?diagnostic=${e}`,{method:"GET"})},xM={submit:t=>De("/bug-report/submit",{method:"POST",body:JSON.stringify(t)}),startLogging:()=>De("/bug-report/start-logging",{method:"POST"}),stopLogging:t=>De(`/bug-report/stop-logging?was_debug=${t}`,{method:"POST"})},HQ=w.createContext(void 0);function cye({children:t}){const[e,n]=w.useState(()=>{const T=localStorage.getItem("theme-mode"),F=localStorage.getItem("theme");return T||F||"dark"}),[r,i]=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"),[d,u]=w.useState(()=>localStorage.getItem("light-style")||"classic"),[m,p]=w.useState(()=>localStorage.getItem("light-background")||"neutral"),[f,x]=w.useState(()=>localStorage.getItem("light-accent")||"green");w.useEffect(()=>{me.getSettings().then(T=>{T.dark_style&&(i(T.dark_style),localStorage.setItem("dark-style",T.dark_style)),T.dark_background&&(o(T.dark_background),localStorage.setItem("dark-background",T.dark_background)),T.dark_accent&&(c(T.dark_accent),localStorage.setItem("dark-accent",T.dark_accent)),T.light_style&&(u(T.light_style),localStorage.setItem("light-style",T.light_style)),T.light_background&&(p(T.light_background),localStorage.setItem("light-background",T.light_background)),T.light_accent&&(x(T.light_accent),localStorage.setItem("light-accent",T.light_accent))}).catch(()=>{})},[]),w.useEffect(()=>{const T=document.documentElement;T.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"?(T.classList.add("dark"),T.classList.add(`style-${r}`),T.classList.add(`bg-${s}`),T.classList.add(`accent-${l}`)):(T.classList.add(`style-${d}`),T.classList.add(`bg-${m}`),T.classList.add(`accent-${f}`)),localStorage.setItem("theme-mode",e),localStorage.removeItem("theme")},[e,r,s,l,d,m,f]);const v=()=>n(T=>T==="dark"?"light":"dark"),g=T=>n(T),b=T=>{i(T),localStorage.setItem("dark-style",T),me.updateSettings({dark_style:T}).catch(()=>{})},_=T=>{o(T),localStorage.setItem("dark-background",T),me.updateSettings({dark_background:T}).catch(()=>{})},C=T=>{c(T),localStorage.setItem("dark-accent",T),me.updateSettings({dark_accent:T}).catch(()=>{})},P=T=>{u(T),localStorage.setItem("light-style",T),me.updateSettings({light_style:T}).catch(()=>{})},N=T=>{p(T),localStorage.setItem("light-background",T),me.updateSettings({light_background:T}).catch(()=>{})},A=T=>{x(T),localStorage.setItem("light-accent",T),me.updateSettings({light_accent:T}).catch(()=>{})};return a.jsx(HQ.Provider,{value:{mode:e,darkStyle:r,darkBackground:s,darkAccent:l,lightStyle:d,lightBackground:m,lightAccent:f,toggleMode:v,setMode:g,setDarkStyle:b,setDarkBackground:_,setDarkAccent:C,setLightStyle:P,setLightBackground:N,setLightAccent:A},children:t})}function wg(){const t=w.useContext(HQ);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const PO=w.createContext("normal");function dye({density:t,children:e}){return a.jsx(PO.Provider,{value:t,children:e})}function At({children:t,className:e="",onClick:n,onContextMenu:r,...i}){return a.jsx("div",{className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary card-shadow ${e}`,onClick:n,onContextMenu:r,...i,children:t})}function wn({children:t,className:e="",dense:n}){const r=w.useContext(PO)==="dense",s=n??r?"px-4 py-2.5":"px-6 py-4";return a.jsx("div",{className:`${s} border-b border-bambu-dark-tertiary ${e}`,children:t})}function Mt({children:t,className:e="",dense:n}){const r=w.useContext(PO)==="dense",s=n??r?"p-4":"p-6";return a.jsx("div",{className:`${s} ${e}`,children:t})}function uye(t,e,n){return[{category:"Navigation",items:t?t.slice(0,9).map((i,s)=>({keys:[String(s+1)],description:i.type==="external"?`Open ${i.label}`:`Go to ${i.labelKey?n(i.labelKey):i.label}`,isExternal:i.type==="external"})):e?e.map((i,s)=>({keys:[String(s+1)],description:`Go to ${n(i.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 NH({children:t}){return a.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 mye({onClose:t,navItems:e,sidebarItems:n}){const{t:r}=Rt(),i=uye(n,e,r);return w.useEffect(()=>{const s=o=>{o.key==="Escape"&&t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:a.jsx(At,{className:"w-full max-w-md",onClick:s=>s.stopPropagation(),children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(G3,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Keyboard Shortcuts"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4 space-y-6 max-h-[60vh] overflow-y-auto",children:i.map(s=>a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:s.category}),a.jsx("div",{className:"space-y-2",children:s.items.map(o=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"text-white text-sm flex items-center gap-1.5",children:[o.description,o.isExternal&&a.jsx(na,{className:"w-3 h-3 text-bambu-gray"})]}),a.jsx("div",{className:"flex gap-1",children:o.keys.map(l=>a.jsx(NH,{children:l},l))})]},o.description))})]},s.category))}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("p",{className:"text-xs text-bambu-gray text-center",children:["Press ",a.jsx(NH,{children:"Esc"})," or click outside to close"]})})]})})})}function Fe({variant:t="primary",size:e="md",className:n="",children:r,...i}){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 a.jsx("button",{className:`${s} ${o[t]} ${l[e]} ${n}`,...i,children:r})}function _n({title:t,message:e,confirmText:n,cancelText:r,cancelVariant:i,cardClassName:s,variant:o="default",isLoading:l=!1,loadingText:c,onConfirm:d,onCancel:u}){const{t:m}=Rt(),p=n??m("common.confirm"),f=r??m("common.cancel"),x=c??m("common.loading");w.useEffect(()=>{const b=_=>{_.key==="Escape"&&!l&&u()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[u,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 text-black"},default:{icon:"text-bambu-green",button:"bg-bambu-green hover:bg-bambu-green-dark"}}[o];return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l?void 0:u,children:a.jsx(At,{className:`w-full max-w-md ${s??""}`,onClick:b=>b.stopPropagation(),children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-start gap-4",children:[a.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${g.icon}`,children:a.jsx(Rn,{className:"w-6 h-6"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t}),a.jsx("p",{className:"text-bambu-gray text-sm whitespace-pre-line",children:e})]})]}),a.jsxs("div",{className:"flex gap-3 mt-6",children:[a.jsx(Fe,{variant:i??"secondary",onClick:u,className:"flex-1",disabled:l,children:f}),a.jsx(Fe,{onClick:d,className:`flex-1 ${g.button}`,disabled:l,children:l?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 mr-2 animate-spin"}),x]}):p})]})]})})})}function hye({plug:t}){const e=sn(),[n,r]=w.useState(null),{data:i,isLoading:s}=Qe({queryKey:["smart-plug-status",t.id],queryFn:()=>me.getSmartPlugStatus(t.id),refetchInterval:1e4}),o=it({mutationFn:f=>me.controlSmartPlug(t.id,f),onSuccess:()=>{e.invalidateQueries({queryKey:["smart-plug-status",t.id]})}}),l=i?.state==="ON",c=t.plug_type==="mqtt"&&i?.energy?.power!==null&&i?.energy?.power!==void 0,d=(i?.reachable??!1)||c,u=o.isPending,m=t.plug_type==="mqtt",p=()=>{n&&(o.mutate(n),r(null))};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between py-2 px-3 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`p-1.5 rounded ${m?d?"bg-teal-500/20":"bg-red-500/20":d?l?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:m?a.jsx(SO,{className:`w-4 h-4 ${d?"text-teal-400":"text-red-400"}`}):a.jsx(Ql,{className:`w-4 h-4 ${d?l?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white font-medium",children:t.name}),a.jsx("div",{className:"flex items-center gap-1 text-xs",children:s?a.jsx(dt,{className:"w-3 h-3 text-bambu-gray animate-spin"}):m?d?a.jsxs(a.Fragment,{children:[a.jsx(ic,{className:"w-3 h-3 text-teal-400"}),a.jsxs("span",{className:"text-teal-400",children:[Math.round(i?.energy?.power??0),"W"]}),a.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),a.jsx(ul,{className:"w-3 h-3 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:"Monitor"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Md,{className:"w-3 h-3 text-status-error"}),a.jsx("span",{className:"text-status-error",children:"Waiting"})]}):d?a.jsxs(a.Fragment,{children:[a.jsx(Vh,{className:"w-3 h-3 text-status-ok"}),a.jsx("span",{className:l?"text-status-ok":"text-bambu-gray",children:i?.state||"Unknown"}),i?.energy?.power!==null&&i?.energy?.power!==void 0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),a.jsx(ic,{className:"w-3 h-3 text-yellow-400"}),a.jsxs("span",{className:"text-yellow-400",children:[Math.round(i.energy.power),"W"]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Md,{className:"w-3 h-3 text-status-error"}),a.jsx("span",{className:"text-status-error",children:"Offline"})]})})]})]}),!m&&a.jsxs("div",{className:"flex gap-1",children:[a.jsx("button",{onClick:()=>r("on"),disabled:!d||u,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:u?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Ud,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("off"),disabled:!d||u,className:`p-1.5 rounded transition-colors ${!l&&d?"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:u?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Uw,{className:"w-4 h-4"})})]})]}),n&&a.jsx(_n,{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:p,onCancel:()=>r(null)})]})}function CH({onClose:t}){const{t:e}=Rt(),{data:n,isLoading:r}=Qe({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),i=n?.filter(s=>s.show_in_switchbar)||[];return a.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:[a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary",children:a.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[a.jsx(Ql,{className:"w-4 h-4 text-bambu-green"}),"Smart Switches"]})}),a.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:r?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-gray animate-spin"})}):i.length===0?a.jsxs("div",{className:"text-center py-6 px-4",children:[a.jsx(Ql,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e("smartPlugs.noSwitchesInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:e("smartPlugs.enableSwitchbarHint")})]}):a.jsx("div",{className:"space-y-1",children:i.map(s=>a.jsx(hye,{plug:s},s.id))})})]})}const qQ=[{name:"globe",icon:rl},{name:"link",icon:ly},{name:"external-link",icon:na},{name:"book",icon:Cpe},{name:"file-text",icon:Ms},{name:"home",icon:Rw},{name:"star",icon:Xf},{name:"heart",icon:Rge},{name:"bookmark",icon:Tpe},{name:"shopping-cart",icon:FQ},{name:"music",icon:X3},{name:"video",icon:kO},{name:"image",icon:rm},{name:"camera",icon:Tx},{name:"map",icon:sbe},{name:"compass",icon:Cfe},{name:"coffee",icon:xfe},{name:"gift",icon:vge},{name:"wrench",icon:Yf},{name:"zap",icon:ic},{name:"cloud",icon:sy},{name:"database",icon:Kl},{name:"folder",icon:PQ},{name:"mail",icon:am},{name:"phone",icon:Abe},{name:"user",icon:sm},{name:"users",icon:Fu},{name:"server",icon:sf},{name:"terminal",icon:IQ},{name:"code",icon:oy}];function DP(t){return qQ.find(n=>n.name===t)?.icon||ly}function pye({value:t,onChange:e}){const[n,r]=w.useState(!1),i=DP(t);return a.jsxs("div",{className:"relative",children:[a.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:[a.jsx(i,{className:"w-5 h-5"}),a.jsx("span",{className:"text-sm text-bambu-gray flex-1 text-left",children:t})]}),n&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>r(!1)}),a.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:a.jsx("div",{className:"grid grid-cols-5 gap-1 p-2",children:qQ.map(({name:s,icon:o})=>a.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:a.jsx(o,{className:"w-5 h-5"})},s))})})]})]})}const PH=1144;function fye(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<PH:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${PH-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}let TO={},$Q=0;const Z3=new Set;function gye(t){const e={};for(const[n,r]of Object.entries(t)){if(!n||!r)continue;const i=n.replace("#","").toLowerCase().slice(0,6);i.length===6&&(e[i]=r)}TO=e,$Q+=1;for(const n of Array.from(Z3))n()}function bye(t){return Z3.add(t),()=>{Z3.delete(t)}}function TH(){return $Q}function AH(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),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,d=0;if(s!==o){const u=s-o;d=l>.5?u/(2-s-o):u/(s+o);const m=n/255,p=r/255,f=i/255;s===m?c=((p-f)/u+(p<f?6:0))/6:s===p?c=((f-m)/u+2)/6:c=((m-p)/u+4)/6}return c=c*360,l<.15?"Black":l>.85?"White":d<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c>=15&&c<45&&l<.45||c>=45&&c<70&&l<.4?"Brown":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 Zl(t){if(!t)return AH(t);const e=t.replace("#","").toLowerCase().substring(0,6),n=TO[e];return n||AH(t)}function FP(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(),r=TO[n];if(r)return r}return null}function AO(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),i=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return i===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${i})`}function VQ(t){if(!t||t.length<6)return!1;const e=t.replace("#",""),n=parseInt(e.slice(0,2),16),r=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);return(.299*n+.587*r+.114*i)/255>.6}function GQ(){return w.useSyncExternalStore(bye,TH,TH)}const WQ=w.createContext(void 0);function xye({children:t}){const[e,n]=w.useState(null),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!0),d=w.useRef(!1),u=w.useRef(!0),m=async()=>{try{const T=new URLSearchParams(window.location.search),F=T.get("token");if(F){mh(F,!1),T.delete("token");const D=T.toString(),H=window.location.pathname+(D?`?${D}`:"")+window.location.hash;window.history.replaceState({},"",H)}const k=await me.getAuthStatus();if(!u.current)return;if(i(k.auth_enabled),o(k.requires_setup),k.auth_enabled){const D=om();if(D)try{const H=await me.getCurrentUser();if(!u.current)return;n(H),F&&D===F&&mh(F,!0)}catch{if(mh(null),!u.current)return;n(null)}else n(null)}else n(null)}catch{if(!u.current)return;i(!1),n(null)}finally{u.current&&c(!1)}};w.useEffect(()=>(u.current=!0,m(),()=>{u.current=!1}),[]),w.useEffect(()=>{if(!l&&s&&!r){const T=window.location.pathname;T!=="/setup"&&!T.startsWith("/camera/")&&!d.current&&(d.current=!0,window.location.href="/setup")}else s||(d.current=!1)},[l,s,r]);const p=async(T,F)=>{const k=await me.login({username:T,password:F});return!k.requires_2fa&&k.access_token&&(mh(k.access_token),await m()),k},f=(T,F)=>{mh(T),n(F),i(!0)},x=()=>{mh(null),n(null),me.logout().catch(()=>{}),window.location.href="/login"},v=async()=>{if(r&&om())try{const T=await me.getCurrentUser();u.current&&n(T)}catch{mh(null),u.current&&n(null)}},g=async()=>{await m()},b=w.useMemo(()=>new Set(e?.permissions??[]),[e?.permissions]),_=w.useMemo(()=>r?e?.is_admin??!1:!0,[r,e?.is_admin]),C=w.useCallback(T=>!r||_?!0:b.has(T),[r,_,b]),P=w.useCallback((...T)=>!r||_?!0:T.some(F=>b.has(F)),[r,_,b]),N=w.useCallback((...T)=>!r||_?!0:T.every(F=>b.has(F)),[r,_,b]),A=w.useCallback((T,F,k)=>{if(!r||_)return!0;const D=`${T}:${F}_all`,H=`${T}:${F}_own`;return b.has(D)?!0:b.has(H)?k==null?!1:k===e?.id:!1},[r,_,b,e?.id]);return a.jsx(WQ.Provider,{value:{user:e,authEnabled:r,requiresSetup:s,loading:l,isAdmin:_,login:p,loginWithToken:f,logout:x,refreshUser:v,refreshAuth:g,hasPermission:C,hasAnyPermission:P,hasAllPermissions:N,canModify:A},children:t})}function wr(){const t=w.useContext(WQ);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function Co(t){if(!Number.isFinite(t)||t<=0)return"0 B";const e=["B","KB","MB","GB","TB"],n=1024,r=Math.floor(Math.log(t)/Math.log(n)),i=t/Math.pow(n,r);return r===0?`${i} ${e[r]}`:`${i.toFixed(1)} ${e[r]}`}const KQ=w.createContext(void 0);function bn(){const t=w.useContext(KQ);if(!t)throw new Error("useToast must be used within a ToastProvider");return t}const jH={success:a.jsx(xr,{className:"w-5 h-5 text-green-400"}),error:a.jsx(Na,{className:"w-5 h-5 text-red-400"}),warning:a.jsx(Wa,{className:"w-5 h-5 text-yellow-400"}),info:a.jsx(fs,{className:"w-5 h-5 text-blue-400"}),loading:a.jsx(dt,{className:"w-5 h-5 text-bambu-green animate-spin"})},yye={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 vye({children:t}){const{t:e}=Rt(),[n,r]=w.useState([]),[i,s]=w.useState(!1),[o,l]=w.useState(new Set),c=w.useRef(new Map),d="background-dispatch",u=w.useRef(null);w.useEffect(()=>{const v=c.current;return()=>{v.forEach(g=>clearTimeout(g)),v.clear()}},[]);const m=w.useCallback((v,g="success")=>{const b=Math.random().toString(36).substr(2,9);r(C=>[...C,{id:b,message:v,type:g}]);const _=setTimeout(()=>{r(C=>C.filter(P=>P.id!==b)),c.current.delete(b)},3e3);c.current.set(b,_)},[]),p=w.useCallback((v,g,b="info")=>{r(_=>_.find(P=>P.id===v)?_.map(P=>P.id===v?{...P,message:g,type:b,persistent:!0}:P):[..._,{id:v,message:g,type:b,persistent:!0}])},[]),f=w.useCallback(v=>{const g=c.current.get(v);g&&(clearTimeout(g),c.current.delete(v)),r(b=>b.filter(_=>_.id!==v))},[]),x=w.useCallback(async v=>{l(g=>{const b=new Set(g);return b.add(v),b});try{const g=await me.cancelBackgroundDispatchJob(v);m(g.status==="cancelling"?e("backgroundDispatch.toast.cancellingUpload"):e("backgroundDispatch.toast.cancelled"),"info")}catch(g){const b=g instanceof Error?g.message:e("backgroundDispatch.toast.cancelFailed");m(b,"error")}finally{l(g=>{const b=new Set(g);return b.delete(v),b})}},[m,e]);return w.useEffect(()=>{const v=(_,C,P)=>{const N=_.findIndex(T=>T.jobId===C);if(N===-1)return[..._,{jobId:C,...P}];const A=[..._];return A[N]={...A[N],...P},A},g=_=>{switch(_){case"failed":return 0;case"processing":return 1;case"dispatched":return 2;case"completed":return 3;case"cancelled":return 4}},b=_=>{const C=_.detail||{},P=C.total??0,N=C.dispatched??0,A=C.processing??0,T=C.completed??0,F=C.failed??0,k=N+A>0,D=P>0&&T+F>=P&&!k,H=C.recent_event?.status;if(H==="completed"&&T>0){const z=`first-complete:${T}:${F}`;if(u.current!==z){u.current=z;const X=P-T-F,L=X>0?e("backgroundDispatch.toast.printStartedRemaining",{completed:T,remaining:X}):F>0?e("backgroundDispatch.toast.completeWithFailures",{completed:T,failed:F}):e("backgroundDispatch.toast.completeSuccess",{completed:T});r(ee=>{const ue={id:d,message:L,type:F>0?"warning":"success",persistent:!0};return ee.find(oe=>oe.id===d)?ee.map(oe=>oe.id===d?ue:oe):[...ee,ue]});const ne=c.current.get(d);ne&&clearTimeout(ne);const ie=setTimeout(()=>{r(ee=>ee.filter(ue=>ue.id!==d)),c.current.delete(d),u.current=null},3e3);c.current.set(d,ie)}return}if(k){u.current=null,r(z=>{const L=z.find(ce=>ce.id===d)?.dispatchData?.jobs||[],ne=(C.dispatched_jobs||[]).map(ce=>({jobId:ce.job_id,sourceName:ce.source_name||e("backgroundDispatch.unknownFile"),printerName:ce.printer_name||e("backgroundDispatch.unknownPrinter"),status:"dispatched"})),ee=(C.active_jobs&&C.active_jobs.length>0?C.active_jobs:C.active_job?.job_id?[C.active_job]:[]).filter(ce=>typeof ce.job_id=="number").map(ce=>({jobId:ce.job_id,sourceName:ce.source_name||e("backgroundDispatch.unknownFile"),printerName:ce.printer_name||e("backgroundDispatch.unknownPrinter"),status:"processing",message:ce.message,uploadBytes:ce.upload_bytes,uploadTotalBytes:ce.upload_total_bytes,uploadProgressPct:ce.upload_progress_pct})),ue=new Set([...ne,...ee].map(ce=>ce.jobId)),le=L.filter(ce=>!ue.has(ce.jobId)&&["completed","failed","cancelled"].includes(ce.status));let oe=[...ne,...ee,...le];if(C.recent_event?.job_id&&C.recent_event?.status){const ce=C.recent_event.status,xe=ce==="cancelled"?"cancelled":ce==="cancelling"?"processing":ce,Ne=C.recent_event.source_name||e("backgroundDispatch.unknownFile"),$=C.recent_event.printer_name||e("backgroundDispatch.unknownPrinter");oe=v(oe,C.recent_event.job_id,{status:xe,sourceName:Ne,printerName:$,message:C.recent_event.message})}ee.forEach(ce=>{oe=v(oe,ce.jobId,{status:"processing",sourceName:ce.sourceName,printerName:ce.printerName,message:ce.message,uploadBytes:ce.uploadBytes,uploadTotalBytes:ce.uploadTotalBytes,uploadProgressPct:ce.uploadProgressPct})});const W={total:P,dispatched:N,processing:A,completed:T,failed:F,jobs:[...oe].sort((ce,xe)=>{const Ne=g(ce.status)-g(xe.status);return Ne!==0?Ne:ce.jobId-xe.jobId})};return z.find(ce=>ce.id===d)?z.map(ce=>ce.id===d?{...ce,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:W}:ce):[...z,{id:d,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:W}]});return}if(D){const z=`${T}:${F}`;if(u.current===z)return;u.current=z;const X=F>0?e("backgroundDispatch.toast.completeWithFailures",{completed:T,failed:F}):e("backgroundDispatch.toast.completeSuccess",{completed:T});r(ie=>{const ee={id:d,message:X,type:F>0?"warning":"success",persistent:!0};return ie.find(le=>le.id===d)?ie.map(le=>le.id===d?ee:le):[...ie,ee]});const L=c.current.get(d);L&&clearTimeout(L);const ne=setTimeout(()=>{r(ie=>ie.filter(ee=>ee.id!==d)),c.current.delete(d),u.current=null},3e3);c.current.set(d,ne);return}if(!k&&H&&["cancelled","failed","completed","idle"].includes(H)&&(r(z=>z.filter(X=>X.id!==d)),u.current=null),C.recent_event?.status==="idle"&&!k&&(r(z=>z.filter(X=>X.id!==d)),u.current=null),k||l(new Set),C.dispatched_jobs){const z=new Set(C.dispatched_jobs.map(X=>X.job_id));l(X=>{const L=new Set;return X.forEach(ne=>{z.has(ne)&&L.add(ne)}),L})}};return window.addEventListener("background-dispatch",b),()=>window.removeEventListener("background-dispatch",b)},[e]),a.jsxs(KQ.Provider,{value:{showToast:m,showPersistentToast:p,dismissToast:f},children:[t,a.jsx("div",{className:"fixed bottom-4 right-20 z-[60] flex flex-col items-end gap-2",children:n.map(v=>a.jsx("div",{className:`rounded-lg border shadow-lg backdrop-blur-sm animate-slide-in ${yye[v.type]} ${v.dispatchData?"w-[420px] p-3":"flex items-center gap-3 px-4 py-3"}`,children:v.dispatchData?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"flex items-start gap-2",children:[jH[v.type],a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:e("backgroundDispatch.startingPrints")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:e("backgroundDispatch.progressSummary",{complete:v.dispatchData.completed+v.dispatchData.failed,total:v.dispatchData.total,dispatched:v.dispatchData.dispatched,processing:v.dispatchData.processing})})]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s(g=>!g),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e(i?"backgroundDispatch.expandDetails":"backgroundDispatch.collapseDetails"),children:i?a.jsx(ac,{className:"w-4 h-4"}):a.jsx(Un,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(v.id),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e("backgroundDispatch.dismissToast"),children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),!i&&a.jsx("div",{className:"mt-3 space-y-2 max-h-64 overflow-y-auto pr-1",children:v.dispatchData.jobs.map(g=>{const b={dispatched:15,processing:60,completed:100,failed:100,cancelled:100},_={dispatched:"bg-bambu-gray/60",processing:"bg-bambu-green",completed:"bg-green-500",failed:"bg-red-500",cancelled:"bg-yellow-500"};return a.jsxs("div",{className:"rounded border border-white/10 bg-black/15 p-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-xs text-white truncate",title:g.sourceName,children:g.sourceName}),a.jsxs("div",{className:"flex items-center gap-2",children:[(g.status==="dispatched"||g.status==="processing")&&a.jsx("button",{onClick:()=>{x(g.jobId)},disabled:o.has(g.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(g.jobId)?e("backgroundDispatch.cancelling"):e("backgroundDispatch.cancel")}),a.jsx("span",{className:"text-[11px] uppercase tracking-wide text-bambu-gray",children:e(`backgroundDispatch.status.${g.status}`)})]})]}),a.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:g.printerName,children:g.printerName}),g.message&&a.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:g.message,children:g.message}),g.status==="processing"&&typeof g.uploadBytes=="number"&&typeof g.uploadTotalBytes=="number"&&g.uploadTotalBytes>0&&a.jsxs("div",{className:"text-[11px] text-bambu-gray truncate",children:[Co(g.uploadBytes)," / ",Co(g.uploadTotalBytes),typeof g.uploadProgressPct=="number"?` (${g.uploadProgressPct.toFixed(1)}%)`:""]}),a.jsx("div",{className:"mt-1 h-1.5 w-full rounded bg-white/10 overflow-hidden",children:a.jsx("div",{className:`h-full ${_[g.status]} transition-all duration-300`,style:{width:`${g.status==="processing"&&typeof g.uploadProgressPct=="number"?Math.max(0,Math.min(100,g.uploadProgressPct)):b[g.status]}%`}})})]},g.jobId)})})]}):a.jsxs(a.Fragment,{children:[jH[v.type],a.jsx("span",{className:"text-white text-sm",children:v.message}),a.jsx("button",{onClick:()=>f(v.id),className:"ml-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]})},v.id))})]})}function wye(t="system"){const e=t==="system"?XQ():t;switch(e){case"us":return"MM/DD/YYYY";case"eu":return"DD/MM/YYYY";case"iso":return"YYYY-MM-DD";default:return e}}function Sye(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 J3(t,e="system"){const n=String(t.getDate()).padStart(2,"0"),r=String(t.getMonth()+1).padStart(2,"0"),i=t.getFullYear();switch(e){case"us":return`${r}/${n}/${i}`;case"eu":return`${n}/${r}/${i}`;case"iso":return`${i}-${r}-${n}`;default:return t.toLocaleDateString()}}function MH(t,e="system"){const n=t.getHours(),r=String(t.getMinutes()).padStart(2,"0");switch(e){case"12h":{const i=n%12||12,s=n<12?"AM":"PM";return`${i}:${r} ${s}`}case"24h":return`${String(n).padStart(2,"0")}:${r}`;default:return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function _ye(t){for(const e of["/",".","-"]){const n=t.split(e);if(n.length===3)return n}return null}function XQ(){const t=new Date(2e3,11,31).toLocaleDateString();return t.startsWith("12")?"us":t.startsWith("31")?"eu":"iso"}function kye(t,e="system"){if(!t)return null;const n=_ye(t);if(!n)return null;const r=e==="system"?XQ():e;let i,s,o;switch(r){case"us":s=parseInt(n[0],10),i=parseInt(n[1],10),o=parseInt(n[2],10);break;case"eu":i=parseInt(n[0],10),s=parseInt(n[1],10),o=parseInt(n[2],10);break;case"iso":o=parseInt(n[0],10),s=parseInt(n[1],10),i=parseInt(n[2],10);break}return isNaN(i)||isNaN(s)||isNaN(o)||s<1||s>12||i<1||i>31||o<1900||o>2100?null:new Date(o,s-1,i)}function Nye(t){if(!t)return null;const n=t.trim().match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);if(!n)return null;let r=parseInt(n[1],10);const i=parseInt(n[2],10),s=n[3]?.toUpperCase();return s==="PM"&&r<12&&(r+=12),s==="AM"&&r===12&&(r=0),r<0||r>23||i<0||i>59?null:{hours:r,minutes:i}}function eF(t){const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),i=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}-${n}-${r}T${i}:${s}`}function q0(t,e="system"){return e==="12h"?t.hour12=!0:e==="24h"&&(t.hour12=!1),t}function er(t){return t?t.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(t)?new Date(t):new Date(t+"Z"):null}function Qf(t,e){const n=er(t);if(!n)return"";const r={year:"numeric",month:"short",day:"numeric"};return n.toLocaleDateString(void 0,e??r)}function Zf(t,e="system",n){const r=er(t);if(!r)return"";const s=q0(n??{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},e);return r.toLocaleString(void 0,s)}function YQ(t,e="system",n){const i=q0({...{hour:"2-digit",minute:"2-digit"},...n},e);return t.toLocaleTimeString([],i)}function jO(t,e="system",n){const r=new Date,i=new Date(r.getTime()+t*60*1e3),s=new Date(r);s.setHours(0,0,0,0);const o=new Date(i);o.setHours(0,0,0,0);const l=q0({hour:"2-digit",minute:"2-digit"},e),c=i.toLocaleTimeString([],l),d=Math.floor((o.getTime()-s.getTime())/864e5);return d===0?c:d===1?`${n?.("common.tomorrow")??"Tomorrow"} ${c}`:`${i.toLocaleDateString([],{weekday:"short"})} ${c}`}function ps(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 Gh(t,e="system",n){if(!t)return n?.("time.unknown")??"-";const r=er(t);if(!r)return n?.("time.unknown")??"-";const i=new Date,s=r.getTime()-i.getTime(),o=s<0,l=Math.abs(s),c=Math.floor(l/6e4),d=Math.floor(l/36e5),u=Math.floor(l/864e5);return c<1?o?n?.("time.justNow")??"Just now":n?.("time.now")??"Now":d<1?o?n?.("time.minsAgo",{count:c})??`${c}m ago`:n?.("time.inMins",{count:c})??`in ${c}m`:u<1?o?n?.("time.hoursAgo",{count:d})??`${d}h ago`:n?.("time.inHours",{count:d})??`in ${d}h`:u<7?o?n?.("time.daysAgo",{count:u})??`${u}d ago`:n?.("time.inDays",{count:u})??`in ${u}d`:Zf(t,e)}function ph(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function Cye(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`}const yM=1920,Pye=.7,Tye=300;function Aye(t){return new Promise((e,n)=>{const r=new Image;r.onload=()=>{let{width:i,height:s}=r;if(i>yM||s>yM){const d=yM/Math.max(i,s);i=Math.round(i*d),s=Math.round(s*d)}const o=document.createElement("canvas");o.width=i,o.height=s;const l=o.getContext("2d");if(!l){n(new Error("No canvas context"));return}l.drawImage(r,0,0,i,s);const c=o.toDataURL("image/jpeg",Pye);e(c.replace(/^data:[^;]+;base64,/,""))},r.onerror=n,r.src=URL.createObjectURL(t)})}function jye(t){const e=Math.floor(t/60),n=t%60;return`${e.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}function Mye(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState("form"),[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(null),[m,p]=w.useState(!1),[f,x]=w.useState(null),[v,g]=w.useState(null),[b,_]=w.useState(""),[C,P]=w.useState(0),[N,A]=w.useState(!1),T=w.useRef(null),F=w.useRef(null),k=w.useRef(()=>{});w.useEffect(()=>{if(r!=="logging")return;if(C>=Tye){k.current();return}const oe=setTimeout(()=>P(W=>W+1),1e3);return()=>clearTimeout(oe)},[r,C]);const D=()=>{n(!0),i("form"),o(""),c(""),u(null),x(null),g(null),_(""),P(0),A(!1)},H=()=>{n(!1)},z=w.useCallback(async oe=>{if(oe.type.startsWith("image/"))try{const W=await Aye(oe);u(W)}catch{}},[]),X=w.useCallback(oe=>{const W=oe.clipboardData?.items;if(W){for(const re of W)if(re.type.startsWith("image/")){const ce=re.getAsFile();ce&&z(ce);break}}},[z]),L=w.useCallback(oe=>{oe.preventDefault(),p(!0)},[]),ne=w.useCallback(oe=>{oe.preventDefault(),p(!1)},[]),ie=w.useCallback(oe=>{oe.preventDefault(),p(!1);const W=oe.dataTransfer.files?.[0];W&&z(W)},[z]),ee=async()=>{if(s.trim())try{const oe=await xM.startLogging();A(oe.was_debug),P(0),i("logging")}catch(oe){_(oe instanceof Error?oe.message:t("bugReport.unexpectedError")),i("error")}},ue=async()=>{i("stopping");try{const oe=await xM.stopLogging(N);await le(oe.logs)}catch(oe){_(oe instanceof Error?oe.message:t("bugReport.unexpectedError")),i("error")}};k.current=ue;const le=async oe=>{i("submitting");try{const W=await xM.submit({description:s.trim(),email:l.trim()||void 0,screenshot_base64:d||void 0,include_support_info:!0,debug_logs:oe||void 0});W.success?(x(W.issue_url||null),g(W.issue_number||null),i("success")):(_(W.message),i("error"))}catch(W){_(W instanceof Error?W.message:t("bugReport.unexpectedError")),i("error")}};return a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:D,className:"fixed bottom-4 right-4 z-40 w-12 h-12 rounded-full bg-red-500 hover:bg-red-600 text-white shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-110 flex items-center justify-center",title:t("bugReport.title"),children:a.jsx(Px,{className:"w-5 h-5"})}),e&&a.jsx("div",{id:"bug-report-modal",className:"fixed bottom-20 right-4 z-50 w-full max-w-md",onPaste:X,children:a.jsxs("div",{ref:T,className:"bg-white dark:bg-gray-800 rounded-lg shadow-2xl border border-gray-200 dark:border-gray-700 max-h-[80vh] overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10",children:[a.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2",children:[a.jsx(Px,{className:"w-5 h-5 text-red-500"}),t("bugReport.title")]}),a.jsx("button",{onClick:H,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[r==="form"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t("bugReport.description")," *"]}),a.jsx("textarea",{value:s,onChange:oe=>o(oe.target.value),placeholder:t("bugReport.descriptionPlaceholder"),rows:3,className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.email")}),a.jsx("input",{type:"email",value:l,onChange:oe=>c(oe.target.value),placeholder:t("bugReport.emailPlaceholder"),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),a.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:t("bugReport.emailPrivacy")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.screenshot")}),d?a.jsxs("div",{className:"relative",children:[a.jsx("img",{src:`data:image/jpeg;base64,${d}`,alt:t("bugReport.screenshot"),className:"w-full max-h-40 object-contain rounded-lg border border-gray-200 dark:border-gray-600"}),a.jsx("button",{onClick:()=>u(null),className:"absolute top-2 right-2 p-1 bg-red-500 hover:bg-red-600 text-white rounded-full shadow",title:t("common.delete"),children:a.jsx(rn,{className:"w-3 h-3"})})]}):a.jsxs("button",{type:"button",onClick:()=>F.current?.click(),onDragOver:L,onDragLeave:ne,onDrop:ie,className:`w-full flex flex-col items-center gap-2 px-4 py-4 border-2 border-dashed rounded-lg transition-colors cursor-pointer ${m?"border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-500":"border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400 dark:hover:border-gray-500 hover:text-gray-600 dark:hover:text-gray-300"}`,children:[a.jsx(Ma,{className:"w-5 h-5"}),a.jsx("span",{className:"text-sm",children:t("bugReport.uploadOrPaste")})]}),a.jsx("input",{ref:F,type:"file",accept:"image/*",className:"hidden",onChange:oe=>{const W=oe.target.files?.[0];W&&z(W),oe.target.value=""}})]}),a.jsxs("details",{className:"text-xs bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:[a.jsx("summary",{className:"cursor-pointer font-medium text-amber-700 dark:text-amber-300 hover:text-amber-800 dark:hover:text-amber-200",children:t("bugReport.dataCollectedSummary")}),a.jsxs("div",{className:"mt-2 space-y-2 pl-2 border-l-2 border-amber-300 dark:border-amber-700 text-amber-800 dark:text-amber-200",children:[a.jsx("p",{className:"font-medium",children:t("bugReport.dataIncluded")}),a.jsx("p",{children:t("bugReport.dataIncludedList")}),a.jsx("p",{className:"font-medium",children:t("bugReport.dataNeverIncluded")}),a.jsx("p",{children:t("bugReport.dataNeverIncludedList")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx("button",{onClick:H,className:"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",children:t("common.cancel")}),a.jsx("button",{onClick:ee,disabled:!s.trim(),className:"px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors",children:t("bugReport.startLogging")})]})]}),r==="logging"&&a.jsxs("div",{className:"py-6 space-y-6",children:[a.jsxs("div",{className:"space-y-3 px-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(nl,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),a.jsx("span",{className:"text-sm text-green-700 dark:text-green-400",children:t("bugReport.stepEnableLogging")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"relative flex h-5 w-5 flex-shrink-0 items-center justify-center",children:[a.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),a.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-blue-500"})]}),a.jsx("span",{className:"text-sm font-medium text-blue-700 dark:text-blue-300",children:t("bugReport.stepReproduce")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(U0,{className:"w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0"}),a.jsx("span",{className:"text-sm text-gray-400 dark:text-gray-500",children:t("bugReport.stepStopLogging")})]})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("p",{className:"text-3xl font-mono text-blue-500",children:jye(C)}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:t("bugReport.maxDuration",{minutes:5})})]}),a.jsx("div",{className:"flex justify-center",children:a.jsx("button",{onClick:ue,className:"px-6 py-2.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors",children:t("bugReport.stopAndSubmit")})})]}),(r==="stopping"||r==="submitting")&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(dt,{className:"w-8 h-8 animate-spin text-blue-500"}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t(r==="stopping"?"bugReport.stoppingLogs":"bugReport.submitting")})]}),r==="success"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(xr,{className:"w-12 h-12 text-green-500"}),a.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.thankYou")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("bugReport.submitted")}),f&&a.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-500 hover:text-blue-600 underline",children:[t("bugReport.viewIssue")," #",v]}),a.jsx("button",{onClick:H,className:"mt-4 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",children:t("common.close")})]}),r==="error"&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[a.jsx(Wa,{className:"w-12 h-12 text-red-500"}),a.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.submitFailed")}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center",children:b}),a.jsxs("div",{className:"flex gap-2 mt-4",children:[a.jsx("button",{onClick:()=>i("form"),className:"px-4 py-2 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-lg transition-colors",children:t("bugReport.submit")}),a.jsx("button",{onClick:H,className:"px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors",children:t("common.close")})]})]})]})]})})]})}const zu=[{id:"printers",to:"/",icon:Ar,labelKey:"nav.printers"},{id:"archives",to:"/archives",icon:Qs,labelKey:"nav.archives"},{id:"queue",to:"/queue",icon:Yr,labelKey:"nav.queue"},{id:"stats",to:"/stats",icon:Hpe,labelKey:"nav.stats"},{id:"profiles",to:"/profiles",icon:sy,labelKey:"nav.profiles"},{id:"maintenance",to:"/maintenance",icon:Yf,labelKey:"nav.maintenance"},{id:"projects",to:"/projects",icon:Es,labelKey:"nav.projects"},{id:"inventory",to:"/inventory",icon:Dfe,labelKey:"nav.inventory"},{id:"files",to:"/files",icon:Uc,labelKey:"nav.files"},{id:"notifications",to:"/notifications",icon:Uh,labelKey:"nav.notifications"},{id:"settings",to:"/settings",icon:Hw,labelKey:"nav.settings"}];function Eye(){const t=localStorage.getItem("sidebarOrder");if(t)try{return JSON.parse(t)}catch{return zu.map(e=>e.id)}return zu.map(e=>e.id)}function EH(t){localStorage.setItem("sidebarOrder",JSON.stringify(t))}function F_(t){return t.startsWith("ext-")}function QQ(){return localStorage.getItem("defaultView")||"/"}function Dye(t){localStorage.setItem("defaultView",t)}function Fye(){const t=Do(),e=$c(),{mode:n,toggleMode:r}=wg(),{t:i}=Rt(),s=fye();GQ();const{user:o,authEnabled:l,logout:c,hasPermission:d}=wr(),{showToast:u}=bn(),[m,p]=w.useState(!1),[f,x]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[v,g]=w.useState(!1),[b,_]=w.useState(()=>localStorage.getItem("sidebarExpanded")!=="false"),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(!1),[k,D]=w.useState(Eye),[H,z]=w.useState(null),[X,L]=w.useState(null),ne=w.useRef(!1),[ie,ee]=w.useState(()=>sessionStorage.getItem("dismissedUpdateVersion")),[ue,le]=w.useState(null),{data:oe}=Qe({queryKey:["version"],queryFn:me.getVersion,staleTime:1/0}),{data:W}=Qe({queryKey:["settings"],queryFn:me.getSettings,staleTime:300*1e3}),{data:re}=Qe({queryKey:["default-sidebar-order"],queryFn:me.getDefaultSidebarOrder,staleTime:300*1e3});w.useEffect(()=>{const ve=re?.default_sidebar_order;if(!ve||l&&!o)return;const je=o?`sidebarDefaultApplied_${o.id}`:"sidebarDefaultApplied";if(!localStorage.getItem(je))try{const Re=JSON.parse(ve),Ee=Array.isArray(Re)?Re:Re.order;if(!Array.isArray(Ee)||Ee.length===0)return;const Te=new Set(zu.map(Be=>Be.id)),Me=Ee.filter(Be=>typeof Be=="string"&&(Te.has(Be)||F_(Be)));Me.length>0&&(D(Me),EH(Me),localStorage.setItem(je,"1"))}catch(Re){console.error("Failed to apply default sidebar order:",Re)}},[re?.default_sidebar_order,D,o,l]);const{data:ce}=Qe({queryKey:["advancedAuthStatus"],queryFn:me.getAdvancedAuthStatus,staleTime:300*1e3,enabled:l}),{data:xe}=Qe({queryKey:["updateCheck"],queryFn:me.checkForUpdates,enabled:W?.check_updates!==!1,staleTime:3600*1e3,refetchInterval:3600*1e3}),{data:Ne}=Qe({queryKey:["external-links"],queryFn:me.getExternalLinks}),{data:$}=Qe({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs,staleTime:30*1e3}),Y=$?.some(ve=>ve.show_in_switchbar)??!1,{data:E}=Qe({queryKey:["debugLogging"],queryFn:ux.getDebugLoggingState,staleTime:60*1e3,refetchInterval:60*1e3}),{data:j}=Qe({queryKey:["developer-mode-warnings"],queryFn:me.getDeveloperModeWarnings,staleTime:10*1e3,refetchInterval:30*1e3,refetchOnWindowFocus:!0}),{data:O}=Qe({queryKey:["queue","pending"],queryFn:()=>me.getQueue(void 0,"pending"),staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),K=O?.length??0,{data:B}=Qe({queryKey:["pending-uploads","count"],queryFn:Xb.getCount,staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),he=B?.count??0,I=w.useMemo(()=>{const ve=new Set;return O?.forEach(je=>{je.printer_id&&ve.add(je.printer_id)}),Array.from(ve)},[O]),Q=fp({queries:I.map(ve=>({queryKey:["printerStatus",ve],queryFn:()=>me.getPrinterStatus(ve),staleTime:30*1e3}))}).some(ve=>{const je=ve.data;return je?!!je.awaiting_plate_clear:!1}),[G,J]=w.useState(null);w.useEffect(()=>{if(!E?.enabled||!E.enabled_at){J(null);return}const ve=er(E.enabled_at)?.getTime()??Date.now(),je=()=>{J(Math.floor((Date.now()-ve)/1e3))};je();const Re=setInterval(je,1e3);return()=>clearInterval(Re)},[E?.enabled,E?.enabled_at]);const se=w.useMemo(()=>new Map(zu.map(ve=>[ve.id,ve])),[]),fe=w.useMemo(()=>new Map((Ne||[]).map(ve=>[`ext-${ve.id}`,ve])),[Ne]),pe=(()=>{const ve=[],je=new Set,Re={archives:"archives:read",queue:"queue:read",stats:"stats:read",profiles:"kprofiles:read",maintenance:"maintenance:read",projects:"projects:read",inventory:"inventory:read",files:"library:read",settings:"settings:read",notifications:"notifications:user_email"},Ee=Te=>!!(l&&Te in Re&&!d(Re[Te])||Te==="notifications"&&(!l||!ce?.advanced_auth_enabled||W?.user_notifications_enabled===!1));for(const Te of k)Ee(Te)||(se.has(Te)||fe.has(Te))&&(ve.push(Te),je.add(Te));for(const Te of zu)Ee(Te.id)||je.has(Te.id)||(ve.push(Te.id),je.add(Te.id));for(const Te of Ne||[]){const Me=`ext-${Te.id}`;je.has(Me)||(ve.push(Me),je.add(Me))}return ve})(),de=(ve,je)=>{z(je),ve.dataTransfer.effectAllowed="move",ve.dataTransfer.setData("text/plain",je)},U=(ve,je)=>{ve.preventDefault(),ve.dataTransfer.dropEffect="move",L(je)},R=()=>{L(null)},ae=(ve,je)=>{if(ve.preventDefault(),H===null||H===je){z(null),L(null);return}const Re=[...pe],Ee=Re.indexOf(H),Te=Re.indexOf(je);if(Ee===-1||Te===-1){z(null),L(null);return}Re.splice(Ee,1),Re.splice(Te,0,H),D(Re),EH(Re),z(null),L(null)},_e=()=>{z(null),L(null)},Se=xe?.update_available&&xe.latest_version&&xe.latest_version!==ie,ye=()=>{xe?.latest_version&&(sessionStorage.setItem("dismissedUpdateVersion",xe.latest_version),ee(xe.latest_version))};w.useEffect(()=>{if(!ne.current&&e.pathname==="/"){const ve=QQ();ve!=="/"&&(ne.current=!0,t(ve,{replace:!0}))}},[e.pathname,t]),w.useEffect(()=>{localStorage.setItem("sidebarExpanded",String(b))},[b]),w.useEffect(()=>{s&&P(!1)},[e.pathname,s]),w.useEffect(()=>{const ve=je=>{if(!d("printers:control"))return;const Re=je.detail;le({printer_id:Re.printer_id,printer_name:Re.printer_name,message:Re.message})};return window.addEventListener("plate-not-empty",ve),()=>window.removeEventListener("plate-not-empty",ve)},[d]);const Ae=w.useCallback(ve=>{const je=ve.target;if(!(je.tagName==="INPUT"||je.tagName==="TEXTAREA"||je.isContentEditable)&&!ve.metaKey&&!ve.ctrlKey&&!ve.altKey){const Re=parseInt(ve.key);if(Re>=1&&Re<=pe.length&&Re<=9){const Ee=pe[Re-1];if(ve.preventDefault(),F_(Ee)){const Te=fe.get(Ee);if(Te?.open_in_new_tab)window.open(Te.url,"_blank","noopener,noreferrer");else{const Me=Ee.replace("ext-","");t(`/external/${Me}`)}}else{const Te=se.get(Ee);Te&&t(Te.to)}return}switch(ve.key){case"?":ve.preventDefault(),A(!0);break;case"Escape":A(!1);break}}},[t,pe,se,fe]);return w.useEffect(()=>(document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)),[Ae]),a.jsxs("div",{className:"flex min-h-screen",children:[s&&a.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:[a.jsx("button",{onClick:()=>P(!0),className:"p-2 -ml-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors","aria-label":"Open menu",children:a.jsx(hbe,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-8 ml-3"})]}),s&&C&&a.jsx("div",{className:"fixed inset-0 bg-black/60 z-40 transition-opacity",onClick:()=>P(!1)}),a.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 ${C?"translate-x-0":"-translate-x-full"}`:`fixed inset-y-0 left-0 z-30 ${b?"w-64":"w-16"}`}`,children:[a.jsx("div",{className:`border-b border-bambu-dark-tertiary flex items-center justify-center ${s||b?"p-4":"p-2"}`,children:a.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:s||b?"h-16 w-auto":"h-8 w-8 object-cover object-left"})}),a.jsx("nav",{className:"flex-1 p-2 overflow-y-auto",children:a.jsx("ul",{className:"space-y-2",children:pe.map(ve=>{if(F_(ve)){const Re=fe.get(ve);if(!Re)return null;const Ee=Re.custom_icon?null:DP(Re.icon);return a.jsx("li",{draggable:!0,onDragStart:Te=>de(Te,ve),onDragOver:Te=>U(Te,ve),onDragLeave:R,onDrop:Te=>ae(Te,ve),onDragEnd:_e,className:`relative ${H===ve?"opacity-50":""} ${X===ve&&H!==ve?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:Re.open_in_new_tab?a.jsxs("a",{href:Re.url,target:"_blank",rel:"noopener noreferrer",className:`flex items-center ${s||b?"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&&!b?Re.name:void 0,children:[b&&!s&&a.jsx($h,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Re.custom_icon?a.jsx("img",{src:me.getExternalLinkIconUrl(Re.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Ee&&a.jsx(Ee,{className:"w-5 h-5 flex-shrink-0"}),(s||b)&&a.jsx("span",{children:Re.name})]}):a.jsxs(nx,{to:`/external/${Re.id}`,className:({isActive:Te})=>`flex items-center ${s||b?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Te?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!b?Re.name:void 0,children:[b&&!s&&a.jsx($h,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Re.custom_icon?a.jsx("img",{src:me.getExternalLinkIconUrl(Re.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Ee&&a.jsx(Ee,{className:"w-5 h-5 flex-shrink-0"}),(s||b)&&a.jsx("span",{children:Re.name})]})},ve)}else{const Re=se.get(ve);if(!Re)return null;const{to:Ee,icon:Te,labelKey:Me}=Re,Be=ve==="queue"&&K>0,Ke=ve==="archives"&&he>0,tt=Be?K:Ke?he:0,te=Be||Ke,Ie=ve==="printers"&&Q;return a.jsx("li",{draggable:!0,onDragStart:be=>de(be,ve),onDragOver:be=>U(be,ve),onDragLeave:R,onDrop:be=>ae(be,ve),onDragEnd:_e,className:`relative ${H===ve?"opacity-50":""} ${X===ve&&H!==ve?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:a.jsxs(nx,{to:Ee,className:({isActive:be})=>`flex items-center ${s||b?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${be?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!b?i(Me):void 0,children:[b&&!s&&a.jsx($h,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),a.jsxs("div",{className:"relative",children:[a.jsx(Te,{className:"w-5 h-5 flex-shrink-0"}),Ie&&a.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-yellow-500 rounded-full border-2 border-bambu-dark-secondary"}),te&&a.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 ${Ke?"bg-blue-500 text-white":"bg-yellow-500 text-black"}`,children:tt>99?"99+":tt})]}),(s||b)&&a.jsx("span",{children:i(Me)})]})},ve)}})})}),!s&&a.jsx("button",{onClick:()=>_(!b),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:i(b?"nav.collapseSidebar":"nav.expandSidebar"),children:b?a.jsx(dl,{className:"w-5 h-5"}):a.jsx(Ka,{className:"w-5 h-5"})}),a.jsx("div",{className:"flex-shrink-0 p-2 border-t border-bambu-dark-tertiary",children:s||b?a.jsxs("div",{className:"flex flex-col gap-2 px-2",children:[a.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[Y&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{onMouseEnter:()=>F(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${T?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:a.jsx(Ql,{className:"w-5 h-5"})}),T&&a.jsx(CH,{onClose:()=>F(!1)})]}),d("system:read")?a.jsx(nx,{to:"/system",className:({isActive:ve})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ve?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:a.jsx(fs,{className:"w-5 h-5"})}):a.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:a.jsx(fs,{className:"w-5 h-5"})}),a.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:i("nav.viewOnGithub"),children:a.jsx(V3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:()=>A(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.keyboardShortcuts"),children:a.jsx(G3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?a.jsx(_H,{className:"w-5 h-5"}):a.jsx(dN,{className:"w-5 h-5"})}),l&&o&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>p(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("changePassword.title"),children:a.jsx(Ws,{className:"w-5 h-5"})}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.logout",{defaultValue:"Logout"}),children:a.jsx(K3,{className:"w-5 h-5"})})]})]}),a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:["v",oe?.version||"..."]}),xe?.update_available&&a.jsxs("button",{onClick:()=>t("/settings"),className:"flex items-center gap-1 text-xs text-bambu-green hover:text-bambu-green/80 transition-colors",title:i("nav.updateAvailable",{version:xe.latest_version}),children:[a.jsx(gM,{className:"w-4 h-4"}),a.jsx("span",{children:i("nav.update")})]})]})]}):a.jsxs("div",{className:"flex flex-col items-center gap-1 overflow-y-auto max-h-[50vh]",children:[xe?.update_available&&a.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:i("nav.updateAvailable",{version:xe.latest_version}),children:a.jsx(gM,{className:"w-5 h-5"})}),Y&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{onMouseEnter:()=>F(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${T?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:a.jsx(Ql,{className:"w-5 h-5"})}),T&&a.jsx(CH,{onClose:()=>F(!1)})]}),d("system:read")?a.jsx(nx,{to:"/system",className:({isActive:ve})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ve?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:a.jsx(fs,{className:"w-5 h-5"})}):a.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:a.jsx(fs,{className:"w-5 h-5"})}),a.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:i("nav.viewOnGithub"),children:a.jsx(V3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:()=>A(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.keyboardShortcuts"),children:a.jsx(G3,{className:"w-5 h-5"})}),a.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?a.jsx(_H,{className:"w-5 h-5"}):a.jsx(dN,{className:"w-5 h-5"})}),l&&o&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>p(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("changePassword.title"),children:a.jsx(Ws,{className:"w-5 h-5"})}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:i("nav.logout",{defaultValue:"Logout"}),children:a.jsx(K3,{className:"w-5 h-5"})})]})]})})]}),a.jsxs("main",{className:`flex-1 bg-bambu-dark overflow-auto transition-all duration-300 ${s?"mt-14":b?"ml-64":"ml-16"}`,children:[E?.enabled&&a.jsx("div",{className:"bg-amber-500/20 border-b border-amber-500/30 px-4 py-2 flex items-center justify-between",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Px,{className:"w-4 h-4 text-amber-500 animate-pulse"}),a.jsxs("span",{className:"text-amber-200",children:[i("support.debugLoggingActive",{defaultValue:"Debug logging is active"}),G!==null&&a.jsxs("span",{className:"text-amber-300/70 ml-2",children:["(",Math.floor(G/60),"m ",G%60,"s)"]})]}),a.jsx("button",{onClick:()=>t("/system"),className:"text-amber-400 hover:text-amber-300 font-medium underline ml-2",children:i("support.manageLogs",{defaultValue:"Manage"})})]})}),j&&j.length>0&&a.jsx("div",{className:"bg-orange-500/20 border-b border-orange-500/30 px-4 py-2 flex items-center justify-between",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(txe,{className:"w-4 h-4 text-orange-500"}),a.jsx("span",{className:"text-orange-200",children:i("printers.developerModeWarning",{names:j.map(ve=>ve.name).join(", "),defaultValue:`Developer LAN mode is not enabled on: ${j.map(ve=>ve.name).join(", ")}. Some features may not work.`})}),a.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:i("printers.howToEnable",{defaultValue:"How to enable"})})]})}),Se&&a.jsxs("div",{className:"bg-bambu-green/20 border-b border-bambu-green/30 px-4 py-2 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(gM,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{children:i("nav.updateAvailableBanner",{version:xe?.latest_version,defaultValue:`Version ${xe?.latest_version} is available!`})}),a.jsx("button",{onClick:()=>t("/settings"),className:"text-bambu-green hover:text-bambu-green/80 font-medium underline",children:i("nav.viewUpdate",{defaultValue:"View update"})})]}),a.jsx("button",{onClick:ye,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:i("common.dismiss",{defaultValue:"Dismiss"}),children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsx(nQ,{})]}),N&&a.jsx(mye,{onClose:()=>A(!1),sidebarItems:pe.map(ve=>{if(F_(ve)){const je=fe.get(ve);return je?{type:"external",label:je.name}:null}else{const je=se.get(ve);return je?{type:"nav",label:je.labelKey,labelKey:je.labelKey}:null}}).filter(Boolean)}),ue&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4",children:a.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:a.jsxs("div",{className:"p-6 text-center",children:[a.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-10 h-10 text-yellow-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.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"})})}),a.jsx("h2",{className:"text-xl font-bold text-yellow-400 mb-2",children:i("plateAlert.title")}),a.jsx("p",{className:"text-lg text-white mb-2",children:ue.printer_name}),a.jsx("p",{className:"text-bambu-gray mb-6",children:i("plateAlert.message")}),a.jsx("button",{onClick:()=>le(null),className:"w-full py-3 px-6 bg-yellow-500 hover:bg-yellow-600 text-black font-semibold rounded-lg transition-colors",children:i("plateAlert.understand")})]})})}),m&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{p(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(At,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ws,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("changePassword.title")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{p(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Mt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.currentPassword")}),a.jsx("input",{type:"password",value:f.currentPassword,onChange:ve=>x({...f,currentPassword:ve.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:i("changePassword.currentPasswordPlaceholder"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.newPassword")}),a.jsx("input",{type:"password",value:f.newPassword,onChange:ve=>x({...f,newPassword:ve.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:i("changePassword.newPasswordPlaceholder"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.confirmPassword")}),a.jsx("input",{type:"password",value:f.confirmPassword,onChange:ve=>x({...f,confirmPassword:ve.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 ${f.confirmPassword&&f.newPassword!==f.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("changePassword.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),f.confirmPassword&&f.newPassword!==f.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("changePassword.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{p(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),a.jsx(Fe,{onClick:async()=>{if(f.newPassword!==f.confirmPassword){u(i("changePassword.passwordsDoNotMatch"),"error");return}if(f.newPassword.length<6){u(i("changePassword.passwordTooShort"),"error");return}g(!0);try{await me.changePassword(f.currentPassword,f.newPassword),u(i("changePassword.success"),"success"),p(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ve){const je=ve instanceof Error?ve.message:i("changePassword.failed");u(je,"error")}finally{g(!1)}},disabled:v||!f.currentPassword||!f.newPassword||f.newPassword!==f.confirmPassword||f.newPassword.length<6,children:v?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("changePassword.changing")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ws,{className:"w-4 h-4"}),i("changePassword.title")]})})]})]})]})}),a.jsx(Mye,{})]})}const tF={"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 Rye(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:Rn};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:Rn};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:Wa};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:fs}}}function nF(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 Uu(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,r=nF(e.attr,n);return tF[r]!==void 0})}function Lye(){return"https://wiki.bambulab.com/en/hms/home"}function Oye({printerName:t,errors:e,onClose:n,printerId:r,hasPermission:i}){const{t:s}=Rt(),{showToast:o}=bn(),l=it({mutationFn:()=>me.clearHMSErrors(r),onSuccess:()=>{o(s("hmsErrors.clearSuccess"),"success"),n()},onError:()=>{o(s("hmsErrors.clearFailed"),"error")}}),c=e.filter(d=>{const u=parseInt(d.code.replace("0x",""),16)||0,m=nF(d.attr,u);return tF[m]!==void 0});return w.useEffect(()=>{const d=u=>{u.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Rn,{className:"w-5 h-5 text-orange-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Wa,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{children:s("hmsErrors.noErrors")})]}):a.jsx("div",{className:"space-y-3",children:c.map((d,u)=>{const{label:m,color:p,bgColor:f,Icon:x}=Rye(d.severity),v=parseInt(d.code.replace("0x",""),16)||0,g=nF(d.attr,v),b=tF[g],_=Lye(),C=g.replace("_","-");return a.jsx("div",{className:`p-4 rounded-lg ${f} border border-white/10`,children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(x,{className:`w-5 h-5 ${p} flex-shrink-0 mt-0.5`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`font-mono text-sm ${p}`,children:["[",C,"]"]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${f} ${p}`,children:m})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:b}),a.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[a.jsx(na,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${d.code}-${u}`)})})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&a.jsxs("button",{onClick:()=>l.mutate(),disabled:!i("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?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}const Iye=[{key:"printing",dot:"bg-bambu-green"},{key:"paused",dot:"bg-status-warning"},{key:"finished",dot:"bg-blue-400"},{key:"idle",dot:"bg-bambu-green"},{key:"error",dot:"bg-status-error"},{key:"offline",dot:"bg-gray-400"}];function zye({selectedIds:t,printers:e,onClose:n,onSelectAll:r,onSelectByLocation:i,onSelectByState:s,onAction:o,actionPending:l}){const{t:c}=Rt(),{hasPermission:d}=wr(),u=sn(),[m,p]=w.useState(!1),[f,x]=w.useState(!1),v=Array.from(t).map(D=>({id:D,status:u.getQueryData(["printerStatus",D])})),g=v.some(({status:D})=>D?.connected&&D.state==="RUNNING"),b=v.some(({status:D})=>D?.connected&&D.state==="PAUSE"),_=g||b,C=v.some(({status:D})=>!!(D?.connected&&D.awaiting_plate_clear)),P=v.some(({status:D})=>!D?.connected||!D.hms_errors?!1:Uu(D.hms_errors).length>0),N=d("printers:control"),A=d("printers:clear_plate"),T=[...new Set(e.map(D=>D.location).filter(D=>!!D))].sort(),F={printing:0,paused:0,finished:0,idle:0,error:0,offline:0};e.forEach(D=>{const H=u.getQueryData(["printerStatus",D.id]);if(!H||!H.connected){F.offline++;return}switch(H.hms_errors&&Uu(H.hms_errors).length>0&&F.error++,H.state){case"RUNNING":F.printing++;break;case"PAUSE":F.paused++;break;case"FINISH":F.finished++;break;case"FAILED":F.error++;break;default:F.idle++;break}});const k={printing:c("printers.status.printing"),paused:c("printers.status.paused","Paused"),finished:c("printers.status.finished","Finished"),idle:c("printers.status.available"),error:c("printers.status.problem"),offline:c("printers.status.offline")};return a.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-3 flex-wrap",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:n,children:a.jsx(Bt,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-white font-medium text-sm",children:c("printers.bulk.selected",{count:t.size})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:r,children:c("printers.bulk.selectAll")}),a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>{x(!f),p(!1)},children:[c("printers.bulk.selectByState"),a.jsx(Un,{className:`w-3 h-3 transition-transform ${f?"rotate-180":""}`})]}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),a.jsx("div",{className:"absolute bottom-full mb-2 left-0 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:Iye.filter(({key:D})=>F[D]>0).map(({key:D,dot:H})=>a.jsxs("button",{onClick:()=>{s(D),x(!1)},className:"w-full text-left px-3 py-2 text-sm text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white transition-colors flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${H}`}),k[D],a.jsx("span",{className:"ml-auto text-bambu-gray text-xs",children:F[D]})]},D))})]})]}),T.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>{p(!m),x(!1)},children:[c("printers.bulk.selectByLocation"),a.jsx(Un,{className:`w-3 h-3 transition-transform ${m?"rotate-180":""}`})]}),m&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),a.jsx("div",{className:"absolute bottom-full mb-2 left-0 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:T.map(D=>a.jsx("button",{onClick:()=>{i(D),p(!1)},className:"w-full text-left px-3 py-2 text-sm text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white transition-colors",children:D},D))})]})]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Fe,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>o("stop"),disabled:l||!N||!_,title:N?_?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(to,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.stop")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>o("pause"),disabled:l||!N||!g,title:N?g?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(zw,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.pause")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>o("resume"),disabled:l||!N||!b,title:N?b?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx($i,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.resume")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>o("clearHMS"),disabled:l||!N||!P,title:N?P?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(wpe,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearHMS")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>o("clearPlate"),disabled:l||!A||!C,title:A?C?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[a.jsx(Vfe,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearPlate")]})]})}const MO="181",mx={ROTATE:0,DOLLY:1,PAN:2},rx={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Uye=0,DH=1,Bye=2,ZQ=1,Hye=2,Cu=3,ip=0,Ao=1,bd=2,Xu=0,hx=1,FH=2,RH=3,LH=4,qye=5,mf=100,$ye=101,Vye=102,Gye=103,Wye=104,Kye=200,Xye=201,Yye=202,Qye=203,rF=204,aF=205,Zye=206,Jye=207,eve=208,tve=209,nve=210,rve=211,ave=212,ive=213,sve=214,iF=0,sF=1,oF=2,jx=3,lF=4,cF=5,dF=6,uF=7,EO=0,ove=1,lve=2,Wh=0,cve=1,dve=2,uve=3,mve=4,hve=5,pve=6,fve=7,JQ=300,Mx=301,Ex=302,mF=303,hF=304,RP=306,pF=1e3,Bu=1001,fF=1002,il=1003,gve=1004,R_=1005,Xl=1006,vM=1007,yf=1008,Ed=1009,eZ=1010,tZ=1011,$0=1012,DO=1013,Jf=1014,Hu=1015,cy=1016,FO=1017,RO=1018,V0=1020,nZ=35902,rZ=35899,aZ=1021,iZ=1022,Rc=1023,G0=1026,W0=1027,sZ=1028,LO=1029,OO=1030,IO=1031,zO=1033,Nk=33776,Ck=33777,Pk=33778,Tk=33779,gF=35840,bF=35841,xF=35842,yF=35843,vF=36196,wF=37492,SF=37496,_F=37808,kF=37809,NF=37810,CF=37811,PF=37812,TF=37813,AF=37814,jF=37815,MF=37816,EF=37817,DF=37818,FF=37819,RF=37820,LF=37821,OF=36492,IF=36494,zF=36495,UF=36283,BF=36284,HF=36285,qF=36286,bve=3200,xve=3201,oZ=0,yve=1,_h="",Zo="srgb",Dx="srgb-linear",pN="linear",Vr="srgb",lb=7680,OH=519,vve=512,wve=513,Sve=514,lZ=515,_ve=516,kve=517,Nve=518,Cve=519,IH=35044,zH="300 es",wd=2e3,fN=2001;function cZ(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function gN(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function Pve(){const t=gN("canvas");return t.style.display="block",t}const UH={};function BH(...t){const e="THREE."+t.shift();console.log(e,...t)}function qn(...t){const e="THREE."+t.shift();console.warn(e,...t)}function ni(...t){const e="THREE."+t.shift();console.error(e,...t)}function K0(...t){const e=t.join(" ");e in UH||(UH[e]=!0,qn(...t))}function Tve(t,e,n){return new Promise(function(r,i){function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:i();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}}setTimeout(s,n)})}let Sg=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 i=r[e];if(i!==void 0){const s=i.indexOf(n);s!==-1&&i.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 i=r.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}};const Ss=["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"],Ak=Math.PI/180,$F=180/Math.PI;function $w(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Ss[t&255]+Ss[t>>8&255]+Ss[t>>16&255]+Ss[t>>24&255]+"-"+Ss[e&255]+Ss[e>>8&255]+"-"+Ss[e>>16&15|64]+Ss[e>>24&255]+"-"+Ss[n&63|128]+Ss[n>>8&255]+"-"+Ss[n>>16&255]+Ss[n>>24&255]+Ss[r&255]+Ss[r>>8&255]+Ss[r>>16&255]+Ss[r>>24&255]).toLowerCase()}function fr(t,e,n){return Math.max(e,Math.min(n,t))}function Ave(t,e){return(t%e+e)%e}function wM(t,e,n){return(1-n)*t+n*e}function fv(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 vo(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 jve={DEG2RAD:Ak};let ar=class dZ{constructor(e=0,n=0){dZ.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,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[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=fr(this.x,e.x,n.x),this.y=fr(this.y,e.y,n.y),this}clampScalar(e,n){return this.x=fr(this.x,e,n),this.y=fr(this.y,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(fr(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(fr(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),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},eg=class{constructor(e=0,n=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=i}static slerpFlat(e,n,r,i,s,o,l){let c=r[i+0],d=r[i+1],u=r[i+2],m=r[i+3],p=s[o+0],f=s[o+1],x=s[o+2],v=s[o+3];if(l<=0){e[n+0]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m;return}if(l>=1){e[n+0]=p,e[n+1]=f,e[n+2]=x,e[n+3]=v;return}if(m!==v||c!==p||d!==f||u!==x){let g=c*p+d*f+u*x+m*v;g<0&&(p=-p,f=-f,x=-x,v=-v,g=-g);let b=1-l;if(g<.9995){const _=Math.acos(g),C=Math.sin(_);b=Math.sin(b*_)/C,l=Math.sin(l*_)/C,c=c*b+p*l,d=d*b+f*l,u=u*b+x*l,m=m*b+v*l}else{c=c*b+p*l,d=d*b+f*l,u=u*b+x*l,m=m*b+v*l;const _=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=_,d*=_,u*=_,m*=_}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,r,i,s,o){const l=r[i],c=r[i+1],d=r[i+2],u=r[i+3],m=s[o],p=s[o+1],f=s[o+2],x=s[o+3];return e[n]=l*x+u*m+c*f-d*p,e[n+1]=c*x+u*p+d*m-l*f,e[n+2]=d*x+u*f+l*p-c*m,e[n+3]=u*x-l*m-c*p-d*f,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,i){return this._x=e,this._y=n,this._z=r,this._w=i,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,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(r/2),u=l(i/2),m=l(s/2),p=c(r/2),f=c(i/2),x=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m-p*f*x;break;case"YXZ":this._x=p*u*m+d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m+p*f*x;break;case"ZXY":this._x=p*u*m-d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m-p*f*x;break;case"ZYX":this._x=p*u*m-d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m+p*f*x;break;case"YZX":this._x=p*u*m+d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m-p*f*x;break;case"XZY":this._x=p*u*m-d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m+p*f*x;break;default:qn("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],l=n[5],c=n[9],d=n[2],u=n[6],m=n[10],p=r+l+m;if(p>0){const f=.5/Math.sqrt(p+1);this._w=.25/f,this._x=(u-c)*f,this._y=(s-d)*f,this._z=(o-i)*f}else if(r>l&&r>m){const f=2*Math.sqrt(1+r-l-m);this._w=(u-c)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+d)/f}else if(l>m){const f=2*Math.sqrt(1+l-r-m);this._w=(s-d)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(c+u)/f}else{const f=2*Math.sqrt(1+m-r-l);this._w=(o-i)/f,this._x=(s+d)/f,this._y=(c+u)/f,this._z=.25*f}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(fr(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),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,i=e._y,s=e._z,o=e._w,l=n._x,c=n._y,d=n._z,u=n._w;return this._x=r*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-r*d,this._z=s*u+o*d+r*c-i*l,this._w=o*u-r*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n<=0)return this;if(n>=1)return this.copy(e);let r=e._x,i=e._y,s=e._z,o=e._w,l=this.dot(e);l<0&&(r=-r,i=-i,s=-s,o=-o,l=-l);let c=1-n;if(l<.9995){const d=Math.acos(l),u=Math.sin(d);c=Math.sin(c*d)/u,n=Math.sin(n*d)/u,this._x=this._x*c+r*n,this._y=this._y*c+i*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+i*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(),i=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(i*Math.sin(e),i*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}},Tt=class uZ{constructor(e=0,n=0,r=0){uZ.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(HH.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(HH.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*r),u=2*(l*n-s*i),m=2*(s*r-o*n);return this.x=n+c*d+o*m-l*u,this.y=r+c*u+l*d-s*m,this.z=i+c*m+s*u-o*d,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,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,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=fr(this.x,e.x,n.x),this.y=fr(this.y,e.y,n.y),this.z=fr(this.z,e.z,n.z),this}clampScalar(e,n){return this.x=fr(this.x,e,n),this.y=fr(this.y,e,n),this.z=fr(this.z,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(fr(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,i=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=i*c-s*l,this.y=s*o-r*c,this.z=r*l-i*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 SM.copy(this).projectOnVector(e),this.sub(SM)}reflect(e){return this.sub(SM.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(fr(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}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 i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*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(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,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 SM=new Tt,HH=new eg;let sr=class mZ{constructor(e,n,r,i,s,o,l,c,d){mZ.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d)}set(e,n,r,i,s,o,l,c,d){const u=this.elements;return u[0]=e,u[1]=i,u[2]=l,u[3]=n,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=d,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,i=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],d=r[1],u=r[4],m=r[7],p=r[2],f=r[5],x=r[8],v=i[0],g=i[3],b=i[6],_=i[1],C=i[4],P=i[7],N=i[2],A=i[5],T=i[8];return s[0]=o*v+l*_+c*N,s[3]=o*g+l*C+c*A,s[6]=o*b+l*P+c*T,s[1]=d*v+u*_+m*N,s[4]=d*g+u*C+m*A,s[7]=d*b+u*P+m*T,s[2]=p*v+f*_+x*N,s[5]=p*g+f*C+x*A,s[8]=p*b+f*P+x*T,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],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8];return n*o*u-n*l*d-r*s*u+r*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=u*o-l*d,p=l*c-u*s,f=d*s-o*c,x=n*m+r*p+i*f;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/x;return e[0]=m*v,e[1]=(i*d-u*r)*v,e[2]=(l*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*c)*v,e[5]=(i*s-l*n)*v,e[6]=f*v,e[7]=(r*c-d*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,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(r*c,r*d,-r*(c*o+d*l)+o+e,-i*d,i*c,-i*(-d*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(_M.makeScale(e,n)),this}rotate(e){return this.premultiply(_M.makeRotation(-e)),this}translate(e,n){return this.premultiply(_M.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 i=0;i<9;i++)if(n[i]!==r[i])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 _M=new sr,qH=new sr().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),$H=new sr().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Mve(){const t={enabled:!0,workingColorSpace:Dx,spaces:{},convert:function(i,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Vr&&(i.r=Yu(i.r),i.g=Yu(i.g),i.b=Yu(i.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Vr&&(i.r=px(i.r),i.g=px(i.g),i.b=px(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===_h?pN:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,o){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return K0("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return K0("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return t.define({[Dx]:{primaries:e,whitePoint:r,transfer:pN,toXYZ:qH,fromXYZ:$H,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Zo},outputColorSpaceConfig:{drawingBufferColorSpace:Zo}},[Zo]:{primaries:e,whitePoint:r,transfer:Vr,toXYZ:qH,fromXYZ:$H,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Zo}}}),t}const Tr=Mve();function Yu(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function px(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let cb,Eve=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{cb===void 0&&(cb=gN("canvas")),cb.width=e.width,cb.height=e.height;const i=cb.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),r=cb}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=gN("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=Yu(s[o]/255)*255;return r.putImageData(i,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(Yu(n[r]/255)*255):n[r]=Yu(n[r]);return{data:n,width:e.width,height:e.height}}else return qn("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},Dve=0,UO=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Dve++}),this.uuid=$w(),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:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,l=i.length;o<l;o++)i[o].isDataTexture?s.push(kM(i[o].image)):s.push(kM(i[o]))}else s=kM(i);r.url=s}return n||(e.images[this.uuid]=r),r}};function kM(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?Eve.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(qn("Texture: Unable to serialize Texture."),{})}let Fve=0;const NM=new Tt;let Vc=class jk extends Sg{constructor(e=jk.DEFAULT_IMAGE,n=jk.DEFAULT_MAPPING,r=Bu,i=Bu,s=Xl,o=yf,l=Rc,c=Ed,d=jk.DEFAULT_ANISOTROPY,u=_h){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Fve++}),this.uuid=$w(),this.name="",this.source=new UO(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new ar(0,0),this.repeat=new ar(1,1),this.center=new ar(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new sr,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,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(NM).x}get height(){return this.source.getSize(NM).y}get depth(){return this.source.getSize(NM).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){qn(`Texture.setValues(): parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){qn(`Texture.setValues(): property '${n}' does not exist.`);continue}i&&r&&i.isVector2&&r.isVector2||i&&r&&i.isVector3&&r.isVector3||i&&r&&i.isMatrix3&&r.isMatrix3?i.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!==JQ)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pF:e.x=e.x-Math.floor(e.x);break;case Bu:e.x=e.x<0?0:1;break;case fF: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 pF:e.y=e.y-Math.floor(e.y);break;case Bu:e.y=e.y<0?0:1;break;case fF: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++}};Vc.DEFAULT_IMAGE=null;Vc.DEFAULT_MAPPING=JQ;Vc.DEFAULT_ANISOTROPY=1;let ui=class hZ{constructor(e=0,n=0,r=0,i=1){hZ.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}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,i){return this.x=e,this.y=n,this.z=r,this.w=i,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,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+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,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],x=c[9],v=c[2],g=c[6],b=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-v)<.01&&Math.abs(x-g)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+v)<.1&&Math.abs(x+g)<.1&&Math.abs(d+f+b-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const C=(d+1)/2,P=(f+1)/2,N=(b+1)/2,A=(u+p)/4,T=(m+v)/4,F=(x+g)/4;return C>P&&C>N?C<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(C),i=A/r,s=T/r):P>N?P<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(P),r=A/i,s=F/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=T/s,i=F/s),this.set(r,i,s,n),this}let _=Math.sqrt((g-x)*(g-x)+(m-v)*(m-v)+(p-u)*(p-u));return Math.abs(_)<.001&&(_=1),this.x=(g-x)/_,this.y=(m-v)/_,this.z=(p-u)/_,this.w=Math.acos((d+f+b-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=fr(this.x,e.x,n.x),this.y=fr(this.y,e.y,n.y),this.z=fr(this.z,e.z,n.z),this.w=fr(this.w,e.w,n.w),this}clampScalar(e,n){return this.x=fr(this.x,e,n),this.y=fr(this.y,e,n),this.z=fr(this.z,e,n),this.w=fr(this.w,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(fr(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}},Rve=class extends Sg{constructor(e=1,n=1,r={}){super(),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Xl,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 ui(0,0,e,n),this.scissorTest=!1,this.viewport=new ui(0,0,e,n);const i={width:e,height:n,depth:r.depth},s=new Vc(i);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:Xl,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 i=0,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=n,this.textures[i].image.depth=r,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].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 i=Object.assign({},e.textures[n].image);this.textures[n].source=new UO(i)}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"})}},tg=class extends Rve{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}},pZ=class extends Vc{constructor(e=null,n=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=il,this.minFilter=il,this.wrapR=Bu,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Lve=class extends Vc{constructor(e=null,n=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=il,this.minFilter=il,this.wrapR=Bu,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Kh=class{constructor(e=new Tt(1/0,1/0,1/0),n=new Tt(-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(Sc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(Sc.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=Sc.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,Sc):Sc.fromBufferAttribute(s,o),Sc.applyMatrix4(e.matrixWorld),this.expandByPoint(Sc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),L_.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),L_.copy(r.boundingBox)),L_.applyMatrix4(e.matrixWorld),this.union(L_)}const i=e.children;for(let s=0,o=i.length;s<o;s++)this.expandByObject(i[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,Sc),Sc.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(gv),O_.subVectors(this.max,gv),db.subVectors(e.a,gv),ub.subVectors(e.b,gv),mb.subVectors(e.c,gv),Qm.subVectors(ub,db),Zm.subVectors(mb,ub),Vp.subVectors(db,mb);let n=[0,-Qm.z,Qm.y,0,-Zm.z,Zm.y,0,-Vp.z,Vp.y,Qm.z,0,-Qm.x,Zm.z,0,-Zm.x,Vp.z,0,-Vp.x,-Qm.y,Qm.x,0,-Zm.y,Zm.x,0,-Vp.y,Vp.x,0];return!CM(n,db,ub,mb,O_)||(n=[1,0,0,0,1,0,0,0,1],!CM(n,db,ub,mb,O_))?!1:(I_.crossVectors(Qm,Zm),n=[I_.x,I_.y,I_.z],CM(n,db,ub,mb,O_))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Sc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Sc).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:(du[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),du[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),du[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),du[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),du[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),du[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),du[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),du[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(du),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 du=[new Tt,new Tt,new Tt,new Tt,new Tt,new Tt,new Tt,new Tt],Sc=new Tt,L_=new Kh,db=new Tt,ub=new Tt,mb=new Tt,Qm=new Tt,Zm=new Tt,Vp=new Tt,gv=new Tt,O_=new Tt,I_=new Tt,Gp=new Tt;function CM(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){Gp.fromArray(t,s);const l=i.x*Math.abs(Gp.x)+i.y*Math.abs(Gp.y)+i.z*Math.abs(Gp.z),c=e.dot(Gp),d=n.dot(Gp),u=r.dot(Gp);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const Ove=new Kh,bv=new Tt,PM=new Tt;let LP=class{constructor(e=new Tt,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):Ove.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),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;bv.subVectors(e,this.center);const n=bv.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(bv,i/r),this.radius+=i}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):(PM.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(bv.copy(e.center).add(PM)),this.expandByPoint(bv.copy(e.center).sub(PM))),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 uu=new Tt,TM=new Tt,z_=new Tt,Jm=new Tt,AM=new Tt,U_=new Tt,jM=new Tt;let BO=class{constructor(e=new Tt,n=new Tt(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,uu)),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=uu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(uu.copy(this.origin).addScaledVector(this.direction,n),uu.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){TM.copy(e).add(n).multiplyScalar(.5),z_.copy(n).sub(e).normalize(),Jm.copy(this.origin).sub(TM);const s=e.distanceTo(n)*.5,o=-this.direction.dot(z_),l=Jm.dot(this.direction),c=-Jm.dot(z_),d=Jm.lengthSq(),u=Math.abs(1-o*o);let m,p,f,x;if(u>0)if(m=o*c-l,p=o*l-c,x=s*u,m>=0)if(p>=-x)if(p<=x){const v=1/u;m*=v,p*=v,f=m*(m+o*p+2*l)+p*(o*m+p+2*c)+d}else p=s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p=-s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p<=-x?(m=Math.max(0,-(-o*s+l)),p=m>0?-s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d):p<=x?(m=0,p=Math.min(Math.max(-s,-c),s),f=p*(p+2*c)+d):(m=Math.max(0,-(o*s+l)),p=m>0?s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d);else p=o>0?-s:s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;return r&&r.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(TM).addScaledVector(z_,p),f}intersectSphere(e,n){uu.subVectors(e.center,this.origin);const r=uu.dot(this.direction),i=uu.dot(uu)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),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,i,s,o,l,c;const d=1/this.direction.x,u=1/this.direction.y,m=1/this.direction.z,p=this.origin;return d>=0?(r=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(r=(e.max.x-p.x)*d,i=(e.min.x-p.x)*d),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o<i||isNaN(i))&&(i=o),m>=0?(l=(e.min.z-p.z)*m,c=(e.max.z-p.z)*m):(l=(e.max.z-p.z)*m,c=(e.min.z-p.z)*m),r>c||l>i)||((l>r||r!==r)&&(r=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(r>=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,uu)!==null}intersectTriangle(e,n,r,i,s){AM.subVectors(n,e),U_.subVectors(r,e),jM.crossVectors(AM,U_);let o=this.direction.dot(jM),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Jm.subVectors(this.origin,e);const c=l*this.direction.dot(U_.crossVectors(Jm,U_));if(c<0)return null;const d=l*this.direction.dot(AM.cross(Jm));if(d<0||c+d>o)return null;const u=-l*Jm.dot(jM);return u<0?null:this.at(u/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)}},fi=class VF{constructor(e,n,r,i,s,o,l,c,d,u,m,p,f,x,v,g){VF.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,i,s,o,l,c,d,u,m,p,f,x,v,g)}set(e,n,r,i,s,o,l,c,d,u,m,p,f,x,v,g){const b=this.elements;return b[0]=e,b[4]=n,b[8]=r,b[12]=i,b[1]=s,b[5]=o,b[9]=l,b[13]=c,b[2]=d,b[6]=u,b[10]=m,b[14]=p,b[3]=f,b[7]=x,b[11]=v,b[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 VF().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,i=1/hb.setFromMatrixColumn(e,0).length(),s=1/hb.setFromMatrixColumn(e,1).length(),o=1/hb.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,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,i=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(i),d=Math.sin(i),u=Math.cos(s),m=Math.sin(s);if(e.order==="XYZ"){const p=o*u,f=o*m,x=l*u,v=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+x*d,n[5]=p-v*d,n[9]=-l*c,n[2]=v-p*d,n[6]=x+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,x=d*u,v=d*m;n[0]=p+v*l,n[4]=x*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-x,n[6]=v+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,x=d*u,v=d*m;n[0]=p-v*l,n[4]=-o*m,n[8]=x+f*l,n[1]=f+x*l,n[5]=o*u,n[9]=v-p*l,n[2]=-o*d,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const p=o*u,f=o*m,x=l*u,v=l*m;n[0]=c*u,n[4]=x*d-f,n[8]=p*d+v,n[1]=c*m,n[5]=v*d+p,n[9]=f*d-x,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,x=l*c,v=l*d;n[0]=c*u,n[4]=v-p*m,n[8]=x*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+x,n[10]=p-v*m}else if(e.order==="XZY"){const p=o*c,f=o*d,x=l*c,v=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+v,n[5]=o*u,n[9]=f*m-x,n[2]=x*m-f,n[6]=l*u,n[10]=v*m+p}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(Ive,e,zve)}lookAt(e,n,r){const i=this.elements;return Wo.subVectors(e,n),Wo.lengthSq()===0&&(Wo.z=1),Wo.normalize(),eh.crossVectors(r,Wo),eh.lengthSq()===0&&(Math.abs(r.z)===1?Wo.x+=1e-4:Wo.z+=1e-4,Wo.normalize(),eh.crossVectors(r,Wo)),eh.normalize(),B_.crossVectors(Wo,eh),i[0]=eh.x,i[4]=B_.x,i[8]=Wo.x,i[1]=eh.y,i[5]=B_.y,i[9]=Wo.y,i[2]=eh.z,i[6]=B_.z,i[10]=Wo.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],d=r[12],u=r[1],m=r[5],p=r[9],f=r[13],x=r[2],v=r[6],g=r[10],b=r[14],_=r[3],C=r[7],P=r[11],N=r[15],A=i[0],T=i[4],F=i[8],k=i[12],D=i[1],H=i[5],z=i[9],X=i[13],L=i[2],ne=i[6],ie=i[10],ee=i[14],ue=i[3],le=i[7],oe=i[11],W=i[15];return s[0]=o*A+l*D+c*L+d*ue,s[4]=o*T+l*H+c*ne+d*le,s[8]=o*F+l*z+c*ie+d*oe,s[12]=o*k+l*X+c*ee+d*W,s[1]=u*A+m*D+p*L+f*ue,s[5]=u*T+m*H+p*ne+f*le,s[9]=u*F+m*z+p*ie+f*oe,s[13]=u*k+m*X+p*ee+f*W,s[2]=x*A+v*D+g*L+b*ue,s[6]=x*T+v*H+g*ne+b*le,s[10]=x*F+v*z+g*ie+b*oe,s[14]=x*k+v*X+g*ee+b*W,s[3]=_*A+C*D+P*L+N*ue,s[7]=_*T+C*H+P*ne+N*le,s[11]=_*F+C*z+P*ie+N*oe,s[15]=_*k+C*X+P*ee+N*W,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],i=e[8],s=e[12],o=e[1],l=e[5],c=e[9],d=e[13],u=e[2],m=e[6],p=e[10],f=e[14],x=e[3],v=e[7],g=e[11],b=e[15];return x*(+s*c*m-i*d*m-s*l*p+r*d*p+i*l*f-r*c*f)+v*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+g*(+n*d*m-n*l*f-s*o*m+r*o*f+s*l*u-r*d*u)+b*(-i*l*u-n*c*m+n*l*p+i*o*m-r*o*p+r*c*u)}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 i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=e[9],p=e[10],f=e[11],x=e[12],v=e[13],g=e[14],b=e[15],_=m*g*d-v*p*d+v*c*f-l*g*f-m*c*b+l*p*b,C=x*p*d-u*g*d-x*c*f+o*g*f+u*c*b-o*p*b,P=u*v*d-x*m*d+x*l*f-o*v*f-u*l*b+o*m*b,N=x*m*c-u*v*c-x*l*p+o*v*p+u*l*g-o*m*g,A=n*_+r*C+i*P+s*N;if(A===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/A;return e[0]=_*T,e[1]=(v*p*s-m*g*s-v*i*f+r*g*f+m*i*b-r*p*b)*T,e[2]=(l*g*s-v*c*s+v*i*d-r*g*d-l*i*b+r*c*b)*T,e[3]=(m*c*s-l*p*s-m*i*d+r*p*d+l*i*f-r*c*f)*T,e[4]=C*T,e[5]=(u*g*s-x*p*s+x*i*f-n*g*f-u*i*b+n*p*b)*T,e[6]=(x*c*s-o*g*s-x*i*d+n*g*d+o*i*b-n*c*b)*T,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*T,e[8]=P*T,e[9]=(x*m*s-u*v*s-x*r*f+n*v*f+u*r*b-n*m*b)*T,e[10]=(o*v*s-x*l*s+x*r*d-n*v*d-o*r*b+n*l*b)*T,e[11]=(u*l*s-o*m*s-u*r*d+n*m*d+o*r*f-n*l*f)*T,e[12]=N*T,e[13]=(u*v*i-x*m*i+x*r*p-n*v*p-u*r*g+n*m*g)*T,e[14]=(x*l*i-o*v*i-x*r*c+n*v*c+o*r*g-n*l*g)*T,e[15]=(o*m*i-u*l*i+u*r*c-n*m*c-o*r*p+n*l*p)*T,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}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),i=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+r,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+r,u*c-i*o,0,d*c-i*l,u*c+i*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,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,d=s+s,u=o+o,m=l+l,p=s*d,f=s*u,x=s*m,v=o*u,g=o*m,b=l*m,_=c*d,C=c*u,P=c*m,N=r.x,A=r.y,T=r.z;return i[0]=(1-(v+b))*N,i[1]=(f+P)*N,i[2]=(x-C)*N,i[3]=0,i[4]=(f-P)*A,i[5]=(1-(p+b))*A,i[6]=(g+_)*A,i[7]=0,i[8]=(x+C)*T,i[9]=(g-_)*T,i[10]=(1-(p+v))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=hb.set(i[0],i[1],i[2]).length();const o=hb.set(i[4],i[5],i[6]).length(),l=hb.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],_c.copy(this);const d=1/s,u=1/o,m=1/l;return _c.elements[0]*=d,_c.elements[1]*=d,_c.elements[2]*=d,_c.elements[4]*=u,_c.elements[5]*=u,_c.elements[6]*=u,_c.elements[8]*=m,_c.elements[9]*=m,_c.elements[10]*=m,n.setFromRotationMatrix(_c),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,i,s,o,l=wd,c=!1){const d=this.elements,u=2*s/(n-e),m=2*s/(r-i),p=(n+e)/(n-e),f=(r+i)/(r-i);let x,v;if(c)x=s/(o-s),v=o*s/(o-s);else if(l===wd)x=-(o+s)/(o-s),v=-2*o*s/(o-s);else if(l===fN)x=-o/(o-s),v=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+l);return d[0]=u,d[4]=0,d[8]=p,d[12]=0,d[1]=0,d[5]=m,d[9]=f,d[13]=0,d[2]=0,d[6]=0,d[10]=x,d[14]=v,d[3]=0,d[7]=0,d[11]=-1,d[15]=0,this}makeOrthographic(e,n,r,i,s,o,l=wd,c=!1){const d=this.elements,u=2/(n-e),m=2/(r-i),p=-(n+e)/(n-e),f=-(r+i)/(r-i);let x,v;if(c)x=1/(o-s),v=o/(o-s);else if(l===wd)x=-2/(o-s),v=-(o+s)/(o-s);else if(l===fN)x=-1/(o-s),v=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return d[0]=u,d[4]=0,d[8]=0,d[12]=p,d[1]=0,d[5]=m,d[9]=0,d[13]=f,d[2]=0,d[6]=0,d[10]=x,d[14]=v,d[3]=0,d[7]=0,d[11]=0,d[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let i=0;i<16;i++)if(n[i]!==r[i])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 hb=new Tt,_c=new fi,Ive=new Tt(0,0,0),zve=new Tt(1,1,1),eh=new Tt,B_=new Tt,Wo=new Tt,VH=new fi,GH=new eg;let sp=class fZ{constructor(e=0,n=0,r=0,i=fZ.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}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,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,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 i=e.elements,s=i[0],o=i[4],l=i[8],c=i[1],d=i[5],u=i[9],m=i[2],p=i[6],f=i[10];switch(n){case"XYZ":this._y=Math.asin(fr(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(p,d),this._z=0);break;case"YXZ":this._x=Math.asin(-fr(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(l,f),this._z=Math.atan2(c,d)):(this._y=Math.atan2(-m,s),this._z=0);break;case"ZXY":this._x=Math.asin(fr(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-m,f),this._z=Math.atan2(-o,d)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-fr(m,-1,1)),Math.abs(m)<.9999999?(this._x=Math.atan2(p,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,d));break;case"YZX":this._z=Math.asin(fr(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,d),this._y=Math.atan2(-m,s)):(this._x=0,this._y=Math.atan2(l,f));break;case"XZY":this._z=Math.asin(-fr(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,d),this._y=Math.atan2(l,s)):(this._x=Math.atan2(-u,f),this._y=0);break;default:qn("Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return VH.makeRotationFromQuaternion(e),this.setFromRotationMatrix(VH,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return GH.setFromEuler(this),this.setFromQuaternion(GH,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}};sp.DEFAULT_ORDER="XYZ";let gZ=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}},Uve=0;const WH=new Tt,pb=new eg,mu=new fi,H_=new Tt,xv=new Tt,Bve=new Tt,Hve=new eg,KH=new Tt(1,0,0),XH=new Tt(0,1,0),YH=new Tt(0,0,1),QH={type:"added"},qve={type:"removed"},fb={type:"childadded",child:null},MM={type:"childremoved",child:null};let ml=class Mk extends Sg{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Uve++}),this.uuid=$w(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Mk.DEFAULT_UP.clone();const e=new Tt,n=new sp,r=new eg,i=new Tt(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:i},modelViewMatrix:{value:new fi},normalMatrix:{value:new sr}}),this.matrix=new fi,this.matrixWorld=new fi,this.matrixAutoUpdate=Mk.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Mk.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new gZ,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 pb.setFromAxisAngle(e,n),this.quaternion.multiply(pb),this}rotateOnWorldAxis(e,n){return pb.setFromAxisAngle(e,n),this.quaternion.premultiply(pb),this}rotateX(e){return this.rotateOnAxis(KH,e)}rotateY(e){return this.rotateOnAxis(XH,e)}rotateZ(e){return this.rotateOnAxis(YH,e)}translateOnAxis(e,n){return WH.copy(e).applyQuaternion(this.quaternion),this.position.add(WH.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(KH,e)}translateY(e){return this.translateOnAxis(XH,e)}translateZ(e){return this.translateOnAxis(YH,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(mu.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?H_.copy(e):H_.set(e,n,r);const i=this.parent;this.updateWorldMatrix(!0,!1),xv.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?mu.lookAt(xv,H_,this.up):mu.lookAt(H_,xv,this.up),this.quaternion.setFromRotationMatrix(mu),i&&(mu.extractRotation(i.matrixWorld),pb.setFromRotationMatrix(mu),this.quaternion.premultiply(pb.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(ni("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(QH),fb.child=e,this.dispatchEvent(fb),fb.child=null):ni("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(qve),MM.child=e,this.dispatchEvent(MM),MM.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),mu.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),mu.multiply(e.parent.matrixWorld)),e.applyMatrix4(mu),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(QH),fb.child=e,this.dispatchEvent(fb),fb.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,i=this.children.length;r<i;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 i=this.children;for(let s=0,o=i.length;s<o;s++)i[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(xv,e,Bve),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(xv,Hve,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,i=n.length;r<i;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,i=n.length;r<i;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,i=n.length;r<i;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 i=this.children;for(let s=0,o=i.length;s<o;s++)i[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 i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(l=>({...l,boundingBox:l.boundingBox?l.boundingBox.toJSON():void 0,boundingSphere:l.boundingSphere?l.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(l=>({...l})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.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?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.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 d=0,u=c.length;d<u;d++){const m=c[d];s(e.shapes,m)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,d=this.material.length;c<d;c++)l.push(s(e.materials,this.material[c]));i.material=l}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let l=0;l<this.children.length;l++)i.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];i.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),d=o(e.textures),u=o(e.images),m=o(e.shapes),p=o(e.skeletons),f=o(e.animations),x=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),d.length>0&&(r.textures=d),u.length>0&&(r.images=u),m.length>0&&(r.shapes=m),p.length>0&&(r.skeletons=p),f.length>0&&(r.animations=f),x.length>0&&(r.nodes=x)}return r.object=i,r;function o(l){const c=[];for(const d in l){const u=l[d];delete u.metadata,c.push(u)}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 i=e.children[r];this.add(i.clone())}return this}};ml.DEFAULT_UP=new Tt(0,1,0);ml.DEFAULT_MATRIX_AUTO_UPDATE=!0;ml.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const kc=new Tt,hu=new Tt,EM=new Tt,pu=new Tt,gb=new Tt,bb=new Tt,ZH=new Tt,DM=new Tt,FM=new Tt,RM=new Tt,LM=new ui,OM=new ui,IM=new ui;let yv=class Yb{constructor(e=new Tt,n=new Tt,r=new Tt){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,i){i.subVectors(r,n),kc.subVectors(e,n),i.cross(kc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){kc.subVectors(i,n),hu.subVectors(r,n),EM.subVectors(e,n);const o=kc.dot(kc),l=kc.dot(hu),c=kc.dot(EM),d=hu.dot(hu),u=hu.dot(EM),m=o*d-l*l;if(m===0)return s.set(0,0,0),null;const p=1/m,f=(d*c-l*u)*p,x=(o*u-l*c)*p;return s.set(1-f-x,x,f)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,pu)===null?!1:pu.x>=0&&pu.y>=0&&pu.x+pu.y<=1}static getInterpolation(e,n,r,i,s,o,l,c){return this.getBarycoord(e,n,r,i,pu)===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,pu.x),c.addScaledVector(o,pu.y),c.addScaledVector(l,pu.z),c)}static getInterpolatedAttribute(e,n,r,i,s,o){return LM.setScalar(0),OM.setScalar(0),IM.setScalar(0),LM.fromBufferAttribute(e,n),OM.fromBufferAttribute(e,r),IM.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(LM,s.x),o.addScaledVector(OM,s.y),o.addScaledVector(IM,s.z),o}static isFrontFacing(e,n,r,i){return kc.subVectors(r,n),hu.subVectors(e,n),kc.cross(hu).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),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 kc.subVectors(this.c,this.b),hu.subVectors(this.a,this.b),kc.cross(hu).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Yb.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return Yb.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,r,i,s){return Yb.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return Yb.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Yb.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,l;gb.subVectors(i,r),bb.subVectors(s,r),DM.subVectors(e,r);const c=gb.dot(DM),d=bb.dot(DM);if(c<=0&&d<=0)return n.copy(r);FM.subVectors(e,i);const u=gb.dot(FM),m=bb.dot(FM);if(u>=0&&m<=u)return n.copy(i);const p=c*m-u*d;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),n.copy(r).addScaledVector(gb,o);RM.subVectors(e,s);const f=gb.dot(RM),x=bb.dot(RM);if(x>=0&&f<=x)return n.copy(s);const v=f*d-c*x;if(v<=0&&d>=0&&x<=0)return l=d/(d-x),n.copy(r).addScaledVector(bb,l);const g=u*x-f*m;if(g<=0&&m-u>=0&&f-x>=0)return ZH.subVectors(s,i),l=(m-u)/(m-u+(f-x)),n.copy(i).addScaledVector(ZH,l);const b=1/(g+v+p);return o=v*b,l=p*b,n.copy(r).addScaledVector(gb,o).addScaledVector(bb,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}};const bZ={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},th={h:0,s:0,l:0},q_={h:0,s:0,l:0};function zM(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 lr=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 i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=Zo){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Tr.colorSpaceToWorking(this,n),this}setRGB(e,n,r,i=Tr.workingColorSpace){return this.r=e,this.g=n,this.b=r,Tr.colorSpaceToWorking(this,i),this}setHSL(e,n,r,i=Tr.workingColorSpace){if(e=Ave(e,1),n=fr(n,0,1),r=fr(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=zM(o,s,e+1/3),this.g=zM(o,s,e),this.b=zM(o,s,e-1/3)}return Tr.colorSpaceToWorking(this,i),this}setStyle(e,n=Zo){function r(s){s!==void 0&&parseFloat(s)<1&&qn("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],l=i[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:qn("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[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);qn("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=Zo){const r=bZ[e.toLowerCase()];return r!==void 0?this.setHex(r,n):qn("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=Yu(e.r),this.g=Yu(e.g),this.b=Yu(e.b),this}copyLinearToSRGB(e){return this.r=px(e.r),this.g=px(e.g),this.b=px(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Zo){return Tr.workingToColorSpace(_s.copy(this),e),Math.round(fr(_s.r*255,0,255))*65536+Math.round(fr(_s.g*255,0,255))*256+Math.round(fr(_s.b*255,0,255))}getHexString(e=Zo){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=Tr.workingColorSpace){Tr.workingToColorSpace(_s.copy(this),n);const r=_s.r,i=_s.g,s=_s.b,o=Math.max(r,i,s),l=Math.min(r,i,s);let c,d;const u=(l+o)/2;if(l===o)c=0,d=0;else{const m=o-l;switch(d=u<=.5?m/(o+l):m/(2-o-l),o){case r:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-r)/m+2;break;case s:c=(r-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=Tr.workingColorSpace){return Tr.workingToColorSpace(_s.copy(this),n),e.r=_s.r,e.g=_s.g,e.b=_s.b,e}getStyle(e=Zo){Tr.workingToColorSpace(_s.copy(this),e);const n=_s.r,r=_s.g,i=_s.b;return e!==Zo?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(i*255)})`}offsetHSL(e,n,r){return this.getHSL(th),this.setHSL(th.h+e,th.s+n,th.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(th),e.getHSL(q_);const r=wM(th.h,q_.h,n),i=wM(th.s,q_.s,n),s=wM(th.l,q_.l,n);return this.setHSL(r,i,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,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*i,this.g=s[1]*n+s[4]*r+s[7]*i,this.b=s[2]*n+s[5]*r+s[8]*i,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 _s=new lr;lr.NAMES=bZ;let $ve=0,dy=class extends Sg{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:$ve++}),this.uuid=$w(),this.name="",this.type="Material",this.blending=hx,this.side=ip,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=rF,this.blendDst=aF,this.blendEquation=mf,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new lr(0,0,0),this.blendAlpha=0,this.depthFunc=jx,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=OH,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=lb,this.stencilZFail=lb,this.stencilZPass=lb,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){qn(`Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){qn(`Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.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!==hx&&(r.blending=this.blending),this.side!==ip&&(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!==rF&&(r.blendSrc=this.blendSrc),this.blendDst!==aF&&(r.blendDst=this.blendDst),this.blendEquation!==mf&&(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!==jx&&(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!==OH&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==lb&&(r.stencilFail=this.stencilFail),this.stencilZFail!==lb&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==lb&&(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 i(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=i(e.textures),o=i(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 i=n.length;r=new Array(i);for(let s=0;s!==i;++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++}},HO=class extends dy{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new lr(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 sp,this.combine=EO,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 ci=new Tt,$_=new ar;let Vve=0,Zs=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:Vve++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=IH,this.updateRanges=[],this.gpuType=Hu,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 i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[r+i];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++)$_.fromBufferAttribute(this,n),$_.applyMatrix3(e),this.setXY(n,$_.x,$_.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)ci.fromBufferAttribute(this,n),ci.applyMatrix3(e),this.setXYZ(n,ci.x,ci.y,ci.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)ci.fromBufferAttribute(this,n),ci.applyMatrix4(e),this.setXYZ(n,ci.x,ci.y,ci.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)ci.fromBufferAttribute(this,n),ci.applyNormalMatrix(e),this.setXYZ(n,ci.x,ci.y,ci.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)ci.fromBufferAttribute(this,n),ci.transformDirection(e),this.setXYZ(n,ci.x,ci.y,ci.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=fv(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=vo(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=fv(n,this.array)),n}setX(e,n){return this.normalized&&(n=vo(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=fv(n,this.array)),n}setY(e,n){return this.normalized&&(n=vo(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=fv(n,this.array)),n}setZ(e,n){return this.normalized&&(n=vo(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=fv(n,this.array)),n}setW(e,n){return this.normalized&&(n=vo(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=vo(n,this.array),r=vo(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,i){return e*=this.itemSize,this.normalized&&(n=vo(n,this.array),r=vo(r,this.array),i=vo(i,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e*=this.itemSize,this.normalized&&(n=vo(n,this.array),r=vo(r,this.array),i=vo(i,this.array),s=vo(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,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!==IH&&(e.usage=this.usage),e}},xZ=class extends Zs{constructor(e,n,r){super(new Uint16Array(e),n,r)}},yZ=class extends Zs{constructor(e,n,r){super(new Uint32Array(e),n,r)}},sl=class extends Zs{constructor(e,n,r){super(new Float32Array(e),n,r)}},Gve=0;const Ml=new fi,UM=new ml,xb=new Tt,Ko=new Kh,vv=new Kh,Fi=new Tt;let sc=class vZ extends Sg{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Gve++}),this.uuid=$w(),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(cZ(e)?yZ:xZ)(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 sr().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ml.makeRotationFromQuaternion(e),this.applyMatrix4(Ml),this}rotateX(e){return Ml.makeRotationX(e),this.applyMatrix4(Ml),this}rotateY(e){return Ml.makeRotationY(e),this.applyMatrix4(Ml),this}rotateZ(e){return Ml.makeRotationZ(e),this.applyMatrix4(Ml),this}translate(e,n,r){return Ml.makeTranslation(e,n,r),this.applyMatrix4(Ml),this}scale(e,n,r){return Ml.makeScale(e,n,r),this.applyMatrix4(Ml),this}lookAt(e){return UM.lookAt(e),UM.updateMatrix(),this.applyMatrix4(UM.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(xb).negate(),this.translate(xb.x,xb.y,xb.z),this}setFromPoints(e){const n=this.getAttribute("position");if(n===void 0){const r=[];for(let i=0,s=e.length;i<s;i++){const o=e[i];r.push(o.x,o.y,o.z||0)}this.setAttribute("position",new sl(r,3))}else{const r=Math.min(e.length,n.count);for(let i=0;i<r;i++){const s=e[i];n.setXYZ(i,s.x,s.y,s.z||0)}e.length>n.count&&qn("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 Kh);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){ni("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new Tt(-1/0,-1/0,-1/0),new Tt(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r<i;r++){const s=n[r];Ko.setFromBufferAttribute(s),this.morphTargetsRelative?(Fi.addVectors(this.boundingBox.min,Ko.min),this.boundingBox.expandByPoint(Fi),Fi.addVectors(this.boundingBox.max,Ko.max),this.boundingBox.expandByPoint(Fi)):(this.boundingBox.expandByPoint(Ko.min),this.boundingBox.expandByPoint(Ko.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&ni('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 LP);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){ni("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new Tt,1/0);return}if(e){const r=this.boundingSphere.center;if(Ko.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];vv.setFromBufferAttribute(l),this.morphTargetsRelative?(Fi.addVectors(Ko.min,vv.min),Ko.expandByPoint(Fi),Fi.addVectors(Ko.max,vv.max),Ko.expandByPoint(Fi)):(Ko.expandByPoint(vv.min),Ko.expandByPoint(vv.max))}Ko.getCenter(r);let i=0;for(let s=0,o=e.count;s<o;s++)Fi.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(Fi));if(n)for(let s=0,o=n.length;s<o;s++){const l=n[s],c=this.morphTargetsRelative;for(let d=0,u=l.count;d<u;d++)Fi.fromBufferAttribute(l,d),c&&(xb.fromBufferAttribute(e,d),Fi.add(xb)),i=Math.max(i,r.distanceToSquared(Fi))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&ni('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){ni("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const r=n.position,i=n.normal,s=n.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Zs(new Float32Array(4*r.count),4));const o=this.getAttribute("tangent"),l=[],c=[];for(let F=0;F<r.count;F++)l[F]=new Tt,c[F]=new Tt;const d=new Tt,u=new Tt,m=new Tt,p=new ar,f=new ar,x=new ar,v=new Tt,g=new Tt;function b(F,k,D){d.fromBufferAttribute(r,F),u.fromBufferAttribute(r,k),m.fromBufferAttribute(r,D),p.fromBufferAttribute(s,F),f.fromBufferAttribute(s,k),x.fromBufferAttribute(s,D),u.sub(d),m.sub(d),f.sub(p),x.sub(p);const H=1/(f.x*x.y-x.x*f.y);isFinite(H)&&(v.copy(u).multiplyScalar(x.y).addScaledVector(m,-f.y).multiplyScalar(H),g.copy(m).multiplyScalar(f.x).addScaledVector(u,-x.x).multiplyScalar(H),l[F].add(v),l[k].add(v),l[D].add(v),c[F].add(g),c[k].add(g),c[D].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let F=0,k=_.length;F<k;++F){const D=_[F],H=D.start,z=D.count;for(let X=H,L=H+z;X<L;X+=3)b(e.getX(X+0),e.getX(X+1),e.getX(X+2))}const C=new Tt,P=new Tt,N=new Tt,A=new Tt;function T(F){N.fromBufferAttribute(i,F),A.copy(N);const k=l[F];C.copy(k),C.sub(N.multiplyScalar(N.dot(k))).normalize(),P.crossVectors(A,k);const H=P.dot(c[F])<0?-1:1;o.setXYZW(F,C.x,C.y,C.z,H)}for(let F=0,k=_.length;F<k;++F){const D=_[F],H=D.start,z=D.count;for(let X=H,L=H+z;X<L;X+=3)T(e.getX(X+0)),T(e.getX(X+1)),T(e.getX(X+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 Zs(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let p=0,f=r.count;p<f;p++)r.setXYZ(p,0,0,0);const i=new Tt,s=new Tt,o=new Tt,l=new Tt,c=new Tt,d=new Tt,u=new Tt,m=new Tt;if(e)for(let p=0,f=e.count;p<f;p+=3){const x=e.getX(p+0),v=e.getX(p+1),g=e.getX(p+2);i.fromBufferAttribute(n,x),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,g),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(r,x),c.fromBufferAttribute(r,v),d.fromBufferAttribute(r,g),l.add(u),c.add(u),d.add(u),r.setXYZ(x,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.setXYZ(g,d.x,d.y,d.z)}else for(let p=0,f=n.count;p<f;p+=3)i.fromBufferAttribute(n,p+0),s.fromBufferAttribute(n,p+1),o.fromBufferAttribute(n,p+2),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),r.setXYZ(p+0,u.x,u.y,u.z),r.setXYZ(p+1,u.x,u.y,u.z),r.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Fi.fromBufferAttribute(e,n),Fi.normalize(),e.setXYZ(n,Fi.x,Fi.y,Fi.z)}toNonIndexed(){function e(l,c){const d=l.array,u=l.itemSize,m=l.normalized,p=new d.constructor(c.length*u);let f=0,x=0;for(let v=0,g=c.length;v<g;v++){l.isInterleavedBufferAttribute?f=c[v]*l.data.stride+l.offset:f=c[v]*u;for(let b=0;b<u;b++)p[x++]=d[f++]}return new Zs(p,u,m)}if(this.index===null)return qn("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new vZ,r=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,r);n.setAttribute(l,d)}const s=this.morphAttributes;for(const l in s){const c=[],d=s[l];for(let u=0,m=d.length;u<m;u++){const p=d[u],f=e(p,r);c.push(f)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const d=o[l];n.addGroup(d.start,d.count,d.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 d in c)c[d]!==void 0&&(e[d]=c[d]);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 d=r[c];e.data.attributes[c]=d.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const d=this.morphAttributes[c],u=[];for(let m=0,p=d.length;m<p;m++){const f=d[m];u.push(f.toJSON(e.data))}u.length>0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,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 i=e.attributes;for(const d in i){const u=i[d];this.setAttribute(d,u.clone(n))}const s=e.morphAttributes;for(const d in s){const u=[],m=s[d];for(let p=0,f=m.length;p<f;p++)u.push(m[p].clone(n));this.morphAttributes[d]=u}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let d=0,u=o.length;d<u;d++){const m=o[d];this.addGroup(m.start,m.count,m.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 JH=new fi,Wp=new BO,V_=new LP,e6=new Tt,G_=new Tt,W_=new Tt,K_=new Tt,BM=new Tt,X_=new Tt,t6=new Tt,Y_=new Tt;let oc=class extends ml{constructor(e=new sc,n=new HO){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 i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,i=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){X_.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(BM.fromBufferAttribute(m,e),o?X_.addScaledVector(BM,u):X_.addScaledVector(BM.sub(n),u))}n.add(X_)}return n}raycast(e,n){const r=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),V_.copy(r.boundingSphere),V_.applyMatrix4(s),Wp.copy(e.ray).recast(e.near),!(V_.containsPoint(Wp.origin)===!1&&(Wp.intersectSphere(V_,e6)===null||Wp.origin.distanceToSquared(e6)>(e.far-e.near)**2))&&(JH.copy(s).invert(),Wp.copy(e.ray).applyMatrix4(JH),!(r.boundingBox!==null&&Wp.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Wp)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,d=s.attributes.uv,u=s.attributes.uv1,m=s.attributes.normal,p=s.groups,f=s.drawRange;if(l!==null)if(Array.isArray(o))for(let x=0,v=p.length;x<v;x++){const g=p[x],b=o[g.materialIndex],_=Math.max(g.start,f.start),C=Math.min(l.count,Math.min(g.start+g.count,f.start+f.count));for(let P=_,N=C;P<N;P+=3){const A=l.getX(P),T=l.getX(P+1),F=l.getX(P+2);i=Q_(this,b,e,r,d,u,m,A,T,F),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=g.materialIndex,n.push(i))}}else{const x=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let g=x,b=v;g<b;g+=3){const _=l.getX(g),C=l.getX(g+1),P=l.getX(g+2);i=Q_(this,o,e,r,d,u,m,_,C,P),i&&(i.faceIndex=Math.floor(g/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let x=0,v=p.length;x<v;x++){const g=p[x],b=o[g.materialIndex],_=Math.max(g.start,f.start),C=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let P=_,N=C;P<N;P+=3){const A=P,T=P+1,F=P+2;i=Q_(this,b,e,r,d,u,m,A,T,F),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=g.materialIndex,n.push(i))}}else{const x=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let g=x,b=v;g<b;g+=3){const _=g,C=g+1,P=g+2;i=Q_(this,o,e,r,d,u,m,_,C,P),i&&(i.faceIndex=Math.floor(g/3),n.push(i))}}}};function Wve(t,e,n,r,i,s,o,l){let c;if(e.side===Ao?c=r.intersectTriangle(o,s,i,!0,l):c=r.intersectTriangle(i,s,o,e.side===ip,l),c===null)return null;Y_.copy(l),Y_.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(Y_);return d<n.near||d>n.far?null:{distance:d,point:Y_.clone(),object:t}}function Q_(t,e,n,r,i,s,o,l,c,d){t.getVertexPosition(l,G_),t.getVertexPosition(c,W_),t.getVertexPosition(d,K_);const u=Wve(t,e,n,r,G_,W_,K_,t6);if(u){const m=new Tt;yv.getBarycoord(t6,G_,W_,K_,m),i&&(u.uv=yv.getInterpolatedAttribute(i,l,c,d,m,new ar)),s&&(u.uv1=yv.getInterpolatedAttribute(s,l,c,d,m,new ar)),o&&(u.normal=yv.getInterpolatedAttribute(o,l,c,d,m,new Tt),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const p={a:l,b:c,c:d,normal:new Tt,materialIndex:0};yv.getNormal(G_,W_,K_,p.normal),u.face=p,u.barycoord=m}return u}let qO=class wZ extends sc{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const l=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],d=[],u=[],m=[];let p=0,f=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,i,o,2),x("x","z","y",1,-1,e,r,-n,i,o,3),x("x","y","z",1,-1,e,n,r,i,s,4),x("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new sl(d,3)),this.setAttribute("normal",new sl(u,3)),this.setAttribute("uv",new sl(m,2));function x(v,g,b,_,C,P,N,A,T,F,k){const D=P/T,H=N/F,z=P/2,X=N/2,L=A/2,ne=T+1,ie=F+1;let ee=0,ue=0;const le=new Tt;for(let oe=0;oe<ie;oe++){const W=oe*H-X;for(let re=0;re<ne;re++){const ce=re*D-z;le[v]=ce*_,le[g]=W*C,le[b]=L,d.push(le.x,le.y,le.z),le[v]=0,le[g]=0,le[b]=A>0?1:-1,u.push(le.x,le.y,le.z),m.push(re/T),m.push(1-oe/F),ee+=1}}for(let oe=0;oe<F;oe++)for(let W=0;W<T;W++){const re=p+W+ne*oe,ce=p+W+ne*(oe+1),xe=p+(W+1)+ne*(oe+1),Ne=p+(W+1)+ne*oe;c.push(re,ce,Ne),c.push(ce,xe,Ne),ue+=6}l.addGroup(f,ue,k),f+=ue,p+=ee}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new wZ(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function Fx(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const i=t[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(qn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=i.clone():Array.isArray(i)?e[n][r]=i.slice():e[n][r]=i}}return e}function Vs(t){const e={};for(let n=0;n<t.length;n++){const r=Fx(t[n]);for(const i in r)e[i]=r[i]}return e}function Kve(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function SZ(t){const e=t.getRenderTarget();return e===null?t.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Tr.workingColorSpace}const Xve={clone:Fx,merge:Vs};var Yve=`void main() {
- gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
- }`,Qve=`void main() {
- gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
- }`;let lm=class extends dy{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Yve,this.fragmentShader=Qve,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=Fx(e.uniforms),this.uniformsGroups=Kve(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 i in this.uniforms){const o=this.uniforms[i].value;o&&o.isTexture?n.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[i]={type:"m4",value:o.toArray()}:n.uniforms[i]={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 i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}},_Z=class extends ml{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new fi,this.projectionMatrix=new fi,this.projectionMatrixInverse=new fi,this.coordinateSystem=wd,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 nh=new Tt,n6=new ar,r6=new ar;let ql=class extends _Z{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,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=$F*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Ak*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return $F*2*Math.atan(Math.tan(Ak*.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){nh.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(nh.x,nh.y).multiplyScalar(-e/nh.z),nh.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(nh.x,nh.y).multiplyScalar(-e/nh.z)}getViewSize(e,n){return this.getViewBounds(e,n6,r6),n.subVectors(r6,n6)}setViewOffset(e,n,r,i,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=i,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(Ak*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,d=o.fullHeight;s+=o.offsetX*i/c,n-=o.offsetY*r/d,i*=o.width/c,r*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,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 yb=-90,vb=1;let Zve=class extends ml{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new ql(yb,vb,e,n);i.layers=this.layers,this.add(i);const s=new ql(yb,vb,e,n);s.layers=this.layers,this.add(s);const o=new ql(yb,vb,e,n);o.layers=this.layers,this.add(o);const l=new ql(yb,vb,e,n);l.layers=this.layers,this.add(l);const c=new ql(yb,vb,e,n);c.layers=this.layers,this.add(c);const d=new ql(yb,vb,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===wd)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.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===fN)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.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 d of n)this.add(d),d.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,d,u]=this.children,m=e.getRenderTarget(),p=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,l),e.setRenderTarget(r,3,i),e.render(n,c),e.setRenderTarget(r,4,i),e.render(n,d),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=x,r.texture.needsPMREMUpdate=!0}},kZ=class extends Vc{constructor(e=[],n=Mx,r,i,s,o,l,c,d,u){super(e,n,r,i,s,o,l,c,d,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Jve=class extends tg{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new kZ(i),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:`
- varying vec3 vWorldDirection;
- vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
- }
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- }
- `,fragmentShader:`
- uniform sampler2D tEquirect;
- varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vec3 direction = normalize( vWorldDirection );
- vec2 sampleUV = equirectUv( direction );
- gl_FragColor = texture2D( tEquirect, sampleUV );
- }
- `},i=new qO(5,5,5),s=new lm({name:"CubemapFromEquirect",uniforms:Fx(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:Ao,blending:Xu});s.uniforms.tEquirect.value=n;const o=new oc(i,s),l=n.minFilter;return n.minFilter===yf&&(n.minFilter=Xl),new Zve(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n=!0,r=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}},ax=class extends ml{constructor(){super(),this.isGroup=!0,this.type="Group"}};const e0e={type:"move"};let HM=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new ax,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 ax,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Tt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Tt),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new ax,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Tt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Tt),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 i=null,s=null,o=null;const l=this._targetRay,c=this._grip,d=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(d&&e.hand){o=!0;for(const v of e.hand.values()){const g=n.getJointPose(v,r),b=this._getHandJoint(d,v);g!==null&&(b.matrix.fromArray(g.transform.matrix),b.matrix.decompose(b.position,b.rotation,b.scale),b.matrixWorldNeedsUpdate=!0,b.jointRadius=g.radius),b.visible=g!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,x=.005;d.inputState.pinching&&p>f+x?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-x&&(d.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&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(l.matrix.fromArray(i.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,i.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(i.linearVelocity)):l.hasLinearVelocity=!1,i.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(i.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(e0e)))}return l!==null&&(l.visible=i!==null),c!==null&&(c.visible=s!==null),d!==null&&(d.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new ax;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}},t0e=class extends ml{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 sp,this.environmentIntensity=1,this.environmentRotation=new sp,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}},n0e=class extends Vc{constructor(e=null,n=1,r=1,i,s,o,l,c,d=il,u=il,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};const qM=new Tt,r0e=new Tt,a0e=new sr;let fh=class{constructor(e=new Tt(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,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=qM.subVectors(r,n).cross(r0e.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,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(qM),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;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||a0e.getNormalMatrix(e),i=this.coplanarPoint(qM).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.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 Kp=new LP,i0e=new ar(.5,.5),Z_=new Tt;let $O=class{constructor(e=new fh,n=new fh,r=new fh,i=new fh,s=new fh,o=new fh){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(i),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=wd,r=!1){const i=this.planes,s=e.elements,o=s[0],l=s[1],c=s[2],d=s[3],u=s[4],m=s[5],p=s[6],f=s[7],x=s[8],v=s[9],g=s[10],b=s[11],_=s[12],C=s[13],P=s[14],N=s[15];if(i[0].setComponents(d-o,f-u,b-x,N-_).normalize(),i[1].setComponents(d+o,f+u,b+x,N+_).normalize(),i[2].setComponents(d+l,f+m,b+v,N+C).normalize(),i[3].setComponents(d-l,f-m,b-v,N-C).normalize(),r)i[4].setComponents(c,p,g,P).normalize(),i[5].setComponents(d-c,f-p,b-g,N-P).normalize();else if(i[4].setComponents(d-c,f-p,b-g,N-P).normalize(),n===wd)i[5].setComponents(d+c,f+p,b+g,N+P).normalize();else if(n===fN)i[5].setComponents(c,p,g,P).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(),Kp.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Kp.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Kp)}intersectsSprite(e){Kp.center.set(0,0,0);const n=i0e.distanceTo(e.center);return Kp.radius=.7071067811865476+n,Kp.applyMatrix4(e.matrixWorld),this.intersectsSphere(Kp)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const i=n[r];if(Z_.x=i.normal.x>0?e.max.x:e.min.x,Z_.y=i.normal.y>0?e.max.y:e.min.y,Z_.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Z_)<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)}},NZ=class extends dy{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new lr(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 bN=new Tt,xN=new Tt,a6=new fi,wv=new BO,J_=new LP,$M=new Tt,i6=new Tt;let s0e=class extends ml{constructor(e=new sc,n=new NZ){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 i=1,s=n.count;i<s;i++)bN.fromBufferAttribute(n,i-1),xN.fromBufferAttribute(n,i),r[i]=r[i-1],r[i]+=bN.distanceTo(xN);e.setAttribute("lineDistance",new sl(r,1))}else qn("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),J_.copy(r.boundingSphere),J_.applyMatrix4(i),J_.radius+=s,e.ray.intersectsSphere(J_)===!1)return;a6.copy(i).invert(),wv.copy(e.ray).applyMatrix4(a6);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=this.isLineSegments?2:1,u=r.index,p=r.attributes.position;if(u!==null){const f=Math.max(0,o.start),x=Math.min(u.count,o.start+o.count);for(let v=f,g=x-1;v<g;v+=d){const b=u.getX(v),_=u.getX(v+1),C=e1(this,e,wv,c,b,_,v);C&&n.push(C)}if(this.isLineLoop){const v=u.getX(x-1),g=u.getX(f),b=e1(this,e,wv,c,v,g,x-1);b&&n.push(b)}}else{const f=Math.max(0,o.start),x=Math.min(p.count,o.start+o.count);for(let v=f,g=x-1;v<g;v+=d){const b=e1(this,e,wv,c,v,v+1,v);b&&n.push(b)}if(this.isLineLoop){const v=e1(this,e,wv,c,x-1,f,x-1);v&&n.push(v)}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};function e1(t,e,n,r,i,s,o){const l=t.geometry.attributes.position;if(bN.fromBufferAttribute(l,i),xN.fromBufferAttribute(l,s),n.distanceSqToSegment(bN,xN,$M,i6)>r)return;$M.applyMatrix4(t.matrixWorld);const d=e.ray.origin.distanceTo($M);if(!(d<e.near||d>e.far))return{distance:d,point:i6.clone().applyMatrix4(t.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:t}}const s6=new Tt,o6=new Tt;let o0e=class extends s0e{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 i=0,s=n.count;i<s;i+=2)s6.fromBufferAttribute(n,i),o6.fromBufferAttribute(n,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+s6.distanceTo(o6);e.setAttribute("lineDistance",new sl(r,1))}else qn("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},CZ=class extends Vc{constructor(e,n,r=Jf,i,s,o,l=il,c=il,d,u=G0,m=1){if(u!==G0&&u!==W0)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const p={width:e,height:n,depth:m};super(p,i,s,o,l,c,u,r,d),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new UO(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 PZ extends Vc{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}let VO=class TZ extends sc{constructor(e=1,n=1,r=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],x=[],v=[],g=[];for(let b=0;b<u;b++){const _=b*p-o;for(let C=0;C<d;C++){const P=C*m-s;x.push(P,-_,0),v.push(0,0,1),g.push(C/l),g.push(1-b/c)}}for(let b=0;b<c;b++)for(let _=0;_<l;_++){const C=_+d*b,P=_+d*(b+1),N=_+1+d*(b+1),A=_+1+d*b;f.push(C,P,A),f.push(P,N,A)}this.setIndex(f),this.setAttribute("position",new sl(x,3)),this.setAttribute("normal",new sl(v,3)),this.setAttribute("uv",new sl(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new TZ(e.width,e.height,e.widthSegments,e.heightSegments)}};class AZ extends dy{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new lr(16777215),this.specular=new lr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new lr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=oZ,this.normalScale=new ar(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new sp,this.combine=EO,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 l0e=class extends dy{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=bve,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}},c0e=class extends dy{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 l6={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 d0e{constructor(e,n,r){const i=this;let s=!1,o=0,l=0,c;const d=[];this.onStart=void 0,this.onLoad=e,this.onProgress=n,this.onError=r,this._abortController=null,this.itemStart=function(u){l++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,l),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,l),o===l&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,m){return d.push(u,m),this},this.removeHandler=function(u){const m=d.indexOf(u);return m!==-1&&d.splice(m,2),this},this.getHandler=function(u){for(let m=0,p=d.length;m<p;m+=2){const f=d[m],x=d[m+1];if(f.global&&(f.lastIndex=0),f.test(u))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 u0e=new d0e;class GO{constructor(e){this.manager=e!==void 0?e:u0e,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,n){const r=this;return new Promise(function(i,s){r.load(e,i,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}}GO.DEFAULT_MATERIAL_NAME="__DEFAULT";const fu={};class m0e extends Error{constructor(e,n){super(e),this.response=n}}class h0e extends GO{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,n,r,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=l6.get(`file:${e}`);if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{n&&n(s),this.manager.itemEnd(e)},0),s;if(fu[e]!==void 0){fu[e].push({onLoad:n,onProgress:r,onError:i});return}fu[e]=[],fu[e].push({onLoad:n,onProgress:r,onError:i});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(d=>{if(d.status===200||d.status===0){if(d.status===0&&qn("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||d.body===void 0||d.body.getReader===void 0)return d;const u=fu[e],m=d.body.getReader(),p=d.headers.get("X-File-Size")||d.headers.get("Content-Length"),f=p?parseInt(p):0,x=f!==0;let v=0;const g=new ReadableStream({start(b){_();function _(){m.read().then(({done:C,value:P})=>{if(C)b.close();else{v+=P.byteLength;const N=new ProgressEvent("progress",{lengthComputable:x,loaded:v,total:f});for(let A=0,T=u.length;A<T;A++){const F=u[A];F.onProgress&&F.onProgress(N)}b.enqueue(P),_()}},C=>{b.error(C)})}}});return new Response(g)}else throw new m0e(`fetch for "${d.url}" responded with ${d.status}: ${d.statusText}`,d)}).then(d=>{switch(c){case"arraybuffer":return d.arrayBuffer();case"blob":return d.blob();case"document":return d.text().then(u=>new DOMParser().parseFromString(u,l));case"json":return d.json();default:if(l==="")return d.text();{const m=/charset="?([^;"\s]*)"?/i.exec(l),p=m&&m[1]?m[1].toLowerCase():void 0,f=new TextDecoder(p);return d.arrayBuffer().then(x=>f.decode(x))}}}).then(d=>{l6.add(`file:${e}`,d);const u=fu[e];delete fu[e];for(let m=0,p=u.length;m<p;m++){const f=u[m];f.onLoad&&f.onLoad(d)}}).catch(d=>{const u=fu[e];if(u===void 0)throw this.manager.itemError(e),d;delete fu[e];for(let m=0,p=u.length;m<p;m++){const f=u[m];f.onError&&f.onError(d)}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 jZ=class extends ml{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new lr(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 VM=new fi,c6=new Tt,d6=new Tt;let p0e=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ar(512,512),this.mapType=Ed,this.map=null,this.mapPass=null,this.matrix=new fi,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new $O,this._frameExtents=new ar(1,1),this._viewportCount=1,this._viewports=[new ui(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;c6.setFromMatrixPosition(e.matrixWorld),n.position.copy(c6),d6.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(d6),n.updateMatrixWorld(),VM.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(VM,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(VM)}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}},MZ=class extends _Z{constructor(e=-1,n=1,r=1,i=-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=i,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,i,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=i,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,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=i+n,c=i-n;if(this.view!==null&&this.view.enabled){const d=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=d*this.view.offsetX,o=s+d*this.view.width,l-=u*this.view.offsetY,c=l-u*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 f0e extends p0e{constructor(){super(new MZ(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class u6 extends jZ{constructor(e,n){super(e,n),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ml.DEFAULT_UP),this.updateMatrix(),this.target=new ml,this.shadow=new f0e}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}let g0e=class extends jZ{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}},b0e=class extends ql{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},m6=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=fr(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(fr(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};class x0e extends o0e{constructor(e=10,n=10,r=4473924,i=8947848){r=new lr(r),i=new lr(i);const s=n/2,o=e/n,l=e/2,c=[],d=[];for(let p=0,f=0,x=-l;p<=n;p++,x+=o){c.push(-l,0,x,l,0,x),c.push(x,0,-l,x,0,l);const v=p===s?r:i;v.toArray(d,f),f+=3,v.toArray(d,f),f+=3,v.toArray(d,f),f+=3,v.toArray(d,f),f+=3}const u=new sc;u.setAttribute("position",new sl(c,3)),u.setAttribute("color",new sl(d,3));const m=new NZ({vertexColors:!0,toneMapped:!1});super(u,m),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class y0e extends Sg{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){qn("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function h6(t,e,n,r){const i=v0e(r);switch(n){case aZ:return t*e;case sZ:return t*e/i.components*i.byteLength;case LO:return t*e/i.components*i.byteLength;case OO:return t*e*2/i.components*i.byteLength;case IO:return t*e*2/i.components*i.byteLength;case iZ:return t*e*3/i.components*i.byteLength;case Rc:return t*e*4/i.components*i.byteLength;case zO:return t*e*4/i.components*i.byteLength;case Nk:case Ck:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case Pk:case Tk:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case bF:case yF:return Math.max(t,16)*Math.max(e,8)/4;case gF:case xF:return Math.max(t,8)*Math.max(e,8)/2;case vF:case wF:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case SF:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case _F:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case kF:return Math.floor((t+4)/5)*Math.floor((e+3)/4)*16;case NF:return Math.floor((t+4)/5)*Math.floor((e+4)/5)*16;case CF:return Math.floor((t+5)/6)*Math.floor((e+4)/5)*16;case PF:return Math.floor((t+5)/6)*Math.floor((e+5)/6)*16;case TF:return Math.floor((t+7)/8)*Math.floor((e+4)/5)*16;case AF:return Math.floor((t+7)/8)*Math.floor((e+5)/6)*16;case jF:return Math.floor((t+7)/8)*Math.floor((e+7)/8)*16;case MF:return Math.floor((t+9)/10)*Math.floor((e+4)/5)*16;case EF:return Math.floor((t+9)/10)*Math.floor((e+5)/6)*16;case DF:return Math.floor((t+9)/10)*Math.floor((e+7)/8)*16;case FF:return Math.floor((t+9)/10)*Math.floor((e+9)/10)*16;case RF:return Math.floor((t+11)/12)*Math.floor((e+9)/10)*16;case LF:return Math.floor((t+11)/12)*Math.floor((e+11)/12)*16;case OF:case IF:case zF:return Math.ceil(t/4)*Math.ceil(e/4)*16;case UF:case BF:return Math.ceil(t/4)*Math.ceil(e/4)*8;case HF:case qF:return Math.ceil(t/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function v0e(t){switch(t){case Ed:case eZ:return{byteLength:1,components:1};case $0:case tZ:case cy:return{byteLength:2,components:1};case FO:case RO:return{byteLength:2,components:4};case Jf:case DO:case Hu:return{byteLength:4,components:1};case nZ:case rZ:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:MO}}));typeof window<"u"&&(window.__THREE__?qn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=MO);function EZ(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function w0e(t){const e=new WeakMap;function n(l,c){const d=l.array,u=l.usage,m=d.byteLength,p=t.createBuffer();t.bindBuffer(c,p),t.bufferData(c,d,u),l.onUploadCallback();let f;if(d instanceof Float32Array)f=t.FLOAT;else if(typeof Float16Array<"u"&&d instanceof Float16Array)f=t.HALF_FLOAT;else if(d instanceof Uint16Array)l.isFloat16BufferAttribute?f=t.HALF_FLOAT:f=t.UNSIGNED_SHORT;else if(d instanceof Int16Array)f=t.SHORT;else if(d instanceof Uint32Array)f=t.UNSIGNED_INT;else if(d instanceof Int32Array)f=t.INT;else if(d instanceof Int8Array)f=t.BYTE;else if(d instanceof Uint8Array)f=t.UNSIGNED_BYTE;else if(d instanceof Uint8ClampedArray)f=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+d);return{buffer:p,type:f,bytesPerElement:d.BYTES_PER_ELEMENT,version:l.version,size:m}}function r(l,c,d){const u=c.array,m=c.updateRanges;if(t.bindBuffer(d,l),m.length===0)t.bufferSubData(d,0,u);else{m.sort((f,x)=>f.start-x.start);let p=0;for(let f=1;f<m.length;f++){const x=m[p],v=m[f];v.start<=x.start+x.count+1?x.count=Math.max(x.count,v.start+v.count-x.start):(++p,m[p]=v)}m.length=p+1;for(let f=0,x=m.length;f<x;f++){const v=m[f];t.bufferSubData(d,v.start*u.BYTES_PER_ELEMENT,u,v.start,v.count)}c.clearUpdateRanges()}c.onUploadCallback()}function i(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 u=e.get(l);(!u||u.version<l.version)&&e.set(l,{buffer:l.buffer,type:l.type,bytesPerElement:l.elementSize,version:l.version});return}const d=e.get(l);if(d===void 0)e.set(l,n(l,c));else if(d.version<l.version){if(d.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(d.buffer,l,c),d.version=l.version}}return{get:i,remove:s,update:o}}var S0e=`#ifdef USE_ALPHAHASH
- if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
- #endif`,_0e=`#ifdef USE_ALPHAHASH
- const float ALPHA_HASH_SCALE = 0.05;
- float hash2D( vec2 value ) {
- return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
- }
- float hash3D( vec3 value ) {
- return hash2D( vec2( hash2D( value.xy ), value.z ) );
- }
- float getAlphaHashThreshold( vec3 position ) {
- float maxDeriv = max(
- length( dFdx( position.xyz ) ),
- length( dFdy( position.xyz ) )
- );
- float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
- vec2 pixScales = vec2(
- exp2( floor( log2( pixScale ) ) ),
- exp2( ceil( log2( pixScale ) ) )
- );
- vec2 alpha = vec2(
- hash3D( floor( pixScales.x * position.xyz ) ),
- hash3D( floor( pixScales.y * position.xyz ) )
- );
- float lerpFactor = fract( log2( pixScale ) );
- float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
- float a = min( lerpFactor, 1.0 - lerpFactor );
- vec3 cases = vec3(
- x * x / ( 2.0 * a * ( 1.0 - a ) ),
- ( x - 0.5 * a ) / ( 1.0 - a ),
- 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
- );
- float threshold = ( x < ( 1.0 - a ) )
- ? ( ( x < a ) ? cases.x : cases.y )
- : cases.z;
- return clamp( threshold , 1.0e-6, 1.0 );
- }
- #endif`,k0e=`#ifdef USE_ALPHAMAP
- diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
- #endif`,N0e=`#ifdef USE_ALPHAMAP
- uniform sampler2D alphaMap;
- #endif`,C0e=`#ifdef USE_ALPHATEST
- #ifdef ALPHA_TO_COVERAGE
- diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
- if ( diffuseColor.a == 0.0 ) discard;
- #else
- if ( diffuseColor.a < alphaTest ) discard;
- #endif
- #endif`,P0e=`#ifdef USE_ALPHATEST
- uniform float alphaTest;
- #endif`,T0e=`#ifdef USE_AOMAP
- float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
- reflectedLight.indirectDiffuse *= ambientOcclusion;
- #if defined( USE_CLEARCOAT )
- clearcoatSpecularIndirect *= ambientOcclusion;
- #endif
- #if defined( USE_SHEEN )
- sheenSpecularIndirect *= ambientOcclusion;
- #endif
- #if defined( USE_ENVMAP ) && defined( STANDARD )
- float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
- reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
- #endif
- #endif`,A0e=`#ifdef USE_AOMAP
- uniform sampler2D aoMap;
- uniform float aoMapIntensity;
- #endif`,j0e=`#ifdef USE_BATCHING
- #if ! defined( GL_ANGLE_multi_draw )
- #define gl_DrawID _gl_DrawID
- uniform int _gl_DrawID;
- #endif
- uniform highp sampler2D batchingTexture;
- uniform highp usampler2D batchingIdTexture;
- mat4 getBatchingMatrix( const in float i ) {
- int size = textureSize( batchingTexture, 0 ).x;
- int j = int( i ) * 4;
- int x = j % size;
- int y = j / size;
- vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
- vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
- vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
- vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
- return mat4( v1, v2, v3, v4 );
- }
- float getIndirectIndex( const in int i ) {
- int size = textureSize( batchingIdTexture, 0 ).x;
- int x = i % size;
- int y = i / size;
- return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
- }
- #endif
- #ifdef USE_BATCHING_COLOR
- uniform sampler2D batchingColorTexture;
- vec3 getBatchingColor( const in float i ) {
- int size = textureSize( batchingColorTexture, 0 ).x;
- int j = int( i );
- int x = j % size;
- int y = j / size;
- return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
- }
- #endif`,M0e=`#ifdef USE_BATCHING
- mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
- #endif`,E0e=`vec3 transformed = vec3( position );
- #ifdef USE_ALPHAHASH
- vPosition = vec3( position );
- #endif`,D0e=`vec3 objectNormal = vec3( normal );
- #ifdef USE_TANGENT
- vec3 objectTangent = vec3( tangent.xyz );
- #endif`,F0e=`float G_BlinnPhong_Implicit( ) {
- return 0.25;
- }
- float D_BlinnPhong( const in float shininess, const in float dotNH ) {
- return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
- }
- vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( specularColor, 1.0, dotVH );
- float G = G_BlinnPhong_Implicit( );
- float D = D_BlinnPhong( shininess, dotNH );
- return F * ( G * D );
- } // validated`,R0e=`#ifdef USE_IRIDESCENCE
- const mat3 XYZ_TO_REC709 = mat3(
- 3.2404542, -0.9692660, 0.0556434,
- -1.5371385, 1.8760108, -0.2040259,
- -0.4985314, 0.0415560, 1.0572252
- );
- vec3 Fresnel0ToIor( vec3 fresnel0 ) {
- vec3 sqrtF0 = sqrt( fresnel0 );
- return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
- }
- vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
- return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
- }
- float IorToFresnel0( float transmittedIor, float incidentIor ) {
- return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
- }
- vec3 evalSensitivity( float OPD, vec3 shift ) {
- float phase = 2.0 * PI * OPD * 1.0e-9;
- vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
- vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
- vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
- vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
- 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 ) );
- xyz /= 1.0685e-7;
- vec3 rgb = XYZ_TO_REC709 * xyz;
- return rgb;
- }
- vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
- vec3 I;
- float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
- float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
- float cosTheta2Sq = 1.0 - sinTheta2Sq;
- if ( cosTheta2Sq < 0.0 ) {
- return vec3( 1.0 );
- }
- float cosTheta2 = sqrt( cosTheta2Sq );
- float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
- float R12 = F_Schlick( R0, 1.0, cosTheta1 );
- float T121 = 1.0 - R12;
- float phi12 = 0.0;
- if ( iridescenceIOR < outsideIOR ) phi12 = PI;
- float phi21 = PI - phi12;
- vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
- vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
- vec3 phi23 = vec3( 0.0 );
- if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
- if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
- if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
- float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
- vec3 phi = vec3( phi21 ) + phi23;
- vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
- vec3 r123 = sqrt( R123 );
- vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
- vec3 C0 = R12 + Rs;
- I = C0;
- vec3 Cm = Rs - T121;
- for ( int m = 1; m <= 2; ++ m ) {
- Cm *= r123;
- vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
- I += Cm * Sm;
- }
- return max( I, vec3( 0.0 ) );
- }
- #endif`,L0e=`#ifdef USE_BUMPMAP
- uniform sampler2D bumpMap;
- uniform float bumpScale;
- vec2 dHdxy_fwd() {
- vec2 dSTdx = dFdx( vBumpMapUv );
- vec2 dSTdy = dFdy( vBumpMapUv );
- float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
- float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
- float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
- return vec2( dBx, dBy );
- }
- vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
- vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
- vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
- vec3 vN = surf_norm;
- vec3 R1 = cross( vSigmaY, vN );
- vec3 R2 = cross( vN, vSigmaX );
- float fDet = dot( vSigmaX, R1 ) * faceDirection;
- vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
- return normalize( abs( fDet ) * surf_norm - vGrad );
- }
- #endif`,O0e=`#if NUM_CLIPPING_PLANES > 0
- vec4 plane;
- #ifdef ALPHA_TO_COVERAGE
- float distanceToPlane, distanceGradient;
- float clipOpacity = 1.0;
- #pragma unroll_loop_start
- for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
- distanceGradient = fwidth( distanceToPlane ) / 2.0;
- clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
- if ( clipOpacity == 0.0 ) discard;
- }
- #pragma unroll_loop_end
- #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
- float unionClipOpacity = 1.0;
- #pragma unroll_loop_start
- for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
- distanceGradient = fwidth( distanceToPlane ) / 2.0;
- unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
- }
- #pragma unroll_loop_end
- clipOpacity *= 1.0 - unionClipOpacity;
- #endif
- diffuseColor.a *= clipOpacity;
- if ( diffuseColor.a == 0.0 ) discard;
- #else
- #pragma unroll_loop_start
- for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
- }
- #pragma unroll_loop_end
- #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
- bool clipped = true;
- #pragma unroll_loop_start
- for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
- }
- #pragma unroll_loop_end
- if ( clipped ) discard;
- #endif
- #endif
- #endif`,I0e=`#if NUM_CLIPPING_PLANES > 0
- varying vec3 vClipPosition;
- uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
- #endif`,z0e=`#if NUM_CLIPPING_PLANES > 0
- varying vec3 vClipPosition;
- #endif`,U0e=`#if NUM_CLIPPING_PLANES > 0
- vClipPosition = - mvPosition.xyz;
- #endif`,B0e=`#if defined( USE_COLOR_ALPHA )
- diffuseColor *= vColor;
- #elif defined( USE_COLOR )
- diffuseColor.rgb *= vColor;
- #endif`,H0e=`#if defined( USE_COLOR_ALPHA )
- varying vec4 vColor;
- #elif defined( USE_COLOR )
- varying vec3 vColor;
- #endif`,q0e=`#if defined( USE_COLOR_ALPHA )
- varying vec4 vColor;
- #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
- varying vec3 vColor;
- #endif`,$0e=`#if defined( USE_COLOR_ALPHA )
- vColor = vec4( 1.0 );
- #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
- vColor = vec3( 1.0 );
- #endif
- #ifdef USE_COLOR
- vColor *= color;
- #endif
- #ifdef USE_INSTANCING_COLOR
- vColor.xyz *= instanceColor.xyz;
- #endif
- #ifdef USE_BATCHING_COLOR
- vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
- vColor.xyz *= batchingColor.xyz;
- #endif`,V0e=`#define PI 3.141592653589793
- #define PI2 6.283185307179586
- #define PI_HALF 1.5707963267948966
- #define RECIPROCAL_PI 0.3183098861837907
- #define RECIPROCAL_PI2 0.15915494309189535
- #define EPSILON 1e-6
- #ifndef saturate
- #define saturate( a ) clamp( a, 0.0, 1.0 )
- #endif
- #define whiteComplement( a ) ( 1.0 - saturate( a ) )
- float pow2( const in float x ) { return x*x; }
- vec3 pow2( const in vec3 x ) { return x*x; }
- float pow3( const in float x ) { return x*x*x; }
- float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
- float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
- float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
- highp float rand( const in vec2 uv ) {
- const highp float a = 12.9898, b = 78.233, c = 43758.5453;
- highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
- return fract( sin( sn ) * c );
- }
- #ifdef HIGH_PRECISION
- float precisionSafeLength( vec3 v ) { return length( v ); }
- #else
- float precisionSafeLength( vec3 v ) {
- float maxComponent = max3( abs( v ) );
- return length( v / maxComponent ) * maxComponent;
- }
- #endif
- struct IncidentLight {
- vec3 color;
- vec3 direction;
- bool visible;
- };
- struct ReflectedLight {
- vec3 directDiffuse;
- vec3 directSpecular;
- vec3 indirectDiffuse;
- vec3 indirectSpecular;
- };
- #ifdef USE_ALPHAHASH
- varying vec3 vPosition;
- #endif
- vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
- }
- vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
- }
- bool isPerspectiveMatrix( mat4 m ) {
- return m[ 2 ][ 3 ] == - 1.0;
- }
- vec2 equirectUv( in vec3 dir ) {
- float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
- float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
- return vec2( u, v );
- }
- vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
- return RECIPROCAL_PI * diffuseColor;
- }
- vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
- float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
- return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
- }
- float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
- float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
- return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
- } // validated`,G0e=`#ifdef ENVMAP_TYPE_CUBE_UV
- #define cubeUV_minMipLevel 4.0
- #define cubeUV_minTileSize 16.0
- float getFace( vec3 direction ) {
- vec3 absDirection = abs( direction );
- float face = - 1.0;
- if ( absDirection.x > absDirection.z ) {
- if ( absDirection.x > absDirection.y )
- face = direction.x > 0.0 ? 0.0 : 3.0;
- else
- face = direction.y > 0.0 ? 1.0 : 4.0;
- } else {
- if ( absDirection.z > absDirection.y )
- face = direction.z > 0.0 ? 2.0 : 5.0;
- else
- face = direction.y > 0.0 ? 1.0 : 4.0;
- }
- return face;
- }
- vec2 getUV( vec3 direction, float face ) {
- vec2 uv;
- if ( face == 0.0 ) {
- uv = vec2( direction.z, direction.y ) / abs( direction.x );
- } else if ( face == 1.0 ) {
- uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
- } else if ( face == 2.0 ) {
- uv = vec2( - direction.x, direction.y ) / abs( direction.z );
- } else if ( face == 3.0 ) {
- uv = vec2( - direction.z, direction.y ) / abs( direction.x );
- } else if ( face == 4.0 ) {
- uv = vec2( - direction.x, direction.z ) / abs( direction.y );
- } else {
- uv = vec2( direction.x, direction.y ) / abs( direction.z );
- }
- return 0.5 * ( uv + 1.0 );
- }
- vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
- float face = getFace( direction );
- float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
- mipInt = max( mipInt, cubeUV_minMipLevel );
- float faceSize = exp2( mipInt );
- highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
- if ( face > 2.0 ) {
- uv.y += faceSize;
- face -= 3.0;
- }
- uv.x += face * faceSize;
- uv.x += filterInt * 3.0 * cubeUV_minTileSize;
- uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
- uv.x *= CUBEUV_TEXEL_WIDTH;
- uv.y *= CUBEUV_TEXEL_HEIGHT;
- #ifdef texture2DGradEXT
- return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
- #else
- return texture2D( envMap, uv ).rgb;
- #endif
- }
- #define cubeUV_r0 1.0
- #define cubeUV_m0 - 2.0
- #define cubeUV_r1 0.8
- #define cubeUV_m1 - 1.0
- #define cubeUV_r4 0.4
- #define cubeUV_m4 2.0
- #define cubeUV_r5 0.305
- #define cubeUV_m5 3.0
- #define cubeUV_r6 0.21
- #define cubeUV_m6 4.0
- float roughnessToMip( float roughness ) {
- float mip = 0.0;
- if ( roughness >= cubeUV_r1 ) {
- mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
- } else if ( roughness >= cubeUV_r4 ) {
- mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
- } else if ( roughness >= cubeUV_r5 ) {
- mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
- } else if ( roughness >= cubeUV_r6 ) {
- mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
- } else {
- mip = - 2.0 * log2( 1.16 * roughness ); }
- return mip;
- }
- vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
- float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
- float mipF = fract( mip );
- float mipInt = floor( mip );
- vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
- if ( mipF == 0.0 ) {
- return vec4( color0, 1.0 );
- } else {
- vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
- return vec4( mix( color0, color1, mipF ), 1.0 );
- }
- }
- #endif`,W0e=`vec3 transformedNormal = objectNormal;
- #ifdef USE_TANGENT
- vec3 transformedTangent = objectTangent;
- #endif
- #ifdef USE_BATCHING
- mat3 bm = mat3( batchingMatrix );
- transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
- transformedNormal = bm * transformedNormal;
- #ifdef USE_TANGENT
- transformedTangent = bm * transformedTangent;
- #endif
- #endif
- #ifdef USE_INSTANCING
- mat3 im = mat3( instanceMatrix );
- transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
- transformedNormal = im * transformedNormal;
- #ifdef USE_TANGENT
- transformedTangent = im * transformedTangent;
- #endif
- #endif
- transformedNormal = normalMatrix * transformedNormal;
- #ifdef FLIP_SIDED
- transformedNormal = - transformedNormal;
- #endif
- #ifdef USE_TANGENT
- transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
- #ifdef FLIP_SIDED
- transformedTangent = - transformedTangent;
- #endif
- #endif`,K0e=`#ifdef USE_DISPLACEMENTMAP
- uniform sampler2D displacementMap;
- uniform float displacementScale;
- uniform float displacementBias;
- #endif`,X0e=`#ifdef USE_DISPLACEMENTMAP
- transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
- #endif`,Y0e=`#ifdef USE_EMISSIVEMAP
- vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
- #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
- emissiveColor = sRGBTransferEOTF( emissiveColor );
- #endif
- totalEmissiveRadiance *= emissiveColor.rgb;
- #endif`,Q0e=`#ifdef USE_EMISSIVEMAP
- uniform sampler2D emissiveMap;
- #endif`,Z0e="gl_FragColor = linearToOutputTexel( gl_FragColor );",J0e=`vec4 LinearTransferOETF( in vec4 value ) {
- return value;
- }
- vec4 sRGBTransferEOTF( in vec4 value ) {
- 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 );
- }
- vec4 sRGBTransferOETF( in vec4 value ) {
- 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 );
- }`,ewe=`#ifdef USE_ENVMAP
- #ifdef ENV_WORLDPOS
- vec3 cameraToFrag;
- if ( isOrthographic ) {
- cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
- } else {
- cameraToFrag = normalize( vWorldPosition - cameraPosition );
- }
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- #ifdef ENVMAP_MODE_REFLECTION
- vec3 reflectVec = reflect( cameraToFrag, worldNormal );
- #else
- vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
- #endif
- #else
- vec3 reflectVec = vReflect;
- #endif
- #ifdef ENVMAP_TYPE_CUBE
- vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
- #else
- vec4 envColor = vec4( 0.0 );
- #endif
- #ifdef ENVMAP_BLENDING_MULTIPLY
- outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
- #elif defined( ENVMAP_BLENDING_MIX )
- outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
- #elif defined( ENVMAP_BLENDING_ADD )
- outgoingLight += envColor.xyz * specularStrength * reflectivity;
- #endif
- #endif`,twe=`#ifdef USE_ENVMAP
- uniform float envMapIntensity;
- uniform float flipEnvMap;
- uniform mat3 envMapRotation;
- #ifdef ENVMAP_TYPE_CUBE
- uniform samplerCube envMap;
- #else
- uniform sampler2D envMap;
- #endif
- #endif`,nwe=`#ifdef USE_ENVMAP
- uniform float reflectivity;
- #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
- #define ENV_WORLDPOS
- #endif
- #ifdef ENV_WORLDPOS
- varying vec3 vWorldPosition;
- uniform float refractionRatio;
- #else
- varying vec3 vReflect;
- #endif
- #endif`,rwe=`#ifdef USE_ENVMAP
- #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
- #define ENV_WORLDPOS
- #endif
- #ifdef ENV_WORLDPOS
-
- varying vec3 vWorldPosition;
- #else
- varying vec3 vReflect;
- uniform float refractionRatio;
- #endif
- #endif`,awe=`#ifdef USE_ENVMAP
- #ifdef ENV_WORLDPOS
- vWorldPosition = worldPosition.xyz;
- #else
- vec3 cameraToVertex;
- if ( isOrthographic ) {
- cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
- } else {
- cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
- }
- vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
- #ifdef ENVMAP_MODE_REFLECTION
- vReflect = reflect( cameraToVertex, worldNormal );
- #else
- vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
- #endif
- #endif
- #endif`,iwe=`#ifdef USE_FOG
- vFogDepth = - mvPosition.z;
- #endif`,swe=`#ifdef USE_FOG
- varying float vFogDepth;
- #endif`,owe=`#ifdef USE_FOG
- #ifdef FOG_EXP2
- float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
- #else
- float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
- #endif
- gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
- #endif`,lwe=`#ifdef USE_FOG
- uniform vec3 fogColor;
- varying float vFogDepth;
- #ifdef FOG_EXP2
- uniform float fogDensity;
- #else
- uniform float fogNear;
- uniform float fogFar;
- #endif
- #endif`,cwe=`#ifdef USE_GRADIENTMAP
- uniform sampler2D gradientMap;
- #endif
- vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
- float dotNL = dot( normal, lightDirection );
- vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
- #ifdef USE_GRADIENTMAP
- return vec3( texture2D( gradientMap, coord ).r );
- #else
- vec2 fw = fwidth( coord ) * 0.5;
- return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
- #endif
- }`,dwe=`#ifdef USE_LIGHTMAP
- uniform sampler2D lightMap;
- uniform float lightMapIntensity;
- #endif`,uwe=`LambertMaterial material;
- material.diffuseColor = diffuseColor.rgb;
- material.specularStrength = specularStrength;`,mwe=`varying vec3 vViewPosition;
- struct LambertMaterial {
- vec3 diffuseColor;
- float specularStrength;
- };
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_Lambert
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,hwe=`uniform bool receiveShadow;
- uniform vec3 ambientLightColor;
- #if defined( USE_LIGHT_PROBES )
- uniform vec3 lightProbe[ 9 ];
- #endif
- vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
- float x = normal.x, y = normal.y, z = normal.z;
- vec3 result = shCoefficients[ 0 ] * 0.886227;
- result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
- result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
- result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
- result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
- result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
- result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
- result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
- result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
- return result;
- }
- vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
- return irradiance;
- }
- vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
- vec3 irradiance = ambientLightColor;
- return irradiance;
- }
- float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
- float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
- if ( cutoffDistance > 0.0 ) {
- distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
- }
- return distanceFalloff;
- }
- float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
- return smoothstep( coneCosine, penumbraCosine, angleCosine );
- }
- #if NUM_DIR_LIGHTS > 0
- struct DirectionalLight {
- vec3 direction;
- vec3 color;
- };
- uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
- void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
- light.color = directionalLight.color;
- light.direction = directionalLight.direction;
- light.visible = true;
- }
- #endif
- #if NUM_POINT_LIGHTS > 0
- struct PointLight {
- vec3 position;
- vec3 color;
- float distance;
- float decay;
- };
- uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
- void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
- vec3 lVector = pointLight.position - geometryPosition;
- light.direction = normalize( lVector );
- float lightDistance = length( lVector );
- light.color = pointLight.color;
- light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
- light.visible = ( light.color != vec3( 0.0 ) );
- }
- #endif
- #if NUM_SPOT_LIGHTS > 0
- struct SpotLight {
- vec3 position;
- vec3 direction;
- vec3 color;
- float distance;
- float decay;
- float coneCos;
- float penumbraCos;
- };
- uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
- void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
- vec3 lVector = spotLight.position - geometryPosition;
- light.direction = normalize( lVector );
- float angleCos = dot( light.direction, spotLight.direction );
- float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
- if ( spotAttenuation > 0.0 ) {
- float lightDistance = length( lVector );
- light.color = spotLight.color * spotAttenuation;
- light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
- light.visible = ( light.color != vec3( 0.0 ) );
- } else {
- light.color = vec3( 0.0 );
- light.visible = false;
- }
- }
- #endif
- #if NUM_RECT_AREA_LIGHTS > 0
- struct RectAreaLight {
- vec3 color;
- vec3 position;
- vec3 halfWidth;
- vec3 halfHeight;
- };
- uniform sampler2D ltc_1; uniform sampler2D ltc_2;
- uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
- #endif
- #if NUM_HEMI_LIGHTS > 0
- struct HemisphereLight {
- vec3 direction;
- vec3 skyColor;
- vec3 groundColor;
- };
- uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
- vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
- float dotNL = dot( normal, hemiLight.direction );
- float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
- vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
- return irradiance;
- }
- #endif`,pwe=`#ifdef USE_ENVMAP
- vec3 getIBLIrradiance( const in vec3 normal ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
- return PI * envMapColor.rgb * envMapIntensity;
- #else
- return vec3( 0.0 );
- #endif
- }
- vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 reflectVec = reflect( - viewDir, normal );
- reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
- reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
- vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
- return envMapColor.rgb * envMapIntensity;
- #else
- return vec3( 0.0 );
- #endif
- }
- #ifdef USE_ANISOTROPY
- vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 bentNormal = cross( bitangent, viewDir );
- bentNormal = normalize( cross( bentNormal, bitangent ) );
- bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
- return getIBLRadiance( viewDir, bentNormal, roughness );
- #else
- return vec3( 0.0 );
- #endif
- }
- #endif
- #endif`,fwe=`ToonMaterial material;
- material.diffuseColor = diffuseColor.rgb;`,gwe=`varying vec3 vViewPosition;
- struct ToonMaterial {
- vec3 diffuseColor;
- };
- 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 ) {
- vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_Toon
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,bwe=`BlinnPhongMaterial material;
- material.diffuseColor = diffuseColor.rgb;
- material.specularColor = specular;
- material.specularShininess = shininess;
- material.specularStrength = specularStrength;`,xwe=`varying vec3 vViewPosition;
- struct BlinnPhongMaterial {
- vec3 diffuseColor;
- vec3 specularColor;
- float specularShininess;
- float specularStrength;
- };
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_BlinnPhong
- #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,ywe=`PhysicalMaterial material;
- material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
- vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
- float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
- material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
- material.roughness = min( material.roughness, 1.0 );
- #ifdef IOR
- material.ior = ior;
- #ifdef USE_SPECULAR
- float specularIntensityFactor = specularIntensity;
- vec3 specularColorFactor = specularColor;
- #ifdef USE_SPECULAR_COLORMAP
- specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
- #endif
- material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
- #else
- float specularIntensityFactor = 1.0;
- vec3 specularColorFactor = vec3( 1.0 );
- material.specularF90 = 1.0;
- #endif
- material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
- #else
- material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
- material.specularF90 = 1.0;
- #endif
- #ifdef USE_CLEARCOAT
- material.clearcoat = clearcoat;
- material.clearcoatRoughness = clearcoatRoughness;
- material.clearcoatF0 = vec3( 0.04 );
- material.clearcoatF90 = 1.0;
- #ifdef USE_CLEARCOATMAP
- material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
- #endif
- material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
- material.clearcoatRoughness += geometryRoughness;
- material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
- #endif
- #ifdef USE_DISPERSION
- material.dispersion = dispersion;
- #endif
- #ifdef USE_IRIDESCENCE
- material.iridescence = iridescence;
- material.iridescenceIOR = iridescenceIOR;
- #ifdef USE_IRIDESCENCEMAP
- material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
- #else
- material.iridescenceThickness = iridescenceThicknessMaximum;
- #endif
- #endif
- #ifdef USE_SHEEN
- material.sheenColor = sheenColor;
- #ifdef USE_SHEEN_COLORMAP
- material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
- #endif
- material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
- #ifdef USE_SHEEN_ROUGHNESSMAP
- material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
- #endif
- #endif
- #ifdef USE_ANISOTROPY
- #ifdef USE_ANISOTROPYMAP
- mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
- vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
- vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
- #else
- vec2 anisotropyV = anisotropyVector;
- #endif
- material.anisotropy = length( anisotropyV );
- if( material.anisotropy == 0.0 ) {
- anisotropyV = vec2( 1.0, 0.0 );
- } else {
- anisotropyV /= material.anisotropy;
- material.anisotropy = saturate( material.anisotropy );
- }
- material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
- material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
- material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
- #endif`,vwe=`uniform sampler2D dfgLUT;
- struct PhysicalMaterial {
- vec3 diffuseColor;
- float roughness;
- vec3 specularColor;
- float specularF90;
- float dispersion;
- #ifdef USE_CLEARCOAT
- float clearcoat;
- float clearcoatRoughness;
- vec3 clearcoatF0;
- float clearcoatF90;
- #endif
- #ifdef USE_IRIDESCENCE
- float iridescence;
- float iridescenceIOR;
- float iridescenceThickness;
- vec3 iridescenceFresnel;
- vec3 iridescenceF0;
- #endif
- #ifdef USE_SHEEN
- vec3 sheenColor;
- float sheenRoughness;
- #endif
- #ifdef IOR
- float ior;
- #endif
- #ifdef USE_TRANSMISSION
- float transmission;
- float transmissionAlpha;
- float thickness;
- float attenuationDistance;
- vec3 attenuationColor;
- #endif
- #ifdef USE_ANISOTROPY
- float anisotropy;
- float alphaT;
- vec3 anisotropyT;
- vec3 anisotropyB;
- #endif
- };
- vec3 clearcoatSpecularDirect = vec3( 0.0 );
- vec3 clearcoatSpecularIndirect = vec3( 0.0 );
- vec3 sheenSpecularDirect = vec3( 0.0 );
- vec3 sheenSpecularIndirect = vec3(0.0 );
- vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
- float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
- float x2 = x * x;
- float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
- return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
- }
- float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
- float a2 = pow2( alpha );
- float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
- float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
- return 0.5 / max( gv + gl, EPSILON );
- }
- float D_GGX( const in float alpha, const in float dotNH ) {
- float a2 = pow2( alpha );
- float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
- return RECIPROCAL_PI * a2 / pow2( denom );
- }
- #ifdef USE_ANISOTROPY
- 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 ) {
- float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
- float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
- float v = 0.5 / ( gv + gl );
- return saturate(v);
- }
- float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
- float a2 = alphaT * alphaB;
- highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
- highp float v2 = dot( v, v );
- float w2 = a2 / v2;
- return RECIPROCAL_PI * a2 * pow2 ( w2 );
- }
- #endif
- #ifdef USE_CLEARCOAT
- vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
- vec3 f0 = material.clearcoatF0;
- float f90 = material.clearcoatF90;
- float roughness = material.clearcoatRoughness;
- float alpha = pow2( roughness );
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( f0, f90, dotVH );
- float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
- float D = D_GGX( alpha, dotNH );
- return F * ( V * D );
- }
- #endif
- vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
- vec3 f0 = material.specularColor;
- float f90 = material.specularF90;
- float roughness = material.roughness;
- float alpha = pow2( roughness );
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( f0, f90, dotVH );
- #ifdef USE_IRIDESCENCE
- F = mix( F, material.iridescenceFresnel, material.iridescence );
- #endif
- #ifdef USE_ANISOTROPY
- float dotTL = dot( material.anisotropyT, lightDir );
- float dotTV = dot( material.anisotropyT, viewDir );
- float dotTH = dot( material.anisotropyT, halfDir );
- float dotBL = dot( material.anisotropyB, lightDir );
- float dotBV = dot( material.anisotropyB, viewDir );
- float dotBH = dot( material.anisotropyB, halfDir );
- float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
- float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
- #else
- float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
- float D = D_GGX( alpha, dotNH );
- #endif
- return F * ( V * D );
- }
- vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
- const float LUT_SIZE = 64.0;
- const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
- const float LUT_BIAS = 0.5 / LUT_SIZE;
- float dotNV = saturate( dot( N, V ) );
- vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
- uv = uv * LUT_SCALE + LUT_BIAS;
- return uv;
- }
- float LTC_ClippedSphereFormFactor( const in vec3 f ) {
- float l = length( f );
- return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
- }
- vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
- float x = dot( v1, v2 );
- float y = abs( x );
- float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
- float b = 3.4175940 + ( 4.1616724 + y ) * y;
- float v = a / b;
- float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
- return cross( v1, v2 ) * theta_sintheta;
- }
- vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
- vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
- vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
- vec3 lightNormal = cross( v1, v2 );
- if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
- vec3 T1, T2;
- T1 = normalize( V - N * dot( V, N ) );
- T2 = - cross( N, T1 );
- mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
- vec3 coords[ 4 ];
- coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
- coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
- coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
- coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
- coords[ 0 ] = normalize( coords[ 0 ] );
- coords[ 1 ] = normalize( coords[ 1 ] );
- coords[ 2 ] = normalize( coords[ 2 ] );
- coords[ 3 ] = normalize( coords[ 3 ] );
- vec3 vectorFormFactor = vec3( 0.0 );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
- float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
- return vec3( result );
- }
- #if defined( USE_SHEEN )
- float D_Charlie( float roughness, float dotNH ) {
- float alpha = pow2( roughness );
- float invAlpha = 1.0 / alpha;
- float cos2h = dotNH * dotNH;
- float sin2h = max( 1.0 - cos2h, 0.0078125 );
- return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
- }
- float V_Neubelt( float dotNV, float dotNL ) {
- return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
- }
- vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float D = D_Charlie( sheenRoughness, dotNH );
- float V = V_Neubelt( dotNV, dotNL );
- return sheenColor * ( D * V );
- }
- #endif
- float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
- float dotNV = saturate( dot( normal, viewDir ) );
- float r2 = roughness * roughness;
- float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
- float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
- float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
- return saturate( DG * RECIPROCAL_PI );
- }
- vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
- float dotNV = saturate( dot( normal, viewDir ) );
- vec2 uv = vec2( roughness, dotNV );
- return texture2D( dfgLUT, uv ).rg;
- }
- vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
- vec2 fab = DFGApprox( normal, viewDir, roughness );
- return specularColor * fab.x + specularF90 * fab.y;
- }
- #ifdef USE_IRIDESCENCE
- 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 ) {
- #else
- 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 ) {
- #endif
- vec2 fab = DFGApprox( normal, viewDir, roughness );
- #ifdef USE_IRIDESCENCE
- vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
- #else
- vec3 Fr = specularColor;
- #endif
- vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
- float Ess = fab.x + fab.y;
- float Ems = 1.0 - Ess;
- vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
- singleScatter += FssEss;
- multiScatter += Fms * Ems;
- }
- vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
- vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness );
- vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness );
- vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y;
- vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y;
- float Ess_V = dfgV.x + dfgV.y;
- float Ess_L = dfgL.x + dfgL.y;
- float Ems_V = 1.0 - Ess_V;
- float Ems_L = 1.0 - Ess_L;
- vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619;
- vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON );
- float compensationFactor = Ems_V * Ems_L;
- vec3 multiScatter = Fms * compensationFactor;
- return singleScatter + multiScatter;
- }
- #if NUM_RECT_AREA_LIGHTS > 0
- 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 ) {
- vec3 normal = geometryNormal;
- vec3 viewDir = geometryViewDir;
- vec3 position = geometryPosition;
- vec3 lightPos = rectAreaLight.position;
- vec3 halfWidth = rectAreaLight.halfWidth;
- vec3 halfHeight = rectAreaLight.halfHeight;
- vec3 lightColor = rectAreaLight.color;
- float roughness = material.roughness;
- vec3 rectCoords[ 4 ];
- rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
- rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
- rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
- vec2 uv = LTC_Uv( normal, viewDir, roughness );
- vec4 t1 = texture2D( ltc_1, uv );
- vec4 t2 = texture2D( ltc_2, uv );
- mat3 mInv = mat3(
- vec3( t1.x, 0, t1.y ),
- vec3( 0, 1, 0 ),
- vec3( t1.z, 0, t1.w )
- );
- vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
- reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
- reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
- }
- #endif
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- #ifdef USE_CLEARCOAT
- float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
- vec3 ccIrradiance = dotNLcc * directLight.color;
- clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
- #endif
- #ifdef USE_SHEEN
- sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
- #endif
- reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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) {
- #ifdef USE_CLEARCOAT
- clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
- #endif
- #ifdef USE_SHEEN
- sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
- #endif
- vec3 singleScattering = vec3( 0.0 );
- vec3 multiScattering = vec3( 0.0 );
- vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
- #ifdef USE_IRIDESCENCE
- computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
- #else
- computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
- #endif
- vec3 totalScattering = singleScattering + multiScattering;
- vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
- reflectedLight.indirectSpecular += radiance * singleScattering;
- reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
- reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
- }
- #define RE_Direct RE_Direct_Physical
- #define RE_Direct_RectArea RE_Direct_RectArea_Physical
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
- #define RE_IndirectSpecular RE_IndirectSpecular_Physical
- float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
- return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
- }`,wwe=`
- vec3 geometryPosition = - vViewPosition;
- vec3 geometryNormal = normal;
- vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
- vec3 geometryClearcoatNormal = vec3( 0.0 );
- #ifdef USE_CLEARCOAT
- geometryClearcoatNormal = clearcoatNormal;
- #endif
- #ifdef USE_IRIDESCENCE
- float dotNVi = saturate( dot( normal, geometryViewDir ) );
- if ( material.iridescenceThickness == 0.0 ) {
- material.iridescence = 0.0;
- } else {
- material.iridescence = saturate( material.iridescence );
- }
- if ( material.iridescence > 0.0 ) {
- material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
- material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
- }
- #endif
- IncidentLight directLight;
- #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
- PointLight pointLight;
- #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
- PointLightShadow pointLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
- pointLight = pointLights[ i ];
- getPointLightInfo( pointLight, geometryPosition, directLight );
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
- pointLightShadow = pointLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
- SpotLight spotLight;
- vec4 spotColor;
- vec3 spotLightCoord;
- bool inSpotLightMap;
- #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
- SpotLightShadow spotLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
- spotLight = spotLights[ i ];
- getSpotLightInfo( spotLight, geometryPosition, directLight );
- #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
- #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
- #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
- #else
- #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
- #endif
- #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
- spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
- inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
- spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
- directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
- #endif
- #undef SPOT_LIGHT_MAP_INDEX
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- spotLightShadow = spotLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
- DirectionalLight directionalLight;
- #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
- DirectionalLightShadow directionalLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
- directionalLight = directionalLights[ i ];
- getDirectionalLightInfo( directionalLight, directLight );
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
- directionalLightShadow = directionalLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
- RectAreaLight rectAreaLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
- rectAreaLight = rectAreaLights[ i ];
- RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if defined( RE_IndirectDiffuse )
- vec3 iblIrradiance = vec3( 0.0 );
- vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
- #if defined( USE_LIGHT_PROBES )
- irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
- #endif
- #if ( NUM_HEMI_LIGHTS > 0 )
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
- irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
- }
- #pragma unroll_loop_end
- #endif
- #endif
- #if defined( RE_IndirectSpecular )
- vec3 radiance = vec3( 0.0 );
- vec3 clearcoatRadiance = vec3( 0.0 );
- #endif`,Swe=`#if defined( RE_IndirectDiffuse )
- #ifdef USE_LIGHTMAP
- vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
- vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
- irradiance += lightMapIrradiance;
- #endif
- #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
- iblIrradiance += getIBLIrradiance( geometryNormal );
- #endif
- #endif
- #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
- #ifdef USE_ANISOTROPY
- radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
- #else
- radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
- #endif
- #ifdef USE_CLEARCOAT
- clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
- #endif
- #endif`,_we=`#if defined( RE_IndirectDiffuse )
- RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- #endif
- #if defined( RE_IndirectSpecular )
- RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- #endif`,kwe=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
- gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
- #endif`,Nwe=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
- uniform float logDepthBufFC;
- varying float vFragDepth;
- varying float vIsPerspective;
- #endif`,Cwe=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
- varying float vFragDepth;
- varying float vIsPerspective;
- #endif`,Pwe=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
- vFragDepth = 1.0 + gl_Position.w;
- vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
- #endif`,Twe=`#ifdef USE_MAP
- vec4 sampledDiffuseColor = texture2D( map, vMapUv );
- #ifdef DECODE_VIDEO_TEXTURE
- sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
- #endif
- diffuseColor *= sampledDiffuseColor;
- #endif`,Awe=`#ifdef USE_MAP
- uniform sampler2D map;
- #endif`,jwe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
- #if defined( USE_POINTS_UV )
- vec2 uv = vUv;
- #else
- vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
- #endif
- #endif
- #ifdef USE_MAP
- diffuseColor *= texture2D( map, uv );
- #endif
- #ifdef USE_ALPHAMAP
- diffuseColor.a *= texture2D( alphaMap, uv ).g;
- #endif`,Mwe=`#if defined( USE_POINTS_UV )
- varying vec2 vUv;
- #else
- #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
- uniform mat3 uvTransform;
- #endif
- #endif
- #ifdef USE_MAP
- uniform sampler2D map;
- #endif
- #ifdef USE_ALPHAMAP
- uniform sampler2D alphaMap;
- #endif`,Ewe=`float metalnessFactor = metalness;
- #ifdef USE_METALNESSMAP
- vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
- metalnessFactor *= texelMetalness.b;
- #endif`,Dwe=`#ifdef USE_METALNESSMAP
- uniform sampler2D metalnessMap;
- #endif`,Fwe=`#ifdef USE_INSTANCING_MORPH
- float morphTargetInfluences[ MORPHTARGETS_COUNT ];
- float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
- }
- #endif`,Rwe=`#if defined( USE_MORPHCOLORS )
- vColor *= morphTargetBaseInfluence;
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- #if defined( USE_COLOR_ALPHA )
- if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
- #elif defined( USE_COLOR )
- if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
- #endif
- }
- #endif`,Lwe=`#ifdef USE_MORPHNORMALS
- objectNormal *= morphTargetBaseInfluence;
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
- }
- #endif`,Owe=`#ifdef USE_MORPHTARGETS
- #ifndef USE_INSTANCING_MORPH
- uniform float morphTargetBaseInfluence;
- uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
- #endif
- uniform sampler2DArray morphTargetsTexture;
- uniform ivec2 morphTargetsTextureSize;
- vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
- int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
- int y = texelIndex / morphTargetsTextureSize.x;
- int x = texelIndex - y * morphTargetsTextureSize.x;
- ivec3 morphUV = ivec3( x, y, morphTargetIndex );
- return texelFetch( morphTargetsTexture, morphUV, 0 );
- }
- #endif`,Iwe=`#ifdef USE_MORPHTARGETS
- transformed *= morphTargetBaseInfluence;
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
- }
- #endif`,zwe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
- #ifdef FLAT_SHADED
- vec3 fdx = dFdx( vViewPosition );
- vec3 fdy = dFdy( vViewPosition );
- vec3 normal = normalize( cross( fdx, fdy ) );
- #else
- vec3 normal = normalize( vNormal );
- #ifdef DOUBLE_SIDED
- normal *= faceDirection;
- #endif
- #endif
- #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
- #ifdef USE_TANGENT
- mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
- #else
- mat3 tbn = getTangentFrame( - vViewPosition, normal,
- #if defined( USE_NORMALMAP )
- vNormalMapUv
- #elif defined( USE_CLEARCOAT_NORMALMAP )
- vClearcoatNormalMapUv
- #else
- vUv
- #endif
- );
- #endif
- #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
- tbn[0] *= faceDirection;
- tbn[1] *= faceDirection;
- #endif
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- #ifdef USE_TANGENT
- mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
- #else
- mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
- #endif
- #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
- tbn2[0] *= faceDirection;
- tbn2[1] *= faceDirection;
- #endif
- #endif
- vec3 nonPerturbedNormal = normal;`,Uwe=`#ifdef USE_NORMALMAP_OBJECTSPACE
- normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
- #ifdef FLIP_SIDED
- normal = - normal;
- #endif
- #ifdef DOUBLE_SIDED
- normal = normal * faceDirection;
- #endif
- normal = normalize( normalMatrix * normal );
- #elif defined( USE_NORMALMAP_TANGENTSPACE )
- vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
- mapN.xy *= normalScale;
- normal = normalize( tbn * mapN );
- #elif defined( USE_BUMPMAP )
- normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
- #endif`,Bwe=`#ifndef FLAT_SHADED
- varying vec3 vNormal;
- #ifdef USE_TANGENT
- varying vec3 vTangent;
- varying vec3 vBitangent;
- #endif
- #endif`,Hwe=`#ifndef FLAT_SHADED
- varying vec3 vNormal;
- #ifdef USE_TANGENT
- varying vec3 vTangent;
- varying vec3 vBitangent;
- #endif
- #endif`,qwe=`#ifndef FLAT_SHADED
- vNormal = normalize( transformedNormal );
- #ifdef USE_TANGENT
- vTangent = normalize( transformedTangent );
- vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
- #endif
- #endif`,$we=`#ifdef USE_NORMALMAP
- uniform sampler2D normalMap;
- uniform vec2 normalScale;
- #endif
- #ifdef USE_NORMALMAP_OBJECTSPACE
- uniform mat3 normalMatrix;
- #endif
- #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
- mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
- vec3 q0 = dFdx( eye_pos.xyz );
- vec3 q1 = dFdy( eye_pos.xyz );
- vec2 st0 = dFdx( uv.st );
- vec2 st1 = dFdy( uv.st );
- vec3 N = surf_norm;
- vec3 q1perp = cross( q1, N );
- vec3 q0perp = cross( N, q0 );
- vec3 T = q1perp * st0.x + q0perp * st1.x;
- vec3 B = q1perp * st0.y + q0perp * st1.y;
- float det = max( dot( T, T ), dot( B, B ) );
- float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
- return mat3( T * scale, B * scale, N );
- }
- #endif`,Vwe=`#ifdef USE_CLEARCOAT
- vec3 clearcoatNormal = nonPerturbedNormal;
- #endif`,Gwe=`#ifdef USE_CLEARCOAT_NORMALMAP
- vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
- clearcoatMapN.xy *= clearcoatNormalScale;
- clearcoatNormal = normalize( tbn2 * clearcoatMapN );
- #endif`,Wwe=`#ifdef USE_CLEARCOATMAP
- uniform sampler2D clearcoatMap;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- uniform sampler2D clearcoatNormalMap;
- uniform vec2 clearcoatNormalScale;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- uniform sampler2D clearcoatRoughnessMap;
- #endif`,Kwe=`#ifdef USE_IRIDESCENCEMAP
- uniform sampler2D iridescenceMap;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- uniform sampler2D iridescenceThicknessMap;
- #endif`,Xwe=`#ifdef OPAQUE
- diffuseColor.a = 1.0;
- #endif
- #ifdef USE_TRANSMISSION
- diffuseColor.a *= material.transmissionAlpha;
- #endif
- gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Ywe=`vec3 packNormalToRGB( const in vec3 normal ) {
- return normalize( normal ) * 0.5 + 0.5;
- }
- vec3 unpackRGBToNormal( const in vec3 rgb ) {
- return 2.0 * rgb.xyz - 1.0;
- }
- const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
- const float Inv255 = 1. / 255.;
- const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
- const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
- const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
- const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
- vec4 packDepthToRGBA( const in float v ) {
- if( v <= 0.0 )
- return vec4( 0., 0., 0., 0. );
- if( v >= 1.0 )
- return vec4( 1., 1., 1., 1. );
- float vuf;
- float af = modf( v * PackFactors.a, vuf );
- float bf = modf( vuf * ShiftRight8, vuf );
- float gf = modf( vuf * ShiftRight8, vuf );
- return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
- }
- vec3 packDepthToRGB( const in float v ) {
- if( v <= 0.0 )
- return vec3( 0., 0., 0. );
- if( v >= 1.0 )
- return vec3( 1., 1., 1. );
- float vuf;
- float bf = modf( v * PackFactors.b, vuf );
- float gf = modf( vuf * ShiftRight8, vuf );
- return vec3( vuf * Inv255, gf * PackUpscale, bf );
- }
- vec2 packDepthToRG( const in float v ) {
- if( v <= 0.0 )
- return vec2( 0., 0. );
- if( v >= 1.0 )
- return vec2( 1., 1. );
- float vuf;
- float gf = modf( v * 256., vuf );
- return vec2( vuf * Inv255, gf );
- }
- float unpackRGBAToDepth( const in vec4 v ) {
- return dot( v, UnpackFactors4 );
- }
- float unpackRGBToDepth( const in vec3 v ) {
- return dot( v, UnpackFactors3 );
- }
- float unpackRGToDepth( const in vec2 v ) {
- return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
- }
- vec4 pack2HalfToRGBA( const in vec2 v ) {
- vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
- return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
- }
- vec2 unpackRGBATo2Half( const in vec4 v ) {
- return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
- }
- float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
- return ( viewZ + near ) / ( near - far );
- }
- float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
- return depth * ( near - far ) - near;
- }
- float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
- return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
- }
- float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
- return ( near * far ) / ( ( far - near ) * depth - far );
- }`,Qwe=`#ifdef PREMULTIPLIED_ALPHA
- gl_FragColor.rgb *= gl_FragColor.a;
- #endif`,Zwe=`vec4 mvPosition = vec4( transformed, 1.0 );
- #ifdef USE_BATCHING
- mvPosition = batchingMatrix * mvPosition;
- #endif
- #ifdef USE_INSTANCING
- mvPosition = instanceMatrix * mvPosition;
- #endif
- mvPosition = modelViewMatrix * mvPosition;
- gl_Position = projectionMatrix * mvPosition;`,Jwe=`#ifdef DITHERING
- gl_FragColor.rgb = dithering( gl_FragColor.rgb );
- #endif`,eSe=`#ifdef DITHERING
- vec3 dithering( vec3 color ) {
- float grid_position = rand( gl_FragCoord.xy );
- vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
- dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
- return color + dither_shift_RGB;
- }
- #endif`,tSe=`float roughnessFactor = roughness;
- #ifdef USE_ROUGHNESSMAP
- vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
- roughnessFactor *= texelRoughness.g;
- #endif`,nSe=`#ifdef USE_ROUGHNESSMAP
- uniform sampler2D roughnessMap;
- #endif`,rSe=`#if NUM_SPOT_LIGHT_COORDS > 0
- varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
- #endif
- #if NUM_SPOT_LIGHT_MAPS > 0
- uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
- #endif
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
- varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
- struct DirectionalLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
- struct SpotLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
- varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
- struct PointLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- float shadowCameraNear;
- float shadowCameraFar;
- };
- uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
- #endif
- float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
- float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
- #ifdef USE_REVERSED_DEPTH_BUFFER
- return step( depth, compare );
- #else
- return step( compare, depth );
- #endif
- }
- vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
- return unpackRGBATo2Half( texture2D( shadow, uv ) );
- }
- float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
- float occlusion = 1.0;
- vec2 distribution = texture2DDistribution( shadow, uv );
- #ifdef USE_REVERSED_DEPTH_BUFFER
- float hard_shadow = step( distribution.x, compare );
- #else
- float hard_shadow = step( compare, distribution.x );
- #endif
- if ( hard_shadow != 1.0 ) {
- float distance = compare - distribution.x;
- float variance = max( 0.00000, distribution.y * distribution.y );
- 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 );
- }
- return occlusion;
- }
- float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
- float shadow = 1.0;
- shadowCoord.xyz /= shadowCoord.w;
- shadowCoord.z += shadowBias;
- bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
- bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
- if ( frustumTest ) {
- #if defined( SHADOWMAP_TYPE_PCF )
- vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
- float dx0 = - texelSize.x * shadowRadius;
- float dy0 = - texelSize.y * shadowRadius;
- float dx1 = + texelSize.x * shadowRadius;
- float dy1 = + texelSize.y * shadowRadius;
- float dx2 = dx0 / 2.0;
- float dy2 = dy0 / 2.0;
- float dx3 = dx1 / 2.0;
- float dy3 = dy1 / 2.0;
- shadow = (
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
- ) * ( 1.0 / 17.0 );
- #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
- vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
- float dx = texelSize.x;
- float dy = texelSize.y;
- vec2 uv = shadowCoord.xy;
- vec2 f = fract( uv * shadowMapSize + 0.5 );
- uv -= f * texelSize;
- shadow = (
- texture2DCompare( shadowMap, uv, shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
- f.x ) +
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
- f.x ) +
- mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
- f.y ) +
- mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
- f.y ) +
- mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
- f.x ),
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
- f.x ),
- f.y )
- ) * ( 1.0 / 9.0 );
- #elif defined( SHADOWMAP_TYPE_VSM )
- shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
- #else
- shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
- #endif
- }
- return mix( 1.0, shadow, shadowIntensity );
- }
- vec2 cubeToUV( vec3 v, float texelSizeY ) {
- vec3 absV = abs( v );
- float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
- absV *= scaleToCube;
- v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
- vec2 planar = v.xy;
- float almostATexel = 1.5 * texelSizeY;
- float almostOne = 1.0 - almostATexel;
- if ( absV.z >= almostOne ) {
- if ( v.z > 0.0 )
- planar.x = 4.0 - v.x;
- } else if ( absV.x >= almostOne ) {
- float signX = sign( v.x );
- planar.x = v.z * signX + 2.0 * signX;
- } else if ( absV.y >= almostOne ) {
- float signY = sign( v.y );
- planar.x = v.x + 2.0 * signY + 2.0;
- planar.y = v.z * signY - 2.0;
- }
- return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
- }
- float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
- float shadow = 1.0;
- vec3 lightToPosition = shadowCoord.xyz;
-
- float lightToPositionLength = length( lightToPosition );
- if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
- float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
- vec3 bd3D = normalize( lightToPosition );
- vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
- #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
- vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
- shadow = (
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
- ) * ( 1.0 / 9.0 );
- #else
- shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
- #endif
- }
- return mix( 1.0, shadow, shadowIntensity );
- }
- #endif`,aSe=`#if NUM_SPOT_LIGHT_COORDS > 0
- uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
- varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
- #endif
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
- varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
- struct DirectionalLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- struct SpotLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
- varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
- struct PointLightShadow {
- float shadowIntensity;
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- float shadowCameraNear;
- float shadowCameraFar;
- };
- uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
- #endif
- #endif`,iSe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
- vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
- vec4 shadowWorldPosition;
- #endif
- #if defined( USE_SHADOWMAP )
- #if NUM_DIR_LIGHT_SHADOWS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
- shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
- vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
- shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
- vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif
- #endif
- #if NUM_SPOT_LIGHT_COORDS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
- shadowWorldPosition = worldPosition;
- #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
- #endif
- vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif`,sSe=`float getShadowMask() {
- float shadow = 1.0;
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- DirectionalLightShadow directionalLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
- directionalLight = directionalLightShadows[ i ];
- shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- SpotLightShadow spotLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
- spotLight = spotLightShadows[ i ];
- shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- PointLightShadow pointLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
- pointLight = pointLightShadows[ i ];
- shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #endif
- return shadow;
- }`,oSe=`#ifdef USE_SKINNING
- mat4 boneMatX = getBoneMatrix( skinIndex.x );
- mat4 boneMatY = getBoneMatrix( skinIndex.y );
- mat4 boneMatZ = getBoneMatrix( skinIndex.z );
- mat4 boneMatW = getBoneMatrix( skinIndex.w );
- #endif`,lSe=`#ifdef USE_SKINNING
- uniform mat4 bindMatrix;
- uniform mat4 bindMatrixInverse;
- uniform highp sampler2D boneTexture;
- mat4 getBoneMatrix( const in float i ) {
- int size = textureSize( boneTexture, 0 ).x;
- int j = int( i ) * 4;
- int x = j % size;
- int y = j / size;
- vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
- vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
- vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
- vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
- return mat4( v1, v2, v3, v4 );
- }
- #endif`,cSe=`#ifdef USE_SKINNING
- vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
- vec4 skinned = vec4( 0.0 );
- skinned += boneMatX * skinVertex * skinWeight.x;
- skinned += boneMatY * skinVertex * skinWeight.y;
- skinned += boneMatZ * skinVertex * skinWeight.z;
- skinned += boneMatW * skinVertex * skinWeight.w;
- transformed = ( bindMatrixInverse * skinned ).xyz;
- #endif`,dSe=`#ifdef USE_SKINNING
- mat4 skinMatrix = mat4( 0.0 );
- skinMatrix += skinWeight.x * boneMatX;
- skinMatrix += skinWeight.y * boneMatY;
- skinMatrix += skinWeight.z * boneMatZ;
- skinMatrix += skinWeight.w * boneMatW;
- skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
- objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
- #ifdef USE_TANGENT
- objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
- #endif
- #endif`,uSe=`float specularStrength;
- #ifdef USE_SPECULARMAP
- vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
- specularStrength = texelSpecular.r;
- #else
- specularStrength = 1.0;
- #endif`,mSe=`#ifdef USE_SPECULARMAP
- uniform sampler2D specularMap;
- #endif`,hSe=`#if defined( TONE_MAPPING )
- gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
- #endif`,pSe=`#ifndef saturate
- #define saturate( a ) clamp( a, 0.0, 1.0 )
- #endif
- uniform float toneMappingExposure;
- vec3 LinearToneMapping( vec3 color ) {
- return saturate( toneMappingExposure * color );
- }
- vec3 ReinhardToneMapping( vec3 color ) {
- color *= toneMappingExposure;
- return saturate( color / ( vec3( 1.0 ) + color ) );
- }
- vec3 CineonToneMapping( vec3 color ) {
- color *= toneMappingExposure;
- color = max( vec3( 0.0 ), color - 0.004 );
- return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
- }
- vec3 RRTAndODTFit( vec3 v ) {
- vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
- vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
- return a / b;
- }
- vec3 ACESFilmicToneMapping( vec3 color ) {
- const mat3 ACESInputMat = mat3(
- vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
- vec3( 0.04823, 0.01566, 0.83777 )
- );
- const mat3 ACESOutputMat = mat3(
- vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
- vec3( -0.07367, -0.00605, 1.07602 )
- );
- color *= toneMappingExposure / 0.6;
- color = ACESInputMat * color;
- color = RRTAndODTFit( color );
- color = ACESOutputMat * color;
- return saturate( color );
- }
- const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
- vec3( 1.6605, - 0.1246, - 0.0182 ),
- vec3( - 0.5876, 1.1329, - 0.1006 ),
- vec3( - 0.0728, - 0.0083, 1.1187 )
- );
- const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
- vec3( 0.6274, 0.0691, 0.0164 ),
- vec3( 0.3293, 0.9195, 0.0880 ),
- vec3( 0.0433, 0.0113, 0.8956 )
- );
- vec3 agxDefaultContrastApprox( vec3 x ) {
- vec3 x2 = x * x;
- vec3 x4 = x2 * x2;
- return + 15.5 * x4 * x2
- - 40.14 * x4 * x
- + 31.96 * x4
- - 6.868 * x2 * x
- + 0.4298 * x2
- + 0.1191 * x
- - 0.00232;
- }
- vec3 AgXToneMapping( vec3 color ) {
- const mat3 AgXInsetMatrix = mat3(
- vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
- vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
- vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
- );
- const mat3 AgXOutsetMatrix = mat3(
- vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
- vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
- vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
- );
- const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
- color *= toneMappingExposure;
- color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
- color = AgXInsetMatrix * color;
- color = max( color, 1e-10 ); color = log2( color );
- color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
- color = clamp( color, 0.0, 1.0 );
- color = agxDefaultContrastApprox( color );
- color = AgXOutsetMatrix * color;
- color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
- color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
- color = clamp( color, 0.0, 1.0 );
- return color;
- }
- vec3 NeutralToneMapping( vec3 color ) {
- const float StartCompression = 0.8 - 0.04;
- const float Desaturation = 0.15;
- color *= toneMappingExposure;
- float x = min( color.r, min( color.g, color.b ) );
- float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
- color -= offset;
- float peak = max( color.r, max( color.g, color.b ) );
- if ( peak < StartCompression ) return color;
- float d = 1. - StartCompression;
- float newPeak = 1. - d * d / ( peak + d - StartCompression );
- color *= newPeak / peak;
- float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
- return mix( color, vec3( newPeak ), g );
- }
- vec3 CustomToneMapping( vec3 color ) { return color; }`,fSe=`#ifdef USE_TRANSMISSION
- material.transmission = transmission;
- material.transmissionAlpha = 1.0;
- material.thickness = thickness;
- material.attenuationDistance = attenuationDistance;
- material.attenuationColor = attenuationColor;
- #ifdef USE_TRANSMISSIONMAP
- material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
- #endif
- #ifdef USE_THICKNESSMAP
- material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
- #endif
- vec3 pos = vWorldPosition;
- vec3 v = normalize( cameraPosition - pos );
- vec3 n = inverseTransformDirection( normal, viewMatrix );
- vec4 transmitted = getIBLVolumeRefraction(
- n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
- pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
- material.attenuationColor, material.attenuationDistance );
- material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
- totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
- #endif`,gSe=`#ifdef USE_TRANSMISSION
- uniform float transmission;
- uniform float thickness;
- uniform float attenuationDistance;
- uniform vec3 attenuationColor;
- #ifdef USE_TRANSMISSIONMAP
- uniform sampler2D transmissionMap;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform sampler2D thicknessMap;
- #endif
- uniform vec2 transmissionSamplerSize;
- uniform sampler2D transmissionSamplerMap;
- uniform mat4 modelMatrix;
- uniform mat4 projectionMatrix;
- varying vec3 vWorldPosition;
- float w0( float a ) {
- return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
- }
- float w1( float a ) {
- return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
- }
- float w2( float a ){
- return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
- }
- float w3( float a ) {
- return ( 1.0 / 6.0 ) * ( a * a * a );
- }
- float g0( float a ) {
- return w0( a ) + w1( a );
- }
- float g1( float a ) {
- return w2( a ) + w3( a );
- }
- float h0( float a ) {
- return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
- }
- float h1( float a ) {
- return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
- }
- vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
- uv = uv * texelSize.zw + 0.5;
- vec2 iuv = floor( uv );
- vec2 fuv = fract( uv );
- float g0x = g0( fuv.x );
- float g1x = g1( fuv.x );
- float h0x = h0( fuv.x );
- float h1x = h1( fuv.x );
- float h0y = h0( fuv.y );
- float h1y = h1( fuv.y );
- vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
- vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
- vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
- vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
- return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
- g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
- }
- vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
- vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
- vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
- vec2 fLodSizeInv = 1.0 / fLodSize;
- vec2 cLodSizeInv = 1.0 / cLodSize;
- vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
- vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
- return mix( fSample, cSample, fract( lod ) );
- }
- vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
- vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
- vec3 modelScale;
- modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
- modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
- modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
- return normalize( refractionVector ) * thickness * modelScale;
- }
- float applyIorToRoughness( const in float roughness, const in float ior ) {
- return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
- }
- vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
- float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
- return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
- }
- vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
- if ( isinf( attenuationDistance ) ) {
- return vec3( 1.0 );
- } else {
- vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
- vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
- }
- }
- vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
- const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
- const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
- const in vec3 attenuationColor, const in float attenuationDistance ) {
- vec4 transmittedLight;
- vec3 transmittance;
- #ifdef USE_DISPERSION
- float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
- vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
- for ( int i = 0; i < 3; i ++ ) {
- vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
- vec3 refractedRayExit = position + transmissionRay;
- vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
- vec2 refractionCoords = ndcPos.xy / ndcPos.w;
- refractionCoords += 1.0;
- refractionCoords /= 2.0;
- vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
- transmittedLight[ i ] = transmissionSample[ i ];
- transmittedLight.a += transmissionSample.a;
- transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
- }
- transmittedLight.a /= 3.0;
- #else
- vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
- vec3 refractedRayExit = position + transmissionRay;
- vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
- vec2 refractionCoords = ndcPos.xy / ndcPos.w;
- refractionCoords += 1.0;
- refractionCoords /= 2.0;
- transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
- transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
- #endif
- vec3 attenuatedColor = transmittance * transmittedLight.rgb;
- vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
- float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
- return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
- }
- #endif`,bSe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- varying vec2 vUv;
- #endif
- #ifdef USE_MAP
- varying vec2 vMapUv;
- #endif
- #ifdef USE_ALPHAMAP
- varying vec2 vAlphaMapUv;
- #endif
- #ifdef USE_LIGHTMAP
- varying vec2 vLightMapUv;
- #endif
- #ifdef USE_AOMAP
- varying vec2 vAoMapUv;
- #endif
- #ifdef USE_BUMPMAP
- varying vec2 vBumpMapUv;
- #endif
- #ifdef USE_NORMALMAP
- varying vec2 vNormalMapUv;
- #endif
- #ifdef USE_EMISSIVEMAP
- varying vec2 vEmissiveMapUv;
- #endif
- #ifdef USE_METALNESSMAP
- varying vec2 vMetalnessMapUv;
- #endif
- #ifdef USE_ROUGHNESSMAP
- varying vec2 vRoughnessMapUv;
- #endif
- #ifdef USE_ANISOTROPYMAP
- varying vec2 vAnisotropyMapUv;
- #endif
- #ifdef USE_CLEARCOATMAP
- varying vec2 vClearcoatMapUv;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- varying vec2 vClearcoatNormalMapUv;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- varying vec2 vClearcoatRoughnessMapUv;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- varying vec2 vIridescenceMapUv;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- varying vec2 vIridescenceThicknessMapUv;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- varying vec2 vSheenColorMapUv;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- varying vec2 vSheenRoughnessMapUv;
- #endif
- #ifdef USE_SPECULARMAP
- varying vec2 vSpecularMapUv;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- varying vec2 vSpecularColorMapUv;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- varying vec2 vSpecularIntensityMapUv;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- uniform mat3 transmissionMapTransform;
- varying vec2 vTransmissionMapUv;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform mat3 thicknessMapTransform;
- varying vec2 vThicknessMapUv;
- #endif`,xSe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- varying vec2 vUv;
- #endif
- #ifdef USE_MAP
- uniform mat3 mapTransform;
- varying vec2 vMapUv;
- #endif
- #ifdef USE_ALPHAMAP
- uniform mat3 alphaMapTransform;
- varying vec2 vAlphaMapUv;
- #endif
- #ifdef USE_LIGHTMAP
- uniform mat3 lightMapTransform;
- varying vec2 vLightMapUv;
- #endif
- #ifdef USE_AOMAP
- uniform mat3 aoMapTransform;
- varying vec2 vAoMapUv;
- #endif
- #ifdef USE_BUMPMAP
- uniform mat3 bumpMapTransform;
- varying vec2 vBumpMapUv;
- #endif
- #ifdef USE_NORMALMAP
- uniform mat3 normalMapTransform;
- varying vec2 vNormalMapUv;
- #endif
- #ifdef USE_DISPLACEMENTMAP
- uniform mat3 displacementMapTransform;
- varying vec2 vDisplacementMapUv;
- #endif
- #ifdef USE_EMISSIVEMAP
- uniform mat3 emissiveMapTransform;
- varying vec2 vEmissiveMapUv;
- #endif
- #ifdef USE_METALNESSMAP
- uniform mat3 metalnessMapTransform;
- varying vec2 vMetalnessMapUv;
- #endif
- #ifdef USE_ROUGHNESSMAP
- uniform mat3 roughnessMapTransform;
- varying vec2 vRoughnessMapUv;
- #endif
- #ifdef USE_ANISOTROPYMAP
- uniform mat3 anisotropyMapTransform;
- varying vec2 vAnisotropyMapUv;
- #endif
- #ifdef USE_CLEARCOATMAP
- uniform mat3 clearcoatMapTransform;
- varying vec2 vClearcoatMapUv;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- uniform mat3 clearcoatNormalMapTransform;
- varying vec2 vClearcoatNormalMapUv;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- uniform mat3 clearcoatRoughnessMapTransform;
- varying vec2 vClearcoatRoughnessMapUv;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- uniform mat3 sheenColorMapTransform;
- varying vec2 vSheenColorMapUv;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- uniform mat3 sheenRoughnessMapTransform;
- varying vec2 vSheenRoughnessMapUv;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- uniform mat3 iridescenceMapTransform;
- varying vec2 vIridescenceMapUv;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- uniform mat3 iridescenceThicknessMapTransform;
- varying vec2 vIridescenceThicknessMapUv;
- #endif
- #ifdef USE_SPECULARMAP
- uniform mat3 specularMapTransform;
- varying vec2 vSpecularMapUv;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- uniform mat3 specularColorMapTransform;
- varying vec2 vSpecularColorMapUv;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- uniform mat3 specularIntensityMapTransform;
- varying vec2 vSpecularIntensityMapUv;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- uniform mat3 transmissionMapTransform;
- varying vec2 vTransmissionMapUv;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform mat3 thicknessMapTransform;
- varying vec2 vThicknessMapUv;
- #endif`,ySe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- vUv = vec3( uv, 1 ).xy;
- #endif
- #ifdef USE_MAP
- vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ALPHAMAP
- vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_LIGHTMAP
- vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_AOMAP
- vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_BUMPMAP
- vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_NORMALMAP
- vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_DISPLACEMENTMAP
- vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_EMISSIVEMAP
- vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_METALNESSMAP
- vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ROUGHNESSMAP
- vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ANISOTROPYMAP
- vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOATMAP
- vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULARMAP
- vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_THICKNESSMAP
- vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
- #endif`,vSe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
- vec4 worldPosition = vec4( transformed, 1.0 );
- #ifdef USE_BATCHING
- worldPosition = batchingMatrix * worldPosition;
- #endif
- #ifdef USE_INSTANCING
- worldPosition = instanceMatrix * worldPosition;
- #endif
- worldPosition = modelMatrix * worldPosition;
- #endif`;const wSe=`varying vec2 vUv;
- uniform mat3 uvTransform;
- void main() {
- vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
- gl_Position = vec4( position.xy, 1.0, 1.0 );
- }`,SSe=`uniform sampler2D t2D;
- uniform float backgroundIntensity;
- varying vec2 vUv;
- void main() {
- vec4 texColor = texture2D( t2D, vUv );
- #ifdef DECODE_VIDEO_TEXTURE
- 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 );
- #endif
- texColor.rgb *= backgroundIntensity;
- gl_FragColor = texColor;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,_Se=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- gl_Position.z = gl_Position.w;
- }`,kSe=`#ifdef ENVMAP_TYPE_CUBE
- uniform samplerCube envMap;
- #elif defined( ENVMAP_TYPE_CUBE_UV )
- uniform sampler2D envMap;
- #endif
- uniform float flipEnvMap;
- uniform float backgroundBlurriness;
- uniform float backgroundIntensity;
- uniform mat3 backgroundRotation;
- varying vec3 vWorldDirection;
- #include <cube_uv_reflection_fragment>
- void main() {
- #ifdef ENVMAP_TYPE_CUBE
- vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
- #elif defined( ENVMAP_TYPE_CUBE_UV )
- vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
- #else
- vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
- #endif
- texColor.rgb *= backgroundIntensity;
- gl_FragColor = texColor;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,NSe=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- gl_Position.z = gl_Position.w;
- }`,CSe=`uniform samplerCube tCube;
- uniform float tFlip;
- uniform float opacity;
- varying vec3 vWorldDirection;
- void main() {
- vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
- gl_FragColor = texColor;
- gl_FragColor.a *= opacity;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,PSe=`#include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- varying vec2 vHighPrecisionZW;
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <skinbase_vertex>
- #include <morphinstance_vertex>
- #ifdef USE_DISPLACEMENTMAP
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vHighPrecisionZW = gl_Position.zw;
- }`,TSe=`#if DEPTH_PACKING == 3200
- uniform float opacity;
- #endif
- #include <common>
- #include <packing>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- varying vec2 vHighPrecisionZW;
- void main() {
- vec4 diffuseColor = vec4( 1.0 );
- #include <clipping_planes_fragment>
- #if DEPTH_PACKING == 3200
- diffuseColor.a = opacity;
- #endif
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <logdepthbuf_fragment>
- #ifdef USE_REVERSED_DEPTH_BUFFER
- float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
- #else
- float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
- #endif
- #if DEPTH_PACKING == 3200
- gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
- #elif DEPTH_PACKING == 3201
- gl_FragColor = packDepthToRGBA( fragCoordZ );
- #elif DEPTH_PACKING == 3202
- gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
- #elif DEPTH_PACKING == 3203
- gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
- #endif
- }`,ASe=`#define DISTANCE
- varying vec3 vWorldPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <skinbase_vertex>
- #include <morphinstance_vertex>
- #ifdef USE_DISPLACEMENTMAP
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <worldpos_vertex>
- #include <clipping_planes_vertex>
- vWorldPosition = worldPosition.xyz;
- }`,jSe=`#define DISTANCE
- uniform vec3 referencePosition;
- uniform float nearDistance;
- uniform float farDistance;
- varying vec3 vWorldPosition;
- #include <common>
- #include <packing>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main () {
- vec4 diffuseColor = vec4( 1.0 );
- #include <clipping_planes_fragment>
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- float dist = length( vWorldPosition - referencePosition );
- dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
- dist = saturate( dist );
- gl_FragColor = packDepthToRGBA( dist );
- }`,MSe=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- }`,ESe=`uniform sampler2D tEquirect;
- varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vec3 direction = normalize( vWorldDirection );
- vec2 sampleUV = equirectUv( direction );
- gl_FragColor = texture2D( tEquirect, sampleUV );
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,DSe=`uniform float scale;
- attribute float lineDistance;
- varying float vLineDistance;
- #include <common>
- #include <uv_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- vLineDistance = scale * lineDistance;
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- }`,FSe=`uniform vec3 diffuse;
- uniform float opacity;
- uniform float dashSize;
- uniform float totalSize;
- varying float vLineDistance;
- #include <common>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- if ( mod( vLineDistance, totalSize ) > dashSize ) {
- discard;
- }
- vec3 outgoingLight = vec3( 0.0 );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- }`,RSe=`#include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <fog_vertex>
- }`,LSe=`uniform vec3 diffuse;
- uniform float opacity;
- #ifndef FLAT_SHADED
- varying vec3 vNormal;
- #endif
- #include <common>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- #ifdef USE_LIGHTMAP
- vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
- reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
- #else
- reflectedLight.indirectDiffuse += vec3( 1.0 );
- #endif
- #include <aomap_fragment>
- reflectedLight.indirectDiffuse *= diffuseColor.rgb;
- vec3 outgoingLight = reflectedLight.indirectDiffuse;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,OSe=`#define LAMBERT
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,ISe=`#define LAMBERT
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_lambert_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_lambert_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,zSe=`#define MATCAP
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <color_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- vViewPosition = - mvPosition.xyz;
- }`,USe=`#define MATCAP
- uniform vec3 diffuse;
- uniform float opacity;
- uniform sampler2D matcap;
- varying vec3 vViewPosition;
- #include <common>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <normal_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- vec3 viewDir = normalize( vViewPosition );
- vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
- vec3 y = cross( viewDir, x );
- vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
- #ifdef USE_MATCAP
- vec4 matcapColor = texture2D( matcap, uv );
- #else
- vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
- #endif
- vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,BSe=`#define NORMAL
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- varying vec3 vViewPosition;
- #endif
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphinstance_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- vViewPosition = - mvPosition.xyz;
- #endif
- }`,HSe=`#define NORMAL
- uniform float opacity;
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- varying vec3 vViewPosition;
- #endif
- #include <packing>
- #include <uv_pars_fragment>
- #include <normal_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
- #include <clipping_planes_fragment>
- #include <logdepthbuf_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
- #ifdef OPAQUE
- gl_FragColor.a = 1.0;
- #endif
- }`,qSe=`#define PHONG
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphinstance_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,$Se=`#define PHONG
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform vec3 specular;
- uniform float shininess;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_phong_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_phong_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,VSe=`#define STANDARD
- varying vec3 vViewPosition;
- #ifdef USE_TRANSMISSION
- varying vec3 vWorldPosition;
- #endif
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- #ifdef USE_TRANSMISSION
- vWorldPosition = worldPosition.xyz;
- #endif
- }`,GSe=`#define STANDARD
- #ifdef PHYSICAL
- #define IOR
- #define USE_SPECULAR
- #endif
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float roughness;
- uniform float metalness;
- uniform float opacity;
- #ifdef IOR
- uniform float ior;
- #endif
- #ifdef USE_SPECULAR
- uniform float specularIntensity;
- uniform vec3 specularColor;
- #ifdef USE_SPECULAR_COLORMAP
- uniform sampler2D specularColorMap;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- uniform sampler2D specularIntensityMap;
- #endif
- #endif
- #ifdef USE_CLEARCOAT
- uniform float clearcoat;
- uniform float clearcoatRoughness;
- #endif
- #ifdef USE_DISPERSION
- uniform float dispersion;
- #endif
- #ifdef USE_IRIDESCENCE
- uniform float iridescence;
- uniform float iridescenceIOR;
- uniform float iridescenceThicknessMinimum;
- uniform float iridescenceThicknessMaximum;
- #endif
- #ifdef USE_SHEEN
- uniform vec3 sheenColor;
- uniform float sheenRoughness;
- #ifdef USE_SHEEN_COLORMAP
- uniform sampler2D sheenColorMap;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- uniform sampler2D sheenRoughnessMap;
- #endif
- #endif
- #ifdef USE_ANISOTROPY
- uniform vec2 anisotropyVector;
- #ifdef USE_ANISOTROPYMAP
- uniform sampler2D anisotropyMap;
- #endif
- #endif
- varying vec3 vViewPosition;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <iridescence_fragment>
- #include <cube_uv_reflection_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_physical_pars_fragment>
- #include <fog_pars_fragment>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_physical_pars_fragment>
- #include <transmission_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <clearcoat_pars_fragment>
- #include <iridescence_pars_fragment>
- #include <roughnessmap_pars_fragment>
- #include <metalnessmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <roughnessmap_fragment>
- #include <metalnessmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <clearcoat_normal_fragment_begin>
- #include <clearcoat_normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_physical_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
- vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
- #include <transmission_fragment>
- vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
- #ifdef USE_SHEEN
- float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
- outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
- #endif
- #ifdef USE_CLEARCOAT
- float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
- vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
- outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
- #endif
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,WSe=`#define TOON
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,KSe=`#define TOON
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <gradientmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_toon_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_toon_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,XSe=`uniform float size;
- uniform float scale;
- #include <common>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- #ifdef USE_POINTS_UV
- varying vec2 vUv;
- uniform mat3 uvTransform;
- #endif
- void main() {
- #ifdef USE_POINTS_UV
- vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
- #endif
- #include <color_vertex>
- #include <morphinstance_vertex>
- #include <morphcolor_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <project_vertex>
- gl_PointSize = size;
- #ifdef USE_SIZEATTENUATION
- bool isPerspective = isPerspectiveMatrix( projectionMatrix );
- if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
- #endif
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <worldpos_vertex>
- #include <fog_vertex>
- }`,YSe=`uniform vec3 diffuse;
- uniform float opacity;
- #include <common>
- #include <color_pars_fragment>
- #include <map_particle_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- vec3 outgoingLight = vec3( 0.0 );
- #include <logdepthbuf_fragment>
- #include <map_particle_fragment>
- #include <color_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- }`,QSe=`#include <common>
- #include <batching_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <shadowmap_pars_vertex>
- void main() {
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphinstance_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,ZSe=`uniform vec3 color;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <logdepthbuf_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <shadowmask_pars_fragment>
- void main() {
- #include <logdepthbuf_fragment>
- gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- }`,JSe=`uniform float rotation;
- uniform vec2 center;
- #include <common>
- #include <uv_pars_vertex>
- #include <fog_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- vec4 mvPosition = modelViewMatrix[ 3 ];
- vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
- #ifndef USE_SIZEATTENUATION
- bool isPerspective = isPerspectiveMatrix( projectionMatrix );
- if ( isPerspective ) scale *= - mvPosition.z;
- #endif
- vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
- vec2 rotatedPosition;
- rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
- rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
- mvPosition.xy += rotatedPosition;
- gl_Position = projectionMatrix * mvPosition;
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- }`,e_e=`uniform vec3 diffuse;
- uniform float opacity;
- #include <common>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <clipping_planes_fragment>
- vec3 outgoingLight = vec3( 0.0 );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- }`,nr={alphahash_fragment:S0e,alphahash_pars_fragment:_0e,alphamap_fragment:k0e,alphamap_pars_fragment:N0e,alphatest_fragment:C0e,alphatest_pars_fragment:P0e,aomap_fragment:T0e,aomap_pars_fragment:A0e,batching_pars_vertex:j0e,batching_vertex:M0e,begin_vertex:E0e,beginnormal_vertex:D0e,bsdfs:F0e,iridescence_fragment:R0e,bumpmap_pars_fragment:L0e,clipping_planes_fragment:O0e,clipping_planes_pars_fragment:I0e,clipping_planes_pars_vertex:z0e,clipping_planes_vertex:U0e,color_fragment:B0e,color_pars_fragment:H0e,color_pars_vertex:q0e,color_vertex:$0e,common:V0e,cube_uv_reflection_fragment:G0e,defaultnormal_vertex:W0e,displacementmap_pars_vertex:K0e,displacementmap_vertex:X0e,emissivemap_fragment:Y0e,emissivemap_pars_fragment:Q0e,colorspace_fragment:Z0e,colorspace_pars_fragment:J0e,envmap_fragment:ewe,envmap_common_pars_fragment:twe,envmap_pars_fragment:nwe,envmap_pars_vertex:rwe,envmap_physical_pars_fragment:pwe,envmap_vertex:awe,fog_vertex:iwe,fog_pars_vertex:swe,fog_fragment:owe,fog_pars_fragment:lwe,gradientmap_pars_fragment:cwe,lightmap_pars_fragment:dwe,lights_lambert_fragment:uwe,lights_lambert_pars_fragment:mwe,lights_pars_begin:hwe,lights_toon_fragment:fwe,lights_toon_pars_fragment:gwe,lights_phong_fragment:bwe,lights_phong_pars_fragment:xwe,lights_physical_fragment:ywe,lights_physical_pars_fragment:vwe,lights_fragment_begin:wwe,lights_fragment_maps:Swe,lights_fragment_end:_we,logdepthbuf_fragment:kwe,logdepthbuf_pars_fragment:Nwe,logdepthbuf_pars_vertex:Cwe,logdepthbuf_vertex:Pwe,map_fragment:Twe,map_pars_fragment:Awe,map_particle_fragment:jwe,map_particle_pars_fragment:Mwe,metalnessmap_fragment:Ewe,metalnessmap_pars_fragment:Dwe,morphinstance_vertex:Fwe,morphcolor_vertex:Rwe,morphnormal_vertex:Lwe,morphtarget_pars_vertex:Owe,morphtarget_vertex:Iwe,normal_fragment_begin:zwe,normal_fragment_maps:Uwe,normal_pars_fragment:Bwe,normal_pars_vertex:Hwe,normal_vertex:qwe,normalmap_pars_fragment:$we,clearcoat_normal_fragment_begin:Vwe,clearcoat_normal_fragment_maps:Gwe,clearcoat_pars_fragment:Wwe,iridescence_pars_fragment:Kwe,opaque_fragment:Xwe,packing:Ywe,premultiplied_alpha_fragment:Qwe,project_vertex:Zwe,dithering_fragment:Jwe,dithering_pars_fragment:eSe,roughnessmap_fragment:tSe,roughnessmap_pars_fragment:nSe,shadowmap_pars_fragment:rSe,shadowmap_pars_vertex:aSe,shadowmap_vertex:iSe,shadowmask_pars_fragment:sSe,skinbase_vertex:oSe,skinning_pars_vertex:lSe,skinning_vertex:cSe,skinnormal_vertex:dSe,specularmap_fragment:uSe,specularmap_pars_fragment:mSe,tonemapping_fragment:hSe,tonemapping_pars_fragment:pSe,transmission_fragment:fSe,transmission_pars_fragment:gSe,uv_pars_fragment:bSe,uv_pars_vertex:xSe,uv_vertex:ySe,worldpos_vertex:vSe,background_vert:wSe,background_frag:SSe,backgroundCube_vert:_Se,backgroundCube_frag:kSe,cube_vert:NSe,cube_frag:CSe,depth_vert:PSe,depth_frag:TSe,distanceRGBA_vert:ASe,distanceRGBA_frag:jSe,equirect_vert:MSe,equirect_frag:ESe,linedashed_vert:DSe,linedashed_frag:FSe,meshbasic_vert:RSe,meshbasic_frag:LSe,meshlambert_vert:OSe,meshlambert_frag:ISe,meshmatcap_vert:zSe,meshmatcap_frag:USe,meshnormal_vert:BSe,meshnormal_frag:HSe,meshphong_vert:qSe,meshphong_frag:$Se,meshphysical_vert:VSe,meshphysical_frag:GSe,meshtoon_vert:WSe,meshtoon_frag:KSe,points_vert:XSe,points_frag:YSe,shadow_vert:QSe,shadow_frag:ZSe,sprite_vert:JSe,sprite_frag:e_e},nn={common:{diffuse:{value:new lr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new sr},alphaMap:{value:null},alphaMapTransform:{value:new sr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new sr}},envmap:{envMap:{value:null},envMapRotation:{value:new sr},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 sr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new sr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new sr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new sr},normalScale:{value:new ar(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new sr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new sr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new sr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new sr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new lr(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 lr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new sr},alphaTest:{value:0},uvTransform:{value:new sr}},sprite:{diffuse:{value:new lr(16777215)},opacity:{value:1},center:{value:new ar(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new sr},alphaMap:{value:null},alphaMapTransform:{value:new sr},alphaTest:{value:0}}},fd={basic:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.fog]),vertexShader:nr.meshbasic_vert,fragmentShader:nr.meshbasic_frag},lambert:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,nn.lights,{emissive:{value:new lr(0)}}]),vertexShader:nr.meshlambert_vert,fragmentShader:nr.meshlambert_frag},phong:{uniforms:Vs([nn.common,nn.specularmap,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,nn.lights,{emissive:{value:new lr(0)},specular:{value:new lr(1118481)},shininess:{value:30}}]),vertexShader:nr.meshphong_vert,fragmentShader:nr.meshphong_frag},standard:{uniforms:Vs([nn.common,nn.envmap,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.roughnessmap,nn.metalnessmap,nn.fog,nn.lights,{emissive:{value:new lr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:nr.meshphysical_vert,fragmentShader:nr.meshphysical_frag},toon:{uniforms:Vs([nn.common,nn.aomap,nn.lightmap,nn.emissivemap,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.gradientmap,nn.fog,nn.lights,{emissive:{value:new lr(0)}}]),vertexShader:nr.meshtoon_vert,fragmentShader:nr.meshtoon_frag},matcap:{uniforms:Vs([nn.common,nn.bumpmap,nn.normalmap,nn.displacementmap,nn.fog,{matcap:{value:null}}]),vertexShader:nr.meshmatcap_vert,fragmentShader:nr.meshmatcap_frag},points:{uniforms:Vs([nn.points,nn.fog]),vertexShader:nr.points_vert,fragmentShader:nr.points_frag},dashed:{uniforms:Vs([nn.common,nn.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:nr.linedashed_vert,fragmentShader:nr.linedashed_frag},depth:{uniforms:Vs([nn.common,nn.displacementmap]),vertexShader:nr.depth_vert,fragmentShader:nr.depth_frag},normal:{uniforms:Vs([nn.common,nn.bumpmap,nn.normalmap,nn.displacementmap,{opacity:{value:1}}]),vertexShader:nr.meshnormal_vert,fragmentShader:nr.meshnormal_frag},sprite:{uniforms:Vs([nn.sprite,nn.fog]),vertexShader:nr.sprite_vert,fragmentShader:nr.sprite_frag},background:{uniforms:{uvTransform:{value:new sr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:nr.background_vert,fragmentShader:nr.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new sr}},vertexShader:nr.backgroundCube_vert,fragmentShader:nr.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:nr.cube_vert,fragmentShader:nr.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:nr.equirect_vert,fragmentShader:nr.equirect_frag},distanceRGBA:{uniforms:Vs([nn.common,nn.displacementmap,{referencePosition:{value:new Tt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:nr.distanceRGBA_vert,fragmentShader:nr.distanceRGBA_frag},shadow:{uniforms:Vs([nn.lights,nn.fog,{color:{value:new lr(0)},opacity:{value:1}}]),vertexShader:nr.shadow_vert,fragmentShader:nr.shadow_frag}};fd.physical={uniforms:Vs([fd.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new sr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new sr},clearcoatNormalScale:{value:new ar(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new sr},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new sr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new sr},sheen:{value:0},sheenColor:{value:new lr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new sr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new sr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new sr},transmissionSamplerSize:{value:new ar},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new sr},attenuationDistance:{value:0},attenuationColor:{value:new lr(0)},specularColor:{value:new lr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new sr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new sr},anisotropyVector:{value:new ar},anisotropyMap:{value:null},anisotropyMapTransform:{value:new sr}}]),vertexShader:nr.meshphysical_vert,fragmentShader:nr.meshphysical_frag};const t1={r:0,b:0,g:0},Xp=new sp,t_e=new fi;function n_e(t,e,n,r,i,s,o){const l=new lr(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function x(C){let P=C.isScene===!0?C.background:null;return P&&P.isTexture&&(P=(C.backgroundBlurriness>0?n:e).get(P)),P}function v(C){let P=!1;const N=x(C);N===null?b(l,c):N&&N.isColor&&(b(N,1),P=!0);const A=t.xr.getEnvironmentBlendMode();A==="additive"?r.buffers.color.setClear(0,0,0,1,o):A==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||P)&&(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(C,P){const N=x(P);N&&(N.isCubeTexture||N.mapping===RP)?(u===void 0&&(u=new oc(new qO(1,1,1),new lm({name:"BackgroundCubeMaterial",uniforms:Fx(fd.backgroundCube.uniforms),vertexShader:fd.backgroundCube.vertexShader,fragmentShader:fd.backgroundCube.fragmentShader,side:Ao,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(A,T,F){this.matrixWorld.copyPosition(F.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Xp.copy(P.backgroundRotation),Xp.x*=-1,Xp.y*=-1,Xp.z*=-1,N.isCubeTexture&&N.isRenderTargetTexture===!1&&(Xp.y*=-1,Xp.z*=-1),u.material.uniforms.envMap.value=N,u.material.uniforms.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=P.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(t_e.makeRotationFromEuler(Xp)),u.material.toneMapped=Tr.getTransfer(N.colorSpace)!==Vr,(m!==N||p!==N.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),u.layers.enableAll(),C.unshift(u,u.geometry,u.material,0,0,null)):N&&N.isTexture&&(d===void 0&&(d=new oc(new VO(2,2),new lm({name:"BackgroundMaterial",uniforms:Fx(fd.background.uniforms),vertexShader:fd.background.vertexShader,fragmentShader:fd.background.fragmentShader,side:ip,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),Object.defineProperty(d.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(d)),d.material.uniforms.t2D.value=N,d.material.uniforms.backgroundIntensity.value=P.backgroundIntensity,d.material.toneMapped=Tr.getTransfer(N.colorSpace)!==Vr,N.matrixAutoUpdate===!0&&N.updateMatrix(),d.material.uniforms.uvTransform.value.copy(N.matrix),(m!==N||p!==N.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=N,p=N.version,f=t.toneMapping),d.layers.enableAll(),C.unshift(d,d.geometry,d.material,0,0,null))}function b(C,P){C.getRGB(t1,SZ(t)),r.buffers.color.setClear(t1.r,t1.g,t1.b,P,o)}function _(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0)}return{getClearColor:function(){return l},setClearColor:function(C,P=1){l.set(C),c=P,b(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(C){c=C,b(l,c)},render:v,addToRenderList:g,dispose:_}}function r_e(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r={},i=p(null);let s=i,o=!1;function l(D,H,z,X,L){let ne=!1;const ie=m(X,z,H);s!==ie&&(s=ie,d(s.object)),ne=f(D,X,z,L),ne&&x(D,X,z,L),L!==null&&e.update(L,t.ELEMENT_ARRAY_BUFFER),(ne||o)&&(o=!1,P(D,H,z,X),L!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(L).buffer))}function c(){return t.createVertexArray()}function d(D){return t.bindVertexArray(D)}function u(D){return t.deleteVertexArray(D)}function m(D,H,z){const X=z.wireframe===!0;let L=r[D.id];L===void 0&&(L={},r[D.id]=L);let ne=L[H.id];ne===void 0&&(ne={},L[H.id]=ne);let ie=ne[X];return ie===void 0&&(ie=p(c()),ne[X]=ie),ie}function p(D){const H=[],z=[],X=[];for(let L=0;L<n;L++)H[L]=0,z[L]=0,X[L]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:H,enabledAttributes:z,attributeDivisors:X,object:D,attributes:{},index:null}}function f(D,H,z,X){const L=s.attributes,ne=H.attributes;let ie=0;const ee=z.getAttributes();for(const ue in ee)if(ee[ue].location>=0){const oe=L[ue];let W=ne[ue];if(W===void 0&&(ue==="instanceMatrix"&&D.instanceMatrix&&(W=D.instanceMatrix),ue==="instanceColor"&&D.instanceColor&&(W=D.instanceColor)),oe===void 0||oe.attribute!==W||W&&oe.data!==W.data)return!0;ie++}return s.attributesNum!==ie||s.index!==X}function x(D,H,z,X){const L={},ne=H.attributes;let ie=0;const ee=z.getAttributes();for(const ue in ee)if(ee[ue].location>=0){let oe=ne[ue];oe===void 0&&(ue==="instanceMatrix"&&D.instanceMatrix&&(oe=D.instanceMatrix),ue==="instanceColor"&&D.instanceColor&&(oe=D.instanceColor));const W={};W.attribute=oe,oe&&oe.data&&(W.data=oe.data),L[ue]=W,ie++}s.attributes=L,s.attributesNum=ie,s.index=X}function v(){const D=s.newAttributes;for(let H=0,z=D.length;H<z;H++)D[H]=0}function g(D){b(D,0)}function b(D,H){const z=s.newAttributes,X=s.enabledAttributes,L=s.attributeDivisors;z[D]=1,X[D]===0&&(t.enableVertexAttribArray(D),X[D]=1),L[D]!==H&&(t.vertexAttribDivisor(D,H),L[D]=H)}function _(){const D=s.newAttributes,H=s.enabledAttributes;for(let z=0,X=H.length;z<X;z++)H[z]!==D[z]&&(t.disableVertexAttribArray(z),H[z]=0)}function C(D,H,z,X,L,ne,ie){ie===!0?t.vertexAttribIPointer(D,H,z,L,ne):t.vertexAttribPointer(D,H,z,X,L,ne)}function P(D,H,z,X){v();const L=X.attributes,ne=z.getAttributes(),ie=H.defaultAttributeValues;for(const ee in ne){const ue=ne[ee];if(ue.location>=0){let le=L[ee];if(le===void 0&&(ee==="instanceMatrix"&&D.instanceMatrix&&(le=D.instanceMatrix),ee==="instanceColor"&&D.instanceColor&&(le=D.instanceColor)),le!==void 0){const oe=le.normalized,W=le.itemSize,re=e.get(le);if(re===void 0)continue;const ce=re.buffer,xe=re.type,Ne=re.bytesPerElement,$=xe===t.INT||xe===t.UNSIGNED_INT||le.gpuType===DO;if(le.isInterleavedBufferAttribute){const Y=le.data,E=Y.stride,j=le.offset;if(Y.isInstancedInterleavedBuffer){for(let O=0;O<ue.locationSize;O++)b(ue.location+O,Y.meshPerAttribute);D.isInstancedMesh!==!0&&X._maxInstanceCount===void 0&&(X._maxInstanceCount=Y.meshPerAttribute*Y.count)}else for(let O=0;O<ue.locationSize;O++)g(ue.location+O);t.bindBuffer(t.ARRAY_BUFFER,ce);for(let O=0;O<ue.locationSize;O++)C(ue.location+O,W/ue.locationSize,xe,oe,E*Ne,(j+W/ue.locationSize*O)*Ne,$)}else{if(le.isInstancedBufferAttribute){for(let Y=0;Y<ue.locationSize;Y++)b(ue.location+Y,le.meshPerAttribute);D.isInstancedMesh!==!0&&X._maxInstanceCount===void 0&&(X._maxInstanceCount=le.meshPerAttribute*le.count)}else for(let Y=0;Y<ue.locationSize;Y++)g(ue.location+Y);t.bindBuffer(t.ARRAY_BUFFER,ce);for(let Y=0;Y<ue.locationSize;Y++)C(ue.location+Y,W/ue.locationSize,xe,oe,W*Ne,W/ue.locationSize*Y*Ne,$)}}else if(ie!==void 0){const oe=ie[ee];if(oe!==void 0)switch(oe.length){case 2:t.vertexAttrib2fv(ue.location,oe);break;case 3:t.vertexAttrib3fv(ue.location,oe);break;case 4:t.vertexAttrib4fv(ue.location,oe);break;default:t.vertexAttrib1fv(ue.location,oe)}}}}_()}function N(){F();for(const D in r){const H=r[D];for(const z in H){const X=H[z];for(const L in X)u(X[L].object),delete X[L];delete H[z]}delete r[D]}}function A(D){if(r[D.id]===void 0)return;const H=r[D.id];for(const z in H){const X=H[z];for(const L in X)u(X[L].object),delete X[L];delete H[z]}delete r[D.id]}function T(D){for(const H in r){const z=r[H];if(z[D.id]===void 0)continue;const X=z[D.id];for(const L in X)u(X[L].object),delete X[L];delete z[D.id]}}function F(){k(),o=!0,s!==i&&(s=i,d(s.object))}function k(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:l,reset:F,resetDefaultState:k,dispose:N,releaseStatesOfGeometry:A,releaseStatesOfProgram:T,initAttributes:v,enableAttribute:g,disableUnusedAttributes:_}}function a_e(t,e,n){let r;function i(d){r=d}function s(d,u){t.drawArrays(r,d,u),n.update(u,r,1)}function o(d,u,m){m!==0&&(t.drawArraysInstanced(r,d,u,m),n.update(u,r,m))}function l(d,u,m){if(m===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r,d,0,u,0,m);let f=0;for(let x=0;x<m;x++)f+=u[x];n.update(f,r,1)}function c(d,u,m,p){if(m===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let x=0;x<d.length;x++)o(d[x],u[x],p[x]);else{f.multiDrawArraysInstancedWEBGL(r,d,0,u,0,p,0,m);let x=0;for(let v=0;v<m;v++)x+=u[v]*p[v];n.update(x,r,1)}}this.setMode=i,this.render=s,this.renderInstances=o,this.renderMultiDraw=l,this.renderMultiDrawInstances=c}function i_e(t,e,n,r){let i;function s(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const T=e.get("EXT_texture_filter_anisotropic");i=t.getParameter(T.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(T){return!(T!==Rc&&r.convert(T)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function l(T){const F=T===cy&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(T!==Ed&&r.convert(T)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&T!==Hu&&!F)}function c(T){if(T==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";T="mediump"}return T==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let d=n.precision!==void 0?n.precision:"highp";const u=c(d);u!==d&&(qn("WebGLRenderer:",d,"not supported, using",u,"instead."),d=u);const m=n.logarithmicDepthBuffer===!0,p=n.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=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),b=t.getParameter(t.MAX_VERTEX_ATTRIBS),_=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),C=t.getParameter(t.MAX_VARYING_VECTORS),P=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=x>0,A=t.getParameter(t.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:l,precision:d,logarithmicDepthBuffer:m,reversedDepthBuffer:p,maxTextures:f,maxVertexTextures:x,maxTextureSize:v,maxCubemapSize:g,maxAttributes:b,maxVertexUniforms:_,maxVaryings:C,maxFragmentUniforms:P,vertexTextures:N,maxSamples:A}}function s_e(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new fh,l=new sr,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(m,p){const f=m.length!==0||p||r!==0||i;return i=p,r=m.length,f},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=u(m,p,0)},this.setState=function(m,p,f){const x=m.clippingPlanes,v=m.clipIntersection,g=m.clipShadows,b=t.get(m);if(!i||x===null||x.length===0||s&&!g)s?u(null):d();else{const _=s?0:r,C=_*4;let P=b.clippingState||null;c.value=P,P=u(x,p,C,f);for(let N=0;N!==C;++N)P[N]=n[N];b.clippingState=P,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(m,p,f,x){const v=m!==null?m.length:0;let g=null;if(v!==0){if(g=c.value,x!==!0||g===null){const b=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(g===null||g.length<b)&&(g=new Float32Array(b));for(let C=0,P=f;C!==v;++C,P+=4)o.copy(m[C]).applyMatrix4(_,l),o.normal.toArray(g,P),g[P+3]=o.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,g}}function o_e(t){let e=new WeakMap;function n(o,l){return l===mF?o.mapping=Mx:l===hF&&(o.mapping=Ex),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===mF||l===hF)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 d=new Jve(c.height);return d.fromEquirectangularTexture(t,o),e.set(o,d),o.addEventListener("dispose",i),n(d.texture,o.mapping)}else return null}}return o}function i(o){const l=o.target;l.removeEventListener("dispose",i);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}const jh=4,p6=[.125,.215,.35,.446,.526,.582],hf=20,l_e=256,Sv=new MZ,f6=new lr;let GM=null,WM=0,KM=0,XM=!1;const c_e=new Tt;let g6=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,i=100,s={}){const{size:o=256,position:l=c_e}=s;GM=this._renderer.getRenderTarget(),WM=this._renderer.getActiveCubeFace(),KM=this._renderer.getActiveMipmapLevel(),XM=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,r,i,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=y6(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=x6(),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(GM,WM,KM),this._renderer.xr.enabled=XM,e.scissorTest=!1,wb(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===Mx||e.mapping===Ex?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),GM=this._renderer.getRenderTarget(),WM=this._renderer.getActiveCubeFace(),KM=this._renderer.getActiveMipmapLevel(),XM=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:Xl,minFilter:Xl,generateMipmaps:!1,type:cy,format:Rc,colorSpace:Dx,depthBuffer:!1},i=b6(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=b6(e,n,r);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=d_e(s)),this._blurMaterial=m_e(s,e,n),this._ggxMaterial=u_e(s,e,n)}return i}_compileMaterial(e){const n=new oc(new sc,e);this._renderer.compile(n,Sv)}_sceneToCubeUV(e,n,r,i,s){const c=new ql(90,1,n,r),d=[1,-1,1,1,1,1],u=[1,1,1,-1,-1,-1],m=this._renderer,p=m.autoClear,f=m.toneMapping;m.getClearColor(f6),m.toneMapping=Wh,m.autoClear=!1,m.state.buffers.depth.getReversed()&&(m.setRenderTarget(i),m.clearDepth(),m.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new oc(new qO,new HO({name:"PMREM.Background",side:Ao,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,g=v.material;let b=!1;const _=e.background;_?_.isColor&&(g.color.copy(_),e.background=null,b=!0):(g.color.copy(f6),b=!0);for(let C=0;C<6;C++){const P=C%3;P===0?(c.up.set(0,d[C],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+u[C],s.y,s.z)):P===1?(c.up.set(0,0,d[C]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+u[C],s.z)):(c.up.set(0,d[C],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+u[C]));const N=this._cubeSize;wb(i,P*N,C>2?N:0,N,N),m.setRenderTarget(i),b&&m.render(v,c),m.render(e,c)}m.toneMapping=f,m.autoClear=p,e.background=_}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===Mx||e.mapping===Ex;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=y6()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=x6());const s=i?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=s;const l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;wb(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,Sv)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;s<i;s++)this._applyGGXFilter(e,s-1,s);n.autoClear=r}_applyGGXFilter(e,n,r){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,l=this._lodMeshes[r];l.material=o;const c=o.uniforms,d=r/(this._lodMeshes.length-1),u=n/(this._lodMeshes.length-1),m=Math.sqrt(d*d-u*u),p=.05+d*.95,f=m*p,{_lodMax:x}=this,v=this._sizeLods[r],g=3*v*(r>x-jh?r-x+jh:0),b=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=x-n,wb(s,g,b,3*v,2*v),i.setRenderTarget(s),i.render(l,Sv),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=x-r,wb(e,g,b,3*v,2*v),i.setRenderTarget(e),i.render(l,Sv)}_blur(e,n,r,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,i,"latitudinal",s),this._halfBlur(o,e,r,r,i,"longitudinal",s)}_halfBlur(e,n,r,i,s,o,l){const c=this._renderer,d=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&ni("blur direction must be either latitudinal or longitudinal!");const u=3,m=this._lodMeshes[i];m.material=d;const p=d.uniforms,f=this._sizeLods[r]-1,x=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*hf-1),v=s/x,g=isFinite(s)?1+Math.floor(u*v):hf;g>hf&&qn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${hf}`);const b=[];let _=0;for(let T=0;T<hf;++T){const F=T/v,k=Math.exp(-F*F/2);b.push(k),T===0?_+=k:T<g&&(_+=2*k)}for(let T=0;T<b.length;T++)b[T]=b[T]/_;p.envMap.value=e.texture,p.samples.value=g,p.weights.value=b,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:C}=this;p.dTheta.value=x,p.mipInt.value=C-r;const P=this._sizeLods[i],N=3*P*(i>C-jh?i-C+jh:0),A=4*(this._cubeSize-P);wb(n,N,A,3*P,2*P),c.setRenderTarget(n),c.render(m,Sv)}};function d_e(t){const e=[],n=[],r=[];let i=t;const s=t-jh+1+p6.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);e.push(l);let c=1/l;o>t-jh?c=p6[o-t+jh-1]:o===0&&(c=0),n.push(c);const d=1/(l-2),u=-d,m=1+d,p=[u,u,m,u,m,m,u,u,m,m,u,m],f=6,x=6,v=3,g=2,b=1,_=new Float32Array(v*x*f),C=new Float32Array(g*x*f),P=new Float32Array(b*x*f);for(let A=0;A<f;A++){const T=A%3*2/3-1,F=A>2?0:-1,k=[T,F,0,T+2/3,F,0,T+2/3,F+1,0,T,F,0,T+2/3,F+1,0,T,F+1,0];_.set(k,v*x*A),C.set(p,g*x*A);const D=[A,A,A,A,A,A];P.set(D,b*x*A)}const N=new sc;N.setAttribute("position",new Zs(_,v)),N.setAttribute("uv",new Zs(C,g)),N.setAttribute("faceIndex",new Zs(P,b)),r.push(new oc(N,null)),i>jh&&i--}return{lodMeshes:r,sizeLods:e,sigmas:n}}function b6(t,e,n){const r=new tg(t,e,n);return r.texture.mapping=RP,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function wb(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function u_e(t,e,n){return new lm({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:l_e,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:OP(),fragmentShader:`
- precision highp float;
- precision highp int;
- varying vec3 vOutputDirection;
- uniform sampler2D envMap;
- uniform float roughness;
- uniform float mipInt;
- #define ENVMAP_TYPE_CUBE_UV
- #include <cube_uv_reflection_fragment>
- #define PI 3.14159265359
- // Van der Corput radical inverse
- float radicalInverse_VdC(uint bits) {
- bits = (bits << 16u) | (bits >> 16u);
- bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
- bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
- bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
- bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
- return float(bits) * 2.3283064365386963e-10; // / 0x100000000
- }
- // Hammersley sequence
- vec2 hammersley(uint i, uint N) {
- return vec2(float(i) / float(N), radicalInverse_VdC(i));
- }
- // GGX VNDF importance sampling (Eric Heitz 2018)
- // "Sampling the GGX Distribution of Visible Normals"
- // https://jcgt.org/published/0007/04/01/
- vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
- float alpha = roughness * roughness;
- // Section 3.2: Transform view direction to hemisphere configuration
- vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
- // Section 4.1: Orthonormal basis
- float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
- vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
- vec3 T2 = cross(Vh, T1);
- // Section 4.2: Parameterization of projected area
- float r = sqrt(Xi.x);
- float phi = 2.0 * PI * Xi.y;
- float t1 = r * cos(phi);
- float t2 = r * sin(phi);
- float s = 0.5 * (1.0 + Vh.z);
- t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
- // Section 4.3: Reprojection onto hemisphere
- vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
- // Section 3.4: Transform back to ellipsoid configuration
- return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
- }
- void main() {
- vec3 N = normalize(vOutputDirection);
- vec3 V = N; // Assume view direction equals normal for pre-filtering
- vec3 prefilteredColor = vec3(0.0);
- float totalWeight = 0.0;
- // For very low roughness, just sample the environment directly
- if (roughness < 0.001) {
- gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
- return;
- }
- // Tangent space basis for VNDF sampling
- vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
- vec3 tangent = normalize(cross(up, N));
- vec3 bitangent = cross(N, tangent);
- for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
- vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
- // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
- vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
- // Transform H back to world space
- vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
- vec3 L = normalize(2.0 * dot(V, H) * H - V);
- float NdotL = max(dot(N, L), 0.0);
- if(NdotL > 0.0) {
- // Sample environment at fixed mip level
- // VNDF importance sampling handles the distribution filtering
- vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
- // Weight by NdotL for the split-sum approximation
- // VNDF PDF naturally accounts for the visible microfacet distribution
- prefilteredColor += sampleColor * NdotL;
- totalWeight += NdotL;
- }
- }
- if (totalWeight > 0.0) {
- prefilteredColor = prefilteredColor / totalWeight;
- }
- gl_FragColor = vec4(prefilteredColor, 1.0);
- }
- `,blending:Xu,depthTest:!1,depthWrite:!1})}function m_e(t,e,n){const r=new Float32Array(hf),i=new Tt(0,1,0);return new lm({name:"SphericalGaussianBlur",defines:{n:hf,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:i}},vertexShader:OP(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- varying vec3 vOutputDirection;
- uniform sampler2D envMap;
- uniform int samples;
- uniform float weights[ n ];
- uniform bool latitudinal;
- uniform float dTheta;
- uniform float mipInt;
- uniform vec3 poleAxis;
- #define ENVMAP_TYPE_CUBE_UV
- #include <cube_uv_reflection_fragment>
- vec3 getSample( float theta, vec3 axis ) {
- float cosTheta = cos( theta );
- // Rodrigues' axis-angle rotation
- vec3 sampleDirection = vOutputDirection * cosTheta
- + cross( axis, vOutputDirection ) * sin( theta )
- + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
- return bilinearCubeUV( envMap, sampleDirection, mipInt );
- }
- void main() {
- vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
- if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
- axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
- }
- axis = normalize( axis );
- gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
- gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
- for ( int i = 1; i < n; i++ ) {
- if ( i >= samples ) {
- break;
- }
- float theta = dTheta * float( i );
- gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
- gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
- }
- }
- `,blending:Xu,depthTest:!1,depthWrite:!1})}function x6(){return new lm({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:OP(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- varying vec3 vOutputDirection;
- uniform sampler2D envMap;
- #include <common>
- void main() {
- vec3 outputDirection = normalize( vOutputDirection );
- vec2 uv = equirectUv( outputDirection );
- gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
- }
- `,blending:Xu,depthTest:!1,depthWrite:!1})}function y6(){return new lm({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:OP(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- uniform float flipEnvMap;
- varying vec3 vOutputDirection;
- uniform samplerCube envMap;
- void main() {
- gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
- }
- `,blending:Xu,depthTest:!1,depthWrite:!1})}function OP(){return`
- precision mediump float;
- precision mediump int;
- attribute float faceIndex;
- varying vec3 vOutputDirection;
- // RH coordinate system; PMREM face-indexing convention
- vec3 getDirection( vec2 uv, float face ) {
- uv = 2.0 * uv - 1.0;
- vec3 direction = vec3( uv, 1.0 );
- if ( face == 0.0 ) {
- direction = direction.zyx; // ( 1, v, u ) pos x
- } else if ( face == 1.0 ) {
- direction = direction.xzy;
- direction.xz *= -1.0; // ( -u, 1, -v ) pos y
- } else if ( face == 2.0 ) {
- direction.x *= -1.0; // ( -u, v, 1 ) pos z
- } else if ( face == 3.0 ) {
- direction = direction.zyx;
- direction.xz *= -1.0; // ( -1, v, -u ) neg x
- } else if ( face == 4.0 ) {
- direction = direction.xzy;
- direction.xy *= -1.0; // ( -u, -1, v ) neg y
- } else if ( face == 5.0 ) {
- direction.z *= -1.0; // ( u, v, -1 ) neg z
- }
- return direction;
- }
- void main() {
- vOutputDirection = getDirection( uv, faceIndex );
- gl_Position = vec4( position, 1.0 );
- }
- `}function h_e(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,d=c===mF||c===hF,u=c===Mx||c===Ex;if(d||u){let m=e.get(l);const p=m!==void 0?m.texture.pmremVersion:0;if(l.isRenderTargetTexture&&l.pmremVersion!==p)return n===null&&(n=new g6(t)),m=d?n.fromEquirectangular(l,m):n.fromCubemap(l,m),m.texture.pmremVersion=l.pmremVersion,e.set(l,m),m.texture;if(m!==void 0)return m.texture;{const f=l.image;return d&&f&&f.height>0||u&&f&&i(f)?(n===null&&(n=new g6(t)),m=d?n.fromEquirectangular(l):n.fromCubemap(l),m.texture.pmremVersion=l.pmremVersion,e.set(l,m),l.addEventListener("dispose",s),m.texture):null}}}return l}function i(l){let c=0;const d=6;for(let u=0;u<d;u++)l[u]!==void 0&&c++;return c===d}function s(l){const c=l.target;c.removeEventListener("dispose",s);const d=e.get(c);d!==void 0&&(e.delete(c),d.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function p_e(t){const e={};function n(r){if(e[r]!==void 0)return e[r];const i=t.getExtension(r);return e[r]=i,i}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 i=n(r);return i===null&&K0("WebGLRenderer: "+r+" extension not supported."),i}}}function f_e(t,e,n,r){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const x in p.attributes)e.remove(p.attributes[x]);p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),r.releaseStatesOfGeometry(p),p.isInstancedBufferGeometry===!0&&delete p._maxInstanceCount,n.memory.geometries--}function l(m,p){return i[p.id]===!0||(p.addEventListener("dispose",o),i[p.id]=!0,n.memory.geometries++),p}function c(m){const p=m.attributes;for(const f in p)e.update(p[f],t.ARRAY_BUFFER)}function d(m){const p=[],f=m.index,x=m.attributes.position;let v=0;if(f!==null){const _=f.array;v=f.version;for(let C=0,P=_.length;C<P;C+=3){const N=_[C+0],A=_[C+1],T=_[C+2];p.push(N,A,A,T,T,N)}}else if(x!==void 0){const _=x.array;v=x.version;for(let C=0,P=_.length/3-1;C<P;C+=3){const N=C+0,A=C+1,T=C+2;p.push(N,A,A,T,T,N)}}else return;const g=new(cZ(p)?yZ:xZ)(p,1);g.version=v;const b=s.get(m);b&&e.remove(b),s.set(m,g)}function u(m){const p=s.get(m);if(p){const f=m.index;f!==null&&p.version<f.version&&d(m)}else d(m);return s.get(m)}return{get:l,update:c,getWireframeAttribute:u}}function g_e(t,e,n){let r;function i(p){r=p}let s,o;function l(p){s=p.type,o=p.bytesPerElement}function c(p,f){t.drawElements(r,f,s,p*o),n.update(f,r,1)}function d(p,f,x){x!==0&&(t.drawElementsInstanced(r,f,s,p*o,x),n.update(f,r,x))}function u(p,f,x){if(x===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r,f,0,s,p,0,x);let g=0;for(let b=0;b<x;b++)g+=f[b];n.update(g,r,1)}function m(p,f,x,v){if(x===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let b=0;b<p.length;b++)d(p[b]/o,f[b],v[b]);else{g.multiDrawElementsInstancedWEBGL(r,f,0,s,p,0,v,0,x);let b=0;for(let _=0;_<x;_++)b+=f[_]*v[_];n.update(b,r,1)}}this.setMode=i,this.setIndex=l,this.render=c,this.renderInstances=d,this.renderMultiDraw=u,this.renderMultiDrawInstances=m}function b_e(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:ni("WebGLInfo: Unknown draw mode:",o);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:i,update:r}}function x_e(t,e,n){const r=new WeakMap,i=new ui;function s(o,l,c){const d=o.morphTargetInfluences,u=l.morphAttributes.position||l.morphAttributes.normal||l.morphAttributes.color,m=u!==void 0?u.length:0;let p=r.get(l);if(p===void 0||p.count!==m){let D=function(){F.dispose(),r.delete(l),l.removeEventListener("dispose",D)};var f=D;p!==void 0&&p.texture.dispose();const x=l.morphAttributes.position!==void 0,v=l.morphAttributes.normal!==void 0,g=l.morphAttributes.color!==void 0,b=l.morphAttributes.position||[],_=l.morphAttributes.normal||[],C=l.morphAttributes.color||[];let P=0;x===!0&&(P=1),v===!0&&(P=2),g===!0&&(P=3);let N=l.attributes.position.count*P,A=1;N>e.maxTextureSize&&(A=Math.ceil(N/e.maxTextureSize),N=e.maxTextureSize);const T=new Float32Array(N*A*4*m),F=new pZ(T,N,A,m);F.type=Hu,F.needsUpdate=!0;const k=P*4;for(let H=0;H<m;H++){const z=b[H],X=_[H],L=C[H],ne=N*A*4*H;for(let ie=0;ie<z.count;ie++){const ee=ie*k;x===!0&&(i.fromBufferAttribute(z,ie),T[ne+ee+0]=i.x,T[ne+ee+1]=i.y,T[ne+ee+2]=i.z,T[ne+ee+3]=0),v===!0&&(i.fromBufferAttribute(X,ie),T[ne+ee+4]=i.x,T[ne+ee+5]=i.y,T[ne+ee+6]=i.z,T[ne+ee+7]=0),g===!0&&(i.fromBufferAttribute(L,ie),T[ne+ee+8]=i.x,T[ne+ee+9]=i.y,T[ne+ee+10]=i.z,T[ne+ee+11]=L.itemSize===4?i.w:1)}}p={count:m,texture:F,size:new ar(N,A)},r.set(l,p),l.addEventListener("dispose",D)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(t,"morphTexture",o.morphTexture,n);else{let x=0;for(let g=0;g<d.length;g++)x+=d[g];const v=l.morphTargetsRelative?1:1-x;c.getUniforms().setValue(t,"morphTargetBaseInfluence",v),c.getUniforms().setValue(t,"morphTargetInfluences",d)}c.getUniforms().setValue(t,"morphTargetsTexture",p.texture,n),c.getUniforms().setValue(t,"morphTargetsTextureSize",p.size)}return{update:s}}function y_e(t,e,n,r){let i=new WeakMap;function s(c){const d=r.render.frame,u=c.geometry,m=e.get(c,u);if(i.get(m)!==d&&(e.update(m),i.set(m,d)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),i.get(c)!==d&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),i.set(c,d))),c.isSkinnedMesh){const p=c.skeleton;i.get(p)!==d&&(p.update(),i.set(p,d))}return m}function o(){i=new WeakMap}function l(c){const d=c.target;d.removeEventListener("dispose",l),n.remove(d.instanceMatrix),d.instanceColor!==null&&n.remove(d.instanceColor)}return{update:s,dispose:o}}const DZ=new Vc,v6=new CZ(1,1),FZ=new pZ,RZ=new Lve,LZ=new kZ,w6=[],S6=[],_6=new Float32Array(16),k6=new Float32Array(9),N6=new Float32Array(4);function uy(t,e,n){const r=t[0];if(r<=0||r>0)return t;const i=e*n;let s=w6[i];if(s===void 0&&(s=new Float32Array(i),w6[i]=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 ki(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 Ni(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function IP(t,e){let n=S6[e];n===void 0&&(n=new Int32Array(e),S6[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function v_e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function w_e(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(ki(n,e))return;t.uniform2fv(this.addr,e),Ni(n,e)}}function S_e(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(ki(n,e))return;t.uniform3fv(this.addr,e),Ni(n,e)}}function __e(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(ki(n,e))return;t.uniform4fv(this.addr,e),Ni(n,e)}}function k_e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(ki(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),Ni(n,e)}else{if(ki(n,r))return;N6.set(r),t.uniformMatrix2fv(this.addr,!1,N6),Ni(n,r)}}function N_e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(ki(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),Ni(n,e)}else{if(ki(n,r))return;k6.set(r),t.uniformMatrix3fv(this.addr,!1,k6),Ni(n,r)}}function C_e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(ki(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),Ni(n,e)}else{if(ki(n,r))return;_6.set(r),t.uniformMatrix4fv(this.addr,!1,_6),Ni(n,r)}}function P_e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function T_e(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(ki(n,e))return;t.uniform2iv(this.addr,e),Ni(n,e)}}function A_e(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(ki(n,e))return;t.uniform3iv(this.addr,e),Ni(n,e)}}function j_e(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(ki(n,e))return;t.uniform4iv(this.addr,e),Ni(n,e)}}function M_e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function E_e(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(ki(n,e))return;t.uniform2uiv(this.addr,e),Ni(n,e)}}function D_e(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(ki(n,e))return;t.uniform3uiv(this.addr,e),Ni(n,e)}}function F_e(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(ki(n,e))return;t.uniform4uiv(this.addr,e),Ni(n,e)}}function R_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i);let s;this.type===t.SAMPLER_2D_SHADOW?(v6.compareFunction=lZ,s=v6):s=DZ,n.setTexture2D(e||s,i)}function L_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(e||RZ,i)}function O_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(e||LZ,i)}function I_e(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(e||FZ,i)}function z_e(t){switch(t){case 5126:return v_e;case 35664:return w_e;case 35665:return S_e;case 35666:return __e;case 35674:return k_e;case 35675:return N_e;case 35676:return C_e;case 5124:case 35670:return P_e;case 35667:case 35671:return T_e;case 35668:case 35672:return A_e;case 35669:case 35673:return j_e;case 5125:return M_e;case 36294:return E_e;case 36295:return D_e;case 36296:return F_e;case 35678:case 36198:case 36298:case 36306:case 35682:return R_e;case 35679:case 36299:case 36307:return L_e;case 35680:case 36300:case 36308:case 36293:return O_e;case 36289:case 36303:case 36311:case 36292:return I_e}}function U_e(t,e){t.uniform1fv(this.addr,e)}function B_e(t,e){const n=uy(e,this.size,2);t.uniform2fv(this.addr,n)}function H_e(t,e){const n=uy(e,this.size,3);t.uniform3fv(this.addr,n)}function q_e(t,e){const n=uy(e,this.size,4);t.uniform4fv(this.addr,n)}function $_e(t,e){const n=uy(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function V_e(t,e){const n=uy(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function G_e(t,e){const n=uy(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function W_e(t,e){t.uniform1iv(this.addr,e)}function K_e(t,e){t.uniform2iv(this.addr,e)}function X_e(t,e){t.uniform3iv(this.addr,e)}function Y_e(t,e){t.uniform4iv(this.addr,e)}function Q_e(t,e){t.uniform1uiv(this.addr,e)}function Z_e(t,e){t.uniform2uiv(this.addr,e)}function J_e(t,e){t.uniform3uiv(this.addr,e)}function e1e(t,e){t.uniform4uiv(this.addr,e)}function t1e(t,e,n){const r=this.cache,i=e.length,s=IP(n,i);ki(r,s)||(t.uniform1iv(this.addr,s),Ni(r,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||DZ,s[o])}function n1e(t,e,n){const r=this.cache,i=e.length,s=IP(n,i);ki(r,s)||(t.uniform1iv(this.addr,s),Ni(r,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||RZ,s[o])}function r1e(t,e,n){const r=this.cache,i=e.length,s=IP(n,i);ki(r,s)||(t.uniform1iv(this.addr,s),Ni(r,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||LZ,s[o])}function a1e(t,e,n){const r=this.cache,i=e.length,s=IP(n,i);ki(r,s)||(t.uniform1iv(this.addr,s),Ni(r,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||FZ,s[o])}function i1e(t){switch(t){case 5126:return U_e;case 35664:return B_e;case 35665:return H_e;case 35666:return q_e;case 35674:return $_e;case 35675:return V_e;case 35676:return G_e;case 5124:case 35670:return W_e;case 35667:case 35671:return K_e;case 35668:case 35672:return X_e;case 35669:case 35673:return Y_e;case 5125:return Q_e;case 36294:return Z_e;case 36295:return J_e;case 36296:return e1e;case 35678:case 36198:case 36298:case 36306:case 35682:return t1e;case 35679:case 36299:case 36307:return n1e;case 35680:case 36300:case 36308:case 36293:return r1e;case 36289:case 36303:case 36311:case 36292:return a1e}}let s1e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=z_e(n.type)}},o1e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=i1e(n.type)}},l1e=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],r)}}};const YM=/(\w+)(\])?(\[|\.)?/g;function C6(t,e){t.seq.push(e),t.map[e.id]=e}function c1e(t,e,n){const r=t.name,i=r.length;for(YM.lastIndex=0;;){const s=YM.exec(r),o=YM.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){C6(n,d===void 0?new s1e(l,t,e):new o1e(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new l1e(l),C6(n,m)),n=m}}}let Ek=class{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<r;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);c1e(s,o,this)}}setValue(e,n,r,i){const s=this.map[n];s!==void 0&&s.setValue(e,r,i)}setOptional(e,n,r){const i=n[r];i!==void 0&&this.setValue(e,r,i)}static upload(e,n,r,i){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,i)}}static seqWithValue(e,n){const r=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&r.push(o)}return r}};function P6(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const d1e=37297;let u1e=0;function m1e(t,e){const n=t.split(`
- `),r=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
- `)}const T6=new sr;function h1e(t){Tr._getMatrix(T6,Tr.workingColorSpace,t);const e=`mat3( ${T6.elements.map(n=>n.toFixed(4))} )`;switch(Tr.getTransfer(t)){case pN:return[e,"LinearTransferOETF"];case Vr:return[e,"sRGBTransferOETF"];default:return qn("WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function A6(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()+`
- `+s+`
- `+m1e(t.getShaderSource(e),l)}else return s}function p1e(t,e){const n=h1e(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`
- `)}function f1e(t,e){let n;switch(e){case cve:n="Linear";break;case dve:n="Reinhard";break;case uve:n="Cineon";break;case mve:n="ACESFilmic";break;case pve:n="AgX";break;case fve:n="Neutral";break;case hve:n="Custom";break;default:qn("WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const n1=new Tt;function g1e(){Tr.getLuminanceCoefficients(n1);const t=n1.x.toFixed(4),e=n1.y.toFixed(4),n=n1.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(`
- `)}function b1e(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Xv).join(`
- `)}function x1e(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
- `)}function y1e(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){const s=t.getActiveAttrib(e,i),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 Xv(t){return t!==""}function j6(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 M6(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const v1e=/^[ \t]*#include +<([\w\d./]+)>/gm;function GF(t){return t.replace(v1e,S1e)}const w1e=new Map;function S1e(t,e){let n=nr[e];if(n===void 0){const r=w1e.get(e);if(r!==void 0)n=nr[r],qn('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return GF(n)}const _1e=/#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 E6(t){return t.replace(_1e,k1e)}function k1e(t,e,n,r){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function D6(t){let e=`precision ${t.precision} float;
- precision ${t.precision} int;
- precision ${t.precision} sampler2D;
- precision ${t.precision} samplerCube;
- precision ${t.precision} sampler3D;
- precision ${t.precision} sampler2DArray;
- precision ${t.precision} sampler2DShadow;
- precision ${t.precision} samplerCubeShadow;
- precision ${t.precision} sampler2DArrayShadow;
- precision ${t.precision} isampler2D;
- precision ${t.precision} isampler3D;
- precision ${t.precision} isamplerCube;
- precision ${t.precision} isampler2DArray;
- precision ${t.precision} usampler2D;
- precision ${t.precision} usampler3D;
- precision ${t.precision} usamplerCube;
- precision ${t.precision} usampler2DArray;
- `;return t.precision==="highp"?e+=`
- #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
- #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
- #define LOW_PRECISION`),e}function N1e(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===ZQ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===Hye?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===Cu&&(e="SHADOWMAP_TYPE_VSM"),e}function C1e(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case Mx:case Ex:e="ENVMAP_TYPE_CUBE";break;case RP:e="ENVMAP_TYPE_CUBE_UV";break}return e}function P1e(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===Ex&&(e="ENVMAP_MODE_REFRACTION"),e}function T1e(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case EO:e="ENVMAP_BLENDING_MULTIPLY";break;case ove:e="ENVMAP_BLENDING_MIX";break;case lve:e="ENVMAP_BLENDING_ADD";break}return e}function A1e(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 j1e(t,e,n,r){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=N1e(n),d=C1e(n),u=P1e(n),m=T1e(n),p=A1e(n),f=b1e(n),x=x1e(s),v=i.createProgram();let g,b,_=n.glslVersion?"#version "+n.glslVersion+`
- `:"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Xv).join(`
- `),g.length>0&&(g+=`
- `),b=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Xv).join(`
- `),b.length>0&&(b+=`
- `)):(g=[D6(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 "+u:"",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",`
- `].filter(Xv).join(`
- `),b=[D6(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 "+d:"",n.envMap?"#define "+u:"",n.envMap?"#define "+m:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.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!==Wh?"#define TONE_MAPPING":"",n.toneMapping!==Wh?nr.tonemapping_pars_fragment:"",n.toneMapping!==Wh?f1e("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",nr.colorspace_pars_fragment,p1e("linearToOutputTexel",n.outputColorSpace),g1e(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
- `].filter(Xv).join(`
- `)),o=GF(o),o=j6(o,n),o=M6(o,n),l=GF(l),l=j6(l,n),l=M6(l,n),o=E6(o),l=E6(l),n.isRawShaderMaterial!==!0&&(_=`#version 300 es
- `,g=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
- `)+`
- `+g,b=["#define varying in",n.glslVersion===zH?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===zH?"":"#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(`
- `)+`
- `+b);const C=_+g+o,P=_+b+l,N=P6(i,i.VERTEX_SHADER,C),A=P6(i,i.FRAGMENT_SHADER,P);i.attachShader(v,N),i.attachShader(v,A),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function T(H){if(t.debug.checkShaderErrors){const z=i.getProgramInfoLog(v)||"",X=i.getShaderInfoLog(N)||"",L=i.getShaderInfoLog(A)||"",ne=z.trim(),ie=X.trim(),ee=L.trim();let ue=!0,le=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(ue=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,A);else{const oe=A6(i,N,"vertex"),W=A6(i,A,"fragment");ni("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+`
- Material Name: `+H.name+`
- Material Type: `+H.type+`
- Program Info Log: `+ne+`
- `+oe+`
- `+W)}else ne!==""?qn("WebGLProgram: Program Info Log:",ne):(ie===""||ee==="")&&(le=!1);le&&(H.diagnostics={runnable:ue,programLog:ne,vertexShader:{log:ie,prefix:g},fragmentShader:{log:ee,prefix:b}})}i.deleteShader(N),i.deleteShader(A),F=new Ek(i,v),k=y1e(i,v)}let F;this.getUniforms=function(){return F===void 0&&T(this),F};let k;this.getAttributes=function(){return k===void 0&&T(this),k};let D=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return D===!1&&(D=i.getProgramParameter(v,d1e)),D},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=u1e++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=A,this}let M1e=0,E1e=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.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 D1e(e),n.set(e,r)),r}},D1e=class{constructor(e){this.id=M1e++,this.code=e,this.usedTimes=0}};function F1e(t,e,n,r,i,s,o){const l=new gZ,c=new E1e,d=new Set,u=[],m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.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(k){return d.add(k),k===0?"uv":`uv${k}`}function g(k,D,H,z,X){const L=z.fog,ne=X.geometry,ie=k.isMeshStandardMaterial?z.environment:null,ee=(k.isMeshStandardMaterial?n:e).get(k.envMap||ie),ue=ee&&ee.mapping===RP?ee.image.height:null,le=x[k.type];k.precision!==null&&(f=i.getMaxPrecision(k.precision),f!==k.precision&&qn("WebGLProgram.getParameters:",k.precision,"not supported, using",f,"instead."));const oe=ne.morphAttributes.position||ne.morphAttributes.normal||ne.morphAttributes.color,W=oe!==void 0?oe.length:0;let re=0;ne.morphAttributes.position!==void 0&&(re=1),ne.morphAttributes.normal!==void 0&&(re=2),ne.morphAttributes.color!==void 0&&(re=3);let ce,xe,Ne,$;if(le){const ut=fd[le];ce=ut.vertexShader,xe=ut.fragmentShader}else ce=k.vertexShader,xe=k.fragmentShader,c.update(k),Ne=c.getVertexShaderID(k),$=c.getFragmentShaderID(k);const Y=t.getRenderTarget(),E=t.state.buffers.depth.getReversed(),j=X.isInstancedMesh===!0,O=X.isBatchedMesh===!0,K=!!k.map,B=!!k.matcap,he=!!ee,I=!!k.aoMap,V=!!k.lightMap,Q=!!k.bumpMap,G=!!k.normalMap,J=!!k.displacementMap,se=!!k.emissiveMap,fe=!!k.metalnessMap,pe=!!k.roughnessMap,de=k.anisotropy>0,U=k.clearcoat>0,R=k.dispersion>0,ae=k.iridescence>0,_e=k.sheen>0,Se=k.transmission>0,ye=de&&!!k.anisotropyMap,Ae=U&&!!k.clearcoatMap,ve=U&&!!k.clearcoatNormalMap,je=U&&!!k.clearcoatRoughnessMap,Re=ae&&!!k.iridescenceMap,Ee=ae&&!!k.iridescenceThicknessMap,Te=_e&&!!k.sheenColorMap,Me=_e&&!!k.sheenRoughnessMap,Be=!!k.specularMap,Ke=!!k.specularColorMap,tt=!!k.specularIntensityMap,te=Se&&!!k.transmissionMap,Ie=Se&&!!k.thicknessMap,be=!!k.gradientMap,$e=!!k.alphaMap,He=k.alphaTest>0,ge=!!k.alphaHash,Pe=!!k.extensions;let qe=Wh;k.toneMapped&&(Y===null||Y.isXRRenderTarget===!0)&&(qe=t.toneMapping);const Ze={shaderID:le,shaderType:k.type,shaderName:k.name,vertexShader:ce,fragmentShader:xe,defines:k.defines,customVertexShaderID:Ne,customFragmentShaderID:$,isRawShaderMaterial:k.isRawShaderMaterial===!0,glslVersion:k.glslVersion,precision:f,batching:O,batchingColor:O&&X._colorsTexture!==null,instancing:j,instancingColor:j&&X.instanceColor!==null,instancingMorph:j&&X.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:Y===null?t.outputColorSpace:Y.isXRRenderTarget===!0?Y.texture.colorSpace:Dx,alphaToCoverage:!!k.alphaToCoverage,map:K,matcap:B,envMap:he,envMapMode:he&&ee.mapping,envMapCubeUVHeight:ue,aoMap:I,lightMap:V,bumpMap:Q,normalMap:G,displacementMap:p&&J,emissiveMap:se,normalMapObjectSpace:G&&k.normalMapType===yve,normalMapTangentSpace:G&&k.normalMapType===oZ,metalnessMap:fe,roughnessMap:pe,anisotropy:de,anisotropyMap:ye,clearcoat:U,clearcoatMap:Ae,clearcoatNormalMap:ve,clearcoatRoughnessMap:je,dispersion:R,iridescence:ae,iridescenceMap:Re,iridescenceThicknessMap:Ee,sheen:_e,sheenColorMap:Te,sheenRoughnessMap:Me,specularMap:Be,specularColorMap:Ke,specularIntensityMap:tt,transmission:Se,transmissionMap:te,thicknessMap:Ie,gradientMap:be,opaque:k.transparent===!1&&k.blending===hx&&k.alphaToCoverage===!1,alphaMap:$e,alphaTest:He,alphaHash:ge,combine:k.combine,mapUv:K&&v(k.map.channel),aoMapUv:I&&v(k.aoMap.channel),lightMapUv:V&&v(k.lightMap.channel),bumpMapUv:Q&&v(k.bumpMap.channel),normalMapUv:G&&v(k.normalMap.channel),displacementMapUv:J&&v(k.displacementMap.channel),emissiveMapUv:se&&v(k.emissiveMap.channel),metalnessMapUv:fe&&v(k.metalnessMap.channel),roughnessMapUv:pe&&v(k.roughnessMap.channel),anisotropyMapUv:ye&&v(k.anisotropyMap.channel),clearcoatMapUv:Ae&&v(k.clearcoatMap.channel),clearcoatNormalMapUv:ve&&v(k.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:je&&v(k.clearcoatRoughnessMap.channel),iridescenceMapUv:Re&&v(k.iridescenceMap.channel),iridescenceThicknessMapUv:Ee&&v(k.iridescenceThicknessMap.channel),sheenColorMapUv:Te&&v(k.sheenColorMap.channel),sheenRoughnessMapUv:Me&&v(k.sheenRoughnessMap.channel),specularMapUv:Be&&v(k.specularMap.channel),specularColorMapUv:Ke&&v(k.specularColorMap.channel),specularIntensityMapUv:tt&&v(k.specularIntensityMap.channel),transmissionMapUv:te&&v(k.transmissionMap.channel),thicknessMapUv:Ie&&v(k.thicknessMap.channel),alphaMapUv:$e&&v(k.alphaMap.channel),vertexTangents:!!ne.attributes.tangent&&(G||de),vertexColors:k.vertexColors,vertexAlphas:k.vertexColors===!0&&!!ne.attributes.color&&ne.attributes.color.itemSize===4,pointsUvs:X.isPoints===!0&&!!ne.attributes.uv&&(K||$e),fog:!!L,useFog:k.fog===!0,fogExp2:!!L&&L.isFogExp2,flatShading:k.flatShading===!0&&k.wireframe===!1,sizeAttenuation:k.sizeAttenuation===!0,logarithmicDepthBuffer:m,reversedDepthBuffer:E,skinning:X.isSkinnedMesh===!0,morphTargets:ne.morphAttributes.position!==void 0,morphNormals:ne.morphAttributes.normal!==void 0,morphColors:ne.morphAttributes.color!==void 0,morphTargetsCount:W,morphTextureStride:re,numDirLights:D.directional.length,numPointLights:D.point.length,numSpotLights:D.spot.length,numSpotLightMaps:D.spotLightMap.length,numRectAreaLights:D.rectArea.length,numHemiLights:D.hemi.length,numDirLightShadows:D.directionalShadowMap.length,numPointLightShadows:D.pointShadowMap.length,numSpotLightShadows:D.spotShadowMap.length,numSpotLightShadowsWithMaps:D.numSpotLightShadowsWithMaps,numLightProbes:D.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:k.dithering,shadowMapEnabled:t.shadowMap.enabled&&H.length>0,shadowMapType:t.shadowMap.type,toneMapping:qe,decodeVideoTexture:K&&k.map.isVideoTexture===!0&&Tr.getTransfer(k.map.colorSpace)===Vr,decodeVideoTextureEmissive:se&&k.emissiveMap.isVideoTexture===!0&&Tr.getTransfer(k.emissiveMap.colorSpace)===Vr,premultipliedAlpha:k.premultipliedAlpha,doubleSided:k.side===bd,flipSided:k.side===Ao,useDepthPacking:k.depthPacking>=0,depthPacking:k.depthPacking||0,index0AttributeName:k.index0AttributeName,extensionClipCullDistance:Pe&&k.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Pe&&k.extensions.multiDraw===!0||O)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:k.customProgramCacheKey()};return Ze.vertexUv1s=d.has(1),Ze.vertexUv2s=d.has(2),Ze.vertexUv3s=d.has(3),d.clear(),Ze}function b(k){const D=[];if(k.shaderID?D.push(k.shaderID):(D.push(k.customVertexShaderID),D.push(k.customFragmentShaderID)),k.defines!==void 0)for(const H in k.defines)D.push(H),D.push(k.defines[H]);return k.isRawShaderMaterial===!1&&(_(D,k),C(D,k),D.push(t.outputColorSpace)),D.push(k.customProgramCacheKey),D.join()}function _(k,D){k.push(D.precision),k.push(D.outputColorSpace),k.push(D.envMapMode),k.push(D.envMapCubeUVHeight),k.push(D.mapUv),k.push(D.alphaMapUv),k.push(D.lightMapUv),k.push(D.aoMapUv),k.push(D.bumpMapUv),k.push(D.normalMapUv),k.push(D.displacementMapUv),k.push(D.emissiveMapUv),k.push(D.metalnessMapUv),k.push(D.roughnessMapUv),k.push(D.anisotropyMapUv),k.push(D.clearcoatMapUv),k.push(D.clearcoatNormalMapUv),k.push(D.clearcoatRoughnessMapUv),k.push(D.iridescenceMapUv),k.push(D.iridescenceThicknessMapUv),k.push(D.sheenColorMapUv),k.push(D.sheenRoughnessMapUv),k.push(D.specularMapUv),k.push(D.specularColorMapUv),k.push(D.specularIntensityMapUv),k.push(D.transmissionMapUv),k.push(D.thicknessMapUv),k.push(D.combine),k.push(D.fogExp2),k.push(D.sizeAttenuation),k.push(D.morphTargetsCount),k.push(D.morphAttributeCount),k.push(D.numDirLights),k.push(D.numPointLights),k.push(D.numSpotLights),k.push(D.numSpotLightMaps),k.push(D.numHemiLights),k.push(D.numRectAreaLights),k.push(D.numDirLightShadows),k.push(D.numPointLightShadows),k.push(D.numSpotLightShadows),k.push(D.numSpotLightShadowsWithMaps),k.push(D.numLightProbes),k.push(D.shadowMapType),k.push(D.toneMapping),k.push(D.numClippingPlanes),k.push(D.numClipIntersection),k.push(D.depthPacking)}function C(k,D){l.disableAll(),D.supportsVertexTextures&&l.enable(0),D.instancing&&l.enable(1),D.instancingColor&&l.enable(2),D.instancingMorph&&l.enable(3),D.matcap&&l.enable(4),D.envMap&&l.enable(5),D.normalMapObjectSpace&&l.enable(6),D.normalMapTangentSpace&&l.enable(7),D.clearcoat&&l.enable(8),D.iridescence&&l.enable(9),D.alphaTest&&l.enable(10),D.vertexColors&&l.enable(11),D.vertexAlphas&&l.enable(12),D.vertexUv1s&&l.enable(13),D.vertexUv2s&&l.enable(14),D.vertexUv3s&&l.enable(15),D.vertexTangents&&l.enable(16),D.anisotropy&&l.enable(17),D.alphaHash&&l.enable(18),D.batching&&l.enable(19),D.dispersion&&l.enable(20),D.batchingColor&&l.enable(21),D.gradientMap&&l.enable(22),k.push(l.mask),l.disableAll(),D.fog&&l.enable(0),D.useFog&&l.enable(1),D.flatShading&&l.enable(2),D.logarithmicDepthBuffer&&l.enable(3),D.reversedDepthBuffer&&l.enable(4),D.skinning&&l.enable(5),D.morphTargets&&l.enable(6),D.morphNormals&&l.enable(7),D.morphColors&&l.enable(8),D.premultipliedAlpha&&l.enable(9),D.shadowMapEnabled&&l.enable(10),D.doubleSided&&l.enable(11),D.flipSided&&l.enable(12),D.useDepthPacking&&l.enable(13),D.dithering&&l.enable(14),D.transmission&&l.enable(15),D.sheen&&l.enable(16),D.opaque&&l.enable(17),D.pointsUvs&&l.enable(18),D.decodeVideoTexture&&l.enable(19),D.decodeVideoTextureEmissive&&l.enable(20),D.alphaToCoverage&&l.enable(21),k.push(l.mask)}function P(k){const D=x[k.type];let H;if(D){const z=fd[D];H=Xve.clone(z.uniforms)}else H=k.uniforms;return H}function N(k,D){let H;for(let z=0,X=u.length;z<X;z++){const L=u[z];if(L.cacheKey===D){H=L,++H.usedTimes;break}}return H===void 0&&(H=new j1e(t,D,k,s),u.push(H)),H}function A(k){if(--k.usedTimes===0){const D=u.indexOf(k);u[D]=u[u.length-1],u.pop(),k.destroy()}}function T(k){c.remove(k)}function F(){c.dispose()}return{getParameters:g,getProgramCacheKey:b,getUniforms:P,acquireProgram:N,releaseProgram:A,releaseShaderCache:T,programs:u,dispose:F}}function R1e(){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 i(o,l,c){t.get(o)[l]=c}function s(){t=new WeakMap}return{has:e,get:n,remove:r,update:i,dispose:s}}function L1e(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 F6(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 R6(){const t=[];let e=0;const n=[],r=[],i=[];function s(){e=0,n.length=0,r.length=0,i.length=0}function o(m,p,f,x,v,g){let b=t[e];return b===void 0?(b={id:m.id,object:m,geometry:p,material:f,groupOrder:x,renderOrder:m.renderOrder,z:v,group:g},t[e]=b):(b.id=m.id,b.object=m,b.geometry=p,b.material=f,b.groupOrder=x,b.renderOrder=m.renderOrder,b.z=v,b.group=g),e++,b}function l(m,p,f,x,v,g){const b=o(m,p,f,x,v,g);f.transmission>0?r.push(b):f.transparent===!0?i.push(b):n.push(b)}function c(m,p,f,x,v,g){const b=o(m,p,f,x,v,g);f.transmission>0?r.unshift(b):f.transparent===!0?i.unshift(b):n.unshift(b)}function d(m,p){n.length>1&&n.sort(m||L1e),r.length>1&&r.sort(p||F6),i.length>1&&i.sort(p||F6)}function u(){for(let m=e,p=t.length;m<p;m++){const f=t[m];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:r,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function O1e(){let t=new WeakMap;function e(r,i){const s=t.get(r);let o;return s===void 0?(o=new R6,t.set(r,[o])):i>=s.length?(o=new R6,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function I1e(){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 Tt,color:new lr};break;case"SpotLight":n={position:new Tt,direction:new Tt,color:new lr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Tt,color:new lr,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Tt,skyColor:new lr,groundColor:new lr};break;case"RectAreaLight":n={color:new lr,position:new Tt,halfWidth:new Tt,halfHeight:new Tt};break}return t[e.id]=n,n}}}function z1e(){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 ar};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ar};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ar,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let U1e=0;function B1e(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function H1e(t){const e=new I1e,n=z1e(),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 d=0;d<9;d++)r.probe.push(new Tt);const i=new Tt,s=new fi,o=new fi;function l(d){let u=0,m=0,p=0;for(let k=0;k<9;k++)r.probe[k].set(0,0,0);let f=0,x=0,v=0,g=0,b=0,_=0,C=0,P=0,N=0,A=0,T=0;d.sort(B1e);for(let k=0,D=d.length;k<D;k++){const H=d[k],z=H.color,X=H.intensity,L=H.distance,ne=H.shadow&&H.shadow.map?H.shadow.map.texture:null;if(H.isAmbientLight)u+=z.r*X,m+=z.g*X,p+=z.b*X;else if(H.isLightProbe){for(let ie=0;ie<9;ie++)r.probe[ie].addScaledVector(H.sh.coefficients[ie],X);T++}else if(H.isDirectionalLight){const ie=e.get(H);if(ie.color.copy(H.color).multiplyScalar(H.intensity),H.castShadow){const ee=H.shadow,ue=n.get(H);ue.shadowIntensity=ee.intensity,ue.shadowBias=ee.bias,ue.shadowNormalBias=ee.normalBias,ue.shadowRadius=ee.radius,ue.shadowMapSize=ee.mapSize,r.directionalShadow[f]=ue,r.directionalShadowMap[f]=ne,r.directionalShadowMatrix[f]=H.shadow.matrix,_++}r.directional[f]=ie,f++}else if(H.isSpotLight){const ie=e.get(H);ie.position.setFromMatrixPosition(H.matrixWorld),ie.color.copy(z).multiplyScalar(X),ie.distance=L,ie.coneCos=Math.cos(H.angle),ie.penumbraCos=Math.cos(H.angle*(1-H.penumbra)),ie.decay=H.decay,r.spot[v]=ie;const ee=H.shadow;if(H.map&&(r.spotLightMap[N]=H.map,N++,ee.updateMatrices(H),H.castShadow&&A++),r.spotLightMatrix[v]=ee.matrix,H.castShadow){const ue=n.get(H);ue.shadowIntensity=ee.intensity,ue.shadowBias=ee.bias,ue.shadowNormalBias=ee.normalBias,ue.shadowRadius=ee.radius,ue.shadowMapSize=ee.mapSize,r.spotShadow[v]=ue,r.spotShadowMap[v]=ne,P++}v++}else if(H.isRectAreaLight){const ie=e.get(H);ie.color.copy(z).multiplyScalar(X),ie.halfWidth.set(H.width*.5,0,0),ie.halfHeight.set(0,H.height*.5,0),r.rectArea[g]=ie,g++}else if(H.isPointLight){const ie=e.get(H);if(ie.color.copy(H.color).multiplyScalar(H.intensity),ie.distance=H.distance,ie.decay=H.decay,H.castShadow){const ee=H.shadow,ue=n.get(H);ue.shadowIntensity=ee.intensity,ue.shadowBias=ee.bias,ue.shadowNormalBias=ee.normalBias,ue.shadowRadius=ee.radius,ue.shadowMapSize=ee.mapSize,ue.shadowCameraNear=ee.camera.near,ue.shadowCameraFar=ee.camera.far,r.pointShadow[x]=ue,r.pointShadowMap[x]=ne,r.pointShadowMatrix[x]=H.shadow.matrix,C++}r.point[x]=ie,x++}else if(H.isHemisphereLight){const ie=e.get(H);ie.skyColor.copy(H.color).multiplyScalar(X),ie.groundColor.copy(H.groundColor).multiplyScalar(X),r.hemi[b]=ie,b++}}g>0&&(t.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=nn.LTC_FLOAT_1,r.rectAreaLTC2=nn.LTC_FLOAT_2):(r.rectAreaLTC1=nn.LTC_HALF_1,r.rectAreaLTC2=nn.LTC_HALF_2)),r.ambient[0]=u,r.ambient[1]=m,r.ambient[2]=p;const F=r.hash;(F.directionalLength!==f||F.pointLength!==x||F.spotLength!==v||F.rectAreaLength!==g||F.hemiLength!==b||F.numDirectionalShadows!==_||F.numPointShadows!==C||F.numSpotShadows!==P||F.numSpotMaps!==N||F.numLightProbes!==T)&&(r.directional.length=f,r.spot.length=v,r.rectArea.length=g,r.point.length=x,r.hemi.length=b,r.directionalShadow.length=_,r.directionalShadowMap.length=_,r.pointShadow.length=C,r.pointShadowMap.length=C,r.spotShadow.length=P,r.spotShadowMap.length=P,r.directionalShadowMatrix.length=_,r.pointShadowMatrix.length=C,r.spotLightMatrix.length=P+N-A,r.spotLightMap.length=N,r.numSpotLightShadowsWithMaps=A,r.numLightProbes=T,F.directionalLength=f,F.pointLength=x,F.spotLength=v,F.rectAreaLength=g,F.hemiLength=b,F.numDirectionalShadows=_,F.numPointShadows=C,F.numSpotShadows=P,F.numSpotMaps=N,F.numLightProbes=T,r.version=U1e++)}function c(d,u){let m=0,p=0,f=0,x=0,v=0;const g=u.matrixWorldInverse;for(let b=0,_=d.length;b<_;b++){const C=d[b];if(C.isDirectionalLight){const P=r.directional[m];P.direction.setFromMatrixPosition(C.matrixWorld),i.setFromMatrixPosition(C.target.matrixWorld),P.direction.sub(i),P.direction.transformDirection(g),m++}else if(C.isSpotLight){const P=r.spot[f];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(g),P.direction.setFromMatrixPosition(C.matrixWorld),i.setFromMatrixPosition(C.target.matrixWorld),P.direction.sub(i),P.direction.transformDirection(g),f++}else if(C.isRectAreaLight){const P=r.rectArea[x];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(g),o.identity(),s.copy(C.matrixWorld),s.premultiply(g),o.extractRotation(s),P.halfWidth.set(C.width*.5,0,0),P.halfHeight.set(0,C.height*.5,0),P.halfWidth.applyMatrix4(o),P.halfHeight.applyMatrix4(o),x++}else if(C.isPointLight){const P=r.point[p];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(g),p++}else if(C.isHemisphereLight){const P=r.hemi[v];P.direction.setFromMatrixPosition(C.matrixWorld),P.direction.transformDirection(g),v++}}}return{setup:l,setupView:c,state:r}}function L6(t){const e=new H1e(t),n=[],r=[];function i(u){d.camera=u,n.length=0,r.length=0}function s(u){n.push(u)}function o(u){r.push(u)}function l(){e.setup(n)}function c(u){e.setupView(n,u)}const d={lightsArray:n,shadowsArray:r,camera:null,lights:e,transmissionRenderTarget:{}};return{init:i,state:d,setupLights:l,setupLightsView:c,pushLight:s,pushShadow:o}}function q1e(t){let e=new WeakMap;function n(i,s=0){const o=e.get(i);let l;return o===void 0?(l=new L6(t),e.set(i,[l])):s>=o.length?(l=new L6(t),o.push(l)):l=o[s],l}function r(){e=new WeakMap}return{get:n,dispose:r}}const $1e=`void main() {
- gl_Position = vec4( position, 1.0 );
- }`,V1e=`uniform sampler2D shadow_pass;
- uniform vec2 resolution;
- uniform float radius;
- #include <packing>
- void main() {
- const float samples = float( VSM_SAMPLES );
- float mean = 0.0;
- float squared_mean = 0.0;
- float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
- float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
- for ( float i = 0.0; i < samples; i ++ ) {
- float uvOffset = uvStart + i * uvStride;
- #ifdef HORIZONTAL_PASS
- vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
- mean += distribution.x;
- squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
- #else
- float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
- mean += depth;
- squared_mean += depth * depth;
- #endif
- }
- mean = mean / samples;
- squared_mean = squared_mean / samples;
- float std_dev = sqrt( squared_mean - mean * mean );
- gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
- }`;function G1e(t,e,n){let r=new $O;const i=new ar,s=new ar,o=new ui,l=new l0e({depthPacking:xve}),c=new c0e,d={},u=n.maxTextureSize,m={[ip]:Ao,[Ao]:ip,[bd]:bd},p=new lm({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ar},radius:{value:4}},vertexShader:$1e,fragmentShader:V1e}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const x=new sc;x.setAttribute("position",new Zs(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new oc(x,p),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=ZQ;let b=this.type;this.render=function(A,T,F){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;const k=t.getRenderTarget(),D=t.getActiveCubeFace(),H=t.getActiveMipmapLevel(),z=t.state;z.setBlending(Xu),z.buffers.depth.getReversed()===!0?z.buffers.color.setClear(0,0,0,0):z.buffers.color.setClear(1,1,1,1),z.buffers.depth.setTest(!0),z.setScissorTest(!1);const X=b!==Cu&&this.type===Cu,L=b===Cu&&this.type!==Cu;for(let ne=0,ie=A.length;ne<ie;ne++){const ee=A[ne],ue=ee.shadow;if(ue===void 0){qn("WebGLShadowMap:",ee,"has no shadow.");continue}if(ue.autoUpdate===!1&&ue.needsUpdate===!1)continue;i.copy(ue.mapSize);const le=ue.getFrameExtents();if(i.multiply(le),s.copy(ue.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/le.x),i.x=s.x*le.x,ue.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/le.y),i.y=s.y*le.y,ue.mapSize.y=s.y)),ue.map===null||X===!0||L===!0){const W=this.type!==Cu?{minFilter:il,magFilter:il}:{};ue.map!==null&&ue.map.dispose(),ue.map=new tg(i.x,i.y,W),ue.map.texture.name=ee.name+".shadowMap",ue.camera.updateProjectionMatrix()}t.setRenderTarget(ue.map),t.clear();const oe=ue.getViewportCount();for(let W=0;W<oe;W++){const re=ue.getViewport(W);o.set(s.x*re.x,s.y*re.y,s.x*re.z,s.y*re.w),z.viewport(o),ue.updateMatrices(ee,W),r=ue.getFrustum(),P(T,F,ue.camera,ee,this.type)}ue.isPointLightShadow!==!0&&this.type===Cu&&_(ue,F),ue.needsUpdate=!1}b=this.type,g.needsUpdate=!1,t.setRenderTarget(k,D,H)};function _(A,T){const F=e.update(v);p.defines.VSM_SAMPLES!==A.blurSamples&&(p.defines.VSM_SAMPLES=A.blurSamples,f.defines.VSM_SAMPLES=A.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),A.mapPass===null&&(A.mapPass=new tg(i.x,i.y)),p.uniforms.shadow_pass.value=A.map.texture,p.uniforms.resolution.value=A.mapSize,p.uniforms.radius.value=A.radius,t.setRenderTarget(A.mapPass),t.clear(),t.renderBufferDirect(T,null,F,p,v,null),f.uniforms.shadow_pass.value=A.mapPass.texture,f.uniforms.resolution.value=A.mapSize,f.uniforms.radius.value=A.radius,t.setRenderTarget(A.map),t.clear(),t.renderBufferDirect(T,null,F,f,v,null)}function C(A,T,F,k){let D=null;const H=F.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(H!==void 0)D=H;else if(D=F.isPointLight===!0?c:l,t.localClippingEnabled&&T.clipShadows===!0&&Array.isArray(T.clippingPlanes)&&T.clippingPlanes.length!==0||T.displacementMap&&T.displacementScale!==0||T.alphaMap&&T.alphaTest>0||T.map&&T.alphaTest>0||T.alphaToCoverage===!0){const z=D.uuid,X=T.uuid;let L=d[z];L===void 0&&(L={},d[z]=L);let ne=L[X];ne===void 0&&(ne=D.clone(),L[X]=ne,T.addEventListener("dispose",N)),D=ne}if(D.visible=T.visible,D.wireframe=T.wireframe,k===Cu?D.side=T.shadowSide!==null?T.shadowSide:T.side:D.side=T.shadowSide!==null?T.shadowSide:m[T.side],D.alphaMap=T.alphaMap,D.alphaTest=T.alphaToCoverage===!0?.5:T.alphaTest,D.map=T.map,D.clipShadows=T.clipShadows,D.clippingPlanes=T.clippingPlanes,D.clipIntersection=T.clipIntersection,D.displacementMap=T.displacementMap,D.displacementScale=T.displacementScale,D.displacementBias=T.displacementBias,D.wireframeLinewidth=T.wireframeLinewidth,D.linewidth=T.linewidth,F.isPointLight===!0&&D.isMeshDistanceMaterial===!0){const z=t.properties.get(D);z.light=F}return D}function P(A,T,F,k,D){if(A.visible===!1)return;if(A.layers.test(T.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&D===Cu)&&(!A.frustumCulled||r.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(F.matrixWorldInverse,A.matrixWorld);const X=e.update(A),L=A.material;if(Array.isArray(L)){const ne=X.groups;for(let ie=0,ee=ne.length;ie<ee;ie++){const ue=ne[ie],le=L[ue.materialIndex];if(le&&le.visible){const oe=C(A,le,k,D);A.onBeforeShadow(t,A,T,F,X,oe,ue),t.renderBufferDirect(F,null,X,oe,A,ue),A.onAfterShadow(t,A,T,F,X,oe,ue)}}}else if(L.visible){const ne=C(A,L,k,D);A.onBeforeShadow(t,A,T,F,X,ne,null),t.renderBufferDirect(F,null,X,ne,A,null),A.onAfterShadow(t,A,T,F,X,ne,null)}}const z=A.children;for(let X=0,L=z.length;X<L;X++)P(z[X],T,F,k,D)}function N(A){A.target.removeEventListener("dispose",N);for(const F in d){const k=d[F],D=A.target.uuid;D in k&&(k[D].dispose(),delete k[D])}}}const W1e={[iF]:sF,[oF]:dF,[lF]:uF,[jx]:cF,[sF]:iF,[dF]:oF,[uF]:lF,[cF]:jx};function K1e(t,e){function n(){let te=!1;const Ie=new ui;let be=null;const $e=new ui(0,0,0,0);return{setMask:function(He){be!==He&&!te&&(t.colorMask(He,He,He,He),be=He)},setLocked:function(He){te=He},setClear:function(He,ge,Pe,qe,Ze){Ze===!0&&(He*=qe,ge*=qe,Pe*=qe),Ie.set(He,ge,Pe,qe),$e.equals(Ie)===!1&&(t.clearColor(He,ge,Pe,qe),$e.copy(Ie))},reset:function(){te=!1,be=null,$e.set(-1,0,0,0)}}}function r(){let te=!1,Ie=!1,be=null,$e=null,He=null;return{setReversed:function(ge){if(Ie!==ge){const Pe=e.get("EXT_clip_control");ge?Pe.clipControlEXT(Pe.LOWER_LEFT_EXT,Pe.ZERO_TO_ONE_EXT):Pe.clipControlEXT(Pe.LOWER_LEFT_EXT,Pe.NEGATIVE_ONE_TO_ONE_EXT),Ie=ge;const qe=He;He=null,this.setClear(qe)}},getReversed:function(){return Ie},setTest:function(ge){ge?Y(t.DEPTH_TEST):E(t.DEPTH_TEST)},setMask:function(ge){be!==ge&&!te&&(t.depthMask(ge),be=ge)},setFunc:function(ge){if(Ie&&(ge=W1e[ge]),$e!==ge){switch(ge){case iF:t.depthFunc(t.NEVER);break;case sF:t.depthFunc(t.ALWAYS);break;case oF:t.depthFunc(t.LESS);break;case jx:t.depthFunc(t.LEQUAL);break;case lF:t.depthFunc(t.EQUAL);break;case cF:t.depthFunc(t.GEQUAL);break;case dF:t.depthFunc(t.GREATER);break;case uF:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}$e=ge}},setLocked:function(ge){te=ge},setClear:function(ge){He!==ge&&(Ie&&(ge=1-ge),t.clearDepth(ge),He=ge)},reset:function(){te=!1,be=null,$e=null,He=null,Ie=!1}}}function i(){let te=!1,Ie=null,be=null,$e=null,He=null,ge=null,Pe=null,qe=null,Ze=null;return{setTest:function(ut){te||(ut?Y(t.STENCIL_TEST):E(t.STENCIL_TEST))},setMask:function(ut){Ie!==ut&&!te&&(t.stencilMask(ut),Ie=ut)},setFunc:function(ut,vt,wt){(be!==ut||$e!==vt||He!==wt)&&(t.stencilFunc(ut,vt,wt),be=ut,$e=vt,He=wt)},setOp:function(ut,vt,wt){(ge!==ut||Pe!==vt||qe!==wt)&&(t.stencilOp(ut,vt,wt),ge=ut,Pe=vt,qe=wt)},setLocked:function(ut){te=ut},setClear:function(ut){Ze!==ut&&(t.clearStencil(ut),Ze=ut)},reset:function(){te=!1,Ie=null,be=null,$e=null,He=null,ge=null,Pe=null,qe=null,Ze=null}}}const s=new n,o=new r,l=new i,c=new WeakMap,d=new WeakMap;let u={},m={},p=new WeakMap,f=[],x=null,v=!1,g=null,b=null,_=null,C=null,P=null,N=null,A=null,T=new lr(0,0,0),F=0,k=!1,D=null,H=null,z=null,X=null,L=null;const ne=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let ie=!1,ee=0;const ue=t.getParameter(t.VERSION);ue.indexOf("WebGL")!==-1?(ee=parseFloat(/^WebGL (\d)/.exec(ue)[1]),ie=ee>=1):ue.indexOf("OpenGL ES")!==-1&&(ee=parseFloat(/^OpenGL ES (\d)/.exec(ue)[1]),ie=ee>=2);let le=null,oe={};const W=t.getParameter(t.SCISSOR_BOX),re=t.getParameter(t.VIEWPORT),ce=new ui().fromArray(W),xe=new ui().fromArray(re);function Ne(te,Ie,be,$e){const He=new Uint8Array(4),ge=t.createTexture();t.bindTexture(te,ge),t.texParameteri(te,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(te,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Pe=0;Pe<be;Pe++)te===t.TEXTURE_3D||te===t.TEXTURE_2D_ARRAY?t.texImage3D(Ie,0,t.RGBA,1,1,$e,0,t.RGBA,t.UNSIGNED_BYTE,He):t.texImage2D(Ie+Pe,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,He);return ge}const $={};$[t.TEXTURE_2D]=Ne(t.TEXTURE_2D,t.TEXTURE_2D,1),$[t.TEXTURE_CUBE_MAP]=Ne(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),$[t.TEXTURE_2D_ARRAY]=Ne(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),$[t.TEXTURE_3D]=Ne(t.TEXTURE_3D,t.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),l.setClear(0),Y(t.DEPTH_TEST),o.setFunc(jx),Q(!1),G(DH),Y(t.CULL_FACE),I(Xu);function Y(te){u[te]!==!0&&(t.enable(te),u[te]=!0)}function E(te){u[te]!==!1&&(t.disable(te),u[te]=!1)}function j(te,Ie){return m[te]!==Ie?(t.bindFramebuffer(te,Ie),m[te]=Ie,te===t.DRAW_FRAMEBUFFER&&(m[t.FRAMEBUFFER]=Ie),te===t.FRAMEBUFFER&&(m[t.DRAW_FRAMEBUFFER]=Ie),!0):!1}function O(te,Ie){let be=f,$e=!1;if(te){be=p.get(Ie),be===void 0&&(be=[],p.set(Ie,be));const He=te.textures;if(be.length!==He.length||be[0]!==t.COLOR_ATTACHMENT0){for(let ge=0,Pe=He.length;ge<Pe;ge++)be[ge]=t.COLOR_ATTACHMENT0+ge;be.length=He.length,$e=!0}}else be[0]!==t.BACK&&(be[0]=t.BACK,$e=!0);$e&&t.drawBuffers(be)}function K(te){return x!==te?(t.useProgram(te),x=te,!0):!1}const B={[mf]:t.FUNC_ADD,[$ye]:t.FUNC_SUBTRACT,[Vye]:t.FUNC_REVERSE_SUBTRACT};B[Gye]=t.MIN,B[Wye]=t.MAX;const he={[Kye]:t.ZERO,[Xye]:t.ONE,[Yye]:t.SRC_COLOR,[rF]:t.SRC_ALPHA,[nve]:t.SRC_ALPHA_SATURATE,[eve]:t.DST_COLOR,[Zye]:t.DST_ALPHA,[Qye]:t.ONE_MINUS_SRC_COLOR,[aF]:t.ONE_MINUS_SRC_ALPHA,[tve]:t.ONE_MINUS_DST_COLOR,[Jye]:t.ONE_MINUS_DST_ALPHA,[rve]:t.CONSTANT_COLOR,[ave]:t.ONE_MINUS_CONSTANT_COLOR,[ive]:t.CONSTANT_ALPHA,[sve]:t.ONE_MINUS_CONSTANT_ALPHA};function I(te,Ie,be,$e,He,ge,Pe,qe,Ze,ut){if(te===Xu){v===!0&&(E(t.BLEND),v=!1);return}if(v===!1&&(Y(t.BLEND),v=!0),te!==qye){if(te!==g||ut!==k){if((b!==mf||P!==mf)&&(t.blendEquation(t.FUNC_ADD),b=mf,P=mf),ut)switch(te){case hx:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FH:t.blendFunc(t.ONE,t.ONE);break;case RH:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case LH:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:ni("WebGLState: Invalid blending: ",te);break}else switch(te){case hx:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case FH:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case RH:ni("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case LH:ni("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ni("WebGLState: Invalid blending: ",te);break}_=null,C=null,N=null,A=null,T.set(0,0,0),F=0,g=te,k=ut}return}He=He||Ie,ge=ge||be,Pe=Pe||$e,(Ie!==b||He!==P)&&(t.blendEquationSeparate(B[Ie],B[He]),b=Ie,P=He),(be!==_||$e!==C||ge!==N||Pe!==A)&&(t.blendFuncSeparate(he[be],he[$e],he[ge],he[Pe]),_=be,C=$e,N=ge,A=Pe),(qe.equals(T)===!1||Ze!==F)&&(t.blendColor(qe.r,qe.g,qe.b,Ze),T.copy(qe),F=Ze),g=te,k=!1}function V(te,Ie){te.side===bd?E(t.CULL_FACE):Y(t.CULL_FACE);let be=te.side===Ao;Ie&&(be=!be),Q(be),te.blending===hx&&te.transparent===!1?I(Xu):I(te.blending,te.blendEquation,te.blendSrc,te.blendDst,te.blendEquationAlpha,te.blendSrcAlpha,te.blendDstAlpha,te.blendColor,te.blendAlpha,te.premultipliedAlpha),o.setFunc(te.depthFunc),o.setTest(te.depthTest),o.setMask(te.depthWrite),s.setMask(te.colorWrite);const $e=te.stencilWrite;l.setTest($e),$e&&(l.setMask(te.stencilWriteMask),l.setFunc(te.stencilFunc,te.stencilRef,te.stencilFuncMask),l.setOp(te.stencilFail,te.stencilZFail,te.stencilZPass)),se(te.polygonOffset,te.polygonOffsetFactor,te.polygonOffsetUnits),te.alphaToCoverage===!0?Y(t.SAMPLE_ALPHA_TO_COVERAGE):E(t.SAMPLE_ALPHA_TO_COVERAGE)}function Q(te){D!==te&&(te?t.frontFace(t.CW):t.frontFace(t.CCW),D=te)}function G(te){te!==Uye?(Y(t.CULL_FACE),te!==H&&(te===DH?t.cullFace(t.BACK):te===Bye?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):E(t.CULL_FACE),H=te}function J(te){te!==z&&(ie&&t.lineWidth(te),z=te)}function se(te,Ie,be){te?(Y(t.POLYGON_OFFSET_FILL),(X!==Ie||L!==be)&&(t.polygonOffset(Ie,be),X=Ie,L=be)):E(t.POLYGON_OFFSET_FILL)}function fe(te){te?Y(t.SCISSOR_TEST):E(t.SCISSOR_TEST)}function pe(te){te===void 0&&(te=t.TEXTURE0+ne-1),le!==te&&(t.activeTexture(te),le=te)}function de(te,Ie,be){be===void 0&&(le===null?be=t.TEXTURE0+ne-1:be=le);let $e=oe[be];$e===void 0&&($e={type:void 0,texture:void 0},oe[be]=$e),($e.type!==te||$e.texture!==Ie)&&(le!==be&&(t.activeTexture(be),le=be),t.bindTexture(te,Ie||$[te]),$e.type=te,$e.texture=Ie)}function U(){const te=oe[le];te!==void 0&&te.type!==void 0&&(t.bindTexture(te.type,null),te.type=void 0,te.texture=void 0)}function R(){try{t.compressedTexImage2D(...arguments)}catch(te){te("WebGLState:",te)}}function ae(){try{t.compressedTexImage3D(...arguments)}catch(te){te("WebGLState:",te)}}function _e(){try{t.texSubImage2D(...arguments)}catch(te){te("WebGLState:",te)}}function Se(){try{t.texSubImage3D(...arguments)}catch(te){te("WebGLState:",te)}}function ye(){try{t.compressedTexSubImage2D(...arguments)}catch(te){te("WebGLState:",te)}}function Ae(){try{t.compressedTexSubImage3D(...arguments)}catch(te){te("WebGLState:",te)}}function ve(){try{t.texStorage2D(...arguments)}catch(te){te("WebGLState:",te)}}function je(){try{t.texStorage3D(...arguments)}catch(te){te("WebGLState:",te)}}function Re(){try{t.texImage2D(...arguments)}catch(te){te("WebGLState:",te)}}function Ee(){try{t.texImage3D(...arguments)}catch(te){te("WebGLState:",te)}}function Te(te){ce.equals(te)===!1&&(t.scissor(te.x,te.y,te.z,te.w),ce.copy(te))}function Me(te){xe.equals(te)===!1&&(t.viewport(te.x,te.y,te.z,te.w),xe.copy(te))}function Be(te,Ie){let be=d.get(Ie);be===void 0&&(be=new WeakMap,d.set(Ie,be));let $e=be.get(te);$e===void 0&&($e=t.getUniformBlockIndex(Ie,te.name),be.set(te,$e))}function Ke(te,Ie){const $e=d.get(Ie).get(te);c.get(Ie)!==$e&&(t.uniformBlockBinding(Ie,$e,te.__bindingPointIndex),c.set(Ie,$e))}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),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),u={},le=null,oe={},m={},p=new WeakMap,f=[],x=null,v=!1,g=null,b=null,_=null,C=null,P=null,N=null,A=null,T=new lr(0,0,0),F=0,k=!1,D=null,H=null,z=null,X=null,L=null,ce.set(0,0,t.canvas.width,t.canvas.height),xe.set(0,0,t.canvas.width,t.canvas.height),s.reset(),o.reset(),l.reset()}return{buffers:{color:s,depth:o,stencil:l},enable:Y,disable:E,bindFramebuffer:j,drawBuffers:O,useProgram:K,setBlending:I,setMaterial:V,setFlipSided:Q,setCullFace:G,setLineWidth:J,setPolygonOffset:se,setScissorTest:fe,activeTexture:pe,bindTexture:de,unbindTexture:U,compressedTexImage2D:R,compressedTexImage3D:ae,texImage2D:Re,texImage3D:Ee,updateUBOMapping:Be,uniformBlockBinding:Ke,texStorage2D:ve,texStorage3D:je,texSubImage2D:_e,texSubImage3D:Se,compressedTexSubImage2D:ye,compressedTexSubImage3D:Ae,scissor:Te,viewport:Me,reset:tt}}function X1e(t,e,n,r,i,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),d=new ar,u=new WeakMap;let m;const p=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function x(U,R){return f?new OffscreenCanvas(U,R):gN("canvas")}function v(U,R,ae){let _e=1;const Se=de(U);if((Se.width>ae||Se.height>ae)&&(_e=ae/Math.max(Se.width,Se.height)),_e<1)if(typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&U instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&U instanceof ImageBitmap||typeof VideoFrame<"u"&&U instanceof VideoFrame){const ye=Math.floor(_e*Se.width),Ae=Math.floor(_e*Se.height);m===void 0&&(m=x(ye,Ae));const ve=R?x(ye,Ae):m;return ve.width=ye,ve.height=Ae,ve.getContext("2d").drawImage(U,0,0,ye,Ae),qn("WebGLRenderer: Texture has been resized from ("+Se.width+"x"+Se.height+") to ("+ye+"x"+Ae+")."),ve}else return"data"in U&&qn("WebGLRenderer: Image in DataTexture is too big ("+Se.width+"x"+Se.height+")."),U;return U}function g(U){return U.generateMipmaps}function b(U){t.generateMipmap(U)}function _(U){return U.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:U.isWebGL3DRenderTarget?t.TEXTURE_3D:U.isWebGLArrayRenderTarget||U.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function C(U,R,ae,_e,Se=!1){if(U!==null){if(t[U]!==void 0)return t[U];qn("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+U+"'")}let ye=R;if(R===t.RED&&(ae===t.FLOAT&&(ye=t.R32F),ae===t.HALF_FLOAT&&(ye=t.R16F),ae===t.UNSIGNED_BYTE&&(ye=t.R8)),R===t.RED_INTEGER&&(ae===t.UNSIGNED_BYTE&&(ye=t.R8UI),ae===t.UNSIGNED_SHORT&&(ye=t.R16UI),ae===t.UNSIGNED_INT&&(ye=t.R32UI),ae===t.BYTE&&(ye=t.R8I),ae===t.SHORT&&(ye=t.R16I),ae===t.INT&&(ye=t.R32I)),R===t.RG&&(ae===t.FLOAT&&(ye=t.RG32F),ae===t.HALF_FLOAT&&(ye=t.RG16F),ae===t.UNSIGNED_BYTE&&(ye=t.RG8)),R===t.RG_INTEGER&&(ae===t.UNSIGNED_BYTE&&(ye=t.RG8UI),ae===t.UNSIGNED_SHORT&&(ye=t.RG16UI),ae===t.UNSIGNED_INT&&(ye=t.RG32UI),ae===t.BYTE&&(ye=t.RG8I),ae===t.SHORT&&(ye=t.RG16I),ae===t.INT&&(ye=t.RG32I)),R===t.RGB_INTEGER&&(ae===t.UNSIGNED_BYTE&&(ye=t.RGB8UI),ae===t.UNSIGNED_SHORT&&(ye=t.RGB16UI),ae===t.UNSIGNED_INT&&(ye=t.RGB32UI),ae===t.BYTE&&(ye=t.RGB8I),ae===t.SHORT&&(ye=t.RGB16I),ae===t.INT&&(ye=t.RGB32I)),R===t.RGBA_INTEGER&&(ae===t.UNSIGNED_BYTE&&(ye=t.RGBA8UI),ae===t.UNSIGNED_SHORT&&(ye=t.RGBA16UI),ae===t.UNSIGNED_INT&&(ye=t.RGBA32UI),ae===t.BYTE&&(ye=t.RGBA8I),ae===t.SHORT&&(ye=t.RGBA16I),ae===t.INT&&(ye=t.RGBA32I)),R===t.RGB&&(ae===t.UNSIGNED_INT_5_9_9_9_REV&&(ye=t.RGB9_E5),ae===t.UNSIGNED_INT_10F_11F_11F_REV&&(ye=t.R11F_G11F_B10F)),R===t.RGBA){const Ae=Se?pN:Tr.getTransfer(_e);ae===t.FLOAT&&(ye=t.RGBA32F),ae===t.HALF_FLOAT&&(ye=t.RGBA16F),ae===t.UNSIGNED_BYTE&&(ye=Ae===Vr?t.SRGB8_ALPHA8:t.RGBA8),ae===t.UNSIGNED_SHORT_4_4_4_4&&(ye=t.RGBA4),ae===t.UNSIGNED_SHORT_5_5_5_1&&(ye=t.RGB5_A1)}return(ye===t.R16F||ye===t.R32F||ye===t.RG16F||ye===t.RG32F||ye===t.RGBA16F||ye===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function P(U,R){let ae;return U?R===null||R===Jf||R===V0?ae=t.DEPTH24_STENCIL8:R===Hu?ae=t.DEPTH32F_STENCIL8:R===$0&&(ae=t.DEPTH24_STENCIL8,qn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===Jf||R===V0?ae=t.DEPTH_COMPONENT24:R===Hu?ae=t.DEPTH_COMPONENT32F:R===$0&&(ae=t.DEPTH_COMPONENT16),ae}function N(U,R){return g(U)===!0||U.isFramebufferTexture&&U.minFilter!==il&&U.minFilter!==Xl?Math.log2(Math.max(R.width,R.height))+1:U.mipmaps!==void 0&&U.mipmaps.length>0?U.mipmaps.length:U.isCompressedTexture&&Array.isArray(U.image)?R.mipmaps.length:1}function A(U){const R=U.target;R.removeEventListener("dispose",A),F(R),R.isVideoTexture&&u.delete(R)}function T(U){const R=U.target;R.removeEventListener("dispose",T),D(R)}function F(U){const R=r.get(U);if(R.__webglInit===void 0)return;const ae=U.source,_e=p.get(ae);if(_e){const Se=_e[R.__cacheKey];Se.usedTimes--,Se.usedTimes===0&&k(U),Object.keys(_e).length===0&&p.delete(ae)}r.remove(U)}function k(U){const R=r.get(U);t.deleteTexture(R.__webglTexture);const ae=U.source,_e=p.get(ae);delete _e[R.__cacheKey],o.memory.textures--}function D(U){const R=r.get(U);if(U.depthTexture&&(U.depthTexture.dispose(),r.remove(U.depthTexture)),U.isWebGLCubeRenderTarget)for(let _e=0;_e<6;_e++){if(Array.isArray(R.__webglFramebuffer[_e]))for(let Se=0;Se<R.__webglFramebuffer[_e].length;Se++)t.deleteFramebuffer(R.__webglFramebuffer[_e][Se]);else t.deleteFramebuffer(R.__webglFramebuffer[_e]);R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer[_e])}else{if(Array.isArray(R.__webglFramebuffer))for(let _e=0;_e<R.__webglFramebuffer.length;_e++)t.deleteFramebuffer(R.__webglFramebuffer[_e]);else t.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&t.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let _e=0;_e<R.__webglColorRenderbuffer.length;_e++)R.__webglColorRenderbuffer[_e]&&t.deleteRenderbuffer(R.__webglColorRenderbuffer[_e]);R.__webglDepthRenderbuffer&&t.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const ae=U.textures;for(let _e=0,Se=ae.length;_e<Se;_e++){const ye=r.get(ae[_e]);ye.__webglTexture&&(t.deleteTexture(ye.__webglTexture),o.memory.textures--),r.remove(ae[_e])}r.remove(U)}let H=0;function z(){H=0}function X(){const U=H;return U>=i.maxTextures&&qn("WebGLTextures: Trying to use "+U+" texture units while this GPU supports only "+i.maxTextures),H+=1,U}function L(U){const R=[];return R.push(U.wrapS),R.push(U.wrapT),R.push(U.wrapR||0),R.push(U.magFilter),R.push(U.minFilter),R.push(U.anisotropy),R.push(U.internalFormat),R.push(U.format),R.push(U.type),R.push(U.generateMipmaps),R.push(U.premultiplyAlpha),R.push(U.flipY),R.push(U.unpackAlignment),R.push(U.colorSpace),R.join()}function ne(U,R){const ae=r.get(U);if(U.isVideoTexture&&fe(U),U.isRenderTargetTexture===!1&&U.isExternalTexture!==!0&&U.version>0&&ae.__version!==U.version){const _e=U.image;if(_e===null)qn("WebGLRenderer: Texture marked for update but no image data found.");else if(_e.complete===!1)qn("WebGLRenderer: Texture marked for update but image is incomplete");else{$(ae,U,R);return}}else U.isExternalTexture&&(ae.__webglTexture=U.sourceTexture?U.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,ae.__webglTexture,t.TEXTURE0+R)}function ie(U,R){const ae=r.get(U);if(U.isRenderTargetTexture===!1&&U.version>0&&ae.__version!==U.version){$(ae,U,R);return}else U.isExternalTexture&&(ae.__webglTexture=U.sourceTexture?U.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,ae.__webglTexture,t.TEXTURE0+R)}function ee(U,R){const ae=r.get(U);if(U.isRenderTargetTexture===!1&&U.version>0&&ae.__version!==U.version){$(ae,U,R);return}n.bindTexture(t.TEXTURE_3D,ae.__webglTexture,t.TEXTURE0+R)}function ue(U,R){const ae=r.get(U);if(U.version>0&&ae.__version!==U.version){Y(ae,U,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ae.__webglTexture,t.TEXTURE0+R)}const le={[pF]:t.REPEAT,[Bu]:t.CLAMP_TO_EDGE,[fF]:t.MIRRORED_REPEAT},oe={[il]:t.NEAREST,[gve]:t.NEAREST_MIPMAP_NEAREST,[R_]:t.NEAREST_MIPMAP_LINEAR,[Xl]:t.LINEAR,[vM]:t.LINEAR_MIPMAP_NEAREST,[yf]:t.LINEAR_MIPMAP_LINEAR},W={[vve]:t.NEVER,[Cve]:t.ALWAYS,[wve]:t.LESS,[lZ]:t.LEQUAL,[Sve]:t.EQUAL,[Nve]:t.GEQUAL,[_ve]:t.GREATER,[kve]:t.NOTEQUAL};function re(U,R){if(R.type===Hu&&e.has("OES_texture_float_linear")===!1&&(R.magFilter===Xl||R.magFilter===vM||R.magFilter===R_||R.magFilter===yf||R.minFilter===Xl||R.minFilter===vM||R.minFilter===R_||R.minFilter===yf)&&qn("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(U,t.TEXTURE_WRAP_S,le[R.wrapS]),t.texParameteri(U,t.TEXTURE_WRAP_T,le[R.wrapT]),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,le[R.wrapR]),t.texParameteri(U,t.TEXTURE_MAG_FILTER,oe[R.magFilter]),t.texParameteri(U,t.TEXTURE_MIN_FILTER,oe[R.minFilter]),R.compareFunction&&(t.texParameteri(U,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(U,t.TEXTURE_COMPARE_FUNC,W[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===il||R.minFilter!==R_&&R.minFilter!==yf||R.type===Hu&&e.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||r.get(R).__currentAnisotropy){const ae=e.get("EXT_texture_filter_anisotropic");t.texParameterf(U,ae.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy}}}function ce(U,R){let ae=!1;U.__webglInit===void 0&&(U.__webglInit=!0,R.addEventListener("dispose",A));const _e=R.source;let Se=p.get(_e);Se===void 0&&(Se={},p.set(_e,Se));const ye=L(R);if(ye!==U.__cacheKey){Se[ye]===void 0&&(Se[ye]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,ae=!0),Se[ye].usedTimes++;const Ae=Se[U.__cacheKey];Ae!==void 0&&(Se[U.__cacheKey].usedTimes--,Ae.usedTimes===0&&k(R)),U.__cacheKey=ye,U.__webglTexture=Se[ye].texture}return ae}function xe(U,R,ae){return Math.floor(Math.floor(U/ae)/R)}function Ne(U,R,ae,_e){const ye=U.updateRanges;if(ye.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,R.width,R.height,ae,_e,R.data);else{ye.sort((Ee,Te)=>Ee.start-Te.start);let Ae=0;for(let Ee=1;Ee<ye.length;Ee++){const Te=ye[Ae],Me=ye[Ee],Be=Te.start+Te.count,Ke=xe(Me.start,R.width,4),tt=xe(Te.start,R.width,4);Me.start<=Be+1&&Ke===tt&&xe(Me.start+Me.count-1,R.width,4)===Ke?Te.count=Math.max(Te.count,Me.start+Me.count-Te.start):(++Ae,ye[Ae]=Me)}ye.length=Ae+1;const ve=t.getParameter(t.UNPACK_ROW_LENGTH),je=t.getParameter(t.UNPACK_SKIP_PIXELS),Re=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,R.width);for(let Ee=0,Te=ye.length;Ee<Te;Ee++){const Me=ye[Ee],Be=Math.floor(Me.start/4),Ke=Math.ceil(Me.count/4),tt=Be%R.width,te=Math.floor(Be/R.width),Ie=Ke,be=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,tt),t.pixelStorei(t.UNPACK_SKIP_ROWS,te),n.texSubImage2D(t.TEXTURE_2D,0,tt,te,Ie,be,ae,_e,R.data)}U.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,ve),t.pixelStorei(t.UNPACK_SKIP_PIXELS,je),t.pixelStorei(t.UNPACK_SKIP_ROWS,Re)}}function $(U,R,ae){let _e=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(_e=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(_e=t.TEXTURE_3D);const Se=ce(U,R),ye=R.source;n.bindTexture(_e,U.__webglTexture,t.TEXTURE0+ae);const Ae=r.get(ye);if(ye.version!==Ae.__version||Se===!0){n.activeTexture(t.TEXTURE0+ae);const ve=Tr.getPrimaries(Tr.workingColorSpace),je=R.colorSpace===_h?null:Tr.getPrimaries(R.colorSpace),Re=R.colorSpace===_h||ve===je?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,Re);let Ee=v(R.image,!1,i.maxTextureSize);Ee=pe(R,Ee);const Te=s.convert(R.format,R.colorSpace),Me=s.convert(R.type);let Be=C(R.internalFormat,Te,Me,R.colorSpace,R.isVideoTexture);re(_e,R);let Ke;const tt=R.mipmaps,te=R.isVideoTexture!==!0,Ie=Ae.__version===void 0||Se===!0,be=ye.dataReady,$e=N(R,Ee);if(R.isDepthTexture)Be=P(R.format===W0,R.type),Ie&&(te?n.texStorage2D(t.TEXTURE_2D,1,Be,Ee.width,Ee.height):n.texImage2D(t.TEXTURE_2D,0,Be,Ee.width,Ee.height,0,Te,Me,null));else if(R.isDataTexture)if(tt.length>0){te&&Ie&&n.texStorage2D(t.TEXTURE_2D,$e,Be,tt[0].width,tt[0].height);for(let He=0,ge=tt.length;He<ge;He++)Ke=tt[He],te?be&&n.texSubImage2D(t.TEXTURE_2D,He,0,0,Ke.width,Ke.height,Te,Me,Ke.data):n.texImage2D(t.TEXTURE_2D,He,Be,Ke.width,Ke.height,0,Te,Me,Ke.data);R.generateMipmaps=!1}else te?(Ie&&n.texStorage2D(t.TEXTURE_2D,$e,Be,Ee.width,Ee.height),be&&Ne(R,Ee,Te,Me)):n.texImage2D(t.TEXTURE_2D,0,Be,Ee.width,Ee.height,0,Te,Me,Ee.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){te&&Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,$e,Be,tt[0].width,tt[0].height,Ee.depth);for(let He=0,ge=tt.length;He<ge;He++)if(Ke=tt[He],R.format!==Rc)if(Te!==null)if(te){if(be)if(R.layerUpdates.size>0){const Pe=h6(Ke.width,Ke.height,R.format,R.type);for(const qe of R.layerUpdates){const Ze=Ke.data.subarray(qe*Pe/Ke.data.BYTES_PER_ELEMENT,(qe+1)*Pe/Ke.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,He,0,0,qe,Ke.width,Ke.height,1,Te,Ze)}R.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,He,0,0,0,Ke.width,Ke.height,Ee.depth,Te,Ke.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,He,Be,Ke.width,Ke.height,Ee.depth,0,Ke.data,0,0);else qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else te?be&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,He,0,0,0,Ke.width,Ke.height,Ee.depth,Te,Me,Ke.data):n.texImage3D(t.TEXTURE_2D_ARRAY,He,Be,Ke.width,Ke.height,Ee.depth,0,Te,Me,Ke.data)}else{te&&Ie&&n.texStorage2D(t.TEXTURE_2D,$e,Be,tt[0].width,tt[0].height);for(let He=0,ge=tt.length;He<ge;He++)Ke=tt[He],R.format!==Rc?Te!==null?te?be&&n.compressedTexSubImage2D(t.TEXTURE_2D,He,0,0,Ke.width,Ke.height,Te,Ke.data):n.compressedTexImage2D(t.TEXTURE_2D,He,Be,Ke.width,Ke.height,0,Ke.data):qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):te?be&&n.texSubImage2D(t.TEXTURE_2D,He,0,0,Ke.width,Ke.height,Te,Me,Ke.data):n.texImage2D(t.TEXTURE_2D,He,Be,Ke.width,Ke.height,0,Te,Me,Ke.data)}else if(R.isDataArrayTexture)if(te){if(Ie&&n.texStorage3D(t.TEXTURE_2D_ARRAY,$e,Be,Ee.width,Ee.height,Ee.depth),be)if(R.layerUpdates.size>0){const He=h6(Ee.width,Ee.height,R.format,R.type);for(const ge of R.layerUpdates){const Pe=Ee.data.subarray(ge*He/Ee.data.BYTES_PER_ELEMENT,(ge+1)*He/Ee.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,ge,Ee.width,Ee.height,1,Te,Me,Pe)}R.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Ee.width,Ee.height,Ee.depth,Te,Me,Ee.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,Be,Ee.width,Ee.height,Ee.depth,0,Te,Me,Ee.data);else if(R.isData3DTexture)te?(Ie&&n.texStorage3D(t.TEXTURE_3D,$e,Be,Ee.width,Ee.height,Ee.depth),be&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Ee.width,Ee.height,Ee.depth,Te,Me,Ee.data)):n.texImage3D(t.TEXTURE_3D,0,Be,Ee.width,Ee.height,Ee.depth,0,Te,Me,Ee.data);else if(R.isFramebufferTexture){if(Ie)if(te)n.texStorage2D(t.TEXTURE_2D,$e,Be,Ee.width,Ee.height);else{let He=Ee.width,ge=Ee.height;for(let Pe=0;Pe<$e;Pe++)n.texImage2D(t.TEXTURE_2D,Pe,Be,He,ge,0,Te,Me,null),He>>=1,ge>>=1}}else if(tt.length>0){if(te&&Ie){const He=de(tt[0]);n.texStorage2D(t.TEXTURE_2D,$e,Be,He.width,He.height)}for(let He=0,ge=tt.length;He<ge;He++)Ke=tt[He],te?be&&n.texSubImage2D(t.TEXTURE_2D,He,0,0,Te,Me,Ke):n.texImage2D(t.TEXTURE_2D,He,Be,Te,Me,Ke);R.generateMipmaps=!1}else if(te){if(Ie){const He=de(Ee);n.texStorage2D(t.TEXTURE_2D,$e,Be,He.width,He.height)}be&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,Te,Me,Ee)}else n.texImage2D(t.TEXTURE_2D,0,Be,Te,Me,Ee);g(R)&&b(_e),Ae.__version=ye.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function Y(U,R,ae){if(R.image.length!==6)return;const _e=ce(U,R),Se=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,U.__webglTexture,t.TEXTURE0+ae);const ye=r.get(Se);if(Se.version!==ye.__version||_e===!0){n.activeTexture(t.TEXTURE0+ae);const Ae=Tr.getPrimaries(Tr.workingColorSpace),ve=R.colorSpace===_h?null:Tr.getPrimaries(R.colorSpace),je=R.colorSpace===_h||Ae===ve?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,je);const Re=R.isCompressedTexture||R.image[0].isCompressedTexture,Ee=R.image[0]&&R.image[0].isDataTexture,Te=[];for(let ge=0;ge<6;ge++)!Re&&!Ee?Te[ge]=v(R.image[ge],!0,i.maxCubemapSize):Te[ge]=Ee?R.image[ge].image:R.image[ge],Te[ge]=pe(R,Te[ge]);const Me=Te[0],Be=s.convert(R.format,R.colorSpace),Ke=s.convert(R.type),tt=C(R.internalFormat,Be,Ke,R.colorSpace),te=R.isVideoTexture!==!0,Ie=ye.__version===void 0||_e===!0,be=Se.dataReady;let $e=N(R,Me);re(t.TEXTURE_CUBE_MAP,R);let He;if(Re){te&&Ie&&n.texStorage2D(t.TEXTURE_CUBE_MAP,$e,tt,Me.width,Me.height);for(let ge=0;ge<6;ge++){He=Te[ge].mipmaps;for(let Pe=0;Pe<He.length;Pe++){const qe=He[Pe];R.format!==Rc?Be!==null?te?be&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,0,0,qe.width,qe.height,Be,qe.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,tt,qe.width,qe.height,0,qe.data):qn("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):te?be&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,0,0,qe.width,qe.height,Be,Ke,qe.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,tt,qe.width,qe.height,0,Be,Ke,qe.data)}}}else{if(He=R.mipmaps,te&&Ie){He.length>0&&$e++;const ge=de(Te[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,$e,tt,ge.width,ge.height)}for(let ge=0;ge<6;ge++)if(Ee){te?be&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,0,0,Te[ge].width,Te[ge].height,Be,Ke,Te[ge].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,tt,Te[ge].width,Te[ge].height,0,Be,Ke,Te[ge].data);for(let Pe=0;Pe<He.length;Pe++){const Ze=He[Pe].image[ge].image;te?be&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,0,0,Ze.width,Ze.height,Be,Ke,Ze.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,tt,Ze.width,Ze.height,0,Be,Ke,Ze.data)}}else{te?be&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,0,0,Be,Ke,Te[ge]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,tt,Be,Ke,Te[ge]);for(let Pe=0;Pe<He.length;Pe++){const qe=He[Pe];te?be&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,0,0,Be,Ke,qe.image[ge]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,tt,Be,Ke,qe.image[ge])}}}g(R)&&b(t.TEXTURE_CUBE_MAP),ye.__version=Se.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function E(U,R,ae,_e,Se,ye){const Ae=s.convert(ae.format,ae.colorSpace),ve=s.convert(ae.type),je=C(ae.internalFormat,Ae,ve,ae.colorSpace),Re=r.get(R),Ee=r.get(ae);if(Ee.__renderTarget=R,!Re.__hasExternalTextures){const Te=Math.max(1,R.width>>ye),Me=Math.max(1,R.height>>ye);Se===t.TEXTURE_3D||Se===t.TEXTURE_2D_ARRAY?n.texImage3D(Se,ye,je,Te,Me,R.depth,0,Ae,ve,null):n.texImage2D(Se,ye,je,Te,Me,0,Ae,ve,null)}n.bindFramebuffer(t.FRAMEBUFFER,U),se(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,_e,Se,Ee.__webglTexture,0,J(R)):(Se===t.TEXTURE_2D||Se>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&Se<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,_e,Se,Ee.__webglTexture,ye),n.bindFramebuffer(t.FRAMEBUFFER,null)}function j(U,R,ae){if(t.bindRenderbuffer(t.RENDERBUFFER,U),R.depthBuffer){const _e=R.depthTexture,Se=_e&&_e.isDepthTexture?_e.type:null,ye=P(R.stencilBuffer,Se),Ae=R.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ve=J(R);se(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ve,ye,R.width,R.height):ae?t.renderbufferStorageMultisample(t.RENDERBUFFER,ve,ye,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,ye,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,Ae,t.RENDERBUFFER,U)}else{const _e=R.textures;for(let Se=0;Se<_e.length;Se++){const ye=_e[Se],Ae=s.convert(ye.format,ye.colorSpace),ve=s.convert(ye.type),je=C(ye.internalFormat,Ae,ve,ye.colorSpace),Re=J(R);ae&&se(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Re,je,R.width,R.height):se(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Re,je,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,je,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function O(U,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,U),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const _e=r.get(R.depthTexture);_e.__renderTarget=R,(!_e.__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),ne(R.depthTexture,0);const Se=_e.__webglTexture,ye=J(R);if(R.depthTexture.format===G0)se(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,Se,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,Se,0);else if(R.depthTexture.format===W0)se(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,Se,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,Se,0);else throw new Error("Unknown depthTexture format")}function K(U){const R=r.get(U),ae=U.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==U.depthTexture){const _e=U.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),_e){const Se=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,_e.removeEventListener("dispose",Se)};_e.addEventListener("dispose",Se),R.__depthDisposeCallback=Se}R.__boundDepthTexture=_e}if(U.depthTexture&&!R.__autoAllocateDepthBuffer){if(ae)throw new Error("target.depthTexture not supported in Cube render targets");const _e=U.texture.mipmaps;_e&&_e.length>0?O(R.__webglFramebuffer[0],U):O(R.__webglFramebuffer,U)}else if(ae){R.__webglDepthbuffer=[];for(let _e=0;_e<6;_e++)if(n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[_e]),R.__webglDepthbuffer[_e]===void 0)R.__webglDepthbuffer[_e]=t.createRenderbuffer(),j(R.__webglDepthbuffer[_e],U,!1);else{const Se=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ye=R.__webglDepthbuffer[_e];t.bindRenderbuffer(t.RENDERBUFFER,ye),t.framebufferRenderbuffer(t.FRAMEBUFFER,Se,t.RENDERBUFFER,ye)}}else{const _e=U.texture.mipmaps;if(_e&&_e.length>0?n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=t.createRenderbuffer(),j(R.__webglDepthbuffer,U,!1);else{const Se=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ye=R.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,ye),t.framebufferRenderbuffer(t.FRAMEBUFFER,Se,t.RENDERBUFFER,ye)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function B(U,R,ae){const _e=r.get(U);R!==void 0&&E(_e.__webglFramebuffer,U,U.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ae!==void 0&&K(U)}function he(U){const R=U.texture,ae=r.get(U),_e=r.get(R);U.addEventListener("dispose",T);const Se=U.textures,ye=U.isWebGLCubeRenderTarget===!0,Ae=Se.length>1;if(Ae||(_e.__webglTexture===void 0&&(_e.__webglTexture=t.createTexture()),_e.__version=R.version,o.memory.textures++),ye){ae.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(R.mipmaps&&R.mipmaps.length>0){ae.__webglFramebuffer[ve]=[];for(let je=0;je<R.mipmaps.length;je++)ae.__webglFramebuffer[ve][je]=t.createFramebuffer()}else ae.__webglFramebuffer[ve]=t.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){ae.__webglFramebuffer=[];for(let ve=0;ve<R.mipmaps.length;ve++)ae.__webglFramebuffer[ve]=t.createFramebuffer()}else ae.__webglFramebuffer=t.createFramebuffer();if(Ae)for(let ve=0,je=Se.length;ve<je;ve++){const Re=r.get(Se[ve]);Re.__webglTexture===void 0&&(Re.__webglTexture=t.createTexture(),o.memory.textures++)}if(U.samples>0&&se(U)===!1){ae.__webglMultisampledFramebuffer=t.createFramebuffer(),ae.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ae.__webglMultisampledFramebuffer);for(let ve=0;ve<Se.length;ve++){const je=Se[ve];ae.__webglColorRenderbuffer[ve]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,ae.__webglColorRenderbuffer[ve]);const Re=s.convert(je.format,je.colorSpace),Ee=s.convert(je.type),Te=C(je.internalFormat,Re,Ee,je.colorSpace,U.isXRRenderTarget===!0),Me=J(U);t.renderbufferStorageMultisample(t.RENDERBUFFER,Me,Te,U.width,U.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+ve,t.RENDERBUFFER,ae.__webglColorRenderbuffer[ve])}t.bindRenderbuffer(t.RENDERBUFFER,null),U.depthBuffer&&(ae.__webglDepthRenderbuffer=t.createRenderbuffer(),j(ae.__webglDepthRenderbuffer,U,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(ye){n.bindTexture(t.TEXTURE_CUBE_MAP,_e.__webglTexture),re(t.TEXTURE_CUBE_MAP,R);for(let ve=0;ve<6;ve++)if(R.mipmaps&&R.mipmaps.length>0)for(let je=0;je<R.mipmaps.length;je++)E(ae.__webglFramebuffer[ve][je],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,je);else E(ae.__webglFramebuffer[ve],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);g(R)&&b(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(Ae){for(let ve=0,je=Se.length;ve<je;ve++){const Re=Se[ve],Ee=r.get(Re);let Te=t.TEXTURE_2D;(U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(Te=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(Te,Ee.__webglTexture),re(Te,Re),E(ae.__webglFramebuffer,U,Re,t.COLOR_ATTACHMENT0+ve,Te,0),g(Re)&&b(Te)}n.unbindTexture()}else{let ve=t.TEXTURE_2D;if((U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(ve=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(ve,_e.__webglTexture),re(ve,R),R.mipmaps&&R.mipmaps.length>0)for(let je=0;je<R.mipmaps.length;je++)E(ae.__webglFramebuffer[je],U,R,t.COLOR_ATTACHMENT0,ve,je);else E(ae.__webglFramebuffer,U,R,t.COLOR_ATTACHMENT0,ve,0);g(R)&&b(ve),n.unbindTexture()}U.depthBuffer&&K(U)}function I(U){const R=U.textures;for(let ae=0,_e=R.length;ae<_e;ae++){const Se=R[ae];if(g(Se)){const ye=_(U),Ae=r.get(Se).__webglTexture;n.bindTexture(ye,Ae),b(ye),n.unbindTexture()}}}const V=[],Q=[];function G(U){if(U.samples>0){if(se(U)===!1){const R=U.textures,ae=U.width,_e=U.height;let Se=t.COLOR_BUFFER_BIT;const ye=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Ae=r.get(U),ve=R.length>1;if(ve)for(let Re=0;Re<R.length;Re++)n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,Ae.__webglMultisampledFramebuffer);const je=U.texture.mipmaps;je&&je.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglFramebuffer);for(let Re=0;Re<R.length;Re++){if(U.resolveDepthBuffer&&(U.depthBuffer&&(Se|=t.DEPTH_BUFFER_BIT),U.stencilBuffer&&U.resolveStencilBuffer&&(Se|=t.STENCIL_BUFFER_BIT)),ve){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,Ae.__webglColorRenderbuffer[Re]);const Ee=r.get(R[Re]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Ee,0)}t.blitFramebuffer(0,0,ae,_e,0,0,ae,_e,Se,t.NEAREST),c===!0&&(V.length=0,Q.length=0,V.push(t.COLOR_ATTACHMENT0+Re),U.depthBuffer&&U.resolveDepthBuffer===!1&&(V.push(ye),Q.push(ye),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,Q)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,V))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),ve)for(let Re=0;Re<R.length;Re++){n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.RENDERBUFFER,Ae.__webglColorRenderbuffer[Re]);const Ee=r.get(R[Re]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,Ae.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.TEXTURE_2D,Ee,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ae.__webglMultisampledFramebuffer)}else if(U.depthBuffer&&U.resolveDepthBuffer===!1&&c){const R=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[R])}}}function J(U){return Math.min(i.maxSamples,U.samples)}function se(U){const R=r.get(U);return U.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function fe(U){const R=o.render.frame;u.get(U)!==R&&(u.set(U,R),U.update())}function pe(U,R){const ae=U.colorSpace,_e=U.format,Se=U.type;return U.isCompressedTexture===!0||U.isVideoTexture===!0||ae!==Dx&&ae!==_h&&(Tr.getTransfer(ae)===Vr?(_e!==Rc||Se!==Ed)&&qn("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ni("WebGLTextures: Unsupported texture color space:",ae)),R}function de(U){return typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement?(d.width=U.naturalWidth||U.width,d.height=U.naturalHeight||U.height):typeof VideoFrame<"u"&&U instanceof VideoFrame?(d.width=U.displayWidth,d.height=U.displayHeight):(d.width=U.width,d.height=U.height),d}this.allocateTextureUnit=X,this.resetTextureUnits=z,this.setTexture2D=ne,this.setTexture2DArray=ie,this.setTexture3D=ee,this.setTextureCube=ue,this.rebindTextures=B,this.setupRenderTarget=he,this.updateRenderTargetMipmap=I,this.updateMultisampleRenderTarget=G,this.setupDepthRenderbuffer=K,this.setupFrameBufferTexture=E,this.useMultisampledRTT=se}function Y1e(t,e){function n(r,i=_h){let s;const o=Tr.getTransfer(i);if(r===Ed)return t.UNSIGNED_BYTE;if(r===FO)return t.UNSIGNED_SHORT_4_4_4_4;if(r===RO)return t.UNSIGNED_SHORT_5_5_5_1;if(r===nZ)return t.UNSIGNED_INT_5_9_9_9_REV;if(r===rZ)return t.UNSIGNED_INT_10F_11F_11F_REV;if(r===eZ)return t.BYTE;if(r===tZ)return t.SHORT;if(r===$0)return t.UNSIGNED_SHORT;if(r===DO)return t.INT;if(r===Jf)return t.UNSIGNED_INT;if(r===Hu)return t.FLOAT;if(r===cy)return t.HALF_FLOAT;if(r===aZ)return t.ALPHA;if(r===iZ)return t.RGB;if(r===Rc)return t.RGBA;if(r===G0)return t.DEPTH_COMPONENT;if(r===W0)return t.DEPTH_STENCIL;if(r===sZ)return t.RED;if(r===LO)return t.RED_INTEGER;if(r===OO)return t.RG;if(r===IO)return t.RG_INTEGER;if(r===zO)return t.RGBA_INTEGER;if(r===Nk||r===Ck||r===Pk||r===Tk)if(o===Vr)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===Nk)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===Ck)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===Pk)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===Tk)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===Nk)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===Ck)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===Pk)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===Tk)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===gF||r===bF||r===xF||r===yF)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===gF)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===bF)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===xF)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===yF)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===vF||r===wF||r===SF)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===vF||r===wF)return o===Vr?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===SF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===_F||r===kF||r===NF||r===CF||r===PF||r===TF||r===AF||r===jF||r===MF||r===EF||r===DF||r===FF||r===RF||r===LF)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===_F)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===kF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===NF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===CF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===PF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===TF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===AF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===jF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===MF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===EF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===DF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===FF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===RF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===LF)return o===Vr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===OF||r===IF||r===zF)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===OF)return o===Vr?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===IF)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===zF)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===UF||r===BF||r===HF||r===qF)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===UF)return s.COMPRESSED_RED_RGTC1_EXT;if(r===BF)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===HF)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===qF)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===V0?t.UNSIGNED_INT_24_8:t[r]!==void 0?t[r]:null}return{convert:n}}const Q1e=`
- void main() {
- gl_Position = vec4( position, 1.0 );
- }`,Z1e=`
- uniform sampler2DArray depthColor;
- uniform float depthWidth;
- uniform float depthHeight;
- void main() {
- vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
- if ( coord.x >= 1.0 ) {
- gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
- } else {
- gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
- }
- }`;class J1e{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const r=new PZ(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 lm({vertexShader:Q1e,fragmentShader:Z1e,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new oc(new VO(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}let eke=class extends Sg{constructor(e,n){super();const r=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,x=null;const v=typeof XRWebGLBinding<"u",g=new J1e,b={},_=n.getContextAttributes();let C=null,P=null;const N=[],A=[],T=new ar;let F=null;const k=new ql;k.viewport=new ui;const D=new ql;D.viewport=new ui;const H=[k,D],z=new b0e;let X=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function($){let Y=N[$];return Y===void 0&&(Y=new HM,N[$]=Y),Y.getTargetRaySpace()},this.getControllerGrip=function($){let Y=N[$];return Y===void 0&&(Y=new HM,N[$]=Y),Y.getGripSpace()},this.getHand=function($){let Y=N[$];return Y===void 0&&(Y=new HM,N[$]=Y),Y.getHandSpace()};function ne($){const Y=A.indexOf($.inputSource);if(Y===-1)return;const E=N[Y];E!==void 0&&(E.update($.inputSource,$.frame,d||o),E.dispatchEvent({type:$.type,data:$.inputSource}))}function ie(){i.removeEventListener("select",ne),i.removeEventListener("selectstart",ne),i.removeEventListener("selectend",ne),i.removeEventListener("squeeze",ne),i.removeEventListener("squeezestart",ne),i.removeEventListener("squeezeend",ne),i.removeEventListener("end",ie),i.removeEventListener("inputsourceschange",ee);for(let $=0;$<N.length;$++){const Y=A[$];Y!==null&&(A[$]=null,N[$].disconnect(Y))}X=null,L=null,g.reset();for(const $ in b)delete b[$];e.setRenderTarget(C),f=null,p=null,m=null,i=null,P=null,Ne.stop(),r.isPresenting=!1,e.setPixelRatio(F),e.setSize(T.width,T.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function($){s=$,r.isPresenting===!0&&qn("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function($){l=$,r.isPresenting===!0&&qn("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||o},this.setReferenceSpace=function($){d=$},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m===null&&v&&(m=new XRWebGLBinding(i,n)),m},this.getFrame=function(){return x},this.getSession=function(){return i},this.setSession=async function($){if(i=$,i!==null){if(C=e.getRenderTarget(),i.addEventListener("select",ne),i.addEventListener("selectstart",ne),i.addEventListener("selectend",ne),i.addEventListener("squeeze",ne),i.addEventListener("squeezestart",ne),i.addEventListener("squeezeend",ne),i.addEventListener("end",ie),i.addEventListener("inputsourceschange",ee),_.xrCompatible!==!0&&await n.makeXRCompatible(),F=e.getPixelRatio(),e.getSize(T),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let E=null,j=null,O=null;_.depth&&(O=_.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,E=_.stencil?W0:G0,j=_.stencil?V0:Jf);const K={colorFormat:n.RGBA8,depthFormat:O,scaleFactor:s};m=this.getBinding(),p=m.createProjectionLayer(K),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),P=new tg(p.textureWidth,p.textureHeight,{format:Rc,type:Ed,depthTexture:new CZ(p.textureWidth,p.textureHeight,j,void 0,void 0,void 0,void 0,void 0,void 0,E),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}else{const E={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,E),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),P=new tg(f.framebufferWidth,f.framebufferHeight,{format:Rc,type:Ed,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}P.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),Ne.setContext(i),Ne.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function ee($){for(let Y=0;Y<$.removed.length;Y++){const E=$.removed[Y],j=A.indexOf(E);j>=0&&(A[j]=null,N[j].disconnect(E))}for(let Y=0;Y<$.added.length;Y++){const E=$.added[Y];let j=A.indexOf(E);if(j===-1){for(let K=0;K<N.length;K++)if(K>=A.length){A.push(E),j=K;break}else if(A[K]===null){A[K]=E,j=K;break}if(j===-1)break}const O=N[j];O&&O.connect(E)}}const ue=new Tt,le=new Tt;function oe($,Y,E){ue.setFromMatrixPosition(Y.matrixWorld),le.setFromMatrixPosition(E.matrixWorld);const j=ue.distanceTo(le),O=Y.projectionMatrix.elements,K=E.projectionMatrix.elements,B=O[14]/(O[10]-1),he=O[14]/(O[10]+1),I=(O[9]+1)/O[5],V=(O[9]-1)/O[5],Q=(O[8]-1)/O[0],G=(K[8]+1)/K[0],J=B*Q,se=B*G,fe=j/(-Q+G),pe=fe*-Q;if(Y.matrixWorld.decompose($.position,$.quaternion,$.scale),$.translateX(pe),$.translateZ(fe),$.matrixWorld.compose($.position,$.quaternion,$.scale),$.matrixWorldInverse.copy($.matrixWorld).invert(),O[10]===-1)$.projectionMatrix.copy(Y.projectionMatrix),$.projectionMatrixInverse.copy(Y.projectionMatrixInverse);else{const de=B+fe,U=he+fe,R=J-pe,ae=se+(j-pe),_e=I*he/U*de,Se=V*he/U*de;$.projectionMatrix.makePerspective(R,ae,_e,Se,de,U),$.projectionMatrixInverse.copy($.projectionMatrix).invert()}}function W($,Y){Y===null?$.matrixWorld.copy($.matrix):$.matrixWorld.multiplyMatrices(Y.matrixWorld,$.matrix),$.matrixWorldInverse.copy($.matrixWorld).invert()}this.updateCamera=function($){if(i===null)return;let Y=$.near,E=$.far;g.texture!==null&&(g.depthNear>0&&(Y=g.depthNear),g.depthFar>0&&(E=g.depthFar)),z.near=D.near=k.near=Y,z.far=D.far=k.far=E,(X!==z.near||L!==z.far)&&(i.updateRenderState({depthNear:z.near,depthFar:z.far}),X=z.near,L=z.far),z.layers.mask=$.layers.mask|6,k.layers.mask=z.layers.mask&3,D.layers.mask=z.layers.mask&5;const j=$.parent,O=z.cameras;W(z,j);for(let K=0;K<O.length;K++)W(O[K],j);O.length===2?oe(z,k,D):z.projectionMatrix.copy(k.projectionMatrix),re($,z,j)};function re($,Y,E){E===null?$.matrix.copy(Y.matrixWorld):($.matrix.copy(E.matrixWorld),$.matrix.invert(),$.matrix.multiply(Y.matrixWorld)),$.matrix.decompose($.position,$.quaternion,$.scale),$.updateMatrixWorld(!0),$.projectionMatrix.copy(Y.projectionMatrix),$.projectionMatrixInverse.copy(Y.projectionMatrixInverse),$.isPerspectiveCamera&&($.fov=$F*2*Math.atan(1/$.projectionMatrix.elements[5]),$.zoom=1)}this.getCamera=function(){return z},this.getFoveation=function(){if(!(p===null&&f===null))return c},this.setFoveation=function($){c=$,p!==null&&(p.fixedFoveation=$),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=$)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(z)},this.getCameraTexture=function($){return b[$]};let ce=null;function xe($,Y){if(u=Y.getViewerPose(d||o),x=Y,u!==null){const E=u.views;f!==null&&(e.setRenderTargetFramebuffer(P,f.framebuffer),e.setRenderTarget(P));let j=!1;E.length!==z.cameras.length&&(z.cameras.length=0,j=!0);for(let he=0;he<E.length;he++){const I=E[he];let V=null;if(f!==null)V=f.getViewport(I);else{const G=m.getViewSubImage(p,I);V=G.viewport,he===0&&(e.setRenderTargetTextures(P,G.colorTexture,G.depthStencilTexture),e.setRenderTarget(P))}let Q=H[he];Q===void 0&&(Q=new ql,Q.layers.enable(he),Q.viewport=new ui,H[he]=Q),Q.matrix.fromArray(I.transform.matrix),Q.matrix.decompose(Q.position,Q.quaternion,Q.scale),Q.projectionMatrix.fromArray(I.projectionMatrix),Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert(),Q.viewport.set(V.x,V.y,V.width,V.height),he===0&&(z.matrix.copy(Q.matrix),z.matrix.decompose(z.position,z.quaternion,z.scale)),j===!0&&z.cameras.push(Q)}const O=i.enabledFeatures;if(O&&O.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&v){m=r.getBinding();const he=m.getDepthInformation(E[0]);he&&he.isValid&&he.texture&&g.init(he,i.renderState)}if(O&&O.includes("camera-access")&&v){e.state.unbindTexture(),m=r.getBinding();for(let he=0;he<E.length;he++){const I=E[he].camera;if(I){let V=b[I];V||(V=new PZ,b[I]=V);const Q=m.getCameraImage(I);V.sourceTexture=Q}}}}for(let E=0;E<N.length;E++){const j=A[E],O=N[E];j!==null&&O!==void 0&&O.update(j,Y,d||o)}ce&&ce($,Y),Y.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:Y}),x=null}const Ne=new EZ;Ne.setAnimationLoop(xe),this.setAnimationLoop=function($){ce=$},this.dispose=function(){}}};const Yp=new sp,tke=new fi;function nke(t,e){function n(g,b){g.matrixAutoUpdate===!0&&g.updateMatrix(),b.value.copy(g.matrix)}function r(g,b){b.color.getRGB(g.fogColor.value,SZ(t)),b.isFog?(g.fogNear.value=b.near,g.fogFar.value=b.far):b.isFogExp2&&(g.fogDensity.value=b.density)}function i(g,b,_,C,P){b.isMeshBasicMaterial||b.isMeshLambertMaterial?s(g,b):b.isMeshToonMaterial?(s(g,b),m(g,b)):b.isMeshPhongMaterial?(s(g,b),u(g,b)):b.isMeshStandardMaterial?(s(g,b),p(g,b),b.isMeshPhysicalMaterial&&f(g,b,P)):b.isMeshMatcapMaterial?(s(g,b),x(g,b)):b.isMeshDepthMaterial?s(g,b):b.isMeshDistanceMaterial?(s(g,b),v(g,b)):b.isMeshNormalMaterial?s(g,b):b.isLineBasicMaterial?(o(g,b),b.isLineDashedMaterial&&l(g,b)):b.isPointsMaterial?c(g,b,_,C):b.isSpriteMaterial?d(g,b):b.isShadowMaterial?(g.color.value.copy(b.color),g.opacity.value=b.opacity):b.isShaderMaterial&&(b.uniformsNeedUpdate=!1)}function s(g,b){g.opacity.value=b.opacity,b.color&&g.diffuse.value.copy(b.color),b.emissive&&g.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity),b.map&&(g.map.value=b.map,n(b.map,g.mapTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.bumpMap&&(g.bumpMap.value=b.bumpMap,n(b.bumpMap,g.bumpMapTransform),g.bumpScale.value=b.bumpScale,b.side===Ao&&(g.bumpScale.value*=-1)),b.normalMap&&(g.normalMap.value=b.normalMap,n(b.normalMap,g.normalMapTransform),g.normalScale.value.copy(b.normalScale),b.side===Ao&&g.normalScale.value.negate()),b.displacementMap&&(g.displacementMap.value=b.displacementMap,n(b.displacementMap,g.displacementMapTransform),g.displacementScale.value=b.displacementScale,g.displacementBias.value=b.displacementBias),b.emissiveMap&&(g.emissiveMap.value=b.emissiveMap,n(b.emissiveMap,g.emissiveMapTransform)),b.specularMap&&(g.specularMap.value=b.specularMap,n(b.specularMap,g.specularMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest);const _=e.get(b),C=_.envMap,P=_.envMapRotation;C&&(g.envMap.value=C,Yp.copy(P),Yp.x*=-1,Yp.y*=-1,Yp.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(Yp.y*=-1,Yp.z*=-1),g.envMapRotation.value.setFromMatrix4(tke.makeRotationFromEuler(Yp)),g.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=b.reflectivity,g.ior.value=b.ior,g.refractionRatio.value=b.refractionRatio),b.lightMap&&(g.lightMap.value=b.lightMap,g.lightMapIntensity.value=b.lightMapIntensity,n(b.lightMap,g.lightMapTransform)),b.aoMap&&(g.aoMap.value=b.aoMap,g.aoMapIntensity.value=b.aoMapIntensity,n(b.aoMap,g.aoMapTransform))}function o(g,b){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,b.map&&(g.map.value=b.map,n(b.map,g.mapTransform))}function l(g,b){g.dashSize.value=b.dashSize,g.totalSize.value=b.dashSize+b.gapSize,g.scale.value=b.scale}function c(g,b,_,C){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,g.size.value=b.size*_,g.scale.value=C*.5,b.map&&(g.map.value=b.map,n(b.map,g.uvTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest)}function d(g,b){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,g.rotation.value=b.rotation,b.map&&(g.map.value=b.map,n(b.map,g.mapTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest)}function u(g,b){g.specular.value.copy(b.specular),g.shininess.value=Math.max(b.shininess,1e-4)}function m(g,b){b.gradientMap&&(g.gradientMap.value=b.gradientMap)}function p(g,b){g.metalness.value=b.metalness,b.metalnessMap&&(g.metalnessMap.value=b.metalnessMap,n(b.metalnessMap,g.metalnessMapTransform)),g.roughness.value=b.roughness,b.roughnessMap&&(g.roughnessMap.value=b.roughnessMap,n(b.roughnessMap,g.roughnessMapTransform)),b.envMap&&(g.envMapIntensity.value=b.envMapIntensity)}function f(g,b,_){g.ior.value=b.ior,b.sheen>0&&(g.sheenColor.value.copy(b.sheenColor).multiplyScalar(b.sheen),g.sheenRoughness.value=b.sheenRoughness,b.sheenColorMap&&(g.sheenColorMap.value=b.sheenColorMap,n(b.sheenColorMap,g.sheenColorMapTransform)),b.sheenRoughnessMap&&(g.sheenRoughnessMap.value=b.sheenRoughnessMap,n(b.sheenRoughnessMap,g.sheenRoughnessMapTransform))),b.clearcoat>0&&(g.clearcoat.value=b.clearcoat,g.clearcoatRoughness.value=b.clearcoatRoughness,b.clearcoatMap&&(g.clearcoatMap.value=b.clearcoatMap,n(b.clearcoatMap,g.clearcoatMapTransform)),b.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=b.clearcoatRoughnessMap,n(b.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),b.clearcoatNormalMap&&(g.clearcoatNormalMap.value=b.clearcoatNormalMap,n(b.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(b.clearcoatNormalScale),b.side===Ao&&g.clearcoatNormalScale.value.negate())),b.dispersion>0&&(g.dispersion.value=b.dispersion),b.iridescence>0&&(g.iridescence.value=b.iridescence,g.iridescenceIOR.value=b.iridescenceIOR,g.iridescenceThicknessMinimum.value=b.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=b.iridescenceThicknessRange[1],b.iridescenceMap&&(g.iridescenceMap.value=b.iridescenceMap,n(b.iridescenceMap,g.iridescenceMapTransform)),b.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=b.iridescenceThicknessMap,n(b.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),b.transmission>0&&(g.transmission.value=b.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),b.transmissionMap&&(g.transmissionMap.value=b.transmissionMap,n(b.transmissionMap,g.transmissionMapTransform)),g.thickness.value=b.thickness,b.thicknessMap&&(g.thicknessMap.value=b.thicknessMap,n(b.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=b.attenuationDistance,g.attenuationColor.value.copy(b.attenuationColor)),b.anisotropy>0&&(g.anisotropyVector.value.set(b.anisotropy*Math.cos(b.anisotropyRotation),b.anisotropy*Math.sin(b.anisotropyRotation)),b.anisotropyMap&&(g.anisotropyMap.value=b.anisotropyMap,n(b.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=b.specularIntensity,g.specularColor.value.copy(b.specularColor),b.specularColorMap&&(g.specularColorMap.value=b.specularColorMap,n(b.specularColorMap,g.specularColorMapTransform)),b.specularIntensityMap&&(g.specularIntensityMap.value=b.specularIntensityMap,n(b.specularIntensityMap,g.specularIntensityMapTransform))}function x(g,b){b.matcap&&(g.matcap.value=b.matcap)}function v(g,b){const _=e.get(b).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function rke(t,e,n,r){let i={},s={},o=[];const l=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function c(_,C){const P=C.program;r.uniformBlockBinding(_,P)}function d(_,C){let P=i[_.id];P===void 0&&(x(_),P=u(_),i[_.id]=P,_.addEventListener("dispose",g));const N=C.program;r.updateUBOMapping(_,N);const A=e.render.frame;s[_.id]!==A&&(p(_),s[_.id]=A)}function u(_){const C=m();_.__bindingPointIndex=C;const P=t.createBuffer(),N=_.__size,A=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,P),t.bufferData(t.UNIFORM_BUFFER,N,A),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,C,P),P}function m(){for(let _=0;_<l;_++)if(o.indexOf(_)===-1)return o.push(_),_;return ni("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function p(_){const C=i[_.id],P=_.uniforms,N=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,C);for(let A=0,T=P.length;A<T;A++){const F=Array.isArray(P[A])?P[A]:[P[A]];for(let k=0,D=F.length;k<D;k++){const H=F[k];if(f(H,A,k,N)===!0){const z=H.__offset,X=Array.isArray(H.value)?H.value:[H.value];let L=0;for(let ne=0;ne<X.length;ne++){const ie=X[ne],ee=v(ie);typeof ie=="number"||typeof ie=="boolean"?(H.__data[0]=ie,t.bufferSubData(t.UNIFORM_BUFFER,z+L,H.__data)):ie.isMatrix3?(H.__data[0]=ie.elements[0],H.__data[1]=ie.elements[1],H.__data[2]=ie.elements[2],H.__data[3]=0,H.__data[4]=ie.elements[3],H.__data[5]=ie.elements[4],H.__data[6]=ie.elements[5],H.__data[7]=0,H.__data[8]=ie.elements[6],H.__data[9]=ie.elements[7],H.__data[10]=ie.elements[8],H.__data[11]=0):(ie.toArray(H.__data,L),L+=ee.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,z,H.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(_,C,P,N){const A=_.value,T=C+"_"+P;if(N[T]===void 0)return typeof A=="number"||typeof A=="boolean"?N[T]=A:N[T]=A.clone(),!0;{const F=N[T];if(typeof A=="number"||typeof A=="boolean"){if(F!==A)return N[T]=A,!0}else if(F.equals(A)===!1)return F.copy(A),!0}return!1}function x(_){const C=_.uniforms;let P=0;const N=16;for(let T=0,F=C.length;T<F;T++){const k=Array.isArray(C[T])?C[T]:[C[T]];for(let D=0,H=k.length;D<H;D++){const z=k[D],X=Array.isArray(z.value)?z.value:[z.value];for(let L=0,ne=X.length;L<ne;L++){const ie=X[L],ee=v(ie),ue=P%N,le=ue%ee.boundary,oe=ue+le;P+=le,oe!==0&&N-oe<ee.storage&&(P+=N-oe),z.__data=new Float32Array(ee.storage/Float32Array.BYTES_PER_ELEMENT),z.__offset=P,P+=ee.storage}}}const A=P%N;return A>0&&(P+=N-A),_.__size=P,_.__cache={},this}function v(_){const C={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(C.boundary=4,C.storage=4):_.isVector2?(C.boundary=8,C.storage=8):_.isVector3||_.isColor?(C.boundary=16,C.storage=12):_.isVector4?(C.boundary=16,C.storage=16):_.isMatrix3?(C.boundary=48,C.storage=48):_.isMatrix4?(C.boundary=64,C.storage=64):_.isTexture?qn("WebGLRenderer: Texture samplers can not be part of an uniforms group."):qn("WebGLRenderer: Unsupported uniform value type.",_),C}function g(_){const C=_.target;C.removeEventListener("dispose",g);const P=o.indexOf(C.__bindingPointIndex);o.splice(P,1),t.deleteBuffer(i[C.id]),delete i[C.id],delete s[C.id]}function b(){for(const _ in i)t.deleteBuffer(i[_]);o=[],i={},s={}}return{bind:c,update:d,dispose:b}}const ake=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 gu=null;function ike(){return gu===null&&(gu=new n0e(ake,32,32,OO,cy),gu.minFilter=Xl,gu.magFilter=Xl,gu.wrapS=Bu,gu.wrapT=Bu,gu.generateMipmaps=!1,gu.needsUpdate=!0),gu}let ske=class{constructor(e={}){const{canvas:n=Pve(),context:r=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:d=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:m=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let f;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=r.getContextAttributes().alpha}else f=o;const x=new Set([zO,IO,LO]),v=new Set([Ed,Jf,$0,V0,FO,RO]),g=new Uint32Array(4),b=new Int32Array(4);let _=null,C=null;const P=[],N=[];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=Wh,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const A=this;let T=!1;this._outputColorSpace=Zo;let F=0,k=0,D=null,H=-1,z=null;const X=new ui,L=new ui;let ne=null;const ie=new lr(0);let ee=0,ue=n.width,le=n.height,oe=1,W=null,re=null;const ce=new ui(0,0,ue,le),xe=new ui(0,0,ue,le);let Ne=!1;const $=new $O;let Y=!1,E=!1;const j=new fi,O=new Tt,K=new ui,B={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let he=!1;function I(){return D===null?oe:1}let V=r;function Q(Ce,We){return n.getContext(Ce,We)}try{const Ce={alpha:!0,depth:i,stencil:s,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:d,powerPreference:u,failIfMajorPerformanceCaveat:m};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${MO}`),n.addEventListener("webglcontextlost",He,!1),n.addEventListener("webglcontextrestored",ge,!1),n.addEventListener("webglcontextcreationerror",Pe,!1),V===null){const We="webgl2";if(V=Q(We,Ce),V===null)throw Q(We)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(Ce){throw Ce("WebGLRenderer: "+Ce.message),Ce}let G,J,se,fe,pe,de,U,R,ae,_e,Se,ye,Ae,ve,je,Re,Ee,Te,Me,Be,Ke,tt,te,Ie;function be(){G=new p_e(V),G.init(),tt=new Y1e(V,G),J=new i_e(V,G,e,tt),se=new K1e(V,G),J.reversedDepthBuffer&&p&&se.buffers.depth.setReversed(!0),fe=new b_e(V),pe=new R1e,de=new X1e(V,G,se,pe,J,tt,fe),U=new o_e(A),R=new h_e(A),ae=new w0e(V),te=new r_e(V,ae),_e=new f_e(V,ae,fe,te),Se=new y_e(V,_e,ae,fe),Me=new x_e(V,J,de),Re=new s_e(pe),ye=new F1e(A,U,R,G,J,te,Re),Ae=new nke(A,pe),ve=new O1e,je=new q1e(G),Te=new n_e(A,U,R,se,Se,f,c),Ee=new G1e(A,Se,J),Ie=new rke(V,fe,J,se),Be=new a_e(V,G,fe),Ke=new g_e(V,G,fe),fe.programs=ye.programs,A.capabilities=J,A.extensions=G,A.properties=pe,A.renderLists=ve,A.shadowMap=Ee,A.state=se,A.info=fe}be();const $e=new eke(A,V);this.xr=$e,this.getContext=function(){return V},this.getContextAttributes=function(){return V.getContextAttributes()},this.forceContextLoss=function(){const Ce=G.get("WEBGL_lose_context");Ce&&Ce.loseContext()},this.forceContextRestore=function(){const Ce=G.get("WEBGL_lose_context");Ce&&Ce.restoreContext()},this.getPixelRatio=function(){return oe},this.setPixelRatio=function(Ce){Ce!==void 0&&(oe=Ce,this.setSize(ue,le,!1))},this.getSize=function(Ce){return Ce.set(ue,le)},this.setSize=function(Ce,We,Je=!0){if($e.isPresenting){qn("WebGLRenderer: Can't change size while VR device is presenting.");return}ue=Ce,le=We,n.width=Math.floor(Ce*oe),n.height=Math.floor(We*oe),Je===!0&&(n.style.width=Ce+"px",n.style.height=We+"px"),this.setViewport(0,0,Ce,We)},this.getDrawingBufferSize=function(Ce){return Ce.set(ue*oe,le*oe).floor()},this.setDrawingBufferSize=function(Ce,We,Je){ue=Ce,le=We,oe=Je,n.width=Math.floor(Ce*Je),n.height=Math.floor(We*Je),this.setViewport(0,0,Ce,We)},this.getCurrentViewport=function(Ce){return Ce.copy(X)},this.getViewport=function(Ce){return Ce.copy(ce)},this.setViewport=function(Ce,We,Je,Xe){Ce.isVector4?ce.set(Ce.x,Ce.y,Ce.z,Ce.w):ce.set(Ce,We,Je,Xe),se.viewport(X.copy(ce).multiplyScalar(oe).round())},this.getScissor=function(Ce){return Ce.copy(xe)},this.setScissor=function(Ce,We,Je,Xe){Ce.isVector4?xe.set(Ce.x,Ce.y,Ce.z,Ce.w):xe.set(Ce,We,Je,Xe),se.scissor(L.copy(xe).multiplyScalar(oe).round())},this.getScissorTest=function(){return Ne},this.setScissorTest=function(Ce){se.setScissorTest(Ne=Ce)},this.setOpaqueSort=function(Ce){W=Ce},this.setTransparentSort=function(Ce){re=Ce},this.getClearColor=function(Ce){return Ce.copy(Te.getClearColor())},this.setClearColor=function(){Te.setClearColor(...arguments)},this.getClearAlpha=function(){return Te.getClearAlpha()},this.setClearAlpha=function(){Te.setClearAlpha(...arguments)},this.clear=function(Ce=!0,We=!0,Je=!0){let Xe=0;if(Ce){let Ye=!1;if(D!==null){const St=D.texture.format;Ye=x.has(St)}if(Ye){const St=D.texture.type,et=v.has(St),jt=Te.getClearColor(),bt=Te.getClearAlpha(),Ve=jt.r,gt=jt.g,Et=jt.b;et?(g[0]=Ve,g[1]=gt,g[2]=Et,g[3]=bt,V.clearBufferuiv(V.COLOR,0,g)):(b[0]=Ve,b[1]=gt,b[2]=Et,b[3]=bt,V.clearBufferiv(V.COLOR,0,b))}else Xe|=V.COLOR_BUFFER_BIT}We&&(Xe|=V.DEPTH_BUFFER_BIT),Je&&(Xe|=V.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),V.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",He,!1),n.removeEventListener("webglcontextrestored",ge,!1),n.removeEventListener("webglcontextcreationerror",Pe,!1),Te.dispose(),ve.dispose(),je.dispose(),pe.dispose(),U.dispose(),R.dispose(),Se.dispose(),te.dispose(),Ie.dispose(),ye.dispose(),$e.dispose(),$e.removeEventListener("sessionstart",Qt),$e.removeEventListener("sessionend",en),Xt.stop()};function He(Ce){Ce.preventDefault(),BH("WebGLRenderer: Context Lost."),T=!0}function ge(){BH("WebGLRenderer: Context Restored."),T=!1;const Ce=fe.autoReset,We=Ee.enabled,Je=Ee.autoUpdate,Xe=Ee.needsUpdate,Ye=Ee.type;be(),fe.autoReset=Ce,Ee.enabled=We,Ee.autoUpdate=Je,Ee.needsUpdate=Xe,Ee.type=Ye}function Pe(Ce){ni("WebGLRenderer: A WebGL context could not be created. Reason: ",Ce.statusMessage)}function qe(Ce){const We=Ce.target;We.removeEventListener("dispose",qe),Ze(We)}function Ze(Ce){ut(Ce),pe.remove(Ce)}function ut(Ce){const We=pe.get(Ce).programs;We!==void 0&&(We.forEach(function(Je){ye.releaseProgram(Je)}),Ce.isShaderMaterial&&ye.releaseShaderCache(Ce))}this.renderBufferDirect=function(Ce,We,Je,Xe,Ye,St){We===null&&(We=B);const et=Ye.isMesh&&Ye.matrixWorld.determinant()<0,jt=ze(Ce,We,Je,Xe,Ye);se.setMaterial(Xe,et);let bt=Je.index,Ve=1;if(Xe.wireframe===!0){if(bt=_e.getWireframeAttribute(Je),bt===void 0)return;Ve=2}const gt=Je.drawRange,Et=Je.attributes.position;let Gt=gt.start*Ve,on=(gt.start+gt.count)*Ve;St!==null&&(Gt=Math.max(Gt,St.start*Ve),on=Math.min(on,(St.start+St.count)*Ve)),bt!==null?(Gt=Math.max(Gt,0),on=Math.min(on,bt.count)):Et!=null&&(Gt=Math.max(Gt,0),on=Math.min(on,Et.count));const fn=on-Gt;if(fn<0||fn===1/0)return;te.setup(Ye,Xe,jt,Je,bt);let Ln,yn=Be;if(bt!==null&&(Ln=ae.get(bt),yn=Ke,yn.setIndex(Ln)),Ye.isMesh)Xe.wireframe===!0?(se.setLineWidth(Xe.wireframeLinewidth*I()),yn.setMode(V.LINES)):yn.setMode(V.TRIANGLES);else if(Ye.isLine){let hn=Xe.linewidth;hn===void 0&&(hn=1),se.setLineWidth(hn*I()),Ye.isLineSegments?yn.setMode(V.LINES):Ye.isLineLoop?yn.setMode(V.LINE_LOOP):yn.setMode(V.LINE_STRIP)}else Ye.isPoints?yn.setMode(V.POINTS):Ye.isSprite&&yn.setMode(V.TRIANGLES);if(Ye.isBatchedMesh)if(Ye._multiDrawInstances!==null)K0("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),yn.renderMultiDrawInstances(Ye._multiDrawStarts,Ye._multiDrawCounts,Ye._multiDrawCount,Ye._multiDrawInstances);else if(G.get("WEBGL_multi_draw"))yn.renderMultiDraw(Ye._multiDrawStarts,Ye._multiDrawCounts,Ye._multiDrawCount);else{const hn=Ye._multiDrawStarts,xn=Ye._multiDrawCounts,Nn=Ye._multiDrawCount,Pn=bt?ae.get(bt).bytesPerElement:1,Nr=pe.get(Xe).currentProgram.getUniforms();for(let Sn=0;Sn<Nn;Sn++)Nr.setValue(V,"_gl_DrawID",Sn),yn.render(hn[Sn]/Pn,xn[Sn])}else if(Ye.isInstancedMesh)yn.renderInstances(Gt,fn,Ye.count);else if(Je.isInstancedBufferGeometry){const hn=Je._maxInstanceCount!==void 0?Je._maxInstanceCount:1/0,xn=Math.min(Je.instanceCount,hn);yn.renderInstances(Gt,fn,xn)}else yn.render(Gt,fn)};function vt(Ce,We,Je){Ce.transparent===!0&&Ce.side===bd&&Ce.forceSinglePass===!1?(Ce.side=Ao,Ce.needsUpdate=!0,pt(Ce,We,Je),Ce.side=ip,Ce.needsUpdate=!0,pt(Ce,We,Je),Ce.side=bd):pt(Ce,We,Je)}this.compile=function(Ce,We,Je=null){Je===null&&(Je=Ce),C=je.get(Je),C.init(We),N.push(C),Je.traverseVisible(function(Ye){Ye.isLight&&Ye.layers.test(We.layers)&&(C.pushLight(Ye),Ye.castShadow&&C.pushShadow(Ye))}),Ce!==Je&&Ce.traverseVisible(function(Ye){Ye.isLight&&Ye.layers.test(We.layers)&&(C.pushLight(Ye),Ye.castShadow&&C.pushShadow(Ye))}),C.setupLights();const Xe=new Set;return Ce.traverse(function(Ye){if(!(Ye.isMesh||Ye.isPoints||Ye.isLine||Ye.isSprite))return;const St=Ye.material;if(St)if(Array.isArray(St))for(let et=0;et<St.length;et++){const jt=St[et];vt(jt,Je,Ye),Xe.add(jt)}else vt(St,Je,Ye),Xe.add(St)}),C=N.pop(),Xe},this.compileAsync=function(Ce,We,Je=null){const Xe=this.compile(Ce,We,Je);return new Promise(Ye=>{function St(){if(Xe.forEach(function(et){pe.get(et).currentProgram.isReady()&&Xe.delete(et)}),Xe.size===0){Ye(Ce);return}setTimeout(St,10)}G.get("KHR_parallel_shader_compile")!==null?St():setTimeout(St,10)})};let wt=null;function $t(Ce){wt&&wt(Ce)}function Qt(){Xt.stop()}function en(){Xt.start()}const Xt=new EZ;Xt.setAnimationLoop($t),typeof self<"u"&&Xt.setContext(self),this.setAnimationLoop=function(Ce){wt=Ce,$e.setAnimationLoop(Ce),Ce===null?Xt.stop():Xt.start()},$e.addEventListener("sessionstart",Qt),$e.addEventListener("sessionend",en),this.render=function(Ce,We){if(We!==void 0&&We.isCamera!==!0){ni("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(Ce.matrixWorldAutoUpdate===!0&&Ce.updateMatrixWorld(),We.parent===null&&We.matrixWorldAutoUpdate===!0&&We.updateMatrixWorld(),$e.enabled===!0&&$e.isPresenting===!0&&($e.cameraAutoUpdate===!0&&$e.updateCamera(We),We=$e.getCamera()),Ce.isScene===!0&&Ce.onBeforeRender(A,Ce,We,D),C=je.get(Ce,N.length),C.init(We),N.push(C),j.multiplyMatrices(We.projectionMatrix,We.matrixWorldInverse),$.setFromProjectionMatrix(j,wd,We.reversedDepth),E=this.localClippingEnabled,Y=Re.init(this.clippingPlanes,E),_=ve.get(Ce,P.length),_.init(),P.push(_),$e.enabled===!0&&$e.isPresenting===!0){const St=A.xr.getDepthSensingMesh();St!==null&&tn(St,We,-1/0,A.sortObjects)}tn(Ce,We,0,A.sortObjects),_.finish(),A.sortObjects===!0&&_.sort(W,re),he=$e.enabled===!1||$e.isPresenting===!1||$e.hasDepthSensing()===!1,he&&Te.addToRenderList(_,Ce),this.info.render.frame++,Y===!0&&Re.beginShadows();const Je=C.state.shadowsArray;Ee.render(Je,Ce,We),Y===!0&&Re.endShadows(),this.info.autoReset===!0&&this.info.reset();const Xe=_.opaque,Ye=_.transmissive;if(C.setupLights(),We.isArrayCamera){const St=We.cameras;if(Ye.length>0)for(let et=0,jt=St.length;et<jt;et++){const bt=St[et];Ft(Xe,Ye,Ce,bt)}he&&Te.render(Ce);for(let et=0,jt=St.length;et<jt;et++){const bt=St[et];Ge(_,Ce,bt,bt.viewport)}}else Ye.length>0&&Ft(Xe,Ye,Ce,We),he&&Te.render(Ce),Ge(_,Ce,We);D!==null&&k===0&&(de.updateMultisampleRenderTarget(D),de.updateRenderTargetMipmap(D)),Ce.isScene===!0&&Ce.onAfterRender(A,Ce,We),te.resetDefaultState(),H=-1,z=null,N.pop(),N.length>0?(C=N[N.length-1],Y===!0&&Re.setGlobalState(A.clippingPlanes,C.state.camera)):C=null,P.pop(),P.length>0?_=P[P.length-1]:_=null};function tn(Ce,We,Je,Xe){if(Ce.visible===!1)return;if(Ce.layers.test(We.layers)){if(Ce.isGroup)Je=Ce.renderOrder;else if(Ce.isLOD)Ce.autoUpdate===!0&&Ce.update(We);else if(Ce.isLight)C.pushLight(Ce),Ce.castShadow&&C.pushShadow(Ce);else if(Ce.isSprite){if(!Ce.frustumCulled||$.intersectsSprite(Ce)){Xe&&K.setFromMatrixPosition(Ce.matrixWorld).applyMatrix4(j);const et=Se.update(Ce),jt=Ce.material;jt.visible&&_.push(Ce,et,jt,Je,K.z,null)}}else if((Ce.isMesh||Ce.isLine||Ce.isPoints)&&(!Ce.frustumCulled||$.intersectsObject(Ce))){const et=Se.update(Ce),jt=Ce.material;if(Xe&&(Ce.boundingSphere!==void 0?(Ce.boundingSphere===null&&Ce.computeBoundingSphere(),K.copy(Ce.boundingSphere.center)):(et.boundingSphere===null&&et.computeBoundingSphere(),K.copy(et.boundingSphere.center)),K.applyMatrix4(Ce.matrixWorld).applyMatrix4(j)),Array.isArray(jt)){const bt=et.groups;for(let Ve=0,gt=bt.length;Ve<gt;Ve++){const Et=bt[Ve],Gt=jt[Et.materialIndex];Gt&&Gt.visible&&_.push(Ce,et,Gt,Je,K.z,Et)}}else jt.visible&&_.push(Ce,et,jt,Je,K.z,null)}}const St=Ce.children;for(let et=0,jt=St.length;et<jt;et++)tn(St[et],We,Je,Xe)}function Ge(Ce,We,Je,Xe){const{opaque:Ye,transmissive:St,transparent:et}=Ce;C.setupLightsView(Je),Y===!0&&Re.setGlobalState(A.clippingPlanes,Je),Xe&&se.viewport(X.copy(Xe)),Ye.length>0&&Yt(Ye,We,Je),St.length>0&&Yt(St,We,Je),et.length>0&&Yt(et,We,Je),se.buffers.depth.setTest(!0),se.buffers.depth.setMask(!0),se.buffers.color.setMask(!0),se.setPolygonOffset(!1)}function Ft(Ce,We,Je,Xe){if((Je.isScene===!0?Je.overrideMaterial:null)!==null)return;C.state.transmissionRenderTarget[Xe.id]===void 0&&(C.state.transmissionRenderTarget[Xe.id]=new tg(1,1,{generateMipmaps:!0,type:G.has("EXT_color_buffer_half_float")||G.has("EXT_color_buffer_float")?cy:Ed,minFilter:yf,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Tr.workingColorSpace}));const St=C.state.transmissionRenderTarget[Xe.id],et=Xe.viewport||X;St.setSize(et.z*A.transmissionResolutionScale,et.w*A.transmissionResolutionScale);const jt=A.getRenderTarget(),bt=A.getActiveCubeFace(),Ve=A.getActiveMipmapLevel();A.setRenderTarget(St),A.getClearColor(ie),ee=A.getClearAlpha(),ee<1&&A.setClearColor(16777215,.5),A.clear(),he&&Te.render(Je);const gt=A.toneMapping;A.toneMapping=Wh;const Et=Xe.viewport;if(Xe.viewport!==void 0&&(Xe.viewport=void 0),C.setupLightsView(Xe),Y===!0&&Re.setGlobalState(A.clippingPlanes,Xe),Yt(Ce,Je,Xe),de.updateMultisampleRenderTarget(St),de.updateRenderTargetMipmap(St),G.has("WEBGL_multisampled_render_to_texture")===!1){let Gt=!1;for(let on=0,fn=We.length;on<fn;on++){const Ln=We[on],{object:yn,geometry:hn,material:xn,group:Nn}=Ln;if(xn.side===bd&&yn.layers.test(Xe.layers)){const Pn=xn.side;xn.side=Ao,xn.needsUpdate=!0,Pt(yn,Je,Xe,hn,xn,Nn),xn.side=Pn,xn.needsUpdate=!0,Gt=!0}}Gt===!0&&(de.updateMultisampleRenderTarget(St),de.updateRenderTargetMipmap(St))}A.setRenderTarget(jt,bt,Ve),A.setClearColor(ie,ee),Et!==void 0&&(Xe.viewport=Et),A.toneMapping=gt}function Yt(Ce,We,Je){const Xe=We.isScene===!0?We.overrideMaterial:null;for(let Ye=0,St=Ce.length;Ye<St;Ye++){const et=Ce[Ye],{object:jt,geometry:bt,group:Ve}=et;let gt=et.material;gt.allowOverride===!0&&Xe!==null&&(gt=Xe),jt.layers.test(Je.layers)&&Pt(jt,We,Je,bt,gt,Ve)}}function Pt(Ce,We,Je,Xe,Ye,St){Ce.onBeforeRender(A,We,Je,Xe,Ye,St),Ce.modelViewMatrix.multiplyMatrices(Je.matrixWorldInverse,Ce.matrixWorld),Ce.normalMatrix.getNormalMatrix(Ce.modelViewMatrix),Ye.onBeforeRender(A,We,Je,Xe,Ce,St),Ye.transparent===!0&&Ye.side===bd&&Ye.forceSinglePass===!1?(Ye.side=Ao,Ye.needsUpdate=!0,A.renderBufferDirect(Je,We,Xe,Ye,Ce,St),Ye.side=ip,Ye.needsUpdate=!0,A.renderBufferDirect(Je,We,Xe,Ye,Ce,St),Ye.side=bd):A.renderBufferDirect(Je,We,Xe,Ye,Ce,St),Ce.onAfterRender(A,We,Je,Xe,Ye,St)}function pt(Ce,We,Je){We.isScene!==!0&&(We=B);const Xe=pe.get(Ce),Ye=C.state.lights,St=C.state.shadowsArray,et=Ye.state.version,jt=ye.getParameters(Ce,Ye.state,St,We,Je),bt=ye.getProgramCacheKey(jt);let Ve=Xe.programs;Xe.environment=Ce.isMeshStandardMaterial?We.environment:null,Xe.fog=We.fog,Xe.envMap=(Ce.isMeshStandardMaterial?R:U).get(Ce.envMap||Xe.environment),Xe.envMapRotation=Xe.environment!==null&&Ce.envMap===null?We.environmentRotation:Ce.envMapRotation,Ve===void 0&&(Ce.addEventListener("dispose",qe),Ve=new Map,Xe.programs=Ve);let gt=Ve.get(bt);if(gt!==void 0){if(Xe.currentProgram===gt&&Xe.lightsStateVersion===et)return Ut(Ce,jt),gt}else jt.uniforms=ye.getUniforms(Ce),Ce.onBeforeCompile(jt,A),gt=ye.acquireProgram(jt,bt),Ve.set(bt,gt),Xe.uniforms=jt.uniforms;const Et=Xe.uniforms;return(!Ce.isShaderMaterial&&!Ce.isRawShaderMaterial||Ce.clipping===!0)&&(Et.clippingPlanes=Re.uniform),Ut(Ce,jt),Xe.needsLights=ht(Ce),Xe.lightsStateVersion=et,Xe.needsLights&&(Et.ambientLightColor.value=Ye.state.ambient,Et.lightProbe.value=Ye.state.probe,Et.directionalLights.value=Ye.state.directional,Et.directionalLightShadows.value=Ye.state.directionalShadow,Et.spotLights.value=Ye.state.spot,Et.spotLightShadows.value=Ye.state.spotShadow,Et.rectAreaLights.value=Ye.state.rectArea,Et.ltc_1.value=Ye.state.rectAreaLTC1,Et.ltc_2.value=Ye.state.rectAreaLTC2,Et.pointLights.value=Ye.state.point,Et.pointLightShadows.value=Ye.state.pointShadow,Et.hemisphereLights.value=Ye.state.hemi,Et.directionalShadowMap.value=Ye.state.directionalShadowMap,Et.directionalShadowMatrix.value=Ye.state.directionalShadowMatrix,Et.spotShadowMap.value=Ye.state.spotShadowMap,Et.spotLightMatrix.value=Ye.state.spotLightMatrix,Et.spotLightMap.value=Ye.state.spotLightMap,Et.pointShadowMap.value=Ye.state.pointShadowMap,Et.pointShadowMatrix.value=Ye.state.pointShadowMatrix),Xe.currentProgram=gt,Xe.uniformsList=null,gt}function Wt(Ce){if(Ce.uniformsList===null){const We=Ce.currentProgram.getUniforms();Ce.uniformsList=Ek.seqWithValue(We.seq,Ce.uniforms)}return Ce.uniformsList}function Ut(Ce,We){const Je=pe.get(Ce);Je.outputColorSpace=We.outputColorSpace,Je.batching=We.batching,Je.batchingColor=We.batchingColor,Je.instancing=We.instancing,Je.instancingColor=We.instancingColor,Je.instancingMorph=We.instancingMorph,Je.skinning=We.skinning,Je.morphTargets=We.morphTargets,Je.morphNormals=We.morphNormals,Je.morphColors=We.morphColors,Je.morphTargetsCount=We.morphTargetsCount,Je.numClippingPlanes=We.numClippingPlanes,Je.numIntersection=We.numClipIntersection,Je.vertexAlphas=We.vertexAlphas,Je.vertexTangents=We.vertexTangents,Je.toneMapping=We.toneMapping}function ze(Ce,We,Je,Xe,Ye){We.isScene!==!0&&(We=B),de.resetTextureUnits();const St=We.fog,et=Xe.isMeshStandardMaterial?We.environment:null,jt=D===null?A.outputColorSpace:D.isXRRenderTarget===!0?D.texture.colorSpace:Dx,bt=(Xe.isMeshStandardMaterial?R:U).get(Xe.envMap||et),Ve=Xe.vertexColors===!0&&!!Je.attributes.color&&Je.attributes.color.itemSize===4,gt=!!Je.attributes.tangent&&(!!Xe.normalMap||Xe.anisotropy>0),Et=!!Je.morphAttributes.position,Gt=!!Je.morphAttributes.normal,on=!!Je.morphAttributes.color;let fn=Wh;Xe.toneMapped&&(D===null||D.isXRRenderTarget===!0)&&(fn=A.toneMapping);const Ln=Je.morphAttributes.position||Je.morphAttributes.normal||Je.morphAttributes.color,yn=Ln!==void 0?Ln.length:0,hn=pe.get(Xe),xn=C.state.lights;if(Y===!0&&(E===!0||Ce!==z)){const Zr=Ce===z&&Xe.id===H;Re.setState(Xe,Ce,Zr)}let Nn=!1;Xe.version===hn.__version?(hn.needsLights&&hn.lightsStateVersion!==xn.state.version||hn.outputColorSpace!==jt||Ye.isBatchedMesh&&hn.batching===!1||!Ye.isBatchedMesh&&hn.batching===!0||Ye.isBatchedMesh&&hn.batchingColor===!0&&Ye.colorTexture===null||Ye.isBatchedMesh&&hn.batchingColor===!1&&Ye.colorTexture!==null||Ye.isInstancedMesh&&hn.instancing===!1||!Ye.isInstancedMesh&&hn.instancing===!0||Ye.isSkinnedMesh&&hn.skinning===!1||!Ye.isSkinnedMesh&&hn.skinning===!0||Ye.isInstancedMesh&&hn.instancingColor===!0&&Ye.instanceColor===null||Ye.isInstancedMesh&&hn.instancingColor===!1&&Ye.instanceColor!==null||Ye.isInstancedMesh&&hn.instancingMorph===!0&&Ye.morphTexture===null||Ye.isInstancedMesh&&hn.instancingMorph===!1&&Ye.morphTexture!==null||hn.envMap!==bt||Xe.fog===!0&&hn.fog!==St||hn.numClippingPlanes!==void 0&&(hn.numClippingPlanes!==Re.numPlanes||hn.numIntersection!==Re.numIntersection)||hn.vertexAlphas!==Ve||hn.vertexTangents!==gt||hn.morphTargets!==Et||hn.morphNormals!==Gt||hn.morphColors!==on||hn.toneMapping!==fn||hn.morphTargetsCount!==yn)&&(Nn=!0):(Nn=!0,hn.__version=Xe.version);let Pn=hn.currentProgram;Nn===!0&&(Pn=pt(Xe,We,Ye));let Nr=!1,Sn=!1,Pa=!1;const On=Pn.getUniforms(),ya=hn.uniforms;if(se.useProgram(Pn.program)&&(Nr=!0,Sn=!0,Pa=!0),Xe.id!==H&&(H=Xe.id,Sn=!0),Nr||z!==Ce){se.buffers.depth.getReversed()&&Ce.reversedDepth!==!0&&(Ce._reversedDepth=!0,Ce.updateProjectionMatrix()),On.setValue(V,"projectionMatrix",Ce.projectionMatrix),On.setValue(V,"viewMatrix",Ce.matrixWorldInverse);const sa=On.map.cameraPosition;sa!==void 0&&sa.setValue(V,O.setFromMatrixPosition(Ce.matrixWorld)),J.logarithmicDepthBuffer&&On.setValue(V,"logDepthBufFC",2/(Math.log(Ce.far+1)/Math.LN2)),(Xe.isMeshPhongMaterial||Xe.isMeshToonMaterial||Xe.isMeshLambertMaterial||Xe.isMeshBasicMaterial||Xe.isMeshStandardMaterial||Xe.isShaderMaterial)&&On.setValue(V,"isOrthographic",Ce.isOrthographicCamera===!0),z!==Ce&&(z=Ce,Sn=!0,Pa=!0)}if(Ye.isSkinnedMesh){On.setOptional(V,Ye,"bindMatrix"),On.setOptional(V,Ye,"bindMatrixInverse");const Zr=Ye.skeleton;Zr&&(Zr.boneTexture===null&&Zr.computeBoneTexture(),On.setValue(V,"boneTexture",Zr.boneTexture,de))}Ye.isBatchedMesh&&(On.setOptional(V,Ye,"batchingTexture"),On.setValue(V,"batchingTexture",Ye._matricesTexture,de),On.setOptional(V,Ye,"batchingIdTexture"),On.setValue(V,"batchingIdTexture",Ye._indirectTexture,de),On.setOptional(V,Ye,"batchingColorTexture"),Ye._colorsTexture!==null&&On.setValue(V,"batchingColorTexture",Ye._colorsTexture,de));const ua=Je.morphAttributes;if((ua.position!==void 0||ua.normal!==void 0||ua.color!==void 0)&&Me.update(Ye,Je,Pn),(Sn||hn.receiveShadow!==Ye.receiveShadow)&&(hn.receiveShadow=Ye.receiveShadow,On.setValue(V,"receiveShadow",Ye.receiveShadow)),Xe.isMeshGouraudMaterial&&Xe.envMap!==null&&(ya.envMap.value=bt,ya.flipEnvMap.value=bt.isCubeTexture&&bt.isRenderTargetTexture===!1?-1:1),Xe.isMeshStandardMaterial&&Xe.envMap===null&&We.environment!==null&&(ya.envMapIntensity.value=We.environmentIntensity),ya.dfgLUT!==void 0&&(ya.dfgLUT.value=ike()),Sn&&(On.setValue(V,"toneMappingExposure",A.toneMappingExposure),hn.needsLights&&st(ya,Pa),St&&Xe.fog===!0&&Ae.refreshFogUniforms(ya,St),Ae.refreshMaterialUniforms(ya,Xe,oe,le,C.state.transmissionRenderTarget[Ce.id]),Ek.upload(V,Wt(hn),ya,de)),Xe.isShaderMaterial&&Xe.uniformsNeedUpdate===!0&&(Ek.upload(V,Wt(hn),ya,de),Xe.uniformsNeedUpdate=!1),Xe.isSpriteMaterial&&On.setValue(V,"center",Ye.center),On.setValue(V,"modelViewMatrix",Ye.modelViewMatrix),On.setValue(V,"normalMatrix",Ye.normalMatrix),On.setValue(V,"modelMatrix",Ye.matrixWorld),Xe.isShaderMaterial||Xe.isRawShaderMaterial){const Zr=Xe.uniformsGroups;for(let sa=0,Ta=Zr.length;sa<Ta;sa++){const Wi=Zr[sa];Ie.update(Wi,Pn),Ie.bind(Wi,Pn)}}return Pn}function st(Ce,We){Ce.ambientLightColor.needsUpdate=We,Ce.lightProbe.needsUpdate=We,Ce.directionalLights.needsUpdate=We,Ce.directionalLightShadows.needsUpdate=We,Ce.pointLights.needsUpdate=We,Ce.pointLightShadows.needsUpdate=We,Ce.spotLights.needsUpdate=We,Ce.spotLightShadows.needsUpdate=We,Ce.rectAreaLights.needsUpdate=We,Ce.hemisphereLights.needsUpdate=We}function ht(Ce){return Ce.isMeshLambertMaterial||Ce.isMeshToonMaterial||Ce.isMeshPhongMaterial||Ce.isMeshStandardMaterial||Ce.isShadowMaterial||Ce.isShaderMaterial&&Ce.lights===!0}this.getActiveCubeFace=function(){return F},this.getActiveMipmapLevel=function(){return k},this.getRenderTarget=function(){return D},this.setRenderTargetTextures=function(Ce,We,Je){const Xe=pe.get(Ce);Xe.__autoAllocateDepthBuffer=Ce.resolveDepthBuffer===!1,Xe.__autoAllocateDepthBuffer===!1&&(Xe.__useRenderToTexture=!1),pe.get(Ce.texture).__webglTexture=We,pe.get(Ce.depthTexture).__webglTexture=Xe.__autoAllocateDepthBuffer?void 0:Je,Xe.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(Ce,We){const Je=pe.get(Ce);Je.__webglFramebuffer=We,Je.__useDefaultFramebuffer=We===void 0};const rt=V.createFramebuffer();this.setRenderTarget=function(Ce,We=0,Je=0){D=Ce,F=We,k=Je;let Xe=!0,Ye=null,St=!1,et=!1;if(Ce){const bt=pe.get(Ce);if(bt.__useDefaultFramebuffer!==void 0)se.bindFramebuffer(V.FRAMEBUFFER,null),Xe=!1;else if(bt.__webglFramebuffer===void 0)de.setupRenderTarget(Ce);else if(bt.__hasExternalTextures)de.rebindTextures(Ce,pe.get(Ce.texture).__webglTexture,pe.get(Ce.depthTexture).__webglTexture);else if(Ce.depthBuffer){const Et=Ce.depthTexture;if(bt.__boundDepthTexture!==Et){if(Et!==null&&pe.has(Et)&&(Ce.width!==Et.image.width||Ce.height!==Et.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");de.setupDepthRenderbuffer(Ce)}}const Ve=Ce.texture;(Ve.isData3DTexture||Ve.isDataArrayTexture||Ve.isCompressedArrayTexture)&&(et=!0);const gt=pe.get(Ce).__webglFramebuffer;Ce.isWebGLCubeRenderTarget?(Array.isArray(gt[We])?Ye=gt[We][Je]:Ye=gt[We],St=!0):Ce.samples>0&&de.useMultisampledRTT(Ce)===!1?Ye=pe.get(Ce).__webglMultisampledFramebuffer:Array.isArray(gt)?Ye=gt[Je]:Ye=gt,X.copy(Ce.viewport),L.copy(Ce.scissor),ne=Ce.scissorTest}else X.copy(ce).multiplyScalar(oe).floor(),L.copy(xe).multiplyScalar(oe).floor(),ne=Ne;if(Je!==0&&(Ye=rt),se.bindFramebuffer(V.FRAMEBUFFER,Ye)&&Xe&&se.drawBuffers(Ce,Ye),se.viewport(X),se.scissor(L),se.setScissorTest(ne),St){const bt=pe.get(Ce.texture);V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_CUBE_MAP_POSITIVE_X+We,bt.__webglTexture,Je)}else if(et){const bt=We;for(let Ve=0;Ve<Ce.textures.length;Ve++){const gt=pe.get(Ce.textures[Ve]);V.framebufferTextureLayer(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0+Ve,gt.__webglTexture,Je,bt)}}else if(Ce!==null&&Je!==0){const bt=pe.get(Ce.texture);V.framebufferTexture2D(V.FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_2D,bt.__webglTexture,Je)}H=-1},this.readRenderTargetPixels=function(Ce,We,Je,Xe,Ye,St,et,jt=0){if(!(Ce&&Ce.isWebGLRenderTarget)){ni("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let bt=pe.get(Ce).__webglFramebuffer;if(Ce.isWebGLCubeRenderTarget&&et!==void 0&&(bt=bt[et]),bt){se.bindFramebuffer(V.FRAMEBUFFER,bt);try{const Ve=Ce.textures[jt],gt=Ve.format,Et=Ve.type;if(!J.textureFormatReadable(gt)){ni("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!J.textureTypeReadable(Et)){ni("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}We>=0&&We<=Ce.width-Xe&&Je>=0&&Je<=Ce.height-Ye&&(Ce.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+jt),V.readPixels(We,Je,Xe,Ye,tt.convert(gt),tt.convert(Et),St))}finally{const Ve=D!==null?pe.get(D).__webglFramebuffer:null;se.bindFramebuffer(V.FRAMEBUFFER,Ve)}}},this.readRenderTargetPixelsAsync=async function(Ce,We,Je,Xe,Ye,St,et,jt=0){if(!(Ce&&Ce.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let bt=pe.get(Ce).__webglFramebuffer;if(Ce.isWebGLCubeRenderTarget&&et!==void 0&&(bt=bt[et]),bt)if(We>=0&&We<=Ce.width-Xe&&Je>=0&&Je<=Ce.height-Ye){se.bindFramebuffer(V.FRAMEBUFFER,bt);const Ve=Ce.textures[jt],gt=Ve.format,Et=Ve.type;if(!J.textureFormatReadable(gt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!J.textureTypeReadable(Et))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Gt=V.createBuffer();V.bindBuffer(V.PIXEL_PACK_BUFFER,Gt),V.bufferData(V.PIXEL_PACK_BUFFER,St.byteLength,V.STREAM_READ),Ce.textures.length>1&&V.readBuffer(V.COLOR_ATTACHMENT0+jt),V.readPixels(We,Je,Xe,Ye,tt.convert(gt),tt.convert(Et),0);const on=D!==null?pe.get(D).__webglFramebuffer:null;se.bindFramebuffer(V.FRAMEBUFFER,on);const fn=V.fenceSync(V.SYNC_GPU_COMMANDS_COMPLETE,0);return V.flush(),await Tve(V,fn,4),V.bindBuffer(V.PIXEL_PACK_BUFFER,Gt),V.getBufferSubData(V.PIXEL_PACK_BUFFER,0,St),V.deleteBuffer(Gt),V.deleteSync(fn),St}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(Ce,We=null,Je=0){const Xe=Math.pow(2,-Je),Ye=Math.floor(Ce.image.width*Xe),St=Math.floor(Ce.image.height*Xe),et=We!==null?We.x:0,jt=We!==null?We.y:0;de.setTexture2D(Ce,0),V.copyTexSubImage2D(V.TEXTURE_2D,Je,0,0,et,jt,Ye,St),se.unbindTexture()};const Le=V.createFramebuffer(),Oe=V.createFramebuffer();this.copyTextureToTexture=function(Ce,We,Je=null,Xe=null,Ye=0,St=null){St===null&&(Ye!==0?(K0("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),St=Ye,Ye=0):St=0);let et,jt,bt,Ve,gt,Et,Gt,on,fn;const Ln=Ce.isCompressedTexture?Ce.mipmaps[St]:Ce.image;if(Je!==null)et=Je.max.x-Je.min.x,jt=Je.max.y-Je.min.y,bt=Je.isBox3?Je.max.z-Je.min.z:1,Ve=Je.min.x,gt=Je.min.y,Et=Je.isBox3?Je.min.z:0;else{const ua=Math.pow(2,-Ye);et=Math.floor(Ln.width*ua),jt=Math.floor(Ln.height*ua),Ce.isDataArrayTexture?bt=Ln.depth:Ce.isData3DTexture?bt=Math.floor(Ln.depth*ua):bt=1,Ve=0,gt=0,Et=0}Xe!==null?(Gt=Xe.x,on=Xe.y,fn=Xe.z):(Gt=0,on=0,fn=0);const yn=tt.convert(We.format),hn=tt.convert(We.type);let xn;We.isData3DTexture?(de.setTexture3D(We,0),xn=V.TEXTURE_3D):We.isDataArrayTexture||We.isCompressedArrayTexture?(de.setTexture2DArray(We,0),xn=V.TEXTURE_2D_ARRAY):(de.setTexture2D(We,0),xn=V.TEXTURE_2D),V.pixelStorei(V.UNPACK_FLIP_Y_WEBGL,We.flipY),V.pixelStorei(V.UNPACK_PREMULTIPLY_ALPHA_WEBGL,We.premultiplyAlpha),V.pixelStorei(V.UNPACK_ALIGNMENT,We.unpackAlignment);const Nn=V.getParameter(V.UNPACK_ROW_LENGTH),Pn=V.getParameter(V.UNPACK_IMAGE_HEIGHT),Nr=V.getParameter(V.UNPACK_SKIP_PIXELS),Sn=V.getParameter(V.UNPACK_SKIP_ROWS),Pa=V.getParameter(V.UNPACK_SKIP_IMAGES);V.pixelStorei(V.UNPACK_ROW_LENGTH,Ln.width),V.pixelStorei(V.UNPACK_IMAGE_HEIGHT,Ln.height),V.pixelStorei(V.UNPACK_SKIP_PIXELS,Ve),V.pixelStorei(V.UNPACK_SKIP_ROWS,gt),V.pixelStorei(V.UNPACK_SKIP_IMAGES,Et);const On=Ce.isDataArrayTexture||Ce.isData3DTexture,ya=We.isDataArrayTexture||We.isData3DTexture;if(Ce.isDepthTexture){const ua=pe.get(Ce),Zr=pe.get(We),sa=pe.get(ua.__renderTarget),Ta=pe.get(Zr.__renderTarget);se.bindFramebuffer(V.READ_FRAMEBUFFER,sa.__webglFramebuffer),se.bindFramebuffer(V.DRAW_FRAMEBUFFER,Ta.__webglFramebuffer);for(let Wi=0;Wi<bt;Wi++)On&&(V.framebufferTextureLayer(V.READ_FRAMEBUFFER,V.COLOR_ATTACHMENT0,pe.get(Ce).__webglTexture,Ye,Et+Wi),V.framebufferTextureLayer(V.DRAW_FRAMEBUFFER,V.COLOR_ATTACHMENT0,pe.get(We).__webglTexture,St,fn+Wi)),V.blitFramebuffer(Ve,gt,et,jt,Gt,on,et,jt,V.DEPTH_BUFFER_BIT,V.NEAREST);se.bindFramebuffer(V.READ_FRAMEBUFFER,null),se.bindFramebuffer(V.DRAW_FRAMEBUFFER,null)}else if(Ye!==0||Ce.isRenderTargetTexture||pe.has(Ce)){const ua=pe.get(Ce),Zr=pe.get(We);se.bindFramebuffer(V.READ_FRAMEBUFFER,Le),se.bindFramebuffer(V.DRAW_FRAMEBUFFER,Oe);for(let sa=0;sa<bt;sa++)On?V.framebufferTextureLayer(V.READ_FRAMEBUFFER,V.COLOR_ATTACHMENT0,ua.__webglTexture,Ye,Et+sa):V.framebufferTexture2D(V.READ_FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_2D,ua.__webglTexture,Ye),ya?V.framebufferTextureLayer(V.DRAW_FRAMEBUFFER,V.COLOR_ATTACHMENT0,Zr.__webglTexture,St,fn+sa):V.framebufferTexture2D(V.DRAW_FRAMEBUFFER,V.COLOR_ATTACHMENT0,V.TEXTURE_2D,Zr.__webglTexture,St),Ye!==0?V.blitFramebuffer(Ve,gt,et,jt,Gt,on,et,jt,V.COLOR_BUFFER_BIT,V.NEAREST):ya?V.copyTexSubImage3D(xn,St,Gt,on,fn+sa,Ve,gt,et,jt):V.copyTexSubImage2D(xn,St,Gt,on,Ve,gt,et,jt);se.bindFramebuffer(V.READ_FRAMEBUFFER,null),se.bindFramebuffer(V.DRAW_FRAMEBUFFER,null)}else ya?Ce.isDataTexture||Ce.isData3DTexture?V.texSubImage3D(xn,St,Gt,on,fn,et,jt,bt,yn,hn,Ln.data):We.isCompressedArrayTexture?V.compressedTexSubImage3D(xn,St,Gt,on,fn,et,jt,bt,yn,Ln.data):V.texSubImage3D(xn,St,Gt,on,fn,et,jt,bt,yn,hn,Ln):Ce.isDataTexture?V.texSubImage2D(V.TEXTURE_2D,St,Gt,on,et,jt,yn,hn,Ln.data):Ce.isCompressedTexture?V.compressedTexSubImage2D(V.TEXTURE_2D,St,Gt,on,Ln.width,Ln.height,yn,Ln.data):V.texSubImage2D(V.TEXTURE_2D,St,Gt,on,et,jt,yn,hn,Ln);V.pixelStorei(V.UNPACK_ROW_LENGTH,Nn),V.pixelStorei(V.UNPACK_IMAGE_HEIGHT,Pn),V.pixelStorei(V.UNPACK_SKIP_PIXELS,Nr),V.pixelStorei(V.UNPACK_SKIP_ROWS,Sn),V.pixelStorei(V.UNPACK_SKIP_IMAGES,Pa),St===0&&We.generateMipmaps&&V.generateMipmap(xn),se.unbindTexture()},this.initRenderTarget=function(Ce){pe.get(Ce).__webglFramebuffer===void 0&&de.setupRenderTarget(Ce)},this.initTexture=function(Ce){Ce.isCubeTexture?de.setTextureCube(Ce,0):Ce.isData3DTexture?de.setTexture3D(Ce,0):Ce.isDataArrayTexture||Ce.isCompressedArrayTexture?de.setTexture2DArray(Ce,0):de.setTexture2D(Ce,0),se.unbindTexture()},this.resetState=function(){F=0,k=0,D=null,se.reset(),te.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return wd}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=Tr._getDrawingBufferColorSpace(e),n.unpackColorSpace=Tr._getUnpackColorSpace()}};const O6={type:"change"},WO={type:"start"},OZ={type:"end"},r1=new BO,I6=new fh,oke=Math.cos(70*jve.DEG2RAD),wi=new Tt,wo=2*Math.PI,Kr={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},QM=1e-6;class lke extends y0e{constructor(e,n=null){super(e,n),this.state=Kr.NONE,this.target=new Tt,this.cursor=new Tt,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:mx.ROTATE,MIDDLE:mx.DOLLY,RIGHT:mx.PAN},this.touches={ONE:rx.ROTATE,TWO:rx.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new Tt,this._lastQuaternion=new eg,this._lastTargetPosition=new Tt,this._quat=new eg().setFromUnitVectors(e.up,new Tt(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new m6,this._sphericalDelta=new m6,this._scale=1,this._panOffset=new Tt,this._rotateStart=new ar,this._rotateEnd=new ar,this._rotateDelta=new ar,this._panStart=new ar,this._panEnd=new ar,this._panDelta=new ar,this._dollyStart=new ar,this._dollyEnd=new ar,this._dollyDelta=new ar,this._dollyDirection=new Tt,this._mouse=new ar,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=dke.bind(this),this._onPointerDown=cke.bind(this),this._onPointerUp=uke.bind(this),this._onContextMenu=xke.bind(this),this._onMouseWheel=pke.bind(this),this._onKeyDown=fke.bind(this),this._onTouchStart=gke.bind(this),this._onTouchMove=bke.bind(this),this._onMouseDown=mke.bind(this),this._onMouseMove=hke.bind(this),this._interceptControlDown=yke.bind(this),this._interceptControlUp=vke.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(O6),this.update(),this.state=Kr.NONE}update(e=null){const n=this.object.position;wi.copy(n).sub(this.target),wi.applyQuaternion(this._quat),this._spherical.setFromVector3(wi),this.autoRotate&&this.state===Kr.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,i=this.maxAzimuthAngle;isFinite(r)&&isFinite(i)&&(r<-Math.PI?r+=wo:r>Math.PI&&(r-=wo),i<-Math.PI?i+=wo:i>Math.PI&&(i-=wo),r<=i?this._spherical.theta=Math.max(r,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+i)/2?Math.max(r,this._spherical.theta):Math.min(i,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(wi.setFromSpherical(this._spherical),wi.applyQuaternion(this._quatInverse),n.copy(this.target).add(wi),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=wi.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 Tt(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 d=new Tt(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(l),this.object.updateMatrixWorld(),o=wi.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):(r1.origin.copy(this.object.position),r1.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(r1.direction))<oke?this.object.lookAt(this.target):(I6.setFromNormalAndCoplanarPoint(this.object.up,this.target),r1.intersectPlane(I6,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)>QM||8*(1-this._lastQuaternion.dot(this.object.quaternion))>QM||this._lastTargetPosition.distanceToSquared(this.target)>QM?(this.dispatchEvent(O6),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?wo/60*this.autoRotateSpeed*e:wo/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){wi.setFromMatrixColumn(n,0),wi.multiplyScalar(-e),this._panOffset.add(wi)}_panUp(e,n){this.screenSpacePanning===!0?wi.setFromMatrixColumn(n,1):(wi.setFromMatrixColumn(n,0),wi.crossVectors(this.object.up,wi)),wi.multiplyScalar(e),this._panOffset.add(wi)}_pan(e,n){const r=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;wi.copy(i).sub(this.target);let s=wi.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(),i=e-r.left,s=n-r.top,o=r.width,l=r.height;this._mouse.x=i/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(wo*this._rotateDelta.x/n.clientHeight),this._rotateUp(wo*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(wo*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(-wo*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(wo*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(-wo*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),i=.5*(e.pageY+n.y);this._rotateStart.set(r,i)}}_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),i=.5*(e.pageY+n.y);this._panStart.set(r,i)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),r=e.pageX-n.x,i=e.pageY-n.y,s=Math.sqrt(r*r+i*i);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),i=.5*(e.pageX+r.x),s=.5*(e.pageY+r.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(wo*this._rotateDelta.x/n.clientHeight),this._rotateUp(wo*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),i=.5*(e.pageY+n.y);this._panEnd.set(r,i)}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,i=e.pageY-n.y,s=Math.sqrt(r*r+i*i);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 ar,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 cke(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 dke(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function uke(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(OZ),this.state=Kr.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 mke(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 mx.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=Kr.DOLLY;break;case mx.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Kr.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Kr.ROTATE}break;case mx.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Kr.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Kr.PAN}break;default:this.state=Kr.NONE}this.state!==Kr.NONE&&this.dispatchEvent(WO)}function hke(t){switch(this.state){case Kr.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case Kr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case Kr.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function pke(t){this.enabled===!1||this.enableZoom===!1||this.state!==Kr.NONE||(t.preventDefault(),this.dispatchEvent(WO),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(OZ))}function fke(t){this.enabled!==!1&&this._handleKeyDown(t)}function gke(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case rx.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=Kr.TOUCH_ROTATE;break;case rx.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=Kr.TOUCH_PAN;break;default:this.state=Kr.NONE}break;case 2:switch(this.touches.TWO){case rx.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=Kr.TOUCH_DOLLY_PAN;break;case rx.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=Kr.TOUCH_DOLLY_ROTATE;break;default:this.state=Kr.NONE}break;default:this.state=Kr.NONE}this.state!==Kr.NONE&&this.dispatchEvent(WO)}function bke(t){switch(this._trackPointer(t),this.state){case Kr.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case Kr.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case Kr.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case Kr.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=Kr.NONE}}function xke(t){this.enabled!==!1&&t.preventDefault()}function yke(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function vke(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function wke(t,e=!1){const n=t[0].index!==null,r=new Set(Object.keys(t[0].attributes)),i=new Set(Object.keys(t[0].morphAttributes)),s={},o={},l=t[0].morphTargetsRelative,c=new sc;let d=0;for(let u=0;u<t.length;++u){const m=t[u];let p=0;if(n!==(m.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const f in m.attributes){if(!r.has(f))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+'. All geometries must have compatible attributes; make sure "'+f+'" attribute exists among all geometries, or in none of them.'),null;s[f]===void 0&&(s[f]=[]),s[f].push(m.attributes[f]),p++}if(p!==r.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". Make sure all geometries have the same number of attributes."),null;if(l!==m.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const f in m.morphAttributes){if(!i.has(f))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". .morphAttributes must be consistent throughout all geometries."),null;o[f]===void 0&&(o[f]=[]),o[f].push(m.morphAttributes[f])}if(e){let f;if(n)f=m.index.count;else if(m.attributes.position!==void 0)f=m.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+u+". The geometry must have either an index or a position attribute"),null;c.addGroup(d,f,u),d+=f}}if(n){let u=0;const m=[];for(let p=0;p<t.length;++p){const f=t[p].index;for(let x=0;x<f.count;++x)m.push(f.getX(x)+u);u+=t[p].attributes.position.count}c.setIndex(m)}for(const u in s){const m=z6(s[u]);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+u+" attribute."),null;c.setAttribute(u,m)}for(const u in o){const m=o[u][0].length;if(m===0)break;c.morphAttributes=c.morphAttributes||{},c.morphAttributes[u]=[];for(let p=0;p<m;++p){const f=[];for(let v=0;v<o[u].length;++v)f.push(o[u][v][p]);const x=z6(f);if(!x)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+u+" morphAttribute."),null;c.morphAttributes[u].push(x)}}return c}function z6(t){let e,n,r,i=-1,s=0;for(let d=0;d<t.length;++d){const u=t[d];if(e===void 0&&(e=u.array.constructor),e!==u.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=u.itemSize),n!==u.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(r===void 0&&(r=u.normalized),r!==u.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(i===-1&&(i=u.gpuType),i!==u.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=u.count*n}const o=new e(s),l=new Zs(o,n,r);let c=0;for(let d=0;d<t.length;++d){const u=t[d];if(u.isInterleavedBufferAttribute){const m=c/n;for(let p=0,f=u.count;p<f;p++)for(let x=0;x<n;x++){const v=u.getComponent(p,x);l.setComponent(p+m,x,v)}}else o.set(u.array,c);c+=u.count*n}return i!==void 0&&(l.gpuType=i),l}class Ske extends GO{constructor(e){super(e)}load(e,n,r,i){const s=this,o=new h0e(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){i?i(c):console.error(c),s.manager.itemError(e)}},r,i)}parse(e){function n(d){const u=new DataView(d),m=32/8*3+32/8*3*3+16/8,p=u.getUint32(80,!0);if(80+32/8+p*m===u.byteLength)return!0;const x=[115,111,108,105,100];for(let v=0;v<5;v++)if(r(x,u,v))return!1;return!0}function r(d,u,m){for(let p=0,f=d.length;p<f;p++)if(d[p]!==u.getUint8(m+p))return!1;return!0}function i(d){const u=new DataView(d),m=u.getUint32(80,!0);let p,f,x,v=!1,g,b,_,C,P;for(let H=0;H<70;H++)u.getUint32(H,!1)==1129270351&&u.getUint8(H+4)==82&&u.getUint8(H+5)==61&&(v=!0,g=new Float32Array(m*3*3),b=u.getUint8(H+6)/255,_=u.getUint8(H+7)/255,C=u.getUint8(H+8)/255,P=u.getUint8(H+9)/255);const N=84,A=50,T=new sc,F=new Float32Array(m*3*3),k=new Float32Array(m*3*3),D=new lr;for(let H=0;H<m;H++){const z=N+H*A,X=u.getFloat32(z,!0),L=u.getFloat32(z+4,!0),ne=u.getFloat32(z+8,!0);if(v){const ie=u.getUint16(z+48,!0);(ie&32768)===0?(p=(ie&31)/31,f=(ie>>5&31)/31,x=(ie>>10&31)/31):(p=b,f=_,x=C)}for(let ie=1;ie<=3;ie++){const ee=z+ie*12,ue=H*3*3+(ie-1)*3;F[ue]=u.getFloat32(ee,!0),F[ue+1]=u.getFloat32(ee+4,!0),F[ue+2]=u.getFloat32(ee+8,!0),k[ue]=X,k[ue+1]=L,k[ue+2]=ne,v&&(D.setRGB(p,f,x,Zo),g[ue]=D.r,g[ue+1]=D.g,g[ue+2]=D.b)}}return T.setAttribute("position",new Zs(F,3)),T.setAttribute("normal",new Zs(k,3)),v&&(T.setAttribute("color",new Zs(g,3)),T.hasColors=!0,T.alpha=P),T}function s(d){const u=new sc,m=/solid([\s\S]*?)endsolid/g,p=/facet([\s\S]*?)endfacet/g,f=/solid\s(.+)/;let x=0;const v=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,g=new RegExp("vertex"+v+v+v,"g"),b=new RegExp("normal"+v+v+v,"g"),_=[],C=[],P=[],N=new Tt;let A,T=0,F=0,k=0;for(;(A=m.exec(d))!==null;){F=k;const D=A[0],H=(A=f.exec(D))!==null?A[1]:"";for(P.push(H);(A=p.exec(D))!==null;){let L=0,ne=0;const ie=A[0];for(;(A=b.exec(ie))!==null;)N.x=parseFloat(A[1]),N.y=parseFloat(A[2]),N.z=parseFloat(A[3]),ne++;for(;(A=g.exec(ie))!==null;)_.push(parseFloat(A[1]),parseFloat(A[2]),parseFloat(A[3])),C.push(N.x,N.y,N.z),L++,k++;ne!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+x),L!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+x),x++}const z=F,X=k-F;u.userData.groupNames=P,u.addGroup(z,X,T),T++}return u.setAttribute("position",new sl(_,3)),u.setAttribute("normal",new sl(C,3)),u}function o(d){return typeof d!="string"?new TextDecoder().decode(d):d}function l(d){if(typeof d=="string"){const u=new Uint8Array(d.length);for(let m=0;m<d.length;m++)u[m]=d.charCodeAt(m)&255;return u.buffer||u}else return d}const c=l(e);return n(c)?i(c):s(o(e))}}function a1(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 ZM={exports:{}};var U6;function _ke(){return U6||(U6=1,(function(t,e){(function(n){t.exports=n()})(function(){return(function n(r,i,s){function o(d,u){if(!i[d]){if(!r[d]){var m=typeof a1=="function"&&a1;if(!u&&m)return m(d,!0);if(l)return l(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var f=i[d]={exports:{}};r[d][0].call(f.exports,function(x){var v=r[d][1][x];return o(v||x)},f,f.exports,n,r,i,s)}return i[d].exports}for(var l=typeof a1=="function"&&a1,c=0;c<s.length;c++)o(s[c]);return o})({1:[function(n,r,i){var s=n("./utils"),o=n("./support"),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(c){for(var d,u,m,p,f,x,v,g=[],b=0,_=c.length,C=_,P=s.getTypeOf(c)!=="string";b<c.length;)C=_-b,m=P?(d=c[b++],u=b<_?c[b++]:0,b<_?c[b++]:0):(d=c.charCodeAt(b++),u=b<_?c.charCodeAt(b++):0,b<_?c.charCodeAt(b++):0),p=d>>2,f=(3&d)<<4|u>>4,x=1<C?(15&u)<<2|m>>6:64,v=2<C?63&m:64,g.push(l.charAt(p)+l.charAt(f)+l.charAt(x)+l.charAt(v));return g.join("")},i.decode=function(c){var d,u,m,p,f,x,v=0,g=0,b="data:";if(c.substr(0,b.length)===b)throw new Error("Invalid base64 input, it looks like a data url.");var _,C=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===l.charAt(64)&&C--,c.charAt(c.length-2)===l.charAt(64)&&C--,C%1!=0)throw new Error("Invalid base64 input, bad content length.");for(_=o.uint8array?new Uint8Array(0|C):new Array(0|C);v<c.length;)d=l.indexOf(c.charAt(v++))<<2|(p=l.indexOf(c.charAt(v++)))>>4,u=(15&p)<<4|(f=l.indexOf(c.charAt(v++)))>>2,m=(3&f)<<6|(x=l.indexOf(c.charAt(v++))),_[g++]=d,f!==64&&(_[g++]=u),x!==64&&(_[g++]=m);return _}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),l=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,m,p,f,x){this.compressedSize=u,this.uncompressedSize=m,this.crc32=p,this.compression=f,this.compressedContent=x}d.prototype={getContentWorker:function(){var u=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),m=this;return u.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},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)}},d.createWorkerFrom=function(u,m,p){return u.pipe(new l).pipe(new c("uncompressedSize")).pipe(m.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=(function(){for(var l,c=[],d=0;d<256;d++){l=d;for(var u=0;u<8;u++)l=1&l?3988292384^l>>>1:l>>>1;c[d]=l}return c})();r.exports=function(l,c){return l!==void 0&&l.length?s.getTypeOf(l)!=="string"?(function(d,u,m,p){var f=o,x=p+m;d^=-1;for(var v=p;v<x;v++)d=d>>>8^f[255&(d^u[v])];return-1^d})(0|c,l,l.length,0):(function(d,u,m,p){var f=o,x=p+m;d^=-1;for(var v=p;v<x;v++)d=d>>>8^f[255&(d^u.charCodeAt(v))];return-1^d})(0|c,l,l.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),l=n("./utils"),c=n("./stream/GenericWorker"),d=s?"uint8array":"array";function u(m,p){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=p,this.meta={}}i.magic="\b\0",l.inherits(u,c),u.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(l.transformTo(d,m.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(p){m.push({data:p,meta:m.meta})}},i.compressWorker=function(m){return new u("Deflate",m)},i.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(f,x){var v,g="";for(v=0;v<x;v++)g+=String.fromCharCode(255&f),f>>>=8;return g}function o(f,x,v,g,b,_){var C,P,N=f.file,A=f.compression,T=_!==d.utf8encode,F=l.transformTo("string",_(N.name)),k=l.transformTo("string",d.utf8encode(N.name)),D=N.comment,H=l.transformTo("string",_(D)),z=l.transformTo("string",d.utf8encode(D)),X=k.length!==N.name.length,L=z.length!==D.length,ne="",ie="",ee="",ue=N.dir,le=N.date,oe={crc32:0,compressedSize:0,uncompressedSize:0};x&&!v||(oe.crc32=f.crc32,oe.compressedSize=f.compressedSize,oe.uncompressedSize=f.uncompressedSize);var W=0;x&&(W|=8),T||!X&&!L||(W|=2048);var re=0,ce=0;ue&&(re|=16),b==="UNIX"?(ce=798,re|=(function(Ne,$){var Y=Ne;return Ne||(Y=$?16893:33204),(65535&Y)<<16})(N.unixPermissions,ue)):(ce=20,re|=(function(Ne){return 63&(Ne||0)})(N.dosPermissions)),C=le.getUTCHours(),C<<=6,C|=le.getUTCMinutes(),C<<=5,C|=le.getUTCSeconds()/2,P=le.getUTCFullYear()-1980,P<<=4,P|=le.getUTCMonth()+1,P<<=5,P|=le.getUTCDate(),X&&(ie=s(1,1)+s(u(F),4)+k,ne+="up"+s(ie.length,2)+ie),L&&(ee=s(1,1)+s(u(H),4)+z,ne+="uc"+s(ee.length,2)+ee);var xe="";return xe+=`
- \0`,xe+=s(W,2),xe+=A.magic,xe+=s(C,2),xe+=s(P,2),xe+=s(oe.crc32,4),xe+=s(oe.compressedSize,4),xe+=s(oe.uncompressedSize,4),xe+=s(F.length,2),xe+=s(ne.length,2),{fileRecord:m.LOCAL_FILE_HEADER+xe+F+ne,dirRecord:m.CENTRAL_FILE_HEADER+s(ce,2)+xe+s(H.length,2)+"\0\0\0\0"+s(re,4)+s(g,4)+F+ne+H}}var l=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),m=n("../signature");function p(f,x,v,g){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=v,this.encodeFileName=g,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(p,c),p.prototype.push=function(f){var x=f.meta.percent||0,v=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:v?(x+100*(v-g-1))/v:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var x=this.streamFiles&&!f.file.dir;if(x){var v=o(f,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var x=this.streamFiles&&!f.file.dir,v=o(f,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),x)this.push({data:(function(g){return m.DATA_DESCRIPTOR+s(g.crc32,4)+s(g.compressedSize,4)+s(g.uncompressedSize,4)})(f),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,x=0;x<this.dirRecords.length;x++)this.push({data:this.dirRecords[x],meta:{percent:100}});var v=this.bytesWritten-f,g=(function(b,_,C,P,N){var A=l.transformTo("string",N(P));return m.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(b,2)+s(b,2)+s(_,4)+s(C,4)+s(A.length,2)+A})(this.dirRecords.length,v,f,this.zipComment,this.encodeFileName);this.push({data:g,meta:{percent:100}})},p.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},p.prototype.registerPrevious=function(f){this._sources.push(f);var x=this;return f.on("data",function(v){x.processChunk(v)}),f.on("end",function(){x.closedSource(x.previous.streamInfo),x._sources.length?x.prepareNextSource():x.end()}),f.on("error",function(v){x.error(v)}),this},p.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))},p.prototype.error=function(f){var x=this._sources;if(!c.prototype.error.call(this,f))return!1;for(var v=0;v<x.length;v++)try{x[v].error(f)}catch{}return!0},p.prototype.lock=function(){c.prototype.lock.call(this);for(var f=this._sources,x=0;x<f.length;x++)f[x].lock()},r.exports=p},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,r,i){var s=n("../compressions"),o=n("./ZipFileWorker");i.generateWorker=function(l,c,d){var u=new o(c.streamFiles,d,c.platform,c.encodeFileName),m=0;try{l.forEach(function(p,f){m++;var x=(function(_,C){var P=_||C,N=s[P];if(!N)throw new Error(P+" is not a valid compression method !");return N})(f.options.compression,c.compression),v=f.options.compressionOptions||c.compressionOptions||{},g=f.dir,b=f.date;f._compressWorker(x,v).withStreamInfo("file",{name:p,dir:g,date:b,comment:f.comment||"",unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions}).pipe(u)}),u.entriesCount=m}catch(p){u.error(p)}return u}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,r,i){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,i){var s=n("./utils"),o=n("./external"),l=n("./utf8"),c=n("./zipEntries"),d=n("./stream/Crc32Probe"),u=n("./nodejsUtils");function m(p){return new o.Promise(function(f,x){var v=p.decompressed.getContentWorker().pipe(new d);v.on("error",function(g){x(g)}).on("end",function(){v.streamInfo.crc32!==p.decompressed.crc32?x(new Error("Corrupted zip : CRC32 mismatch")):f()}).resume()})}r.exports=function(p,f){var x=this;return f=s.extend(f||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:l.utf8decode}),u.isNode&&u.isStream(p)?o.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):s.prepareContent("the loaded zip file",p,!0,f.optimizedBinaryString,f.base64).then(function(v){var g=new c(f);return g.load(v),g}).then(function(v){var g=[o.Promise.resolve(v)],b=v.files;if(f.checkCRC32)for(var _=0;_<b.length;_++)g.push(m(b[_]));return o.Promise.all(g)}).then(function(v){for(var g=v.shift(),b=g.files,_=0;_<b.length;_++){var C=b[_],P=C.fileNameStr,N=s.resolve(C.fileNameStr);x.file(N,C.decompressed,{binary:!0,optimizedBinaryString:!0,date:C.date,dir:C.dir,comment:C.fileCommentStr.length?C.fileCommentStr:null,unixPermissions:C.unixPermissions,dosPermissions:C.dosPermissions,createFolders:f.createFolders}),C.dir||(x.file(N).unsafeOriginalName=P)}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,i){var s=n("../utils"),o=n("../stream/GenericWorker");function l(c,d){o.call(this,"Nodejs stream input adapter for "+c),this._upstreamEnded=!1,this._bindStream(d)}s.inherits(l,o),l.prototype._bindStream=function(c){var d=this;(this._stream=c).pause(),c.on("data",function(u){d.push({data:u,meta:{percent:0}})}).on("error",function(u){d.isPaused?this.generatedError=u:d.error(u)}).on("end",function(){d.isPaused?d._upstreamEnded=!0:d.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,i){var s=n("readable-stream").Readable;function o(l,c,d){s.call(this,c),this._helper=l;var u=this;l.on("data",function(m,p){u.push(m)||u._helper.pause(),d&&d(p)}).on("error",function(m){u.emit("error",m)}).on("end",function(){u.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,i){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,i){function s(N,A,T){var F,k=l.getTypeOf(A),D=l.extend(T||{},u);D.date=D.date||new Date,D.compression!==null&&(D.compression=D.compression.toUpperCase()),typeof D.unixPermissions=="string"&&(D.unixPermissions=parseInt(D.unixPermissions,8)),D.unixPermissions&&16384&D.unixPermissions&&(D.dir=!0),D.dosPermissions&&16&D.dosPermissions&&(D.dir=!0),D.dir&&(N=b(N)),D.createFolders&&(F=g(N))&&_.call(this,F,!0);var H=k==="string"&&D.binary===!1&&D.base64===!1;T&&T.binary!==void 0||(D.binary=!H),(A instanceof m&&A.uncompressedSize===0||D.dir||!A||A.length===0)&&(D.base64=!1,D.binary=!0,A="",D.compression="STORE",k="string");var z=null;z=A instanceof m||A instanceof c?A:x.isNode&&x.isStream(A)?new v(N,A):l.prepareContent(N,A,D.binary,D.optimizedBinaryString,D.base64);var X=new p(N,z,D);this.files[N]=X}var o=n("./utf8"),l=n("./utils"),c=n("./stream/GenericWorker"),d=n("./stream/StreamHelper"),u=n("./defaults"),m=n("./compressedObject"),p=n("./zipObject"),f=n("./generate"),x=n("./nodejsUtils"),v=n("./nodejs/NodejsStreamInputAdapter"),g=function(N){N.slice(-1)==="/"&&(N=N.substring(0,N.length-1));var A=N.lastIndexOf("/");return 0<A?N.substring(0,A):""},b=function(N){return N.slice(-1)!=="/"&&(N+="/"),N},_=function(N,A){return A=A!==void 0?A:u.createFolders,N=b(N),this.files[N]||s.call(this,N,null,{dir:!0,createFolders:A}),this.files[N]};function C(N){return Object.prototype.toString.call(N)==="[object RegExp]"}var P={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(N){var A,T,F;for(A in this.files)F=this.files[A],(T=A.slice(this.root.length,A.length))&&A.slice(0,this.root.length)===this.root&&N(T,F)},filter:function(N){var A=[];return this.forEach(function(T,F){N(T,F)&&A.push(F)}),A},file:function(N,A,T){if(arguments.length!==1)return N=this.root+N,s.call(this,N,A,T),this;if(C(N)){var F=N;return this.filter(function(D,H){return!H.dir&&F.test(D)})}var k=this.files[this.root+N];return k&&!k.dir?k:null},folder:function(N){if(!N)return this;if(C(N))return this.filter(function(k,D){return D.dir&&N.test(k)});var A=this.root+N,T=_.call(this,A),F=this.clone();return F.root=T.name,F},remove:function(N){N=this.root+N;var A=this.files[N];if(A||(N.slice(-1)!=="/"&&(N+="/"),A=this.files[N]),A&&!A.dir)delete this.files[N];else for(var T=this.filter(function(k,D){return D.name.slice(0,N.length)===N}),F=0;F<T.length;F++)delete this.files[T[F].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(N){var A,T={};try{if((T=l.extend(N||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:o.utf8encode})).type=T.type.toLowerCase(),T.compression=T.compression.toUpperCase(),T.type==="binarystring"&&(T.type="string"),!T.type)throw new Error("No output type specified.");l.checkSupport(T.type),T.platform!=="darwin"&&T.platform!=="freebsd"&&T.platform!=="linux"&&T.platform!=="sunos"||(T.platform="UNIX"),T.platform==="win32"&&(T.platform="DOS");var F=T.comment||this.comment||"";A=f.generateWorker(this,T,F)}catch(k){(A=new c("error")).error(k)}return new d(A,T.type||"string",T.mimeType)},generateAsync:function(N,A){return this.generateInternalStream(N).accumulate(A)},generateNodeStream:function(N,A){return(N=N||{}).type||(N.type="nodebuffer"),this.generateInternalStream(N).toNodejsStream(A)}};r.exports=P},{"./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,i){r.exports=n("stream")},{stream:void 0}],17:[function(n,r,i){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),d=l.charCodeAt(1),u=l.charCodeAt(2),m=l.charCodeAt(3),p=this.length-4;0<=p;--p)if(this.data[p]===c&&this.data[p+1]===d&&this.data[p+2]===u&&this.data[p+3]===m)return p-this.zero;return-1},o.prototype.readAndCheckSignature=function(l){var c=l.charCodeAt(0),d=l.charCodeAt(1),u=l.charCodeAt(2),m=l.charCodeAt(3),p=this.readData(4);return c===p[0]&&d===p[1]&&u===p[2]&&m===p[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,i){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,d=0;for(this.checkOffset(l),c=this.index+l-1;c>=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=l,d},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,i){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,i){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,i){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,i){var s=n("../utils"),o=n("../support"),l=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(m){var p=s.getTypeOf(m);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new d(m):o.uint8array?new u(s.transformTo("uint8array",m)):new l(s.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){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,i){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,i){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 d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=l},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function l(c){o.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=s.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}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,d=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,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,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,i){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,i){var s=n("../utils"),o=n("./ConvertWorker"),l=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),m=null;if(d.nodestream)try{m=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(x,v){return new u.Promise(function(g,b){var _=[],C=x._internalType,P=x._outputType,N=x._mimeType;x.on("data",function(A,T){_.push(A),v&&v(T)}).on("error",function(A){_=[],b(A)}).on("end",function(){try{var A=(function(T,F,k){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",F),k);case"base64":return c.encode(F);default:return s.transformTo(T,F)}})(P,(function(T,F){var k,D=0,H=null,z=0;for(k=0;k<F.length;k++)z+=F[k].length;switch(T){case"string":return F.join("");case"array":return Array.prototype.concat.apply([],F);case"uint8array":for(H=new Uint8Array(z),k=0;k<F.length;k++)H.set(F[k],D),D+=F[k].length;return H;case"nodebuffer":return Buffer.concat(F);default:throw new Error("concat : unsupported type '"+T+"'")}})(C,_),N);g(A)}catch(T){b(T)}_=[]}).resume()})}function f(x,v,g){var b=v;switch(v){case"blob":case"arraybuffer":b="uint8array";break;case"base64":b="string"}try{this._internalType=b,this._outputType=v,this._mimeType=g,s.checkSupport(b),this._worker=x.pipe(new o(b)),x.lock()}catch(_){this._worker=new l("error"),this._worker.error(_)}}f.prototype={accumulate:function(x){return p(this,x)},on:function(x,v){var g=this;return x==="data"?this._worker.on(x,function(b){v.call(g,b.data,b.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 m(this,{objectMode:this._outputType!=="nodebuffer"},x)}},r.exports=f},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,r,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",i.nodebuffer=typeof Buffer<"u",i.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.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),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),l=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function m(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}i.utf8encode=function(f){return o.nodebuffer?l.newBufferFrom(f,"utf-8"):(function(x){var v,g,b,_,C,P=x.length,N=0;for(_=0;_<P;_++)(64512&(g=x.charCodeAt(_)))==55296&&_+1<P&&(64512&(b=x.charCodeAt(_+1)))==56320&&(g=65536+(g-55296<<10)+(b-56320),_++),N+=g<128?1:g<2048?2:g<65536?3:4;for(v=o.uint8array?new Uint8Array(N):new Array(N),_=C=0;C<N;_++)(64512&(g=x.charCodeAt(_)))==55296&&_+1<P&&(64512&(b=x.charCodeAt(_+1)))==56320&&(g=65536+(g-55296<<10)+(b-56320),_++),g<128?v[C++]=g:(g<2048?v[C++]=192|g>>>6:(g<65536?v[C++]=224|g>>>12:(v[C++]=240|g>>>18,v[C++]=128|g>>>12&63),v[C++]=128|g>>>6&63),v[C++]=128|63&g);return v})(f)},i.utf8decode=function(f){return o.nodebuffer?s.transformTo("nodebuffer",f).toString("utf-8"):(function(x){var v,g,b,_,C=x.length,P=new Array(2*C);for(v=g=0;v<C;)if((b=x[v++])<128)P[g++]=b;else if(4<(_=d[b]))P[g++]=65533,v+=_-1;else{for(b&=_===2?31:_===3?15:7;1<_&&v<C;)b=b<<6|63&x[v++],_--;1<_?P[g++]=65533:b<65536?P[g++]=b:(b-=65536,P[g++]=55296|b>>10&1023,P[g++]=56320|1023&b)}return P.length!==g&&(P.subarray?P=P.subarray(0,g):P.length=g),s.applyFromCharCode(P)})(f=s.transformTo(o.uint8array?"uint8array":"array",f))},s.inherits(m,c),m.prototype.processChunk=function(f){var x=s.transformTo(o.uint8array?"uint8array":"array",f.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(_,C){var P;for((C=C||_.length)>_.length&&(C=_.length),P=C-1;0<=P&&(192&_[P])==128;)P--;return P<0||P===0?C:P+d[_[P]]>C?P:C})(x),b=x;g!==x.length&&(o.uint8array?(b=x.subarray(0,g),this.leftOver=x.subarray(g,x.length)):(b=x.slice(0,g),this.leftOver=x.slice(g,x.length))),this.push({data:i.utf8decode(b),meta:f.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=m,s.inherits(p,c),p.prototype.processChunk=function(f){this.push({data:i.utf8encode(f.data),meta:f.meta})},i.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),l=n("./nodejsUtils"),c=n("./external");function d(v){return v}function u(v,g){for(var b=0;b<v.length;++b)g[b]=255&v.charCodeAt(b);return g}n("setimmediate"),i.newBlob=function(v,g){i.checkSupport("blob");try{return new Blob([v],{type:g})}catch{try{var b=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return b.append(v),b.getBlob(g)}catch{throw new Error("Bug : can't construct the Blob.")}}};var m={stringifyByChunk:function(v,g,b){var _=[],C=0,P=v.length;if(P<=b)return String.fromCharCode.apply(null,v);for(;C<P;)g==="array"||g==="nodebuffer"?_.push(String.fromCharCode.apply(null,v.slice(C,Math.min(C+b,P)))):_.push(String.fromCharCode.apply(null,v.subarray(C,Math.min(C+b,P)))),C+=b;return _.join("")},stringifyByChar:function(v){for(var g="",b=0;b<v.length;b++)g+=String.fromCharCode(v[b]);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 p(v){var g=65536,b=i.getTypeOf(v),_=!0;if(b==="uint8array"?_=m.applyCanBeUsed.uint8array:b==="nodebuffer"&&(_=m.applyCanBeUsed.nodebuffer),_)for(;1<g;)try{return m.stringifyByChunk(v,b,g)}catch{g=Math.floor(g/2)}return m.stringifyByChar(v)}function f(v,g){for(var b=0;b<v.length;b++)g[b]=v[b];return g}i.applyFromCharCode=p;var x={};x.string={string:d,array:function(v){return u(v,new Array(v.length))},arraybuffer:function(v){return x.string.uint8array(v).buffer},uint8array:function(v){return u(v,new Uint8Array(v.length))},nodebuffer:function(v){return u(v,l.allocBuffer(v.length))}},x.array={string:p,array:d,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 p(new Uint8Array(v))},array:function(v){return f(new Uint8Array(v),new Array(v.byteLength))},arraybuffer:d,uint8array:function(v){return new Uint8Array(v)},nodebuffer:function(v){return l.newBufferFrom(new Uint8Array(v))}},x.uint8array={string:p,array:function(v){return f(v,new Array(v.length))},arraybuffer:function(v){return v.buffer},uint8array:d,nodebuffer:function(v){return l.newBufferFrom(v)}},x.nodebuffer={string:p,array:function(v){return f(v,new Array(v.length))},arraybuffer:function(v){return x.nodebuffer.uint8array(v).buffer},uint8array:function(v){return f(v,new Uint8Array(v.length))},nodebuffer:d},i.transformTo=function(v,g){if(g=g||"",!v)return g;i.checkSupport(v);var b=i.getTypeOf(g);return x[b][v](g)},i.resolve=function(v){for(var g=v.split("/"),b=[],_=0;_<g.length;_++){var C=g[_];C==="."||C===""&&_!==0&&_!==g.length-1||(C===".."?b.pop():b.push(C))}return b.join("/")},i.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},i.checkSupport=function(v){if(!s[v.toLowerCase()])throw new Error(v+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(v){var g,b,_="";for(b=0;b<(v||"").length;b++)_+="\\x"+((g=v.charCodeAt(b))<16?"0":"")+g.toString(16).toUpperCase();return _},i.delay=function(v,g,b){setImmediate(function(){v.apply(b||null,g||[])})},i.inherits=function(v,g){function b(){}b.prototype=g.prototype,v.prototype=new b},i.extend=function(){var v,g,b={};for(v=0;v<arguments.length;v++)for(g in arguments[v])Object.prototype.hasOwnProperty.call(arguments[v],g)&&b[g]===void 0&&(b[g]=arguments[v][g]);return b},i.prepareContent=function(v,g,b,_,C){return c.Promise.resolve(g).then(function(P){return s.blob&&(P instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(P))!==-1)&&typeof FileReader<"u"?new c.Promise(function(N,A){var T=new FileReader;T.onload=function(F){N(F.target.result)},T.onerror=function(F){A(F.target.error)},T.readAsArrayBuffer(P)}):P}).then(function(P){var N=i.getTypeOf(P);return N?(N==="arraybuffer"?P=i.transformTo("uint8array",P):N==="string"&&(C?P=o.decode(P):b&&_!==!0&&(P=(function(A){return u(A,s.uint8array?new Uint8Array(A.length):new Array(A.length))})(P))),P):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,i){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./signature"),c=n("./zipEntry"),d=n("./support");function u(m){this.files=[],this.loadOptions=m}u.prototype={checkSignature:function(m){if(!this.reader.readAndCheckSignature(m)){this.reader.index-=4;var p=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+o.pretty(p)+", expected "+o.pretty(m)+")")}},isSignature:function(m,p){var f=this.reader.index;this.reader.setIndex(m);var x=this.reader.readString(4)===p;return this.reader.setIndex(f),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 m=this.reader.readData(this.zipCommentLength),p=d.uint8array?"uint8array":"array",f=o.transformTo(p,m);this.zipComment=this.loadOptions.decodeFileName(f)},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 m,p,f,x=this.zip64EndOfCentralSize-44;0<x;)m=this.reader.readInt(2),p=this.reader.readInt(4),f=this.reader.readData(p),this.zip64ExtensibleData[m]={id:m,length:p,value:f}},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 m,p;for(m=0;m<this.files.length;m++)p=this.files[m],this.reader.setIndex(p.localHeaderOffset),this.checkSignature(l.LOCAL_FILE_HEADER),p.readLocalPart(this.reader),p.handleUTF8(),p.processAttributes()},readCentralDir:function(){var m;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(l.CENTRAL_FILE_HEADER);)(m=new c({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(m);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 m=this.reader.lastIndexOfSignature(l.CENTRAL_DIRECTORY_END);if(m<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(m);var p=m;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,(m=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(m),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 f=this.centralDirOffset+this.centralDirSize;this.zip64&&(f+=20,f+=12+this.zip64EndOfCentralSize);var x=p-f;if(0<x)this.isSignature(p,l.CENTRAL_FILE_HEADER)||(this.reader.zero=x);else if(x<0)throw new Error("Corrupted zip: missing "+Math.abs(x)+" bytes.")},prepareReader:function(m){this.reader=s(m)},load:function(m){this.prepareReader(m),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},r.exports=u},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,r,i){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./compressedObject"),c=n("./crc32"),d=n("./utf8"),u=n("./compressions"),m=n("./support");function p(f,x){this.options=f,this.loadOptions=x}p.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(f){var x,v;if(f.skip(22),this.fileNameLength=f.readInt(2),v=f.readInt(2),this.fileName=f.readData(this.fileNameLength),f.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 b in u)if(Object.prototype.hasOwnProperty.call(u,b)&&u[b].magic===g)return u[b];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,f.readData(this.compressedSize))},readCentralPart:function(f){this.versionMadeBy=f.readInt(2),f.skip(2),this.bitFlag=f.readInt(2),this.compressionMethod=f.readString(2),this.date=f.readDate(),this.crc32=f.readInt(4),this.compressedSize=f.readInt(4),this.uncompressedSize=f.readInt(4);var x=f.readInt(2);if(this.extraFieldsLength=f.readInt(2),this.fileCommentLength=f.readInt(2),this.diskNumberStart=f.readInt(2),this.internalFileAttributes=f.readInt(2),this.externalFileAttributes=f.readInt(4),this.localHeaderOffset=f.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");f.skip(x),this.readExtraFields(f),this.parseZIP64ExtraField(f),this.fileComment=f.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var f=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var x,v,g,b=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4<b;)x=f.readInt(2),v=f.readInt(2),g=f.readData(v),this.extraFields[x]={id:x,length:v,value:g};f.setIndex(b)},handleUTF8:function(){var f=m.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=d.utf8decode(this.fileName),this.fileCommentStr=d.utf8decode(this.fileComment);else{var x=this.findExtraFieldUnicodePath();if(x!==null)this.fileNameStr=x;else{var v=o.transformTo(f,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var g=this.findExtraFieldUnicodeComment();if(g!==null)this.fileCommentStr=g;else{var b=o.transformTo(f,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(b)}}},findExtraFieldUnicodePath:function(){var f=this.extraFields[28789];if(f){var x=s(f.value);return x.readInt(1)!==1||c(this.fileName)!==x.readInt(4)?null:d.utf8decode(x.readData(f.length-5))}return null},findExtraFieldUnicodeComment:function(){var f=this.extraFields[25461];if(f){var x=s(f.value);return x.readInt(1)!==1||c(this.fileComment)!==x.readInt(4)?null:d.utf8decode(x.readData(f.length-5))}return null}},r.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,i){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"),d=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(x){var v=null,g="string";try{if(!x)throw new Error("No output type specified.");var b=(g=x.toLowerCase())==="string"||g==="text";g!=="binarystring"&&g!=="text"||(g="string"),v=this._decompressWorker();var _=!this._dataBinary;_&&!b&&(v=v.pipe(new c.Utf8EncodeWorker)),!_&&b&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(C){(v=new u("error")).error(C)}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 d&&this._data.compression.magic===x.magic)return this._data.getCompressedWorker();var g=this._decompressWorker();return this._dataBinary||(g=g.pipe(new c.Utf8EncodeWorker)),d.createWorkerFrom(g,x,v)},_decompressWorker:function(){return this._data instanceof d?this._data.getContentWorker():this._data instanceof u?this._data:new l(this._data)}};for(var m=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],p=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},f=0;f<m.length;f++)s.prototype[m[f]]=p;r.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,r,i){(function(s){var o,l,c=s.MutationObserver||s.WebKitMutationObserver;if(c){var d=0,u=new c(x),m=s.document.createTextNode("");u.observe(m,{characterData:!0}),o=function(){m.data=d=++d%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 p=new s.MessageChannel;p.port1.onmessage=x,o=function(){p.port2.postMessage(0)}}var f=[];function x(){var v,g;l=!0;for(var b=f.length;b;){for(g=f,f=[],v=-1;++v<b;)g[v]();b=f.length}l=!1}r.exports=function(v){f.push(v)!==1||l||o()}}).call(this,typeof j_<"u"?j_:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,r,i){var s=n("immediate");function o(){}var l={},c=["REJECTED"],d=["FULFILLED"],u=["PENDING"];function m(b){if(typeof b!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,b!==o&&v(this,b)}function p(b,_,C){this.promise=b,typeof _=="function"&&(this.onFulfilled=_,this.callFulfilled=this.otherCallFulfilled),typeof C=="function"&&(this.onRejected=C,this.callRejected=this.otherCallRejected)}function f(b,_,C){s(function(){var P;try{P=_(C)}catch(N){return l.reject(b,N)}P===b?l.reject(b,new TypeError("Cannot resolve promise with itself")):l.resolve(b,P)})}function x(b){var _=b&&b.then;if(b&&(typeof b=="object"||typeof b=="function")&&typeof _=="function")return function(){_.apply(b,arguments)}}function v(b,_){var C=!1;function P(T){C||(C=!0,l.reject(b,T))}function N(T){C||(C=!0,l.resolve(b,T))}var A=g(function(){_(N,P)});A.status==="error"&&P(A.value)}function g(b,_){var C={};try{C.value=b(_),C.status="success"}catch(P){C.status="error",C.value=P}return C}(r.exports=m).prototype.finally=function(b){if(typeof b!="function")return this;var _=this.constructor;return this.then(function(C){return _.resolve(b()).then(function(){return C})},function(C){return _.resolve(b()).then(function(){throw C})})},m.prototype.catch=function(b){return this.then(null,b)},m.prototype.then=function(b,_){if(typeof b!="function"&&this.state===d||typeof _!="function"&&this.state===c)return this;var C=new this.constructor(o);return this.state!==u?f(C,this.state===d?b:_,this.outcome):this.queue.push(new p(C,b,_)),C},p.prototype.callFulfilled=function(b){l.resolve(this.promise,b)},p.prototype.otherCallFulfilled=function(b){f(this.promise,this.onFulfilled,b)},p.prototype.callRejected=function(b){l.reject(this.promise,b)},p.prototype.otherCallRejected=function(b){f(this.promise,this.onRejected,b)},l.resolve=function(b,_){var C=g(x,_);if(C.status==="error")return l.reject(b,C.value);var P=C.value;if(P)v(b,P);else{b.state=d,b.outcome=_;for(var N=-1,A=b.queue.length;++N<A;)b.queue[N].callFulfilled(_)}return b},l.reject=function(b,_){b.state=c,b.outcome=_;for(var C=-1,P=b.queue.length;++C<P;)b.queue[C].callRejected(_);return b},m.resolve=function(b){return b instanceof this?b:l.resolve(new this(o),b)},m.reject=function(b){var _=new this(o);return l.reject(_,b)},m.all=function(b){var _=this;if(Object.prototype.toString.call(b)!=="[object Array]")return this.reject(new TypeError("must be an array"));var C=b.length,P=!1;if(!C)return this.resolve([]);for(var N=new Array(C),A=0,T=-1,F=new this(o);++T<C;)k(b[T],T);return F;function k(D,H){_.resolve(D).then(function(z){N[H]=z,++A!==C||P||(P=!0,l.resolve(F,N))},function(z){P||(P=!0,l.reject(F,z))})}},m.race=function(b){var _=this;if(Object.prototype.toString.call(b)!=="[object Array]")return this.reject(new TypeError("must be an array"));var C=b.length,P=!1;if(!C)return this.resolve([]);for(var N=-1,A=new this(o);++N<C;)T=b[N],_.resolve(T).then(function(F){P||(P=!0,l.resolve(A,F))},function(F){P||(P=!0,l.reject(A,F))});var T;return A}},{immediate:36}],38:[function(n,r,i){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,i){var s=n("./zlib/deflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/messages"),d=n("./zlib/zstream"),u=Object.prototype.toString,m=0,p=-1,f=0,x=8;function v(b){if(!(this instanceof v))return new v(b);this.options=o.assign({level:p,method:x,chunkSize:16384,windowBits:15,memLevel:8,strategy:f,to:""},b||{});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 d,this.strm.avail_out=0;var C=s.deflateInit2(this.strm,_.level,_.method,_.windowBits,_.memLevel,_.strategy);if(C!==m)throw new Error(c[C]);if(_.header&&s.deflateSetHeader(this.strm,_.header),_.dictionary){var P;if(P=typeof _.dictionary=="string"?l.string2buf(_.dictionary):u.call(_.dictionary)==="[object ArrayBuffer]"?new Uint8Array(_.dictionary):_.dictionary,(C=s.deflateSetDictionary(this.strm,P))!==m)throw new Error(c[C]);this._dict_set=!0}}function g(b,_){var C=new v(_);if(C.push(b,!0),C.err)throw C.msg||c[C.err];return C.result}v.prototype.push=function(b,_){var C,P,N=this.strm,A=this.options.chunkSize;if(this.ended)return!1;P=_===~~_?_:_===!0?4:0,typeof b=="string"?N.input=l.string2buf(b):u.call(b)==="[object ArrayBuffer]"?N.input=new Uint8Array(b):N.input=b,N.next_in=0,N.avail_in=N.input.length;do{if(N.avail_out===0&&(N.output=new o.Buf8(A),N.next_out=0,N.avail_out=A),(C=s.deflate(N,P))!==1&&C!==m)return this.onEnd(C),!(this.ended=!0);N.avail_out!==0&&(N.avail_in!==0||P!==4&&P!==2)||(this.options.to==="string"?this.onData(l.buf2binstring(o.shrinkBuf(N.output,N.next_out))):this.onData(o.shrinkBuf(N.output,N.next_out)))}while((0<N.avail_in||N.avail_out===0)&&C!==1);return P===4?(C=s.deflateEnd(this.strm),this.onEnd(C),this.ended=!0,C===m):P!==2||(this.onEnd(m),!(N.avail_out=0))},v.prototype.onData=function(b){this.chunks.push(b)},v.prototype.onEnd=function(b){b===m&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=b,this.msg=this.strm.msg},i.Deflate=v,i.deflate=g,i.deflateRaw=function(b,_){return(_=_||{}).raw=!0,g(b,_)},i.gzip=function(b,_){return(_=_||{}).gzip=!0,g(b,_)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,r,i){var s=n("./zlib/inflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/constants"),d=n("./zlib/messages"),u=n("./zlib/zstream"),m=n("./zlib/gzheader"),p=Object.prototype.toString;function f(v){if(!(this instanceof f))return new f(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 u,this.strm.avail_out=0;var b=s.inflateInit2(this.strm,g.windowBits);if(b!==c.Z_OK)throw new Error(d[b]);this.header=new m,s.inflateGetHeader(this.strm,this.header)}function x(v,g){var b=new f(g);if(b.push(v,!0),b.err)throw b.msg||d[b.err];return b.result}f.prototype.push=function(v,g){var b,_,C,P,N,A,T=this.strm,F=this.options.chunkSize,k=this.options.dictionary,D=!1;if(this.ended)return!1;_=g===~~g?g:g===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof v=="string"?T.input=l.binstring2buf(v):p.call(v)==="[object ArrayBuffer]"?T.input=new Uint8Array(v):T.input=v,T.next_in=0,T.avail_in=T.input.length;do{if(T.avail_out===0&&(T.output=new o.Buf8(F),T.next_out=0,T.avail_out=F),(b=s.inflate(T,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&k&&(A=typeof k=="string"?l.string2buf(k):p.call(k)==="[object ArrayBuffer]"?new Uint8Array(k):k,b=s.inflateSetDictionary(this.strm,A)),b===c.Z_BUF_ERROR&&D===!0&&(b=c.Z_OK,D=!1),b!==c.Z_STREAM_END&&b!==c.Z_OK)return this.onEnd(b),!(this.ended=!0);T.next_out&&(T.avail_out!==0&&b!==c.Z_STREAM_END&&(T.avail_in!==0||_!==c.Z_FINISH&&_!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(C=l.utf8border(T.output,T.next_out),P=T.next_out-C,N=l.buf2string(T.output,C),T.next_out=P,T.avail_out=F-P,P&&o.arraySet(T.output,T.output,C,P,0),this.onData(N)):this.onData(o.shrinkBuf(T.output,T.next_out)))),T.avail_in===0&&T.avail_out===0&&(D=!0)}while((0<T.avail_in||T.avail_out===0)&&b!==c.Z_STREAM_END);return b===c.Z_STREAM_END&&(_=c.Z_FINISH),_===c.Z_FINISH?(b=s.inflateEnd(this.strm),this.onEnd(b),this.ended=!0,b===c.Z_OK):_!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(T.avail_out=0))},f.prototype.onData=function(v){this.chunks.push(v)},f.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},i.Inflate=f,i.inflate=x,i.inflateRaw=function(v,g){return(g=g||{}).raw=!0,x(v,g)},i.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,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";i.assign=function(c){for(var d=Array.prototype.slice.call(arguments,1);d.length;){var u=d.shift();if(u){if(typeof u!="object")throw new TypeError(u+"must be non-object");for(var m in u)u.hasOwnProperty(m)&&(c[m]=u[m])}}return c},i.shrinkBuf=function(c,d){return c.length===d?c:c.subarray?c.subarray(0,d):(c.length=d,c)};var o={arraySet:function(c,d,u,m,p){if(d.subarray&&c.subarray)c.set(d.subarray(u,u+m),p);else for(var f=0;f<m;f++)c[p+f]=d[u+f]},flattenChunks:function(c){var d,u,m,p,f,x;for(d=m=0,u=c.length;d<u;d++)m+=c[d].length;for(x=new Uint8Array(m),d=p=0,u=c.length;d<u;d++)f=c[d],x.set(f,p),p+=f.length;return x}},l={arraySet:function(c,d,u,m,p){for(var f=0;f<m;f++)c[p+f]=d[u+f]},flattenChunks:function(c){return[].concat.apply([],c)}};i.setTyped=function(c){c?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,o)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,l))},i.setTyped(s)},{}],42:[function(n,r,i){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),d=0;d<256;d++)c[d]=252<=d?6:248<=d?5:240<=d?4:224<=d?3:192<=d?2:1;function u(m,p){if(p<65537&&(m.subarray&&l||!m.subarray&&o))return String.fromCharCode.apply(null,s.shrinkBuf(m,p));for(var f="",x=0;x<p;x++)f+=String.fromCharCode(m[x]);return f}c[254]=c[254]=1,i.string2buf=function(m){var p,f,x,v,g,b=m.length,_=0;for(v=0;v<b;v++)(64512&(f=m.charCodeAt(v)))==55296&&v+1<b&&(64512&(x=m.charCodeAt(v+1)))==56320&&(f=65536+(f-55296<<10)+(x-56320),v++),_+=f<128?1:f<2048?2:f<65536?3:4;for(p=new s.Buf8(_),v=g=0;g<_;v++)(64512&(f=m.charCodeAt(v)))==55296&&v+1<b&&(64512&(x=m.charCodeAt(v+1)))==56320&&(f=65536+(f-55296<<10)+(x-56320),v++),f<128?p[g++]=f:(f<2048?p[g++]=192|f>>>6:(f<65536?p[g++]=224|f>>>12:(p[g++]=240|f>>>18,p[g++]=128|f>>>12&63),p[g++]=128|f>>>6&63),p[g++]=128|63&f);return p},i.buf2binstring=function(m){return u(m,m.length)},i.binstring2buf=function(m){for(var p=new s.Buf8(m.length),f=0,x=p.length;f<x;f++)p[f]=m.charCodeAt(f);return p},i.buf2string=function(m,p){var f,x,v,g,b=p||m.length,_=new Array(2*b);for(f=x=0;f<b;)if((v=m[f++])<128)_[x++]=v;else if(4<(g=c[v]))_[x++]=65533,f+=g-1;else{for(v&=g===2?31:g===3?15:7;1<g&&f<b;)v=v<<6|63&m[f++],g--;1<g?_[x++]=65533:v<65536?_[x++]=v:(v-=65536,_[x++]=55296|v>>10&1023,_[x++]=56320|1023&v)}return u(_,x)},i.utf8border=function(m,p){var f;for((p=p||m.length)>m.length&&(p=m.length),f=p-1;0<=f&&(192&m[f])==128;)f--;return f<0||f===0?p:f+c[m[f]]>p?f:p}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,l,c){for(var d=65535&s|0,u=s>>>16&65535|0,m=0;l!==0;){for(l-=m=2e3<l?2e3:l;u=u+(d=d+o[c++]|0)|0,--m;);d%=65521,u%=65521}return d|u<<16|0}},{}],44:[function(n,r,i){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,i){var s=(function(){for(var o,l=[],c=0;c<256;c++){o=c;for(var d=0;d<8;d++)o=1&o?3988292384^o>>>1:o>>>1;l[c]=o}return l})();r.exports=function(o,l,c,d){var u=s,m=d+c;o^=-1;for(var p=d;p<m;p++)o=o>>>8^u[255&(o^l[p])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),l=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),m=0,p=4,f=0,x=-2,v=-1,g=4,b=2,_=8,C=9,P=286,N=30,A=19,T=2*P+1,F=15,k=3,D=258,H=D+k+1,z=42,X=113,L=1,ne=2,ie=3,ee=4;function ue(I,V){return I.msg=u[V],V}function le(I){return(I<<1)-(4<I?9:0)}function oe(I){for(var V=I.length;0<=--V;)I[V]=0}function W(I){var V=I.state,Q=V.pending;Q>I.avail_out&&(Q=I.avail_out),Q!==0&&(o.arraySet(I.output,V.pending_buf,V.pending_out,Q,I.next_out),I.next_out+=Q,V.pending_out+=Q,I.total_out+=Q,I.avail_out-=Q,V.pending-=Q,V.pending===0&&(V.pending_out=0))}function re(I,V){l._tr_flush_block(I,0<=I.block_start?I.block_start:-1,I.strstart-I.block_start,V),I.block_start=I.strstart,W(I.strm)}function ce(I,V){I.pending_buf[I.pending++]=V}function xe(I,V){I.pending_buf[I.pending++]=V>>>8&255,I.pending_buf[I.pending++]=255&V}function Ne(I,V){var Q,G,J=I.max_chain_length,se=I.strstart,fe=I.prev_length,pe=I.nice_match,de=I.strstart>I.w_size-H?I.strstart-(I.w_size-H):0,U=I.window,R=I.w_mask,ae=I.prev,_e=I.strstart+D,Se=U[se+fe-1],ye=U[se+fe];I.prev_length>=I.good_match&&(J>>=2),pe>I.lookahead&&(pe=I.lookahead);do if(U[(Q=V)+fe]===ye&&U[Q+fe-1]===Se&&U[Q]===U[se]&&U[++Q]===U[se+1]){se+=2,Q++;do;while(U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&U[++se]===U[++Q]&&se<_e);if(G=D-(_e-se),se=_e-D,fe<G){if(I.match_start=V,pe<=(fe=G))break;Se=U[se+fe-1],ye=U[se+fe]}}while((V=ae[V&R])>de&&--J!=0);return fe<=I.lookahead?fe:I.lookahead}function $(I){var V,Q,G,J,se,fe,pe,de,U,R,ae=I.w_size;do{if(J=I.window_size-I.lookahead-I.strstart,I.strstart>=ae+(ae-H)){for(o.arraySet(I.window,I.window,ae,ae,0),I.match_start-=ae,I.strstart-=ae,I.block_start-=ae,V=Q=I.hash_size;G=I.head[--V],I.head[V]=ae<=G?G-ae:0,--Q;);for(V=Q=ae;G=I.prev[--V],I.prev[V]=ae<=G?G-ae:0,--Q;);J+=ae}if(I.strm.avail_in===0)break;if(fe=I.strm,pe=I.window,de=I.strstart+I.lookahead,U=J,R=void 0,R=fe.avail_in,U<R&&(R=U),Q=R===0?0:(fe.avail_in-=R,o.arraySet(pe,fe.input,fe.next_in,R,de),fe.state.wrap===1?fe.adler=c(fe.adler,pe,R,de):fe.state.wrap===2&&(fe.adler=d(fe.adler,pe,R,de)),fe.next_in+=R,fe.total_in+=R,R),I.lookahead+=Q,I.lookahead+I.insert>=k)for(se=I.strstart-I.insert,I.ins_h=I.window[se],I.ins_h=(I.ins_h<<I.hash_shift^I.window[se+1])&I.hash_mask;I.insert&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[se+k-1])&I.hash_mask,I.prev[se&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=se,se++,I.insert--,!(I.lookahead+I.insert<k)););}while(I.lookahead<H&&I.strm.avail_in!==0)}function Y(I,V){for(var Q,G;;){if(I.lookahead<H){if($(I),I.lookahead<H&&V===m)return L;if(I.lookahead===0)break}if(Q=0,I.lookahead>=k&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+k-1])&I.hash_mask,Q=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart),Q!==0&&I.strstart-Q<=I.w_size-H&&(I.match_length=Ne(I,Q)),I.match_length>=k)if(G=l._tr_tally(I,I.strstart-I.match_start,I.match_length-k),I.lookahead-=I.match_length,I.match_length<=I.max_lazy_match&&I.lookahead>=k){for(I.match_length--;I.strstart++,I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+k-1])&I.hash_mask,Q=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart,--I.match_length!=0;);I.strstart++}else I.strstart+=I.match_length,I.match_length=0,I.ins_h=I.window[I.strstart],I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+1])&I.hash_mask;else G=l._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++;if(G&&(re(I,!1),I.strm.avail_out===0))return L}return I.insert=I.strstart<k-1?I.strstart:k-1,V===p?(re(I,!0),I.strm.avail_out===0?ie:ee):I.last_lit&&(re(I,!1),I.strm.avail_out===0)?L:ne}function E(I,V){for(var Q,G,J;;){if(I.lookahead<H){if($(I),I.lookahead<H&&V===m)return L;if(I.lookahead===0)break}if(Q=0,I.lookahead>=k&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+k-1])&I.hash_mask,Q=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart),I.prev_length=I.match_length,I.prev_match=I.match_start,I.match_length=k-1,Q!==0&&I.prev_length<I.max_lazy_match&&I.strstart-Q<=I.w_size-H&&(I.match_length=Ne(I,Q),I.match_length<=5&&(I.strategy===1||I.match_length===k&&4096<I.strstart-I.match_start)&&(I.match_length=k-1)),I.prev_length>=k&&I.match_length<=I.prev_length){for(J=I.strstart+I.lookahead-k,G=l._tr_tally(I,I.strstart-1-I.prev_match,I.prev_length-k),I.lookahead-=I.prev_length-1,I.prev_length-=2;++I.strstart<=J&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+k-1])&I.hash_mask,Q=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart),--I.prev_length!=0;);if(I.match_available=0,I.match_length=k-1,I.strstart++,G&&(re(I,!1),I.strm.avail_out===0))return L}else if(I.match_available){if((G=l._tr_tally(I,0,I.window[I.strstart-1]))&&re(I,!1),I.strstart++,I.lookahead--,I.strm.avail_out===0)return L}else I.match_available=1,I.strstart++,I.lookahead--}return I.match_available&&(G=l._tr_tally(I,0,I.window[I.strstart-1]),I.match_available=0),I.insert=I.strstart<k-1?I.strstart:k-1,V===p?(re(I,!0),I.strm.avail_out===0?ie:ee):I.last_lit&&(re(I,!1),I.strm.avail_out===0)?L:ne}function j(I,V,Q,G,J){this.good_length=I,this.max_lazy=V,this.nice_length=Q,this.max_chain=G,this.func=J}function O(){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*T),this.dyn_dtree=new o.Buf16(2*(2*N+1)),this.bl_tree=new o.Buf16(2*(2*A+1)),oe(this.dyn_ltree),oe(this.dyn_dtree),oe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new o.Buf16(F+1),this.heap=new o.Buf16(2*P+1),oe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new o.Buf16(2*P+1),oe(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 K(I){var V;return I&&I.state?(I.total_in=I.total_out=0,I.data_type=b,(V=I.state).pending=0,V.pending_out=0,V.wrap<0&&(V.wrap=-V.wrap),V.status=V.wrap?z:X,I.adler=V.wrap===2?0:1,V.last_flush=m,l._tr_init(V),f):ue(I,x)}function B(I){var V=K(I);return V===f&&(function(Q){Q.window_size=2*Q.w_size,oe(Q.head),Q.max_lazy_match=s[Q.level].max_lazy,Q.good_match=s[Q.level].good_length,Q.nice_match=s[Q.level].nice_length,Q.max_chain_length=s[Q.level].max_chain,Q.strstart=0,Q.block_start=0,Q.lookahead=0,Q.insert=0,Q.match_length=Q.prev_length=k-1,Q.match_available=0,Q.ins_h=0})(I.state),V}function he(I,V,Q,G,J,se){if(!I)return x;var fe=1;if(V===v&&(V=6),G<0?(fe=0,G=-G):15<G&&(fe=2,G-=16),J<1||C<J||Q!==_||G<8||15<G||V<0||9<V||se<0||g<se)return ue(I,x);G===8&&(G=9);var pe=new O;return(I.state=pe).strm=I,pe.wrap=fe,pe.gzhead=null,pe.w_bits=G,pe.w_size=1<<pe.w_bits,pe.w_mask=pe.w_size-1,pe.hash_bits=J+7,pe.hash_size=1<<pe.hash_bits,pe.hash_mask=pe.hash_size-1,pe.hash_shift=~~((pe.hash_bits+k-1)/k),pe.window=new o.Buf8(2*pe.w_size),pe.head=new o.Buf16(pe.hash_size),pe.prev=new o.Buf16(pe.w_size),pe.lit_bufsize=1<<J+6,pe.pending_buf_size=4*pe.lit_bufsize,pe.pending_buf=new o.Buf8(pe.pending_buf_size),pe.d_buf=1*pe.lit_bufsize,pe.l_buf=3*pe.lit_bufsize,pe.level=V,pe.strategy=se,pe.method=Q,B(I)}s=[new j(0,0,0,0,function(I,V){var Q=65535;for(Q>I.pending_buf_size-5&&(Q=I.pending_buf_size-5);;){if(I.lookahead<=1){if($(I),I.lookahead===0&&V===m)return L;if(I.lookahead===0)break}I.strstart+=I.lookahead,I.lookahead=0;var G=I.block_start+Q;if((I.strstart===0||I.strstart>=G)&&(I.lookahead=I.strstart-G,I.strstart=G,re(I,!1),I.strm.avail_out===0)||I.strstart-I.block_start>=I.w_size-H&&(re(I,!1),I.strm.avail_out===0))return L}return I.insert=0,V===p?(re(I,!0),I.strm.avail_out===0?ie:ee):(I.strstart>I.block_start&&(re(I,!1),I.strm.avail_out),L)}),new j(4,4,8,4,Y),new j(4,5,16,8,Y),new j(4,6,32,32,Y),new j(4,4,16,16,E),new j(8,16,32,32,E),new j(8,16,128,128,E),new j(8,32,128,256,E),new j(32,128,258,1024,E),new j(32,258,258,4096,E)],i.deflateInit=function(I,V){return he(I,V,_,15,8,0)},i.deflateInit2=he,i.deflateReset=B,i.deflateResetKeep=K,i.deflateSetHeader=function(I,V){return I&&I.state?I.state.wrap!==2?x:(I.state.gzhead=V,f):x},i.deflate=function(I,V){var Q,G,J,se;if(!I||!I.state||5<V||V<0)return I?ue(I,x):x;if(G=I.state,!I.output||!I.input&&I.avail_in!==0||G.status===666&&V!==p)return ue(I,I.avail_out===0?-5:x);if(G.strm=I,Q=G.last_flush,G.last_flush=V,G.status===z)if(G.wrap===2)I.adler=0,ce(G,31),ce(G,139),ce(G,8),G.gzhead?(ce(G,(G.gzhead.text?1:0)+(G.gzhead.hcrc?2:0)+(G.gzhead.extra?4:0)+(G.gzhead.name?8:0)+(G.gzhead.comment?16:0)),ce(G,255&G.gzhead.time),ce(G,G.gzhead.time>>8&255),ce(G,G.gzhead.time>>16&255),ce(G,G.gzhead.time>>24&255),ce(G,G.level===9?2:2<=G.strategy||G.level<2?4:0),ce(G,255&G.gzhead.os),G.gzhead.extra&&G.gzhead.extra.length&&(ce(G,255&G.gzhead.extra.length),ce(G,G.gzhead.extra.length>>8&255)),G.gzhead.hcrc&&(I.adler=d(I.adler,G.pending_buf,G.pending,0)),G.gzindex=0,G.status=69):(ce(G,0),ce(G,0),ce(G,0),ce(G,0),ce(G,0),ce(G,G.level===9?2:2<=G.strategy||G.level<2?4:0),ce(G,3),G.status=X);else{var fe=_+(G.w_bits-8<<4)<<8;fe|=(2<=G.strategy||G.level<2?0:G.level<6?1:G.level===6?2:3)<<6,G.strstart!==0&&(fe|=32),fe+=31-fe%31,G.status=X,xe(G,fe),G.strstart!==0&&(xe(G,I.adler>>>16),xe(G,65535&I.adler)),I.adler=1}if(G.status===69)if(G.gzhead.extra){for(J=G.pending;G.gzindex<(65535&G.gzhead.extra.length)&&(G.pending!==G.pending_buf_size||(G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),W(I),J=G.pending,G.pending!==G.pending_buf_size));)ce(G,255&G.gzhead.extra[G.gzindex]),G.gzindex++;G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),G.gzindex===G.gzhead.extra.length&&(G.gzindex=0,G.status=73)}else G.status=73;if(G.status===73)if(G.gzhead.name){J=G.pending;do{if(G.pending===G.pending_buf_size&&(G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),W(I),J=G.pending,G.pending===G.pending_buf_size)){se=1;break}se=G.gzindex<G.gzhead.name.length?255&G.gzhead.name.charCodeAt(G.gzindex++):0,ce(G,se)}while(se!==0);G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),se===0&&(G.gzindex=0,G.status=91)}else G.status=91;if(G.status===91)if(G.gzhead.comment){J=G.pending;do{if(G.pending===G.pending_buf_size&&(G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),W(I),J=G.pending,G.pending===G.pending_buf_size)){se=1;break}se=G.gzindex<G.gzhead.comment.length?255&G.gzhead.comment.charCodeAt(G.gzindex++):0,ce(G,se)}while(se!==0);G.gzhead.hcrc&&G.pending>J&&(I.adler=d(I.adler,G.pending_buf,G.pending-J,J)),se===0&&(G.status=103)}else G.status=103;if(G.status===103&&(G.gzhead.hcrc?(G.pending+2>G.pending_buf_size&&W(I),G.pending+2<=G.pending_buf_size&&(ce(G,255&I.adler),ce(G,I.adler>>8&255),I.adler=0,G.status=X)):G.status=X),G.pending!==0){if(W(I),I.avail_out===0)return G.last_flush=-1,f}else if(I.avail_in===0&&le(V)<=le(Q)&&V!==p)return ue(I,-5);if(G.status===666&&I.avail_in!==0)return ue(I,-5);if(I.avail_in!==0||G.lookahead!==0||V!==m&&G.status!==666){var pe=G.strategy===2?(function(de,U){for(var R;;){if(de.lookahead===0&&($(de),de.lookahead===0)){if(U===m)return L;break}if(de.match_length=0,R=l._tr_tally(de,0,de.window[de.strstart]),de.lookahead--,de.strstart++,R&&(re(de,!1),de.strm.avail_out===0))return L}return de.insert=0,U===p?(re(de,!0),de.strm.avail_out===0?ie:ee):de.last_lit&&(re(de,!1),de.strm.avail_out===0)?L:ne})(G,V):G.strategy===3?(function(de,U){for(var R,ae,_e,Se,ye=de.window;;){if(de.lookahead<=D){if($(de),de.lookahead<=D&&U===m)return L;if(de.lookahead===0)break}if(de.match_length=0,de.lookahead>=k&&0<de.strstart&&(ae=ye[_e=de.strstart-1])===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]){Se=de.strstart+D;do;while(ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&ae===ye[++_e]&&_e<Se);de.match_length=D-(Se-_e),de.match_length>de.lookahead&&(de.match_length=de.lookahead)}if(de.match_length>=k?(R=l._tr_tally(de,1,de.match_length-k),de.lookahead-=de.match_length,de.strstart+=de.match_length,de.match_length=0):(R=l._tr_tally(de,0,de.window[de.strstart]),de.lookahead--,de.strstart++),R&&(re(de,!1),de.strm.avail_out===0))return L}return de.insert=0,U===p?(re(de,!0),de.strm.avail_out===0?ie:ee):de.last_lit&&(re(de,!1),de.strm.avail_out===0)?L:ne})(G,V):s[G.level].func(G,V);if(pe!==ie&&pe!==ee||(G.status=666),pe===L||pe===ie)return I.avail_out===0&&(G.last_flush=-1),f;if(pe===ne&&(V===1?l._tr_align(G):V!==5&&(l._tr_stored_block(G,0,0,!1),V===3&&(oe(G.head),G.lookahead===0&&(G.strstart=0,G.block_start=0,G.insert=0))),W(I),I.avail_out===0))return G.last_flush=-1,f}return V!==p?f:G.wrap<=0?1:(G.wrap===2?(ce(G,255&I.adler),ce(G,I.adler>>8&255),ce(G,I.adler>>16&255),ce(G,I.adler>>24&255),ce(G,255&I.total_in),ce(G,I.total_in>>8&255),ce(G,I.total_in>>16&255),ce(G,I.total_in>>24&255)):(xe(G,I.adler>>>16),xe(G,65535&I.adler)),W(I),0<G.wrap&&(G.wrap=-G.wrap),G.pending!==0?f:1)},i.deflateEnd=function(I){var V;return I&&I.state?(V=I.state.status)!==z&&V!==69&&V!==73&&V!==91&&V!==103&&V!==X&&V!==666?ue(I,x):(I.state=null,V===X?ue(I,-3):f):x},i.deflateSetDictionary=function(I,V){var Q,G,J,se,fe,pe,de,U,R=V.length;if(!I||!I.state||(se=(Q=I.state).wrap)===2||se===1&&Q.status!==z||Q.lookahead)return x;for(se===1&&(I.adler=c(I.adler,V,R,0)),Q.wrap=0,R>=Q.w_size&&(se===0&&(oe(Q.head),Q.strstart=0,Q.block_start=0,Q.insert=0),U=new o.Buf8(Q.w_size),o.arraySet(U,V,R-Q.w_size,Q.w_size,0),V=U,R=Q.w_size),fe=I.avail_in,pe=I.next_in,de=I.input,I.avail_in=R,I.next_in=0,I.input=V,$(Q);Q.lookahead>=k;){for(G=Q.strstart,J=Q.lookahead-(k-1);Q.ins_h=(Q.ins_h<<Q.hash_shift^Q.window[G+k-1])&Q.hash_mask,Q.prev[G&Q.w_mask]=Q.head[Q.ins_h],Q.head[Q.ins_h]=G,G++,--J;);Q.strstart=G,Q.lookahead=k-1,$(Q)}return Q.strstart+=Q.lookahead,Q.block_start=Q.strstart,Q.insert=Q.lookahead,Q.lookahead=0,Q.match_length=Q.prev_length=k-1,Q.match_available=0,I.next_in=pe,I.input=de,I.avail_in=fe,Q.wrap=se,f},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,r,i){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,i){r.exports=function(s,o){var l,c,d,u,m,p,f,x,v,g,b,_,C,P,N,A,T,F,k,D,H,z,X,L,ne;l=s.state,c=s.next_in,L=s.input,d=c+(s.avail_in-5),u=s.next_out,ne=s.output,m=u-(o-s.avail_out),p=u+(s.avail_out-257),f=l.dmax,x=l.wsize,v=l.whave,g=l.wnext,b=l.window,_=l.hold,C=l.bits,P=l.lencode,N=l.distcode,A=(1<<l.lenbits)-1,T=(1<<l.distbits)-1;e:do{C<15&&(_+=L[c++]<<C,C+=8,_+=L[c++]<<C,C+=8),F=P[_&A];t:for(;;){if(_>>>=k=F>>>24,C-=k,(k=F>>>16&255)===0)ne[u++]=65535&F;else{if(!(16&k)){if((64&k)==0){F=P[(65535&F)+(_&(1<<k)-1)];continue t}if(32&k){l.mode=12;break e}s.msg="invalid literal/length code",l.mode=30;break e}D=65535&F,(k&=15)&&(C<k&&(_+=L[c++]<<C,C+=8),D+=_&(1<<k)-1,_>>>=k,C-=k),C<15&&(_+=L[c++]<<C,C+=8,_+=L[c++]<<C,C+=8),F=N[_&T];n:for(;;){if(_>>>=k=F>>>24,C-=k,!(16&(k=F>>>16&255))){if((64&k)==0){F=N[(65535&F)+(_&(1<<k)-1)];continue n}s.msg="invalid distance code",l.mode=30;break e}if(H=65535&F,C<(k&=15)&&(_+=L[c++]<<C,(C+=8)<k&&(_+=L[c++]<<C,C+=8)),f<(H+=_&(1<<k)-1)){s.msg="invalid distance too far back",l.mode=30;break e}if(_>>>=k,C-=k,(k=u-m)<H){if(v<(k=H-k)&&l.sane){s.msg="invalid distance too far back",l.mode=30;break e}if(X=b,(z=0)===g){if(z+=x-k,k<D){for(D-=k;ne[u++]=b[z++],--k;);z=u-H,X=ne}}else if(g<k){if(z+=x+g-k,(k-=g)<D){for(D-=k;ne[u++]=b[z++],--k;);if(z=0,g<D){for(D-=k=g;ne[u++]=b[z++],--k;);z=u-H,X=ne}}}else if(z+=g-k,k<D){for(D-=k;ne[u++]=b[z++],--k;);z=u-H,X=ne}for(;2<D;)ne[u++]=X[z++],ne[u++]=X[z++],ne[u++]=X[z++],D-=3;D&&(ne[u++]=X[z++],1<D&&(ne[u++]=X[z++]))}else{for(z=u-H;ne[u++]=ne[z++],ne[u++]=ne[z++],ne[u++]=ne[z++],2<(D-=3););D&&(ne[u++]=ne[z++],1<D&&(ne[u++]=ne[z++]))}break}}break}}while(c<d&&u<p);c-=D=C>>3,_&=(1<<(C-=D<<3))-1,s.next_in=c,s.next_out=u,s.avail_in=c<d?d-c+5:5-(c-d),s.avail_out=u<p?p-u+257:257-(u-p),l.hold=_,l.bits=C}},{}],49:[function(n,r,i){var s=n("../utils/common"),o=n("./adler32"),l=n("./crc32"),c=n("./inffast"),d=n("./inftrees"),u=1,m=2,p=0,f=-2,x=1,v=852,g=592;function b(z){return(z>>>24&255)+(z>>>8&65280)+((65280&z)<<8)+((255&z)<<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 C(z){var X;return z&&z.state?(X=z.state,z.total_in=z.total_out=X.total=0,z.msg="",X.wrap&&(z.adler=1&X.wrap),X.mode=x,X.last=0,X.havedict=0,X.dmax=32768,X.head=null,X.hold=0,X.bits=0,X.lencode=X.lendyn=new s.Buf32(v),X.distcode=X.distdyn=new s.Buf32(g),X.sane=1,X.back=-1,p):f}function P(z){var X;return z&&z.state?((X=z.state).wsize=0,X.whave=0,X.wnext=0,C(z)):f}function N(z,X){var L,ne;return z&&z.state?(ne=z.state,X<0?(L=0,X=-X):(L=1+(X>>4),X<48&&(X&=15)),X&&(X<8||15<X)?f:(ne.window!==null&&ne.wbits!==X&&(ne.window=null),ne.wrap=L,ne.wbits=X,P(z))):f}function A(z,X){var L,ne;return z?(ne=new _,(z.state=ne).window=null,(L=N(z,X))!==p&&(z.state=null),L):f}var T,F,k=!0;function D(z){if(k){var X;for(T=new s.Buf32(512),F=new s.Buf32(32),X=0;X<144;)z.lens[X++]=8;for(;X<256;)z.lens[X++]=9;for(;X<280;)z.lens[X++]=7;for(;X<288;)z.lens[X++]=8;for(d(u,z.lens,0,288,T,0,z.work,{bits:9}),X=0;X<32;)z.lens[X++]=5;d(m,z.lens,0,32,F,0,z.work,{bits:5}),k=!1}z.lencode=T,z.lenbits=9,z.distcode=F,z.distbits=5}function H(z,X,L,ne){var ie,ee=z.state;return ee.window===null&&(ee.wsize=1<<ee.wbits,ee.wnext=0,ee.whave=0,ee.window=new s.Buf8(ee.wsize)),ne>=ee.wsize?(s.arraySet(ee.window,X,L-ee.wsize,ee.wsize,0),ee.wnext=0,ee.whave=ee.wsize):(ne<(ie=ee.wsize-ee.wnext)&&(ie=ne),s.arraySet(ee.window,X,L-ne,ie,ee.wnext),(ne-=ie)?(s.arraySet(ee.window,X,L-ne,ne,0),ee.wnext=ne,ee.whave=ee.wsize):(ee.wnext+=ie,ee.wnext===ee.wsize&&(ee.wnext=0),ee.whave<ee.wsize&&(ee.whave+=ie))),0}i.inflateReset=P,i.inflateReset2=N,i.inflateResetKeep=C,i.inflateInit=function(z){return A(z,15)},i.inflateInit2=A,i.inflate=function(z,X){var L,ne,ie,ee,ue,le,oe,W,re,ce,xe,Ne,$,Y,E,j,O,K,B,he,I,V,Q,G,J=0,se=new s.Buf8(4),fe=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!z||!z.state||!z.output||!z.input&&z.avail_in!==0)return f;(L=z.state).mode===12&&(L.mode=13),ue=z.next_out,ie=z.output,oe=z.avail_out,ee=z.next_in,ne=z.input,le=z.avail_in,W=L.hold,re=L.bits,ce=le,xe=oe,V=p;e:for(;;)switch(L.mode){case x:if(L.wrap===0){L.mode=13;break}for(;re<16;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(2&L.wrap&&W===35615){se[L.check=0]=255&W,se[1]=W>>>8&255,L.check=l(L.check,se,2,0),re=W=0,L.mode=2;break}if(L.flags=0,L.head&&(L.head.done=!1),!(1&L.wrap)||(((255&W)<<8)+(W>>8))%31){z.msg="incorrect header check",L.mode=30;break}if((15&W)!=8){z.msg="unknown compression method",L.mode=30;break}if(re-=4,I=8+(15&(W>>>=4)),L.wbits===0)L.wbits=I;else if(I>L.wbits){z.msg="invalid window size",L.mode=30;break}L.dmax=1<<I,z.adler=L.check=1,L.mode=512&W?10:12,re=W=0;break;case 2:for(;re<16;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(L.flags=W,(255&L.flags)!=8){z.msg="unknown compression method",L.mode=30;break}if(57344&L.flags){z.msg="unknown header flags set",L.mode=30;break}L.head&&(L.head.text=W>>8&1),512&L.flags&&(se[0]=255&W,se[1]=W>>>8&255,L.check=l(L.check,se,2,0)),re=W=0,L.mode=3;case 3:for(;re<32;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.head&&(L.head.time=W),512&L.flags&&(se[0]=255&W,se[1]=W>>>8&255,se[2]=W>>>16&255,se[3]=W>>>24&255,L.check=l(L.check,se,4,0)),re=W=0,L.mode=4;case 4:for(;re<16;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.head&&(L.head.xflags=255&W,L.head.os=W>>8),512&L.flags&&(se[0]=255&W,se[1]=W>>>8&255,L.check=l(L.check,se,2,0)),re=W=0,L.mode=5;case 5:if(1024&L.flags){for(;re<16;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.length=W,L.head&&(L.head.extra_len=W),512&L.flags&&(se[0]=255&W,se[1]=W>>>8&255,L.check=l(L.check,se,2,0)),re=W=0}else L.head&&(L.head.extra=null);L.mode=6;case 6:if(1024&L.flags&&(le<(Ne=L.length)&&(Ne=le),Ne&&(L.head&&(I=L.head.extra_len-L.length,L.head.extra||(L.head.extra=new Array(L.head.extra_len)),s.arraySet(L.head.extra,ne,ee,Ne,I)),512&L.flags&&(L.check=l(L.check,ne,Ne,ee)),le-=Ne,ee+=Ne,L.length-=Ne),L.length))break e;L.length=0,L.mode=7;case 7:if(2048&L.flags){if(le===0)break e;for(Ne=0;I=ne[ee+Ne++],L.head&&I&&L.length<65536&&(L.head.name+=String.fromCharCode(I)),I&&Ne<le;);if(512&L.flags&&(L.check=l(L.check,ne,Ne,ee)),le-=Ne,ee+=Ne,I)break e}else L.head&&(L.head.name=null);L.length=0,L.mode=8;case 8:if(4096&L.flags){if(le===0)break e;for(Ne=0;I=ne[ee+Ne++],L.head&&I&&L.length<65536&&(L.head.comment+=String.fromCharCode(I)),I&&Ne<le;);if(512&L.flags&&(L.check=l(L.check,ne,Ne,ee)),le-=Ne,ee+=Ne,I)break e}else L.head&&(L.head.comment=null);L.mode=9;case 9:if(512&L.flags){for(;re<16;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(W!==(65535&L.check)){z.msg="header crc mismatch",L.mode=30;break}re=W=0}L.head&&(L.head.hcrc=L.flags>>9&1,L.head.done=!0),z.adler=L.check=0,L.mode=12;break;case 10:for(;re<32;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}z.adler=L.check=b(W),re=W=0,L.mode=11;case 11:if(L.havedict===0)return z.next_out=ue,z.avail_out=oe,z.next_in=ee,z.avail_in=le,L.hold=W,L.bits=re,2;z.adler=L.check=1,L.mode=12;case 12:if(X===5||X===6)break e;case 13:if(L.last){W>>>=7&re,re-=7&re,L.mode=27;break}for(;re<3;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}switch(L.last=1&W,re-=1,3&(W>>>=1)){case 0:L.mode=14;break;case 1:if(D(L),L.mode=20,X!==6)break;W>>>=2,re-=2;break e;case 2:L.mode=17;break;case 3:z.msg="invalid block type",L.mode=30}W>>>=2,re-=2;break;case 14:for(W>>>=7&re,re-=7&re;re<32;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if((65535&W)!=(W>>>16^65535)){z.msg="invalid stored block lengths",L.mode=30;break}if(L.length=65535&W,re=W=0,L.mode=15,X===6)break e;case 15:L.mode=16;case 16:if(Ne=L.length){if(le<Ne&&(Ne=le),oe<Ne&&(Ne=oe),Ne===0)break e;s.arraySet(ie,ne,ee,Ne,ue),le-=Ne,ee+=Ne,oe-=Ne,ue+=Ne,L.length-=Ne;break}L.mode=12;break;case 17:for(;re<14;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(L.nlen=257+(31&W),W>>>=5,re-=5,L.ndist=1+(31&W),W>>>=5,re-=5,L.ncode=4+(15&W),W>>>=4,re-=4,286<L.nlen||30<L.ndist){z.msg="too many length or distance symbols",L.mode=30;break}L.have=0,L.mode=18;case 18:for(;L.have<L.ncode;){for(;re<3;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.lens[fe[L.have++]]=7&W,W>>>=3,re-=3}for(;L.have<19;)L.lens[fe[L.have++]]=0;if(L.lencode=L.lendyn,L.lenbits=7,Q={bits:L.lenbits},V=d(0,L.lens,0,19,L.lencode,0,L.work,Q),L.lenbits=Q.bits,V){z.msg="invalid code lengths set",L.mode=30;break}L.have=0,L.mode=19;case 19:for(;L.have<L.nlen+L.ndist;){for(;j=(J=L.lencode[W&(1<<L.lenbits)-1])>>>16&255,O=65535&J,!((E=J>>>24)<=re);){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(O<16)W>>>=E,re-=E,L.lens[L.have++]=O;else{if(O===16){for(G=E+2;re<G;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(W>>>=E,re-=E,L.have===0){z.msg="invalid bit length repeat",L.mode=30;break}I=L.lens[L.have-1],Ne=3+(3&W),W>>>=2,re-=2}else if(O===17){for(G=E+3;re<G;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}re-=E,I=0,Ne=3+(7&(W>>>=E)),W>>>=3,re-=3}else{for(G=E+7;re<G;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}re-=E,I=0,Ne=11+(127&(W>>>=E)),W>>>=7,re-=7}if(L.have+Ne>L.nlen+L.ndist){z.msg="invalid bit length repeat",L.mode=30;break}for(;Ne--;)L.lens[L.have++]=I}}if(L.mode===30)break;if(L.lens[256]===0){z.msg="invalid code -- missing end-of-block",L.mode=30;break}if(L.lenbits=9,Q={bits:L.lenbits},V=d(u,L.lens,0,L.nlen,L.lencode,0,L.work,Q),L.lenbits=Q.bits,V){z.msg="invalid literal/lengths set",L.mode=30;break}if(L.distbits=6,L.distcode=L.distdyn,Q={bits:L.distbits},V=d(m,L.lens,L.nlen,L.ndist,L.distcode,0,L.work,Q),L.distbits=Q.bits,V){z.msg="invalid distances set",L.mode=30;break}if(L.mode=20,X===6)break e;case 20:L.mode=21;case 21:if(6<=le&&258<=oe){z.next_out=ue,z.avail_out=oe,z.next_in=ee,z.avail_in=le,L.hold=W,L.bits=re,c(z,xe),ue=z.next_out,ie=z.output,oe=z.avail_out,ee=z.next_in,ne=z.input,le=z.avail_in,W=L.hold,re=L.bits,L.mode===12&&(L.back=-1);break}for(L.back=0;j=(J=L.lencode[W&(1<<L.lenbits)-1])>>>16&255,O=65535&J,!((E=J>>>24)<=re);){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(j&&(240&j)==0){for(K=E,B=j,he=O;j=(J=L.lencode[he+((W&(1<<K+B)-1)>>K)])>>>16&255,O=65535&J,!(K+(E=J>>>24)<=re);){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}W>>>=K,re-=K,L.back+=K}if(W>>>=E,re-=E,L.back+=E,L.length=O,j===0){L.mode=26;break}if(32&j){L.back=-1,L.mode=12;break}if(64&j){z.msg="invalid literal/length code",L.mode=30;break}L.extra=15&j,L.mode=22;case 22:if(L.extra){for(G=L.extra;re<G;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.length+=W&(1<<L.extra)-1,W>>>=L.extra,re-=L.extra,L.back+=L.extra}L.was=L.length,L.mode=23;case 23:for(;j=(J=L.distcode[W&(1<<L.distbits)-1])>>>16&255,O=65535&J,!((E=J>>>24)<=re);){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if((240&j)==0){for(K=E,B=j,he=O;j=(J=L.distcode[he+((W&(1<<K+B)-1)>>K)])>>>16&255,O=65535&J,!(K+(E=J>>>24)<=re);){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}W>>>=K,re-=K,L.back+=K}if(W>>>=E,re-=E,L.back+=E,64&j){z.msg="invalid distance code",L.mode=30;break}L.offset=O,L.extra=15&j,L.mode=24;case 24:if(L.extra){for(G=L.extra;re<G;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}L.offset+=W&(1<<L.extra)-1,W>>>=L.extra,re-=L.extra,L.back+=L.extra}if(L.offset>L.dmax){z.msg="invalid distance too far back",L.mode=30;break}L.mode=25;case 25:if(oe===0)break e;if(Ne=xe-oe,L.offset>Ne){if((Ne=L.offset-Ne)>L.whave&&L.sane){z.msg="invalid distance too far back",L.mode=30;break}$=Ne>L.wnext?(Ne-=L.wnext,L.wsize-Ne):L.wnext-Ne,Ne>L.length&&(Ne=L.length),Y=L.window}else Y=ie,$=ue-L.offset,Ne=L.length;for(oe<Ne&&(Ne=oe),oe-=Ne,L.length-=Ne;ie[ue++]=Y[$++],--Ne;);L.length===0&&(L.mode=21);break;case 26:if(oe===0)break e;ie[ue++]=L.length,oe--,L.mode=21;break;case 27:if(L.wrap){for(;re<32;){if(le===0)break e;le--,W|=ne[ee++]<<re,re+=8}if(xe-=oe,z.total_out+=xe,L.total+=xe,xe&&(z.adler=L.check=L.flags?l(L.check,ie,xe,ue-xe):o(L.check,ie,xe,ue-xe)),xe=oe,(L.flags?W:b(W))!==L.check){z.msg="incorrect data check",L.mode=30;break}re=W=0}L.mode=28;case 28:if(L.wrap&&L.flags){for(;re<32;){if(le===0)break e;le--,W+=ne[ee++]<<re,re+=8}if(W!==(4294967295&L.total)){z.msg="incorrect length check",L.mode=30;break}re=W=0}L.mode=29;case 29:V=1;break e;case 30:V=-3;break e;case 31:return-4;default:return f}return z.next_out=ue,z.avail_out=oe,z.next_in=ee,z.avail_in=le,L.hold=W,L.bits=re,(L.wsize||xe!==z.avail_out&&L.mode<30&&(L.mode<27||X!==4))&&H(z,z.output,z.next_out,xe-z.avail_out)?(L.mode=31,-4):(ce-=z.avail_in,xe-=z.avail_out,z.total_in+=ce,z.total_out+=xe,L.total+=xe,L.wrap&&xe&&(z.adler=L.check=L.flags?l(L.check,ie,xe,z.next_out-xe):o(L.check,ie,xe,z.next_out-xe)),z.data_type=L.bits+(L.last?64:0)+(L.mode===12?128:0)+(L.mode===20||L.mode===15?256:0),(ce==0&&xe===0||X===4)&&V===p&&(V=-5),V)},i.inflateEnd=function(z){if(!z||!z.state)return f;var X=z.state;return X.window&&(X.window=null),z.state=null,p},i.inflateGetHeader=function(z,X){var L;return z&&z.state?(2&(L=z.state).wrap)==0?f:((L.head=X).done=!1,p):f},i.inflateSetDictionary=function(z,X){var L,ne=X.length;return z&&z.state?(L=z.state).wrap!==0&&L.mode!==11?f:L.mode===11&&o(1,X,ne,0)!==L.check?-3:H(z,X,ne,ne)?(L.mode=31,-4):(L.havedict=1,p):f},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(n,r,i){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],d=[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(u,m,p,f,x,v,g,b){var _,C,P,N,A,T,F,k,D,H=b.bits,z=0,X=0,L=0,ne=0,ie=0,ee=0,ue=0,le=0,oe=0,W=0,re=null,ce=0,xe=new s.Buf16(16),Ne=new s.Buf16(16),$=null,Y=0;for(z=0;z<=15;z++)xe[z]=0;for(X=0;X<f;X++)xe[m[p+X]]++;for(ie=H,ne=15;1<=ne&&xe[ne]===0;ne--);if(ne<ie&&(ie=ne),ne===0)return x[v++]=20971520,x[v++]=20971520,b.bits=1,0;for(L=1;L<ne&&xe[L]===0;L++);for(ie<L&&(ie=L),z=le=1;z<=15;z++)if(le<<=1,(le-=xe[z])<0)return-1;if(0<le&&(u===0||ne!==1))return-1;for(Ne[1]=0,z=1;z<15;z++)Ne[z+1]=Ne[z]+xe[z];for(X=0;X<f;X++)m[p+X]!==0&&(g[Ne[m[p+X]]++]=X);if(T=u===0?(re=$=g,19):u===1?(re=o,ce-=257,$=l,Y-=257,256):(re=c,$=d,-1),z=L,A=v,ue=X=W=0,P=-1,N=(oe=1<<(ee=ie))-1,u===1&&852<oe||u===2&&592<oe)return 1;for(;;){for(F=z-ue,D=g[X]<T?(k=0,g[X]):g[X]>T?(k=$[Y+g[X]],re[ce+g[X]]):(k=96,0),_=1<<z-ue,L=C=1<<ee;x[A+(W>>ue)+(C-=_)]=F<<24|k<<16|D|0,C!==0;);for(_=1<<z-1;W&_;)_>>=1;if(_!==0?(W&=_-1,W+=_):W=0,X++,--xe[z]==0){if(z===ne)break;z=m[p+g[X]]}if(ie<z&&(W&N)!==P){for(ue===0&&(ue=ie),A+=L,le=1<<(ee=z-ue);ee+ue<ne&&!((le-=xe[ee+ue])<=0);)ee++,le<<=1;if(oe+=1<<ee,u===1&&852<oe||u===2&&592<oe)return 1;x[P=W&N]=ie<<24|ee<<16|A-v|0}}return W!==0&&(x[A+W]=z-ue<<24|64<<16|0),b.bits=ie,0}},{"../utils/common":41}],51:[function(n,r,i){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,i){var s=n("../utils/common"),o=0,l=1;function c(J){for(var se=J.length;0<=--se;)J[se]=0}var d=0,u=29,m=256,p=m+1+u,f=30,x=19,v=2*p+1,g=15,b=16,_=7,C=256,P=16,N=17,A=18,T=[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],F=[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],k=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],D=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],H=new Array(2*(p+2));c(H);var z=new Array(2*f);c(z);var X=new Array(512);c(X);var L=new Array(256);c(L);var ne=new Array(u);c(ne);var ie,ee,ue,le=new Array(f);function oe(J,se,fe,pe,de){this.static_tree=J,this.extra_bits=se,this.extra_base=fe,this.elems=pe,this.max_length=de,this.has_stree=J&&J.length}function W(J,se){this.dyn_tree=J,this.max_code=0,this.stat_desc=se}function re(J){return J<256?X[J]:X[256+(J>>>7)]}function ce(J,se){J.pending_buf[J.pending++]=255&se,J.pending_buf[J.pending++]=se>>>8&255}function xe(J,se,fe){J.bi_valid>b-fe?(J.bi_buf|=se<<J.bi_valid&65535,ce(J,J.bi_buf),J.bi_buf=se>>b-J.bi_valid,J.bi_valid+=fe-b):(J.bi_buf|=se<<J.bi_valid&65535,J.bi_valid+=fe)}function Ne(J,se,fe){xe(J,fe[2*se],fe[2*se+1])}function $(J,se){for(var fe=0;fe|=1&J,J>>>=1,fe<<=1,0<--se;);return fe>>>1}function Y(J,se,fe){var pe,de,U=new Array(g+1),R=0;for(pe=1;pe<=g;pe++)U[pe]=R=R+fe[pe-1]<<1;for(de=0;de<=se;de++){var ae=J[2*de+1];ae!==0&&(J[2*de]=$(U[ae]++,ae))}}function E(J){var se;for(se=0;se<p;se++)J.dyn_ltree[2*se]=0;for(se=0;se<f;se++)J.dyn_dtree[2*se]=0;for(se=0;se<x;se++)J.bl_tree[2*se]=0;J.dyn_ltree[2*C]=1,J.opt_len=J.static_len=0,J.last_lit=J.matches=0}function j(J){8<J.bi_valid?ce(J,J.bi_buf):0<J.bi_valid&&(J.pending_buf[J.pending++]=J.bi_buf),J.bi_buf=0,J.bi_valid=0}function O(J,se,fe,pe){var de=2*se,U=2*fe;return J[de]<J[U]||J[de]===J[U]&&pe[se]<=pe[fe]}function K(J,se,fe){for(var pe=J.heap[fe],de=fe<<1;de<=J.heap_len&&(de<J.heap_len&&O(se,J.heap[de+1],J.heap[de],J.depth)&&de++,!O(se,pe,J.heap[de],J.depth));)J.heap[fe]=J.heap[de],fe=de,de<<=1;J.heap[fe]=pe}function B(J,se,fe){var pe,de,U,R,ae=0;if(J.last_lit!==0)for(;pe=J.pending_buf[J.d_buf+2*ae]<<8|J.pending_buf[J.d_buf+2*ae+1],de=J.pending_buf[J.l_buf+ae],ae++,pe===0?Ne(J,de,se):(Ne(J,(U=L[de])+m+1,se),(R=T[U])!==0&&xe(J,de-=ne[U],R),Ne(J,U=re(--pe),fe),(R=F[U])!==0&&xe(J,pe-=le[U],R)),ae<J.last_lit;);Ne(J,C,se)}function he(J,se){var fe,pe,de,U=se.dyn_tree,R=se.stat_desc.static_tree,ae=se.stat_desc.has_stree,_e=se.stat_desc.elems,Se=-1;for(J.heap_len=0,J.heap_max=v,fe=0;fe<_e;fe++)U[2*fe]!==0?(J.heap[++J.heap_len]=Se=fe,J.depth[fe]=0):U[2*fe+1]=0;for(;J.heap_len<2;)U[2*(de=J.heap[++J.heap_len]=Se<2?++Se:0)]=1,J.depth[de]=0,J.opt_len--,ae&&(J.static_len-=R[2*de+1]);for(se.max_code=Se,fe=J.heap_len>>1;1<=fe;fe--)K(J,U,fe);for(de=_e;fe=J.heap[1],J.heap[1]=J.heap[J.heap_len--],K(J,U,1),pe=J.heap[1],J.heap[--J.heap_max]=fe,J.heap[--J.heap_max]=pe,U[2*de]=U[2*fe]+U[2*pe],J.depth[de]=(J.depth[fe]>=J.depth[pe]?J.depth[fe]:J.depth[pe])+1,U[2*fe+1]=U[2*pe+1]=de,J.heap[1]=de++,K(J,U,1),2<=J.heap_len;);J.heap[--J.heap_max]=J.heap[1],(function(ye,Ae){var ve,je,Re,Ee,Te,Me,Be=Ae.dyn_tree,Ke=Ae.max_code,tt=Ae.stat_desc.static_tree,te=Ae.stat_desc.has_stree,Ie=Ae.stat_desc.extra_bits,be=Ae.stat_desc.extra_base,$e=Ae.stat_desc.max_length,He=0;for(Ee=0;Ee<=g;Ee++)ye.bl_count[Ee]=0;for(Be[2*ye.heap[ye.heap_max]+1]=0,ve=ye.heap_max+1;ve<v;ve++)$e<(Ee=Be[2*Be[2*(je=ye.heap[ve])+1]+1]+1)&&(Ee=$e,He++),Be[2*je+1]=Ee,Ke<je||(ye.bl_count[Ee]++,Te=0,be<=je&&(Te=Ie[je-be]),Me=Be[2*je],ye.opt_len+=Me*(Ee+Te),te&&(ye.static_len+=Me*(tt[2*je+1]+Te)));if(He!==0){do{for(Ee=$e-1;ye.bl_count[Ee]===0;)Ee--;ye.bl_count[Ee]--,ye.bl_count[Ee+1]+=2,ye.bl_count[$e]--,He-=2}while(0<He);for(Ee=$e;Ee!==0;Ee--)for(je=ye.bl_count[Ee];je!==0;)Ke<(Re=ye.heap[--ve])||(Be[2*Re+1]!==Ee&&(ye.opt_len+=(Ee-Be[2*Re+1])*Be[2*Re],Be[2*Re+1]=Ee),je--)}})(J,se),Y(U,Se,J.bl_count)}function I(J,se,fe){var pe,de,U=-1,R=se[1],ae=0,_e=7,Se=4;for(R===0&&(_e=138,Se=3),se[2*(fe+1)+1]=65535,pe=0;pe<=fe;pe++)de=R,R=se[2*(pe+1)+1],++ae<_e&&de===R||(ae<Se?J.bl_tree[2*de]+=ae:de!==0?(de!==U&&J.bl_tree[2*de]++,J.bl_tree[2*P]++):ae<=10?J.bl_tree[2*N]++:J.bl_tree[2*A]++,U=de,Se=(ae=0)===R?(_e=138,3):de===R?(_e=6,3):(_e=7,4))}function V(J,se,fe){var pe,de,U=-1,R=se[1],ae=0,_e=7,Se=4;for(R===0&&(_e=138,Se=3),pe=0;pe<=fe;pe++)if(de=R,R=se[2*(pe+1)+1],!(++ae<_e&&de===R)){if(ae<Se)for(;Ne(J,de,J.bl_tree),--ae!=0;);else de!==0?(de!==U&&(Ne(J,de,J.bl_tree),ae--),Ne(J,P,J.bl_tree),xe(J,ae-3,2)):ae<=10?(Ne(J,N,J.bl_tree),xe(J,ae-3,3)):(Ne(J,A,J.bl_tree),xe(J,ae-11,7));U=de,Se=(ae=0)===R?(_e=138,3):de===R?(_e=6,3):(_e=7,4)}}c(le);var Q=!1;function G(J,se,fe,pe){xe(J,(d<<1)+(pe?1:0),3),(function(de,U,R,ae){j(de),ce(de,R),ce(de,~R),s.arraySet(de.pending_buf,de.window,U,R,de.pending),de.pending+=R})(J,se,fe)}i._tr_init=function(J){Q||((function(){var se,fe,pe,de,U,R=new Array(g+1);for(de=pe=0;de<u-1;de++)for(ne[de]=pe,se=0;se<1<<T[de];se++)L[pe++]=de;for(L[pe-1]=de,de=U=0;de<16;de++)for(le[de]=U,se=0;se<1<<F[de];se++)X[U++]=de;for(U>>=7;de<f;de++)for(le[de]=U<<7,se=0;se<1<<F[de]-7;se++)X[256+U++]=de;for(fe=0;fe<=g;fe++)R[fe]=0;for(se=0;se<=143;)H[2*se+1]=8,se++,R[8]++;for(;se<=255;)H[2*se+1]=9,se++,R[9]++;for(;se<=279;)H[2*se+1]=7,se++,R[7]++;for(;se<=287;)H[2*se+1]=8,se++,R[8]++;for(Y(H,p+1,R),se=0;se<f;se++)z[2*se+1]=5,z[2*se]=$(se,5);ie=new oe(H,T,m+1,p,g),ee=new oe(z,F,0,f,g),ue=new oe(new Array(0),k,0,x,_)})(),Q=!0),J.l_desc=new W(J.dyn_ltree,ie),J.d_desc=new W(J.dyn_dtree,ee),J.bl_desc=new W(J.bl_tree,ue),J.bi_buf=0,J.bi_valid=0,E(J)},i._tr_stored_block=G,i._tr_flush_block=function(J,se,fe,pe){var de,U,R=0;0<J.level?(J.strm.data_type===2&&(J.strm.data_type=(function(ae){var _e,Se=4093624447;for(_e=0;_e<=31;_e++,Se>>>=1)if(1&Se&&ae.dyn_ltree[2*_e]!==0)return o;if(ae.dyn_ltree[18]!==0||ae.dyn_ltree[20]!==0||ae.dyn_ltree[26]!==0)return l;for(_e=32;_e<m;_e++)if(ae.dyn_ltree[2*_e]!==0)return l;return o})(J)),he(J,J.l_desc),he(J,J.d_desc),R=(function(ae){var _e;for(I(ae,ae.dyn_ltree,ae.l_desc.max_code),I(ae,ae.dyn_dtree,ae.d_desc.max_code),he(ae,ae.bl_desc),_e=x-1;3<=_e&&ae.bl_tree[2*D[_e]+1]===0;_e--);return ae.opt_len+=3*(_e+1)+5+5+4,_e})(J),de=J.opt_len+3+7>>>3,(U=J.static_len+3+7>>>3)<=de&&(de=U)):de=U=fe+5,fe+4<=de&&se!==-1?G(J,se,fe,pe):J.strategy===4||U===de?(xe(J,2+(pe?1:0),3),B(J,H,z)):(xe(J,4+(pe?1:0),3),(function(ae,_e,Se,ye){var Ae;for(xe(ae,_e-257,5),xe(ae,Se-1,5),xe(ae,ye-4,4),Ae=0;Ae<ye;Ae++)xe(ae,ae.bl_tree[2*D[Ae]+1],3);V(ae,ae.dyn_ltree,_e-1),V(ae,ae.dyn_dtree,Se-1)})(J,J.l_desc.max_code+1,J.d_desc.max_code+1,R+1),B(J,J.dyn_ltree,J.dyn_dtree)),E(J),pe&&j(J)},i._tr_tally=function(J,se,fe){return J.pending_buf[J.d_buf+2*J.last_lit]=se>>>8&255,J.pending_buf[J.d_buf+2*J.last_lit+1]=255&se,J.pending_buf[J.l_buf+J.last_lit]=255&fe,J.last_lit++,se===0?J.dyn_ltree[2*fe]++:(J.matches++,se--,J.dyn_ltree[2*(L[fe]+m+1)]++,J.dyn_dtree[2*re(se)]++),J.last_lit===J.lit_bufsize-1},i._tr_align=function(J){xe(J,2,3),Ne(J,C,H),(function(se){se.bi_valid===16?(ce(se,se.bi_buf),se.bi_buf=0,se.bi_valid=0):8<=se.bi_valid&&(se.pending_buf[se.pending++]=255&se.bi_buf,se.bi_buf>>=8,se.bi_valid-=8)})(J)}},{"../utils/common":41}],53:[function(n,r,i){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,i){(function(s){(function(o,l){if(!o.setImmediate){var c,d,u,m,p=1,f={},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(P){process.nextTick(function(){_(P)})}:(function(){if(o.postMessage&&!o.importScripts){var P=!0,N=o.onmessage;return o.onmessage=function(){P=!1},o.postMessage("","*"),o.onmessage=N,P}})()?(m="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",C,!1):o.attachEvent("onmessage",C),function(P){o.postMessage(m+P,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(P){_(P.data)},function(P){u.port2.postMessage(P)}):v&&"onreadystatechange"in v.createElement("script")?(d=v.documentElement,function(P){var N=v.createElement("script");N.onreadystatechange=function(){_(P),N.onreadystatechange=null,d.removeChild(N),N=null},d.appendChild(N)}):function(P){setTimeout(_,0,P)},g.setImmediate=function(P){typeof P!="function"&&(P=new Function(""+P));for(var N=new Array(arguments.length-1),A=0;A<N.length;A++)N[A]=arguments[A+1];var T={callback:P,args:N};return f[p]=T,c(p),p++},g.clearImmediate=b}function b(P){delete f[P]}function _(P){if(x)setTimeout(_,0,P);else{var N=f[P];if(N){x=!0;try{(function(A){var T=A.callback,F=A.args;switch(F.length){case 0:T();break;case 1:T(F[0]);break;case 2:T(F[0],F[1]);break;case 3:T(F[0],F[1],F[2]);break;default:T.apply(l,F)}})(N)}finally{b(P),x=!1}}}}function C(P){P.source===o&&typeof P.data=="string"&&P.data.indexOf(m)===0&&_(+P.data.slice(m.length))}})(typeof self>"u"?s===void 0?this:s:self)}).call(this,typeof j_<"u"?j_:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(ZM)),ZM.exports}var kke=_ke();const Nke=mc(kke);function Cke(t){const e=new fi;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 B6=Cke;async function H6(t,e=0){const n=[],r=t.getElementsByTagName("mesh");for(let i=0;i<r.length;i++){const s=r[i],o=[],l=[],c=s.getElementsByTagName("vertex");for(let u=0;u<c.length;u++){const m=c[u];o.push(parseFloat(m.getAttribute("x")||"0"),parseFloat(m.getAttribute("y")||"0"),parseFloat(m.getAttribute("z")||"0"))}const d=s.getElementsByTagName("triangle");for(let u=0;u<d.length;u++){const m=d[u];l.push(parseInt(m.getAttribute("v1")||"0"),parseInt(m.getAttribute("v2")||"0"),parseInt(m.getAttribute("v3")||"0"))}o.length>0&&l.length>0&&n.push({vertices:o,triangles:l,extruder:e})}return n}function q6(t){const e=Array.from(t.attributes).find(r=>{const i=r.name.toLowerCase();return i==="plate_id"||i==="plater_id"||i==="plateid"||i==="platerid"||i.endsWith(":plate_id")||i.endsWith(":plater_id")});if(!e?.value)return null;const n=Number.parseInt(e.value,10);return Number.isFinite(n)?n:null}async function Pke(t){let e;try{e=await Nke.loadAsync(t)}catch{throw new Error("Unsupported file format")}const n=new Map,r=[],i=new Map,s=new Map,o=new DOMParser;async function l(C){const P=C.startsWith("/")?C.slice(1):C,N=e.files[P];if(!N)return null;const A=await N.async("string");return o.parseFromString(A,"application/xml")}const c=new Map,d=new Map,u=new Map,m=new Map,p=e.files["Metadata/model_settings.config"];if(p)try{const C=await p.async("string"),P=o.parseFromString(C,"application/xml"),N=P.getElementsByTagName("object");for(let T=0;T<N.length;T++){const F=N[T],k=F.getAttribute("id");if(!k)continue;const D=Array.from(F.children).filter(L=>L.tagName==="metadata"&&L.getAttribute("key")==="extruder");if(D.length>0){const L=D[0].getAttribute("value");L&&c.set(k,Math.max(0,parseInt(L,10)-1))}const z=Array.from(F.children).find(L=>L.tagName==="metadata"&&L.getAttribute("key")==="name")?.getAttribute("value");z&&u.set(k,z);const X=F.getElementsByTagName("part");for(let L=0;L<X.length;L++){const ne=X[L],ie=ne.getAttribute("id");if(!ie)continue;const ee=Array.from(ne.children).filter(ue=>ue.tagName==="metadata"&&ue.getAttribute("key")==="extruder");if(ee.length>0){const ue=ee[0].getAttribute("value");ue&&d.set(`${k}:${ie}`,Math.max(0,parseInt(ue,10)-1))}}}const A=P.getElementsByTagName("plate");for(let T=0;T<A.length;T++){const F=A[T];let k=null;const D=F.getElementsByTagName("metadata");let H=0,z=0;for(let L=0;L<D.length;L++){const ne=D[L],ie=ne.getAttribute("key");if(ie==="plater_id"||ie==="plate_id"){const ee=ne.getAttribute("value");if(ee){const ue=Number.parseInt(ee,10);Number.isFinite(ue)&&(k=ue)}}else if(ie==="pos_x"){const ee=ne.getAttribute("value"),ue=ee?Number.parseFloat(ee):Number.NaN;Number.isFinite(ue)&&(H=ue)}else if(ie==="pos_y"){const ee=ne.getAttribute("value"),ue=ee?Number.parseFloat(ee):Number.NaN;Number.isFinite(ue)&&(z=ue)}}if(k==null)continue;(H!==0||z!==0)&&s.set(k,{offsetX:H,offsetY:z});const X=F.getElementsByTagName("model_instance");for(let L=0;L<X.length;L++){const ie=X[L].getElementsByTagName("metadata");for(let ee=0;ee<ie.length;ee++){const ue=ie[ee];if(ue.getAttribute("key")==="object_id"){const le=ue.getAttribute("value");le&&m.set(le,k)}}}}}catch{}const f=new Map,x=Object.keys(e.files).filter(C=>C.startsWith("Metadata/plate_")&&C.endsWith(".json"));for(const C of x){const P=C.match(/^Metadata\/plate_(\d+)\.json$/);if(!P)continue;const N=Number.parseInt(P[1],10);if(Number.isFinite(N))try{const A=await e.files[C].async("string"),T=JSON.parse(A),F=T.bbox_objects??[];for(const k of F)k?.name&&f.set(k.name,N);if(Array.isArray(T.bbox_all)&&T.bbox_all.length>=4){const[k,D,H,z]=T.bbox_all;[k,D,H,z].every(X=>Number.isFinite(X))&&i.set(N,{minX:k,minY:D,maxX:H,maxY:z})}}catch{}}const v=Object.keys(e.files).find(C=>C==="3D/3dmodel.model"||C.endsWith("/3dmodel.model"));if(!v){const C=Object.keys(e.files).find(P=>P.endsWith(".model"));if(C){const P=await l(C);if(P){const N=await H6(P,0);N.length>0&&n.set("1",{id:"1",meshes:N,defaultExtruder:0})}}return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s}}const g=await l(v);if(!g)return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s};const b=g.getElementsByTagName("object");for(let C=0;C<b.length;C++){const P=b[C],N=P.getAttribute("id");if(!N)continue;const A=q6(P)??m.get(N)??null;let T=c.get(N)??-1;if(T<0){const H=P.getAttribute("p:extruder")||P.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","extruder")||"1";T=Math.max(0,parseInt(H,10)-1)}const F=[],k=P.getElementsByTagName("mesh");for(let H=0;H<k.length;H++){const z=k[H],X=[],L=[],ne=z.getElementsByTagName("vertex");for(let ee=0;ee<ne.length;ee++){const ue=ne[ee];X.push(parseFloat(ue.getAttribute("x")||"0"),parseFloat(ue.getAttribute("y")||"0"),parseFloat(ue.getAttribute("z")||"0"))}const ie=z.getElementsByTagName("triangle");for(let ee=0;ee<ie.length;ee++){const ue=ie[ee];L.push(parseInt(ue.getAttribute("v1")||"0"),parseInt(ue.getAttribute("v2")||"0"),parseInt(ue.getAttribute("v3")||"0"))}X.length>0&&L.length>0&&F.push({vertices:X,triangles:L,extruder:T})}const D=P.getElementsByTagName("component");for(let H=0;H<D.length;H++){const z=D[H],X=z.getAttribute("p:path")||z.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","path"),L=z.getAttribute("objectid");if(X){const ne=await l(X);if(ne){const ie=L?`${N}:${L}`:null,ee=ie?d.get(ie)??T:T,ue=await H6(ne,ee),le=z.getAttribute("transform"),oe=B6(le);for(const W of ue)if(le){const re=[];for(let ce=0;ce<W.vertices.length;ce+=3){const xe=new Tt(W.vertices[ce],W.vertices[ce+1],W.vertices[ce+2]);xe.applyMatrix4(oe),re.push(xe.x,xe.y,xe.z)}F.push({vertices:re,triangles:W.triangles,extruder:W.extruder})}else F.push(W)}}}F.length>0&&n.set(N,{id:N,meshes:F,defaultExtruder:T,plateId:A})}const _=g.getElementsByTagName("build");if(_.length>0){const C=_[0].getElementsByTagName("item");for(let P=0;P<C.length;P++){const N=C[P],A=N.getAttribute("objectid");if(!A)continue;const T=B6(N.getAttribute("transform")),F=q6(N),k=n.get(A)?.plateId??null,D=u.get(A),H=D?f.get(D)??null:null;r.push({objectId:A,transform:T,plateId:F??k??H??null})}}return{objects:n,buildItems:r,plateBounds:i,plateOffsets:s}}function $6(t){const e=new sc,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 Zs(n,3)),e.setIndex(t.triangles),e.computeVertexNormals(),e}function Tke(t){t.traverse(e=>{if(e instanceof oc)if(e.geometry.dispose(),Array.isArray(e.material))for(const n of e.material)n.dispose();else e.material.dispose()})}function Ake(t,e,n){const{objects:r,buildItems:i}=t,s=new ax,o=m=>{const f=n?.[m]||"#00ae42",x=new lr(f);return new AZ({color:x,shininess:30,flatShading:!1})},l=new Map,c=i.some(m=>m.plateId!=null),d=e==null||!c?i:i.filter(m=>m.plateId===e),u=d.length>0?d:i;if(u.length>0)for(const m of u){const p=r.get(m.objectId);if(p)for(const f of p.meshes){const x=m.extruder??f.extruder,v=[];for(let b=0;b<f.vertices.length;b+=3){const _=new Tt(f.vertices[b],f.vertices[b+1],f.vertices[b+2]);_.applyMatrix4(m.transform),v.push(_.x,_.y,_.z)}const g=$6({vertices:v,triangles:f.triangles});l.has(x)||l.set(x,[]),l.get(x).push(g)}}else for(const m of r.values())for(const p of m.meshes){const f=p.extruder,x=$6(p);l.has(f)||l.set(f,[]),l.get(f).push(x)}for(const[m,p]of l){if(p.length===0)continue;const f=p.length===1?p[0]:wke(p,!1);if(f){const x=o(m),v=new oc(f,x);s.add(v)}if(p.length>1)for(const x of p)x.dispose()}return s}function IZ({url:t,fileType:e,buildVolume:n={x:256,y:256,z:256},filamentColors:r,selectedPlateId:i=null,className:s=""}){const{t:o}=Rt(),l=w.useRef(null),c=w.useRef(null),d=w.useRef(null),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=w.useRef(null),x=w.useRef(null),[v,g]=w.useState(!0),[b,_]=w.useState(null),[C,P]=w.useState(null),[N,A]=w.useState(null);w.useEffect(()=>{if(!l.current)return;const k=l.current,D=k.clientWidth,H=k.clientHeight,z=new t0e;z.background=new lr(1710618),d.current=z;const X=new ql(45,D/H,.1,1e4);X.position.set(150,150,150),u.current=X;const L=new ske({antialias:!0});L.setSize(D,H),L.setPixelRatio(window.devicePixelRatio),k.appendChild(L.domElement),c.current=L;const ne=new lke(X,L.domElement);ne.enableDamping=!0,ne.dampingFactor=.05,m.current=ne;const ie=new g0e(16777215,.6);z.add(ie);const ee=new u6(16777215,.8);ee.position.set(100,100,100),z.add(ee);const ue=new u6(16777215,.4);ue.position.set(-100,50,-100),z.add(ue);const le=Math.max(n.x,n.y),oe=Math.ceil(le/16),W=new x0e(le,oe,4473924,3355443);z.add(W),x.current=W;const re=new VO(n.x,n.y),ce=new HO({color:44610,transparent:!0,opacity:.15,side:bd}),xe=new oc(re,ce);xe.rotation.x=-Math.PI/2,xe.position.y=-.5,z.add(xe),f.current=xe;let Ne;const $=()=>{Ne=requestAnimationFrame($),ne.update(),L.render(z,X)};$(),g(!0),_(null),P(null),A(null);const Y=(e||t.split("?")[0].split(".").pop()||"").toLowerCase(),E={},j=om();j&&(E.Authorization=`Bearer ${j}`),Y==="stl"?fetch(t,{headers:E}).then(B=>{if(!B.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return B.arrayBuffer()}).then(B=>{const I=new Ske().parse(B);I.computeVertexNormals(),I.rotateX(-Math.PI/2),A(I)}).catch(B=>{_(B.message),g(!1)}):Y==="3mf"?fetch(t,{headers:E}).then(B=>{if(!B.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return B.arrayBuffer()}).then(Pke).then(B=>{if(B.objects.size===0)throw new Error(o("modelViewer.errors.noMeshes"));P(B)}).catch(B=>{_(B.message),g(!1)}):(_(o("modelViewer.errors.unsupportedFormat")),g(!1));const O=()=>{if(!k)return;const B=k.clientWidth,he=k.clientHeight;B===0||he===0||(X.aspect=B/he,X.updateProjectionMatrix(),L.setSize(B,he))};window.addEventListener("resize",O);const K=new ResizeObserver(()=>{O()});return K.observe(k),()=>{window.removeEventListener("resize",O),K.disconnect(),cancelAnimationFrame(Ne),ne.dispose(),L.dispose(),k.removeChild(L.domElement),p.current=null,f.current=null,x.current=null}},[t,n,e,o]),w.useEffect(()=>{if(!d.current||!u.current||!m.current||!C&&!N)return;p.current&&(d.current.remove(p.current),Tke(p.current));const k=!!N,D=k?(()=>{const Y=r?.[0]||"#00ae42",E=new AZ({color:new lr(Y),shininess:30}),j=new oc(N,E),O=new ax;return O.add(j),O})():Ake(C,i??null,r);p.current=D,d.current.add(D);const H=new Kh().setFromObject(D),z=H.getCenter(new Tt);D.position.y=-H.min.y;const X=!k&&i!=null&&C.buildItems.length>0?C.plateBounds.get(i):void 0,L=!k&&i!=null?C.plateOffsets.get(i):void 0,ne=k||C.buildItems.length===0||i!=null&&!X&&!L,ie=ne?-z.x:0,ee=ne?-z.z:0;let ue=0,le=0;if(!k&&i!=null&&C.buildItems.length>0&&X){const Y=new Kh().setFromObject(D);ue=Y.min.x-X.minX,le=Y.min.z-X.minY}const oe=n.x/2,W=n.y/2;!k&&i!=null&&C.buildItems.length>0&&X?(D.position.x=ie-ue,D.position.z=ee-le):!k&&i!=null&&L?(D.position.x=ie+(oe-L.offsetX),D.position.z=ee+(W-L.offsetY)):ne?(D.position.x=ie+oe,D.position.z=ee+W):(D.position.x=ie,D.position.z=ee),f.current&&(f.current.position.x=oe,f.current.position.z=W),x.current&&(x.current.position.x=oe,x.current.position.z=W);const re=new Kh().setFromObject(D),ce=re.getCenter(new Tt),xe=re.getSize(new Tt),$=Math.max(xe.x,xe.y,xe.z)*1.8;u.current.position.set(ce.x+$*.7,ce.y+$*.5,ce.z+$*.7),m.current.target.copy(ce),m.current.update(),g(!1)},[C,N,i,r,n]);const T=()=>{u.current&&m.current&&(u.current.position.set(150,150,150),m.current.target.set(0,50,0),m.current.update())},F=k=>{u.current&&u.current.position.multiplyScalar(k)};return a.jsxs("div",{className:`relative ${s}`,children:[a.jsx("div",{ref:l,className:"w-full h-full min-h-[400px]"}),v&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}),b&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx("p",{className:"text-red-400",children:b})}),!v&&!b&&a.jsxs("div",{className:"absolute bottom-4 right-4 flex gap-2",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>F(.8),children:a.jsx(NO,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>F(1.25),children:a.jsx(CO,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:T,children:a.jsx(eo,{className:"w-4 h-4"})})]})]})}const zP="159",Sb={ROTATE:0,DOLLY:1,PAN:2},_b={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},jke=0,V6=1,Mke=2,zZ=1,Eke=2,Pu=3,op=0,jo=1,Ru=2,Xh=0,fx=1,G6=2,W6=3,K6=4,Dke=5,pf=100,Fke=101,Rke=102,X6=103,Y6=104,Lke=200,Oke=201,Ike=202,zke=203,WF=204,KF=205,Uke=206,Bke=207,Hke=208,qke=209,$ke=210,Vke=211,Gke=212,Wke=213,Kke=214,Xke=0,Yke=1,Qke=2,yN=3,Zke=4,Jke=5,eNe=6,tNe=7,KO=0,nNe=1,rNe=2,Yh=0,aNe=1,iNe=2,sNe=3,oNe=4,lNe=5,UZ=300,Rx=301,Lx=302,XF=303,YF=304,UP=306,QF=1e3,jc=1001,ZF=1002,cs=1003,Q6=1004,JM=1005,$l=1006,cNe=1007,X0=1008,Qh=1009,dNe=1010,uNe=1011,XO=1012,BZ=1013,Mh=1014,qu=1015,Y0=1016,HZ=1017,qZ=1018,Ef=1020,mNe=1021,Vl=1023,hNe=1024,pNe=1025,Df=1026,Ox=1027,fNe=1028,$Z=1029,gNe=1030,VZ=1031,GZ=1033,eE=33776,tE=33777,nE=33778,rE=33779,Z6=35840,J6=35841,eq=35842,tq=35843,WZ=36196,nq=37492,rq=37496,aq=37808,iq=37809,sq=37810,oq=37811,lq=37812,cq=37813,dq=37814,uq=37815,mq=37816,hq=37817,pq=37818,fq=37819,gq=37820,bq=37821,aE=36492,xq=36494,yq=36495,bNe=36283,vq=36284,wq=36285,Sq=36286,KZ=3e3,Ff=3001,xNe=3200,yNe=3201,XZ=0,vNe=1,Gl="",ds="srgb",cm="srgb-linear",YO="display-p3",BP="display-p3-linear",vN="linear",ga="srgb",wN="rec709",SN="p3",kb=7680,_q=519,wNe=512,SNe=513,_Ne=514,YZ=515,kNe=516,NNe=517,CNe=518,PNe=519,JF=35044,kq="300 es",eR=1035,Sd=2e3,Q0=2001;class _g{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 i=this._listeners[e];if(i!==void 0){const s=i.indexOf(n);s!==-1&&i.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 i=r.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}}const ks=["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 Nq=1234567;const m0=Math.PI/180,Z0=180/Math.PI;function Qu(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(ks[t&255]+ks[t>>8&255]+ks[t>>16&255]+ks[t>>24&255]+"-"+ks[e&255]+ks[e>>8&255]+"-"+ks[e>>16&15|64]+ks[e>>24&255]+"-"+ks[n&63|128]+ks[n>>8&255]+"-"+ks[n>>16&255]+ks[n>>24&255]+ks[r&255]+ks[r>>8&255]+ks[r>>16&255]+ks[r>>24&255]).toLowerCase()}function us(t,e,n){return Math.max(e,Math.min(n,t))}function QO(t,e){return(t%e+e)%e}function TNe(t,e,n,r,i){return r+(t-e)*(i-r)/(n-e)}function ANe(t,e,n){return t!==e?(n-t)/(e-t):0}function h0(t,e,n){return(1-n)*t+n*e}function jNe(t,e,n,r){return h0(t,e,1-Math.exp(-n*r))}function MNe(t,e=1){return e-Math.abs(QO(t,e*2)-e)}function ENe(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function DNe(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function FNe(t,e){return t+Math.floor(Math.random()*(e-t+1))}function RNe(t,e){return t+Math.random()*(e-t)}function LNe(t){return t*(.5-Math.random())}function ONe(t){t!==void 0&&(Nq=t);let e=Nq+=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 INe(t){return t*m0}function zNe(t){return t*Z0}function tR(t){return(t&t-1)===0&&t!==0}function UNe(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function _N(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function BNe(t,e,n,r,i){const s=Math.cos,o=Math.sin,l=s(n/2),c=o(n/2),d=s((e+r)/2),u=o((e+r)/2),m=s((e-r)/2),p=o((e-r)/2),f=s((r-e)/2),x=o((r-e)/2);switch(i){case"XYX":t.set(l*u,c*m,c*p,l*d);break;case"YZY":t.set(c*p,l*u,c*m,l*d);break;case"ZXZ":t.set(c*m,c*p,l*u,l*d);break;case"XZX":t.set(l*u,c*x,c*f,l*d);break;case"YXY":t.set(c*f,l*u,c*x,l*d);break;case"ZYZ":t.set(c*x,c*f,l*u,l*d);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function xd(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 Gr(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 QZ={DEG2RAD:m0,RAD2DEG:Z0,generateUUID:Qu,clamp:us,euclideanModulo:QO,mapLinear:TNe,inverseLerp:ANe,lerp:h0,damp:jNe,pingpong:MNe,smoothstep:ENe,smootherstep:DNe,randInt:FNe,randFloat:RNe,randFloatSpread:LNe,seededRandom:ONe,degToRad:INe,radToDeg:zNe,isPowerOfTwo:tR,ceilPowerOfTwo:UNe,floorPowerOfTwo:_N,setQuaternionFromProperEuler:BNe,normalize:Gr,denormalize:xd};class Gn{constructor(e=0,n=0){Gn.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,i=e.elements;return this.x=i[0]*n+i[3]*r+i[6],this.y=i[1]*n+i[4]*r+i[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(us(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),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*i+e.x,this.y=s*i+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 ur{constructor(e,n,r,i,s,o,l,c,d){ur.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,i,s,o,l,c,d)}set(e,n,r,i,s,o,l,c,d){const u=this.elements;return u[0]=e,u[1]=i,u[2]=l,u[3]=n,u[4]=s,u[5]=c,u[6]=r,u[7]=o,u[8]=d,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,i=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],d=r[1],u=r[4],m=r[7],p=r[2],f=r[5],x=r[8],v=i[0],g=i[3],b=i[6],_=i[1],C=i[4],P=i[7],N=i[2],A=i[5],T=i[8];return s[0]=o*v+l*_+c*N,s[3]=o*g+l*C+c*A,s[6]=o*b+l*P+c*T,s[1]=d*v+u*_+m*N,s[4]=d*g+u*C+m*A,s[7]=d*b+u*P+m*T,s[2]=p*v+f*_+x*N,s[5]=p*g+f*C+x*A,s[8]=p*b+f*P+x*T,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],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8];return n*o*u-n*l*d-r*s*u+r*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=u*o-l*d,p=l*c-u*s,f=d*s-o*c,x=n*m+r*p+i*f;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/x;return e[0]=m*v,e[1]=(i*d-u*r)*v,e[2]=(l*r-i*o)*v,e[3]=p*v,e[4]=(u*n-i*c)*v,e[5]=(i*s-l*n)*v,e[6]=f*v,e[7]=(r*c-d*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,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(r*c,r*d,-r*(c*o+d*l)+o+e,-i*d,i*c,-i*(-d*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(iE.makeScale(e,n)),this}rotate(e){return this.premultiply(iE.makeRotation(-e)),this}translate(e,n){return this.premultiply(iE.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 i=0;i<9;i++)if(n[i]!==r[i])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 iE=new ur;function ZZ(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function kN(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function HNe(){const t=kN("canvas");return t.style.display="block",t}const Cq={};function p0(t){t in Cq||(Cq[t]=!0,console.warn(t))}const Pq=new ur().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Tq=new ur().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),i1={[cm]:{transfer:vN,primaries:wN,toReference:t=>t,fromReference:t=>t},[ds]:{transfer:ga,primaries:wN,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[BP]:{transfer:vN,primaries:SN,toReference:t=>t.applyMatrix3(Tq),fromReference:t=>t.applyMatrix3(Pq)},[YO]:{transfer:ga,primaries:SN,toReference:t=>t.convertSRGBToLinear().applyMatrix3(Tq),fromReference:t=>t.applyMatrix3(Pq).convertLinearToSRGB()}},qNe=new Set([cm,BP]),Wr={enabled:!0,_workingColorSpace:cm,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(!qNe.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=i1[e].toReference,i=i1[n].fromReference;return i(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 i1[t].primaries},getTransfer:function(t){return t===Gl?vN:i1[t].transfer}};function gx(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function sE(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let Nb;class JZ{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Nb===void 0&&(Nb=kN("canvas")),Nb.width=e.width,Nb.height=e.height;const r=Nb.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=Nb}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=kN("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const i=r.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=gx(s[o]/255)*255;return r.putImageData(i,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(gx(n[r]/255)*255):n[r]=gx(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 $Ne=0;class eJ{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:$Ne++}),this.uuid=Qu(),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:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,l=i.length;o<l;o++)i[o].isDataTexture?s.push(oE(i[o].image)):s.push(oE(i[o]))}else s=oE(i);r.url=s}return n||(e.images[this.uuid]=r),r}}function oE(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?JZ.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 VNe=0;class Mo extends _g{constructor(e=Mo.DEFAULT_IMAGE,n=Mo.DEFAULT_MAPPING,r=jc,i=jc,s=$l,o=X0,l=Vl,c=Qh,d=Mo.DEFAULT_ANISOTROPY,u=Gl){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:VNe++}),this.uuid=Qu(),this.name="",this.source=new eJ(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new Gn(0,0),this.repeat=new Gn(1,1),this.center=new Gn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ur,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof u=="string"?this.colorSpace=u:(p0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=u===Ff?ds:Gl),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!==UZ)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case QF:e.x=e.x-Math.floor(e.x);break;case jc:e.x=e.x<0?0:1;break;case ZF: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 QF:e.y=e.y-Math.floor(e.y);break;case jc:e.y=e.y<0?0:1;break;case ZF: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 p0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===ds?Ff:KZ}set encoding(e){p0("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===Ff?ds:Gl}}Mo.DEFAULT_IMAGE=null;Mo.DEFAULT_MAPPING=UZ;Mo.DEFAULT_ANISOTROPY=1;class Xr{constructor(e=0,n=0,r=0,i=1){Xr.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=i}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,i){return this.x=e,this.y=n,this.z=r,this.w=i,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,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*i+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,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],x=c[9],v=c[2],g=c[6],b=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-v)<.01&&Math.abs(x-g)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+v)<.1&&Math.abs(x+g)<.1&&Math.abs(d+f+b-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const C=(d+1)/2,P=(f+1)/2,N=(b+1)/2,A=(u+p)/4,T=(m+v)/4,F=(x+g)/4;return C>P&&C>N?C<.01?(r=0,i=.707106781,s=.707106781):(r=Math.sqrt(C),i=A/r,s=T/r):P>N?P<.01?(r=.707106781,i=0,s=.707106781):(i=Math.sqrt(P),r=A/i,s=F/i):N<.01?(r=.707106781,i=.707106781,s=0):(s=Math.sqrt(N),r=T/s,i=F/s),this.set(r,i,s,n),this}let _=Math.sqrt((g-x)*(g-x)+(m-v)*(m-v)+(p-u)*(p-u));return Math.abs(_)<.001&&(_=1),this.x=(g-x)/_,this.y=(m-v)/_,this.z=(p-u)/_,this.w=Math.acos((d+f+b-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 GNe extends _g{constructor(e=1,n=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new Xr(0,0,e,n),this.scissorTest=!1,this.viewport=new Xr(0,0,e,n);const i={width:e,height:n,depth:1};r.encoding!==void 0&&(p0("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),r.colorSpace=r.encoding===Ff?ds:Gl),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:$l,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},r),this.texture=new Mo(i,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 eJ(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 ng extends GNe{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}}class tJ extends Mo{constructor(e=null,n=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=cs,this.minFilter=cs,this.wrapR=jc,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class WNe extends Mo{constructor(e=null,n=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:i},this.magFilter=cs,this.minFilter=cs,this.wrapR=jc,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class rg{constructor(e=0,n=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=i}static slerpFlat(e,n,r,i,s,o,l){let c=r[i+0],d=r[i+1],u=r[i+2],m=r[i+3];const p=s[o+0],f=s[o+1],x=s[o+2],v=s[o+3];if(l===0){e[n+0]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m;return}if(l===1){e[n+0]=p,e[n+1]=f,e[n+2]=x,e[n+3]=v;return}if(m!==v||c!==p||d!==f||u!==x){let g=1-l;const b=c*p+d*f+u*x+m*v,_=b>=0?1:-1,C=1-b*b;if(C>Number.EPSILON){const N=Math.sqrt(C),A=Math.atan2(N,b*_);g=Math.sin(g*A)/N,l=Math.sin(l*A)/N}const P=l*_;if(c=c*g+p*P,d=d*g+f*P,u=u*g+x*P,m=m*g+v*P,g===1-l){const N=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=N,d*=N,u*=N,m*=N}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,r,i,s,o){const l=r[i],c=r[i+1],d=r[i+2],u=r[i+3],m=s[o],p=s[o+1],f=s[o+2],x=s[o+3];return e[n]=l*x+u*m+c*f-d*p,e[n+1]=c*x+u*p+d*m-l*f,e[n+2]=d*x+u*f+l*p-c*m,e[n+3]=u*x-l*m-c*p-d*f,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,i){return this._x=e,this._y=n,this._z=r,this._w=i,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,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(r/2),u=l(i/2),m=l(s/2),p=c(r/2),f=c(i/2),x=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m-p*f*x;break;case"YXZ":this._x=p*u*m+d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m+p*f*x;break;case"ZXY":this._x=p*u*m-d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m-p*f*x;break;case"ZYX":this._x=p*u*m-d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m+p*f*x;break;case"YZX":this._x=p*u*m+d*f*x,this._y=d*f*m+p*u*x,this._z=d*u*x-p*f*m,this._w=d*u*m-p*f*x;break;case"XZY":this._x=p*u*m-d*f*x,this._y=d*f*m-p*u*x,this._z=d*u*x+p*f*m,this._w=d*u*m+p*f*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,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],i=n[4],s=n[8],o=n[1],l=n[5],c=n[9],d=n[2],u=n[6],m=n[10],p=r+l+m;if(p>0){const f=.5/Math.sqrt(p+1);this._w=.25/f,this._x=(u-c)*f,this._y=(s-d)*f,this._z=(o-i)*f}else if(r>l&&r>m){const f=2*Math.sqrt(1+r-l-m);this._w=(u-c)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+d)/f}else if(l>m){const f=2*Math.sqrt(1+l-r-m);this._w=(s-d)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(c+u)/f}else{const f=2*Math.sqrt(1+m-r-l);this._w=(o-i)/f,this._x=(s+d)/f,this._y=(c+u)/f,this._z=.25*f}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(us(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const i=Math.min(1,n/r);return this.slerp(e,i),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,i=e._y,s=e._z,o=e._w,l=n._x,c=n._y,d=n._z,u=n._w;return this._x=r*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-r*d,this._z=s*u+o*d+r*c-i*l,this._w=o*u-r*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const r=this._x,i=this._y,s=this._z,o=this._w;let l=o*e._w+r*e._x+i*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=i,this._z=s,this;const c=1-l*l;if(c<=Number.EPSILON){const f=1-n;return this._w=f*o+n*this._w,this._x=f*r+n*this._x,this._y=f*i+n*this._y,this._z=f*s+n*this._z,this.normalize(),this._onChangeCallback(),this}const d=Math.sqrt(c),u=Math.atan2(d,l),m=Math.sin((1-n)*u)/d,p=Math.sin(n*u)/d;return this._w=o*m+this._w*p,this._x=r*m+this._x*p,this._y=i*m+this._y*p,this._z=s*m+this._z*p,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),i=2*Math.PI*Math.random(),s=2*Math.PI*Math.random();return this.set(n*Math.cos(i),r*Math.sin(s),r*Math.cos(s),n*Math.sin(i))}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 ct{constructor(e=0,n=0,r=0){ct.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(Aq.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(Aq.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*i,this.y=s[1]*n+s[4]*r+s[7]*i,this.z=s[2]*n+s[5]*r+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*r),u=2*(l*n-s*i),m=2*(s*r-o*n);return this.x=n+c*d+o*m-l*u,this.y=r+c*u+l*d-s*m,this.z=i+c*m+s*u-o*d,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,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*i,this.y=s[1]*n+s[5]*r+s[9]*i,this.z=s[2]*n+s[6]*r+s[10]*i,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,i=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=i*c-s*l,this.y=s*o-r*c,this.z=r*l-i*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 lE.copy(this).projectOnVector(e),this.sub(lE)}reflect(e){return this.sub(lE.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(us(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,i=this.z-e.z;return n*n+r*r+i*i}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 i=Math.sin(n)*e;return this.x=i*Math.sin(r),this.y=Math.cos(n)*e,this.z=i*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(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=i,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 lE=new ct,Aq=new rg;class Jl{constructor(e=new ct(1/0,1/0,1/0),n=new ct(-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(Nc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(Nc.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=Nc.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,Nc):Nc.fromBufferAttribute(s,o),Nc.applyMatrix4(e.matrixWorld),this.expandByPoint(Nc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),s1.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),s1.copy(r.boundingBox)),s1.applyMatrix4(e.matrixWorld),this.union(s1)}const i=e.children;for(let s=0,o=i.length;s<o;s++)this.expandByObject(i[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,Nc),Nc.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(_v),o1.subVectors(this.max,_v),Cb.subVectors(e.a,_v),Pb.subVectors(e.b,_v),Tb.subVectors(e.c,_v),rh.subVectors(Pb,Cb),ah.subVectors(Tb,Pb),Qp.subVectors(Cb,Tb);let n=[0,-rh.z,rh.y,0,-ah.z,ah.y,0,-Qp.z,Qp.y,rh.z,0,-rh.x,ah.z,0,-ah.x,Qp.z,0,-Qp.x,-rh.y,rh.x,0,-ah.y,ah.x,0,-Qp.y,Qp.x,0];return!cE(n,Cb,Pb,Tb,o1)||(n=[1,0,0,0,1,0,0,0,1],!cE(n,Cb,Pb,Tb,o1))?!1:(l1.crossVectors(rh,ah),n=[l1.x,l1.y,l1.z],cE(n,Cb,Pb,Tb,o1))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Nc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Nc).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:(bu[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),bu[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),bu[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),bu[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),bu[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),bu[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),bu[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),bu[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(bu),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 bu=[new ct,new ct,new ct,new ct,new ct,new ct,new ct,new ct],Nc=new ct,s1=new Jl,Cb=new ct,Pb=new ct,Tb=new ct,rh=new ct,ah=new ct,Qp=new ct,_v=new ct,o1=new ct,l1=new ct,Zp=new ct;function cE(t,e,n,r,i){for(let s=0,o=t.length-3;s<=o;s+=3){Zp.fromArray(t,s);const l=i.x*Math.abs(Zp.x)+i.y*Math.abs(Zp.y)+i.z*Math.abs(Zp.z),c=e.dot(Zp),d=n.dot(Zp),u=r.dot(Zp);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const KNe=new Jl,kv=new ct,dE=new ct;class Cd{constructor(e=new ct,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):KNe.setFromPoints(e).getCenter(r);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),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;kv.subVectors(e,this.center);const n=kv.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),i=(r-this.radius)*.5;this.center.addScaledVector(kv,i/r),this.radius+=i}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):(dE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(kv.copy(e.center).add(dE)),this.expandByPoint(kv.copy(e.center).sub(dE))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const xu=new ct,uE=new ct,c1=new ct,ih=new ct,mE=new ct,d1=new ct,hE=new ct;class ZO{constructor(e=new ct,n=new ct(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,xu)),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=xu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(xu.copy(this.origin).addScaledVector(this.direction,n),xu.distanceToSquared(e))}distanceSqToSegment(e,n,r,i){uE.copy(e).add(n).multiplyScalar(.5),c1.copy(n).sub(e).normalize(),ih.copy(this.origin).sub(uE);const s=e.distanceTo(n)*.5,o=-this.direction.dot(c1),l=ih.dot(this.direction),c=-ih.dot(c1),d=ih.lengthSq(),u=Math.abs(1-o*o);let m,p,f,x;if(u>0)if(m=o*c-l,p=o*l-c,x=s*u,m>=0)if(p>=-x)if(p<=x){const v=1/u;m*=v,p*=v,f=m*(m+o*p+2*l)+p*(o*m+p+2*c)+d}else p=s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p=-s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;else p<=-x?(m=Math.max(0,-(-o*s+l)),p=m>0?-s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d):p<=x?(m=0,p=Math.min(Math.max(-s,-c),s),f=p*(p+2*c)+d):(m=Math.max(0,-(o*s+l)),p=m>0?s:Math.min(Math.max(-s,-c),s),f=-m*m+p*(p+2*c)+d);else p=o>0?-s:s,m=Math.max(0,-(o*p+l)),f=-m*m+p*(p+2*c)+d;return r&&r.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(uE).addScaledVector(c1,p),f}intersectSphere(e,n){xu.subVectors(e.center,this.origin);const r=xu.dot(this.direction),i=xu.dot(xu)-r*r,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),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,i,s,o,l,c;const d=1/this.direction.x,u=1/this.direction.y,m=1/this.direction.z,p=this.origin;return d>=0?(r=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(r=(e.max.x-p.x)*d,i=(e.min.x-p.x)*d),u>=0?(s=(e.min.y-p.y)*u,o=(e.max.y-p.y)*u):(s=(e.max.y-p.y)*u,o=(e.min.y-p.y)*u),r>o||s>i||((s>r||isNaN(r))&&(r=s),(o<i||isNaN(i))&&(i=o),m>=0?(l=(e.min.z-p.z)*m,c=(e.max.z-p.z)*m):(l=(e.max.z-p.z)*m,c=(e.min.z-p.z)*m),r>c||l>i)||((l>r||r!==r)&&(r=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(r>=0?r:i,n)}intersectsBox(e){return this.intersectBox(e,xu)!==null}intersectTriangle(e,n,r,i,s){mE.subVectors(n,e),d1.subVectors(r,e),hE.crossVectors(mE,d1);let o=this.direction.dot(hE),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;ih.subVectors(this.origin,e);const c=l*this.direction.dot(d1.crossVectors(ih,d1));if(c<0)return null;const d=l*this.direction.dot(mE.cross(ih));if(d<0||c+d>o)return null;const u=-l*ih.dot(hE);return u<0?null:this.at(u/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 da{constructor(e,n,r,i,s,o,l,c,d,u,m,p,f,x,v,g){da.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,i,s,o,l,c,d,u,m,p,f,x,v,g)}set(e,n,r,i,s,o,l,c,d,u,m,p,f,x,v,g){const b=this.elements;return b[0]=e,b[4]=n,b[8]=r,b[12]=i,b[1]=s,b[5]=o,b[9]=l,b[13]=c,b[2]=d,b[6]=u,b[10]=m,b[14]=p,b[3]=f,b[7]=x,b[11]=v,b[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 da().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,i=1/Ab.setFromMatrixColumn(e,0).length(),s=1/Ab.setFromMatrixColumn(e,1).length(),o=1/Ab.setFromMatrixColumn(e,2).length();return n[0]=r[0]*i,n[1]=r[1]*i,n[2]=r[2]*i,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,i=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(i),d=Math.sin(i),u=Math.cos(s),m=Math.sin(s);if(e.order==="XYZ"){const p=o*u,f=o*m,x=l*u,v=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+x*d,n[5]=p-v*d,n[9]=-l*c,n[2]=v-p*d,n[6]=x+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,x=d*u,v=d*m;n[0]=p+v*l,n[4]=x*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-x,n[6]=v+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,x=d*u,v=d*m;n[0]=p-v*l,n[4]=-o*m,n[8]=x+f*l,n[1]=f+x*l,n[5]=o*u,n[9]=v-p*l,n[2]=-o*d,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const p=o*u,f=o*m,x=l*u,v=l*m;n[0]=c*u,n[4]=x*d-f,n[8]=p*d+v,n[1]=c*m,n[5]=v*d+p,n[9]=f*d-x,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,x=l*c,v=l*d;n[0]=c*u,n[4]=v-p*m,n[8]=x*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+x,n[10]=p-v*m}else if(e.order==="XZY"){const p=o*c,f=o*d,x=l*c,v=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+v,n[5]=o*u,n[9]=f*m-x,n[2]=x*m-f,n[6]=l*u,n[10]=v*m+p}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(XNe,e,YNe)}lookAt(e,n,r){const i=this.elements;return Xo.subVectors(e,n),Xo.lengthSq()===0&&(Xo.z=1),Xo.normalize(),sh.crossVectors(r,Xo),sh.lengthSq()===0&&(Math.abs(r.z)===1?Xo.x+=1e-4:Xo.z+=1e-4,Xo.normalize(),sh.crossVectors(r,Xo)),sh.normalize(),u1.crossVectors(Xo,sh),i[0]=sh.x,i[4]=u1.x,i[8]=Xo.x,i[1]=sh.y,i[5]=u1.y,i[9]=Xo.y,i[2]=sh.z,i[6]=u1.z,i[10]=Xo.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,i=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],d=r[12],u=r[1],m=r[5],p=r[9],f=r[13],x=r[2],v=r[6],g=r[10],b=r[14],_=r[3],C=r[7],P=r[11],N=r[15],A=i[0],T=i[4],F=i[8],k=i[12],D=i[1],H=i[5],z=i[9],X=i[13],L=i[2],ne=i[6],ie=i[10],ee=i[14],ue=i[3],le=i[7],oe=i[11],W=i[15];return s[0]=o*A+l*D+c*L+d*ue,s[4]=o*T+l*H+c*ne+d*le,s[8]=o*F+l*z+c*ie+d*oe,s[12]=o*k+l*X+c*ee+d*W,s[1]=u*A+m*D+p*L+f*ue,s[5]=u*T+m*H+p*ne+f*le,s[9]=u*F+m*z+p*ie+f*oe,s[13]=u*k+m*X+p*ee+f*W,s[2]=x*A+v*D+g*L+b*ue,s[6]=x*T+v*H+g*ne+b*le,s[10]=x*F+v*z+g*ie+b*oe,s[14]=x*k+v*X+g*ee+b*W,s[3]=_*A+C*D+P*L+N*ue,s[7]=_*T+C*H+P*ne+N*le,s[11]=_*F+C*z+P*ie+N*oe,s[15]=_*k+C*X+P*ee+N*W,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],i=e[8],s=e[12],o=e[1],l=e[5],c=e[9],d=e[13],u=e[2],m=e[6],p=e[10],f=e[14],x=e[3],v=e[7],g=e[11],b=e[15];return x*(+s*c*m-i*d*m-s*l*p+r*d*p+i*l*f-r*c*f)+v*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+g*(+n*d*m-n*l*f-s*o*m+r*o*f+s*l*u-r*d*u)+b*(-i*l*u-n*c*m+n*l*p+i*o*m-r*o*p+r*c*u)}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 i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=n,i[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],i=e[2],s=e[3],o=e[4],l=e[5],c=e[6],d=e[7],u=e[8],m=e[9],p=e[10],f=e[11],x=e[12],v=e[13],g=e[14],b=e[15],_=m*g*d-v*p*d+v*c*f-l*g*f-m*c*b+l*p*b,C=x*p*d-u*g*d-x*c*f+o*g*f+u*c*b-o*p*b,P=u*v*d-x*m*d+x*l*f-o*v*f-u*l*b+o*m*b,N=x*m*c-u*v*c-x*l*p+o*v*p+u*l*g-o*m*g,A=n*_+r*C+i*P+s*N;if(A===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/A;return e[0]=_*T,e[1]=(v*p*s-m*g*s-v*i*f+r*g*f+m*i*b-r*p*b)*T,e[2]=(l*g*s-v*c*s+v*i*d-r*g*d-l*i*b+r*c*b)*T,e[3]=(m*c*s-l*p*s-m*i*d+r*p*d+l*i*f-r*c*f)*T,e[4]=C*T,e[5]=(u*g*s-x*p*s+x*i*f-n*g*f-u*i*b+n*p*b)*T,e[6]=(x*c*s-o*g*s-x*i*d+n*g*d+o*i*b-n*c*b)*T,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*T,e[8]=P*T,e[9]=(x*m*s-u*v*s-x*r*f+n*v*f+u*r*b-n*m*b)*T,e[10]=(o*v*s-x*l*s+x*r*d-n*v*d-o*r*b+n*l*b)*T,e[11]=(u*l*s-o*m*s-u*r*d+n*m*d+o*r*f-n*l*f)*T,e[12]=N*T,e[13]=(u*v*i-x*m*i+x*r*p-n*v*p-u*r*g+n*m*g)*T,e[14]=(x*l*i-o*v*i-x*r*c+n*v*c+o*r*g-n*l*g)*T,e[15]=(o*m*i-u*l*i+u*r*c-n*m*c-o*r*p+n*l*p)*T,this}scale(e){const n=this.elements,r=e.x,i=e.y,s=e.z;return n[0]*=r,n[4]*=i,n[8]*=s,n[1]*=r,n[5]*=i,n[9]*=s,n[2]*=r,n[6]*=i,n[10]*=s,n[3]*=r,n[7]*=i,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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,i))}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),i=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+r,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+r,u*c-i*o,0,d*c-i*l,u*c+i*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,i,s,o){return this.set(1,r,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,r){const i=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,d=s+s,u=o+o,m=l+l,p=s*d,f=s*u,x=s*m,v=o*u,g=o*m,b=l*m,_=c*d,C=c*u,P=c*m,N=r.x,A=r.y,T=r.z;return i[0]=(1-(v+b))*N,i[1]=(f+P)*N,i[2]=(x-C)*N,i[3]=0,i[4]=(f-P)*A,i[5]=(1-(p+b))*A,i[6]=(g+_)*A,i[7]=0,i[8]=(x+C)*T,i[9]=(g-_)*T,i[10]=(1-(p+v))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,r){const i=this.elements;let s=Ab.set(i[0],i[1],i[2]).length();const o=Ab.set(i[4],i[5],i[6]).length(),l=Ab.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],Cc.copy(this);const d=1/s,u=1/o,m=1/l;return Cc.elements[0]*=d,Cc.elements[1]*=d,Cc.elements[2]*=d,Cc.elements[4]*=u,Cc.elements[5]*=u,Cc.elements[6]*=u,Cc.elements[8]*=m,Cc.elements[9]*=m,Cc.elements[10]*=m,n.setFromRotationMatrix(Cc),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,i,s,o,l=Sd){const c=this.elements,d=2*s/(n-e),u=2*s/(r-i),m=(n+e)/(n-e),p=(r+i)/(r-i);let f,x;if(l===Sd)f=-(o+s)/(o-s),x=-2*o*s/(o-s);else if(l===Q0)f=-o/(o-s),x=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+l);return c[0]=d,c[4]=0,c[8]=m,c[12]=0,c[1]=0,c[5]=u,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=x,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,n,r,i,s,o,l=Sd){const c=this.elements,d=1/(n-e),u=1/(r-i),m=1/(o-s),p=(n+e)*d,f=(r+i)*u;let x,v;if(l===Sd)x=(o+s)*m,v=-2*m;else if(l===Q0)x=s*m,v=-1*m;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return c[0]=2*d,c[4]=0,c[8]=0,c[12]=-p,c[1]=0,c[5]=2*u,c[9]=0,c[13]=-f,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 i=0;i<16;i++)if(n[i]!==r[i])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 Ab=new ct,Cc=new da,XNe=new ct(0,0,0),YNe=new ct(1,1,1),sh=new ct,u1=new ct,Xo=new ct,jq=new da,Mq=new rg;class Vw{constructor(e=0,n=0,r=0,i=Vw.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=i}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,i=this._order){return this._x=e,this._y=n,this._z=r,this._order=i,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 i=e.elements,s=i[0],o=i[4],l=i[8],c=i[1],d=i[5],u=i[9],m=i[2],p=i[6],f=i[10];switch(n){case"XYZ":this._y=Math.asin(us(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(p,d),this._z=0);break;case"YXZ":this._x=Math.asin(-us(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(l,f),this._z=Math.atan2(c,d)):(this._y=Math.atan2(-m,s),this._z=0);break;case"ZXY":this._x=Math.asin(us(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(-m,f),this._z=Math.atan2(-o,d)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-us(m,-1,1)),Math.abs(m)<.9999999?(this._x=Math.atan2(p,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,d));break;case"YZX":this._z=Math.asin(us(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,d),this._y=Math.atan2(-m,s)):(this._x=0,this._y=Math.atan2(l,f));break;case"XZY":this._z=Math.asin(-us(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(p,d),this._y=Math.atan2(l,s)):(this._x=Math.atan2(-u,f),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 jq.makeRotationFromQuaternion(e),this.setFromRotationMatrix(jq,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return Mq.setFromEuler(this),this.setFromQuaternion(Mq,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}}Vw.DEFAULT_ORDER="XYZ";class nJ{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 QNe=0;const Eq=new ct,jb=new rg,yu=new da,m1=new ct,Nv=new ct,ZNe=new ct,JNe=new rg,Dq=new ct(1,0,0),Fq=new ct(0,1,0),Rq=new ct(0,0,1),eCe={type:"added"},tCe={type:"removed"};class Js extends _g{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:QNe++}),this.uuid=Qu(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Js.DEFAULT_UP.clone();const e=new ct,n=new Vw,r=new rg,i=new ct(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:i},modelViewMatrix:{value:new da},normalMatrix:{value:new ur}}),this.matrix=new da,this.matrixWorld=new da,this.matrixAutoUpdate=Js.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Js.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new nJ,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 jb.setFromAxisAngle(e,n),this.quaternion.multiply(jb),this}rotateOnWorldAxis(e,n){return jb.setFromAxisAngle(e,n),this.quaternion.premultiply(jb),this}rotateX(e){return this.rotateOnAxis(Dq,e)}rotateY(e){return this.rotateOnAxis(Fq,e)}rotateZ(e){return this.rotateOnAxis(Rq,e)}translateOnAxis(e,n){return Eq.copy(e).applyQuaternion(this.quaternion),this.position.add(Eq.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(Dq,e)}translateY(e){return this.translateOnAxis(Fq,e)}translateZ(e){return this.translateOnAxis(Rq,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(yu.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?m1.copy(e):m1.set(e,n,r);const i=this.parent;this.updateWorldMatrix(!0,!1),Nv.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?yu.lookAt(Nv,m1,this.up):yu.lookAt(m1,Nv,this.up),this.quaternion.setFromRotationMatrix(yu),i&&(yu.extractRotation(i.matrixWorld),jb.setFromRotationMatrix(yu),this.quaternion.premultiply(jb.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(eCe)):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(tCe)),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),yu.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),yu.multiply(e.parent.matrixWorld)),e.applyMatrix4(yu),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,i=this.children.length;r<i;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 i=this.children;for(let s=0,o=i.length;s<o;s++)i[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(Nv,e,ZNe),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Nv,JNe,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,i=n.length;r<i;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,i=n.length;r<i;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,i=n.length;r<i;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 i=this.children;for(let s=0,o=i.length;s<o;s++){const l=i[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 i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.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()})),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),this.boundingBox!==null&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.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?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.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 d=0,u=c.length;d<u;d++){const m=c[d];s(e.shapes,m)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,d=this.material.length;c<d;c++)l.push(s(e.materials,this.material[c]));i.material=l}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let l=0;l<this.children.length;l++)i.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];i.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),d=o(e.textures),u=o(e.images),m=o(e.shapes),p=o(e.skeletons),f=o(e.animations),x=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),d.length>0&&(r.textures=d),u.length>0&&(r.images=u),m.length>0&&(r.shapes=m),p.length>0&&(r.skeletons=p),f.length>0&&(r.animations=f),x.length>0&&(r.nodes=x)}return r.object=i,r;function o(l){const c=[];for(const d in l){const u=l[d];delete u.metadata,c.push(u)}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 i=e.children[r];this.add(i.clone())}return this}}Js.DEFAULT_UP=new ct(0,1,0);Js.DEFAULT_MATRIX_AUTO_UPDATE=!0;Js.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Pc=new ct,vu=new ct,pE=new ct,wu=new ct,Mb=new ct,Eb=new ct,Lq=new ct,fE=new ct,gE=new ct,bE=new ct;let h1=!1;class Ac{constructor(e=new ct,n=new ct,r=new ct){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,i){i.subVectors(r,n),Pc.subVectors(e,n),i.cross(Pc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,r,i,s){Pc.subVectors(i,n),vu.subVectors(r,n),pE.subVectors(e,n);const o=Pc.dot(Pc),l=Pc.dot(vu),c=Pc.dot(pE),d=vu.dot(vu),u=vu.dot(pE),m=o*d-l*l;if(m===0)return s.set(-2,-1,-1);const p=1/m,f=(d*c-l*u)*p,x=(o*u-l*c)*p;return s.set(1-f-x,x,f)}static containsPoint(e,n,r,i){return this.getBarycoord(e,n,r,i,wu),wu.x>=0&&wu.y>=0&&wu.x+wu.y<=1}static getUV(e,n,r,i,s,o,l,c){return h1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),h1=!0),this.getInterpolation(e,n,r,i,s,o,l,c)}static getInterpolation(e,n,r,i,s,o,l,c){return this.getBarycoord(e,n,r,i,wu),c.setScalar(0),c.addScaledVector(s,wu.x),c.addScaledVector(o,wu.y),c.addScaledVector(l,wu.z),c}static isFrontFacing(e,n,r,i){return Pc.subVectors(r,n),vu.subVectors(e,n),Pc.cross(vu).dot(i)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,i){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,r,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,i),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 Pc.subVectors(this.c,this.b),vu.subVectors(this.a,this.b),Pc.cross(vu).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ac.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return Ac.getBarycoord(e,this.a,this.b,this.c,n)}getUV(e,n,r,i,s){return h1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),h1=!0),Ac.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}getInterpolation(e,n,r,i,s){return Ac.getInterpolation(e,this.a,this.b,this.c,n,r,i,s)}containsPoint(e){return Ac.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ac.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,i=this.b,s=this.c;let o,l;Mb.subVectors(i,r),Eb.subVectors(s,r),fE.subVectors(e,r);const c=Mb.dot(fE),d=Eb.dot(fE);if(c<=0&&d<=0)return n.copy(r);gE.subVectors(e,i);const u=Mb.dot(gE),m=Eb.dot(gE);if(u>=0&&m<=u)return n.copy(i);const p=c*m-u*d;if(p<=0&&c>=0&&u<=0)return o=c/(c-u),n.copy(r).addScaledVector(Mb,o);bE.subVectors(e,s);const f=Mb.dot(bE),x=Eb.dot(bE);if(x>=0&&f<=x)return n.copy(s);const v=f*d-c*x;if(v<=0&&d>=0&&x<=0)return l=d/(d-x),n.copy(r).addScaledVector(Eb,l);const g=u*x-f*m;if(g<=0&&m-u>=0&&f-x>=0)return Lq.subVectors(s,i),l=(m-u)/(m-u+(f-x)),n.copy(i).addScaledVector(Lq,l);const b=1/(g+v+p);return o=v*b,l=p*b,n.copy(r).addScaledVector(Mb,o).addScaledVector(Eb,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const rJ={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},oh={h:0,s:0,l:0},p1={h:0,s:0,l:0};function xE(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 i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=ds){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Wr.toWorkingColorSpace(this,n),this}setRGB(e,n,r,i=Wr.workingColorSpace){return this.r=e,this.g=n,this.b=r,Wr.toWorkingColorSpace(this,i),this}setHSL(e,n,r,i=Wr.workingColorSpace){if(e=QO(e,1),n=us(n,0,1),r=us(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=xE(o,s,e+1/3),this.g=xE(o,s,e),this.b=xE(o,s,e-1/3)}return Wr.toWorkingColorSpace(this,i),this}setStyle(e,n=ds){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],l=i[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(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[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=ds){const r=rJ[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=gx(e.r),this.g=gx(e.g),this.b=gx(e.b),this}copyLinearToSRGB(e){return this.r=sE(e.r),this.g=sE(e.g),this.b=sE(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ds){return Wr.fromWorkingColorSpace(Ns.copy(this),e),Math.round(us(Ns.r*255,0,255))*65536+Math.round(us(Ns.g*255,0,255))*256+Math.round(us(Ns.b*255,0,255))}getHexString(e=ds){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=Wr.workingColorSpace){Wr.fromWorkingColorSpace(Ns.copy(this),n);const r=Ns.r,i=Ns.g,s=Ns.b,o=Math.max(r,i,s),l=Math.min(r,i,s);let c,d;const u=(l+o)/2;if(l===o)c=0,d=0;else{const m=o-l;switch(d=u<=.5?m/(o+l):m/(2-o-l),o){case r:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-r)/m+2;break;case s:c=(r-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=Wr.workingColorSpace){return Wr.fromWorkingColorSpace(Ns.copy(this),n),e.r=Ns.r,e.g=Ns.g,e.b=Ns.b,e}getStyle(e=ds){Wr.fromWorkingColorSpace(Ns.copy(this),e);const n=Ns.r,r=Ns.g,i=Ns.b;return e!==ds?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(i*255)})`}offsetHSL(e,n,r){return this.getHSL(oh),this.setHSL(oh.h+e,oh.s+n,oh.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(oh),e.getHSL(p1);const r=h0(oh.h,p1.h,n),i=h0(oh.s,p1.s,n),s=h0(oh.l,p1.l,n);return this.setHSL(r,i,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,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*i,this.g=s[1]*n+s[4]*r+s[7]*i,this.b=s[2]*n+s[5]*r+s[8]*i,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 Ns=new Dn;Dn.NAMES=rJ;let nCe=0;class my extends _g{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:nCe++}),this.uuid=Qu(),this.name="",this.type="Material",this.blending=fx,this.side=op,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=WF,this.blendDst=KF,this.blendEquation=pf,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Dn(0,0,0),this.blendAlpha=0,this.depthFunc=yN,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=_q,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=kb,this.stencilZFail=kb,this.stencilZPass=kb,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 i=this[n];if(i===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.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!==fx&&(r.blending=this.blending),this.side!==op&&(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!==WF&&(r.blendSrc=this.blendSrc),this.blendDst!==KF&&(r.blendDst=this.blendDst),this.blendEquation!==pf&&(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!==yN&&(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!==_q&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==kb&&(r.stencilFail=this.stencilFail),this.stencilZFail!==kb&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==kb&&(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 i(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=i(e.textures),o=i(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 i=n.length;r=new Array(i);for(let s=0;s!==i;++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 aJ extends my{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=KO,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 di=new ct,f1=new Gn;class ol{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=JF,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=qu,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 i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[r+i];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++)f1.fromBufferAttribute(this,n),f1.applyMatrix3(e),this.setXY(n,f1.x,f1.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)di.fromBufferAttribute(this,n),di.applyMatrix3(e),this.setXYZ(n,di.x,di.y,di.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)di.fromBufferAttribute(this,n),di.applyMatrix4(e),this.setXYZ(n,di.x,di.y,di.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)di.fromBufferAttribute(this,n),di.applyNormalMatrix(e),this.setXYZ(n,di.x,di.y,di.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)di.fromBufferAttribute(this,n),di.transformDirection(e),this.setXYZ(n,di.x,di.y,di.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=xd(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=Gr(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=xd(n,this.array)),n}setX(e,n){return this.normalized&&(n=Gr(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=xd(n,this.array)),n}setY(e,n){return this.normalized&&(n=Gr(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=xd(n,this.array)),n}setZ(e,n){return this.normalized&&(n=Gr(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=xd(n,this.array)),n}setW(e,n){return this.normalized&&(n=Gr(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,i){return e*=this.itemSize,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array),i=Gr(i,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e*=this.itemSize,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array),i=Gr(i,this.array),s=Gr(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=i,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!==JF&&(e.usage=this.usage),e}}class iJ extends ol{constructor(e,n,r){super(new Uint16Array(e),n,r)}}class sJ extends ol{constructor(e,n,r){super(new Uint32Array(e),n,r)}}class ri extends ol{constructor(e,n,r){super(new Float32Array(e),n,r)}}let rCe=0;const El=new da,yE=new Js,Db=new ct,Yo=new Jl,Cv=new Jl,Ri=new ct;class Ls extends _g{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:rCe++}),this.uuid=Qu(),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(ZZ(e)?sJ:iJ)(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 ur().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return El.makeRotationFromQuaternion(e),this.applyMatrix4(El),this}rotateX(e){return El.makeRotationX(e),this.applyMatrix4(El),this}rotateY(e){return El.makeRotationY(e),this.applyMatrix4(El),this}rotateZ(e){return El.makeRotationZ(e),this.applyMatrix4(El),this}translate(e,n,r){return El.makeTranslation(e,n,r),this.applyMatrix4(El),this}scale(e,n,r){return El.makeScale(e,n,r),this.applyMatrix4(El),this}lookAt(e){return yE.lookAt(e),yE.updateMatrix(),this.applyMatrix4(yE.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Db).negate(),this.translate(Db.x,Db.y,Db.z),this}setFromPoints(e){const n=[];for(let r=0,i=e.length;r<i;r++){const s=e[r];n.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new ri(n,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Jl);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 ct(-1/0,-1/0,-1/0),new ct(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,i=n.length;r<i;r++){const s=n[r];Yo.setFromBufferAttribute(s),this.morphTargetsRelative?(Ri.addVectors(this.boundingBox.min,Yo.min),this.boundingBox.expandByPoint(Ri),Ri.addVectors(this.boundingBox.max,Yo.max),this.boundingBox.expandByPoint(Ri)):(this.boundingBox.expandByPoint(Yo.min),this.boundingBox.expandByPoint(Yo.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 Cd);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 ct,1/0);return}if(e){const r=this.boundingSphere.center;if(Yo.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];Cv.setFromBufferAttribute(l),this.morphTargetsRelative?(Ri.addVectors(Yo.min,Cv.min),Yo.expandByPoint(Ri),Ri.addVectors(Yo.max,Cv.max),Yo.expandByPoint(Ri)):(Yo.expandByPoint(Cv.min),Yo.expandByPoint(Cv.max))}Yo.getCenter(r);let i=0;for(let s=0,o=e.count;s<o;s++)Ri.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(Ri));if(n)for(let s=0,o=n.length;s<o;s++){const l=n[s],c=this.morphTargetsRelative;for(let d=0,u=l.count;d<u;d++)Ri.fromBufferAttribute(l,d),c&&(Db.fromBufferAttribute(e,d),Ri.add(Db)),i=Math.max(i,r.distanceToSquared(Ri))}this.boundingSphere.radius=Math.sqrt(i),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,i=n.position.array,s=n.normal.array,o=n.uv.array,l=i.length/3;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ol(new Float32Array(4*l),4));const c=this.getAttribute("tangent").array,d=[],u=[];for(let D=0;D<l;D++)d[D]=new ct,u[D]=new ct;const m=new ct,p=new ct,f=new ct,x=new Gn,v=new Gn,g=new Gn,b=new ct,_=new ct;function C(D,H,z){m.fromArray(i,D*3),p.fromArray(i,H*3),f.fromArray(i,z*3),x.fromArray(o,D*2),v.fromArray(o,H*2),g.fromArray(o,z*2),p.sub(m),f.sub(m),v.sub(x),g.sub(x);const X=1/(v.x*g.y-g.x*v.y);isFinite(X)&&(b.copy(p).multiplyScalar(g.y).addScaledVector(f,-v.y).multiplyScalar(X),_.copy(f).multiplyScalar(v.x).addScaledVector(p,-g.x).multiplyScalar(X),d[D].add(b),d[H].add(b),d[z].add(b),u[D].add(_),u[H].add(_),u[z].add(_))}let P=this.groups;P.length===0&&(P=[{start:0,count:r.length}]);for(let D=0,H=P.length;D<H;++D){const z=P[D],X=z.start,L=z.count;for(let ne=X,ie=X+L;ne<ie;ne+=3)C(r[ne+0],r[ne+1],r[ne+2])}const N=new ct,A=new ct,T=new ct,F=new ct;function k(D){T.fromArray(s,D*3),F.copy(T);const H=d[D];N.copy(H),N.sub(T.multiplyScalar(T.dot(H))).normalize(),A.crossVectors(F,H);const X=A.dot(u[D])<0?-1:1;c[D*4]=N.x,c[D*4+1]=N.y,c[D*4+2]=N.z,c[D*4+3]=X}for(let D=0,H=P.length;D<H;++D){const z=P[D],X=z.start,L=z.count;for(let ne=X,ie=X+L;ne<ie;ne+=3)k(r[ne+0]),k(r[ne+1]),k(r[ne+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 ol(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let p=0,f=r.count;p<f;p++)r.setXYZ(p,0,0,0);const i=new ct,s=new ct,o=new ct,l=new ct,c=new ct,d=new ct,u=new ct,m=new ct;if(e)for(let p=0,f=e.count;p<f;p+=3){const x=e.getX(p+0),v=e.getX(p+1),g=e.getX(p+2);i.fromBufferAttribute(n,x),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,g),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(r,x),c.fromBufferAttribute(r,v),d.fromBufferAttribute(r,g),l.add(u),c.add(u),d.add(u),r.setXYZ(x,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.setXYZ(g,d.x,d.y,d.z)}else for(let p=0,f=n.count;p<f;p+=3)i.fromBufferAttribute(n,p+0),s.fromBufferAttribute(n,p+1),o.fromBufferAttribute(n,p+2),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),r.setXYZ(p+0,u.x,u.y,u.z),r.setXYZ(p+1,u.x,u.y,u.z),r.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Ri.fromBufferAttribute(e,n),Ri.normalize(),e.setXYZ(n,Ri.x,Ri.y,Ri.z)}toNonIndexed(){function e(l,c){const d=l.array,u=l.itemSize,m=l.normalized,p=new d.constructor(c.length*u);let f=0,x=0;for(let v=0,g=c.length;v<g;v++){l.isInterleavedBufferAttribute?f=c[v]*l.data.stride+l.offset:f=c[v]*u;for(let b=0;b<u;b++)p[x++]=d[f++]}return new ol(p,u,m)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new Ls,r=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,r);n.setAttribute(l,d)}const s=this.morphAttributes;for(const l in s){const c=[],d=s[l];for(let u=0,m=d.length;u<m;u++){const p=d[u],f=e(p,r);c.push(f)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const d=o[l];n.addGroup(d.start,d.count,d.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 d in c)c[d]!==void 0&&(e[d]=c[d]);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 d=r[c];e.data.attributes[c]=d.toJSON(e.data)}const i={};let s=!1;for(const c in this.morphAttributes){const d=this.morphAttributes[c],u=[];for(let m=0,p=d.length;m<p;m++){const f=d[m];u.push(f.toJSON(e.data))}u.length>0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,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 i=e.attributes;for(const d in i){const u=i[d];this.setAttribute(d,u.clone(n))}const s=e.morphAttributes;for(const d in s){const u=[],m=s[d];for(let p=0,f=m.length;p<f;p++)u.push(m[p].clone(n));this.morphAttributes[d]=u}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let d=0,u=o.length;d<u;d++){const m=o[d];this.addGroup(m.start,m.count,m.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 Oq=new da,Jp=new ZO,g1=new Cd,Iq=new ct,Fb=new ct,Rb=new ct,Lb=new ct,vE=new ct,b1=new ct,x1=new Gn,y1=new Gn,v1=new Gn,zq=new ct,Uq=new ct,Bq=new ct,w1=new ct,S1=new ct;class Lc extends Js{constructor(e=new Ls,n=new aJ){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 i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,i=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){b1.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(vE.fromBufferAttribute(m,e),o?b1.addScaledVector(vE,u):b1.addScaledVector(vE.sub(n),u))}n.add(b1)}return n}raycast(e,n){const r=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),g1.copy(r.boundingSphere),g1.applyMatrix4(s),Jp.copy(e.ray).recast(e.near),!(g1.containsPoint(Jp.origin)===!1&&(Jp.intersectSphere(g1,Iq)===null||Jp.origin.distanceToSquared(Iq)>(e.far-e.near)**2))&&(Oq.copy(s).invert(),Jp.copy(e.ray).applyMatrix4(Oq),!(r.boundingBox!==null&&Jp.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Jp)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,d=s.attributes.uv,u=s.attributes.uv1,m=s.attributes.normal,p=s.groups,f=s.drawRange;if(l!==null)if(Array.isArray(o))for(let x=0,v=p.length;x<v;x++){const g=p[x],b=o[g.materialIndex],_=Math.max(g.start,f.start),C=Math.min(l.count,Math.min(g.start+g.count,f.start+f.count));for(let P=_,N=C;P<N;P+=3){const A=l.getX(P),T=l.getX(P+1),F=l.getX(P+2);i=_1(this,b,e,r,d,u,m,A,T,F),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=g.materialIndex,n.push(i))}}else{const x=Math.max(0,f.start),v=Math.min(l.count,f.start+f.count);for(let g=x,b=v;g<b;g+=3){const _=l.getX(g),C=l.getX(g+1),P=l.getX(g+2);i=_1(this,o,e,r,d,u,m,_,C,P),i&&(i.faceIndex=Math.floor(g/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let x=0,v=p.length;x<v;x++){const g=p[x],b=o[g.materialIndex],_=Math.max(g.start,f.start),C=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let P=_,N=C;P<N;P+=3){const A=P,T=P+1,F=P+2;i=_1(this,b,e,r,d,u,m,A,T,F),i&&(i.faceIndex=Math.floor(P/3),i.face.materialIndex=g.materialIndex,n.push(i))}}else{const x=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let g=x,b=v;g<b;g+=3){const _=g,C=g+1,P=g+2;i=_1(this,o,e,r,d,u,m,_,C,P),i&&(i.faceIndex=Math.floor(g/3),n.push(i))}}}}function aCe(t,e,n,r,i,s,o,l){let c;if(e.side===jo?c=r.intersectTriangle(o,s,i,!0,l):c=r.intersectTriangle(i,s,o,e.side===op,l),c===null)return null;S1.copy(l),S1.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(S1);return d<n.near||d>n.far?null:{distance:d,point:S1.clone(),object:t}}function _1(t,e,n,r,i,s,o,l,c,d){t.getVertexPosition(l,Fb),t.getVertexPosition(c,Rb),t.getVertexPosition(d,Lb);const u=aCe(t,e,n,r,Fb,Rb,Lb,w1);if(u){i&&(x1.fromBufferAttribute(i,l),y1.fromBufferAttribute(i,c),v1.fromBufferAttribute(i,d),u.uv=Ac.getInterpolation(w1,Fb,Rb,Lb,x1,y1,v1,new Gn)),s&&(x1.fromBufferAttribute(s,l),y1.fromBufferAttribute(s,c),v1.fromBufferAttribute(s,d),u.uv1=Ac.getInterpolation(w1,Fb,Rb,Lb,x1,y1,v1,new Gn),u.uv2=u.uv1),o&&(zq.fromBufferAttribute(o,l),Uq.fromBufferAttribute(o,c),Bq.fromBufferAttribute(o,d),u.normal=Ac.getInterpolation(w1,Fb,Rb,Lb,zq,Uq,Bq,new ct),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const m={a:l,b:c,c:d,normal:new ct,materialIndex:0};Ac.getNormal(Fb,Rb,Lb,m.normal),u.face=m}return u}class Gw extends Ls{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const l=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],d=[],u=[],m=[];let p=0,f=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,i,o,2),x("x","z","y",1,-1,e,r,-n,i,o,3),x("x","y","z",1,-1,e,n,r,i,s,4),x("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new ri(d,3)),this.setAttribute("normal",new ri(u,3)),this.setAttribute("uv",new ri(m,2));function x(v,g,b,_,C,P,N,A,T,F,k){const D=P/T,H=N/F,z=P/2,X=N/2,L=A/2,ne=T+1,ie=F+1;let ee=0,ue=0;const le=new ct;for(let oe=0;oe<ie;oe++){const W=oe*H-X;for(let re=0;re<ne;re++){const ce=re*D-z;le[v]=ce*_,le[g]=W*C,le[b]=L,d.push(le.x,le.y,le.z),le[v]=0,le[g]=0,le[b]=A>0?1:-1,u.push(le.x,le.y,le.z),m.push(re/T),m.push(1-oe/F),ee+=1}}for(let oe=0;oe<F;oe++)for(let W=0;W<T;W++){const re=p+W+ne*oe,ce=p+W+ne*(oe+1),xe=p+(W+1)+ne*(oe+1),Ne=p+(W+1)+ne*oe;c.push(re,ce,Ne),c.push(ce,xe,Ne),ue+=6}l.addGroup(f,ue,k),f+=ue,p+=ee}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Gw(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Ix(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const i=t[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=i.clone():Array.isArray(i)?e[n][r]=i.slice():e[n][r]=i}}return e}function Gs(t){const e={};for(let n=0;n<t.length;n++){const r=Ix(t[n]);for(const i in r)e[i]=r[i]}return e}function iCe(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function oJ(t){return t.getRenderTarget()===null?t.outputColorSpace:Wr.workingColorSpace}const JO={clone:Ix,merge:Gs};var sCe=`void main() {
- gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
- }`,oCe=`void main() {
- gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
- }`;class lp extends my{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=sCe,this.fragmentShader=oCe,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=Ix(e.uniforms),this.uniformsGroups=iCe(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 i in this.uniforms){const o=this.uniforms[i].value;o&&o.isTexture?n.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[i]={type:"m4",value:o.toArray()}:n.uniforms[i]={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 i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}}class lJ extends Js{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new da,this.projectionMatrix=new da,this.projectionMatrixInverse=new da,this.coordinateSystem=Sd}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 Jo extends lJ{constructor(e=50,n=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,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=Z0*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(m0*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Z0*2*Math.atan(Math.tan(m0*.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,i,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=i,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(m0*.5*this.fov)/this.zoom,r=2*n,i=this.aspect*r,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,d=o.fullHeight;s+=o.offsetX*i/c,n-=o.offsetY*r/d,i*=o.width/c,r*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,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 Ob=-90,Ib=1;class lCe extends Js{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Jo(Ob,Ib,e,n);i.layers=this.layers,this.add(i);const s=new Jo(Ob,Ib,e,n);s.layers=this.layers,this.add(s);const o=new Jo(Ob,Ib,e,n);o.layers=this.layers,this.add(o);const l=new Jo(Ob,Ib,e,n);l.layers=this.layers,this.add(l);const c=new Jo(Ob,Ib,e,n);c.layers=this.layers,this.add(c);const d=new Jo(Ob,Ib,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===Sd)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.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===Q0)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.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 d of n)this.add(d),d.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,d,u]=this.children,m=e.getRenderTarget(),p=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(n,s),e.setRenderTarget(r,1,i),e.render(n,o),e.setRenderTarget(r,2,i),e.render(n,l),e.setRenderTarget(r,3,i),e.render(n,c),e.setRenderTarget(r,4,i),e.render(n,d),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=x,r.texture.needsPMREMUpdate=!0}}class cJ extends Mo{constructor(e,n,r,i,s,o,l,c,d,u){e=e!==void 0?e:[],n=n!==void 0?n:Rx,super(e,n,r,i,s,o,l,c,d,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class cCe extends ng{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];n.encoding!==void 0&&(p0("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===Ff?ds:Gl),this.texture=new cJ(i,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:$l}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:`
- varying vec3 vWorldDirection;
- vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
- }
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- }
- `,fragmentShader:`
- uniform sampler2D tEquirect;
- varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vec3 direction = normalize( vWorldDirection );
- vec2 sampleUV = equirectUv( direction );
- gl_FragColor = texture2D( tEquirect, sampleUV );
- }
- `},i=new Gw(5,5,5),s=new lp({name:"CubemapFromEquirect",uniforms:Ix(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:jo,blending:Xh});s.uniforms.tEquirect.value=n;const o=new Lc(i,s),l=n.minFilter;return n.minFilter===X0&&(n.minFilter=$l),new lCe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,i);e.setRenderTarget(s)}}const wE=new ct,dCe=new ct,uCe=new ur;class gh{constructor(e=new ct(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,i){return this.normal.set(e,n,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const i=wE.subVectors(r,n).cross(dCe.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(i,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(wE),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/i;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||uCe.getNormalMatrix(e),i=this.coplanarPoint(wE).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-i.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 ef=new Cd,k1=new ct;class HP{constructor(e=new gh,n=new gh,r=new gh,i=new gh,s=new gh,o=new gh){this.planes=[e,n,r,i,s,o]}set(e,n,r,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(i),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=Sd){const r=this.planes,i=e.elements,s=i[0],o=i[1],l=i[2],c=i[3],d=i[4],u=i[5],m=i[6],p=i[7],f=i[8],x=i[9],v=i[10],g=i[11],b=i[12],_=i[13],C=i[14],P=i[15];if(r[0].setComponents(c-s,p-d,g-f,P-b).normalize(),r[1].setComponents(c+s,p+d,g+f,P+b).normalize(),r[2].setComponents(c+o,p+u,g+x,P+_).normalize(),r[3].setComponents(c-o,p-u,g-x,P-_).normalize(),r[4].setComponents(c-l,p-m,g-v,P-C).normalize(),n===Sd)r[5].setComponents(c+l,p+m,g+v,P+C).normalize();else if(n===Q0)r[5].setComponents(l,m,v,C).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(),ef.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),ef.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ef)}intersectsSprite(e){return ef.center.set(0,0,0),ef.radius=.7071067811865476,ef.applyMatrix4(e.matrixWorld),this.intersectsSphere(ef)}intersectsSphere(e){const n=this.planes,r=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const i=n[r];if(k1.x=i.normal.x>0?e.max.x:e.min.x,k1.y=i.normal.y>0?e.max.y:e.min.y,k1.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(k1)<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 dJ(){let t=null,e=!1,n=null,r=null;function i(s,o){n(s,o),r=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function mCe(t,e){const n=e.isWebGL2,r=new WeakMap;function i(d,u){const m=d.array,p=d.usage,f=m.byteLength,x=t.createBuffer();t.bindBuffer(u,x),t.bufferData(u,m,p),d.onUploadCallback();let v;if(m instanceof Float32Array)v=t.FLOAT;else if(m instanceof Uint16Array)if(d.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(m instanceof Int16Array)v=t.SHORT;else if(m instanceof Uint32Array)v=t.UNSIGNED_INT;else if(m instanceof Int32Array)v=t.INT;else if(m instanceof Int8Array)v=t.BYTE;else if(m instanceof Uint8Array)v=t.UNSIGNED_BYTE;else if(m instanceof Uint8ClampedArray)v=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+m);return{buffer:x,type:v,bytesPerElement:m.BYTES_PER_ELEMENT,version:d.version,size:f}}function s(d,u,m){const p=u.array,f=u._updateRange,x=u.updateRanges;if(t.bindBuffer(m,d),f.count===-1&&x.length===0&&t.bufferSubData(m,0,p),x.length!==0){for(let v=0,g=x.length;v<g;v++){const b=x[v];n?t.bufferSubData(m,b.start*p.BYTES_PER_ELEMENT,p,b.start,b.count):t.bufferSubData(m,b.start*p.BYTES_PER_ELEMENT,p.subarray(b.start,b.start+b.count))}u.clearUpdateRanges()}f.count!==-1&&(n?t.bufferSubData(m,f.offset*p.BYTES_PER_ELEMENT,p,f.offset,f.count):t.bufferSubData(m,f.offset*p.BYTES_PER_ELEMENT,p.subarray(f.offset,f.offset+f.count)),f.count=-1),u.onUploadCallback()}function o(d){return d.isInterleavedBufferAttribute&&(d=d.data),r.get(d)}function l(d){d.isInterleavedBufferAttribute&&(d=d.data);const u=r.get(d);u&&(t.deleteBuffer(u.buffer),r.delete(d))}function c(d,u){if(d.isGLBufferAttribute){const p=r.get(d);(!p||p.version<d.version)&&r.set(d,{buffer:d.buffer,type:d.type,bytesPerElement:d.elementSize,version:d.version});return}d.isInterleavedBufferAttribute&&(d=d.data);const m=r.get(d);if(m===void 0)r.set(d,i(d,u));else if(m.version<d.version){if(m.size!==d.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(m.buffer,d,u),m.version=d.version}}return{get:o,remove:l,update:c}}class eI extends Ls{constructor(e=1,n=1,r=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],x=[],v=[],g=[];for(let b=0;b<u;b++){const _=b*p-o;for(let C=0;C<d;C++){const P=C*m-s;x.push(P,-_,0),v.push(0,0,1),g.push(C/l),g.push(1-b/c)}}for(let b=0;b<c;b++)for(let _=0;_<l;_++){const C=_+d*b,P=_+d*(b+1),N=_+1+d*(b+1),A=_+1+d*b;f.push(C,P,A),f.push(P,N,A)}this.setIndex(f),this.setAttribute("position",new ri(x,3)),this.setAttribute("normal",new ri(v,3)),this.setAttribute("uv",new ri(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new eI(e.width,e.height,e.widthSegments,e.heightSegments)}}var hCe=`#ifdef USE_ALPHAHASH
- if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
- #endif`,pCe=`#ifdef USE_ALPHAHASH
- const float ALPHA_HASH_SCALE = 0.05;
- float hash2D( vec2 value ) {
- return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
- }
- float hash3D( vec3 value ) {
- return hash2D( vec2( hash2D( value.xy ), value.z ) );
- }
- float getAlphaHashThreshold( vec3 position ) {
- float maxDeriv = max(
- length( dFdx( position.xyz ) ),
- length( dFdy( position.xyz ) )
- );
- float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
- vec2 pixScales = vec2(
- exp2( floor( log2( pixScale ) ) ),
- exp2( ceil( log2( pixScale ) ) )
- );
- vec2 alpha = vec2(
- hash3D( floor( pixScales.x * position.xyz ) ),
- hash3D( floor( pixScales.y * position.xyz ) )
- );
- float lerpFactor = fract( log2( pixScale ) );
- float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
- float a = min( lerpFactor, 1.0 - lerpFactor );
- vec3 cases = vec3(
- x * x / ( 2.0 * a * ( 1.0 - a ) ),
- ( x - 0.5 * a ) / ( 1.0 - a ),
- 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
- );
- float threshold = ( x < ( 1.0 - a ) )
- ? ( ( x < a ) ? cases.x : cases.y )
- : cases.z;
- return clamp( threshold , 1.0e-6, 1.0 );
- }
- #endif`,fCe=`#ifdef USE_ALPHAMAP
- diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
- #endif`,gCe=`#ifdef USE_ALPHAMAP
- uniform sampler2D alphaMap;
- #endif`,bCe=`#ifdef USE_ALPHATEST
- if ( diffuseColor.a < alphaTest ) discard;
- #endif`,xCe=`#ifdef USE_ALPHATEST
- uniform float alphaTest;
- #endif`,yCe=`#ifdef USE_AOMAP
- float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
- reflectedLight.indirectDiffuse *= ambientOcclusion;
- #if defined( USE_CLEARCOAT )
- clearcoatSpecularIndirect *= ambientOcclusion;
- #endif
- #if defined( USE_SHEEN )
- sheenSpecularIndirect *= ambientOcclusion;
- #endif
- #if defined( USE_ENVMAP ) && defined( STANDARD )
- float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
- reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
- #endif
- #endif`,vCe=`#ifdef USE_AOMAP
- uniform sampler2D aoMap;
- uniform float aoMapIntensity;
- #endif`,wCe=`#ifdef USE_BATCHING
- attribute float batchId;
- uniform highp sampler2D batchingTexture;
- mat4 getBatchingMatrix( const in float i ) {
- int size = textureSize( batchingTexture, 0 ).x;
- int j = int( i ) * 4;
- int x = j % size;
- int y = j / size;
- vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
- vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
- vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
- vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
- return mat4( v1, v2, v3, v4 );
- }
- #endif`,SCe=`#ifdef USE_BATCHING
- mat4 batchingMatrix = getBatchingMatrix( batchId );
- #endif`,_Ce=`vec3 transformed = vec3( position );
- #ifdef USE_ALPHAHASH
- vPosition = vec3( position );
- #endif`,kCe=`vec3 objectNormal = vec3( normal );
- #ifdef USE_TANGENT
- vec3 objectTangent = vec3( tangent.xyz );
- #endif`,NCe=`float G_BlinnPhong_Implicit( ) {
- return 0.25;
- }
- float D_BlinnPhong( const in float shininess, const in float dotNH ) {
- return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
- }
- vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( specularColor, 1.0, dotVH );
- float G = G_BlinnPhong_Implicit( );
- float D = D_BlinnPhong( shininess, dotNH );
- return F * ( G * D );
- } // validated`,CCe=`#ifdef USE_IRIDESCENCE
- const mat3 XYZ_TO_REC709 = mat3(
- 3.2404542, -0.9692660, 0.0556434,
- -1.5371385, 1.8760108, -0.2040259,
- -0.4985314, 0.0415560, 1.0572252
- );
- vec3 Fresnel0ToIor( vec3 fresnel0 ) {
- vec3 sqrtF0 = sqrt( fresnel0 );
- return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
- }
- vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
- return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
- }
- float IorToFresnel0( float transmittedIor, float incidentIor ) {
- return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
- }
- vec3 evalSensitivity( float OPD, vec3 shift ) {
- float phase = 2.0 * PI * OPD * 1.0e-9;
- vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
- vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
- vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
- vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
- 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 ) );
- xyz /= 1.0685e-7;
- vec3 rgb = XYZ_TO_REC709 * xyz;
- return rgb;
- }
- vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
- vec3 I;
- float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
- float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
- float cosTheta2Sq = 1.0 - sinTheta2Sq;
- if ( cosTheta2Sq < 0.0 ) {
- return vec3( 1.0 );
- }
- float cosTheta2 = sqrt( cosTheta2Sq );
- float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
- float R12 = F_Schlick( R0, 1.0, cosTheta1 );
- float T121 = 1.0 - R12;
- float phi12 = 0.0;
- if ( iridescenceIOR < outsideIOR ) phi12 = PI;
- float phi21 = PI - phi12;
- vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
- vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
- vec3 phi23 = vec3( 0.0 );
- if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
- if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
- if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
- float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
- vec3 phi = vec3( phi21 ) + phi23;
- vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
- vec3 r123 = sqrt( R123 );
- vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
- vec3 C0 = R12 + Rs;
- I = C0;
- vec3 Cm = Rs - T121;
- for ( int m = 1; m <= 2; ++ m ) {
- Cm *= r123;
- vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
- I += Cm * Sm;
- }
- return max( I, vec3( 0.0 ) );
- }
- #endif`,PCe=`#ifdef USE_BUMPMAP
- uniform sampler2D bumpMap;
- uniform float bumpScale;
- vec2 dHdxy_fwd() {
- vec2 dSTdx = dFdx( vBumpMapUv );
- vec2 dSTdy = dFdy( vBumpMapUv );
- float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
- float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
- float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
- return vec2( dBx, dBy );
- }
- vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
- vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
- vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
- vec3 vN = surf_norm;
- vec3 R1 = cross( vSigmaY, vN );
- vec3 R2 = cross( vN, vSigmaX );
- float fDet = dot( vSigmaX, R1 ) * faceDirection;
- vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
- return normalize( abs( fDet ) * surf_norm - vGrad );
- }
- #endif`,TCe=`#if NUM_CLIPPING_PLANES > 0
- vec4 plane;
- #pragma unroll_loop_start
- for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
- }
- #pragma unroll_loop_end
- #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
- bool clipped = true;
- #pragma unroll_loop_start
- for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
- plane = clippingPlanes[ i ];
- clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
- }
- #pragma unroll_loop_end
- if ( clipped ) discard;
- #endif
- #endif`,ACe=`#if NUM_CLIPPING_PLANES > 0
- varying vec3 vClipPosition;
- uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
- #endif`,jCe=`#if NUM_CLIPPING_PLANES > 0
- varying vec3 vClipPosition;
- #endif`,MCe=`#if NUM_CLIPPING_PLANES > 0
- vClipPosition = - mvPosition.xyz;
- #endif`,ECe=`#if defined( USE_COLOR_ALPHA )
- diffuseColor *= vColor;
- #elif defined( USE_COLOR )
- diffuseColor.rgb *= vColor;
- #endif`,DCe=`#if defined( USE_COLOR_ALPHA )
- varying vec4 vColor;
- #elif defined( USE_COLOR )
- varying vec3 vColor;
- #endif`,FCe=`#if defined( USE_COLOR_ALPHA )
- varying vec4 vColor;
- #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
- varying vec3 vColor;
- #endif`,RCe=`#if defined( USE_COLOR_ALPHA )
- vColor = vec4( 1.0 );
- #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
- vColor = vec3( 1.0 );
- #endif
- #ifdef USE_COLOR
- vColor *= color;
- #endif
- #ifdef USE_INSTANCING_COLOR
- vColor.xyz *= instanceColor.xyz;
- #endif`,LCe=`#define PI 3.141592653589793
- #define PI2 6.283185307179586
- #define PI_HALF 1.5707963267948966
- #define RECIPROCAL_PI 0.3183098861837907
- #define RECIPROCAL_PI2 0.15915494309189535
- #define EPSILON 1e-6
- #ifndef saturate
- #define saturate( a ) clamp( a, 0.0, 1.0 )
- #endif
- #define whiteComplement( a ) ( 1.0 - saturate( a ) )
- float pow2( const in float x ) { return x*x; }
- vec3 pow2( const in vec3 x ) { return x*x; }
- float pow3( const in float x ) { return x*x*x; }
- float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
- float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
- float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
- highp float rand( const in vec2 uv ) {
- const highp float a = 12.9898, b = 78.233, c = 43758.5453;
- highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
- return fract( sin( sn ) * c );
- }
- #ifdef HIGH_PRECISION
- float precisionSafeLength( vec3 v ) { return length( v ); }
- #else
- float precisionSafeLength( vec3 v ) {
- float maxComponent = max3( abs( v ) );
- return length( v / maxComponent ) * maxComponent;
- }
- #endif
- struct IncidentLight {
- vec3 color;
- vec3 direction;
- bool visible;
- };
- struct ReflectedLight {
- vec3 directDiffuse;
- vec3 directSpecular;
- vec3 indirectDiffuse;
- vec3 indirectSpecular;
- };
- #ifdef USE_ALPHAHASH
- varying vec3 vPosition;
- #endif
- vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
- }
- vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
- return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
- }
- mat3 transposeMat3( const in mat3 m ) {
- mat3 tmp;
- tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
- tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
- tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
- return tmp;
- }
- float luminance( const in vec3 rgb ) {
- const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
- return dot( weights, rgb );
- }
- bool isPerspectiveMatrix( mat4 m ) {
- return m[ 2 ][ 3 ] == - 1.0;
- }
- vec2 equirectUv( in vec3 dir ) {
- float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
- float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
- return vec2( u, v );
- }
- vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
- return RECIPROCAL_PI * diffuseColor;
- }
- vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
- float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
- return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
- }
- float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
- float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
- return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
- } // validated`,OCe=`#ifdef ENVMAP_TYPE_CUBE_UV
- #define cubeUV_minMipLevel 4.0
- #define cubeUV_minTileSize 16.0
- float getFace( vec3 direction ) {
- vec3 absDirection = abs( direction );
- float face = - 1.0;
- if ( absDirection.x > absDirection.z ) {
- if ( absDirection.x > absDirection.y )
- face = direction.x > 0.0 ? 0.0 : 3.0;
- else
- face = direction.y > 0.0 ? 1.0 : 4.0;
- } else {
- if ( absDirection.z > absDirection.y )
- face = direction.z > 0.0 ? 2.0 : 5.0;
- else
- face = direction.y > 0.0 ? 1.0 : 4.0;
- }
- return face;
- }
- vec2 getUV( vec3 direction, float face ) {
- vec2 uv;
- if ( face == 0.0 ) {
- uv = vec2( direction.z, direction.y ) / abs( direction.x );
- } else if ( face == 1.0 ) {
- uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
- } else if ( face == 2.0 ) {
- uv = vec2( - direction.x, direction.y ) / abs( direction.z );
- } else if ( face == 3.0 ) {
- uv = vec2( - direction.z, direction.y ) / abs( direction.x );
- } else if ( face == 4.0 ) {
- uv = vec2( - direction.x, direction.z ) / abs( direction.y );
- } else {
- uv = vec2( direction.x, direction.y ) / abs( direction.z );
- }
- return 0.5 * ( uv + 1.0 );
- }
- vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
- float face = getFace( direction );
- float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
- mipInt = max( mipInt, cubeUV_minMipLevel );
- float faceSize = exp2( mipInt );
- highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
- if ( face > 2.0 ) {
- uv.y += faceSize;
- face -= 3.0;
- }
- uv.x += face * faceSize;
- uv.x += filterInt * 3.0 * cubeUV_minTileSize;
- uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
- uv.x *= CUBEUV_TEXEL_WIDTH;
- uv.y *= CUBEUV_TEXEL_HEIGHT;
- #ifdef texture2DGradEXT
- return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
- #else
- return texture2D( envMap, uv ).rgb;
- #endif
- }
- #define cubeUV_r0 1.0
- #define cubeUV_v0 0.339
- #define cubeUV_m0 - 2.0
- #define cubeUV_r1 0.8
- #define cubeUV_v1 0.276
- #define cubeUV_m1 - 1.0
- #define cubeUV_r4 0.4
- #define cubeUV_v4 0.046
- #define cubeUV_m4 2.0
- #define cubeUV_r5 0.305
- #define cubeUV_v5 0.016
- #define cubeUV_m5 3.0
- #define cubeUV_r6 0.21
- #define cubeUV_v6 0.0038
- #define cubeUV_m6 4.0
- float roughnessToMip( float roughness ) {
- float mip = 0.0;
- if ( roughness >= cubeUV_r1 ) {
- mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
- } else if ( roughness >= cubeUV_r4 ) {
- mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
- } else if ( roughness >= cubeUV_r5 ) {
- mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
- } else if ( roughness >= cubeUV_r6 ) {
- mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
- } else {
- mip = - 2.0 * log2( 1.16 * roughness ); }
- return mip;
- }
- vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
- float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
- float mipF = fract( mip );
- float mipInt = floor( mip );
- vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
- if ( mipF == 0.0 ) {
- return vec4( color0, 1.0 );
- } else {
- vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
- return vec4( mix( color0, color1, mipF ), 1.0 );
- }
- }
- #endif`,ICe=`vec3 transformedNormal = objectNormal;
- #ifdef USE_TANGENT
- vec3 transformedTangent = objectTangent;
- #endif
- #ifdef USE_BATCHING
- mat3 bm = mat3( batchingMatrix );
- transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
- transformedNormal = bm * transformedNormal;
- #ifdef USE_TANGENT
- transformedTangent = bm * transformedTangent;
- #endif
- #endif
- #ifdef USE_INSTANCING
- mat3 im = mat3( instanceMatrix );
- transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
- transformedNormal = im * transformedNormal;
- #ifdef USE_TANGENT
- transformedTangent = im * transformedTangent;
- #endif
- #endif
- transformedNormal = normalMatrix * transformedNormal;
- #ifdef FLIP_SIDED
- transformedNormal = - transformedNormal;
- #endif
- #ifdef USE_TANGENT
- transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
- #ifdef FLIP_SIDED
- transformedTangent = - transformedTangent;
- #endif
- #endif`,zCe=`#ifdef USE_DISPLACEMENTMAP
- uniform sampler2D displacementMap;
- uniform float displacementScale;
- uniform float displacementBias;
- #endif`,UCe=`#ifdef USE_DISPLACEMENTMAP
- transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
- #endif`,BCe=`#ifdef USE_EMISSIVEMAP
- vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
- totalEmissiveRadiance *= emissiveColor.rgb;
- #endif`,HCe=`#ifdef USE_EMISSIVEMAP
- uniform sampler2D emissiveMap;
- #endif`,qCe="gl_FragColor = linearToOutputTexel( gl_FragColor );",$Ce=`
- const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
- vec3( 0.8224621, 0.177538, 0.0 ),
- vec3( 0.0331941, 0.9668058, 0.0 ),
- vec3( 0.0170827, 0.0723974, 0.9105199 )
- );
- const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
- vec3( 1.2249401, - 0.2249404, 0.0 ),
- vec3( - 0.0420569, 1.0420571, 0.0 ),
- vec3( - 0.0196376, - 0.0786361, 1.0982735 )
- );
- vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
- return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
- }
- vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
- return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
- }
- vec4 LinearTransferOETF( in vec4 value ) {
- return value;
- }
- vec4 sRGBTransferOETF( in vec4 value ) {
- 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 );
- }
- vec4 LinearToLinear( in vec4 value ) {
- return value;
- }
- vec4 LinearTosRGB( in vec4 value ) {
- return sRGBTransferOETF( value );
- }`,VCe=`#ifdef USE_ENVMAP
- #ifdef ENV_WORLDPOS
- vec3 cameraToFrag;
- if ( isOrthographic ) {
- cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
- } else {
- cameraToFrag = normalize( vWorldPosition - cameraPosition );
- }
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- #ifdef ENVMAP_MODE_REFLECTION
- vec3 reflectVec = reflect( cameraToFrag, worldNormal );
- #else
- vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
- #endif
- #else
- vec3 reflectVec = vReflect;
- #endif
- #ifdef ENVMAP_TYPE_CUBE
- vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
- #else
- vec4 envColor = vec4( 0.0 );
- #endif
- #ifdef ENVMAP_BLENDING_MULTIPLY
- outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
- #elif defined( ENVMAP_BLENDING_MIX )
- outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
- #elif defined( ENVMAP_BLENDING_ADD )
- outgoingLight += envColor.xyz * specularStrength * reflectivity;
- #endif
- #endif`,GCe=`#ifdef USE_ENVMAP
- uniform float envMapIntensity;
- uniform float flipEnvMap;
- #ifdef ENVMAP_TYPE_CUBE
- uniform samplerCube envMap;
- #else
- uniform sampler2D envMap;
- #endif
-
- #endif`,WCe=`#ifdef USE_ENVMAP
- uniform float reflectivity;
- #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
- #define ENV_WORLDPOS
- #endif
- #ifdef ENV_WORLDPOS
- varying vec3 vWorldPosition;
- uniform float refractionRatio;
- #else
- varying vec3 vReflect;
- #endif
- #endif`,KCe=`#ifdef USE_ENVMAP
- #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
- #define ENV_WORLDPOS
- #endif
- #ifdef ENV_WORLDPOS
-
- varying vec3 vWorldPosition;
- #else
- varying vec3 vReflect;
- uniform float refractionRatio;
- #endif
- #endif`,XCe=`#ifdef USE_ENVMAP
- #ifdef ENV_WORLDPOS
- vWorldPosition = worldPosition.xyz;
- #else
- vec3 cameraToVertex;
- if ( isOrthographic ) {
- cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
- } else {
- cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
- }
- vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
- #ifdef ENVMAP_MODE_REFLECTION
- vReflect = reflect( cameraToVertex, worldNormal );
- #else
- vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
- #endif
- #endif
- #endif`,YCe=`#ifdef USE_FOG
- vFogDepth = - mvPosition.z;
- #endif`,QCe=`#ifdef USE_FOG
- varying float vFogDepth;
- #endif`,ZCe=`#ifdef USE_FOG
- #ifdef FOG_EXP2
- float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
- #else
- float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
- #endif
- gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
- #endif`,JCe=`#ifdef USE_FOG
- uniform vec3 fogColor;
- varying float vFogDepth;
- #ifdef FOG_EXP2
- uniform float fogDensity;
- #else
- uniform float fogNear;
- uniform float fogFar;
- #endif
- #endif`,ePe=`#ifdef USE_GRADIENTMAP
- uniform sampler2D gradientMap;
- #endif
- vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
- float dotNL = dot( normal, lightDirection );
- vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
- #ifdef USE_GRADIENTMAP
- return vec3( texture2D( gradientMap, coord ).r );
- #else
- vec2 fw = fwidth( coord ) * 0.5;
- return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
- #endif
- }`,tPe=`#ifdef USE_LIGHTMAP
- vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
- vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
- reflectedLight.indirectDiffuse += lightMapIrradiance;
- #endif`,nPe=`#ifdef USE_LIGHTMAP
- uniform sampler2D lightMap;
- uniform float lightMapIntensity;
- #endif`,rPe=`LambertMaterial material;
- material.diffuseColor = diffuseColor.rgb;
- material.specularStrength = specularStrength;`,aPe=`varying vec3 vViewPosition;
- struct LambertMaterial {
- vec3 diffuseColor;
- float specularStrength;
- };
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_Lambert
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,iPe=`uniform bool receiveShadow;
- uniform vec3 ambientLightColor;
- #if defined( USE_LIGHT_PROBES )
- uniform vec3 lightProbe[ 9 ];
- #endif
- vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
- float x = normal.x, y = normal.y, z = normal.z;
- vec3 result = shCoefficients[ 0 ] * 0.886227;
- result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
- result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
- result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
- result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
- result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
- result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
- result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
- result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
- return result;
- }
- vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
- return irradiance;
- }
- vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
- vec3 irradiance = ambientLightColor;
- return irradiance;
- }
- float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
- #if defined ( LEGACY_LIGHTS )
- if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
- return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
- }
- return 1.0;
- #else
- float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
- if ( cutoffDistance > 0.0 ) {
- distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
- }
- return distanceFalloff;
- #endif
- }
- float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
- return smoothstep( coneCosine, penumbraCosine, angleCosine );
- }
- #if NUM_DIR_LIGHTS > 0
- struct DirectionalLight {
- vec3 direction;
- vec3 color;
- };
- uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
- void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
- light.color = directionalLight.color;
- light.direction = directionalLight.direction;
- light.visible = true;
- }
- #endif
- #if NUM_POINT_LIGHTS > 0
- struct PointLight {
- vec3 position;
- vec3 color;
- float distance;
- float decay;
- };
- uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
- void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
- vec3 lVector = pointLight.position - geometryPosition;
- light.direction = normalize( lVector );
- float lightDistance = length( lVector );
- light.color = pointLight.color;
- light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
- light.visible = ( light.color != vec3( 0.0 ) );
- }
- #endif
- #if NUM_SPOT_LIGHTS > 0
- struct SpotLight {
- vec3 position;
- vec3 direction;
- vec3 color;
- float distance;
- float decay;
- float coneCos;
- float penumbraCos;
- };
- uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
- void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
- vec3 lVector = spotLight.position - geometryPosition;
- light.direction = normalize( lVector );
- float angleCos = dot( light.direction, spotLight.direction );
- float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
- if ( spotAttenuation > 0.0 ) {
- float lightDistance = length( lVector );
- light.color = spotLight.color * spotAttenuation;
- light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
- light.visible = ( light.color != vec3( 0.0 ) );
- } else {
- light.color = vec3( 0.0 );
- light.visible = false;
- }
- }
- #endif
- #if NUM_RECT_AREA_LIGHTS > 0
- struct RectAreaLight {
- vec3 color;
- vec3 position;
- vec3 halfWidth;
- vec3 halfHeight;
- };
- uniform sampler2D ltc_1; uniform sampler2D ltc_2;
- uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
- #endif
- #if NUM_HEMI_LIGHTS > 0
- struct HemisphereLight {
- vec3 direction;
- vec3 skyColor;
- vec3 groundColor;
- };
- uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
- vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
- float dotNL = dot( normal, hemiLight.direction );
- float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
- vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
- return irradiance;
- }
- #endif`,sPe=`#ifdef USE_ENVMAP
- vec3 getIBLIrradiance( const in vec3 normal ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
- vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
- return PI * envMapColor.rgb * envMapIntensity;
- #else
- return vec3( 0.0 );
- #endif
- }
- vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 reflectVec = reflect( - viewDir, normal );
- reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
- reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
- vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
- return envMapColor.rgb * envMapIntensity;
- #else
- return vec3( 0.0 );
- #endif
- }
- #ifdef USE_ANISOTROPY
- vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
- #ifdef ENVMAP_TYPE_CUBE_UV
- vec3 bentNormal = cross( bitangent, viewDir );
- bentNormal = normalize( cross( bentNormal, bitangent ) );
- bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
- return getIBLRadiance( viewDir, bentNormal, roughness );
- #else
- return vec3( 0.0 );
- #endif
- }
- #endif
- #endif`,oPe=`ToonMaterial material;
- material.diffuseColor = diffuseColor.rgb;`,lPe=`varying vec3 vViewPosition;
- struct ToonMaterial {
- vec3 diffuseColor;
- };
- 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 ) {
- vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_Toon
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,cPe=`BlinnPhongMaterial material;
- material.diffuseColor = diffuseColor.rgb;
- material.specularColor = specular;
- material.specularShininess = shininess;
- material.specularStrength = specularStrength;`,dPe=`varying vec3 vViewPosition;
- struct BlinnPhongMaterial {
- vec3 diffuseColor;
- vec3 specularColor;
- float specularShininess;
- float specularStrength;
- };
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- #define RE_Direct RE_Direct_BlinnPhong
- #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,uPe=`PhysicalMaterial material;
- material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
- vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
- float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
- material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
- material.roughness = min( material.roughness, 1.0 );
- #ifdef IOR
- material.ior = ior;
- #ifdef USE_SPECULAR
- float specularIntensityFactor = specularIntensity;
- vec3 specularColorFactor = specularColor;
- #ifdef USE_SPECULAR_COLORMAP
- specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
- #endif
- material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
- #else
- float specularIntensityFactor = 1.0;
- vec3 specularColorFactor = vec3( 1.0 );
- material.specularF90 = 1.0;
- #endif
- material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
- #else
- material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
- material.specularF90 = 1.0;
- #endif
- #ifdef USE_CLEARCOAT
- material.clearcoat = clearcoat;
- material.clearcoatRoughness = clearcoatRoughness;
- material.clearcoatF0 = vec3( 0.04 );
- material.clearcoatF90 = 1.0;
- #ifdef USE_CLEARCOATMAP
- material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
- #endif
- material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
- material.clearcoatRoughness += geometryRoughness;
- material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
- #endif
- #ifdef USE_IRIDESCENCE
- material.iridescence = iridescence;
- material.iridescenceIOR = iridescenceIOR;
- #ifdef USE_IRIDESCENCEMAP
- material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
- #else
- material.iridescenceThickness = iridescenceThicknessMaximum;
- #endif
- #endif
- #ifdef USE_SHEEN
- material.sheenColor = sheenColor;
- #ifdef USE_SHEEN_COLORMAP
- material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
- #endif
- material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
- #ifdef USE_SHEEN_ROUGHNESSMAP
- material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
- #endif
- #endif
- #ifdef USE_ANISOTROPY
- #ifdef USE_ANISOTROPYMAP
- mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
- vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
- vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
- #else
- vec2 anisotropyV = anisotropyVector;
- #endif
- material.anisotropy = length( anisotropyV );
- if( material.anisotropy == 0.0 ) {
- anisotropyV = vec2( 1.0, 0.0 );
- } else {
- anisotropyV /= material.anisotropy;
- material.anisotropy = saturate( material.anisotropy );
- }
- material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
- material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
- material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
- #endif`,mPe=`struct PhysicalMaterial {
- vec3 diffuseColor;
- float roughness;
- vec3 specularColor;
- float specularF90;
- #ifdef USE_CLEARCOAT
- float clearcoat;
- float clearcoatRoughness;
- vec3 clearcoatF0;
- float clearcoatF90;
- #endif
- #ifdef USE_IRIDESCENCE
- float iridescence;
- float iridescenceIOR;
- float iridescenceThickness;
- vec3 iridescenceFresnel;
- vec3 iridescenceF0;
- #endif
- #ifdef USE_SHEEN
- vec3 sheenColor;
- float sheenRoughness;
- #endif
- #ifdef IOR
- float ior;
- #endif
- #ifdef USE_TRANSMISSION
- float transmission;
- float transmissionAlpha;
- float thickness;
- float attenuationDistance;
- vec3 attenuationColor;
- #endif
- #ifdef USE_ANISOTROPY
- float anisotropy;
- float alphaT;
- vec3 anisotropyT;
- vec3 anisotropyB;
- #endif
- };
- vec3 clearcoatSpecularDirect = vec3( 0.0 );
- vec3 clearcoatSpecularIndirect = vec3( 0.0 );
- vec3 sheenSpecularDirect = vec3( 0.0 );
- vec3 sheenSpecularIndirect = vec3(0.0 );
- vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
- float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
- float x2 = x * x;
- float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
- return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
- }
- float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
- float a2 = pow2( alpha );
- float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
- float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
- return 0.5 / max( gv + gl, EPSILON );
- }
- float D_GGX( const in float alpha, const in float dotNH ) {
- float a2 = pow2( alpha );
- float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
- return RECIPROCAL_PI * a2 / pow2( denom );
- }
- #ifdef USE_ANISOTROPY
- 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 ) {
- float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
- float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
- float v = 0.5 / ( gv + gl );
- return saturate(v);
- }
- float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
- float a2 = alphaT * alphaB;
- highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
- highp float v2 = dot( v, v );
- float w2 = a2 / v2;
- return RECIPROCAL_PI * a2 * pow2 ( w2 );
- }
- #endif
- #ifdef USE_CLEARCOAT
- vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
- vec3 f0 = material.clearcoatF0;
- float f90 = material.clearcoatF90;
- float roughness = material.clearcoatRoughness;
- float alpha = pow2( roughness );
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( f0, f90, dotVH );
- float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
- float D = D_GGX( alpha, dotNH );
- return F * ( V * D );
- }
- #endif
- vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
- vec3 f0 = material.specularColor;
- float f90 = material.specularF90;
- float roughness = material.roughness;
- float alpha = pow2( roughness );
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float dotVH = saturate( dot( viewDir, halfDir ) );
- vec3 F = F_Schlick( f0, f90, dotVH );
- #ifdef USE_IRIDESCENCE
- F = mix( F, material.iridescenceFresnel, material.iridescence );
- #endif
- #ifdef USE_ANISOTROPY
- float dotTL = dot( material.anisotropyT, lightDir );
- float dotTV = dot( material.anisotropyT, viewDir );
- float dotTH = dot( material.anisotropyT, halfDir );
- float dotBL = dot( material.anisotropyB, lightDir );
- float dotBV = dot( material.anisotropyB, viewDir );
- float dotBH = dot( material.anisotropyB, halfDir );
- float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
- float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
- #else
- float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
- float D = D_GGX( alpha, dotNH );
- #endif
- return F * ( V * D );
- }
- vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
- const float LUT_SIZE = 64.0;
- const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
- const float LUT_BIAS = 0.5 / LUT_SIZE;
- float dotNV = saturate( dot( N, V ) );
- vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
- uv = uv * LUT_SCALE + LUT_BIAS;
- return uv;
- }
- float LTC_ClippedSphereFormFactor( const in vec3 f ) {
- float l = length( f );
- return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
- }
- vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
- float x = dot( v1, v2 );
- float y = abs( x );
- float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
- float b = 3.4175940 + ( 4.1616724 + y ) * y;
- float v = a / b;
- float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
- return cross( v1, v2 ) * theta_sintheta;
- }
- vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
- vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
- vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
- vec3 lightNormal = cross( v1, v2 );
- if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
- vec3 T1, T2;
- T1 = normalize( V - N * dot( V, N ) );
- T2 = - cross( N, T1 );
- mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
- vec3 coords[ 4 ];
- coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
- coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
- coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
- coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
- coords[ 0 ] = normalize( coords[ 0 ] );
- coords[ 1 ] = normalize( coords[ 1 ] );
- coords[ 2 ] = normalize( coords[ 2 ] );
- coords[ 3 ] = normalize( coords[ 3 ] );
- vec3 vectorFormFactor = vec3( 0.0 );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
- vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
- float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
- return vec3( result );
- }
- #if defined( USE_SHEEN )
- float D_Charlie( float roughness, float dotNH ) {
- float alpha = pow2( roughness );
- float invAlpha = 1.0 / alpha;
- float cos2h = dotNH * dotNH;
- float sin2h = max( 1.0 - cos2h, 0.0078125 );
- return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
- }
- float V_Neubelt( float dotNV, float dotNL ) {
- return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
- }
- vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
- vec3 halfDir = normalize( lightDir + viewDir );
- float dotNL = saturate( dot( normal, lightDir ) );
- float dotNV = saturate( dot( normal, viewDir ) );
- float dotNH = saturate( dot( normal, halfDir ) );
- float D = D_Charlie( sheenRoughness, dotNH );
- float V = V_Neubelt( dotNV, dotNL );
- return sheenColor * ( D * V );
- }
- #endif
- float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
- float dotNV = saturate( dot( normal, viewDir ) );
- float r2 = roughness * roughness;
- float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
- float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
- float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
- return saturate( DG * RECIPROCAL_PI );
- }
- vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
- float dotNV = saturate( dot( normal, viewDir ) );
- const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
- const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
- vec4 r = roughness * c0 + c1;
- float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
- vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
- return fab;
- }
- vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
- vec2 fab = DFGApprox( normal, viewDir, roughness );
- return specularColor * fab.x + specularF90 * fab.y;
- }
- #ifdef USE_IRIDESCENCE
- 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 ) {
- #else
- 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 ) {
- #endif
- vec2 fab = DFGApprox( normal, viewDir, roughness );
- #ifdef USE_IRIDESCENCE
- vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
- #else
- vec3 Fr = specularColor;
- #endif
- vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
- float Ess = fab.x + fab.y;
- float Ems = 1.0 - Ess;
- vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
- singleScatter += FssEss;
- multiScatter += Fms * Ems;
- }
- #if NUM_RECT_AREA_LIGHTS > 0
- 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 ) {
- vec3 normal = geometryNormal;
- vec3 viewDir = geometryViewDir;
- vec3 position = geometryPosition;
- vec3 lightPos = rectAreaLight.position;
- vec3 halfWidth = rectAreaLight.halfWidth;
- vec3 halfHeight = rectAreaLight.halfHeight;
- vec3 lightColor = rectAreaLight.color;
- float roughness = material.roughness;
- vec3 rectCoords[ 4 ];
- rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
- rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
- rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
- vec2 uv = LTC_Uv( normal, viewDir, roughness );
- vec4 t1 = texture2D( ltc_1, uv );
- vec4 t2 = texture2D( ltc_2, uv );
- mat3 mInv = mat3(
- vec3( t1.x, 0, t1.y ),
- vec3( 0, 1, 0 ),
- vec3( t1.z, 0, t1.w )
- );
- vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
- reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
- reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
- }
- #endif
- 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 ) {
- float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
- vec3 irradiance = dotNL * directLight.color;
- #ifdef USE_CLEARCOAT
- float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
- vec3 ccIrradiance = dotNLcc * directLight.color;
- clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
- #endif
- #ifdef USE_SHEEN
- sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
- #endif
- reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
- reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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 ) {
- reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
- }
- 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) {
- #ifdef USE_CLEARCOAT
- clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
- #endif
- #ifdef USE_SHEEN
- sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
- #endif
- vec3 singleScattering = vec3( 0.0 );
- vec3 multiScattering = vec3( 0.0 );
- vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
- #ifdef USE_IRIDESCENCE
- computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
- #else
- computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
- #endif
- vec3 totalScattering = singleScattering + multiScattering;
- vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
- reflectedLight.indirectSpecular += radiance * singleScattering;
- reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
- reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
- }
- #define RE_Direct RE_Direct_Physical
- #define RE_Direct_RectArea RE_Direct_RectArea_Physical
- #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
- #define RE_IndirectSpecular RE_IndirectSpecular_Physical
- float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
- return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
- }`,hPe=`
- vec3 geometryPosition = - vViewPosition;
- vec3 geometryNormal = normal;
- vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
- vec3 geometryClearcoatNormal = vec3( 0.0 );
- #ifdef USE_CLEARCOAT
- geometryClearcoatNormal = clearcoatNormal;
- #endif
- #ifdef USE_IRIDESCENCE
- float dotNVi = saturate( dot( normal, geometryViewDir ) );
- if ( material.iridescenceThickness == 0.0 ) {
- material.iridescence = 0.0;
- } else {
- material.iridescence = saturate( material.iridescence );
- }
- if ( material.iridescence > 0.0 ) {
- material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
- material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
- }
- #endif
- IncidentLight directLight;
- #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
- PointLight pointLight;
- #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
- PointLightShadow pointLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
- pointLight = pointLights[ i ];
- getPointLightInfo( pointLight, geometryPosition, directLight );
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
- pointLightShadow = pointLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
- SpotLight spotLight;
- vec4 spotColor;
- vec3 spotLightCoord;
- bool inSpotLightMap;
- #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
- SpotLightShadow spotLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
- spotLight = spotLights[ i ];
- getSpotLightInfo( spotLight, geometryPosition, directLight );
- #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
- #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
- #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
- #else
- #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
- #endif
- #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
- spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
- inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
- spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
- directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
- #endif
- #undef SPOT_LIGHT_MAP_INDEX
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- spotLightShadow = spotLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
- DirectionalLight directionalLight;
- #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
- DirectionalLightShadow directionalLightShadow;
- #endif
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
- directionalLight = directionalLights[ i ];
- getDirectionalLightInfo( directionalLight, directLight );
- #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
- directionalLightShadow = directionalLightShadows[ i ];
- directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
- #endif
- RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
- RectAreaLight rectAreaLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
- rectAreaLight = rectAreaLights[ i ];
- RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- }
- #pragma unroll_loop_end
- #endif
- #if defined( RE_IndirectDiffuse )
- vec3 iblIrradiance = vec3( 0.0 );
- vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
- #if defined( USE_LIGHT_PROBES )
- irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
- #endif
- #if ( NUM_HEMI_LIGHTS > 0 )
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
- irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
- }
- #pragma unroll_loop_end
- #endif
- #endif
- #if defined( RE_IndirectSpecular )
- vec3 radiance = vec3( 0.0 );
- vec3 clearcoatRadiance = vec3( 0.0 );
- #endif`,pPe=`#if defined( RE_IndirectDiffuse )
- #ifdef USE_LIGHTMAP
- vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
- vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
- irradiance += lightMapIrradiance;
- #endif
- #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
- iblIrradiance += getIBLIrradiance( geometryNormal );
- #endif
- #endif
- #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
- #ifdef USE_ANISOTROPY
- radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
- #else
- radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
- #endif
- #ifdef USE_CLEARCOAT
- clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
- #endif
- #endif`,fPe=`#if defined( RE_IndirectDiffuse )
- RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- #endif
- #if defined( RE_IndirectSpecular )
- RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
- #endif`,gPe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
- gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
- #endif`,bPe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
- uniform float logDepthBufFC;
- varying float vFragDepth;
- varying float vIsPerspective;
- #endif`,xPe=`#ifdef USE_LOGDEPTHBUF
- #ifdef USE_LOGDEPTHBUF_EXT
- varying float vFragDepth;
- varying float vIsPerspective;
- #else
- uniform float logDepthBufFC;
- #endif
- #endif`,yPe=`#ifdef USE_LOGDEPTHBUF
- #ifdef USE_LOGDEPTHBUF_EXT
- vFragDepth = 1.0 + gl_Position.w;
- vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
- #else
- if ( isPerspectiveMatrix( projectionMatrix ) ) {
- gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;
- gl_Position.z *= gl_Position.w;
- }
- #endif
- #endif`,vPe=`#ifdef USE_MAP
- vec4 sampledDiffuseColor = texture2D( map, vMapUv );
- #ifdef DECODE_VIDEO_TEXTURE
- 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 );
-
- #endif
- diffuseColor *= sampledDiffuseColor;
- #endif`,wPe=`#ifdef USE_MAP
- uniform sampler2D map;
- #endif`,SPe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
- #if defined( USE_POINTS_UV )
- vec2 uv = vUv;
- #else
- vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
- #endif
- #endif
- #ifdef USE_MAP
- diffuseColor *= texture2D( map, uv );
- #endif
- #ifdef USE_ALPHAMAP
- diffuseColor.a *= texture2D( alphaMap, uv ).g;
- #endif`,_Pe=`#if defined( USE_POINTS_UV )
- varying vec2 vUv;
- #else
- #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
- uniform mat3 uvTransform;
- #endif
- #endif
- #ifdef USE_MAP
- uniform sampler2D map;
- #endif
- #ifdef USE_ALPHAMAP
- uniform sampler2D alphaMap;
- #endif`,kPe=`float metalnessFactor = metalness;
- #ifdef USE_METALNESSMAP
- vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
- metalnessFactor *= texelMetalness.b;
- #endif`,NPe=`#ifdef USE_METALNESSMAP
- uniform sampler2D metalnessMap;
- #endif`,CPe=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )
- vColor *= morphTargetBaseInfluence;
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- #if defined( USE_COLOR_ALPHA )
- if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
- #elif defined( USE_COLOR )
- if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
- #endif
- }
- #endif`,PPe=`#ifdef USE_MORPHNORMALS
- objectNormal *= morphTargetBaseInfluence;
- #ifdef MORPHTARGETS_TEXTURE
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
- }
- #else
- objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];
- objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];
- objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];
- objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];
- #endif
- #endif`,TPe=`#ifdef USE_MORPHTARGETS
- uniform float morphTargetBaseInfluence;
- #ifdef MORPHTARGETS_TEXTURE
- uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
- uniform sampler2DArray morphTargetsTexture;
- uniform ivec2 morphTargetsTextureSize;
- vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
- int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
- int y = texelIndex / morphTargetsTextureSize.x;
- int x = texelIndex - y * morphTargetsTextureSize.x;
- ivec3 morphUV = ivec3( x, y, morphTargetIndex );
- return texelFetch( morphTargetsTexture, morphUV, 0 );
- }
- #else
- #ifndef USE_MORPHNORMALS
- uniform float morphTargetInfluences[ 8 ];
- #else
- uniform float morphTargetInfluences[ 4 ];
- #endif
- #endif
- #endif`,APe=`#ifdef USE_MORPHTARGETS
- transformed *= morphTargetBaseInfluence;
- #ifdef MORPHTARGETS_TEXTURE
- for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
- if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
- }
- #else
- transformed += morphTarget0 * morphTargetInfluences[ 0 ];
- transformed += morphTarget1 * morphTargetInfluences[ 1 ];
- transformed += morphTarget2 * morphTargetInfluences[ 2 ];
- transformed += morphTarget3 * morphTargetInfluences[ 3 ];
- #ifndef USE_MORPHNORMALS
- transformed += morphTarget4 * morphTargetInfluences[ 4 ];
- transformed += morphTarget5 * morphTargetInfluences[ 5 ];
- transformed += morphTarget6 * morphTargetInfluences[ 6 ];
- transformed += morphTarget7 * morphTargetInfluences[ 7 ];
- #endif
- #endif
- #endif`,jPe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
- #ifdef FLAT_SHADED
- vec3 fdx = dFdx( vViewPosition );
- vec3 fdy = dFdy( vViewPosition );
- vec3 normal = normalize( cross( fdx, fdy ) );
- #else
- vec3 normal = normalize( vNormal );
- #ifdef DOUBLE_SIDED
- normal *= faceDirection;
- #endif
- #endif
- #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
- #ifdef USE_TANGENT
- mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
- #else
- mat3 tbn = getTangentFrame( - vViewPosition, normal,
- #if defined( USE_NORMALMAP )
- vNormalMapUv
- #elif defined( USE_CLEARCOAT_NORMALMAP )
- vClearcoatNormalMapUv
- #else
- vUv
- #endif
- );
- #endif
- #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
- tbn[0] *= faceDirection;
- tbn[1] *= faceDirection;
- #endif
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- #ifdef USE_TANGENT
- mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
- #else
- mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
- #endif
- #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
- tbn2[0] *= faceDirection;
- tbn2[1] *= faceDirection;
- #endif
- #endif
- vec3 nonPerturbedNormal = normal;`,MPe=`#ifdef USE_NORMALMAP_OBJECTSPACE
- normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
- #ifdef FLIP_SIDED
- normal = - normal;
- #endif
- #ifdef DOUBLE_SIDED
- normal = normal * faceDirection;
- #endif
- normal = normalize( normalMatrix * normal );
- #elif defined( USE_NORMALMAP_TANGENTSPACE )
- vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
- mapN.xy *= normalScale;
- normal = normalize( tbn * mapN );
- #elif defined( USE_BUMPMAP )
- normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
- #endif`,EPe=`#ifndef FLAT_SHADED
- varying vec3 vNormal;
- #ifdef USE_TANGENT
- varying vec3 vTangent;
- varying vec3 vBitangent;
- #endif
- #endif`,DPe=`#ifndef FLAT_SHADED
- varying vec3 vNormal;
- #ifdef USE_TANGENT
- varying vec3 vTangent;
- varying vec3 vBitangent;
- #endif
- #endif`,FPe=`#ifndef FLAT_SHADED
- vNormal = normalize( transformedNormal );
- #ifdef USE_TANGENT
- vTangent = normalize( transformedTangent );
- vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
- #endif
- #endif`,RPe=`#ifdef USE_NORMALMAP
- uniform sampler2D normalMap;
- uniform vec2 normalScale;
- #endif
- #ifdef USE_NORMALMAP_OBJECTSPACE
- uniform mat3 normalMatrix;
- #endif
- #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
- mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
- vec3 q0 = dFdx( eye_pos.xyz );
- vec3 q1 = dFdy( eye_pos.xyz );
- vec2 st0 = dFdx( uv.st );
- vec2 st1 = dFdy( uv.st );
- vec3 N = surf_norm;
- vec3 q1perp = cross( q1, N );
- vec3 q0perp = cross( N, q0 );
- vec3 T = q1perp * st0.x + q0perp * st1.x;
- vec3 B = q1perp * st0.y + q0perp * st1.y;
- float det = max( dot( T, T ), dot( B, B ) );
- float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
- return mat3( T * scale, B * scale, N );
- }
- #endif`,LPe=`#ifdef USE_CLEARCOAT
- vec3 clearcoatNormal = nonPerturbedNormal;
- #endif`,OPe=`#ifdef USE_CLEARCOAT_NORMALMAP
- vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
- clearcoatMapN.xy *= clearcoatNormalScale;
- clearcoatNormal = normalize( tbn2 * clearcoatMapN );
- #endif`,IPe=`#ifdef USE_CLEARCOATMAP
- uniform sampler2D clearcoatMap;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- uniform sampler2D clearcoatNormalMap;
- uniform vec2 clearcoatNormalScale;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- uniform sampler2D clearcoatRoughnessMap;
- #endif`,zPe=`#ifdef USE_IRIDESCENCEMAP
- uniform sampler2D iridescenceMap;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- uniform sampler2D iridescenceThicknessMap;
- #endif`,UPe=`#ifdef OPAQUE
- diffuseColor.a = 1.0;
- #endif
- #ifdef USE_TRANSMISSION
- diffuseColor.a *= material.transmissionAlpha;
- #endif
- gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,BPe=`vec3 packNormalToRGB( const in vec3 normal ) {
- return normalize( normal ) * 0.5 + 0.5;
- }
- vec3 unpackRGBToNormal( const in vec3 rgb ) {
- return 2.0 * rgb.xyz - 1.0;
- }
- const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
- const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
- const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
- const float ShiftRight8 = 1. / 256.;
- vec4 packDepthToRGBA( const in float v ) {
- vec4 r = vec4( fract( v * PackFactors ), v );
- r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;
- }
- float unpackRGBAToDepth( const in vec4 v ) {
- return dot( v, UnpackFactors );
- }
- vec2 packDepthToRG( in highp float v ) {
- return packDepthToRGBA( v ).yx;
- }
- float unpackRGToDepth( const in highp vec2 v ) {
- return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
- }
- vec4 pack2HalfToRGBA( vec2 v ) {
- vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
- return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
- }
- vec2 unpackRGBATo2Half( vec4 v ) {
- return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
- }
- float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
- return ( viewZ + near ) / ( near - far );
- }
- float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
- return depth * ( near - far ) - near;
- }
- float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
- return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
- }
- float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
- return ( near * far ) / ( ( far - near ) * depth - far );
- }`,HPe=`#ifdef PREMULTIPLIED_ALPHA
- gl_FragColor.rgb *= gl_FragColor.a;
- #endif`,qPe=`vec4 mvPosition = vec4( transformed, 1.0 );
- #ifdef USE_BATCHING
- mvPosition = batchingMatrix * mvPosition;
- #endif
- #ifdef USE_INSTANCING
- mvPosition = instanceMatrix * mvPosition;
- #endif
- mvPosition = modelViewMatrix * mvPosition;
- gl_Position = projectionMatrix * mvPosition;`,$Pe=`#ifdef DITHERING
- gl_FragColor.rgb = dithering( gl_FragColor.rgb );
- #endif`,VPe=`#ifdef DITHERING
- vec3 dithering( vec3 color ) {
- float grid_position = rand( gl_FragCoord.xy );
- vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
- dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
- return color + dither_shift_RGB;
- }
- #endif`,GPe=`float roughnessFactor = roughness;
- #ifdef USE_ROUGHNESSMAP
- vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
- roughnessFactor *= texelRoughness.g;
- #endif`,WPe=`#ifdef USE_ROUGHNESSMAP
- uniform sampler2D roughnessMap;
- #endif`,KPe=`#if NUM_SPOT_LIGHT_COORDS > 0
- varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
- #endif
- #if NUM_SPOT_LIGHT_MAPS > 0
- uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
- #endif
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
- varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
- struct DirectionalLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
- struct SpotLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
- varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
- struct PointLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- float shadowCameraNear;
- float shadowCameraFar;
- };
- uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
- #endif
- float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
- return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
- }
- vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
- return unpackRGBATo2Half( texture2D( shadow, uv ) );
- }
- float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
- float occlusion = 1.0;
- vec2 distribution = texture2DDistribution( shadow, uv );
- float hard_shadow = step( compare , distribution.x );
- if (hard_shadow != 1.0 ) {
- float distance = compare - distribution.x ;
- float variance = max( 0.00000, distribution.y * distribution.y );
- 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 );
- }
- return occlusion;
- }
- float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
- float shadow = 1.0;
- shadowCoord.xyz /= shadowCoord.w;
- shadowCoord.z += shadowBias;
- bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
- bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
- if ( frustumTest ) {
- #if defined( SHADOWMAP_TYPE_PCF )
- vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
- float dx0 = - texelSize.x * shadowRadius;
- float dy0 = - texelSize.y * shadowRadius;
- float dx1 = + texelSize.x * shadowRadius;
- float dy1 = + texelSize.y * shadowRadius;
- float dx2 = dx0 / 2.0;
- float dy2 = dy0 / 2.0;
- float dx3 = dx1 / 2.0;
- float dy3 = dy1 / 2.0;
- shadow = (
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
- ) * ( 1.0 / 17.0 );
- #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
- vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
- float dx = texelSize.x;
- float dy = texelSize.y;
- vec2 uv = shadowCoord.xy;
- vec2 f = fract( uv * shadowMapSize + 0.5 );
- uv -= f * texelSize;
- shadow = (
- texture2DCompare( shadowMap, uv, shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
- texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
- f.x ) +
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
- f.x ) +
- mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
- f.y ) +
- mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
- f.y ) +
- mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
- f.x ),
- mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
- texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
- f.x ),
- f.y )
- ) * ( 1.0 / 9.0 );
- #elif defined( SHADOWMAP_TYPE_VSM )
- shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
- #else
- shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
- #endif
- }
- return shadow;
- }
- vec2 cubeToUV( vec3 v, float texelSizeY ) {
- vec3 absV = abs( v );
- float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
- absV *= scaleToCube;
- v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
- vec2 planar = v.xy;
- float almostATexel = 1.5 * texelSizeY;
- float almostOne = 1.0 - almostATexel;
- if ( absV.z >= almostOne ) {
- if ( v.z > 0.0 )
- planar.x = 4.0 - v.x;
- } else if ( absV.x >= almostOne ) {
- float signX = sign( v.x );
- planar.x = v.z * signX + 2.0 * signX;
- } else if ( absV.y >= almostOne ) {
- float signY = sign( v.y );
- planar.x = v.x + 2.0 * signY + 2.0;
- planar.y = v.z * signY - 2.0;
- }
- return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
- }
- float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
- vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
- vec3 lightToPosition = shadowCoord.xyz;
- float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
- vec3 bd3D = normalize( lightToPosition );
- #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
- vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
- return (
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
- texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
- ) * ( 1.0 / 9.0 );
- #else
- return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
- #endif
- }
- #endif`,XPe=`#if NUM_SPOT_LIGHT_COORDS > 0
- uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
- varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
- #endif
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
- varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
- struct DirectionalLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- struct SpotLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- };
- uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
- varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
- struct PointLightShadow {
- float shadowBias;
- float shadowNormalBias;
- float shadowRadius;
- vec2 shadowMapSize;
- float shadowCameraNear;
- float shadowCameraFar;
- };
- uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
- #endif
- #endif`,YPe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
- vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
- vec4 shadowWorldPosition;
- #endif
- #if defined( USE_SHADOWMAP )
- #if NUM_DIR_LIGHT_SHADOWS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
- shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
- vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
- shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
- vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif
- #endif
- #if NUM_SPOT_LIGHT_COORDS > 0
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
- shadowWorldPosition = worldPosition;
- #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
- shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
- #endif
- vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
- }
- #pragma unroll_loop_end
- #endif`,QPe=`float getShadowMask() {
- float shadow = 1.0;
- #ifdef USE_SHADOWMAP
- #if NUM_DIR_LIGHT_SHADOWS > 0
- DirectionalLightShadow directionalLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
- directionalLight = directionalLightShadows[ i ];
- shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_SPOT_LIGHT_SHADOWS > 0
- SpotLightShadow spotLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
- spotLight = spotLightShadows[ i ];
- shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #if NUM_POINT_LIGHT_SHADOWS > 0
- PointLightShadow pointLight;
- #pragma unroll_loop_start
- for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
- pointLight = pointLightShadows[ i ];
- shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
- }
- #pragma unroll_loop_end
- #endif
- #endif
- return shadow;
- }`,ZPe=`#ifdef USE_SKINNING
- mat4 boneMatX = getBoneMatrix( skinIndex.x );
- mat4 boneMatY = getBoneMatrix( skinIndex.y );
- mat4 boneMatZ = getBoneMatrix( skinIndex.z );
- mat4 boneMatW = getBoneMatrix( skinIndex.w );
- #endif`,JPe=`#ifdef USE_SKINNING
- uniform mat4 bindMatrix;
- uniform mat4 bindMatrixInverse;
- uniform highp sampler2D boneTexture;
- mat4 getBoneMatrix( const in float i ) {
- int size = textureSize( boneTexture, 0 ).x;
- int j = int( i ) * 4;
- int x = j % size;
- int y = j / size;
- vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
- vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
- vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
- vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
- return mat4( v1, v2, v3, v4 );
- }
- #endif`,eTe=`#ifdef USE_SKINNING
- vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
- vec4 skinned = vec4( 0.0 );
- skinned += boneMatX * skinVertex * skinWeight.x;
- skinned += boneMatY * skinVertex * skinWeight.y;
- skinned += boneMatZ * skinVertex * skinWeight.z;
- skinned += boneMatW * skinVertex * skinWeight.w;
- transformed = ( bindMatrixInverse * skinned ).xyz;
- #endif`,tTe=`#ifdef USE_SKINNING
- mat4 skinMatrix = mat4( 0.0 );
- skinMatrix += skinWeight.x * boneMatX;
- skinMatrix += skinWeight.y * boneMatY;
- skinMatrix += skinWeight.z * boneMatZ;
- skinMatrix += skinWeight.w * boneMatW;
- skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
- objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
- #ifdef USE_TANGENT
- objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
- #endif
- #endif`,nTe=`float specularStrength;
- #ifdef USE_SPECULARMAP
- vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
- specularStrength = texelSpecular.r;
- #else
- specularStrength = 1.0;
- #endif`,rTe=`#ifdef USE_SPECULARMAP
- uniform sampler2D specularMap;
- #endif`,aTe=`#if defined( TONE_MAPPING )
- gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
- #endif`,iTe=`#ifndef saturate
- #define saturate( a ) clamp( a, 0.0, 1.0 )
- #endif
- uniform float toneMappingExposure;
- vec3 LinearToneMapping( vec3 color ) {
- return saturate( toneMappingExposure * color );
- }
- vec3 ReinhardToneMapping( vec3 color ) {
- color *= toneMappingExposure;
- return saturate( color / ( vec3( 1.0 ) + color ) );
- }
- vec3 OptimizedCineonToneMapping( vec3 color ) {
- color *= toneMappingExposure;
- color = max( vec3( 0.0 ), color - 0.004 );
- return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
- }
- vec3 RRTAndODTFit( vec3 v ) {
- vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
- vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
- return a / b;
- }
- vec3 ACESFilmicToneMapping( vec3 color ) {
- const mat3 ACESInputMat = mat3(
- vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
- vec3( 0.04823, 0.01566, 0.83777 )
- );
- const mat3 ACESOutputMat = mat3(
- vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
- vec3( -0.07367, -0.00605, 1.07602 )
- );
- color *= toneMappingExposure / 0.6;
- color = ACESInputMat * color;
- color = RRTAndODTFit( color );
- color = ACESOutputMat * color;
- return saturate( color );
- }
- vec3 CustomToneMapping( vec3 color ) { return color; }`,sTe=`#ifdef USE_TRANSMISSION
- material.transmission = transmission;
- material.transmissionAlpha = 1.0;
- material.thickness = thickness;
- material.attenuationDistance = attenuationDistance;
- material.attenuationColor = attenuationColor;
- #ifdef USE_TRANSMISSIONMAP
- material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
- #endif
- #ifdef USE_THICKNESSMAP
- material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
- #endif
- vec3 pos = vWorldPosition;
- vec3 v = normalize( cameraPosition - pos );
- vec3 n = inverseTransformDirection( normal, viewMatrix );
- vec4 transmitted = getIBLVolumeRefraction(
- n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
- pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,
- material.attenuationColor, material.attenuationDistance );
- material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
- totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
- #endif`,oTe=`#ifdef USE_TRANSMISSION
- uniform float transmission;
- uniform float thickness;
- uniform float attenuationDistance;
- uniform vec3 attenuationColor;
- #ifdef USE_TRANSMISSIONMAP
- uniform sampler2D transmissionMap;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform sampler2D thicknessMap;
- #endif
- uniform vec2 transmissionSamplerSize;
- uniform sampler2D transmissionSamplerMap;
- uniform mat4 modelMatrix;
- uniform mat4 projectionMatrix;
- varying vec3 vWorldPosition;
- float w0( float a ) {
- return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
- }
- float w1( float a ) {
- return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
- }
- float w2( float a ){
- return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
- }
- float w3( float a ) {
- return ( 1.0 / 6.0 ) * ( a * a * a );
- }
- float g0( float a ) {
- return w0( a ) + w1( a );
- }
- float g1( float a ) {
- return w2( a ) + w3( a );
- }
- float h0( float a ) {
- return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
- }
- float h1( float a ) {
- return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
- }
- vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
- uv = uv * texelSize.zw + 0.5;
- vec2 iuv = floor( uv );
- vec2 fuv = fract( uv );
- float g0x = g0( fuv.x );
- float g1x = g1( fuv.x );
- float h0x = h0( fuv.x );
- float h1x = h1( fuv.x );
- float h0y = h0( fuv.y );
- float h1y = h1( fuv.y );
- vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
- vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
- vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
- vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
- return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
- g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
- }
- vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
- vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
- vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
- vec2 fLodSizeInv = 1.0 / fLodSize;
- vec2 cLodSizeInv = 1.0 / cLodSize;
- vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
- vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
- return mix( fSample, cSample, fract( lod ) );
- }
- vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
- vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
- vec3 modelScale;
- modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
- modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
- modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
- return normalize( refractionVector ) * thickness * modelScale;
- }
- float applyIorToRoughness( const in float roughness, const in float ior ) {
- return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
- }
- vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
- float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
- return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
- }
- vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
- if ( isinf( attenuationDistance ) ) {
- return vec3( 1.0 );
- } else {
- vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
- vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
- }
- }
- vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
- const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
- const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
- const in vec3 attenuationColor, const in float attenuationDistance ) {
- vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
- vec3 refractedRayExit = position + transmissionRay;
- vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
- vec2 refractionCoords = ndcPos.xy / ndcPos.w;
- refractionCoords += 1.0;
- refractionCoords /= 2.0;
- vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
- vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
- vec3 attenuatedColor = transmittance * transmittedLight.rgb;
- vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
- float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
- return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
- }
- #endif`,lTe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- varying vec2 vUv;
- #endif
- #ifdef USE_MAP
- varying vec2 vMapUv;
- #endif
- #ifdef USE_ALPHAMAP
- varying vec2 vAlphaMapUv;
- #endif
- #ifdef USE_LIGHTMAP
- varying vec2 vLightMapUv;
- #endif
- #ifdef USE_AOMAP
- varying vec2 vAoMapUv;
- #endif
- #ifdef USE_BUMPMAP
- varying vec2 vBumpMapUv;
- #endif
- #ifdef USE_NORMALMAP
- varying vec2 vNormalMapUv;
- #endif
- #ifdef USE_EMISSIVEMAP
- varying vec2 vEmissiveMapUv;
- #endif
- #ifdef USE_METALNESSMAP
- varying vec2 vMetalnessMapUv;
- #endif
- #ifdef USE_ROUGHNESSMAP
- varying vec2 vRoughnessMapUv;
- #endif
- #ifdef USE_ANISOTROPYMAP
- varying vec2 vAnisotropyMapUv;
- #endif
- #ifdef USE_CLEARCOATMAP
- varying vec2 vClearcoatMapUv;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- varying vec2 vClearcoatNormalMapUv;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- varying vec2 vClearcoatRoughnessMapUv;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- varying vec2 vIridescenceMapUv;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- varying vec2 vIridescenceThicknessMapUv;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- varying vec2 vSheenColorMapUv;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- varying vec2 vSheenRoughnessMapUv;
- #endif
- #ifdef USE_SPECULARMAP
- varying vec2 vSpecularMapUv;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- varying vec2 vSpecularColorMapUv;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- varying vec2 vSpecularIntensityMapUv;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- uniform mat3 transmissionMapTransform;
- varying vec2 vTransmissionMapUv;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform mat3 thicknessMapTransform;
- varying vec2 vThicknessMapUv;
- #endif`,cTe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- varying vec2 vUv;
- #endif
- #ifdef USE_MAP
- uniform mat3 mapTransform;
- varying vec2 vMapUv;
- #endif
- #ifdef USE_ALPHAMAP
- uniform mat3 alphaMapTransform;
- varying vec2 vAlphaMapUv;
- #endif
- #ifdef USE_LIGHTMAP
- uniform mat3 lightMapTransform;
- varying vec2 vLightMapUv;
- #endif
- #ifdef USE_AOMAP
- uniform mat3 aoMapTransform;
- varying vec2 vAoMapUv;
- #endif
- #ifdef USE_BUMPMAP
- uniform mat3 bumpMapTransform;
- varying vec2 vBumpMapUv;
- #endif
- #ifdef USE_NORMALMAP
- uniform mat3 normalMapTransform;
- varying vec2 vNormalMapUv;
- #endif
- #ifdef USE_DISPLACEMENTMAP
- uniform mat3 displacementMapTransform;
- varying vec2 vDisplacementMapUv;
- #endif
- #ifdef USE_EMISSIVEMAP
- uniform mat3 emissiveMapTransform;
- varying vec2 vEmissiveMapUv;
- #endif
- #ifdef USE_METALNESSMAP
- uniform mat3 metalnessMapTransform;
- varying vec2 vMetalnessMapUv;
- #endif
- #ifdef USE_ROUGHNESSMAP
- uniform mat3 roughnessMapTransform;
- varying vec2 vRoughnessMapUv;
- #endif
- #ifdef USE_ANISOTROPYMAP
- uniform mat3 anisotropyMapTransform;
- varying vec2 vAnisotropyMapUv;
- #endif
- #ifdef USE_CLEARCOATMAP
- uniform mat3 clearcoatMapTransform;
- varying vec2 vClearcoatMapUv;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- uniform mat3 clearcoatNormalMapTransform;
- varying vec2 vClearcoatNormalMapUv;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- uniform mat3 clearcoatRoughnessMapTransform;
- varying vec2 vClearcoatRoughnessMapUv;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- uniform mat3 sheenColorMapTransform;
- varying vec2 vSheenColorMapUv;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- uniform mat3 sheenRoughnessMapTransform;
- varying vec2 vSheenRoughnessMapUv;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- uniform mat3 iridescenceMapTransform;
- varying vec2 vIridescenceMapUv;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- uniform mat3 iridescenceThicknessMapTransform;
- varying vec2 vIridescenceThicknessMapUv;
- #endif
- #ifdef USE_SPECULARMAP
- uniform mat3 specularMapTransform;
- varying vec2 vSpecularMapUv;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- uniform mat3 specularColorMapTransform;
- varying vec2 vSpecularColorMapUv;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- uniform mat3 specularIntensityMapTransform;
- varying vec2 vSpecularIntensityMapUv;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- uniform mat3 transmissionMapTransform;
- varying vec2 vTransmissionMapUv;
- #endif
- #ifdef USE_THICKNESSMAP
- uniform mat3 thicknessMapTransform;
- varying vec2 vThicknessMapUv;
- #endif`,dTe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
- vUv = vec3( uv, 1 ).xy;
- #endif
- #ifdef USE_MAP
- vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ALPHAMAP
- vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_LIGHTMAP
- vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_AOMAP
- vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_BUMPMAP
- vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_NORMALMAP
- vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_DISPLACEMENTMAP
- vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_EMISSIVEMAP
- vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_METALNESSMAP
- vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ROUGHNESSMAP
- vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_ANISOTROPYMAP
- vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOATMAP
- vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOAT_NORMALMAP
- vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_CLEARCOAT_ROUGHNESSMAP
- vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_IRIDESCENCEMAP
- vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_IRIDESCENCE_THICKNESSMAP
- vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SHEEN_COLORMAP
- vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULARMAP
- vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULAR_COLORMAP
- vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_TRANSMISSIONMAP
- vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
- #endif
- #ifdef USE_THICKNESSMAP
- vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
- #endif`,uTe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
- vec4 worldPosition = vec4( transformed, 1.0 );
- #ifdef USE_BATCHING
- worldPosition = batchingMatrix * worldPosition;
- #endif
- #ifdef USE_INSTANCING
- worldPosition = instanceMatrix * worldPosition;
- #endif
- worldPosition = modelMatrix * worldPosition;
- #endif`;const mTe=`varying vec2 vUv;
- uniform mat3 uvTransform;
- void main() {
- vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
- gl_Position = vec4( position.xy, 1.0, 1.0 );
- }`,hTe=`uniform sampler2D t2D;
- uniform float backgroundIntensity;
- varying vec2 vUv;
- void main() {
- vec4 texColor = texture2D( t2D, vUv );
- #ifdef DECODE_VIDEO_TEXTURE
- 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 );
- #endif
- texColor.rgb *= backgroundIntensity;
- gl_FragColor = texColor;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,pTe=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- gl_Position.z = gl_Position.w;
- }`,fTe=`#ifdef ENVMAP_TYPE_CUBE
- uniform samplerCube envMap;
- #elif defined( ENVMAP_TYPE_CUBE_UV )
- uniform sampler2D envMap;
- #endif
- uniform float flipEnvMap;
- uniform float backgroundBlurriness;
- uniform float backgroundIntensity;
- varying vec3 vWorldDirection;
- #include <cube_uv_reflection_fragment>
- void main() {
- #ifdef ENVMAP_TYPE_CUBE
- vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
- #elif defined( ENVMAP_TYPE_CUBE_UV )
- vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );
- #else
- vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
- #endif
- texColor.rgb *= backgroundIntensity;
- gl_FragColor = texColor;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,gTe=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- gl_Position.z = gl_Position.w;
- }`,bTe=`uniform samplerCube tCube;
- uniform float tFlip;
- uniform float opacity;
- varying vec3 vWorldDirection;
- void main() {
- vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
- gl_FragColor = texColor;
- gl_FragColor.a *= opacity;
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,xTe=`#include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- varying vec2 vHighPrecisionZW;
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <skinbase_vertex>
- #ifdef USE_DISPLACEMENTMAP
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vHighPrecisionZW = gl_Position.zw;
- }`,yTe=`#if DEPTH_PACKING == 3200
- uniform float opacity;
- #endif
- #include <common>
- #include <packing>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- varying vec2 vHighPrecisionZW;
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( 1.0 );
- #if DEPTH_PACKING == 3200
- diffuseColor.a = opacity;
- #endif
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <logdepthbuf_fragment>
- float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
- #if DEPTH_PACKING == 3200
- gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
- #elif DEPTH_PACKING == 3201
- gl_FragColor = packDepthToRGBA( fragCoordZ );
- #endif
- }`,vTe=`#define DISTANCE
- varying vec3 vWorldPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <skinbase_vertex>
- #ifdef USE_DISPLACEMENTMAP
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <worldpos_vertex>
- #include <clipping_planes_vertex>
- vWorldPosition = worldPosition.xyz;
- }`,wTe=`#define DISTANCE
- uniform vec3 referencePosition;
- uniform float nearDistance;
- uniform float farDistance;
- varying vec3 vWorldPosition;
- #include <common>
- #include <packing>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main () {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( 1.0 );
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- float dist = length( vWorldPosition - referencePosition );
- dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
- dist = saturate( dist );
- gl_FragColor = packDepthToRGBA( dist );
- }`,STe=`varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vWorldDirection = transformDirection( position, modelMatrix );
- #include <begin_vertex>
- #include <project_vertex>
- }`,_Te=`uniform sampler2D tEquirect;
- varying vec3 vWorldDirection;
- #include <common>
- void main() {
- vec3 direction = normalize( vWorldDirection );
- vec2 sampleUV = equirectUv( direction );
- gl_FragColor = texture2D( tEquirect, sampleUV );
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- }`,kTe=`uniform float scale;
- attribute float lineDistance;
- varying float vLineDistance;
- #include <common>
- #include <uv_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- vLineDistance = scale * lineDistance;
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- }`,NTe=`uniform vec3 diffuse;
- uniform float opacity;
- uniform float dashSize;
- uniform float totalSize;
- varying float vLineDistance;
- #include <common>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- if ( mod( vLineDistance, totalSize ) > dashSize ) {
- discard;
- }
- vec3 outgoingLight = vec3( 0.0 );
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- }`,CTe=`#include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #endif
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <fog_vertex>
- }`,PTe=`uniform vec3 diffuse;
- uniform float opacity;
- #ifndef FLAT_SHADED
- varying vec3 vNormal;
- #endif
- #include <common>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- #ifdef USE_LIGHTMAP
- vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
- reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
- #else
- reflectedLight.indirectDiffuse += vec3( 1.0 );
- #endif
- #include <aomap_fragment>
- reflectedLight.indirectDiffuse *= diffuseColor.rgb;
- vec3 outgoingLight = reflectedLight.indirectDiffuse;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,TTe=`#define LAMBERT
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,ATe=`#define LAMBERT
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_lambert_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_lambert_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,jTe=`#define MATCAP
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <color_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- vViewPosition = - mvPosition.xyz;
- }`,MTe=`#define MATCAP
- uniform vec3 diffuse;
- uniform float opacity;
- uniform sampler2D matcap;
- varying vec3 vViewPosition;
- #include <common>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <normal_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- vec3 viewDir = normalize( vViewPosition );
- vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
- vec3 y = cross( viewDir, x );
- vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
- #ifdef USE_MATCAP
- vec4 matcapColor = texture2D( matcap, uv );
- #else
- vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
- #endif
- vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,ETe=`#define NORMAL
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- varying vec3 vViewPosition;
- #endif
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- vViewPosition = - mvPosition.xyz;
- #endif
- }`,DTe=`#define NORMAL
- uniform float opacity;
- #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
- varying vec3 vViewPosition;
- #endif
- #include <packing>
- #include <uv_pars_fragment>
- #include <normal_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- #include <logdepthbuf_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- gl_FragColor = vec4( packNormalToRGB( normal ), opacity );
- #ifdef OPAQUE
- gl_FragColor.a = 1.0;
- #endif
- }`,FTe=`#define PHONG
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <envmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <envmap_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,RTe=`#define PHONG
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform vec3 specular;
- uniform float shininess;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_phong_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <specularmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <specularmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_phong_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
- #include <envmap_fragment>
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,LTe=`#define STANDARD
- varying vec3 vViewPosition;
- #ifdef USE_TRANSMISSION
- varying vec3 vWorldPosition;
- #endif
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- #ifdef USE_TRANSMISSION
- vWorldPosition = worldPosition.xyz;
- #endif
- }`,OTe=`#define STANDARD
- #ifdef PHYSICAL
- #define IOR
- #define USE_SPECULAR
- #endif
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float roughness;
- uniform float metalness;
- uniform float opacity;
- #ifdef IOR
- uniform float ior;
- #endif
- #ifdef USE_SPECULAR
- uniform float specularIntensity;
- uniform vec3 specularColor;
- #ifdef USE_SPECULAR_COLORMAP
- uniform sampler2D specularColorMap;
- #endif
- #ifdef USE_SPECULAR_INTENSITYMAP
- uniform sampler2D specularIntensityMap;
- #endif
- #endif
- #ifdef USE_CLEARCOAT
- uniform float clearcoat;
- uniform float clearcoatRoughness;
- #endif
- #ifdef USE_IRIDESCENCE
- uniform float iridescence;
- uniform float iridescenceIOR;
- uniform float iridescenceThicknessMinimum;
- uniform float iridescenceThicknessMaximum;
- #endif
- #ifdef USE_SHEEN
- uniform vec3 sheenColor;
- uniform float sheenRoughness;
- #ifdef USE_SHEEN_COLORMAP
- uniform sampler2D sheenColorMap;
- #endif
- #ifdef USE_SHEEN_ROUGHNESSMAP
- uniform sampler2D sheenRoughnessMap;
- #endif
- #endif
- #ifdef USE_ANISOTROPY
- uniform vec2 anisotropyVector;
- #ifdef USE_ANISOTROPYMAP
- uniform sampler2D anisotropyMap;
- #endif
- #endif
- varying vec3 vViewPosition;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <iridescence_fragment>
- #include <cube_uv_reflection_fragment>
- #include <envmap_common_pars_fragment>
- #include <envmap_physical_pars_fragment>
- #include <fog_pars_fragment>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_physical_pars_fragment>
- #include <transmission_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <clearcoat_pars_fragment>
- #include <iridescence_pars_fragment>
- #include <roughnessmap_pars_fragment>
- #include <metalnessmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <roughnessmap_fragment>
- #include <metalnessmap_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <clearcoat_normal_fragment_begin>
- #include <clearcoat_normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_physical_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
- vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
- #include <transmission_fragment>
- vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
- #ifdef USE_SHEEN
- float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
- outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
- #endif
- #ifdef USE_CLEARCOAT
- float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
- vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
- outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
- #endif
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,ITe=`#define TOON
- varying vec3 vViewPosition;
- #include <common>
- #include <batching_pars_vertex>
- #include <uv_pars_vertex>
- #include <displacementmap_pars_vertex>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <normal_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <shadowmap_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <normal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <displacementmap_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- vViewPosition = - mvPosition.xyz;
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,zTe=`#define TOON
- uniform vec3 diffuse;
- uniform vec3 emissive;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <dithering_pars_fragment>
- #include <color_pars_fragment>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <aomap_pars_fragment>
- #include <lightmap_pars_fragment>
- #include <emissivemap_pars_fragment>
- #include <gradientmap_pars_fragment>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <normal_pars_fragment>
- #include <lights_toon_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <bumpmap_pars_fragment>
- #include <normalmap_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec4 diffuseColor = vec4( diffuse, opacity );
- ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
- vec3 totalEmissiveRadiance = emissive;
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <color_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- #include <normal_fragment_begin>
- #include <normal_fragment_maps>
- #include <emissivemap_fragment>
- #include <lights_toon_fragment>
- #include <lights_fragment_begin>
- #include <lights_fragment_maps>
- #include <lights_fragment_end>
- #include <aomap_fragment>
- vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- #include <dithering_fragment>
- }`,UTe=`uniform float size;
- uniform float scale;
- #include <common>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- #ifdef USE_POINTS_UV
- varying vec2 vUv;
- uniform mat3 uvTransform;
- #endif
- void main() {
- #ifdef USE_POINTS_UV
- vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
- #endif
- #include <color_vertex>
- #include <morphcolor_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <project_vertex>
- gl_PointSize = size;
- #ifdef USE_SIZEATTENUATION
- bool isPerspective = isPerspectiveMatrix( projectionMatrix );
- if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
- #endif
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <worldpos_vertex>
- #include <fog_vertex>
- }`,BTe=`uniform vec3 diffuse;
- uniform float opacity;
- #include <common>
- #include <color_pars_fragment>
- #include <map_particle_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec3 outgoingLight = vec3( 0.0 );
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <logdepthbuf_fragment>
- #include <map_particle_fragment>
- #include <color_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- }`,HTe=`#include <common>
- #include <batching_pars_vertex>
- #include <fog_pars_vertex>
- #include <morphtarget_pars_vertex>
- #include <skinning_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <shadowmap_pars_vertex>
- void main() {
- #include <batching_vertex>
- #include <beginnormal_vertex>
- #include <morphnormal_vertex>
- #include <skinbase_vertex>
- #include <skinnormal_vertex>
- #include <defaultnormal_vertex>
- #include <begin_vertex>
- #include <morphtarget_vertex>
- #include <skinning_vertex>
- #include <project_vertex>
- #include <logdepthbuf_vertex>
- #include <worldpos_vertex>
- #include <shadowmap_vertex>
- #include <fog_vertex>
- }`,qTe=`uniform vec3 color;
- uniform float opacity;
- #include <common>
- #include <packing>
- #include <fog_pars_fragment>
- #include <bsdfs>
- #include <lights_pars_begin>
- #include <logdepthbuf_pars_fragment>
- #include <shadowmap_pars_fragment>
- #include <shadowmask_pars_fragment>
- void main() {
- #include <logdepthbuf_fragment>
- gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- }`,$Te=`uniform float rotation;
- uniform vec2 center;
- #include <common>
- #include <uv_pars_vertex>
- #include <fog_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- void main() {
- #include <uv_vertex>
- vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
- vec2 scale;
- scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
- scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
- #ifndef USE_SIZEATTENUATION
- bool isPerspective = isPerspectiveMatrix( projectionMatrix );
- if ( isPerspective ) scale *= - mvPosition.z;
- #endif
- vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
- vec2 rotatedPosition;
- rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
- rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
- mvPosition.xy += rotatedPosition;
- gl_Position = projectionMatrix * mvPosition;
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- }`,VTe=`uniform vec3 diffuse;
- uniform float opacity;
- #include <common>
- #include <uv_pars_fragment>
- #include <map_pars_fragment>
- #include <alphamap_pars_fragment>
- #include <alphatest_pars_fragment>
- #include <alphahash_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- void main() {
- #include <clipping_planes_fragment>
- vec3 outgoingLight = vec3( 0.0 );
- vec4 diffuseColor = vec4( diffuse, opacity );
- #include <logdepthbuf_fragment>
- #include <map_fragment>
- #include <alphamap_fragment>
- #include <alphatest_fragment>
- #include <alphahash_fragment>
- outgoingLight = diffuseColor.rgb;
- #include <opaque_fragment>
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- }`,rr={alphahash_fragment:hCe,alphahash_pars_fragment:pCe,alphamap_fragment:fCe,alphamap_pars_fragment:gCe,alphatest_fragment:bCe,alphatest_pars_fragment:xCe,aomap_fragment:yCe,aomap_pars_fragment:vCe,batching_pars_vertex:wCe,batching_vertex:SCe,begin_vertex:_Ce,beginnormal_vertex:kCe,bsdfs:NCe,iridescence_fragment:CCe,bumpmap_pars_fragment:PCe,clipping_planes_fragment:TCe,clipping_planes_pars_fragment:ACe,clipping_planes_pars_vertex:jCe,clipping_planes_vertex:MCe,color_fragment:ECe,color_pars_fragment:DCe,color_pars_vertex:FCe,color_vertex:RCe,common:LCe,cube_uv_reflection_fragment:OCe,defaultnormal_vertex:ICe,displacementmap_pars_vertex:zCe,displacementmap_vertex:UCe,emissivemap_fragment:BCe,emissivemap_pars_fragment:HCe,colorspace_fragment:qCe,colorspace_pars_fragment:$Ce,envmap_fragment:VCe,envmap_common_pars_fragment:GCe,envmap_pars_fragment:WCe,envmap_pars_vertex:KCe,envmap_physical_pars_fragment:sPe,envmap_vertex:XCe,fog_vertex:YCe,fog_pars_vertex:QCe,fog_fragment:ZCe,fog_pars_fragment:JCe,gradientmap_pars_fragment:ePe,lightmap_fragment:tPe,lightmap_pars_fragment:nPe,lights_lambert_fragment:rPe,lights_lambert_pars_fragment:aPe,lights_pars_begin:iPe,lights_toon_fragment:oPe,lights_toon_pars_fragment:lPe,lights_phong_fragment:cPe,lights_phong_pars_fragment:dPe,lights_physical_fragment:uPe,lights_physical_pars_fragment:mPe,lights_fragment_begin:hPe,lights_fragment_maps:pPe,lights_fragment_end:fPe,logdepthbuf_fragment:gPe,logdepthbuf_pars_fragment:bPe,logdepthbuf_pars_vertex:xPe,logdepthbuf_vertex:yPe,map_fragment:vPe,map_pars_fragment:wPe,map_particle_fragment:SPe,map_particle_pars_fragment:_Pe,metalnessmap_fragment:kPe,metalnessmap_pars_fragment:NPe,morphcolor_vertex:CPe,morphnormal_vertex:PPe,morphtarget_pars_vertex:TPe,morphtarget_vertex:APe,normal_fragment_begin:jPe,normal_fragment_maps:MPe,normal_pars_fragment:EPe,normal_pars_vertex:DPe,normal_vertex:FPe,normalmap_pars_fragment:RPe,clearcoat_normal_fragment_begin:LPe,clearcoat_normal_fragment_maps:OPe,clearcoat_pars_fragment:IPe,iridescence_pars_fragment:zPe,opaque_fragment:UPe,packing:BPe,premultiplied_alpha_fragment:HPe,project_vertex:qPe,dithering_fragment:$Pe,dithering_pars_fragment:VPe,roughnessmap_fragment:GPe,roughnessmap_pars_fragment:WPe,shadowmap_pars_fragment:KPe,shadowmap_pars_vertex:XPe,shadowmap_vertex:YPe,shadowmask_pars_fragment:QPe,skinbase_vertex:ZPe,skinning_pars_vertex:JPe,skinning_vertex:eTe,skinnormal_vertex:tTe,specularmap_fragment:nTe,specularmap_pars_fragment:rTe,tonemapping_fragment:aTe,tonemapping_pars_fragment:iTe,transmission_fragment:sTe,transmission_pars_fragment:oTe,uv_pars_fragment:lTe,uv_pars_vertex:cTe,uv_vertex:dTe,worldpos_vertex:uTe,background_vert:mTe,background_frag:hTe,backgroundCube_vert:pTe,backgroundCube_frag:fTe,cube_vert:gTe,cube_frag:bTe,depth_vert:xTe,depth_frag:yTe,distanceRGBA_vert:vTe,distanceRGBA_frag:wTe,equirect_vert:STe,equirect_frag:_Te,linedashed_vert:kTe,linedashed_frag:NTe,meshbasic_vert:CTe,meshbasic_frag:PTe,meshlambert_vert:TTe,meshlambert_frag:ATe,meshmatcap_vert:jTe,meshmatcap_frag:MTe,meshnormal_vert:ETe,meshnormal_frag:DTe,meshphong_vert:FTe,meshphong_frag:RTe,meshphysical_vert:LTe,meshphysical_frag:OTe,meshtoon_vert:ITe,meshtoon_frag:zTe,points_vert:UTe,points_frag:BTe,shadow_vert:HTe,shadow_frag:qTe,sprite_vert:$Te,sprite_frag:VTe},Zt={common:{diffuse:{value:new Dn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ur},alphaMap:{value:null},alphaMapTransform:{value:new ur},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ur}},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 ur}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ur}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ur},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ur},normalScale:{value:new Gn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ur},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ur}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ur}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ur}},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 ur},alphaTest:{value:0},uvTransform:{value:new ur}},sprite:{diffuse:{value:new Dn(16777215)},opacity:{value:1},center:{value:new Gn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ur},alphaMap:{value:null},alphaMapTransform:{value:new ur},alphaTest:{value:0}}},ko={basic:{uniforms:Gs([Zt.common,Zt.specularmap,Zt.envmap,Zt.aomap,Zt.lightmap,Zt.fog]),vertexShader:rr.meshbasic_vert,fragmentShader:rr.meshbasic_frag},lambert:{uniforms:Gs([Zt.common,Zt.specularmap,Zt.envmap,Zt.aomap,Zt.lightmap,Zt.emissivemap,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,Zt.fog,Zt.lights,{emissive:{value:new Dn(0)}}]),vertexShader:rr.meshlambert_vert,fragmentShader:rr.meshlambert_frag},phong:{uniforms:Gs([Zt.common,Zt.specularmap,Zt.envmap,Zt.aomap,Zt.lightmap,Zt.emissivemap,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,Zt.fog,Zt.lights,{emissive:{value:new Dn(0)},specular:{value:new Dn(1118481)},shininess:{value:30}}]),vertexShader:rr.meshphong_vert,fragmentShader:rr.meshphong_frag},standard:{uniforms:Gs([Zt.common,Zt.envmap,Zt.aomap,Zt.lightmap,Zt.emissivemap,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,Zt.roughnessmap,Zt.metalnessmap,Zt.fog,Zt.lights,{emissive:{value:new Dn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:rr.meshphysical_vert,fragmentShader:rr.meshphysical_frag},toon:{uniforms:Gs([Zt.common,Zt.aomap,Zt.lightmap,Zt.emissivemap,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,Zt.gradientmap,Zt.fog,Zt.lights,{emissive:{value:new Dn(0)}}]),vertexShader:rr.meshtoon_vert,fragmentShader:rr.meshtoon_frag},matcap:{uniforms:Gs([Zt.common,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,Zt.fog,{matcap:{value:null}}]),vertexShader:rr.meshmatcap_vert,fragmentShader:rr.meshmatcap_frag},points:{uniforms:Gs([Zt.points,Zt.fog]),vertexShader:rr.points_vert,fragmentShader:rr.points_frag},dashed:{uniforms:Gs([Zt.common,Zt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:rr.linedashed_vert,fragmentShader:rr.linedashed_frag},depth:{uniforms:Gs([Zt.common,Zt.displacementmap]),vertexShader:rr.depth_vert,fragmentShader:rr.depth_frag},normal:{uniforms:Gs([Zt.common,Zt.bumpmap,Zt.normalmap,Zt.displacementmap,{opacity:{value:1}}]),vertexShader:rr.meshnormal_vert,fragmentShader:rr.meshnormal_frag},sprite:{uniforms:Gs([Zt.sprite,Zt.fog]),vertexShader:rr.sprite_vert,fragmentShader:rr.sprite_frag},background:{uniforms:{uvTransform:{value:new ur},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:rr.background_vert,fragmentShader:rr.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:rr.backgroundCube_vert,fragmentShader:rr.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:rr.cube_vert,fragmentShader:rr.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:rr.equirect_vert,fragmentShader:rr.equirect_frag},distanceRGBA:{uniforms:Gs([Zt.common,Zt.displacementmap,{referencePosition:{value:new ct},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:rr.distanceRGBA_vert,fragmentShader:rr.distanceRGBA_frag},shadow:{uniforms:Gs([Zt.lights,Zt.fog,{color:{value:new Dn(0)},opacity:{value:1}}]),vertexShader:rr.shadow_vert,fragmentShader:rr.shadow_frag}};ko.physical={uniforms:Gs([ko.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ur},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ur},clearcoatNormalScale:{value:new Gn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ur},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ur},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ur},sheen:{value:0},sheenColor:{value:new Dn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ur},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ur},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ur},transmissionSamplerSize:{value:new Gn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ur},attenuationDistance:{value:0},attenuationColor:{value:new Dn(0)},specularColor:{value:new Dn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ur},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ur},anisotropyVector:{value:new Gn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ur}}]),vertexShader:rr.meshphysical_vert,fragmentShader:rr.meshphysical_frag};const N1={r:0,b:0,g:0};function GTe(t,e,n,r,i,s,o){const l=new Dn(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function x(g,b){let _=!1,C=b.isScene===!0?b.background:null;C&&C.isTexture&&(C=(b.backgroundBlurriness>0?n:e).get(C)),C===null?v(l,c):C&&C.isColor&&(v(C,1),_=!0);const P=t.xr.getEnvironmentBlendMode();P==="additive"?r.buffers.color.setClear(0,0,0,1,o):P==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),C&&(C.isCubeTexture||C.mapping===UP)?(u===void 0&&(u=new Lc(new Gw(1,1,1),new lp({name:"BackgroundCubeMaterial",uniforms:Ix(ko.backgroundCube.uniforms),vertexShader:ko.backgroundCube.vertexShader,fragmentShader:ko.backgroundCube.fragmentShader,side:jo,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(N,A,T){this.matrixWorld.copyPosition(T.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),u.material.uniforms.envMap.value=C,u.material.uniforms.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.toneMapped=Wr.getTransfer(C.colorSpace)!==ga,(m!==C||p!==C.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=C,p=C.version,f=t.toneMapping),u.layers.enableAll(),g.unshift(u,u.geometry,u.material,0,0,null)):C&&C.isTexture&&(d===void 0&&(d=new Lc(new eI(2,2),new lp({name:"BackgroundMaterial",uniforms:Ix(ko.background.uniforms),vertexShader:ko.background.vertexShader,fragmentShader:ko.background.fragmentShader,side:op,depthTest:!1,depthWrite:!1,fog:!1})),d.geometry.deleteAttribute("normal"),Object.defineProperty(d.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(d)),d.material.uniforms.t2D.value=C,d.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,d.material.toneMapped=Wr.getTransfer(C.colorSpace)!==ga,C.matrixAutoUpdate===!0&&C.updateMatrix(),d.material.uniforms.uvTransform.value.copy(C.matrix),(m!==C||p!==C.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=C,p=C.version,f=t.toneMapping),d.layers.enableAll(),g.unshift(d,d.geometry,d.material,0,0,null))}function v(g,b){g.getRGB(N1,oJ(t)),r.buffers.color.setClear(N1.r,N1.g,N1.b,b,o)}return{getClearColor:function(){return l},setClearColor:function(g,b=1){l.set(g),c=b,v(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(g){c=g,v(l,c)},render:x}}function WTe(t,e,n,r){const i=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 d=c,u=!1;function m(L,ne,ie,ee,ue){let le=!1;if(o){const oe=v(ee,ie,ne);d!==oe&&(d=oe,f(d.object)),le=b(L,ee,ie,ue),le&&_(L,ee,ie,ue)}else{const oe=ne.wireframe===!0;(d.geometry!==ee.id||d.program!==ie.id||d.wireframe!==oe)&&(d.geometry=ee.id,d.program=ie.id,d.wireframe=oe,le=!0)}ue!==null&&n.update(ue,t.ELEMENT_ARRAY_BUFFER),(le||u)&&(u=!1,F(L,ne,ie,ee),ue!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(ue).buffer))}function p(){return r.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function f(L){return r.isWebGL2?t.bindVertexArray(L):s.bindVertexArrayOES(L)}function x(L){return r.isWebGL2?t.deleteVertexArray(L):s.deleteVertexArrayOES(L)}function v(L,ne,ie){const ee=ie.wireframe===!0;let ue=l[L.id];ue===void 0&&(ue={},l[L.id]=ue);let le=ue[ne.id];le===void 0&&(le={},ue[ne.id]=le);let oe=le[ee];return oe===void 0&&(oe=g(p()),le[ee]=oe),oe}function g(L){const ne=[],ie=[],ee=[];for(let ue=0;ue<i;ue++)ne[ue]=0,ie[ue]=0,ee[ue]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:ne,enabledAttributes:ie,attributeDivisors:ee,object:L,attributes:{},index:null}}function b(L,ne,ie,ee){const ue=d.attributes,le=ne.attributes;let oe=0;const W=ie.getAttributes();for(const re in W)if(W[re].location>=0){const xe=ue[re];let Ne=le[re];if(Ne===void 0&&(re==="instanceMatrix"&&L.instanceMatrix&&(Ne=L.instanceMatrix),re==="instanceColor"&&L.instanceColor&&(Ne=L.instanceColor)),xe===void 0||xe.attribute!==Ne||Ne&&xe.data!==Ne.data)return!0;oe++}return d.attributesNum!==oe||d.index!==ee}function _(L,ne,ie,ee){const ue={},le=ne.attributes;let oe=0;const W=ie.getAttributes();for(const re in W)if(W[re].location>=0){let xe=le[re];xe===void 0&&(re==="instanceMatrix"&&L.instanceMatrix&&(xe=L.instanceMatrix),re==="instanceColor"&&L.instanceColor&&(xe=L.instanceColor));const Ne={};Ne.attribute=xe,xe&&xe.data&&(Ne.data=xe.data),ue[re]=Ne,oe++}d.attributes=ue,d.attributesNum=oe,d.index=ee}function C(){const L=d.newAttributes;for(let ne=0,ie=L.length;ne<ie;ne++)L[ne]=0}function P(L){N(L,0)}function N(L,ne){const ie=d.newAttributes,ee=d.enabledAttributes,ue=d.attributeDivisors;ie[L]=1,ee[L]===0&&(t.enableVertexAttribArray(L),ee[L]=1),ue[L]!==ne&&((r.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[r.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](L,ne),ue[L]=ne)}function A(){const L=d.newAttributes,ne=d.enabledAttributes;for(let ie=0,ee=ne.length;ie<ee;ie++)ne[ie]!==L[ie]&&(t.disableVertexAttribArray(ie),ne[ie]=0)}function T(L,ne,ie,ee,ue,le,oe){oe===!0?t.vertexAttribIPointer(L,ne,ie,ue,le):t.vertexAttribPointer(L,ne,ie,ee,ue,le)}function F(L,ne,ie,ee){if(r.isWebGL2===!1&&(L.isInstancedMesh||ee.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;C();const ue=ee.attributes,le=ie.getAttributes(),oe=ne.defaultAttributeValues;for(const W in le){const re=le[W];if(re.location>=0){let ce=ue[W];if(ce===void 0&&(W==="instanceMatrix"&&L.instanceMatrix&&(ce=L.instanceMatrix),W==="instanceColor"&&L.instanceColor&&(ce=L.instanceColor)),ce!==void 0){const xe=ce.normalized,Ne=ce.itemSize,$=n.get(ce);if($===void 0)continue;const Y=$.buffer,E=$.type,j=$.bytesPerElement,O=r.isWebGL2===!0&&(E===t.INT||E===t.UNSIGNED_INT||ce.gpuType===BZ);if(ce.isInterleavedBufferAttribute){const K=ce.data,B=K.stride,he=ce.offset;if(K.isInstancedInterleavedBuffer){for(let I=0;I<re.locationSize;I++)N(re.location+I,K.meshPerAttribute);L.isInstancedMesh!==!0&&ee._maxInstanceCount===void 0&&(ee._maxInstanceCount=K.meshPerAttribute*K.count)}else for(let I=0;I<re.locationSize;I++)P(re.location+I);t.bindBuffer(t.ARRAY_BUFFER,Y);for(let I=0;I<re.locationSize;I++)T(re.location+I,Ne/re.locationSize,E,xe,B*j,(he+Ne/re.locationSize*I)*j,O)}else{if(ce.isInstancedBufferAttribute){for(let K=0;K<re.locationSize;K++)N(re.location+K,ce.meshPerAttribute);L.isInstancedMesh!==!0&&ee._maxInstanceCount===void 0&&(ee._maxInstanceCount=ce.meshPerAttribute*ce.count)}else for(let K=0;K<re.locationSize;K++)P(re.location+K);t.bindBuffer(t.ARRAY_BUFFER,Y);for(let K=0;K<re.locationSize;K++)T(re.location+K,Ne/re.locationSize,E,xe,Ne*j,Ne/re.locationSize*K*j,O)}}else if(oe!==void 0){const xe=oe[W];if(xe!==void 0)switch(xe.length){case 2:t.vertexAttrib2fv(re.location,xe);break;case 3:t.vertexAttrib3fv(re.location,xe);break;case 4:t.vertexAttrib4fv(re.location,xe);break;default:t.vertexAttrib1fv(re.location,xe)}}}}A()}function k(){z();for(const L in l){const ne=l[L];for(const ie in ne){const ee=ne[ie];for(const ue in ee)x(ee[ue].object),delete ee[ue];delete ne[ie]}delete l[L]}}function D(L){if(l[L.id]===void 0)return;const ne=l[L.id];for(const ie in ne){const ee=ne[ie];for(const ue in ee)x(ee[ue].object),delete ee[ue];delete ne[ie]}delete l[L.id]}function H(L){for(const ne in l){const ie=l[ne];if(ie[L.id]===void 0)continue;const ee=ie[L.id];for(const ue in ee)x(ee[ue].object),delete ee[ue];delete ie[L.id]}}function z(){X(),u=!0,d!==c&&(d=c,f(d.object))}function X(){c.geometry=null,c.program=null,c.wireframe=!1}return{setup:m,reset:z,resetDefaultState:X,dispose:k,releaseStatesOfGeometry:D,releaseStatesOfProgram:H,initAttributes:C,enableAttribute:P,disableUnusedAttributes:A}}function KTe(t,e,n,r){const i=r.isWebGL2;let s;function o(u){s=u}function l(u,m){t.drawArrays(s,u,m),n.update(m,s,1)}function c(u,m,p){if(p===0)return;let f,x;if(i)f=t,x="drawArraysInstanced";else if(f=e.get("ANGLE_instanced_arrays"),x="drawArraysInstancedANGLE",f===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}f[x](s,u,m,p),n.update(m,s,p)}function d(u,m,p){if(p===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let x=0;x<p;x++)this.render(u[x],m[x]);else{f.multiDrawArraysWEBGL(s,u,0,m,0,p);let x=0;for(let v=0;v<p;v++)x+=m[v];n.update(x,s,1)}}this.setMode=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=d}function XTe(t,e,n){let r;function i(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){const T=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(T.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function s(T){if(T==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";T="mediump"}return T==="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 d=o||e.has("WEBGL_draw_buffers"),u=n.logarithmicDepthBuffer===!0,m=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),p=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),f=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),b=t.getParameter(t.MAX_VARYING_VECTORS),_=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),C=p>0,P=o||e.has("OES_texture_float"),N=C&&P,A=o?t.getParameter(t.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:d,getMaxAnisotropy:i,getMaxPrecision:s,precision:l,logarithmicDepthBuffer:u,maxTextures:m,maxVertexTextures:p,maxTextureSize:f,maxCubemapSize:x,maxAttributes:v,maxVertexUniforms:g,maxVaryings:b,maxFragmentUniforms:_,vertexTextures:C,floatFragmentTextures:P,floatVertexTextures:N,maxSamples:A}}function YTe(t){const e=this;let n=null,r=0,i=!1,s=!1;const o=new gh,l=new ur,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(m,p){const f=m.length!==0||p||r!==0||i;return i=p,r=m.length,f},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(m,p){n=u(m,p,0)},this.setState=function(m,p,f){const x=m.clippingPlanes,v=m.clipIntersection,g=m.clipShadows,b=t.get(m);if(!i||x===null||x.length===0||s&&!g)s?u(null):d();else{const _=s?0:r,C=_*4;let P=b.clippingState||null;c.value=P,P=u(x,p,C,f);for(let N=0;N!==C;++N)P[N]=n[N];b.clippingState=P,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function u(m,p,f,x){const v=m!==null?m.length:0;let g=null;if(v!==0){if(g=c.value,x!==!0||g===null){const b=f+v*4,_=p.matrixWorldInverse;l.getNormalMatrix(_),(g===null||g.length<b)&&(g=new Float32Array(b));for(let C=0,P=f;C!==v;++C,P+=4)o.copy(m[C]).applyMatrix4(_,l),o.normal.toArray(g,P),g[P+3]=o.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,g}}function QTe(t){let e=new WeakMap;function n(o,l){return l===XF?o.mapping=Rx:l===YF&&(o.mapping=Lx),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===XF||l===YF)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 d=new cCe(c.height/2);return d.fromEquirectangularTexture(t,o),e.set(o,d),o.addEventListener("dispose",i),n(d.texture,o.mapping)}else return null}}return o}function i(o){const l=o.target;l.removeEventListener("dispose",i);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class ZTe extends lJ{constructor(e=-1,n=1,r=1,i=-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=i,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,i,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=i,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,i=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=i+n,c=i-n;if(this.view!==null&&this.view.enabled){const d=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=d*this.view.offsetX,o=s+d*this.view.width,l-=u*this.view.offsetY,c=l-u*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 ix=4,Hq=[.125,.215,.35,.446,.526,.582],ff=20,SE=new ZTe,qq=new Dn;let _E=null,kE=0,NE=0;const lf=(1+Math.sqrt(5))/2,zb=1/lf,$q=[new ct(1,1,1),new ct(-1,1,1),new ct(1,1,-1),new ct(-1,1,-1),new ct(0,lf,zb),new ct(0,lf,-zb),new ct(zb,0,lf),new ct(-zb,0,lf),new ct(lf,zb,0),new ct(-lf,zb,0)];class Vq{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,i=100){_E=this._renderer.getRenderTarget(),kE=this._renderer.getActiveCubeFace(),NE=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,i,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=Kq(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Wq(),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(_E,kE,NE),e.scissorTest=!1,C1(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===Rx||e.mapping===Lx?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),_E=this._renderer.getRenderTarget(),kE=this._renderer.getActiveCubeFace(),NE=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:$l,minFilter:$l,generateMipmaps:!1,type:Y0,format:Vl,colorSpace:cm,depthBuffer:!1},i=Gq(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Gq(e,n,r);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=JTe(s)),this._blurMaterial=eAe(s,e,n)}return i}_compileMaterial(e){const n=new Lc(this._lodPlanes[0],e);this._renderer.compile(n,SE)}_sceneToCubeUV(e,n,r,i){const l=new Jo(90,1,n,r),c=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,m=u.autoClear,p=u.toneMapping;u.getClearColor(qq),u.toneMapping=Yh,u.autoClear=!1;const f=new aJ({name:"PMREM.Background",side:jo,depthWrite:!1,depthTest:!1}),x=new Lc(new Gw,f);let v=!1;const g=e.background;g?g.isColor&&(f.color.copy(g),e.background=null,v=!0):(f.color.copy(qq),v=!0);for(let b=0;b<6;b++){const _=b%3;_===0?(l.up.set(0,c[b],0),l.lookAt(d[b],0,0)):_===1?(l.up.set(0,0,c[b]),l.lookAt(0,d[b],0)):(l.up.set(0,c[b],0),l.lookAt(0,0,d[b]));const C=this._cubeSize;C1(i,_*C,b>2?C:0,C,C),u.setRenderTarget(i),v&&u.render(x,l),u.render(e,l)}x.geometry.dispose(),x.material.dispose(),u.toneMapping=p,u.autoClear=m,e.background=g}_textureToCubeUV(e,n){const r=this._renderer,i=e.mapping===Rx||e.mapping===Lx;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=Kq()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Wq());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new Lc(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;C1(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,SE)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;for(let i=1;i<this._lodPlanes.length;i++){const s=Math.sqrt(this._sigmas[i]*this._sigmas[i]-this._sigmas[i-1]*this._sigmas[i-1]),o=$q[(i-1)%$q.length];this._blur(e,i-1,i,s,o)}n.autoClear=r}_blur(e,n,r,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,i,"latitudinal",s),this._halfBlur(o,e,r,r,i,"longitudinal",s)}_halfBlur(e,n,r,i,s,o,l){const c=this._renderer,d=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const u=3,m=new Lc(this._lodPlanes[i],d),p=d.uniforms,f=this._sizeLods[r]-1,x=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*ff-1),v=s/x,g=isFinite(s)?1+Math.floor(u*v):ff;g>ff&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${ff}`);const b=[];let _=0;for(let T=0;T<ff;++T){const F=T/v,k=Math.exp(-F*F/2);b.push(k),T===0?_+=k:T<g&&(_+=2*k)}for(let T=0;T<b.length;T++)b[T]=b[T]/_;p.envMap.value=e.texture,p.samples.value=g,p.weights.value=b,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:C}=this;p.dTheta.value=x,p.mipInt.value=C-r;const P=this._sizeLods[i],N=3*P*(i>C-ix?i-C+ix:0),A=4*(this._cubeSize-P);C1(n,N,A,3*P,2*P),c.setRenderTarget(n),c.render(m,SE)}}function JTe(t){const e=[],n=[],r=[];let i=t;const s=t-ix+1+Hq.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);n.push(l);let c=1/l;o>t-ix?c=Hq[o-t+ix-1]:o===0&&(c=0),r.push(c);const d=1/(l-2),u=-d,m=1+d,p=[u,u,m,u,m,m,u,u,m,m,u,m],f=6,x=6,v=3,g=2,b=1,_=new Float32Array(v*x*f),C=new Float32Array(g*x*f),P=new Float32Array(b*x*f);for(let A=0;A<f;A++){const T=A%3*2/3-1,F=A>2?0:-1,k=[T,F,0,T+2/3,F,0,T+2/3,F+1,0,T,F,0,T+2/3,F+1,0,T,F+1,0];_.set(k,v*x*A),C.set(p,g*x*A);const D=[A,A,A,A,A,A];P.set(D,b*x*A)}const N=new Ls;N.setAttribute("position",new ol(_,v)),N.setAttribute("uv",new ol(C,g)),N.setAttribute("faceIndex",new ol(P,b)),e.push(N),i>ix&&i--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function Gq(t,e,n){const r=new ng(t,e,n);return r.texture.mapping=UP,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function C1(t,e,n,r,i){t.viewport.set(e,n,r,i),t.scissor.set(e,n,r,i)}function eAe(t,e,n){const r=new Float32Array(ff),i=new ct(0,1,0);return new lp({name:"SphericalGaussianBlur",defines:{n:ff,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:i}},vertexShader:tI(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- varying vec3 vOutputDirection;
- uniform sampler2D envMap;
- uniform int samples;
- uniform float weights[ n ];
- uniform bool latitudinal;
- uniform float dTheta;
- uniform float mipInt;
- uniform vec3 poleAxis;
- #define ENVMAP_TYPE_CUBE_UV
- #include <cube_uv_reflection_fragment>
- vec3 getSample( float theta, vec3 axis ) {
- float cosTheta = cos( theta );
- // Rodrigues' axis-angle rotation
- vec3 sampleDirection = vOutputDirection * cosTheta
- + cross( axis, vOutputDirection ) * sin( theta )
- + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
- return bilinearCubeUV( envMap, sampleDirection, mipInt );
- }
- void main() {
- vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
- if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
- axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
- }
- axis = normalize( axis );
- gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
- gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
- for ( int i = 1; i < n; i++ ) {
- if ( i >= samples ) {
- break;
- }
- float theta = dTheta * float( i );
- gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
- gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
- }
- }
- `,blending:Xh,depthTest:!1,depthWrite:!1})}function Wq(){return new lp({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:tI(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- varying vec3 vOutputDirection;
- uniform sampler2D envMap;
- #include <common>
- void main() {
- vec3 outputDirection = normalize( vOutputDirection );
- vec2 uv = equirectUv( outputDirection );
- gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
- }
- `,blending:Xh,depthTest:!1,depthWrite:!1})}function Kq(){return new lp({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:tI(),fragmentShader:`
- precision mediump float;
- precision mediump int;
- uniform float flipEnvMap;
- varying vec3 vOutputDirection;
- uniform samplerCube envMap;
- void main() {
- gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
- }
- `,blending:Xh,depthTest:!1,depthWrite:!1})}function tI(){return`
- precision mediump float;
- precision mediump int;
- attribute float faceIndex;
- varying vec3 vOutputDirection;
- // RH coordinate system; PMREM face-indexing convention
- vec3 getDirection( vec2 uv, float face ) {
- uv = 2.0 * uv - 1.0;
- vec3 direction = vec3( uv, 1.0 );
- if ( face == 0.0 ) {
- direction = direction.zyx; // ( 1, v, u ) pos x
- } else if ( face == 1.0 ) {
- direction = direction.xzy;
- direction.xz *= -1.0; // ( -u, 1, -v ) pos y
- } else if ( face == 2.0 ) {
- direction.x *= -1.0; // ( -u, v, 1 ) pos z
- } else if ( face == 3.0 ) {
- direction = direction.zyx;
- direction.xz *= -1.0; // ( -1, v, -u ) neg x
- } else if ( face == 4.0 ) {
- direction = direction.xzy;
- direction.xy *= -1.0; // ( -u, -1, v ) neg y
- } else if ( face == 5.0 ) {
- direction.z *= -1.0; // ( u, v, -1 ) neg z
- }
- return direction;
- }
- void main() {
- vOutputDirection = getDirection( uv, faceIndex );
- gl_Position = vec4( position, 1.0 );
- }
- `}function tAe(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,d=c===XF||c===YF,u=c===Rx||c===Lx;if(d||u)if(l.isRenderTargetTexture&&l.needsPMREMUpdate===!0){l.needsPMREMUpdate=!1;let m=e.get(l);return n===null&&(n=new Vq(t)),m=d?n.fromEquirectangular(l,m):n.fromCubemap(l,m),e.set(l,m),m.texture}else{if(e.has(l))return e.get(l).texture;{const m=l.image;if(d&&m&&m.height>0||u&&m&&i(m)){n===null&&(n=new Vq(t));const p=d?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,p),l.addEventListener("dispose",s),p.texture}else return null}}}return l}function i(l){let c=0;const d=6;for(let u=0;u<d;u++)l[u]!==void 0&&c++;return c===d}function s(l){const c=l.target;c.removeEventListener("dispose",s);const d=e.get(c);d!==void 0&&(e.delete(c),d.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function nAe(t){const e={};function n(r){if(e[r]!==void 0)return e[r];let i;switch(r){case"WEBGL_depth_texture":i=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=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":i=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":i=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=t.getExtension(r)}return e[r]=i,i}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 i=n(r);return i===null&&console.warn("THREE.WebGLRenderer: "+r+" extension not supported."),i}}}function rAe(t,e,n,r){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const x in p.attributes)e.remove(p.attributes[x]);for(const x in p.morphAttributes){const v=p.morphAttributes[x];for(let g=0,b=v.length;g<b;g++)e.remove(v[g])}p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),r.releaseStatesOfGeometry(p),p.isInstancedBufferGeometry===!0&&delete p._maxInstanceCount,n.memory.geometries--}function l(m,p){return i[p.id]===!0||(p.addEventListener("dispose",o),i[p.id]=!0,n.memory.geometries++),p}function c(m){const p=m.attributes;for(const x in p)e.update(p[x],t.ARRAY_BUFFER);const f=m.morphAttributes;for(const x in f){const v=f[x];for(let g=0,b=v.length;g<b;g++)e.update(v[g],t.ARRAY_BUFFER)}}function d(m){const p=[],f=m.index,x=m.attributes.position;let v=0;if(f!==null){const _=f.array;v=f.version;for(let C=0,P=_.length;C<P;C+=3){const N=_[C+0],A=_[C+1],T=_[C+2];p.push(N,A,A,T,T,N)}}else if(x!==void 0){const _=x.array;v=x.version;for(let C=0,P=_.length/3-1;C<P;C+=3){const N=C+0,A=C+1,T=C+2;p.push(N,A,A,T,T,N)}}else return;const g=new(ZZ(p)?sJ:iJ)(p,1);g.version=v;const b=s.get(m);b&&e.remove(b),s.set(m,g)}function u(m){const p=s.get(m);if(p){const f=m.index;f!==null&&p.version<f.version&&d(m)}else d(m);return s.get(m)}return{get:l,update:c,getWireframeAttribute:u}}function aAe(t,e,n,r){const i=r.isWebGL2;let s;function o(f){s=f}let l,c;function d(f){l=f.type,c=f.bytesPerElement}function u(f,x){t.drawElements(s,x,l,f*c),n.update(x,s,1)}function m(f,x,v){if(v===0)return;let g,b;if(i)g=t,b="drawElementsInstanced";else if(g=e.get("ANGLE_instanced_arrays"),b="drawElementsInstancedANGLE",g===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}g[b](s,x,l,f*c,v),n.update(x,s,v)}function p(f,x,v){if(v===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let b=0;b<v;b++)this.render(f[b]/c,x[b]);else{g.multiDrawElementsWEBGL(s,x,0,l,f,0,v);let b=0;for(let _=0;_<v;_++)b+=x[_];n.update(b,s,1)}}this.setMode=o,this.setIndex=d,this.render=u,this.renderInstances=m,this.renderMultiDraw=p}function iAe(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 i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:i,update:r}}function sAe(t,e){return t[0]-e[0]}function oAe(t,e){return Math.abs(e[1])-Math.abs(t[1])}function lAe(t,e,n){const r={},i=new Float32Array(8),s=new WeakMap,o=new Xr,l=[];for(let d=0;d<8;d++)l[d]=[d,0];function c(d,u,m){const p=d.morphTargetInfluences;if(e.isWebGL2===!0){const x=u.morphAttributes.position||u.morphAttributes.normal||u.morphAttributes.color,v=x!==void 0?x.length:0;let g=s.get(u);if(g===void 0||g.count!==v){let ne=function(){X.dispose(),s.delete(u),u.removeEventListener("dispose",ne)};var f=ne;g!==void 0&&g.texture.dispose();const C=u.morphAttributes.position!==void 0,P=u.morphAttributes.normal!==void 0,N=u.morphAttributes.color!==void 0,A=u.morphAttributes.position||[],T=u.morphAttributes.normal||[],F=u.morphAttributes.color||[];let k=0;C===!0&&(k=1),P===!0&&(k=2),N===!0&&(k=3);let D=u.attributes.position.count*k,H=1;D>e.maxTextureSize&&(H=Math.ceil(D/e.maxTextureSize),D=e.maxTextureSize);const z=new Float32Array(D*H*4*v),X=new tJ(z,D,H,v);X.type=qu,X.needsUpdate=!0;const L=k*4;for(let ie=0;ie<v;ie++){const ee=A[ie],ue=T[ie],le=F[ie],oe=D*H*4*ie;for(let W=0;W<ee.count;W++){const re=W*L;C===!0&&(o.fromBufferAttribute(ee,W),z[oe+re+0]=o.x,z[oe+re+1]=o.y,z[oe+re+2]=o.z,z[oe+re+3]=0),P===!0&&(o.fromBufferAttribute(ue,W),z[oe+re+4]=o.x,z[oe+re+5]=o.y,z[oe+re+6]=o.z,z[oe+re+7]=0),N===!0&&(o.fromBufferAttribute(le,W),z[oe+re+8]=o.x,z[oe+re+9]=o.y,z[oe+re+10]=o.z,z[oe+re+11]=le.itemSize===4?o.w:1)}}g={count:v,texture:X,size:new Gn(D,H)},s.set(u,g),u.addEventListener("dispose",ne)}let b=0;for(let C=0;C<p.length;C++)b+=p[C];const _=u.morphTargetsRelative?1:1-b;m.getUniforms().setValue(t,"morphTargetBaseInfluence",_),m.getUniforms().setValue(t,"morphTargetInfluences",p),m.getUniforms().setValue(t,"morphTargetsTexture",g.texture,n),m.getUniforms().setValue(t,"morphTargetsTextureSize",g.size)}else{const x=p===void 0?0:p.length;let v=r[u.id];if(v===void 0||v.length!==x){v=[];for(let P=0;P<x;P++)v[P]=[P,0];r[u.id]=v}for(let P=0;P<x;P++){const N=v[P];N[0]=P,N[1]=p[P]}v.sort(oAe);for(let P=0;P<8;P++)P<x&&v[P][1]?(l[P][0]=v[P][0],l[P][1]=v[P][1]):(l[P][0]=Number.MAX_SAFE_INTEGER,l[P][1]=0);l.sort(sAe);const g=u.morphAttributes.position,b=u.morphAttributes.normal;let _=0;for(let P=0;P<8;P++){const N=l[P],A=N[0],T=N[1];A!==Number.MAX_SAFE_INTEGER&&T?(g&&u.getAttribute("morphTarget"+P)!==g[A]&&u.setAttribute("morphTarget"+P,g[A]),b&&u.getAttribute("morphNormal"+P)!==b[A]&&u.setAttribute("morphNormal"+P,b[A]),i[P]=T,_+=T):(g&&u.hasAttribute("morphTarget"+P)===!0&&u.deleteAttribute("morphTarget"+P),b&&u.hasAttribute("morphNormal"+P)===!0&&u.deleteAttribute("morphNormal"+P),i[P]=0)}const C=u.morphTargetsRelative?1:1-_;m.getUniforms().setValue(t,"morphTargetBaseInfluence",C),m.getUniforms().setValue(t,"morphTargetInfluences",i)}}return{update:c}}function cAe(t,e,n,r){let i=new WeakMap;function s(c){const d=r.render.frame,u=c.geometry,m=e.get(c,u);if(i.get(m)!==d&&(e.update(m),i.set(m,d)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),i.get(c)!==d&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),i.set(c,d))),c.isSkinnedMesh){const p=c.skeleton;i.get(p)!==d&&(p.update(),i.set(p,d))}return m}function o(){i=new WeakMap}function l(c){const d=c.target;d.removeEventListener("dispose",l),n.remove(d.instanceMatrix),d.instanceColor!==null&&n.remove(d.instanceColor)}return{update:s,dispose:o}}class uJ extends Mo{constructor(e,n,r,i,s,o,l,c,d,u){if(u=u!==void 0?u:Df,u!==Df&&u!==Ox)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&u===Df&&(r=Mh),r===void 0&&u===Ox&&(r=Ef),super(null,i,s,o,l,c,u,r,d),this.isDepthTexture=!0,this.image={width:e,height:n},this.magFilter=l!==void 0?l:cs,this.minFilter=c!==void 0?c:cs,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 mJ=new Mo,hJ=new uJ(1,1);hJ.compareFunction=YZ;const pJ=new tJ,fJ=new WNe,gJ=new cJ,Xq=[],Yq=[],Qq=new Float32Array(16),Zq=new Float32Array(9),Jq=new Float32Array(4);function hy(t,e,n){const r=t[0];if(r<=0||r>0)return t;const i=e*n;let s=Xq[i];if(s===void 0&&(s=new Float32Array(i),Xq[i]=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 Ci(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 Pi(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function qP(t,e){let n=Yq[e];n===void 0&&(n=new Int32Array(e),Yq[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function dAe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function uAe(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(Ci(n,e))return;t.uniform2fv(this.addr,e),Pi(n,e)}}function mAe(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(Ci(n,e))return;t.uniform3fv(this.addr,e),Pi(n,e)}}function hAe(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(Ci(n,e))return;t.uniform4fv(this.addr,e),Pi(n,e)}}function pAe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(Ci(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),Pi(n,e)}else{if(Ci(n,r))return;Jq.set(r),t.uniformMatrix2fv(this.addr,!1,Jq),Pi(n,r)}}function fAe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(Ci(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),Pi(n,e)}else{if(Ci(n,r))return;Zq.set(r),t.uniformMatrix3fv(this.addr,!1,Zq),Pi(n,r)}}function gAe(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(Ci(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),Pi(n,e)}else{if(Ci(n,r))return;Qq.set(r),t.uniformMatrix4fv(this.addr,!1,Qq),Pi(n,r)}}function bAe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function xAe(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(Ci(n,e))return;t.uniform2iv(this.addr,e),Pi(n,e)}}function yAe(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(Ci(n,e))return;t.uniform3iv(this.addr,e),Pi(n,e)}}function vAe(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(Ci(n,e))return;t.uniform4iv(this.addr,e),Pi(n,e)}}function wAe(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function SAe(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(Ci(n,e))return;t.uniform2uiv(this.addr,e),Pi(n,e)}}function _Ae(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(Ci(n,e))return;t.uniform3uiv(this.addr,e),Pi(n,e)}}function kAe(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(Ci(n,e))return;t.uniform4uiv(this.addr,e),Pi(n,e)}}function NAe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i);const s=this.type===t.SAMPLER_2D_SHADOW?hJ:mJ;n.setTexture2D(e||s,i)}function CAe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(e||fJ,i)}function PAe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(e||gJ,i)}function TAe(t,e,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(t.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(e||pJ,i)}function AAe(t){switch(t){case 5126:return dAe;case 35664:return uAe;case 35665:return mAe;case 35666:return hAe;case 35674:return pAe;case 35675:return fAe;case 35676:return gAe;case 5124:case 35670:return bAe;case 35667:case 35671:return xAe;case 35668:case 35672:return yAe;case 35669:case 35673:return vAe;case 5125:return wAe;case 36294:return SAe;case 36295:return _Ae;case 36296:return kAe;case 35678:case 36198:case 36298:case 36306:case 35682:return NAe;case 35679:case 36299:case 36307:return CAe;case 35680:case 36300:case 36308:case 36293:return PAe;case 36289:case 36303:case 36311:case 36292:return TAe}}function jAe(t,e){t.uniform1fv(this.addr,e)}function MAe(t,e){const n=hy(e,this.size,2);t.uniform2fv(this.addr,n)}function EAe(t,e){const n=hy(e,this.size,3);t.uniform3fv(this.addr,n)}function DAe(t,e){const n=hy(e,this.size,4);t.uniform4fv(this.addr,n)}function FAe(t,e){const n=hy(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function RAe(t,e){const n=hy(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function LAe(t,e){const n=hy(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function OAe(t,e){t.uniform1iv(this.addr,e)}function IAe(t,e){t.uniform2iv(this.addr,e)}function zAe(t,e){t.uniform3iv(this.addr,e)}function UAe(t,e){t.uniform4iv(this.addr,e)}function BAe(t,e){t.uniform1uiv(this.addr,e)}function HAe(t,e){t.uniform2uiv(this.addr,e)}function qAe(t,e){t.uniform3uiv(this.addr,e)}function $Ae(t,e){t.uniform4uiv(this.addr,e)}function VAe(t,e,n){const r=this.cache,i=e.length,s=qP(n,i);Ci(r,s)||(t.uniform1iv(this.addr,s),Pi(r,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||mJ,s[o])}function GAe(t,e,n){const r=this.cache,i=e.length,s=qP(n,i);Ci(r,s)||(t.uniform1iv(this.addr,s),Pi(r,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||fJ,s[o])}function WAe(t,e,n){const r=this.cache,i=e.length,s=qP(n,i);Ci(r,s)||(t.uniform1iv(this.addr,s),Pi(r,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||gJ,s[o])}function KAe(t,e,n){const r=this.cache,i=e.length,s=qP(n,i);Ci(r,s)||(t.uniform1iv(this.addr,s),Pi(r,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||pJ,s[o])}function XAe(t){switch(t){case 5126:return jAe;case 35664:return MAe;case 35665:return EAe;case 35666:return DAe;case 35674:return FAe;case 35675:return RAe;case 35676:return LAe;case 5124:case 35670:return OAe;case 35667:case 35671:return IAe;case 35668:case 35672:return zAe;case 35669:case 35673:return UAe;case 5125:return BAe;case 36294:return HAe;case 36295:return qAe;case 36296:return $Ae;case 35678:case 36198:case 36298:case 36306:case 35682:return VAe;case 35679:case 36299:case 36307:return GAe;case 35680:case 36300:case 36308:case 36293:return WAe;case 36289:case 36303:case 36311:case 36292:return KAe}}class YAe{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=AAe(n.type)}}class QAe{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=XAe(n.type)}}class ZAe{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],r)}}}const CE=/(\w+)(\])?(\[|\.)?/g;function e$(t,e){t.seq.push(e),t.map[e.id]=e}function JAe(t,e,n){const r=t.name,i=r.length;for(CE.lastIndex=0;;){const s=CE.exec(r),o=CE.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){e$(n,d===void 0?new YAe(l,t,e):new QAe(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new ZAe(l),e$(n,m)),n=m}}}class Dk{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<r;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);JAe(s,o,this)}}setValue(e,n,r,i){const s=this.map[n];s!==void 0&&s.setValue(e,r,i)}setOptional(e,n,r){const i=n[r];i!==void 0&&this.setValue(e,r,i)}static upload(e,n,r,i){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,i)}}static seqWithValue(e,n){const r=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&r.push(o)}return r}}function t$(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const eje=37297;let tje=0;function nje(t,e){const n=t.split(`
- `),r=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
- `)}function rje(t){const e=Wr.getPrimaries(Wr.workingColorSpace),n=Wr.getPrimaries(t);let r;switch(e===n?r="":e===SN&&n===wN?r="LinearDisplayP3ToLinearSRGB":e===wN&&n===SN&&(r="LinearSRGBToLinearDisplayP3"),t){case cm:case BP:return[r,"LinearTransferOETF"];case ds:case YO:return[r,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[r,"LinearTransferOETF"]}}function n$(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),i=t.getShaderInfoLog(e).trim();if(r&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return n.toUpperCase()+`
- `+i+`
- `+nje(t.getShaderSource(e),o)}else return i}function aje(t,e){const n=rje(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function ije(t,e){let n;switch(e){case aNe:n="Linear";break;case iNe:n="Reinhard";break;case sNe:n="OptimizedCineon";break;case oNe:n="ACESFilmic";break;case lNe:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function sje(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(Yv).join(`
- `)}function oje(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
- `)}function lje(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){const s=t.getActiveAttrib(e,i),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 Yv(t){return t!==""}function r$(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 a$(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const cje=/^[ \t]*#include +<([\w\d./]+)>/gm;function nR(t){return t.replace(cje,uje)}const dje=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function uje(t,e){let n=rr[e];if(n===void 0){const r=dje.get(e);if(r!==void 0)n=rr[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 nR(n)}const mje=/#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 i$(t){return t.replace(mje,hje)}function hje(t,e,n,r){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function s$(t){let e="precision "+t.precision+` float;
- precision `+t.precision+" int;";return t.precision==="highp"?e+=`
- #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
- #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
- #define LOW_PRECISION`),e}function pje(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===zZ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===Eke?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===Pu&&(e="SHADOWMAP_TYPE_VSM"),e}function fje(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case Rx:case Lx:e="ENVMAP_TYPE_CUBE";break;case UP:e="ENVMAP_TYPE_CUBE_UV";break}return e}function gje(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===Lx&&(e="ENVMAP_MODE_REFRACTION"),e}function bje(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case KO:e="ENVMAP_BLENDING_MULTIPLY";break;case nNe:e="ENVMAP_BLENDING_MIX";break;case rNe:e="ENVMAP_BLENDING_ADD";break}return e}function xje(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 yje(t,e,n,r){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=pje(n),d=fje(n),u=gje(n),m=bje(n),p=xje(n),f=n.isWebGL2?"":sje(n),x=oje(s),v=i.createProgram();let g,b,_=n.glslVersion?"#version "+n.glslVersion+`
- `:"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Yv).join(`
- `),g.length>0&&(g+=`
- `),b=[f,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Yv).join(`
- `),b.length>0&&(b+=`
- `)):(g=[s$(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 "+u:"",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",`
- `].filter(Yv).join(`
- `),b=[f,s$(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 "+d:"",n.envMap?"#define "+u:"",n.envMap?"#define "+m:"",p?"#define CUBEUV_TEXEL_WIDTH "+p.texelWidth:"",p?"#define CUBEUV_TEXEL_HEIGHT "+p.texelHeight:"",p?"#define CUBEUV_MAX_MIP "+p.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!==Yh?"#define TONE_MAPPING":"",n.toneMapping!==Yh?rr.tonemapping_pars_fragment:"",n.toneMapping!==Yh?ije("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",rr.colorspace_pars_fragment,aje("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
- `].filter(Yv).join(`
- `)),o=nR(o),o=r$(o,n),o=a$(o,n),l=nR(l),l=r$(l,n),l=a$(l,n),o=i$(o),l=i$(l),n.isWebGL2&&n.isRawShaderMaterial!==!0&&(_=`#version 300 es
- `,g=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(`
- `)+`
- `+g,b=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===kq?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===kq?"":"#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(`
- `)+`
- `+b);const C=_+g+o,P=_+b+l,N=t$(i,i.VERTEX_SHADER,C),A=t$(i,i.FRAGMENT_SHADER,P);i.attachShader(v,N),i.attachShader(v,A),n.index0AttributeName!==void 0?i.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(v,0,"position"),i.linkProgram(v);function T(H){if(t.debug.checkShaderErrors){const z=i.getProgramInfoLog(v).trim(),X=i.getShaderInfoLog(N).trim(),L=i.getShaderInfoLog(A).trim();let ne=!0,ie=!0;if(i.getProgramParameter(v,i.LINK_STATUS)===!1)if(ne=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,v,N,A);else{const ee=n$(i,N,"vertex"),ue=n$(i,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(v,i.VALIDATE_STATUS)+`
- Program Info Log: `+z+`
- `+ee+`
- `+ue)}else z!==""?console.warn("THREE.WebGLProgram: Program Info Log:",z):(X===""||L==="")&&(ie=!1);ie&&(H.diagnostics={runnable:ne,programLog:z,vertexShader:{log:X,prefix:g},fragmentShader:{log:L,prefix:b}})}i.deleteShader(N),i.deleteShader(A),F=new Dk(i,v),k=lje(i,v)}let F;this.getUniforms=function(){return F===void 0&&T(this),F};let k;this.getAttributes=function(){return k===void 0&&T(this),k};let D=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return D===!1&&(D=i.getProgramParameter(v,eje)),D},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=tje++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=N,this.fragmentShader=A,this}let vje=0;class wje{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.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 Sje(e),n.set(e,r)),r}}class Sje{constructor(e){this.id=vje++,this.code=e,this.usedTimes=0}}function _je(t,e,n,r,i,s,o){const l=new nJ,c=new wje,d=[],u=i.isWebGL2,m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.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(k){return k===0?"uv":`uv${k}`}function g(k,D,H,z,X){const L=z.fog,ne=X.geometry,ie=k.isMeshStandardMaterial?z.environment:null,ee=(k.isMeshStandardMaterial?n:e).get(k.envMap||ie),ue=ee&&ee.mapping===UP?ee.image.height:null,le=x[k.type];k.precision!==null&&(f=i.getMaxPrecision(k.precision),f!==k.precision&&console.warn("THREE.WebGLProgram.getParameters:",k.precision,"not supported, using",f,"instead."));const oe=ne.morphAttributes.position||ne.morphAttributes.normal||ne.morphAttributes.color,W=oe!==void 0?oe.length:0;let re=0;ne.morphAttributes.position!==void 0&&(re=1),ne.morphAttributes.normal!==void 0&&(re=2),ne.morphAttributes.color!==void 0&&(re=3);let ce,xe,Ne,$;if(le){const vt=ko[le];ce=vt.vertexShader,xe=vt.fragmentShader}else ce=k.vertexShader,xe=k.fragmentShader,c.update(k),Ne=c.getVertexShaderID(k),$=c.getFragmentShaderID(k);const Y=t.getRenderTarget(),E=X.isInstancedMesh===!0,j=X.isBatchedMesh===!0,O=!!k.map,K=!!k.matcap,B=!!ee,he=!!k.aoMap,I=!!k.lightMap,V=!!k.bumpMap,Q=!!k.normalMap,G=!!k.displacementMap,J=!!k.emissiveMap,se=!!k.metalnessMap,fe=!!k.roughnessMap,pe=k.anisotropy>0,de=k.clearcoat>0,U=k.iridescence>0,R=k.sheen>0,ae=k.transmission>0,_e=pe&&!!k.anisotropyMap,Se=de&&!!k.clearcoatMap,ye=de&&!!k.clearcoatNormalMap,Ae=de&&!!k.clearcoatRoughnessMap,ve=U&&!!k.iridescenceMap,je=U&&!!k.iridescenceThicknessMap,Re=R&&!!k.sheenColorMap,Ee=R&&!!k.sheenRoughnessMap,Te=!!k.specularMap,Me=!!k.specularColorMap,Be=!!k.specularIntensityMap,Ke=ae&&!!k.transmissionMap,tt=ae&&!!k.thicknessMap,te=!!k.gradientMap,Ie=!!k.alphaMap,be=k.alphaTest>0,$e=!!k.alphaHash,He=!!k.extensions,ge=!!ne.attributes.uv1,Pe=!!ne.attributes.uv2,qe=!!ne.attributes.uv3;let Ze=Yh;return k.toneMapped&&(Y===null||Y.isXRRenderTarget===!0)&&(Ze=t.toneMapping),{isWebGL2:u,shaderID:le,shaderType:k.type,shaderName:k.name,vertexShader:ce,fragmentShader:xe,defines:k.defines,customVertexShaderID:Ne,customFragmentShaderID:$,isRawShaderMaterial:k.isRawShaderMaterial===!0,glslVersion:k.glslVersion,precision:f,batching:j,instancing:E,instancingColor:E&&X.instanceColor!==null,supportsVertexTextures:p,outputColorSpace:Y===null?t.outputColorSpace:Y.isXRRenderTarget===!0?Y.texture.colorSpace:cm,map:O,matcap:K,envMap:B,envMapMode:B&&ee.mapping,envMapCubeUVHeight:ue,aoMap:he,lightMap:I,bumpMap:V,normalMap:Q,displacementMap:p&&G,emissiveMap:J,normalMapObjectSpace:Q&&k.normalMapType===vNe,normalMapTangentSpace:Q&&k.normalMapType===XZ,metalnessMap:se,roughnessMap:fe,anisotropy:pe,anisotropyMap:_e,clearcoat:de,clearcoatMap:Se,clearcoatNormalMap:ye,clearcoatRoughnessMap:Ae,iridescence:U,iridescenceMap:ve,iridescenceThicknessMap:je,sheen:R,sheenColorMap:Re,sheenRoughnessMap:Ee,specularMap:Te,specularColorMap:Me,specularIntensityMap:Be,transmission:ae,transmissionMap:Ke,thicknessMap:tt,gradientMap:te,opaque:k.transparent===!1&&k.blending===fx,alphaMap:Ie,alphaTest:be,alphaHash:$e,combine:k.combine,mapUv:O&&v(k.map.channel),aoMapUv:he&&v(k.aoMap.channel),lightMapUv:I&&v(k.lightMap.channel),bumpMapUv:V&&v(k.bumpMap.channel),normalMapUv:Q&&v(k.normalMap.channel),displacementMapUv:G&&v(k.displacementMap.channel),emissiveMapUv:J&&v(k.emissiveMap.channel),metalnessMapUv:se&&v(k.metalnessMap.channel),roughnessMapUv:fe&&v(k.roughnessMap.channel),anisotropyMapUv:_e&&v(k.anisotropyMap.channel),clearcoatMapUv:Se&&v(k.clearcoatMap.channel),clearcoatNormalMapUv:ye&&v(k.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(k.clearcoatRoughnessMap.channel),iridescenceMapUv:ve&&v(k.iridescenceMap.channel),iridescenceThicknessMapUv:je&&v(k.iridescenceThicknessMap.channel),sheenColorMapUv:Re&&v(k.sheenColorMap.channel),sheenRoughnessMapUv:Ee&&v(k.sheenRoughnessMap.channel),specularMapUv:Te&&v(k.specularMap.channel),specularColorMapUv:Me&&v(k.specularColorMap.channel),specularIntensityMapUv:Be&&v(k.specularIntensityMap.channel),transmissionMapUv:Ke&&v(k.transmissionMap.channel),thicknessMapUv:tt&&v(k.thicknessMap.channel),alphaMapUv:Ie&&v(k.alphaMap.channel),vertexTangents:!!ne.attributes.tangent&&(Q||pe),vertexColors:k.vertexColors,vertexAlphas:k.vertexColors===!0&&!!ne.attributes.color&&ne.attributes.color.itemSize===4,vertexUv1s:ge,vertexUv2s:Pe,vertexUv3s:qe,pointsUvs:X.isPoints===!0&&!!ne.attributes.uv&&(O||Ie),fog:!!L,useFog:k.fog===!0,fogExp2:L&&L.isFogExp2,flatShading:k.flatShading===!0,sizeAttenuation:k.sizeAttenuation===!0,logarithmicDepthBuffer:m,skinning:X.isSkinnedMesh===!0,morphTargets:ne.morphAttributes.position!==void 0,morphNormals:ne.morphAttributes.normal!==void 0,morphColors:ne.morphAttributes.color!==void 0,morphTargetsCount:W,morphTextureStride:re,numDirLights:D.directional.length,numPointLights:D.point.length,numSpotLights:D.spot.length,numSpotLightMaps:D.spotLightMap.length,numRectAreaLights:D.rectArea.length,numHemiLights:D.hemi.length,numDirLightShadows:D.directionalShadowMap.length,numPointLightShadows:D.pointShadowMap.length,numSpotLightShadows:D.spotShadowMap.length,numSpotLightShadowsWithMaps:D.numSpotLightShadowsWithMaps,numLightProbes:D.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:k.dithering,shadowMapEnabled:t.shadowMap.enabled&&H.length>0,shadowMapType:t.shadowMap.type,toneMapping:Ze,useLegacyLights:t._useLegacyLights,decodeVideoTexture:O&&k.map.isVideoTexture===!0&&Wr.getTransfer(k.map.colorSpace)===ga,premultipliedAlpha:k.premultipliedAlpha,doubleSided:k.side===Ru,flipSided:k.side===jo,useDepthPacking:k.depthPacking>=0,depthPacking:k.depthPacking||0,index0AttributeName:k.index0AttributeName,extensionDerivatives:He&&k.extensions.derivatives===!0,extensionFragDepth:He&&k.extensions.fragDepth===!0,extensionDrawBuffers:He&&k.extensions.drawBuffers===!0,extensionShaderTextureLOD:He&&k.extensions.shaderTextureLOD===!0,rendererExtensionFragDepth:u||r.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||r.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||r.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:k.customProgramCacheKey()}}function b(k){const D=[];if(k.shaderID?D.push(k.shaderID):(D.push(k.customVertexShaderID),D.push(k.customFragmentShaderID)),k.defines!==void 0)for(const H in k.defines)D.push(H),D.push(k.defines[H]);return k.isRawShaderMaterial===!1&&(_(D,k),C(D,k),D.push(t.outputColorSpace)),D.push(k.customProgramCacheKey),D.join()}function _(k,D){k.push(D.precision),k.push(D.outputColorSpace),k.push(D.envMapMode),k.push(D.envMapCubeUVHeight),k.push(D.mapUv),k.push(D.alphaMapUv),k.push(D.lightMapUv),k.push(D.aoMapUv),k.push(D.bumpMapUv),k.push(D.normalMapUv),k.push(D.displacementMapUv),k.push(D.emissiveMapUv),k.push(D.metalnessMapUv),k.push(D.roughnessMapUv),k.push(D.anisotropyMapUv),k.push(D.clearcoatMapUv),k.push(D.clearcoatNormalMapUv),k.push(D.clearcoatRoughnessMapUv),k.push(D.iridescenceMapUv),k.push(D.iridescenceThicknessMapUv),k.push(D.sheenColorMapUv),k.push(D.sheenRoughnessMapUv),k.push(D.specularMapUv),k.push(D.specularColorMapUv),k.push(D.specularIntensityMapUv),k.push(D.transmissionMapUv),k.push(D.thicknessMapUv),k.push(D.combine),k.push(D.fogExp2),k.push(D.sizeAttenuation),k.push(D.morphTargetsCount),k.push(D.morphAttributeCount),k.push(D.numDirLights),k.push(D.numPointLights),k.push(D.numSpotLights),k.push(D.numSpotLightMaps),k.push(D.numHemiLights),k.push(D.numRectAreaLights),k.push(D.numDirLightShadows),k.push(D.numPointLightShadows),k.push(D.numSpotLightShadows),k.push(D.numSpotLightShadowsWithMaps),k.push(D.numLightProbes),k.push(D.shadowMapType),k.push(D.toneMapping),k.push(D.numClippingPlanes),k.push(D.numClipIntersection),k.push(D.depthPacking)}function C(k,D){l.disableAll(),D.isWebGL2&&l.enable(0),D.supportsVertexTextures&&l.enable(1),D.instancing&&l.enable(2),D.instancingColor&&l.enable(3),D.matcap&&l.enable(4),D.envMap&&l.enable(5),D.normalMapObjectSpace&&l.enable(6),D.normalMapTangentSpace&&l.enable(7),D.clearcoat&&l.enable(8),D.iridescence&&l.enable(9),D.alphaTest&&l.enable(10),D.vertexColors&&l.enable(11),D.vertexAlphas&&l.enable(12),D.vertexUv1s&&l.enable(13),D.vertexUv2s&&l.enable(14),D.vertexUv3s&&l.enable(15),D.vertexTangents&&l.enable(16),D.anisotropy&&l.enable(17),D.alphaHash&&l.enable(18),D.batching&&l.enable(19),k.push(l.mask),l.disableAll(),D.fog&&l.enable(0),D.useFog&&l.enable(1),D.flatShading&&l.enable(2),D.logarithmicDepthBuffer&&l.enable(3),D.skinning&&l.enable(4),D.morphTargets&&l.enable(5),D.morphNormals&&l.enable(6),D.morphColors&&l.enable(7),D.premultipliedAlpha&&l.enable(8),D.shadowMapEnabled&&l.enable(9),D.useLegacyLights&&l.enable(10),D.doubleSided&&l.enable(11),D.flipSided&&l.enable(12),D.useDepthPacking&&l.enable(13),D.dithering&&l.enable(14),D.transmission&&l.enable(15),D.sheen&&l.enable(16),D.opaque&&l.enable(17),D.pointsUvs&&l.enable(18),D.decodeVideoTexture&&l.enable(19),k.push(l.mask)}function P(k){const D=x[k.type];let H;if(D){const z=ko[D];H=JO.clone(z.uniforms)}else H=k.uniforms;return H}function N(k,D){let H;for(let z=0,X=d.length;z<X;z++){const L=d[z];if(L.cacheKey===D){H=L,++H.usedTimes;break}}return H===void 0&&(H=new yje(t,D,k,s),d.push(H)),H}function A(k){if(--k.usedTimes===0){const D=d.indexOf(k);d[D]=d[d.length-1],d.pop(),k.destroy()}}function T(k){c.remove(k)}function F(){c.dispose()}return{getParameters:g,getProgramCacheKey:b,getUniforms:P,acquireProgram:N,releaseProgram:A,releaseShaderCache:T,programs:d,dispose:F}}function kje(){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 i(){t=new WeakMap}return{get:e,remove:n,update:r,dispose:i}}function Nje(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 o$(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 l$(){const t=[];let e=0;const n=[],r=[],i=[];function s(){e=0,n.length=0,r.length=0,i.length=0}function o(m,p,f,x,v,g){let b=t[e];return b===void 0?(b={id:m.id,object:m,geometry:p,material:f,groupOrder:x,renderOrder:m.renderOrder,z:v,group:g},t[e]=b):(b.id=m.id,b.object=m,b.geometry=p,b.material=f,b.groupOrder=x,b.renderOrder=m.renderOrder,b.z=v,b.group=g),e++,b}function l(m,p,f,x,v,g){const b=o(m,p,f,x,v,g);f.transmission>0?r.push(b):f.transparent===!0?i.push(b):n.push(b)}function c(m,p,f,x,v,g){const b=o(m,p,f,x,v,g);f.transmission>0?r.unshift(b):f.transparent===!0?i.unshift(b):n.unshift(b)}function d(m,p){n.length>1&&n.sort(m||Nje),r.length>1&&r.sort(p||o$),i.length>1&&i.sort(p||o$)}function u(){for(let m=e,p=t.length;m<p;m++){const f=t[m];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:n,transmissive:r,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function Cje(){let t=new WeakMap;function e(r,i){const s=t.get(r);let o;return s===void 0?(o=new l$,t.set(r,[o])):i>=s.length?(o=new l$,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function Pje(){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 ct,color:new Dn};break;case"SpotLight":n={position:new ct,direction:new ct,color:new Dn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new ct,color:new Dn,distance:0,decay:0};break;case"HemisphereLight":n={direction:new ct,skyColor:new Dn,groundColor:new Dn};break;case"RectAreaLight":n={color:new Dn,position:new ct,halfWidth:new ct,halfHeight:new ct};break}return t[e.id]=n,n}}}function Tje(){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 Gn};break;case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Gn};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Gn,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let Aje=0;function jje(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Mje(t,e){const n=new Pje,r=Tje(),i={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++)i.probe.push(new ct);const s=new ct,o=new da,l=new da;function c(u,m){let p=0,f=0,x=0;for(let z=0;z<9;z++)i.probe[z].set(0,0,0);let v=0,g=0,b=0,_=0,C=0,P=0,N=0,A=0,T=0,F=0,k=0;u.sort(jje);const D=m===!0?Math.PI:1;for(let z=0,X=u.length;z<X;z++){const L=u[z],ne=L.color,ie=L.intensity,ee=L.distance,ue=L.shadow&&L.shadow.map?L.shadow.map.texture:null;if(L.isAmbientLight)p+=ne.r*ie*D,f+=ne.g*ie*D,x+=ne.b*ie*D;else if(L.isLightProbe){for(let le=0;le<9;le++)i.probe[le].addScaledVector(L.sh.coefficients[le],ie);k++}else if(L.isDirectionalLight){const le=n.get(L);if(le.color.copy(L.color).multiplyScalar(L.intensity*D),L.castShadow){const oe=L.shadow,W=r.get(L);W.shadowBias=oe.bias,W.shadowNormalBias=oe.normalBias,W.shadowRadius=oe.radius,W.shadowMapSize=oe.mapSize,i.directionalShadow[v]=W,i.directionalShadowMap[v]=ue,i.directionalShadowMatrix[v]=L.shadow.matrix,P++}i.directional[v]=le,v++}else if(L.isSpotLight){const le=n.get(L);le.position.setFromMatrixPosition(L.matrixWorld),le.color.copy(ne).multiplyScalar(ie*D),le.distance=ee,le.coneCos=Math.cos(L.angle),le.penumbraCos=Math.cos(L.angle*(1-L.penumbra)),le.decay=L.decay,i.spot[b]=le;const oe=L.shadow;if(L.map&&(i.spotLightMap[T]=L.map,T++,oe.updateMatrices(L),L.castShadow&&F++),i.spotLightMatrix[b]=oe.matrix,L.castShadow){const W=r.get(L);W.shadowBias=oe.bias,W.shadowNormalBias=oe.normalBias,W.shadowRadius=oe.radius,W.shadowMapSize=oe.mapSize,i.spotShadow[b]=W,i.spotShadowMap[b]=ue,A++}b++}else if(L.isRectAreaLight){const le=n.get(L);le.color.copy(ne).multiplyScalar(ie),le.halfWidth.set(L.width*.5,0,0),le.halfHeight.set(0,L.height*.5,0),i.rectArea[_]=le,_++}else if(L.isPointLight){const le=n.get(L);if(le.color.copy(L.color).multiplyScalar(L.intensity*D),le.distance=L.distance,le.decay=L.decay,L.castShadow){const oe=L.shadow,W=r.get(L);W.shadowBias=oe.bias,W.shadowNormalBias=oe.normalBias,W.shadowRadius=oe.radius,W.shadowMapSize=oe.mapSize,W.shadowCameraNear=oe.camera.near,W.shadowCameraFar=oe.camera.far,i.pointShadow[g]=W,i.pointShadowMap[g]=ue,i.pointShadowMatrix[g]=L.shadow.matrix,N++}i.point[g]=le,g++}else if(L.isHemisphereLight){const le=n.get(L);le.skyColor.copy(L.color).multiplyScalar(ie*D),le.groundColor.copy(L.groundColor).multiplyScalar(ie*D),i.hemi[C]=le,C++}}_>0&&(e.isWebGL2||t.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Zt.LTC_FLOAT_1,i.rectAreaLTC2=Zt.LTC_FLOAT_2):t.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=Zt.LTC_HALF_1,i.rectAreaLTC2=Zt.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=p,i.ambient[1]=f,i.ambient[2]=x;const H=i.hash;(H.directionalLength!==v||H.pointLength!==g||H.spotLength!==b||H.rectAreaLength!==_||H.hemiLength!==C||H.numDirectionalShadows!==P||H.numPointShadows!==N||H.numSpotShadows!==A||H.numSpotMaps!==T||H.numLightProbes!==k)&&(i.directional.length=v,i.spot.length=b,i.rectArea.length=_,i.point.length=g,i.hemi.length=C,i.directionalShadow.length=P,i.directionalShadowMap.length=P,i.pointShadow.length=N,i.pointShadowMap.length=N,i.spotShadow.length=A,i.spotShadowMap.length=A,i.directionalShadowMatrix.length=P,i.pointShadowMatrix.length=N,i.spotLightMatrix.length=A+T-F,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=F,i.numLightProbes=k,H.directionalLength=v,H.pointLength=g,H.spotLength=b,H.rectAreaLength=_,H.hemiLength=C,H.numDirectionalShadows=P,H.numPointShadows=N,H.numSpotShadows=A,H.numSpotMaps=T,H.numLightProbes=k,i.version=Aje++)}function d(u,m){let p=0,f=0,x=0,v=0,g=0;const b=m.matrixWorldInverse;for(let _=0,C=u.length;_<C;_++){const P=u[_];if(P.isDirectionalLight){const N=i.directional[p];N.direction.setFromMatrixPosition(P.matrixWorld),s.setFromMatrixPosition(P.target.matrixWorld),N.direction.sub(s),N.direction.transformDirection(b),p++}else if(P.isSpotLight){const N=i.spot[x];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(b),N.direction.setFromMatrixPosition(P.matrixWorld),s.setFromMatrixPosition(P.target.matrixWorld),N.direction.sub(s),N.direction.transformDirection(b),x++}else if(P.isRectAreaLight){const N=i.rectArea[v];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(b),l.identity(),o.copy(P.matrixWorld),o.premultiply(b),l.extractRotation(o),N.halfWidth.set(P.width*.5,0,0),N.halfHeight.set(0,P.height*.5,0),N.halfWidth.applyMatrix4(l),N.halfHeight.applyMatrix4(l),v++}else if(P.isPointLight){const N=i.point[f];N.position.setFromMatrixPosition(P.matrixWorld),N.position.applyMatrix4(b),f++}else if(P.isHemisphereLight){const N=i.hemi[g];N.direction.setFromMatrixPosition(P.matrixWorld),N.direction.transformDirection(b),g++}}}return{setup:c,setupView:d,state:i}}function c$(t,e){const n=new Mje(t,e),r=[],i=[];function s(){r.length=0,i.length=0}function o(m){r.push(m)}function l(m){i.push(m)}function c(m){n.setup(r,m)}function d(m){n.setupView(r,m)}return{init:s,state:{lightsArray:r,shadowsArray:i,lights:n},setupLights:c,setupLightsView:d,pushLight:o,pushShadow:l}}function Eje(t,e){let n=new WeakMap;function r(s,o=0){const l=n.get(s);let c;return l===void 0?(c=new c$(t,e),n.set(s,[c])):o>=l.length?(c=new c$(t,e),l.push(c)):c=l[o],c}function i(){n=new WeakMap}return{get:r,dispose:i}}class Dje extends my{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=xNe,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 Fje extends my{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 Rje=`void main() {
- gl_Position = vec4( position, 1.0 );
- }`,Lje=`uniform sampler2D shadow_pass;
- uniform vec2 resolution;
- uniform float radius;
- #include <packing>
- void main() {
- const float samples = float( VSM_SAMPLES );
- float mean = 0.0;
- float squared_mean = 0.0;
- float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
- float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
- for ( float i = 0.0; i < samples; i ++ ) {
- float uvOffset = uvStart + i * uvStride;
- #ifdef HORIZONTAL_PASS
- vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
- mean += distribution.x;
- squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
- #else
- float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
- mean += depth;
- squared_mean += depth * depth;
- #endif
- }
- mean = mean / samples;
- squared_mean = squared_mean / samples;
- float std_dev = sqrt( squared_mean - mean * mean );
- gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
- }`;function Oje(t,e,n){let r=new HP;const i=new Gn,s=new Gn,o=new Xr,l=new Dje({depthPacking:yNe}),c=new Fje,d={},u=n.maxTextureSize,m={[op]:jo,[jo]:op,[Ru]:Ru},p=new lp({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Gn},radius:{value:4}},vertexShader:Rje,fragmentShader:Lje}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const x=new Ls;x.setAttribute("position",new ol(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Lc(x,p),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=zZ;let b=this.type;this.render=function(N,A,T){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||N.length===0)return;const F=t.getRenderTarget(),k=t.getActiveCubeFace(),D=t.getActiveMipmapLevel(),H=t.state;H.setBlending(Xh),H.buffers.color.setClear(1,1,1,1),H.buffers.depth.setTest(!0),H.setScissorTest(!1);const z=b!==Pu&&this.type===Pu,X=b===Pu&&this.type!==Pu;for(let L=0,ne=N.length;L<ne;L++){const ie=N[L],ee=ie.shadow;if(ee===void 0){console.warn("THREE.WebGLShadowMap:",ie,"has no shadow.");continue}if(ee.autoUpdate===!1&&ee.needsUpdate===!1)continue;i.copy(ee.mapSize);const ue=ee.getFrameExtents();if(i.multiply(ue),s.copy(ee.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/ue.x),i.x=s.x*ue.x,ee.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/ue.y),i.y=s.y*ue.y,ee.mapSize.y=s.y)),ee.map===null||z===!0||X===!0){const oe=this.type!==Pu?{minFilter:cs,magFilter:cs}:{};ee.map!==null&&ee.map.dispose(),ee.map=new ng(i.x,i.y,oe),ee.map.texture.name=ie.name+".shadowMap",ee.camera.updateProjectionMatrix()}t.setRenderTarget(ee.map),t.clear();const le=ee.getViewportCount();for(let oe=0;oe<le;oe++){const W=ee.getViewport(oe);o.set(s.x*W.x,s.y*W.y,s.x*W.z,s.y*W.w),H.viewport(o),ee.updateMatrices(ie,oe),r=ee.getFrustum(),P(A,T,ee.camera,ie,this.type)}ee.isPointLightShadow!==!0&&this.type===Pu&&_(ee,T),ee.needsUpdate=!1}b=this.type,g.needsUpdate=!1,t.setRenderTarget(F,k,D)};function _(N,A){const T=e.update(v);p.defines.VSM_SAMPLES!==N.blurSamples&&(p.defines.VSM_SAMPLES=N.blurSamples,f.defines.VSM_SAMPLES=N.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),N.mapPass===null&&(N.mapPass=new ng(i.x,i.y)),p.uniforms.shadow_pass.value=N.map.texture,p.uniforms.resolution.value=N.mapSize,p.uniforms.radius.value=N.radius,t.setRenderTarget(N.mapPass),t.clear(),t.renderBufferDirect(A,null,T,p,v,null),f.uniforms.shadow_pass.value=N.mapPass.texture,f.uniforms.resolution.value=N.mapSize,f.uniforms.radius.value=N.radius,t.setRenderTarget(N.map),t.clear(),t.renderBufferDirect(A,null,T,f,v,null)}function C(N,A,T,F){let k=null;const D=T.isPointLight===!0?N.customDistanceMaterial:N.customDepthMaterial;if(D!==void 0)k=D;else if(k=T.isPointLight===!0?c:l,t.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0){const H=k.uuid,z=A.uuid;let X=d[H];X===void 0&&(X={},d[H]=X);let L=X[z];L===void 0&&(L=k.clone(),X[z]=L),k=L}if(k.visible=A.visible,k.wireframe=A.wireframe,F===Pu?k.side=A.shadowSide!==null?A.shadowSide:A.side:k.side=A.shadowSide!==null?A.shadowSide:m[A.side],k.alphaMap=A.alphaMap,k.alphaTest=A.alphaTest,k.map=A.map,k.clipShadows=A.clipShadows,k.clippingPlanes=A.clippingPlanes,k.clipIntersection=A.clipIntersection,k.displacementMap=A.displacementMap,k.displacementScale=A.displacementScale,k.displacementBias=A.displacementBias,k.wireframeLinewidth=A.wireframeLinewidth,k.linewidth=A.linewidth,T.isPointLight===!0&&k.isMeshDistanceMaterial===!0){const H=t.properties.get(k);H.light=T}return k}function P(N,A,T,F,k){if(N.visible===!1)return;if(N.layers.test(A.layers)&&(N.isMesh||N.isLine||N.isPoints)&&(N.castShadow||N.receiveShadow&&k===Pu)&&(!N.frustumCulled||r.intersectsObject(N))){N.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse,N.matrixWorld);const z=e.update(N),X=N.material;if(Array.isArray(X)){const L=z.groups;for(let ne=0,ie=L.length;ne<ie;ne++){const ee=L[ne],ue=X[ee.materialIndex];if(ue&&ue.visible){const le=C(N,ue,F,k);N.onBeforeShadow(t,N,A,T,z,le,ee),t.renderBufferDirect(T,null,z,le,N,ee),N.onAfterShadow(t,N,A,T,z,le,ee)}}}else if(X.visible){const L=C(N,X,F,k);N.onBeforeShadow(t,N,A,T,z,L,null),t.renderBufferDirect(T,null,z,L,N,null),N.onAfterShadow(t,N,A,T,z,L,null)}}const H=N.children;for(let z=0,X=H.length;z<X;z++)P(H[z],A,T,F,k)}}function Ije(t,e,n){const r=n.isWebGL2;function i(){let be=!1;const $e=new Xr;let He=null;const ge=new Xr(0,0,0,0);return{setMask:function(Pe){He!==Pe&&!be&&(t.colorMask(Pe,Pe,Pe,Pe),He=Pe)},setLocked:function(Pe){be=Pe},setClear:function(Pe,qe,Ze,ut,vt){vt===!0&&(Pe*=ut,qe*=ut,Ze*=ut),$e.set(Pe,qe,Ze,ut),ge.equals($e)===!1&&(t.clearColor(Pe,qe,Ze,ut),ge.copy($e))},reset:function(){be=!1,He=null,ge.set(-1,0,0,0)}}}function s(){let be=!1,$e=null,He=null,ge=null;return{setTest:function(Pe){Pe?j(t.DEPTH_TEST):O(t.DEPTH_TEST)},setMask:function(Pe){$e!==Pe&&!be&&(t.depthMask(Pe),$e=Pe)},setFunc:function(Pe){if(He!==Pe){switch(Pe){case Xke:t.depthFunc(t.NEVER);break;case Yke:t.depthFunc(t.ALWAYS);break;case Qke:t.depthFunc(t.LESS);break;case yN:t.depthFunc(t.LEQUAL);break;case Zke:t.depthFunc(t.EQUAL);break;case Jke:t.depthFunc(t.GEQUAL);break;case eNe:t.depthFunc(t.GREATER);break;case tNe:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}He=Pe}},setLocked:function(Pe){be=Pe},setClear:function(Pe){ge!==Pe&&(t.clearDepth(Pe),ge=Pe)},reset:function(){be=!1,$e=null,He=null,ge=null}}}function o(){let be=!1,$e=null,He=null,ge=null,Pe=null,qe=null,Ze=null,ut=null,vt=null;return{setTest:function(wt){be||(wt?j(t.STENCIL_TEST):O(t.STENCIL_TEST))},setMask:function(wt){$e!==wt&&!be&&(t.stencilMask(wt),$e=wt)},setFunc:function(wt,$t,Qt){(He!==wt||ge!==$t||Pe!==Qt)&&(t.stencilFunc(wt,$t,Qt),He=wt,ge=$t,Pe=Qt)},setOp:function(wt,$t,Qt){(qe!==wt||Ze!==$t||ut!==Qt)&&(t.stencilOp(wt,$t,Qt),qe=wt,Ze=$t,ut=Qt)},setLocked:function(wt){be=wt},setClear:function(wt){vt!==wt&&(t.clearStencil(wt),vt=wt)},reset:function(){be=!1,$e=null,He=null,ge=null,Pe=null,qe=null,Ze=null,ut=null,vt=null}}}const l=new i,c=new s,d=new o,u=new WeakMap,m=new WeakMap;let p={},f={},x=new WeakMap,v=[],g=null,b=!1,_=null,C=null,P=null,N=null,A=null,T=null,F=null,k=new Dn(0,0,0),D=0,H=!1,z=null,X=null,L=null,ne=null,ie=null;const ee=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let ue=!1,le=0;const oe=t.getParameter(t.VERSION);oe.indexOf("WebGL")!==-1?(le=parseFloat(/^WebGL (\d)/.exec(oe)[1]),ue=le>=1):oe.indexOf("OpenGL ES")!==-1&&(le=parseFloat(/^OpenGL ES (\d)/.exec(oe)[1]),ue=le>=2);let W=null,re={};const ce=t.getParameter(t.SCISSOR_BOX),xe=t.getParameter(t.VIEWPORT),Ne=new Xr().fromArray(ce),$=new Xr().fromArray(xe);function Y(be,$e,He,ge){const Pe=new Uint8Array(4),qe=t.createTexture();t.bindTexture(be,qe),t.texParameteri(be,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(be,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Ze=0;Ze<He;Ze++)r&&(be===t.TEXTURE_3D||be===t.TEXTURE_2D_ARRAY)?t.texImage3D($e,0,t.RGBA,1,1,ge,0,t.RGBA,t.UNSIGNED_BYTE,Pe):t.texImage2D($e+Ze,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Pe);return qe}const E={};E[t.TEXTURE_2D]=Y(t.TEXTURE_2D,t.TEXTURE_2D,1),E[t.TEXTURE_CUBE_MAP]=Y(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),r&&(E[t.TEXTURE_2D_ARRAY]=Y(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),E[t.TEXTURE_3D]=Y(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),l.setClear(0,0,0,1),c.setClear(1),d.setClear(0),j(t.DEPTH_TEST),c.setFunc(yN),J(!1),se(V6),j(t.CULL_FACE),Q(Xh);function j(be){p[be]!==!0&&(t.enable(be),p[be]=!0)}function O(be){p[be]!==!1&&(t.disable(be),p[be]=!1)}function K(be,$e){return f[be]!==$e?(t.bindFramebuffer(be,$e),f[be]=$e,r&&(be===t.DRAW_FRAMEBUFFER&&(f[t.FRAMEBUFFER]=$e),be===t.FRAMEBUFFER&&(f[t.DRAW_FRAMEBUFFER]=$e)),!0):!1}function B(be,$e){let He=v,ge=!1;if(be)if(He=x.get($e),He===void 0&&(He=[],x.set($e,He)),be.isWebGLMultipleRenderTargets){const Pe=be.texture;if(He.length!==Pe.length||He[0]!==t.COLOR_ATTACHMENT0){for(let qe=0,Ze=Pe.length;qe<Ze;qe++)He[qe]=t.COLOR_ATTACHMENT0+qe;He.length=Pe.length,ge=!0}}else He[0]!==t.COLOR_ATTACHMENT0&&(He[0]=t.COLOR_ATTACHMENT0,ge=!0);else He[0]!==t.BACK&&(He[0]=t.BACK,ge=!0);ge&&(n.isWebGL2?t.drawBuffers(He):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(He))}function he(be){return g!==be?(t.useProgram(be),g=be,!0):!1}const I={[pf]:t.FUNC_ADD,[Fke]:t.FUNC_SUBTRACT,[Rke]:t.FUNC_REVERSE_SUBTRACT};if(r)I[X6]=t.MIN,I[Y6]=t.MAX;else{const be=e.get("EXT_blend_minmax");be!==null&&(I[X6]=be.MIN_EXT,I[Y6]=be.MAX_EXT)}const V={[Lke]:t.ZERO,[Oke]:t.ONE,[Ike]:t.SRC_COLOR,[WF]:t.SRC_ALPHA,[$ke]:t.SRC_ALPHA_SATURATE,[Hke]:t.DST_COLOR,[Uke]:t.DST_ALPHA,[zke]:t.ONE_MINUS_SRC_COLOR,[KF]:t.ONE_MINUS_SRC_ALPHA,[qke]:t.ONE_MINUS_DST_COLOR,[Bke]:t.ONE_MINUS_DST_ALPHA,[Vke]:t.CONSTANT_COLOR,[Gke]:t.ONE_MINUS_CONSTANT_COLOR,[Wke]:t.CONSTANT_ALPHA,[Kke]:t.ONE_MINUS_CONSTANT_ALPHA};function Q(be,$e,He,ge,Pe,qe,Ze,ut,vt,wt){if(be===Xh){b===!0&&(O(t.BLEND),b=!1);return}if(b===!1&&(j(t.BLEND),b=!0),be!==Dke){if(be!==_||wt!==H){if((C!==pf||A!==pf)&&(t.blendEquation(t.FUNC_ADD),C=pf,A=pf),wt)switch(be){case fx:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case G6:t.blendFunc(t.ONE,t.ONE);break;case W6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case K6:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",be);break}else switch(be){case fx:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case G6:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case W6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case K6:t.blendFunc(t.ZERO,t.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",be);break}P=null,N=null,T=null,F=null,k.set(0,0,0),D=0,_=be,H=wt}return}Pe=Pe||$e,qe=qe||He,Ze=Ze||ge,($e!==C||Pe!==A)&&(t.blendEquationSeparate(I[$e],I[Pe]),C=$e,A=Pe),(He!==P||ge!==N||qe!==T||Ze!==F)&&(t.blendFuncSeparate(V[He],V[ge],V[qe],V[Ze]),P=He,N=ge,T=qe,F=Ze),(ut.equals(k)===!1||vt!==D)&&(t.blendColor(ut.r,ut.g,ut.b,vt),k.copy(ut),D=vt),_=be,H=!1}function G(be,$e){be.side===Ru?O(t.CULL_FACE):j(t.CULL_FACE);let He=be.side===jo;$e&&(He=!He),J(He),be.blending===fx&&be.transparent===!1?Q(Xh):Q(be.blending,be.blendEquation,be.blendSrc,be.blendDst,be.blendEquationAlpha,be.blendSrcAlpha,be.blendDstAlpha,be.blendColor,be.blendAlpha,be.premultipliedAlpha),c.setFunc(be.depthFunc),c.setTest(be.depthTest),c.setMask(be.depthWrite),l.setMask(be.colorWrite);const ge=be.stencilWrite;d.setTest(ge),ge&&(d.setMask(be.stencilWriteMask),d.setFunc(be.stencilFunc,be.stencilRef,be.stencilFuncMask),d.setOp(be.stencilFail,be.stencilZFail,be.stencilZPass)),pe(be.polygonOffset,be.polygonOffsetFactor,be.polygonOffsetUnits),be.alphaToCoverage===!0?j(t.SAMPLE_ALPHA_TO_COVERAGE):O(t.SAMPLE_ALPHA_TO_COVERAGE)}function J(be){z!==be&&(be?t.frontFace(t.CW):t.frontFace(t.CCW),z=be)}function se(be){be!==jke?(j(t.CULL_FACE),be!==X&&(be===V6?t.cullFace(t.BACK):be===Mke?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):O(t.CULL_FACE),X=be}function fe(be){be!==L&&(ue&&t.lineWidth(be),L=be)}function pe(be,$e,He){be?(j(t.POLYGON_OFFSET_FILL),(ne!==$e||ie!==He)&&(t.polygonOffset($e,He),ne=$e,ie=He)):O(t.POLYGON_OFFSET_FILL)}function de(be){be?j(t.SCISSOR_TEST):O(t.SCISSOR_TEST)}function U(be){be===void 0&&(be=t.TEXTURE0+ee-1),W!==be&&(t.activeTexture(be),W=be)}function R(be,$e,He){He===void 0&&(W===null?He=t.TEXTURE0+ee-1:He=W);let ge=re[He];ge===void 0&&(ge={type:void 0,texture:void 0},re[He]=ge),(ge.type!==be||ge.texture!==$e)&&(W!==He&&(t.activeTexture(He),W=He),t.bindTexture(be,$e||E[be]),ge.type=be,ge.texture=$e)}function ae(){const be=re[W];be!==void 0&&be.type!==void 0&&(t.bindTexture(be.type,null),be.type=void 0,be.texture=void 0)}function _e(){try{t.compressedTexImage2D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Se(){try{t.compressedTexImage3D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function ye(){try{t.texSubImage2D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Ae(){try{t.texSubImage3D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function ve(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function je(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Re(){try{t.texStorage2D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Ee(){try{t.texStorage3D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Te(){try{t.texImage2D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Me(){try{t.texImage3D.apply(t,arguments)}catch(be){console.error("THREE.WebGLState:",be)}}function Be(be){Ne.equals(be)===!1&&(t.scissor(be.x,be.y,be.z,be.w),Ne.copy(be))}function Ke(be){$.equals(be)===!1&&(t.viewport(be.x,be.y,be.z,be.w),$.copy(be))}function tt(be,$e){let He=m.get($e);He===void 0&&(He=new WeakMap,m.set($e,He));let ge=He.get(be);ge===void 0&&(ge=t.getUniformBlockIndex($e,be.name),He.set(be,ge))}function te(be,$e){const ge=m.get($e).get(be);u.get($e)!==ge&&(t.uniformBlockBinding($e,ge,be.__bindingPointIndex),u.set($e,ge))}function Ie(){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),p={},W=null,re={},f={},x=new WeakMap,v=[],g=null,b=!1,_=null,C=null,P=null,N=null,A=null,T=null,F=null,k=new Dn(0,0,0),D=0,H=!1,z=null,X=null,L=null,ne=null,ie=null,Ne.set(0,0,t.canvas.width,t.canvas.height),$.set(0,0,t.canvas.width,t.canvas.height),l.reset(),c.reset(),d.reset()}return{buffers:{color:l,depth:c,stencil:d},enable:j,disable:O,bindFramebuffer:K,drawBuffers:B,useProgram:he,setBlending:Q,setMaterial:G,setFlipSided:J,setCullFace:se,setLineWidth:fe,setPolygonOffset:pe,setScissorTest:de,activeTexture:U,bindTexture:R,unbindTexture:ae,compressedTexImage2D:_e,compressedTexImage3D:Se,texImage2D:Te,texImage3D:Me,updateUBOMapping:tt,uniformBlockBinding:te,texStorage2D:Re,texStorage3D:Ee,texSubImage2D:ye,texSubImage3D:Ae,compressedTexSubImage2D:ve,compressedTexSubImage3D:je,scissor:Be,viewport:Ke,reset:Ie}}function zje(t,e,n,r,i,s,o){const l=i.isWebGL2,c=i.maxTextures,d=i.maxCubemapSize,u=i.maxTextureSize,m=i.maxSamples,p=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,f=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),x=new WeakMap;let v;const g=new WeakMap;let b=!1;try{b=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(U,R){return b?new OffscreenCanvas(U,R):kN("canvas")}function C(U,R,ae,_e){let Se=1;if((U.width>_e||U.height>_e)&&(Se=_e/Math.max(U.width,U.height)),Se<1||R===!0)if(typeof HTMLImageElement<"u"&&U instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&U instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&U instanceof ImageBitmap){const ye=R?_N:Math.floor,Ae=ye(Se*U.width),ve=ye(Se*U.height);v===void 0&&(v=_(Ae,ve));const je=ae?_(Ae,ve):v;return je.width=Ae,je.height=ve,je.getContext("2d").drawImage(U,0,0,Ae,ve),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+U.width+"x"+U.height+") to ("+Ae+"x"+ve+")."),je}else return"data"in U&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+U.width+"x"+U.height+")."),U;return U}function P(U){return tR(U.width)&&tR(U.height)}function N(U){return l?!1:U.wrapS!==jc||U.wrapT!==jc||U.minFilter!==cs&&U.minFilter!==$l}function A(U,R){return U.generateMipmaps&&R&&U.minFilter!==cs&&U.minFilter!==$l}function T(U){t.generateMipmap(U)}function F(U,R,ae,_e,Se=!1){if(l===!1)return R;if(U!==null){if(t[U]!==void 0)return t[U];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+U+"'")}let ye=R;if(R===t.RED&&(ae===t.FLOAT&&(ye=t.R32F),ae===t.HALF_FLOAT&&(ye=t.R16F),ae===t.UNSIGNED_BYTE&&(ye=t.R8)),R===t.RED_INTEGER&&(ae===t.UNSIGNED_BYTE&&(ye=t.R8UI),ae===t.UNSIGNED_SHORT&&(ye=t.R16UI),ae===t.UNSIGNED_INT&&(ye=t.R32UI),ae===t.BYTE&&(ye=t.R8I),ae===t.SHORT&&(ye=t.R16I),ae===t.INT&&(ye=t.R32I)),R===t.RG&&(ae===t.FLOAT&&(ye=t.RG32F),ae===t.HALF_FLOAT&&(ye=t.RG16F),ae===t.UNSIGNED_BYTE&&(ye=t.RG8)),R===t.RGBA){const Ae=Se?vN:Wr.getTransfer(_e);ae===t.FLOAT&&(ye=t.RGBA32F),ae===t.HALF_FLOAT&&(ye=t.RGBA16F),ae===t.UNSIGNED_BYTE&&(ye=Ae===ga?t.SRGB8_ALPHA8:t.RGBA8),ae===t.UNSIGNED_SHORT_4_4_4_4&&(ye=t.RGBA4),ae===t.UNSIGNED_SHORT_5_5_5_1&&(ye=t.RGB5_A1)}return(ye===t.R16F||ye===t.R32F||ye===t.RG16F||ye===t.RG32F||ye===t.RGBA16F||ye===t.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function k(U,R,ae){return A(U,ae)===!0||U.isFramebufferTexture&&U.minFilter!==cs&&U.minFilter!==$l?Math.log2(Math.max(R.width,R.height))+1:U.mipmaps!==void 0&&U.mipmaps.length>0?U.mipmaps.length:U.isCompressedTexture&&Array.isArray(U.image)?R.mipmaps.length:1}function D(U){return U===cs||U===Q6||U===JM?t.NEAREST:t.LINEAR}function H(U){const R=U.target;R.removeEventListener("dispose",H),X(R),R.isVideoTexture&&x.delete(R)}function z(U){const R=U.target;R.removeEventListener("dispose",z),ne(R)}function X(U){const R=r.get(U);if(R.__webglInit===void 0)return;const ae=U.source,_e=g.get(ae);if(_e){const Se=_e[R.__cacheKey];Se.usedTimes--,Se.usedTimes===0&&L(U),Object.keys(_e).length===0&&g.delete(ae)}r.remove(U)}function L(U){const R=r.get(U);t.deleteTexture(R.__webglTexture);const ae=U.source,_e=g.get(ae);delete _e[R.__cacheKey],o.memory.textures--}function ne(U){const R=U.texture,ae=r.get(U),_e=r.get(R);if(_e.__webglTexture!==void 0&&(t.deleteTexture(_e.__webglTexture),o.memory.textures--),U.depthTexture&&U.depthTexture.dispose(),U.isWebGLCubeRenderTarget)for(let Se=0;Se<6;Se++){if(Array.isArray(ae.__webglFramebuffer[Se]))for(let ye=0;ye<ae.__webglFramebuffer[Se].length;ye++)t.deleteFramebuffer(ae.__webglFramebuffer[Se][ye]);else t.deleteFramebuffer(ae.__webglFramebuffer[Se]);ae.__webglDepthbuffer&&t.deleteRenderbuffer(ae.__webglDepthbuffer[Se])}else{if(Array.isArray(ae.__webglFramebuffer))for(let Se=0;Se<ae.__webglFramebuffer.length;Se++)t.deleteFramebuffer(ae.__webglFramebuffer[Se]);else t.deleteFramebuffer(ae.__webglFramebuffer);if(ae.__webglDepthbuffer&&t.deleteRenderbuffer(ae.__webglDepthbuffer),ae.__webglMultisampledFramebuffer&&t.deleteFramebuffer(ae.__webglMultisampledFramebuffer),ae.__webglColorRenderbuffer)for(let Se=0;Se<ae.__webglColorRenderbuffer.length;Se++)ae.__webglColorRenderbuffer[Se]&&t.deleteRenderbuffer(ae.__webglColorRenderbuffer[Se]);ae.__webglDepthRenderbuffer&&t.deleteRenderbuffer(ae.__webglDepthRenderbuffer)}if(U.isWebGLMultipleRenderTargets)for(let Se=0,ye=R.length;Se<ye;Se++){const Ae=r.get(R[Se]);Ae.__webglTexture&&(t.deleteTexture(Ae.__webglTexture),o.memory.textures--),r.remove(R[Se])}r.remove(R),r.remove(U)}let ie=0;function ee(){ie=0}function ue(){const U=ie;return U>=c&&console.warn("THREE.WebGLTextures: Trying to use "+U+" texture units while this GPU supports only "+c),ie+=1,U}function le(U){const R=[];return R.push(U.wrapS),R.push(U.wrapT),R.push(U.wrapR||0),R.push(U.magFilter),R.push(U.minFilter),R.push(U.anisotropy),R.push(U.internalFormat),R.push(U.format),R.push(U.type),R.push(U.generateMipmaps),R.push(U.premultiplyAlpha),R.push(U.flipY),R.push(U.unpackAlignment),R.push(U.colorSpace),R.join()}function oe(U,R){const ae=r.get(U);if(U.isVideoTexture&&pe(U),U.isRenderTargetTexture===!1&&U.version>0&&ae.__version!==U.version){const _e=U.image;if(_e===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(_e.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{j(ae,U,R);return}}n.bindTexture(t.TEXTURE_2D,ae.__webglTexture,t.TEXTURE0+R)}function W(U,R){const ae=r.get(U);if(U.version>0&&ae.__version!==U.version){j(ae,U,R);return}n.bindTexture(t.TEXTURE_2D_ARRAY,ae.__webglTexture,t.TEXTURE0+R)}function re(U,R){const ae=r.get(U);if(U.version>0&&ae.__version!==U.version){j(ae,U,R);return}n.bindTexture(t.TEXTURE_3D,ae.__webglTexture,t.TEXTURE0+R)}function ce(U,R){const ae=r.get(U);if(U.version>0&&ae.__version!==U.version){O(ae,U,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,ae.__webglTexture,t.TEXTURE0+R)}const xe={[QF]:t.REPEAT,[jc]:t.CLAMP_TO_EDGE,[ZF]:t.MIRRORED_REPEAT},Ne={[cs]:t.NEAREST,[Q6]:t.NEAREST_MIPMAP_NEAREST,[JM]:t.NEAREST_MIPMAP_LINEAR,[$l]:t.LINEAR,[cNe]:t.LINEAR_MIPMAP_NEAREST,[X0]:t.LINEAR_MIPMAP_LINEAR},$={[wNe]:t.NEVER,[PNe]:t.ALWAYS,[SNe]:t.LESS,[YZ]:t.LEQUAL,[_Ne]:t.EQUAL,[CNe]:t.GEQUAL,[kNe]:t.GREATER,[NNe]:t.NOTEQUAL};function Y(U,R,ae){if(ae?(t.texParameteri(U,t.TEXTURE_WRAP_S,xe[R.wrapS]),t.texParameteri(U,t.TEXTURE_WRAP_T,xe[R.wrapT]),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,xe[R.wrapR]),t.texParameteri(U,t.TEXTURE_MAG_FILTER,Ne[R.magFilter]),t.texParameteri(U,t.TEXTURE_MIN_FILTER,Ne[R.minFilter])):(t.texParameteri(U,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(U,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(U===t.TEXTURE_3D||U===t.TEXTURE_2D_ARRAY)&&t.texParameteri(U,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(R.wrapS!==jc||R.wrapT!==jc)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(U,t.TEXTURE_MAG_FILTER,D(R.magFilter)),t.texParameteri(U,t.TEXTURE_MIN_FILTER,D(R.minFilter)),R.minFilter!==cs&&R.minFilter!==$l&&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(U,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(U,t.TEXTURE_COMPARE_FUNC,$[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const _e=e.get("EXT_texture_filter_anisotropic");if(R.magFilter===cs||R.minFilter!==JM&&R.minFilter!==X0||R.type===qu&&e.has("OES_texture_float_linear")===!1||l===!1&&R.type===Y0&&e.has("OES_texture_half_float_linear")===!1)return;(R.anisotropy>1||r.get(R).__currentAnisotropy)&&(t.texParameterf(U,_e.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy)}}function E(U,R){let ae=!1;U.__webglInit===void 0&&(U.__webglInit=!0,R.addEventListener("dispose",H));const _e=R.source;let Se=g.get(_e);Se===void 0&&(Se={},g.set(_e,Se));const ye=le(R);if(ye!==U.__cacheKey){Se[ye]===void 0&&(Se[ye]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,ae=!0),Se[ye].usedTimes++;const Ae=Se[U.__cacheKey];Ae!==void 0&&(Se[U.__cacheKey].usedTimes--,Ae.usedTimes===0&&L(R)),U.__cacheKey=ye,U.__webglTexture=Se[ye].texture}return ae}function j(U,R,ae){let _e=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(_e=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(_e=t.TEXTURE_3D);const Se=E(U,R),ye=R.source;n.bindTexture(_e,U.__webglTexture,t.TEXTURE0+ae);const Ae=r.get(ye);if(ye.version!==Ae.__version||Se===!0){n.activeTexture(t.TEXTURE0+ae);const ve=Wr.getPrimaries(Wr.workingColorSpace),je=R.colorSpace===Gl?null:Wr.getPrimaries(R.colorSpace),Re=R.colorSpace===Gl||ve===je?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,Re);const Ee=N(R)&&P(R.image)===!1;let Te=C(R.image,Ee,!1,u);Te=de(R,Te);const Me=P(Te)||l,Be=s.convert(R.format,R.colorSpace);let Ke=s.convert(R.type),tt=F(R.internalFormat,Be,Ke,R.colorSpace,R.isVideoTexture);Y(_e,R,Me);let te;const Ie=R.mipmaps,be=l&&R.isVideoTexture!==!0&&tt!==WZ,$e=Ae.__version===void 0||Se===!0,He=k(R,Te,Me);if(R.isDepthTexture)tt=t.DEPTH_COMPONENT,l?R.type===qu?tt=t.DEPTH_COMPONENT32F:R.type===Mh?tt=t.DEPTH_COMPONENT24:R.type===Ef?tt=t.DEPTH24_STENCIL8:tt=t.DEPTH_COMPONENT16:R.type===qu&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),R.format===Df&&tt===t.DEPTH_COMPONENT&&R.type!==XO&&R.type!==Mh&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),R.type=Mh,Ke=s.convert(R.type)),R.format===Ox&&tt===t.DEPTH_COMPONENT&&(tt=t.DEPTH_STENCIL,R.type!==Ef&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),R.type=Ef,Ke=s.convert(R.type))),$e&&(be?n.texStorage2D(t.TEXTURE_2D,1,tt,Te.width,Te.height):n.texImage2D(t.TEXTURE_2D,0,tt,Te.width,Te.height,0,Be,Ke,null));else if(R.isDataTexture)if(Ie.length>0&&Me){be&&$e&&n.texStorage2D(t.TEXTURE_2D,He,tt,Ie[0].width,Ie[0].height);for(let ge=0,Pe=Ie.length;ge<Pe;ge++)te=Ie[ge],be?n.texSubImage2D(t.TEXTURE_2D,ge,0,0,te.width,te.height,Be,Ke,te.data):n.texImage2D(t.TEXTURE_2D,ge,tt,te.width,te.height,0,Be,Ke,te.data);R.generateMipmaps=!1}else be?($e&&n.texStorage2D(t.TEXTURE_2D,He,tt,Te.width,Te.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,Te.width,Te.height,Be,Ke,Te.data)):n.texImage2D(t.TEXTURE_2D,0,tt,Te.width,Te.height,0,Be,Ke,Te.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){be&&$e&&n.texStorage3D(t.TEXTURE_2D_ARRAY,He,tt,Ie[0].width,Ie[0].height,Te.depth);for(let ge=0,Pe=Ie.length;ge<Pe;ge++)te=Ie[ge],R.format!==Vl?Be!==null?be?n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,ge,0,0,0,te.width,te.height,Te.depth,Be,te.data,0,0):n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,ge,tt,te.width,te.height,Te.depth,0,te.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):be?n.texSubImage3D(t.TEXTURE_2D_ARRAY,ge,0,0,0,te.width,te.height,Te.depth,Be,Ke,te.data):n.texImage3D(t.TEXTURE_2D_ARRAY,ge,tt,te.width,te.height,Te.depth,0,Be,Ke,te.data)}else{be&&$e&&n.texStorage2D(t.TEXTURE_2D,He,tt,Ie[0].width,Ie[0].height);for(let ge=0,Pe=Ie.length;ge<Pe;ge++)te=Ie[ge],R.format!==Vl?Be!==null?be?n.compressedTexSubImage2D(t.TEXTURE_2D,ge,0,0,te.width,te.height,Be,te.data):n.compressedTexImage2D(t.TEXTURE_2D,ge,tt,te.width,te.height,0,te.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):be?n.texSubImage2D(t.TEXTURE_2D,ge,0,0,te.width,te.height,Be,Ke,te.data):n.texImage2D(t.TEXTURE_2D,ge,tt,te.width,te.height,0,Be,Ke,te.data)}else if(R.isDataArrayTexture)be?($e&&n.texStorage3D(t.TEXTURE_2D_ARRAY,He,tt,Te.width,Te.height,Te.depth),n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Te.width,Te.height,Te.depth,Be,Ke,Te.data)):n.texImage3D(t.TEXTURE_2D_ARRAY,0,tt,Te.width,Te.height,Te.depth,0,Be,Ke,Te.data);else if(R.isData3DTexture)be?($e&&n.texStorage3D(t.TEXTURE_3D,He,tt,Te.width,Te.height,Te.depth),n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Te.width,Te.height,Te.depth,Be,Ke,Te.data)):n.texImage3D(t.TEXTURE_3D,0,tt,Te.width,Te.height,Te.depth,0,Be,Ke,Te.data);else if(R.isFramebufferTexture){if($e)if(be)n.texStorage2D(t.TEXTURE_2D,He,tt,Te.width,Te.height);else{let ge=Te.width,Pe=Te.height;for(let qe=0;qe<He;qe++)n.texImage2D(t.TEXTURE_2D,qe,tt,ge,Pe,0,Be,Ke,null),ge>>=1,Pe>>=1}}else if(Ie.length>0&&Me){be&&$e&&n.texStorage2D(t.TEXTURE_2D,He,tt,Ie[0].width,Ie[0].height);for(let ge=0,Pe=Ie.length;ge<Pe;ge++)te=Ie[ge],be?n.texSubImage2D(t.TEXTURE_2D,ge,0,0,Be,Ke,te):n.texImage2D(t.TEXTURE_2D,ge,tt,Be,Ke,te);R.generateMipmaps=!1}else be?($e&&n.texStorage2D(t.TEXTURE_2D,He,tt,Te.width,Te.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,Be,Ke,Te)):n.texImage2D(t.TEXTURE_2D,0,tt,Be,Ke,Te);A(R,Me)&&T(_e),Ae.__version=ye.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function O(U,R,ae){if(R.image.length!==6)return;const _e=E(U,R),Se=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,U.__webglTexture,t.TEXTURE0+ae);const ye=r.get(Se);if(Se.version!==ye.__version||_e===!0){n.activeTexture(t.TEXTURE0+ae);const Ae=Wr.getPrimaries(Wr.workingColorSpace),ve=R.colorSpace===Gl?null:Wr.getPrimaries(R.colorSpace),je=R.colorSpace===Gl||Ae===ve?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,je);const Re=R.isCompressedTexture||R.image[0].isCompressedTexture,Ee=R.image[0]&&R.image[0].isDataTexture,Te=[];for(let ge=0;ge<6;ge++)!Re&&!Ee?Te[ge]=C(R.image[ge],!1,!0,d):Te[ge]=Ee?R.image[ge].image:R.image[ge],Te[ge]=de(R,Te[ge]);const Me=Te[0],Be=P(Me)||l,Ke=s.convert(R.format,R.colorSpace),tt=s.convert(R.type),te=F(R.internalFormat,Ke,tt,R.colorSpace),Ie=l&&R.isVideoTexture!==!0,be=ye.__version===void 0||_e===!0;let $e=k(R,Me,Be);Y(t.TEXTURE_CUBE_MAP,R,Be);let He;if(Re){Ie&&be&&n.texStorage2D(t.TEXTURE_CUBE_MAP,$e,te,Me.width,Me.height);for(let ge=0;ge<6;ge++){He=Te[ge].mipmaps;for(let Pe=0;Pe<He.length;Pe++){const qe=He[Pe];R.format!==Vl?Ke!==null?Ie?n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,0,0,qe.width,qe.height,Ke,qe.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,te,qe.width,qe.height,0,qe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Ie?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,0,0,qe.width,qe.height,Ke,tt,qe.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe,te,qe.width,qe.height,0,Ke,tt,qe.data)}}}else{He=R.mipmaps,Ie&&be&&(He.length>0&&$e++,n.texStorage2D(t.TEXTURE_CUBE_MAP,$e,te,Te[0].width,Te[0].height));for(let ge=0;ge<6;ge++)if(Ee){Ie?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,0,0,Te[ge].width,Te[ge].height,Ke,tt,Te[ge].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,te,Te[ge].width,Te[ge].height,0,Ke,tt,Te[ge].data);for(let Pe=0;Pe<He.length;Pe++){const Ze=He[Pe].image[ge].image;Ie?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,0,0,Ze.width,Ze.height,Ke,tt,Ze.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,te,Ze.width,Ze.height,0,Ke,tt,Ze.data)}}else{Ie?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,0,0,Ke,tt,Te[ge]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,te,Ke,tt,Te[ge]);for(let Pe=0;Pe<He.length;Pe++){const qe=He[Pe];Ie?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,0,0,Ke,tt,qe.image[ge]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Pe+1,te,Ke,tt,qe.image[ge])}}}A(R,Be)&&T(t.TEXTURE_CUBE_MAP),ye.__version=Se.version,R.onUpdate&&R.onUpdate(R)}U.__version=R.version}function K(U,R,ae,_e,Se,ye){const Ae=s.convert(ae.format,ae.colorSpace),ve=s.convert(ae.type),je=F(ae.internalFormat,Ae,ve,ae.colorSpace);if(!r.get(R).__hasExternalTextures){const Ee=Math.max(1,R.width>>ye),Te=Math.max(1,R.height>>ye);Se===t.TEXTURE_3D||Se===t.TEXTURE_2D_ARRAY?n.texImage3D(Se,ye,je,Ee,Te,R.depth,0,Ae,ve,null):n.texImage2D(Se,ye,je,Ee,Te,0,Ae,ve,null)}n.bindFramebuffer(t.FRAMEBUFFER,U),fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,_e,Se,r.get(ae).__webglTexture,0,se(R)):(Se===t.TEXTURE_2D||Se>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&Se<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,_e,Se,r.get(ae).__webglTexture,ye),n.bindFramebuffer(t.FRAMEBUFFER,null)}function B(U,R,ae){if(t.bindRenderbuffer(t.RENDERBUFFER,U),R.depthBuffer&&!R.stencilBuffer){let _e=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(ae||fe(R)){const Se=R.depthTexture;Se&&Se.isDepthTexture&&(Se.type===qu?_e=t.DEPTH_COMPONENT32F:Se.type===Mh&&(_e=t.DEPTH_COMPONENT24));const ye=se(R);fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ye,_e,R.width,R.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,ye,_e,R.width,R.height)}else t.renderbufferStorage(t.RENDERBUFFER,_e,R.width,R.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,U)}else if(R.depthBuffer&&R.stencilBuffer){const _e=se(R);ae&&fe(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,_e,t.DEPTH24_STENCIL8,R.width,R.height):fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,_e,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,U)}else{const _e=R.isWebGLMultipleRenderTargets===!0?R.texture:[R.texture];for(let Se=0;Se<_e.length;Se++){const ye=_e[Se],Ae=s.convert(ye.format,ye.colorSpace),ve=s.convert(ye.type),je=F(ye.internalFormat,Ae,ve,ye.colorSpace),Re=se(R);ae&&fe(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Re,je,R.width,R.height):fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Re,je,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,je,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function he(U,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,U),!(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),oe(R.depthTexture,0);const _e=r.get(R.depthTexture).__webglTexture,Se=se(R);if(R.depthTexture.format===Df)fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,_e,0,Se):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,_e,0);else if(R.depthTexture.format===Ox)fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,_e,0,Se):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,_e,0);else throw new Error("Unknown depthTexture format")}function I(U){const R=r.get(U),ae=U.isWebGLCubeRenderTarget===!0;if(U.depthTexture&&!R.__autoAllocateDepthBuffer){if(ae)throw new Error("target.depthTexture not supported in Cube render targets");he(R.__webglFramebuffer,U)}else if(ae){R.__webglDepthbuffer=[];for(let _e=0;_e<6;_e++)n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[_e]),R.__webglDepthbuffer[_e]=t.createRenderbuffer(),B(R.__webglDepthbuffer[_e],U,!1)}else n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer=t.createRenderbuffer(),B(R.__webglDepthbuffer,U,!1);n.bindFramebuffer(t.FRAMEBUFFER,null)}function V(U,R,ae){const _e=r.get(U);R!==void 0&&K(_e.__webglFramebuffer,U,U.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),ae!==void 0&&I(U)}function Q(U){const R=U.texture,ae=r.get(U),_e=r.get(R);U.addEventListener("dispose",z),U.isWebGLMultipleRenderTargets!==!0&&(_e.__webglTexture===void 0&&(_e.__webglTexture=t.createTexture()),_e.__version=R.version,o.memory.textures++);const Se=U.isWebGLCubeRenderTarget===!0,ye=U.isWebGLMultipleRenderTargets===!0,Ae=P(U)||l;if(Se){ae.__webglFramebuffer=[];for(let ve=0;ve<6;ve++)if(l&&R.mipmaps&&R.mipmaps.length>0){ae.__webglFramebuffer[ve]=[];for(let je=0;je<R.mipmaps.length;je++)ae.__webglFramebuffer[ve][je]=t.createFramebuffer()}else ae.__webglFramebuffer[ve]=t.createFramebuffer()}else{if(l&&R.mipmaps&&R.mipmaps.length>0){ae.__webglFramebuffer=[];for(let ve=0;ve<R.mipmaps.length;ve++)ae.__webglFramebuffer[ve]=t.createFramebuffer()}else ae.__webglFramebuffer=t.createFramebuffer();if(ye)if(i.drawBuffers){const ve=U.texture;for(let je=0,Re=ve.length;je<Re;je++){const Ee=r.get(ve[je]);Ee.__webglTexture===void 0&&(Ee.__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&&U.samples>0&&fe(U)===!1){const ve=ye?R:[R];ae.__webglMultisampledFramebuffer=t.createFramebuffer(),ae.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,ae.__webglMultisampledFramebuffer);for(let je=0;je<ve.length;je++){const Re=ve[je];ae.__webglColorRenderbuffer[je]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,ae.__webglColorRenderbuffer[je]);const Ee=s.convert(Re.format,Re.colorSpace),Te=s.convert(Re.type),Me=F(Re.internalFormat,Ee,Te,Re.colorSpace,U.isXRRenderTarget===!0),Be=se(U);t.renderbufferStorageMultisample(t.RENDERBUFFER,Be,Me,U.width,U.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+je,t.RENDERBUFFER,ae.__webglColorRenderbuffer[je])}t.bindRenderbuffer(t.RENDERBUFFER,null),U.depthBuffer&&(ae.__webglDepthRenderbuffer=t.createRenderbuffer(),B(ae.__webglDepthRenderbuffer,U,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(Se){n.bindTexture(t.TEXTURE_CUBE_MAP,_e.__webglTexture),Y(t.TEXTURE_CUBE_MAP,R,Ae);for(let ve=0;ve<6;ve++)if(l&&R.mipmaps&&R.mipmaps.length>0)for(let je=0;je<R.mipmaps.length;je++)K(ae.__webglFramebuffer[ve][je],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,je);else K(ae.__webglFramebuffer[ve],U,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ve,0);A(R,Ae)&&T(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(ye){const ve=U.texture;for(let je=0,Re=ve.length;je<Re;je++){const Ee=ve[je],Te=r.get(Ee);n.bindTexture(t.TEXTURE_2D,Te.__webglTexture),Y(t.TEXTURE_2D,Ee,Ae),K(ae.__webglFramebuffer,U,Ee,t.COLOR_ATTACHMENT0+je,t.TEXTURE_2D,0),A(Ee,Ae)&&T(t.TEXTURE_2D)}n.unbindTexture()}else{let ve=t.TEXTURE_2D;if((U.isWebGL3DRenderTarget||U.isWebGLArrayRenderTarget)&&(l?ve=U.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),n.bindTexture(ve,_e.__webglTexture),Y(ve,R,Ae),l&&R.mipmaps&&R.mipmaps.length>0)for(let je=0;je<R.mipmaps.length;je++)K(ae.__webglFramebuffer[je],U,R,t.COLOR_ATTACHMENT0,ve,je);else K(ae.__webglFramebuffer,U,R,t.COLOR_ATTACHMENT0,ve,0);A(R,Ae)&&T(ve),n.unbindTexture()}U.depthBuffer&&I(U)}function G(U){const R=P(U)||l,ae=U.isWebGLMultipleRenderTargets===!0?U.texture:[U.texture];for(let _e=0,Se=ae.length;_e<Se;_e++){const ye=ae[_e];if(A(ye,R)){const Ae=U.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,ve=r.get(ye).__webglTexture;n.bindTexture(Ae,ve),T(Ae),n.unbindTexture()}}}function J(U){if(l&&U.samples>0&&fe(U)===!1){const R=U.isWebGLMultipleRenderTargets?U.texture:[U.texture],ae=U.width,_e=U.height;let Se=t.COLOR_BUFFER_BIT;const ye=[],Ae=U.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ve=r.get(U),je=U.isWebGLMultipleRenderTargets===!0;if(je)for(let Re=0;Re<R.length;Re++)n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,ve.__webglMultisampledFramebuffer),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ve.__webglFramebuffer);for(let Re=0;Re<R.length;Re++){ye.push(t.COLOR_ATTACHMENT0+Re),U.depthBuffer&&ye.push(Ae);const Ee=ve.__ignoreDepthValues!==void 0?ve.__ignoreDepthValues:!1;if(Ee===!1&&(U.depthBuffer&&(Se|=t.DEPTH_BUFFER_BIT),U.stencilBuffer&&(Se|=t.STENCIL_BUFFER_BIT)),je&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,ve.__webglColorRenderbuffer[Re]),Ee===!0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[Ae]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[Ae])),je){const Te=r.get(R[Re]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Te,0)}t.blitFramebuffer(0,0,ae,_e,0,0,ae,_e,Se,t.NEAREST),f&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,ye)}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),je)for(let Re=0;Re<R.length;Re++){n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.RENDERBUFFER,ve.__webglColorRenderbuffer[Re]);const Ee=r.get(R[Re]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,ve.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Re,t.TEXTURE_2D,Ee,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ve.__webglMultisampledFramebuffer)}}function se(U){return Math.min(m,U.samples)}function fe(U){const R=r.get(U);return l&&U.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function pe(U){const R=o.render.frame;x.get(U)!==R&&(x.set(U,R),U.update())}function de(U,R){const ae=U.colorSpace,_e=U.format,Se=U.type;return U.isCompressedTexture===!0||U.isVideoTexture===!0||U.format===eR||ae!==cm&&ae!==Gl&&(Wr.getTransfer(ae)===ga?l===!1?e.has("EXT_sRGB")===!0&&_e===Vl?(U.format=eR,U.minFilter=$l,U.generateMipmaps=!1):R=JZ.sRGBToLinear(R):(_e!==Vl||Se!==Qh)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",ae)),R}this.allocateTextureUnit=ue,this.resetTextureUnits=ee,this.setTexture2D=oe,this.setTexture2DArray=W,this.setTexture3D=re,this.setTextureCube=ce,this.rebindTextures=V,this.setupRenderTarget=Q,this.updateRenderTargetMipmap=G,this.updateMultisampleRenderTarget=J,this.setupDepthRenderbuffer=I,this.setupFrameBufferTexture=K,this.useMultisampledRTT=fe}function Uje(t,e,n){const r=n.isWebGL2;function i(s,o=Gl){let l;const c=Wr.getTransfer(o);if(s===Qh)return t.UNSIGNED_BYTE;if(s===HZ)return t.UNSIGNED_SHORT_4_4_4_4;if(s===qZ)return t.UNSIGNED_SHORT_5_5_5_1;if(s===dNe)return t.BYTE;if(s===uNe)return t.SHORT;if(s===XO)return t.UNSIGNED_SHORT;if(s===BZ)return t.INT;if(s===Mh)return t.UNSIGNED_INT;if(s===qu)return t.FLOAT;if(s===Y0)return r?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===mNe)return t.ALPHA;if(s===Vl)return t.RGBA;if(s===hNe)return t.LUMINANCE;if(s===pNe)return t.LUMINANCE_ALPHA;if(s===Df)return t.DEPTH_COMPONENT;if(s===Ox)return t.DEPTH_STENCIL;if(s===eR)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===fNe)return t.RED;if(s===$Z)return t.RED_INTEGER;if(s===gNe)return t.RG;if(s===VZ)return t.RG_INTEGER;if(s===GZ)return t.RGBA_INTEGER;if(s===eE||s===tE||s===nE||s===rE)if(c===ga)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===eE)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===tE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===nE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===rE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===eE)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===tE)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===nE)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===rE)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===Z6||s===J6||s===eq||s===tq)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===Z6)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===J6)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===eq)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===tq)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===WZ)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===nq||s===rq)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===nq)return c===ga?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===rq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===aq||s===iq||s===sq||s===oq||s===lq||s===cq||s===dq||s===uq||s===mq||s===hq||s===pq||s===fq||s===gq||s===bq)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===aq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===iq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===sq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===oq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===lq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===cq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===dq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===uq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===mq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===hq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===pq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===fq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===gq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===bq)return c===ga?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===aE||s===xq||s===yq)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===aE)return c===ga?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===xq)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===yq)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===bNe||s===vq||s===wq||s===Sq)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===aE)return l.COMPRESSED_RED_RGTC1_EXT;if(s===vq)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===wq)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===Sq)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===Ef?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:i}}class Bje extends Jo{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Qv extends Js{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Hje={type:"move"};class PE{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Qv,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 Qv,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ct,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ct),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Qv,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ct,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ct),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 i=null,s=null,o=null;const l=this._targetRay,c=this._grip,d=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(d&&e.hand){o=!0;for(const v of e.hand.values()){const g=n.getJointPose(v,r),b=this._getHandJoint(d,v);g!==null&&(b.matrix.fromArray(g.transform.matrix),b.matrix.decompose(b.position,b.rotation,b.scale),b.matrixWorldNeedsUpdate=!0,b.jointRadius=g.radius),b.visible=g!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,x=.005;d.inputState.pinching&&p>f+x?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-x&&(d.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&&(i=n.getPose(e.targetRaySpace,r),i===null&&s!==null&&(i=s),i!==null&&(l.matrix.fromArray(i.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,i.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(i.linearVelocity)):l.hasLinearVelocity=!1,i.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(i.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(Hje)))}return l!==null&&(l.visible=i!==null),c!==null&&(c.visible=s!==null),d!==null&&(d.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new Qv;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}class qje extends _g{constructor(e,n){super();const r=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,x=null;const v=n.getContextAttributes();let g=null,b=null;const _=[],C=[],P=new Gn;let N=null;const A=new Jo;A.layers.enable(1),A.viewport=new Xr;const T=new Jo;T.layers.enable(2),T.viewport=new Xr;const F=[A,T],k=new Bje;k.layers.enable(1),k.layers.enable(2);let D=null,H=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ce){let xe=_[ce];return xe===void 0&&(xe=new PE,_[ce]=xe),xe.getTargetRaySpace()},this.getControllerGrip=function(ce){let xe=_[ce];return xe===void 0&&(xe=new PE,_[ce]=xe),xe.getGripSpace()},this.getHand=function(ce){let xe=_[ce];return xe===void 0&&(xe=new PE,_[ce]=xe),xe.getHandSpace()};function z(ce){const xe=C.indexOf(ce.inputSource);if(xe===-1)return;const Ne=_[xe];Ne!==void 0&&(Ne.update(ce.inputSource,ce.frame,d||o),Ne.dispatchEvent({type:ce.type,data:ce.inputSource}))}function X(){i.removeEventListener("select",z),i.removeEventListener("selectstart",z),i.removeEventListener("selectend",z),i.removeEventListener("squeeze",z),i.removeEventListener("squeezestart",z),i.removeEventListener("squeezeend",z),i.removeEventListener("end",X),i.removeEventListener("inputsourceschange",L);for(let ce=0;ce<_.length;ce++){const xe=C[ce];xe!==null&&(C[ce]=null,_[ce].disconnect(xe))}D=null,H=null,e.setRenderTarget(g),f=null,p=null,m=null,i=null,b=null,re.stop(),r.isPresenting=!1,e.setPixelRatio(N),e.setSize(P.width,P.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(ce){s=ce,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ce){l=ce,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||o},this.setReferenceSpace=function(ce){d=ce},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m},this.getFrame=function(){return x},this.getSession=function(){return i},this.setSession=async function(ce){if(i=ce,i!==null){if(g=e.getRenderTarget(),i.addEventListener("select",z),i.addEventListener("selectstart",z),i.addEventListener("selectend",z),i.addEventListener("squeeze",z),i.addEventListener("squeezestart",z),i.addEventListener("squeezeend",z),i.addEventListener("end",X),i.addEventListener("inputsourceschange",L),v.xrCompatible!==!0&&await n.makeXRCompatible(),N=e.getPixelRatio(),e.getSize(P),i.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const xe={antialias:i.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,xe),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),b=new ng(f.framebufferWidth,f.framebufferHeight,{format:Vl,type:Qh,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let xe=null,Ne=null,$=null;v.depth&&($=v.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,xe=v.stencil?Ox:Df,Ne=v.stencil?Ef:Mh);const Y={colorFormat:n.RGBA8,depthFormat:$,scaleFactor:s};m=new XRWebGLBinding(i,n),p=m.createProjectionLayer(Y),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),b=new ng(p.textureWidth,p.textureHeight,{format:Vl,type:Qh,depthTexture:new uJ(p.textureWidth,p.textureHeight,Ne,void 0,void 0,void 0,void 0,void 0,void 0,xe),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const E=e.properties.get(b);E.__ignoreDepthValues=p.ignoreDepthValues}b.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),re.setContext(i),re.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode};function L(ce){for(let xe=0;xe<ce.removed.length;xe++){const Ne=ce.removed[xe],$=C.indexOf(Ne);$>=0&&(C[$]=null,_[$].disconnect(Ne))}for(let xe=0;xe<ce.added.length;xe++){const Ne=ce.added[xe];let $=C.indexOf(Ne);if($===-1){for(let E=0;E<_.length;E++)if(E>=C.length){C.push(Ne),$=E;break}else if(C[E]===null){C[E]=Ne,$=E;break}if($===-1)break}const Y=_[$];Y&&Y.connect(Ne)}}const ne=new ct,ie=new ct;function ee(ce,xe,Ne){ne.setFromMatrixPosition(xe.matrixWorld),ie.setFromMatrixPosition(Ne.matrixWorld);const $=ne.distanceTo(ie),Y=xe.projectionMatrix.elements,E=Ne.projectionMatrix.elements,j=Y[14]/(Y[10]-1),O=Y[14]/(Y[10]+1),K=(Y[9]+1)/Y[5],B=(Y[9]-1)/Y[5],he=(Y[8]-1)/Y[0],I=(E[8]+1)/E[0],V=j*he,Q=j*I,G=$/(-he+I),J=G*-he;xe.matrixWorld.decompose(ce.position,ce.quaternion,ce.scale),ce.translateX(J),ce.translateZ(G),ce.matrixWorld.compose(ce.position,ce.quaternion,ce.scale),ce.matrixWorldInverse.copy(ce.matrixWorld).invert();const se=j+G,fe=O+G,pe=V-J,de=Q+($-J),U=K*O/fe*se,R=B*O/fe*se;ce.projectionMatrix.makePerspective(pe,de,U,R,se,fe),ce.projectionMatrixInverse.copy(ce.projectionMatrix).invert()}function ue(ce,xe){xe===null?ce.matrixWorld.copy(ce.matrix):ce.matrixWorld.multiplyMatrices(xe.matrixWorld,ce.matrix),ce.matrixWorldInverse.copy(ce.matrixWorld).invert()}this.updateCamera=function(ce){if(i===null)return;k.near=T.near=A.near=ce.near,k.far=T.far=A.far=ce.far,(D!==k.near||H!==k.far)&&(i.updateRenderState({depthNear:k.near,depthFar:k.far}),D=k.near,H=k.far);const xe=ce.parent,Ne=k.cameras;ue(k,xe);for(let $=0;$<Ne.length;$++)ue(Ne[$],xe);Ne.length===2?ee(k,A,T):k.projectionMatrix.copy(A.projectionMatrix),le(ce,k,xe)};function le(ce,xe,Ne){Ne===null?ce.matrix.copy(xe.matrixWorld):(ce.matrix.copy(Ne.matrixWorld),ce.matrix.invert(),ce.matrix.multiply(xe.matrixWorld)),ce.matrix.decompose(ce.position,ce.quaternion,ce.scale),ce.updateMatrixWorld(!0),ce.projectionMatrix.copy(xe.projectionMatrix),ce.projectionMatrixInverse.copy(xe.projectionMatrixInverse),ce.isPerspectiveCamera&&(ce.fov=Z0*2*Math.atan(1/ce.projectionMatrix.elements[5]),ce.zoom=1)}this.getCamera=function(){return k},this.getFoveation=function(){if(!(p===null&&f===null))return c},this.setFoveation=function(ce){c=ce,p!==null&&(p.fixedFoveation=ce),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=ce)};let oe=null;function W(ce,xe){if(u=xe.getViewerPose(d||o),x=xe,u!==null){const Ne=u.views;f!==null&&(e.setRenderTargetFramebuffer(b,f.framebuffer),e.setRenderTarget(b));let $=!1;Ne.length!==k.cameras.length&&(k.cameras.length=0,$=!0);for(let Y=0;Y<Ne.length;Y++){const E=Ne[Y];let j=null;if(f!==null)j=f.getViewport(E);else{const K=m.getViewSubImage(p,E);j=K.viewport,Y===0&&(e.setRenderTargetTextures(b,K.colorTexture,p.ignoreDepthValues?void 0:K.depthStencilTexture),e.setRenderTarget(b))}let O=F[Y];O===void 0&&(O=new Jo,O.layers.enable(Y),O.viewport=new Xr,F[Y]=O),O.matrix.fromArray(E.transform.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale),O.projectionMatrix.fromArray(E.projectionMatrix),O.projectionMatrixInverse.copy(O.projectionMatrix).invert(),O.viewport.set(j.x,j.y,j.width,j.height),Y===0&&(k.matrix.copy(O.matrix),k.matrix.decompose(k.position,k.quaternion,k.scale)),$===!0&&k.cameras.push(O)}}for(let Ne=0;Ne<_.length;Ne++){const $=C[Ne],Y=_[Ne];$!==null&&Y!==void 0&&Y.update($,xe,d||o)}oe&&oe(ce,xe),xe.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:xe}),x=null}const re=new dJ;re.setAnimationLoop(W),this.setAnimationLoop=function(ce){oe=ce},this.dispose=function(){}}}function $je(t,e){function n(g,b){g.matrixAutoUpdate===!0&&g.updateMatrix(),b.value.copy(g.matrix)}function r(g,b){b.color.getRGB(g.fogColor.value,oJ(t)),b.isFog?(g.fogNear.value=b.near,g.fogFar.value=b.far):b.isFogExp2&&(g.fogDensity.value=b.density)}function i(g,b,_,C,P){b.isMeshBasicMaterial||b.isMeshLambertMaterial?s(g,b):b.isMeshToonMaterial?(s(g,b),m(g,b)):b.isMeshPhongMaterial?(s(g,b),u(g,b)):b.isMeshStandardMaterial?(s(g,b),p(g,b),b.isMeshPhysicalMaterial&&f(g,b,P)):b.isMeshMatcapMaterial?(s(g,b),x(g,b)):b.isMeshDepthMaterial?s(g,b):b.isMeshDistanceMaterial?(s(g,b),v(g,b)):b.isMeshNormalMaterial?s(g,b):b.isLineBasicMaterial?(o(g,b),b.isLineDashedMaterial&&l(g,b)):b.isPointsMaterial?c(g,b,_,C):b.isSpriteMaterial?d(g,b):b.isShadowMaterial?(g.color.value.copy(b.color),g.opacity.value=b.opacity):b.isShaderMaterial&&(b.uniformsNeedUpdate=!1)}function s(g,b){g.opacity.value=b.opacity,b.color&&g.diffuse.value.copy(b.color),b.emissive&&g.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity),b.map&&(g.map.value=b.map,n(b.map,g.mapTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.bumpMap&&(g.bumpMap.value=b.bumpMap,n(b.bumpMap,g.bumpMapTransform),g.bumpScale.value=b.bumpScale,b.side===jo&&(g.bumpScale.value*=-1)),b.normalMap&&(g.normalMap.value=b.normalMap,n(b.normalMap,g.normalMapTransform),g.normalScale.value.copy(b.normalScale),b.side===jo&&g.normalScale.value.negate()),b.displacementMap&&(g.displacementMap.value=b.displacementMap,n(b.displacementMap,g.displacementMapTransform),g.displacementScale.value=b.displacementScale,g.displacementBias.value=b.displacementBias),b.emissiveMap&&(g.emissiveMap.value=b.emissiveMap,n(b.emissiveMap,g.emissiveMapTransform)),b.specularMap&&(g.specularMap.value=b.specularMap,n(b.specularMap,g.specularMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest);const _=e.get(b).envMap;if(_&&(g.envMap.value=_,g.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=b.reflectivity,g.ior.value=b.ior,g.refractionRatio.value=b.refractionRatio),b.lightMap){g.lightMap.value=b.lightMap;const C=t._useLegacyLights===!0?Math.PI:1;g.lightMapIntensity.value=b.lightMapIntensity*C,n(b.lightMap,g.lightMapTransform)}b.aoMap&&(g.aoMap.value=b.aoMap,g.aoMapIntensity.value=b.aoMapIntensity,n(b.aoMap,g.aoMapTransform))}function o(g,b){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,b.map&&(g.map.value=b.map,n(b.map,g.mapTransform))}function l(g,b){g.dashSize.value=b.dashSize,g.totalSize.value=b.dashSize+b.gapSize,g.scale.value=b.scale}function c(g,b,_,C){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,g.size.value=b.size*_,g.scale.value=C*.5,b.map&&(g.map.value=b.map,n(b.map,g.uvTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest)}function d(g,b){g.diffuse.value.copy(b.color),g.opacity.value=b.opacity,g.rotation.value=b.rotation,b.map&&(g.map.value=b.map,n(b.map,g.mapTransform)),b.alphaMap&&(g.alphaMap.value=b.alphaMap,n(b.alphaMap,g.alphaMapTransform)),b.alphaTest>0&&(g.alphaTest.value=b.alphaTest)}function u(g,b){g.specular.value.copy(b.specular),g.shininess.value=Math.max(b.shininess,1e-4)}function m(g,b){b.gradientMap&&(g.gradientMap.value=b.gradientMap)}function p(g,b){g.metalness.value=b.metalness,b.metalnessMap&&(g.metalnessMap.value=b.metalnessMap,n(b.metalnessMap,g.metalnessMapTransform)),g.roughness.value=b.roughness,b.roughnessMap&&(g.roughnessMap.value=b.roughnessMap,n(b.roughnessMap,g.roughnessMapTransform)),e.get(b).envMap&&(g.envMapIntensity.value=b.envMapIntensity)}function f(g,b,_){g.ior.value=b.ior,b.sheen>0&&(g.sheenColor.value.copy(b.sheenColor).multiplyScalar(b.sheen),g.sheenRoughness.value=b.sheenRoughness,b.sheenColorMap&&(g.sheenColorMap.value=b.sheenColorMap,n(b.sheenColorMap,g.sheenColorMapTransform)),b.sheenRoughnessMap&&(g.sheenRoughnessMap.value=b.sheenRoughnessMap,n(b.sheenRoughnessMap,g.sheenRoughnessMapTransform))),b.clearcoat>0&&(g.clearcoat.value=b.clearcoat,g.clearcoatRoughness.value=b.clearcoatRoughness,b.clearcoatMap&&(g.clearcoatMap.value=b.clearcoatMap,n(b.clearcoatMap,g.clearcoatMapTransform)),b.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=b.clearcoatRoughnessMap,n(b.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),b.clearcoatNormalMap&&(g.clearcoatNormalMap.value=b.clearcoatNormalMap,n(b.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(b.clearcoatNormalScale),b.side===jo&&g.clearcoatNormalScale.value.negate())),b.iridescence>0&&(g.iridescence.value=b.iridescence,g.iridescenceIOR.value=b.iridescenceIOR,g.iridescenceThicknessMinimum.value=b.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=b.iridescenceThicknessRange[1],b.iridescenceMap&&(g.iridescenceMap.value=b.iridescenceMap,n(b.iridescenceMap,g.iridescenceMapTransform)),b.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=b.iridescenceThicknessMap,n(b.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),b.transmission>0&&(g.transmission.value=b.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),b.transmissionMap&&(g.transmissionMap.value=b.transmissionMap,n(b.transmissionMap,g.transmissionMapTransform)),g.thickness.value=b.thickness,b.thicknessMap&&(g.thicknessMap.value=b.thicknessMap,n(b.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=b.attenuationDistance,g.attenuationColor.value.copy(b.attenuationColor)),b.anisotropy>0&&(g.anisotropyVector.value.set(b.anisotropy*Math.cos(b.anisotropyRotation),b.anisotropy*Math.sin(b.anisotropyRotation)),b.anisotropyMap&&(g.anisotropyMap.value=b.anisotropyMap,n(b.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=b.specularIntensity,g.specularColor.value.copy(b.specularColor),b.specularColorMap&&(g.specularColorMap.value=b.specularColorMap,n(b.specularColorMap,g.specularColorMapTransform)),b.specularIntensityMap&&(g.specularIntensityMap.value=b.specularIntensityMap,n(b.specularIntensityMap,g.specularIntensityMapTransform))}function x(g,b){b.matcap&&(g.matcap.value=b.matcap)}function v(g,b){const _=e.get(b).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function Vje(t,e,n,r){let i={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(_,C){const P=C.program;r.uniformBlockBinding(_,P)}function d(_,C){let P=i[_.id];P===void 0&&(x(_),P=u(_),i[_.id]=P,_.addEventListener("dispose",g));const N=C.program;r.updateUBOMapping(_,N);const A=e.render.frame;s[_.id]!==A&&(p(_),s[_.id]=A)}function u(_){const C=m();_.__bindingPointIndex=C;const P=t.createBuffer(),N=_.__size,A=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,P),t.bufferData(t.UNIFORM_BUFFER,N,A),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,C,P),P}function m(){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 p(_){const C=i[_.id],P=_.uniforms,N=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,C);for(let A=0,T=P.length;A<T;A++){const F=P[A];if(f(F,A,N)===!0){const k=F.__offset,D=Array.isArray(F.value)?F.value:[F.value];let H=0;for(let z=0;z<D.length;z++){const X=D[z],L=v(X);typeof X=="number"?(F.__data[0]=X,t.bufferSubData(t.UNIFORM_BUFFER,k+H,F.__data)):X.isMatrix3?(F.__data[0]=X.elements[0],F.__data[1]=X.elements[1],F.__data[2]=X.elements[2],F.__data[3]=X.elements[0],F.__data[4]=X.elements[3],F.__data[5]=X.elements[4],F.__data[6]=X.elements[5],F.__data[7]=X.elements[0],F.__data[8]=X.elements[6],F.__data[9]=X.elements[7],F.__data[10]=X.elements[8],F.__data[11]=X.elements[0]):(X.toArray(F.__data,H),H+=L.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,k,F.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(_,C,P){const N=_.value;if(P[C]===void 0){if(typeof N=="number")P[C]=N;else{const A=Array.isArray(N)?N:[N],T=[];for(let F=0;F<A.length;F++)T.push(A[F].clone());P[C]=T}return!0}else if(typeof N=="number"){if(P[C]!==N)return P[C]=N,!0}else{const A=Array.isArray(P[C])?P[C]:[P[C]],T=Array.isArray(N)?N:[N];for(let F=0;F<A.length;F++){const k=A[F];if(k.equals(T[F])===!1)return k.copy(T[F]),!0}}return!1}function x(_){const C=_.uniforms;let P=0;const N=16;let A=0;for(let T=0,F=C.length;T<F;T++){const k=C[T],D={boundary:0,storage:0},H=Array.isArray(k.value)?k.value:[k.value];for(let z=0,X=H.length;z<X;z++){const L=H[z],ne=v(L);D.boundary+=ne.boundary,D.storage+=ne.storage}if(k.__data=new Float32Array(D.storage/Float32Array.BYTES_PER_ELEMENT),k.__offset=P,T>0){A=P%N;const z=N-A;A!==0&&z-D.boundary<0&&(P+=N-A,k.__offset=P)}P+=D.storage}return A=P%N,A>0&&(P+=N-A),_.__size=P,_.__cache={},this}function v(_){const C={boundary:0,storage:0};return typeof _=="number"?(C.boundary=4,C.storage=4):_.isVector2?(C.boundary=8,C.storage=8):_.isVector3||_.isColor?(C.boundary=16,C.storage=12):_.isVector4?(C.boundary=16,C.storage=16):_.isMatrix3?(C.boundary=48,C.storage=48):_.isMatrix4?(C.boundary=64,C.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.",_),C}function g(_){const C=_.target;C.removeEventListener("dispose",g);const P=o.indexOf(C.__bindingPointIndex);o.splice(P,1),t.deleteBuffer(i[C.id]),delete i[C.id],delete s[C.id]}function b(){for(const _ in i)t.deleteBuffer(i[_]);o=[],i={},s={}}return{bind:c,update:d,dispose:b}}class rR{constructor(e={}){const{canvas:n=HNe(),context:r=null,depth:i=!0,stencil:s=!0,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:d=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:m=!1}=e;this.isWebGLRenderer=!0;let p;r!==null?p=r.getContextAttributes().alpha:p=o;const f=new Uint32Array(4),x=new Int32Array(4);let v=null,g=null;const b=[],_=[];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=ds,this._useLegacyLights=!1,this.toneMapping=Yh,this.toneMappingExposure=1;const C=this;let P=!1,N=0,A=0,T=null,F=-1,k=null;const D=new Xr,H=new Xr;let z=null;const X=new Dn(0);let L=0,ne=n.width,ie=n.height,ee=1,ue=null,le=null;const oe=new Xr(0,0,ne,ie),W=new Xr(0,0,ne,ie);let re=!1;const ce=new HP;let xe=!1,Ne=!1,$=null;const Y=new da,E=new Gn,j=new ct,O={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function K(){return T===null?ee:1}let B=r;function he(ze,st){for(let ht=0;ht<ze.length;ht++){const rt=ze[ht],Le=n.getContext(rt,st);if(Le!==null)return Le}return null}try{const ze={alpha:!0,depth:i,stencil:s,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:d,powerPreference:u,failIfMajorPerformanceCaveat:m};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${zP}`),n.addEventListener("webglcontextlost",Ie,!1),n.addEventListener("webglcontextrestored",be,!1),n.addEventListener("webglcontextcreationerror",$e,!1),B===null){const st=["webgl2","webgl","experimental-webgl"];if(C.isWebGL1Renderer===!0&&st.shift(),B=he(st,ze),B===null)throw he(st)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&B instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),B.getShaderPrecisionFormat===void 0&&(B.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(ze){throw console.error("THREE.WebGLRenderer: "+ze.message),ze}let I,V,Q,G,J,se,fe,pe,de,U,R,ae,_e,Se,ye,Ae,ve,je,Re,Ee,Te,Me,Be,Ke;function tt(){I=new nAe(B),V=new XTe(B,I,e),I.init(V),Me=new Uje(B,I,V),Q=new Ije(B,I,V),G=new iAe(B),J=new kje,se=new zje(B,I,Q,J,V,Me,G),fe=new QTe(C),pe=new tAe(C),de=new mCe(B,V),Be=new WTe(B,I,de,V),U=new rAe(B,de,G,Be),R=new cAe(B,U,de,G),Re=new lAe(B,V,se),Ae=new YTe(J),ae=new _je(C,fe,pe,I,V,Be,Ae),_e=new $je(C,J),Se=new Cje,ye=new Eje(I,V),je=new GTe(C,fe,pe,Q,R,p,c),ve=new Oje(C,R,V),Ke=new Vje(B,G,V,Q),Ee=new KTe(B,I,G,V),Te=new aAe(B,I,G,V),G.programs=ae.programs,C.capabilities=V,C.extensions=I,C.properties=J,C.renderLists=Se,C.shadowMap=ve,C.state=Q,C.info=G}tt();const te=new qje(C,B);this.xr=te,this.getContext=function(){return B},this.getContextAttributes=function(){return B.getContextAttributes()},this.forceContextLoss=function(){const ze=I.get("WEBGL_lose_context");ze&&ze.loseContext()},this.forceContextRestore=function(){const ze=I.get("WEBGL_lose_context");ze&&ze.restoreContext()},this.getPixelRatio=function(){return ee},this.setPixelRatio=function(ze){ze!==void 0&&(ee=ze,this.setSize(ne,ie,!1))},this.getSize=function(ze){return ze.set(ne,ie)},this.setSize=function(ze,st,ht=!0){if(te.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}ne=ze,ie=st,n.width=Math.floor(ze*ee),n.height=Math.floor(st*ee),ht===!0&&(n.style.width=ze+"px",n.style.height=st+"px"),this.setViewport(0,0,ze,st)},this.getDrawingBufferSize=function(ze){return ze.set(ne*ee,ie*ee).floor()},this.setDrawingBufferSize=function(ze,st,ht){ne=ze,ie=st,ee=ht,n.width=Math.floor(ze*ht),n.height=Math.floor(st*ht),this.setViewport(0,0,ze,st)},this.getCurrentViewport=function(ze){return ze.copy(D)},this.getViewport=function(ze){return ze.copy(oe)},this.setViewport=function(ze,st,ht,rt){ze.isVector4?oe.set(ze.x,ze.y,ze.z,ze.w):oe.set(ze,st,ht,rt),Q.viewport(D.copy(oe).multiplyScalar(ee).floor())},this.getScissor=function(ze){return ze.copy(W)},this.setScissor=function(ze,st,ht,rt){ze.isVector4?W.set(ze.x,ze.y,ze.z,ze.w):W.set(ze,st,ht,rt),Q.scissor(H.copy(W).multiplyScalar(ee).floor())},this.getScissorTest=function(){return re},this.setScissorTest=function(ze){Q.setScissorTest(re=ze)},this.setOpaqueSort=function(ze){ue=ze},this.setTransparentSort=function(ze){le=ze},this.getClearColor=function(ze){return ze.copy(je.getClearColor())},this.setClearColor=function(){je.setClearColor.apply(je,arguments)},this.getClearAlpha=function(){return je.getClearAlpha()},this.setClearAlpha=function(){je.setClearAlpha.apply(je,arguments)},this.clear=function(ze=!0,st=!0,ht=!0){let rt=0;if(ze){let Le=!1;if(T!==null){const Oe=T.texture.format;Le=Oe===GZ||Oe===VZ||Oe===$Z}if(Le){const Oe=T.texture.type,Ce=Oe===Qh||Oe===Mh||Oe===XO||Oe===Ef||Oe===HZ||Oe===qZ,We=je.getClearColor(),Je=je.getClearAlpha(),Xe=We.r,Ye=We.g,St=We.b;Ce?(f[0]=Xe,f[1]=Ye,f[2]=St,f[3]=Je,B.clearBufferuiv(B.COLOR,0,f)):(x[0]=Xe,x[1]=Ye,x[2]=St,x[3]=Je,B.clearBufferiv(B.COLOR,0,x))}else rt|=B.COLOR_BUFFER_BIT}st&&(rt|=B.DEPTH_BUFFER_BIT),ht&&(rt|=B.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),B.clear(rt)},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",Ie,!1),n.removeEventListener("webglcontextrestored",be,!1),n.removeEventListener("webglcontextcreationerror",$e,!1),Se.dispose(),ye.dispose(),J.dispose(),fe.dispose(),pe.dispose(),R.dispose(),Be.dispose(),Ke.dispose(),ae.dispose(),te.dispose(),te.removeEventListener("sessionstart",vt),te.removeEventListener("sessionend",wt),$&&($.dispose(),$=null),$t.stop()};function Ie(ze){ze.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),P=!0}function be(){console.log("THREE.WebGLRenderer: Context Restored."),P=!1;const ze=G.autoReset,st=ve.enabled,ht=ve.autoUpdate,rt=ve.needsUpdate,Le=ve.type;tt(),G.autoReset=ze,ve.enabled=st,ve.autoUpdate=ht,ve.needsUpdate=rt,ve.type=Le}function $e(ze){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",ze.statusMessage)}function He(ze){const st=ze.target;st.removeEventListener("dispose",He),ge(st)}function ge(ze){Pe(ze),J.remove(ze)}function Pe(ze){const st=J.get(ze).programs;st!==void 0&&(st.forEach(function(ht){ae.releaseProgram(ht)}),ze.isShaderMaterial&&ae.releaseShaderCache(ze))}this.renderBufferDirect=function(ze,st,ht,rt,Le,Oe){st===null&&(st=O);const Ce=Le.isMesh&&Le.matrixWorld.determinant()<0,We=pt(ze,st,ht,rt,Le);Q.setMaterial(rt,Ce);let Je=ht.index,Xe=1;if(rt.wireframe===!0){if(Je=U.getWireframeAttribute(ht),Je===void 0)return;Xe=2}const Ye=ht.drawRange,St=ht.attributes.position;let et=Ye.start*Xe,jt=(Ye.start+Ye.count)*Xe;Oe!==null&&(et=Math.max(et,Oe.start*Xe),jt=Math.min(jt,(Oe.start+Oe.count)*Xe)),Je!==null?(et=Math.max(et,0),jt=Math.min(jt,Je.count)):St!=null&&(et=Math.max(et,0),jt=Math.min(jt,St.count));const bt=jt-et;if(bt<0||bt===1/0)return;Be.setup(Le,rt,We,ht,Je);let Ve,gt=Ee;if(Je!==null&&(Ve=de.get(Je),gt=Te,gt.setIndex(Ve)),Le.isMesh)rt.wireframe===!0?(Q.setLineWidth(rt.wireframeLinewidth*K()),gt.setMode(B.LINES)):gt.setMode(B.TRIANGLES);else if(Le.isLine){let Et=rt.linewidth;Et===void 0&&(Et=1),Q.setLineWidth(Et*K()),Le.isLineSegments?gt.setMode(B.LINES):Le.isLineLoop?gt.setMode(B.LINE_LOOP):gt.setMode(B.LINE_STRIP)}else Le.isPoints?gt.setMode(B.POINTS):Le.isSprite&>.setMode(B.TRIANGLES);if(Le.isBatchedMesh)gt.renderMultiDraw(Le._multiDrawStarts,Le._multiDrawCounts,Le._multiDrawCount);else if(Le.isInstancedMesh)gt.renderInstances(et,bt,Le.count);else if(ht.isInstancedBufferGeometry){const Et=ht._maxInstanceCount!==void 0?ht._maxInstanceCount:1/0,Gt=Math.min(ht.instanceCount,Et);gt.renderInstances(et,bt,Gt)}else gt.render(et,bt)};function qe(ze,st,ht){ze.transparent===!0&&ze.side===Ru&&ze.forceSinglePass===!1?(ze.side=jo,ze.needsUpdate=!0,Ft(ze,st,ht),ze.side=op,ze.needsUpdate=!0,Ft(ze,st,ht),ze.side=Ru):Ft(ze,st,ht)}this.compile=function(ze,st,ht=null){ht===null&&(ht=ze),g=ye.get(ht),g.init(),_.push(g),ht.traverseVisible(function(Le){Le.isLight&&Le.layers.test(st.layers)&&(g.pushLight(Le),Le.castShadow&&g.pushShadow(Le))}),ze!==ht&&ze.traverseVisible(function(Le){Le.isLight&&Le.layers.test(st.layers)&&(g.pushLight(Le),Le.castShadow&&g.pushShadow(Le))}),g.setupLights(C._useLegacyLights);const rt=new Set;return ze.traverse(function(Le){const Oe=Le.material;if(Oe)if(Array.isArray(Oe))for(let Ce=0;Ce<Oe.length;Ce++){const We=Oe[Ce];qe(We,ht,Le),rt.add(We)}else qe(Oe,ht,Le),rt.add(Oe)}),_.pop(),g=null,rt},this.compileAsync=function(ze,st,ht=null){const rt=this.compile(ze,st,ht);return new Promise(Le=>{function Oe(){if(rt.forEach(function(Ce){J.get(Ce).currentProgram.isReady()&&rt.delete(Ce)}),rt.size===0){Le(ze);return}setTimeout(Oe,10)}I.get("KHR_parallel_shader_compile")!==null?Oe():setTimeout(Oe,10)})};let Ze=null;function ut(ze){Ze&&Ze(ze)}function vt(){$t.stop()}function wt(){$t.start()}const $t=new dJ;$t.setAnimationLoop(ut),typeof self<"u"&&$t.setContext(self),this.setAnimationLoop=function(ze){Ze=ze,te.setAnimationLoop(ze),ze===null?$t.stop():$t.start()},te.addEventListener("sessionstart",vt),te.addEventListener("sessionend",wt),this.render=function(ze,st){if(st!==void 0&&st.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(P===!0)return;ze.matrixWorldAutoUpdate===!0&&ze.updateMatrixWorld(),st.parent===null&&st.matrixWorldAutoUpdate===!0&&st.updateMatrixWorld(),te.enabled===!0&&te.isPresenting===!0&&(te.cameraAutoUpdate===!0&&te.updateCamera(st),st=te.getCamera()),ze.isScene===!0&&ze.onBeforeRender(C,ze,st,T),g=ye.get(ze,_.length),g.init(),_.push(g),Y.multiplyMatrices(st.projectionMatrix,st.matrixWorldInverse),ce.setFromProjectionMatrix(Y),Ne=this.localClippingEnabled,xe=Ae.init(this.clippingPlanes,Ne),v=Se.get(ze,b.length),v.init(),b.push(v),Qt(ze,st,0,C.sortObjects),v.finish(),C.sortObjects===!0&&v.sort(ue,le),this.info.render.frame++,xe===!0&&Ae.beginShadows();const ht=g.state.shadowsArray;if(ve.render(ht,ze,st),xe===!0&&Ae.endShadows(),this.info.autoReset===!0&&this.info.reset(),je.render(v,ze),g.setupLights(C._useLegacyLights),st.isArrayCamera){const rt=st.cameras;for(let Le=0,Oe=rt.length;Le<Oe;Le++){const Ce=rt[Le];en(v,ze,Ce,Ce.viewport)}}else en(v,ze,st);T!==null&&(se.updateMultisampleRenderTarget(T),se.updateRenderTargetMipmap(T)),ze.isScene===!0&&ze.onAfterRender(C,ze,st),Be.resetDefaultState(),F=-1,k=null,_.pop(),_.length>0?g=_[_.length-1]:g=null,b.pop(),b.length>0?v=b[b.length-1]:v=null};function Qt(ze,st,ht,rt){if(ze.visible===!1)return;if(ze.layers.test(st.layers)){if(ze.isGroup)ht=ze.renderOrder;else if(ze.isLOD)ze.autoUpdate===!0&&ze.update(st);else if(ze.isLight)g.pushLight(ze),ze.castShadow&&g.pushShadow(ze);else if(ze.isSprite){if(!ze.frustumCulled||ce.intersectsSprite(ze)){rt&&j.setFromMatrixPosition(ze.matrixWorld).applyMatrix4(Y);const Ce=R.update(ze),We=ze.material;We.visible&&v.push(ze,Ce,We,ht,j.z,null)}}else if((ze.isMesh||ze.isLine||ze.isPoints)&&(!ze.frustumCulled||ce.intersectsObject(ze))){const Ce=R.update(ze),We=ze.material;if(rt&&(ze.boundingSphere!==void 0?(ze.boundingSphere===null&&ze.computeBoundingSphere(),j.copy(ze.boundingSphere.center)):(Ce.boundingSphere===null&&Ce.computeBoundingSphere(),j.copy(Ce.boundingSphere.center)),j.applyMatrix4(ze.matrixWorld).applyMatrix4(Y)),Array.isArray(We)){const Je=Ce.groups;for(let Xe=0,Ye=Je.length;Xe<Ye;Xe++){const St=Je[Xe],et=We[St.materialIndex];et&&et.visible&&v.push(ze,Ce,et,ht,j.z,St)}}else We.visible&&v.push(ze,Ce,We,ht,j.z,null)}}const Oe=ze.children;for(let Ce=0,We=Oe.length;Ce<We;Ce++)Qt(Oe[Ce],st,ht,rt)}function en(ze,st,ht,rt){const Le=ze.opaque,Oe=ze.transmissive,Ce=ze.transparent;g.setupLightsView(ht),xe===!0&&Ae.setGlobalState(C.clippingPlanes,ht),Oe.length>0&&Xt(Le,Oe,st,ht),rt&&Q.viewport(D.copy(rt)),Le.length>0&&tn(Le,st,ht),Oe.length>0&&tn(Oe,st,ht),Ce.length>0&&tn(Ce,st,ht),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function Xt(ze,st,ht,rt){if((ht.isScene===!0?ht.overrideMaterial:null)!==null)return;const Oe=V.isWebGL2;$===null&&($=new ng(1,1,{generateMipmaps:!0,type:I.has("EXT_color_buffer_half_float")?Y0:Qh,minFilter:X0,samples:Oe?4:0})),C.getDrawingBufferSize(E),Oe?$.setSize(E.x,E.y):$.setSize(_N(E.x),_N(E.y));const Ce=C.getRenderTarget();C.setRenderTarget($),C.getClearColor(X),L=C.getClearAlpha(),L<1&&C.setClearColor(16777215,.5),C.clear();const We=C.toneMapping;C.toneMapping=Yh,tn(ze,ht,rt),se.updateMultisampleRenderTarget($),se.updateRenderTargetMipmap($);let Je=!1;for(let Xe=0,Ye=st.length;Xe<Ye;Xe++){const St=st[Xe],et=St.object,jt=St.geometry,bt=St.material,Ve=St.group;if(bt.side===Ru&&et.layers.test(rt.layers)){const gt=bt.side;bt.side=jo,bt.needsUpdate=!0,Ge(et,ht,rt,jt,bt,Ve),bt.side=gt,bt.needsUpdate=!0,Je=!0}}Je===!0&&(se.updateMultisampleRenderTarget($),se.updateRenderTargetMipmap($)),C.setRenderTarget(Ce),C.setClearColor(X,L),C.toneMapping=We}function tn(ze,st,ht){const rt=st.isScene===!0?st.overrideMaterial:null;for(let Le=0,Oe=ze.length;Le<Oe;Le++){const Ce=ze[Le],We=Ce.object,Je=Ce.geometry,Xe=rt===null?Ce.material:rt,Ye=Ce.group;We.layers.test(ht.layers)&&Ge(We,st,ht,Je,Xe,Ye)}}function Ge(ze,st,ht,rt,Le,Oe){ze.onBeforeRender(C,st,ht,rt,Le,Oe),ze.modelViewMatrix.multiplyMatrices(ht.matrixWorldInverse,ze.matrixWorld),ze.normalMatrix.getNormalMatrix(ze.modelViewMatrix),Le.onBeforeRender(C,st,ht,rt,ze,Oe),Le.transparent===!0&&Le.side===Ru&&Le.forceSinglePass===!1?(Le.side=jo,Le.needsUpdate=!0,C.renderBufferDirect(ht,st,rt,Le,ze,Oe),Le.side=op,Le.needsUpdate=!0,C.renderBufferDirect(ht,st,rt,Le,ze,Oe),Le.side=Ru):C.renderBufferDirect(ht,st,rt,Le,ze,Oe),ze.onAfterRender(C,st,ht,rt,Le,Oe)}function Ft(ze,st,ht){st.isScene!==!0&&(st=O);const rt=J.get(ze),Le=g.state.lights,Oe=g.state.shadowsArray,Ce=Le.state.version,We=ae.getParameters(ze,Le.state,Oe,st,ht),Je=ae.getProgramCacheKey(We);let Xe=rt.programs;rt.environment=ze.isMeshStandardMaterial?st.environment:null,rt.fog=st.fog,rt.envMap=(ze.isMeshStandardMaterial?pe:fe).get(ze.envMap||rt.environment),Xe===void 0&&(ze.addEventListener("dispose",He),Xe=new Map,rt.programs=Xe);let Ye=Xe.get(Je);if(Ye!==void 0){if(rt.currentProgram===Ye&&rt.lightsStateVersion===Ce)return Pt(ze,We),Ye}else We.uniforms=ae.getUniforms(ze),ze.onBuild(ht,We,C),ze.onBeforeCompile(We,C),Ye=ae.acquireProgram(We,Je),Xe.set(Je,Ye),rt.uniforms=We.uniforms;const St=rt.uniforms;return(!ze.isShaderMaterial&&!ze.isRawShaderMaterial||ze.clipping===!0)&&(St.clippingPlanes=Ae.uniform),Pt(ze,We),rt.needsLights=Ut(ze),rt.lightsStateVersion=Ce,rt.needsLights&&(St.ambientLightColor.value=Le.state.ambient,St.lightProbe.value=Le.state.probe,St.directionalLights.value=Le.state.directional,St.directionalLightShadows.value=Le.state.directionalShadow,St.spotLights.value=Le.state.spot,St.spotLightShadows.value=Le.state.spotShadow,St.rectAreaLights.value=Le.state.rectArea,St.ltc_1.value=Le.state.rectAreaLTC1,St.ltc_2.value=Le.state.rectAreaLTC2,St.pointLights.value=Le.state.point,St.pointLightShadows.value=Le.state.pointShadow,St.hemisphereLights.value=Le.state.hemi,St.directionalShadowMap.value=Le.state.directionalShadowMap,St.directionalShadowMatrix.value=Le.state.directionalShadowMatrix,St.spotShadowMap.value=Le.state.spotShadowMap,St.spotLightMatrix.value=Le.state.spotLightMatrix,St.spotLightMap.value=Le.state.spotLightMap,St.pointShadowMap.value=Le.state.pointShadowMap,St.pointShadowMatrix.value=Le.state.pointShadowMatrix),rt.currentProgram=Ye,rt.uniformsList=null,Ye}function Yt(ze){if(ze.uniformsList===null){const st=ze.currentProgram.getUniforms();ze.uniformsList=Dk.seqWithValue(st.seq,ze.uniforms)}return ze.uniformsList}function Pt(ze,st){const ht=J.get(ze);ht.outputColorSpace=st.outputColorSpace,ht.batching=st.batching,ht.instancing=st.instancing,ht.instancingColor=st.instancingColor,ht.skinning=st.skinning,ht.morphTargets=st.morphTargets,ht.morphNormals=st.morphNormals,ht.morphColors=st.morphColors,ht.morphTargetsCount=st.morphTargetsCount,ht.numClippingPlanes=st.numClippingPlanes,ht.numIntersection=st.numClipIntersection,ht.vertexAlphas=st.vertexAlphas,ht.vertexTangents=st.vertexTangents,ht.toneMapping=st.toneMapping}function pt(ze,st,ht,rt,Le){st.isScene!==!0&&(st=O),se.resetTextureUnits();const Oe=st.fog,Ce=rt.isMeshStandardMaterial?st.environment:null,We=T===null?C.outputColorSpace:T.isXRRenderTarget===!0?T.texture.colorSpace:cm,Je=(rt.isMeshStandardMaterial?pe:fe).get(rt.envMap||Ce),Xe=rt.vertexColors===!0&&!!ht.attributes.color&&ht.attributes.color.itemSize===4,Ye=!!ht.attributes.tangent&&(!!rt.normalMap||rt.anisotropy>0),St=!!ht.morphAttributes.position,et=!!ht.morphAttributes.normal,jt=!!ht.morphAttributes.color;let bt=Yh;rt.toneMapped&&(T===null||T.isXRRenderTarget===!0)&&(bt=C.toneMapping);const Ve=ht.morphAttributes.position||ht.morphAttributes.normal||ht.morphAttributes.color,gt=Ve!==void 0?Ve.length:0,Et=J.get(rt),Gt=g.state.lights;if(xe===!0&&(Ne===!0||ze!==k)){const Nr=ze===k&&rt.id===F;Ae.setState(rt,ze,Nr)}let on=!1;rt.version===Et.__version?(Et.needsLights&&Et.lightsStateVersion!==Gt.state.version||Et.outputColorSpace!==We||Le.isBatchedMesh&&Et.batching===!1||!Le.isBatchedMesh&&Et.batching===!0||Le.isInstancedMesh&&Et.instancing===!1||!Le.isInstancedMesh&&Et.instancing===!0||Le.isSkinnedMesh&&Et.skinning===!1||!Le.isSkinnedMesh&&Et.skinning===!0||Le.isInstancedMesh&&Et.instancingColor===!0&&Le.instanceColor===null||Le.isInstancedMesh&&Et.instancingColor===!1&&Le.instanceColor!==null||Et.envMap!==Je||rt.fog===!0&&Et.fog!==Oe||Et.numClippingPlanes!==void 0&&(Et.numClippingPlanes!==Ae.numPlanes||Et.numIntersection!==Ae.numIntersection)||Et.vertexAlphas!==Xe||Et.vertexTangents!==Ye||Et.morphTargets!==St||Et.morphNormals!==et||Et.morphColors!==jt||Et.toneMapping!==bt||V.isWebGL2===!0&&Et.morphTargetsCount!==gt)&&(on=!0):(on=!0,Et.__version=rt.version);let fn=Et.currentProgram;on===!0&&(fn=Ft(rt,st,Le));let Ln=!1,yn=!1,hn=!1;const xn=fn.getUniforms(),Nn=Et.uniforms;if(Q.useProgram(fn.program)&&(Ln=!0,yn=!0,hn=!0),rt.id!==F&&(F=rt.id,yn=!0),Ln||k!==ze){xn.setValue(B,"projectionMatrix",ze.projectionMatrix),xn.setValue(B,"viewMatrix",ze.matrixWorldInverse);const Nr=xn.map.cameraPosition;Nr!==void 0&&Nr.setValue(B,j.setFromMatrixPosition(ze.matrixWorld)),V.logarithmicDepthBuffer&&xn.setValue(B,"logDepthBufFC",2/(Math.log(ze.far+1)/Math.LN2)),(rt.isMeshPhongMaterial||rt.isMeshToonMaterial||rt.isMeshLambertMaterial||rt.isMeshBasicMaterial||rt.isMeshStandardMaterial||rt.isShaderMaterial)&&xn.setValue(B,"isOrthographic",ze.isOrthographicCamera===!0),k!==ze&&(k=ze,yn=!0,hn=!0)}if(Le.isSkinnedMesh){xn.setOptional(B,Le,"bindMatrix"),xn.setOptional(B,Le,"bindMatrixInverse");const Nr=Le.skeleton;Nr&&(V.floatVertexTextures?(Nr.boneTexture===null&&Nr.computeBoneTexture(),xn.setValue(B,"boneTexture",Nr.boneTexture,se)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}Le.isBatchedMesh&&(xn.setOptional(B,Le,"batchingTexture"),xn.setValue(B,"batchingTexture",Le._matricesTexture,se));const Pn=ht.morphAttributes;if((Pn.position!==void 0||Pn.normal!==void 0||Pn.color!==void 0&&V.isWebGL2===!0)&&Re.update(Le,ht,fn),(yn||Et.receiveShadow!==Le.receiveShadow)&&(Et.receiveShadow=Le.receiveShadow,xn.setValue(B,"receiveShadow",Le.receiveShadow)),rt.isMeshGouraudMaterial&&rt.envMap!==null&&(Nn.envMap.value=Je,Nn.flipEnvMap.value=Je.isCubeTexture&&Je.isRenderTargetTexture===!1?-1:1),yn&&(xn.setValue(B,"toneMappingExposure",C.toneMappingExposure),Et.needsLights&&Wt(Nn,hn),Oe&&rt.fog===!0&&_e.refreshFogUniforms(Nn,Oe),_e.refreshMaterialUniforms(Nn,rt,ee,ie,$),Dk.upload(B,Yt(Et),Nn,se)),rt.isShaderMaterial&&rt.uniformsNeedUpdate===!0&&(Dk.upload(B,Yt(Et),Nn,se),rt.uniformsNeedUpdate=!1),rt.isSpriteMaterial&&xn.setValue(B,"center",Le.center),xn.setValue(B,"modelViewMatrix",Le.modelViewMatrix),xn.setValue(B,"normalMatrix",Le.normalMatrix),xn.setValue(B,"modelMatrix",Le.matrixWorld),rt.isShaderMaterial||rt.isRawShaderMaterial){const Nr=rt.uniformsGroups;for(let Sn=0,Pa=Nr.length;Sn<Pa;Sn++)if(V.isWebGL2){const On=Nr[Sn];Ke.update(On,fn),Ke.bind(On,fn)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return fn}function Wt(ze,st){ze.ambientLightColor.needsUpdate=st,ze.lightProbe.needsUpdate=st,ze.directionalLights.needsUpdate=st,ze.directionalLightShadows.needsUpdate=st,ze.pointLights.needsUpdate=st,ze.pointLightShadows.needsUpdate=st,ze.spotLights.needsUpdate=st,ze.spotLightShadows.needsUpdate=st,ze.rectAreaLights.needsUpdate=st,ze.hemisphereLights.needsUpdate=st}function Ut(ze){return ze.isMeshLambertMaterial||ze.isMeshToonMaterial||ze.isMeshPhongMaterial||ze.isMeshStandardMaterial||ze.isShadowMaterial||ze.isShaderMaterial&&ze.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return A},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(ze,st,ht){J.get(ze.texture).__webglTexture=st,J.get(ze.depthTexture).__webglTexture=ht;const rt=J.get(ze);rt.__hasExternalTextures=!0,rt.__hasExternalTextures&&(rt.__autoAllocateDepthBuffer=ht===void 0,rt.__autoAllocateDepthBuffer||I.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),rt.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(ze,st){const ht=J.get(ze);ht.__webglFramebuffer=st,ht.__useDefaultFramebuffer=st===void 0},this.setRenderTarget=function(ze,st=0,ht=0){T=ze,N=st,A=ht;let rt=!0,Le=null,Oe=!1,Ce=!1;if(ze){const Je=J.get(ze);Je.__useDefaultFramebuffer!==void 0?(Q.bindFramebuffer(B.FRAMEBUFFER,null),rt=!1):Je.__webglFramebuffer===void 0?se.setupRenderTarget(ze):Je.__hasExternalTextures&&se.rebindTextures(ze,J.get(ze.texture).__webglTexture,J.get(ze.depthTexture).__webglTexture);const Xe=ze.texture;(Xe.isData3DTexture||Xe.isDataArrayTexture||Xe.isCompressedArrayTexture)&&(Ce=!0);const Ye=J.get(ze).__webglFramebuffer;ze.isWebGLCubeRenderTarget?(Array.isArray(Ye[st])?Le=Ye[st][ht]:Le=Ye[st],Oe=!0):V.isWebGL2&&ze.samples>0&&se.useMultisampledRTT(ze)===!1?Le=J.get(ze).__webglMultisampledFramebuffer:Array.isArray(Ye)?Le=Ye[ht]:Le=Ye,D.copy(ze.viewport),H.copy(ze.scissor),z=ze.scissorTest}else D.copy(oe).multiplyScalar(ee).floor(),H.copy(W).multiplyScalar(ee).floor(),z=re;if(Q.bindFramebuffer(B.FRAMEBUFFER,Le)&&V.drawBuffers&&rt&&Q.drawBuffers(ze,Le),Q.viewport(D),Q.scissor(H),Q.setScissorTest(z),Oe){const Je=J.get(ze.texture);B.framebufferTexture2D(B.FRAMEBUFFER,B.COLOR_ATTACHMENT0,B.TEXTURE_CUBE_MAP_POSITIVE_X+st,Je.__webglTexture,ht)}else if(Ce){const Je=J.get(ze.texture),Xe=st||0;B.framebufferTextureLayer(B.FRAMEBUFFER,B.COLOR_ATTACHMENT0,Je.__webglTexture,ht||0,Xe)}F=-1},this.readRenderTargetPixels=function(ze,st,ht,rt,Le,Oe,Ce){if(!(ze&&ze.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let We=J.get(ze).__webglFramebuffer;if(ze.isWebGLCubeRenderTarget&&Ce!==void 0&&(We=We[Ce]),We){Q.bindFramebuffer(B.FRAMEBUFFER,We);try{const Je=ze.texture,Xe=Je.format,Ye=Je.type;if(Xe!==Vl&&Me.convert(Xe)!==B.getParameter(B.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const St=Ye===Y0&&(I.has("EXT_color_buffer_half_float")||V.isWebGL2&&I.has("EXT_color_buffer_float"));if(Ye!==Qh&&Me.convert(Ye)!==B.getParameter(B.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Ye===qu&&(V.isWebGL2||I.has("OES_texture_float")||I.has("WEBGL_color_buffer_float")))&&!St){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}st>=0&&st<=ze.width-rt&&ht>=0&&ht<=ze.height-Le&&B.readPixels(st,ht,rt,Le,Me.convert(Xe),Me.convert(Ye),Oe)}finally{const Je=T!==null?J.get(T).__webglFramebuffer:null;Q.bindFramebuffer(B.FRAMEBUFFER,Je)}}},this.copyFramebufferToTexture=function(ze,st,ht=0){const rt=Math.pow(2,-ht),Le=Math.floor(st.image.width*rt),Oe=Math.floor(st.image.height*rt);se.setTexture2D(st,0),B.copyTexSubImage2D(B.TEXTURE_2D,ht,0,0,ze.x,ze.y,Le,Oe),Q.unbindTexture()},this.copyTextureToTexture=function(ze,st,ht,rt=0){const Le=st.image.width,Oe=st.image.height,Ce=Me.convert(ht.format),We=Me.convert(ht.type);se.setTexture2D(ht,0),B.pixelStorei(B.UNPACK_FLIP_Y_WEBGL,ht.flipY),B.pixelStorei(B.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ht.premultiplyAlpha),B.pixelStorei(B.UNPACK_ALIGNMENT,ht.unpackAlignment),st.isDataTexture?B.texSubImage2D(B.TEXTURE_2D,rt,ze.x,ze.y,Le,Oe,Ce,We,st.image.data):st.isCompressedTexture?B.compressedTexSubImage2D(B.TEXTURE_2D,rt,ze.x,ze.y,st.mipmaps[0].width,st.mipmaps[0].height,Ce,st.mipmaps[0].data):B.texSubImage2D(B.TEXTURE_2D,rt,ze.x,ze.y,Ce,We,st.image),rt===0&&ht.generateMipmaps&&B.generateMipmap(B.TEXTURE_2D),Q.unbindTexture()},this.copyTextureToTexture3D=function(ze,st,ht,rt,Le=0){if(C.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const Oe=ze.max.x-ze.min.x+1,Ce=ze.max.y-ze.min.y+1,We=ze.max.z-ze.min.z+1,Je=Me.convert(rt.format),Xe=Me.convert(rt.type);let Ye;if(rt.isData3DTexture)se.setTexture3D(rt,0),Ye=B.TEXTURE_3D;else if(rt.isDataArrayTexture)se.setTexture2DArray(rt,0),Ye=B.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}B.pixelStorei(B.UNPACK_FLIP_Y_WEBGL,rt.flipY),B.pixelStorei(B.UNPACK_PREMULTIPLY_ALPHA_WEBGL,rt.premultiplyAlpha),B.pixelStorei(B.UNPACK_ALIGNMENT,rt.unpackAlignment);const St=B.getParameter(B.UNPACK_ROW_LENGTH),et=B.getParameter(B.UNPACK_IMAGE_HEIGHT),jt=B.getParameter(B.UNPACK_SKIP_PIXELS),bt=B.getParameter(B.UNPACK_SKIP_ROWS),Ve=B.getParameter(B.UNPACK_SKIP_IMAGES),gt=ht.isCompressedTexture?ht.mipmaps[0]:ht.image;B.pixelStorei(B.UNPACK_ROW_LENGTH,gt.width),B.pixelStorei(B.UNPACK_IMAGE_HEIGHT,gt.height),B.pixelStorei(B.UNPACK_SKIP_PIXELS,ze.min.x),B.pixelStorei(B.UNPACK_SKIP_ROWS,ze.min.y),B.pixelStorei(B.UNPACK_SKIP_IMAGES,ze.min.z),ht.isDataTexture||ht.isData3DTexture?B.texSubImage3D(Ye,Le,st.x,st.y,st.z,Oe,Ce,We,Je,Xe,gt.data):ht.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),B.compressedTexSubImage3D(Ye,Le,st.x,st.y,st.z,Oe,Ce,We,Je,gt.data)):B.texSubImage3D(Ye,Le,st.x,st.y,st.z,Oe,Ce,We,Je,Xe,gt),B.pixelStorei(B.UNPACK_ROW_LENGTH,St),B.pixelStorei(B.UNPACK_IMAGE_HEIGHT,et),B.pixelStorei(B.UNPACK_SKIP_PIXELS,jt),B.pixelStorei(B.UNPACK_SKIP_ROWS,bt),B.pixelStorei(B.UNPACK_SKIP_IMAGES,Ve),Le===0&&rt.generateMipmaps&&B.generateMipmap(Ye),Q.unbindTexture()},this.initTexture=function(ze){ze.isCubeTexture?se.setTextureCube(ze,0):ze.isData3DTexture?se.setTexture3D(ze,0):ze.isDataArrayTexture||ze.isCompressedArrayTexture?se.setTexture2DArray(ze,0):se.setTexture2D(ze,0),Q.unbindTexture()},this.resetState=function(){N=0,A=0,T=null,Q.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Sd}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===YO?"display-p3":"srgb",n.unpackColorSpace=Wr.workingColorSpace===BP?"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===ds?Ff:KZ}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===Ff?ds:cm}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 Gje extends rR{}Gje.prototype.isWebGL1Renderer=!0;class nI{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 nI(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Wje extends Js{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 Kje{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=JF,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Qu()}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 i=0,s=this.stride;i<s;i++)this.array[e+i]=n.array[r+i];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=Qu()),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=Qu()),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 qs=new ct;class Eh{constructor(e,n,r,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=n,this.offset=r,this.normalized=i}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++)qs.fromBufferAttribute(this,n),qs.applyMatrix4(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)qs.fromBufferAttribute(this,n),qs.applyNormalMatrix(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)qs.fromBufferAttribute(this,n),qs.transformDirection(e),this.setXYZ(n,qs.x,qs.y,qs.z);return this}setX(e,n){return this.normalized&&(n=Gr(n,this.array)),this.data.array[e*this.data.stride+this.offset]=n,this}setY(e,n){return this.normalized&&(n=Gr(n,this.array)),this.data.array[e*this.data.stride+this.offset+1]=n,this}setZ(e,n){return this.normalized&&(n=Gr(n,this.array)),this.data.array[e*this.data.stride+this.offset+2]=n,this}setW(e,n){return this.normalized&&(n=Gr(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=xd(n,this.array)),n}getY(e){let n=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(n=xd(n,this.array)),n}getZ(e){let n=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(n=xd(n,this.array)),n}getW(e){let n=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(n=xd(n,this.array)),n}setXY(e,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this}setXYZ(e,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array),i=Gr(i,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=i,this}setXYZW(e,n,r,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(n=Gr(n,this.array),r=Gr(r,this.array),i=Gr(i,this.array),s=Gr(s,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=i,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 i=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[i+s])}return new ol(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 Eh(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 i=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[i+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 Xje extends Mo{constructor(e=null,n=1,r=1,i,s,o,l,c,d=cs,u=cs,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function Yje(t,e){return t.z-e.z}function Qje(t,e){return e.z-t.z}class Zje{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,n){const r=this.pool,i=this.list;this.index>=r.length&&r.push({start:-1,count:-1,z:-1});const s=r[this.index];i.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=n}reset(){this.list.length=0,this.index=0}}const Ub="batchId",lh=new da,d$=new da,Jje=new da,u$=new da,TE=new HP,P1=new Jl,tf=new Cd,Pv=new ct,AE=new Zje,Cs=new Lc,T1=[];function eMe(t,e,n=0){const r=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const i=t.count;for(let s=0;s<i;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 tMe extends Lc{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,n,r=n*2,i){super(new Ls,i),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 Xje(n,e,e,Vl,qu);this._matricesTexture=r}_initializeGeometry(e){const n=this.geometry,r=this._maxVertexCount,i=this._maxGeometryCount,s=this._maxIndexCount;if(this._geometryInitialized===!1){for(const l in e.attributes){const c=e.getAttribute(l),{array:d,itemSize:u,normalized:m}=c,p=new d.constructor(r*u),f=new c.constructor(p,u,m);f.setUsage(c.usage),n.setAttribute(l,f)}if(e.getIndex()!==null){const l=r>65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new ol(l,1))}const o=i>65536?new Uint32Array(r):new Uint16Array(r);n.setAttribute(Ub,new ol(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(Ub))throw new Error(`BatchedMesh: Geometry cannot use attribute "${Ub}"`);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===Ub)continue;if(!e.hasAttribute(r))throw new Error(`BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);const i=e.getAttribute(r),s=n.getAttribute(r);if(i.itemSize!==s.itemSize||i.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 Jl);const e=this._geometryCount,n=this.boundingBox,r=this._active;n.makeEmpty();for(let i=0;i<e;i++)r[i]!==!1&&(this.getMatrixAt(i,lh),this.getBoundingBoxAt(i,P1).applyMatrix4(lh),n.union(P1))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Cd);const e=this._geometryCount,n=this.boundingSphere,r=this._active;n.makeEmpty();for(let i=0;i<e;i++)r[i]!==!1&&(this.getMatrixAt(i,lh),this.getBoundingSphereAt(i,tf).applyMatrix4(lh),n.union(tf))}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 i={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?i.vertexCount=e.getAttribute("position").count:i.vertexCount=n,s===null?i.vertexStart=0:i.vertexStart=s.vertexStart+s.vertexCount;const d=e.getIndex(),u=d!==null;if(u&&(r===-1?i.indexCount=d.count:i.indexCount=r,s===null?i.indexStart=0:i.indexStart=s.indexStart+s.indexCount),i.indexStart!==-1&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const m=this._visibility,p=this._active,f=this._matricesTexture,x=this._matricesTexture.image.data;m.push(!0),p.push(!0);const v=this._geometryCount;this._geometryCount++,Jje.toArray(x,v*16),f.needsUpdate=!0,o.push(i),l.push({start:u?i.indexStart:i.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new Jl,sphereInitialized:!1,sphere:new Cd});const g=this.geometry.getAttribute(Ub);for(let b=0;b<i.vertexCount;b++)g.setX(i.vertexStart+b,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,i=r.getIndex()!==null,s=r.getIndex(),o=n.getIndex(),l=this._reservedRanges[e];if(i&&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,d=l.vertexCount;for(const f in r.attributes){if(f===Ub)continue;const x=n.getAttribute(f),v=r.getAttribute(f);eMe(x,v,c);const g=x.itemSize;for(let b=x.count,_=d;b<_;b++){const C=c+b;for(let P=0;P<g;P++)v.setComponent(C,P,0)}v.needsUpdate=!0}if(i){const f=l.indexStart;for(let x=0;x<o.count;x++)s.setX(f+x,c+o.getX(x));for(let x=o.count,v=l.indexCount;x<v;x++)s.setX(f+x,c);s.needsUpdate=!0}const u=this._bounds[e];n.boundingBox!==null?(u.box.copy(n.boundingBox),u.boxInitialized=!0):u.boxInitialized=!1,n.boundingSphere!==null?(u.sphere.copy(n.boundingSphere),u.sphereInitialized=!0):u.sphereInitialized=!1;const m=this._drawRanges[e],p=n.getAttribute("position");return m.count=i?o.count:p.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 i=this._bounds[e],s=i.box,o=this.geometry;if(i.boxInitialized===!1){s.makeEmpty();const l=o.index,c=o.attributes.position,d=this._drawRanges[e];for(let u=d.start,m=d.start+d.count;u<m;u++){let p=u;l&&(p=l.getX(p)),s.expandByPoint(Pv.fromBufferAttribute(c,p))}i.boxInitialized=!0}return n.copy(s),n}getBoundingSphereAt(e,n){if(this._active[e]===!1)return this;const i=this._bounds[e],s=i.sphere,o=this.geometry;if(i.sphereInitialized===!1){s.makeEmpty(),this.getBoundingBoxAt(e,P1),P1.getCenter(s.center);const l=o.index,c=o.attributes.position,d=this._drawRanges[e];let u=0;for(let m=d.start,p=d.start+d.count;m<p;m++){let f=m;l&&(f=l.getX(f)),Pv.fromBufferAttribute(c,f),u=Math.max(u,s.center.distanceToSquared(Pv))}s.radius=Math.sqrt(u),i.sphereInitialized=!0}return n.copy(s),n}setMatrixAt(e,n){const r=this._active,i=this._matricesTexture,s=this._matricesTexture.image.data,o=this._geometryCount;return e>=o||r[e]===!1?this:(n.toArray(s,e*16),i.needsUpdate=!0,this)}getMatrixAt(e,n){const r=this._active,i=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||r[e]===!1?null:n.fromArray(i,e*16)}setVisibleAt(e,n){const r=this._visibility,i=this._active,s=this._geometryCount;return e>=s||i[e]===!1||r[e]===n?this:(r[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,r=this._active,i=this._geometryCount;return e>=i||r[e]===!1?!1:n[e]}raycast(e,n){const r=this._visibility,i=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;Cs.material=this.material,Cs.geometry.index=c.index,Cs.geometry.attributes=c.attributes,Cs.geometry.boundingBox===null&&(Cs.geometry.boundingBox=new Jl),Cs.geometry.boundingSphere===null&&(Cs.geometry.boundingSphere=new Cd);for(let d=0;d<o;d++){if(!r[d]||!i[d])continue;const u=s[d];Cs.geometry.setDrawRange(u.start,u.count),this.getMatrixAt(d,Cs.matrixWorld).premultiply(l),this.getBoundingBoxAt(d,Cs.geometry.boundingBox),this.getBoundingSphereAt(d,Cs.geometry.boundingSphere),Cs.raycast(e,T1);for(let m=0,p=T1.length;m<p;m++){const f=T1[m];f.object=this,f.batchId=d,n.push(f)}T1.length=0}Cs.material=null,Cs.geometry.index=null,Cs.geometry.attributes={},Cs.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,i,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=i.getIndex(),l=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._visibility,d=this._multiDrawStarts,u=this._multiDrawCounts,m=this._drawRanges,p=this.perObjectFrustumCulled;p&&(u$.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),TE.setFromProjectionMatrix(u$,e.isWebGPURenderer?Q0:Sd));let f=0;if(this.sortObjects){d$.copy(this.matrixWorld).invert(),Pv.setFromMatrixPosition(r.matrixWorld).applyMatrix4(d$);for(let g=0,b=c.length;g<b;g++)if(c[g]){this.getMatrixAt(g,lh),this.getBoundingSphereAt(g,tf).applyMatrix4(lh);let _=!1;if(p&&(_=!TE.intersectsSphere(tf)),!_){const C=Pv.distanceTo(tf.center);AE.push(m[g],C)}}const x=AE.list,v=this.customSort;v===null?x.sort(s.transparent?Qje:Yje):v.call(this,x,r);for(let g=0,b=x.length;g<b;g++){const _=x[g];d[f]=_.start*l,u[f]=_.count,f++}AE.reset()}else for(let x=0,v=c.length;x<v;x++)if(c[x]){let g=!1;if(p&&(this.getMatrixAt(x,lh),this.getBoundingSphereAt(x,tf).applyMatrix4(lh),g=!TE.intersectsSphere(tf)),!g){const b=m[x];d[f]=b.start*l,u[f]=b.count,f++}}this._multiDrawCount=f,this._visibilityChanged=!1}onBeforeShadow(e,n,r,i,s,o){this.onBeforeRender(e,null,i,s,o)}}class Ww extends my{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 m$=new ct,h$=new ct,p$=new da,jE=new ZO,A1=new Cd;let nMe=class extends Js{constructor(e=new Ls,n=new Ww){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 i=1,s=n.count;i<s;i++)m$.fromBufferAttribute(n,i-1),h$.fromBufferAttribute(n,i),r[i]=r[i-1],r[i]+=m$.distanceTo(h$);e.setAttribute("lineDistance",new ri(r,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),A1.copy(r.boundingSphere),A1.applyMatrix4(i),A1.radius+=s,e.ray.intersectsSphere(A1)===!1)return;p$.copy(i).invert(),jE.copy(e.ray).applyMatrix4(p$);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=new ct,u=new ct,m=new ct,p=new ct,f=this.isLineSegments?2:1,x=r.index,g=r.attributes.position;if(x!==null){const b=Math.max(0,o.start),_=Math.min(x.count,o.start+o.count);for(let C=b,P=_-1;C<P;C+=f){const N=x.getX(C),A=x.getX(C+1);if(d.fromBufferAttribute(g,N),u.fromBufferAttribute(g,A),jE.distanceSqToSegment(d,u,p,m)>c)continue;p.applyMatrix4(this.matrixWorld);const F=e.ray.origin.distanceTo(p);F<e.near||F>e.far||n.push({distance:F,point:m.clone().applyMatrix4(this.matrixWorld),index:C,face:null,faceIndex:null,object:this})}}else{const b=Math.max(0,o.start),_=Math.min(g.count,o.start+o.count);for(let C=b,P=_-1;C<P;C+=f){if(d.fromBufferAttribute(g,C),u.fromBufferAttribute(g,C+1),jE.distanceSqToSegment(d,u,p,m)>c)continue;p.applyMatrix4(this.matrixWorld);const A=e.ray.origin.distanceTo(p);A<e.near||A>e.far||n.push({distance:A,point:m.clone().applyMatrix4(this.matrixWorld),index:C,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){const l=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};const f$=new ct,g$=new ct;class $P extends nMe{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 i=0,s=n.count;i<s;i+=2)f$.fromBufferAttribute(n,i),g$.fromBufferAttribute(n,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+f$.distanceTo(g$);e.setAttribute("lineDistance",new ri(r,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class rMe extends Ls{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const n=[],r=new Set,i=new ct,s=new ct;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 d=0,u=c.length;d<u;++d){const m=c[d],p=m.start,f=m.count;for(let x=p,v=p+f;x<v;x+=3)for(let g=0;g<3;g++){const b=l.getX(x+g),_=l.getX(x+(g+1)%3);i.fromBufferAttribute(o,b),s.fromBufferAttribute(o,_),b$(i,s,r)===!0&&(n.push(i.x,i.y,i.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 d=0;d<3;d++){const u=3*l+d,m=3*l+(d+1)%3;i.fromBufferAttribute(o,u),s.fromBufferAttribute(o,m),b$(i,s,r)===!0&&(n.push(i.x,i.y,i.z),n.push(s.x,s.y,s.z))}}this.setAttribute("position",new ri(n,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function b$(t,e,n){const r=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,i=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return n.has(r)===!0||n.has(i)===!0?!1:(n.add(r),n.add(i),!0)}class aMe extends my{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=XZ,this.normalScale=new Gn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=KO,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 iMe extends Ww{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 bJ extends Js{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 ME=new da,x$=new ct,y$=new ct;class sMe{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Gn(512,512),this.map=null,this.mapPass=null,this.matrix=new da,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new HP,this._frameExtents=new Gn(1,1),this._viewportCount=1,this._viewports=[new Xr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;x$.setFromMatrixPosition(e.matrixWorld),n.position.copy(x$),y$.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(y$),n.updateMatrixWorld(),ME.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ME),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(ME)}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 v$=new da,Tv=new ct,EE=new ct;class oMe extends sMe{constructor(){super(new Jo(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Gn(4,2),this._viewportCount=6,this._viewports=[new Xr(2,1,1,1),new Xr(0,1,1,1),new Xr(3,1,1,1),new Xr(1,1,1,1),new Xr(3,0,1,1),new Xr(1,0,1,1)],this._cubeDirections=[new ct(1,0,0),new ct(-1,0,0),new ct(0,0,1),new ct(0,0,-1),new ct(0,1,0),new ct(0,-1,0)],this._cubeUps=[new ct(0,1,0),new ct(0,1,0),new ct(0,1,0),new ct(0,1,0),new ct(0,0,1),new ct(0,0,-1)]}updateMatrices(e,n=0){const r=this.camera,i=this.matrix,s=e.distance||r.far;s!==r.far&&(r.far=s,r.updateProjectionMatrix()),Tv.setFromMatrixPosition(e.matrixWorld),r.position.copy(Tv),EE.copy(r.position),EE.add(this._cubeDirections[n]),r.up.copy(this._cubeUps[n]),r.lookAt(EE),r.updateMatrixWorld(),i.makeTranslation(-Tv.x,-Tv.y,-Tv.z),v$.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),this._frustum.setFromProjectionMatrix(v$)}}class lMe extends bJ{constructor(e,n,r=0,i=2){super(e,n),this.isPointLight=!0,this.type="PointLight",this.distance=r,this.decay=i,this.shadow=new oMe}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 cMe extends bJ{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}}class dMe extends Ls{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 aR extends Kje{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 w${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(us(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const S$=new ct,j1=new ct;class uMe{constructor(e=new ct,n=new ct){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){S$.subVectors(e,this.start),j1.subVectors(this.end,this.start);const r=j1.dot(j1);let s=j1.dot(S$)/r;return n&&(s=us(s,0,1)),s}closestPointToPoint(e,n,r){const i=this.closestPointToPointParameter(e,n);return this.delta(r).multiplyScalar(i).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 mMe extends $P{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],i=new Ls;i.setAttribute("position",new ri(n,3)),i.setAttribute("color",new ri(r,3));const s=new Ww({vertexColors:!0,toneMapped:!1});super(i,s),this.type="AxesHelper"}setColors(e,n,r){const i=new Dn,s=this.geometry.attributes.color.array;return i.set(e),i.toArray(s,0),i.toArray(s,3),i.set(n),i.toArray(s,6),i.toArray(s,9),i.set(r),i.toArray(s,12),i.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:zP}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=zP);class Pd{constructor(e,n,r,i,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(i),this.$name=document.createElement("div"),this.$name.classList.add("name"),Pd.nextNameID=Pd.nextNameID||0,this.$name.id=`lil-gui-name-${++Pd.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 hMe extends Pd{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 iR(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 pMe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:iR,toHexString:iR},J0={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},fMe={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const r=J0.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 i=t*r<<16^e*r<<8^n*r<<0;return J0.toHexString(i)}},gMe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const r=J0.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 i=t*r<<16^e*r<<8^n*r<<0;return J0.toHexString(i)}},bMe=[pMe,J0,fMe,gMe];function xMe(t){return bMe.find(e=>e.match(t))}class yMe extends Pd{constructor(e,n,r,i){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=xMe(this.initialValue),this._rgbScale=i,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=iR(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 DE extends Pd{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",i=>{i.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class vMe extends Pd{constructor(e,n,r,i,s,o){super(e,n,r,"number"),this._initInput(),this.min(i),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 C=parseFloat(this.$input.value);isNaN(C)||(this._snapClampSetValue(C+_),this.$input.value=this.getValue())},i=_=>{_.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,d,u,m;const p=5,f=_=>{l=_.clientX,c=d=_.clientY,o=!0,u=this.getValue(),m=0,window.addEventListener("mousemove",x),window.addEventListener("mouseup",v)},x=_=>{if(o){const C=_.clientX-l,P=_.clientY-c;Math.abs(P)>p?(_.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(C)>p&&v()}if(!o){const C=_.clientY-d;m-=C*this._step*this._arrowKeyMultiplier(_),u+m>this._max?m=this._max-u:u+m<this._min&&(m=this._min-u),this._snapClampSetValue(u+m)}d=_.clientY},v=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",v)},g=()=>{this._inputFocused=!0},b=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",n),this.$input.addEventListener("keydown",i),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",f),this.$input.addEventListener("focus",g),this.$input.addEventListener("blur",b)}_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=(b,_,C,P,N)=>(b-_)/(C-_)*(N-P)+P,n=b=>{const _=this.$slider.getBoundingClientRect();let C=e(b,_.left,_.right,this._min,this._max);this._snapClampSetValue(C)},r=b=>{this._setDraggingStyle(!0),n(b.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},i=b=>{n(b.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};let o=!1,l,c;const d=b=>{b.preventDefault(),this._setDraggingStyle(!0),n(b.touches[0].clientX),o=!1},u=b=>{b.touches.length>1||(this._hasScrollBar?(l=b.touches[0].clientX,c=b.touches[0].clientY,o=!0):d(b),window.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("touchend",p))},m=b=>{if(o){const _=b.touches[0].clientX-l,C=b.touches[0].clientY-c;Math.abs(_)>Math.abs(C)?d(b):(window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p))}else b.preventDefault(),n(b.touches[0].clientX)},p=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p)},f=this._callOnFinishChange.bind(this),x=400;let v;const g=b=>{if(Math.abs(b.deltaX)<Math.abs(b.deltaY)&&this._hasScrollBar)return;b.preventDefault();const C=this._normalizeMouseWheel(b)*this._step;this._snapClampSetValue(this.getValue()+C),this.$input.value=this.getValue(),clearTimeout(v),v=setTimeout(f,x)};this.$slider.addEventListener("mousedown",r),this.$slider.addEventListener("touchstart",u,{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 wMe extends Pd{constructor(e,n,r,i){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(i)}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 SMe extends Pd{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",i=>{i.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 _Me=`.lil-gui {
- font-family: var(--font-family);
- font-size: var(--font-size);
- line-height: 1;
- font-weight: normal;
- font-style: normal;
- text-align: left;
- color: var(--text-color);
- user-select: none;
- -webkit-user-select: none;
- touch-action: manipulation;
- --background-color: #1f1f1f;
- --text-color: #ebebeb;
- --title-background-color: #111111;
- --title-text-color: #ebebeb;
- --widget-color: #424242;
- --hover-color: #4f4f4f;
- --focus-color: #595959;
- --number-color: #2cc9ff;
- --string-color: #a2db3c;
- --font-size: 11px;
- --input-font-size: 11px;
- --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
- --font-family-mono: Menlo, Monaco, Consolas, "Droid Sans Mono", monospace;
- --padding: 4px;
- --spacing: 4px;
- --widget-height: 20px;
- --title-height: calc(var(--widget-height) + var(--spacing) * 1.25);
- --name-width: 45%;
- --slider-knob-width: 2px;
- --slider-input-width: 27%;
- --color-input-width: 27%;
- --slider-input-min-width: 45px;
- --color-input-min-width: 45px;
- --folder-indent: 7px;
- --widget-padding: 0 0 0 3px;
- --widget-border-radius: 2px;
- --checkbox-size: calc(0.75 * var(--widget-height));
- --scrollbar-width: 5px;
- }
- .lil-gui, .lil-gui * {
- box-sizing: border-box;
- margin: 0;
- padding: 0;
- }
- .lil-gui.root {
- width: var(--width, 245px);
- display: flex;
- flex-direction: column;
- background: var(--background-color);
- }
- .lil-gui.root > .title {
- background: var(--title-background-color);
- color: var(--title-text-color);
- }
- .lil-gui.root > .children {
- overflow-x: hidden;
- overflow-y: auto;
- }
- .lil-gui.root > .children::-webkit-scrollbar {
- width: var(--scrollbar-width);
- height: var(--scrollbar-width);
- background: var(--background-color);
- }
- .lil-gui.root > .children::-webkit-scrollbar-thumb {
- border-radius: var(--scrollbar-width);
- background: var(--focus-color);
- }
- @media (pointer: coarse) {
- .lil-gui.allow-touch-styles, .lil-gui.allow-touch-styles .lil-gui {
- --widget-height: 28px;
- --padding: 6px;
- --spacing: 6px;
- --font-size: 13px;
- --input-font-size: 16px;
- --folder-indent: 10px;
- --scrollbar-width: 7px;
- --slider-input-min-width: 50px;
- --color-input-min-width: 65px;
- }
- }
- .lil-gui.force-touch-styles, .lil-gui.force-touch-styles .lil-gui {
- --widget-height: 28px;
- --padding: 6px;
- --spacing: 6px;
- --font-size: 13px;
- --input-font-size: 16px;
- --folder-indent: 10px;
- --scrollbar-width: 7px;
- --slider-input-min-width: 50px;
- --color-input-min-width: 65px;
- }
- .lil-gui.autoPlace {
- max-height: 100%;
- position: fixed;
- top: 0;
- right: 15px;
- z-index: 1001;
- }
- .lil-gui .controller {
- display: flex;
- align-items: center;
- padding: 0 var(--padding);
- margin: var(--spacing) 0;
- }
- .lil-gui .controller.disabled {
- opacity: 0.5;
- }
- .lil-gui .controller.disabled, .lil-gui .controller.disabled * {
- pointer-events: none !important;
- }
- .lil-gui .controller > .name {
- min-width: var(--name-width);
- flex-shrink: 0;
- white-space: pre;
- padding-right: var(--spacing);
- line-height: var(--widget-height);
- }
- .lil-gui .controller .widget {
- position: relative;
- display: flex;
- align-items: center;
- width: 100%;
- min-height: var(--widget-height);
- }
- .lil-gui .controller.string input {
- color: var(--string-color);
- }
- .lil-gui .controller.boolean {
- cursor: pointer;
- }
- .lil-gui .controller.color .display {
- width: 100%;
- height: var(--widget-height);
- border-radius: var(--widget-border-radius);
- position: relative;
- }
- @media (hover: hover) {
- .lil-gui .controller.color .display:hover:before {
- content: " ";
- display: block;
- position: absolute;
- border-radius: var(--widget-border-radius);
- border: 1px solid #fff9;
- top: 0;
- right: 0;
- bottom: 0;
- left: 0;
- }
- }
- .lil-gui .controller.color input[type=color] {
- opacity: 0;
- width: 100%;
- height: 100%;
- cursor: pointer;
- }
- .lil-gui .controller.color input[type=text] {
- margin-left: var(--spacing);
- font-family: var(--font-family-mono);
- min-width: var(--color-input-min-width);
- width: var(--color-input-width);
- flex-shrink: 0;
- }
- .lil-gui .controller.option select {
- opacity: 0;
- position: absolute;
- width: 100%;
- max-width: 100%;
- }
- .lil-gui .controller.option .display {
- position: relative;
- pointer-events: none;
- border-radius: var(--widget-border-radius);
- height: var(--widget-height);
- line-height: var(--widget-height);
- max-width: 100%;
- overflow: hidden;
- word-break: break-all;
- padding-left: 0.55em;
- padding-right: 1.75em;
- background: var(--widget-color);
- }
- @media (hover: hover) {
- .lil-gui .controller.option .display.focus {
- background: var(--focus-color);
- }
- }
- .lil-gui .controller.option .display.active {
- background: var(--focus-color);
- }
- .lil-gui .controller.option .display:after {
- font-family: "lil-gui";
- content: "↕";
- position: absolute;
- top: 0;
- right: 0;
- bottom: 0;
- padding-right: 0.375em;
- }
- .lil-gui .controller.option .widget,
- .lil-gui .controller.option select {
- cursor: pointer;
- }
- @media (hover: hover) {
- .lil-gui .controller.option .widget:hover .display {
- background: var(--hover-color);
- }
- }
- .lil-gui .controller.number input {
- color: var(--number-color);
- }
- .lil-gui .controller.number.hasSlider input {
- margin-left: var(--spacing);
- width: var(--slider-input-width);
- min-width: var(--slider-input-min-width);
- flex-shrink: 0;
- }
- .lil-gui .controller.number .slider {
- width: 100%;
- height: var(--widget-height);
- background: var(--widget-color);
- border-radius: var(--widget-border-radius);
- padding-right: var(--slider-knob-width);
- overflow: hidden;
- cursor: ew-resize;
- touch-action: pan-y;
- }
- @media (hover: hover) {
- .lil-gui .controller.number .slider:hover {
- background: var(--hover-color);
- }
- }
- .lil-gui .controller.number .slider.active {
- background: var(--focus-color);
- }
- .lil-gui .controller.number .slider.active .fill {
- opacity: 0.95;
- }
- .lil-gui .controller.number .fill {
- height: 100%;
- border-right: var(--slider-knob-width) solid var(--number-color);
- box-sizing: content-box;
- }
- .lil-gui-dragging .lil-gui {
- --hover-color: var(--widget-color);
- }
- .lil-gui-dragging * {
- cursor: ew-resize !important;
- }
- .lil-gui-dragging.lil-gui-vertical * {
- cursor: ns-resize !important;
- }
- .lil-gui .title {
- height: var(--title-height);
- line-height: calc(var(--title-height) - 4px);
- font-weight: 600;
- padding: 0 var(--padding);
- -webkit-tap-highlight-color: transparent;
- cursor: pointer;
- outline: none;
- text-decoration-skip: objects;
- }
- .lil-gui .title:before {
- font-family: "lil-gui";
- content: "▾";
- padding-right: 2px;
- display: inline-block;
- }
- .lil-gui .title:active {
- background: var(--title-background-color);
- opacity: 0.75;
- }
- @media (hover: hover) {
- body:not(.lil-gui-dragging) .lil-gui .title:hover {
- background: var(--title-background-color);
- opacity: 0.85;
- }
- .lil-gui .title:focus {
- text-decoration: underline var(--focus-color);
- }
- }
- .lil-gui.root > .title:focus {
- text-decoration: none !important;
- }
- .lil-gui.closed > .title:before {
- content: "▸";
- }
- .lil-gui.closed > .children {
- transform: translateY(-7px);
- opacity: 0;
- }
- .lil-gui.closed:not(.transition) > .children {
- display: none;
- }
- .lil-gui.transition > .children {
- transition-duration: 300ms;
- transition-property: height, opacity, transform;
- transition-timing-function: cubic-bezier(0.2, 0.6, 0.35, 1);
- overflow: hidden;
- pointer-events: none;
- }
- .lil-gui .children:empty:before {
- content: "Empty";
- padding: 0 var(--padding);
- margin: var(--spacing) 0;
- display: block;
- height: var(--widget-height);
- font-style: italic;
- line-height: var(--widget-height);
- opacity: 0.5;
- }
- .lil-gui.root > .children > .lil-gui > .title {
- border: 0 solid var(--widget-color);
- border-width: 1px 0;
- transition: border-color 300ms;
- }
- .lil-gui.root > .children > .lil-gui.closed > .title {
- border-bottom-color: transparent;
- }
- .lil-gui + .controller {
- border-top: 1px solid var(--widget-color);
- margin-top: 0;
- padding-top: var(--spacing);
- }
- .lil-gui .lil-gui .lil-gui > .title {
- border: none;
- }
- .lil-gui .lil-gui .lil-gui > .children {
- border: none;
- margin-left: var(--folder-indent);
- border-left: 2px solid var(--widget-color);
- }
- .lil-gui .lil-gui .controller {
- border: none;
- }
- .lil-gui label, .lil-gui input, .lil-gui button {
- -webkit-tap-highlight-color: transparent;
- }
- .lil-gui input {
- border: 0;
- outline: none;
- font-family: var(--font-family);
- font-size: var(--input-font-size);
- border-radius: var(--widget-border-radius);
- height: var(--widget-height);
- background: var(--widget-color);
- color: var(--text-color);
- width: 100%;
- }
- @media (hover: hover) {
- .lil-gui input:hover {
- background: var(--hover-color);
- }
- .lil-gui input:active {
- background: var(--focus-color);
- }
- }
- .lil-gui input:disabled {
- opacity: 1;
- }
- .lil-gui input[type=text],
- .lil-gui input[type=number] {
- padding: var(--widget-padding);
- -moz-appearance: textfield;
- }
- .lil-gui input[type=text]:focus,
- .lil-gui input[type=number]:focus {
- background: var(--focus-color);
- }
- .lil-gui input[type=checkbox] {
- appearance: none;
- width: var(--checkbox-size);
- height: var(--checkbox-size);
- border-radius: var(--widget-border-radius);
- text-align: center;
- cursor: pointer;
- }
- .lil-gui input[type=checkbox]:checked:before {
- font-family: "lil-gui";
- content: "✓";
- font-size: var(--checkbox-size);
- line-height: var(--checkbox-size);
- }
- @media (hover: hover) {
- .lil-gui input[type=checkbox]:focus {
- box-shadow: inset 0 0 0 1px var(--focus-color);
- }
- }
- .lil-gui button {
- outline: none;
- cursor: pointer;
- font-family: var(--font-family);
- font-size: var(--font-size);
- color: var(--text-color);
- width: 100%;
- height: var(--widget-height);
- text-transform: none;
- background: var(--widget-color);
- border-radius: var(--widget-border-radius);
- border: none;
- }
- @media (hover: hover) {
- .lil-gui button:hover {
- background: var(--hover-color);
- }
- .lil-gui button:focus {
- box-shadow: inset 0 0 0 1px var(--focus-color);
- }
- }
- .lil-gui button:active {
- background: var(--focus-color);
- }
- @font-face {
- font-family: "lil-gui";
- 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");
- }`;function kMe(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 _$=!1;class NN{constructor({parent:e,autoPlace:n=e===void 0,container:r,width:i,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",d=>{(d.code==="Enter"||d.code==="Space")&&(d.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"),!_$&&l&&(kMe(_Me),_$=!0),r?r.appendChild(this.domElement):n&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),i&&this.domElement.style.setProperty("--width",i+"px"),this._closeFolders=o}add(e,n,r,i,s){if(Object(r)===r)return new wMe(this,e,n,r);const o=e[n];switch(typeof o){case"number":return new vMe(this,e,n,r,i,s);case"boolean":return new hMe(this,e,n);case"string":return new SMe(this,e,n);case"function":return new DE(this,e,n)}console.error(`gui.add failed
- property:`,n,`
- object:`,e,`
- value:`,o)}addColor(e,n,r=1){return new yMe(this,e,n,r)}addFolder(e){const n=new NN({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(r=>{r instanceof DE||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 DE)){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 i=e?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!e),requestAnimationFrame(()=>{this.$children.style.height=i+"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 FE(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(d){try{c(r.next(d))}catch(u){s(u)}}function l(d){try{c(r.throw(d))}catch(u){s(u)}}function c(d){var u;d.done?i(d.value):(u=d.value,u instanceof n?u:new n((function(m){m(u)}))).then(o,l)}c((r=r.apply(t,[])).next())}))}class rI{constructor(e,n,r,i){this.size=e,this.width=n,this.height=r,this.charLength=i,this.chars=""}static parse(e){const n=e.split(" "),r=n[0],i=r.split("x");return new rI(r,+i[0],+i[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 aI{constructor(e,n,r,i){this.src=e,this.gcode=n,this.params=r,this.comment=i}}class k$ extends aI{constructor(e,n,r,i){super(e,n,r,i),this.params=r}}class ch extends aI{constructor(e,n,r,i){super(e,n,void 0,r),this.toolIndex=i}}class N${constructor(e,n,r,i=0){this.layer=e,this.commands=n,this.lineNumber=r,this.height=i}}class CN{constructor(e){this.lines=[],this.preamble=new N$(-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(`
- `);this.lines=this.lines.concat(n);const r=this.lines2commands(n);this.groupIntoLayers(r);const i=this.parseMetadata(r.filter((s=>s.comment))).thumbnails;for(const[s,o]of Object.entries(i))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 i=e.trim().split(";"),s=i[0],o=n&&i[1]||void 0,l=s.split(/([a-zA-Z])/g).slice(1).map((u=>u.trim())),c=l.length?`${(r=l[0])===null||r===void 0?void 0:r.toLowerCase()}${l[1]}`:"",d=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 k$(e,c,d,o);case"t0":return new ch(e,c,o,0);case"t1":return new ch(e,c,o,1);case"t2":return new ch(e,c,o,2);case"t3":return new ch(e,c,o,3);case"t4":return new ch(e,c,o,4);case"t5":return new ch(e,c,o,5);case"t6":return new ch(e,c,o,6);case"t7":return new ch(e,c,o,7);default:return new aI(e,c,d,o)}}parseMove(e){return e.reduce(((n,r)=>{const i=r.charAt(0).toLowerCase();return i!="x"&&i!="y"&&i!="z"&&i!="e"&&i!="r"&&i!="f"&&i!="i"&&i!="j"||(n[i]=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,i,s)=>{if(i%2==0)return n;let o=s[i-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 i=e[r];if(i instanceof k$){const s=i.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 N$(this.layers.length,[],r,o))}}this.maxLayer.commands.push(i)}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 i of e){const s=i.comment;if(!s)continue;const o=s.indexOf("thumbnail begin"),l=s.indexOf("thumbnail end");o>-1?r=rI.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}}}CN.prototype.parseGcode=CN.prototype.parseGCode;const C$={type:"change"},RE={type:"start"},P$={type:"end"},M1=new ZO,T$=new gh,NMe=Math.cos(70*QZ.DEG2RAD);class CMe extends _g{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new ct,this.cursor=new ct,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:Sb.ROTATE,MIDDLE:Sb.DOLLY,RIGHT:Sb.PAN},this.touches={ONE:_b.ROTATE,TWO:_b.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(V){V.addEventListener("keydown",K),this._domElementKeyEvents=V},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",K),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(C$),r.update(),s=i.NONE},this.update=(function(){const V=new ct,Q=new rg().setFromUnitVectors(e.up,new ct(0,1,0)),G=Q.clone().invert(),J=new ct,se=new rg,fe=new ct,pe=2*Math.PI;return function(de=null){const U=r.object.position;V.copy(U).sub(r.target),V.applyQuaternion(Q),l.setFromVector3(V),r.autoRotate&&s===i.NONE&&D((function(Se){return Se!==null?2*Math.PI/60*r.autoRotateSpeed*Se:2*Math.PI/60/60*r.autoRotateSpeed})(de)),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,ae=r.maxAzimuthAngle;isFinite(R)&&isFinite(ae)&&(R<-Math.PI?R+=pe:R>Math.PI&&(R-=pe),ae<-Math.PI?ae+=pe:ae>Math.PI&&(ae-=pe),l.theta=R<=ae?Math.max(R,Math.min(ae,l.theta)):l.theta>(R+ae)/2?Math.max(R,l.theta):Math.min(ae,l.theta)),l.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,l.phi)),l.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(u,r.dampingFactor):r.target.add(u),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&A||r.object.isOrthographicCamera?l.radius=ue(l.radius):l.radius=ue(l.radius*d),V.setFromSpherical(l),V.applyQuaternion(G),U.copy(r.target).add(V),r.object.lookAt(r.target),r.enableDamping===!0?(c.theta*=1-r.dampingFactor,c.phi*=1-r.dampingFactor,u.multiplyScalar(1-r.dampingFactor)):(c.set(0,0,0),u.set(0,0,0));let _e=!1;if(r.zoomToCursor&&A){let Se=null;if(r.object.isPerspectiveCamera){const ye=V.length();Se=ue(ye*d);const Ae=ye-Se;r.object.position.addScaledVector(P,Ae),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const ye=new ct(N.x,N.y,0);ye.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/d)),r.object.updateProjectionMatrix(),_e=!0;const Ae=new ct(N.x,N.y,0);Ae.unproject(r.object),r.object.position.sub(Ae).add(ye),r.object.updateMatrixWorld(),Se=V.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;Se!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(Se).add(r.object.position):(M1.origin.copy(r.object.position),M1.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(M1.direction))<NMe?e.lookAt(r.target):(T$.setFromNormalAndCoplanarPoint(r.object.up,r.target),M1.intersectPlane(T$,r.target))))}else r.object.isOrthographicCamera&&(r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/d)),r.object.updateProjectionMatrix(),_e=!0);return d=1,A=!1,!!(_e||J.distanceToSquared(r.object.position)>o||8*(1-se.dot(r.object.quaternion))>o||fe.distanceToSquared(r.target)>0)&&(r.dispatchEvent(C$),J.copy(r.object.position),se.copy(r.object.quaternion),fe.copy(r.target),!0)}})(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",B),r.domElement.removeEventListener("pointerdown",Y),r.domElement.removeEventListener("pointercancel",j),r.domElement.removeEventListener("wheel",O),r.domElement.removeEventListener("pointermove",E),r.domElement.removeEventListener("pointerup",j),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",K),r._domElementKeyEvents=null)};const r=this,i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=i.NONE;const o=1e-6,l=new w$,c=new w$;let d=1;const u=new ct,m=new Gn,p=new Gn,f=new Gn,x=new Gn,v=new Gn,g=new Gn,b=new Gn,_=new Gn,C=new Gn,P=new ct,N=new Gn;let A=!1;const T=[],F={};function k(){return Math.pow(.95,r.zoomSpeed)}function D(V){c.theta-=V}function H(V){c.phi-=V}const z=(function(){const V=new ct;return function(Q,G){V.setFromMatrixColumn(G,0),V.multiplyScalar(-Q),u.add(V)}})(),X=(function(){const V=new ct;return function(Q,G){r.screenSpacePanning===!0?V.setFromMatrixColumn(G,1):(V.setFromMatrixColumn(G,0),V.crossVectors(r.object.up,V)),V.multiplyScalar(Q),u.add(V)}})(),L=(function(){const V=new ct;return function(Q,G){const J=r.domElement;if(r.object.isPerspectiveCamera){const se=r.object.position;V.copy(se).sub(r.target);let fe=V.length();fe*=Math.tan(r.object.fov/2*Math.PI/180),z(2*Q*fe/J.clientHeight,r.object.matrix),X(2*G*fe/J.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(z(Q*(r.object.right-r.object.left)/r.object.zoom/J.clientWidth,r.object.matrix),X(G*(r.object.top-r.object.bottom)/r.object.zoom/J.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function ne(V){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?d/=V:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ie(V){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?d*=V:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function ee(V){if(!r.zoomToCursor)return;A=!0;const Q=r.domElement.getBoundingClientRect(),G=V.clientX-Q.left,J=V.clientY-Q.top,se=Q.width,fe=Q.height;N.x=G/se*2-1,N.y=-J/fe*2+1,P.set(N.x,N.y,1).unproject(r.object).sub(r.object.position).normalize()}function ue(V){return Math.max(r.minDistance,Math.min(r.maxDistance,V))}function le(V){m.set(V.clientX,V.clientY)}function oe(V){x.set(V.clientX,V.clientY)}function W(){if(T.length===1)m.set(T[0].pageX,T[0].pageY);else{const V=.5*(T[0].pageX+T[1].pageX),Q=.5*(T[0].pageY+T[1].pageY);m.set(V,Q)}}function re(){if(T.length===1)x.set(T[0].pageX,T[0].pageY);else{const V=.5*(T[0].pageX+T[1].pageX),Q=.5*(T[0].pageY+T[1].pageY);x.set(V,Q)}}function ce(){const V=T[0].pageX-T[1].pageX,Q=T[0].pageY-T[1].pageY,G=Math.sqrt(V*V+Q*Q);b.set(0,G)}function xe(V){if(T.length==1)p.set(V.pageX,V.pageY);else{const G=I(V),J=.5*(V.pageX+G.x),se=.5*(V.pageY+G.y);p.set(J,se)}f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const Q=r.domElement;D(2*Math.PI*f.x/Q.clientHeight),H(2*Math.PI*f.y/Q.clientHeight),m.copy(p)}function Ne(V){if(T.length===1)v.set(V.pageX,V.pageY);else{const Q=I(V),G=.5*(V.pageX+Q.x),J=.5*(V.pageY+Q.y);v.set(G,J)}g.subVectors(v,x).multiplyScalar(r.panSpeed),L(g.x,g.y),x.copy(v)}function $(V){const Q=I(V),G=V.pageX-Q.x,J=V.pageY-Q.y,se=Math.sqrt(G*G+J*J);_.set(0,se),C.set(0,Math.pow(_.y/b.y,r.zoomSpeed)),ne(C.y),b.copy(_)}function Y(V){r.enabled!==!1&&(T.length===0&&(r.domElement.setPointerCapture(V.pointerId),r.domElement.addEventListener("pointermove",E),r.domElement.addEventListener("pointerup",j)),(function(Q){T.push(Q)})(V),V.pointerType==="touch"?(function(Q){switch(he(Q),T.length){case 1:switch(r.touches.ONE){case _b.ROTATE:if(r.enableRotate===!1)return;W(),s=i.TOUCH_ROTATE;break;case _b.PAN:if(r.enablePan===!1)return;re(),s=i.TOUCH_PAN;break;default:s=i.NONE}break;case 2:switch(r.touches.TWO){case _b.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;r.enableZoom&&ce(),r.enablePan&&re(),s=i.TOUCH_DOLLY_PAN;break;case _b.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;r.enableZoom&&ce(),r.enableRotate&&W(),s=i.TOUCH_DOLLY_ROTATE;break;default:s=i.NONE}break;default:s=i.NONE}s!==i.NONE&&r.dispatchEvent(RE)})(V):(function(Q){let G;switch(Q.button){case 0:G=r.mouseButtons.LEFT;break;case 1:G=r.mouseButtons.MIDDLE;break;case 2:G=r.mouseButtons.RIGHT;break;default:G=-1}switch(G){case Sb.DOLLY:if(r.enableZoom===!1)return;(function(J){ee(J),b.set(J.clientX,J.clientY)})(Q),s=i.DOLLY;break;case Sb.ROTATE:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(r.enablePan===!1)return;oe(Q),s=i.PAN}else{if(r.enableRotate===!1)return;le(Q),s=i.ROTATE}break;case Sb.PAN:if(Q.ctrlKey||Q.metaKey||Q.shiftKey){if(r.enableRotate===!1)return;le(Q),s=i.ROTATE}else{if(r.enablePan===!1)return;oe(Q),s=i.PAN}break;default:s=i.NONE}s!==i.NONE&&r.dispatchEvent(RE)})(V))}function E(V){r.enabled!==!1&&(V.pointerType==="touch"?(function(Q){switch(he(Q),s){case i.TOUCH_ROTATE:if(r.enableRotate===!1)return;xe(Q),r.update();break;case i.TOUCH_PAN:if(r.enablePan===!1)return;Ne(Q),r.update();break;case i.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;(function(G){r.enableZoom&&$(G),r.enablePan&&Ne(G)})(Q),r.update();break;case i.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;(function(G){r.enableZoom&&$(G),r.enableRotate&&xe(G)})(Q),r.update();break;default:s=i.NONE}})(V):(function(Q){switch(s){case i.ROTATE:if(r.enableRotate===!1)return;(function(G){p.set(G.clientX,G.clientY),f.subVectors(p,m).multiplyScalar(r.rotateSpeed);const J=r.domElement;D(2*Math.PI*f.x/J.clientHeight),H(2*Math.PI*f.y/J.clientHeight),m.copy(p),r.update()})(Q);break;case i.DOLLY:if(r.enableZoom===!1)return;(function(G){_.set(G.clientX,G.clientY),C.subVectors(_,b),C.y>0?ne(k()):C.y<0&&ie(k()),b.copy(_),r.update()})(Q);break;case i.PAN:if(r.enablePan===!1)return;(function(G){v.set(G.clientX,G.clientY),g.subVectors(v,x).multiplyScalar(r.panSpeed),L(g.x,g.y),x.copy(v),r.update()})(Q)}})(V))}function j(V){(function(Q){delete F[Q.pointerId];for(let G=0;G<T.length;G++)if(T[G].pointerId==Q.pointerId)return void T.splice(G,1)})(V),T.length===0&&(r.domElement.releasePointerCapture(V.pointerId),r.domElement.removeEventListener("pointermove",E),r.domElement.removeEventListener("pointerup",j)),r.dispatchEvent(P$),s=i.NONE}function O(V){r.enabled!==!1&&r.enableZoom!==!1&&s===i.NONE&&(V.preventDefault(),r.dispatchEvent(RE),(function(Q){ee(Q),Q.deltaY<0?ie(k()):Q.deltaY>0&&ne(k()),r.update()})(V),r.dispatchEvent(P$))}function K(V){r.enabled!==!1&&r.enablePan!==!1&&(function(Q){let G=!1;switch(Q.code){case r.keys.UP:Q.ctrlKey||Q.metaKey||Q.shiftKey?H(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,r.keyPanSpeed),G=!0;break;case r.keys.BOTTOM:Q.ctrlKey||Q.metaKey||Q.shiftKey?H(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(0,-r.keyPanSpeed),G=!0;break;case r.keys.LEFT:Q.ctrlKey||Q.metaKey||Q.shiftKey?D(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(r.keyPanSpeed,0),G=!0;break;case r.keys.RIGHT:Q.ctrlKey||Q.metaKey||Q.shiftKey?D(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):L(-r.keyPanSpeed,0),G=!0}G&&(Q.preventDefault(),r.update())})(V)}function B(V){r.enabled!==!1&&V.preventDefault()}function he(V){let Q=F[V.pointerId];Q===void 0&&(Q=new Gn,F[V.pointerId]=Q),Q.set(V.pageX,V.pageY)}function I(V){const Q=V.pointerId===T[0].pointerId?T[1]:T[0];return F[Q.pointerId]}r.domElement.addEventListener("contextmenu",B),r.domElement.addEventListener("pointerdown",Y),r.domElement.addEventListener("pointercancel",j),r.domElement.addEventListener("wheel",O,{passive:!1}),this.update()}}Zt.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Gn(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},ko.line={uniforms:JO.merge([Zt.common,Zt.fog,Zt.line]),vertexShader:`
- #include <common>
- #include <color_pars_vertex>
- #include <fog_pars_vertex>
- #include <logdepthbuf_pars_vertex>
- #include <clipping_planes_pars_vertex>
- uniform float linewidth;
- uniform vec2 resolution;
- attribute vec3 instanceStart;
- attribute vec3 instanceEnd;
- attribute vec3 instanceColorStart;
- attribute vec3 instanceColorEnd;
- #ifdef WORLD_UNITS
- varying vec4 worldPos;
- varying vec3 worldStart;
- varying vec3 worldEnd;
- #ifdef USE_DASH
- varying vec2 vUv;
- #endif
- #else
- varying vec2 vUv;
- #endif
- #ifdef USE_DASH
- uniform float dashScale;
- attribute float instanceDistanceStart;
- attribute float instanceDistanceEnd;
- varying float vLineDistance;
- #endif
- void trimSegment( const in vec4 start, inout vec4 end ) {
- // trim end segment so it terminates between the camera plane and the near plane
- // conservative estimate of the near plane
- float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
- float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
- float nearEstimate = - 0.5 * b / a;
- float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
- end.xyz = mix( start.xyz, end.xyz, alpha );
- }
- void main() {
- #ifdef USE_COLOR
- vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
- #endif
- #ifdef USE_DASH
- vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
- vUv = uv;
- #endif
- float aspect = resolution.x / resolution.y;
- // camera space
- vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
- vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
- #ifdef WORLD_UNITS
- worldStart = start.xyz;
- worldEnd = end.xyz;
- #else
- vUv = uv;
- #endif
- // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
- // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
- // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
- // perhaps there is a more elegant solution -- WestLangley
- bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
- if ( perspective ) {
- if ( start.z < 0.0 && end.z >= 0.0 ) {
- trimSegment( start, end );
- } else if ( end.z < 0.0 && start.z >= 0.0 ) {
- trimSegment( end, start );
- }
- }
- // clip space
- vec4 clipStart = projectionMatrix * start;
- vec4 clipEnd = projectionMatrix * end;
- // ndc space
- vec3 ndcStart = clipStart.xyz / clipStart.w;
- vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
- // direction
- vec2 dir = ndcEnd.xy - ndcStart.xy;
- // account for clip-space aspect ratio
- dir.x *= aspect;
- dir = normalize( dir );
- #ifdef WORLD_UNITS
- // get the offset direction as perpendicular to the view vector
- vec3 worldDir = normalize( end.xyz - start.xyz );
- vec3 offset;
- if ( position.y < 0.5 ) {
- offset = normalize( cross( start.xyz, worldDir ) );
- } else {
- offset = normalize( cross( end.xyz, worldDir ) );
- }
- // sign flip
- if ( position.x < 0.0 ) offset *= - 1.0;
- float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
- // don't extend the line if we're rendering dashes because we
- // won't be rendering the endcaps
- #ifndef USE_DASH
- // extend the line bounds to encompass endcaps
- start.xyz += - worldDir * linewidth * 0.5;
- end.xyz += worldDir * linewidth * 0.5;
- // shift the position of the quad so it hugs the forward edge of the line
- offset.xy -= dir * forwardOffset;
- offset.z += 0.5;
- #endif
- // endcaps
- if ( position.y > 1.0 || position.y < 0.0 ) {
- offset.xy += dir * 2.0 * forwardOffset;
- }
- // adjust for linewidth
- offset *= linewidth * 0.5;
- // set the world position
- worldPos = ( position.y < 0.5 ) ? start : end;
- worldPos.xyz += offset;
- // project the worldpos
- vec4 clip = projectionMatrix * worldPos;
- // shift the depth of the projected points so the line
- // segments overlap neatly
- vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
- clip.z = clipPose.z * clip.w;
- #else
- vec2 offset = vec2( dir.y, - dir.x );
- // undo aspect ratio adjustment
- dir.x /= aspect;
- offset.x /= aspect;
- // sign flip
- if ( position.x < 0.0 ) offset *= - 1.0;
- // endcaps
- if ( position.y < 0.0 ) {
- offset += - dir;
- } else if ( position.y > 1.0 ) {
- offset += dir;
- }
- // adjust for linewidth
- offset *= linewidth;
- // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
- offset /= resolution.y;
- // select end
- vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
- // back to clip space
- offset *= clip.w;
- clip.xy += offset;
- #endif
- gl_Position = clip;
- vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
- #include <logdepthbuf_vertex>
- #include <clipping_planes_vertex>
- #include <fog_vertex>
- }
- `,fragmentShader:`
- uniform vec3 diffuse;
- uniform float opacity;
- uniform float linewidth;
- #ifdef USE_DASH
- uniform float dashOffset;
- uniform float dashSize;
- uniform float gapSize;
- #endif
- varying float vLineDistance;
- #ifdef WORLD_UNITS
- varying vec4 worldPos;
- varying vec3 worldStart;
- varying vec3 worldEnd;
- #ifdef USE_DASH
- varying vec2 vUv;
- #endif
- #else
- varying vec2 vUv;
- #endif
- #include <common>
- #include <color_pars_fragment>
- #include <fog_pars_fragment>
- #include <logdepthbuf_pars_fragment>
- #include <clipping_planes_pars_fragment>
- vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
- float mua;
- float mub;
- vec3 p13 = p1 - p3;
- vec3 p43 = p4 - p3;
- vec3 p21 = p2 - p1;
- float d1343 = dot( p13, p43 );
- float d4321 = dot( p43, p21 );
- float d1321 = dot( p13, p21 );
- float d4343 = dot( p43, p43 );
- float d2121 = dot( p21, p21 );
- float denom = d2121 * d4343 - d4321 * d4321;
- float numer = d1343 * d4321 - d1321 * d4343;
- mua = numer / denom;
- mua = clamp( mua, 0.0, 1.0 );
- mub = ( d1343 + d4321 * ( mua ) ) / d4343;
- mub = clamp( mub, 0.0, 1.0 );
- return vec2( mua, mub );
- }
- void main() {
- #include <clipping_planes_fragment>
- #ifdef USE_DASH
- if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
- if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
- #endif
- float alpha = opacity;
- #ifdef WORLD_UNITS
- // Find the closest points on the view ray and the line segment
- vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
- vec3 lineDir = worldEnd - worldStart;
- vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
- vec3 p1 = worldStart + lineDir * params.x;
- vec3 p2 = rayEnd * params.y;
- vec3 delta = p1 - p2;
- float len = length( delta );
- float norm = len / linewidth;
- #ifndef USE_DASH
- #ifdef USE_ALPHA_TO_COVERAGE
- float dnorm = fwidth( norm );
- alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
- #else
- if ( norm > 0.5 ) {
- discard;
- }
- #endif
- #endif
- #else
- #ifdef USE_ALPHA_TO_COVERAGE
- // artifacts appear on some hardware if a derivative is taken within a conditional
- float a = vUv.x;
- float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
- float len2 = a * a + b * b;
- float dlen = fwidth( len2 );
- if ( abs( vUv.y ) > 1.0 ) {
- alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
- }
- #else
- if ( abs( vUv.y ) > 1.0 ) {
- float a = vUv.x;
- float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
- float len2 = a * a + b * b;
- if ( len2 > 1.0 ) discard;
- }
- #endif
- #endif
- vec4 diffuseColor = vec4( diffuse, alpha );
- #include <logdepthbuf_fragment>
- #include <color_fragment>
- gl_FragColor = vec4( diffuseColor.rgb, alpha );
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
- #include <premultiplied_alpha_fragment>
- }
- `};class xJ extends lp{constructor(e){super({type:"LineMaterial",uniforms:JO.clone(ko.line.uniforms),vertexShader:ko.line.vertexShader,fragmentShader:ko.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 A$=new Jl,E1=new ct;class yJ extends dMe{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 ri([-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 ri([-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 aR(n,6,1);return this.setAttribute("instanceStart",new Eh(r,3,0)),this.setAttribute("instanceEnd",new Eh(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 aR(n,6,1);return this.setAttribute("instanceColorStart",new Eh(r,3,0)),this.setAttribute("instanceColorEnd",new Eh(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 rMe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Jl);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),A$.setFromBufferAttribute(n),this.boundingBox.union(A$))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Cd),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 i=0;for(let s=0,o=e.count;s<o;s++)E1.fromBufferAttribute(e,s),i=Math.max(i,r.distanceToSquared(E1)),E1.fromBufferAttribute(n,s),i=Math.max(i,r.distanceToSquared(E1));this.boundingSphere.radius=Math.sqrt(i),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 j$=new ct,M$=new ct,ns=new Xr,rs=new Xr,ad=new Xr,LE=new ct,OE=new da,as=new uMe,E$=new ct,D1=new Jl,F1=new Cd,id=new Xr;let sd,gf;function D$(t,e,n){return id.set(0,0,-e,1).applyMatrix4(t.projectionMatrix),id.multiplyScalar(1/id.w),id.x=gf/n.width,id.y=gf/n.height,id.applyMatrix4(t.projectionMatrixInverse),id.multiplyScalar(1/id.w),Math.abs(Math.max(id.x,id.y))}class PMe extends Lc{constructor(e=new yJ,n=new xJ({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,i=new Float32Array(2*n.count);for(let o=0,l=0,c=n.count;o<c;o++,l+=2)j$.fromBufferAttribute(n,o),M$.fromBufferAttribute(r,o),i[l]=l===0?0:i[l-1],i[l+1]=i[l]+j$.distanceTo(M$);const s=new aR(i,2,1);return e.setAttribute("instanceDistanceStart",new Eh(s,1,0)),e.setAttribute("instanceDistanceEnd",new Eh(s,1,1)),this}raycast(e,n){const r=this.material.worldUnits,i=e.camera;i!==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;sd=e.ray;const o=this.matrixWorld,l=this.geometry,c=this.material;let d,u;gf=c.linewidth+s,l.boundingSphere===null&&l.computeBoundingSphere(),F1.copy(l.boundingSphere).applyMatrix4(o),r?d=.5*gf:d=D$(i,Math.max(i.near,F1.distanceToPoint(sd.origin)),c.resolution),F1.radius+=d,sd.intersectsSphere(F1)!==!1&&(l.boundingBox===null&&l.computeBoundingBox(),D1.copy(l.boundingBox).applyMatrix4(o),r?u=.5*gf:u=D$(i,Math.max(i.near,D1.distanceToPoint(sd.origin)),c.resolution),D1.expandByScalar(u),sd.intersectsBox(D1)!==!1&&(r?(function(m,p){const f=m.matrixWorld,x=m.geometry,v=x.attributes.instanceStart,g=x.attributes.instanceEnd;for(let b=0,_=Math.min(x.instanceCount,v.count);b<_;b++){as.start.fromBufferAttribute(v,b),as.end.fromBufferAttribute(g,b),as.applyMatrix4(f);const C=new ct,P=new ct;sd.distanceSqToSegment(as.start,as.end,P,C),P.distanceTo(C)<.5*gf&&p.push({point:P,pointOnLine:C,distance:sd.origin.distanceTo(P),object:m,face:null,faceIndex:b,uv:null,uv1:null})}})(this,n):(function(m,p,f){const x=p.projectionMatrix,v=m.material.resolution,g=m.matrixWorld,b=m.geometry,_=b.attributes.instanceStart,C=b.attributes.instanceEnd,P=Math.min(b.instanceCount,_.count),N=-p.near;sd.at(1,ad),ad.w=1,ad.applyMatrix4(p.matrixWorldInverse),ad.applyMatrix4(x),ad.multiplyScalar(1/ad.w),ad.x*=v.x/2,ad.y*=v.y/2,ad.z=0,LE.copy(ad),OE.multiplyMatrices(p.matrixWorldInverse,g);for(let A=0,T=P;A<T;A++){if(ns.fromBufferAttribute(_,A),rs.fromBufferAttribute(C,A),ns.w=1,rs.w=1,ns.applyMatrix4(OE),rs.applyMatrix4(OE),ns.z>N&&rs.z>N)continue;if(ns.z>N){const z=ns.z-rs.z,X=(ns.z-N)/z;ns.lerp(rs,X)}else if(rs.z>N){const z=rs.z-ns.z,X=(rs.z-N)/z;rs.lerp(ns,X)}ns.applyMatrix4(x),rs.applyMatrix4(x),ns.multiplyScalar(1/ns.w),rs.multiplyScalar(1/rs.w),ns.x*=v.x/2,ns.y*=v.y/2,rs.x*=v.x/2,rs.y*=v.y/2,as.start.copy(ns),as.start.z=0,as.end.copy(rs),as.end.z=0;const F=as.closestPointToPointParameter(LE,!0);as.at(F,E$);const k=QZ.lerp(ns.z,rs.z,F),D=k>=-1&&k<=1,H=LE.distanceTo(E$)<.5*gf;if(D&&H){as.start.fromBufferAttribute(_,A),as.end.fromBufferAttribute(C,A),as.start.applyMatrix4(g),as.end.applyMatrix4(g);const z=new ct,X=new ct;sd.distanceSqToSegment(as.start,as.end,X,z),f.push({point:X,pointOnLine:z,distance:sd.origin.distanceTo(X),object:m,face:null,faceIndex:A,uv:null,uv1:null})}}})(this,i,n)))}}class TMe extends $P{constructor(e,n,r,i,s=4473924,o=8947848){s=new Dn(s),o=new Dn(o);const l=Math.round(e/n);r=Math.round(r/i)*i/2;const c=[],d=[];let u=0;for(let p=-1*(e=l*n/2);p<=e;p+=n){c.push(p,0,-1*r,p,0,r);const f=p===0?s:o;f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3}for(let p=-1*r;p<=r;p+=i){c.push(-1*e,0,p,e,0,p);const f=p===0?s:o;f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3,f.toArray(d,u),u+=3}const m=new Ls;m.setAttribute("position",new ri(c,3)),m.setAttribute("color",new ri(d,3)),super(m,new Ww({vertexColors:!0,toneMapped:!1}))}}function AMe(t,e,n,r){const i=(function(o,l,c){o*=.5,l*=.5,c*=.5;const d=new Ls,u=[];return u.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),d.setAttribute("position",new ri(u,3)),d})(t,e,n),s=new $P(i,new iMe({color:new Dn(r),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var f0=function(){var t=0,e=document.createElement("div");function n(u){return e.appendChild(u.dom),u}function r(u){for(var m=0;m<e.children.length;m++)e.children[m].style.display=m===u?"block":"none";t=u}e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",(function(u){u.preventDefault(),r(++t%e.children.length)}),!1);var i=(performance||Date).now(),s=i,o=0,l=n(new f0.Panel("FPS","#0ff","#002")),c=n(new f0.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=n(new f0.Panel("MB","#f08","#201"));return r(0),{REVISION:16,dom:e,addPanel:n,showPanel:r,begin:function(){i=(performance||Date).now()},end:function(){o++;var u=(performance||Date).now();if(c.update(u-i,200),u>=s+1e3&&(l.update(1e3*o/(u-s),100),s=u,o=0,d)){var m=performance.memory;d.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return u},update:function(){i=this.end()},domElement:e,setMode:r}};f0.Panel=function(t,e,n){var r=1/0,i=0,s=Math.round,o=s(window.devicePixelRatio||1),l=80*o,c=48*o,d=3*o,u=2*o,m=3*o,p=15*o,f=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,d,u),g.fillRect(m,p,f,x),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(m,p,f,x),{dom:v,update:function(b,_){r=Math.min(r,b),i=Math.max(i,b),g.fillStyle=n,g.globalAlpha=1,g.fillRect(0,0,l,p),g.fillStyle=e,g.fillText(s(b)+" "+t+" ("+s(r)+"-"+s(i)+")",d,u),g.drawImage(v,m+o,p,f-o,x,m,p,f-o,x),g.fillRect(m+f-o,p,o,x),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(m+f-o,p,o,s((1-b/_)*x))}}};var jMe=f0;class F${constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new NN,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 NN,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 MMe extends Ls{constructor(e=[new ct],n=.6,r=.2,i=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:i,closed:!1};const s=new ct,o=new ct,l=new Gn,c=[],d=[],u=[],m=[];function p(f){const[x,v,g]=(function(b){const _=e[b],C=new ct,P=new ct,N=new ct,A=new ct;C.copy(_).sub(e[b-1]||_).normalize().add((e[b+1]||_).clone().sub(_).normalize()).normalize();let T=Number.MAX_VALUE;const F=Math.abs(C.x),k=Math.abs(C.y),D=Math.abs(C.z);return F<=T&&(T=F,P.set(1,0,0)),k<=T&&(T=k,P.set(0,1,0)),D<=T&&P.set(0,0,1),A.crossVectors(C,P).normalize(),P.crossVectors(C,A),N.crossVectors(C,P),[_,P,N]})(f);for(let b=0;b<=i;b++){const _=b/i*Math.PI*2,C=Math.sin(_),P=-Math.cos(_);o.x=P*v.x+C*g.x,o.y=P*v.y+C*g.y,o.z=P*v.z+C*g.z,o.normalize(),d.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 f=0;f<e.length;f++)p(f);p(closed===!1?e.length-1:0),(function(){for(let f=0;f<e.length;f++)for(let x=0;x<=i;x++)l.x=f/e.length,l.y=x/i,u.push(l.x,l.y)})(),(function(){for(let f=1;f<e.length;f++)for(let x=1;x<=i;x++){const v=(i+1)*(f-1)+(x-1),g=(i+1)*f+(x-1),b=(i+1)*f+x,_=(i+1)*(f-1)+x;m.push(v,g,_),m.push(g,b,_)}})()})(),this.setIndex(m),this.setAttribute("position",new ri(c,3)),this.setAttribute("normal",new ri(d,3)),this.setAttribute("uv",new ri(u,2))}}class g0{static get initial(){const e=new g0;return Object.assign(e,{x:0,y:0,z:0,r:0,e:0,i:0,j:0,t:0}),e}}const IE={h:0,s:0,l:0};class bx{constructor(e){var n,r,i,s,o,l,c,d,u;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=g0.initial,this.beyondFirstMove=!1,this.disposables=[],this._extrusionColor=bx.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 CN(this.minLayerThreshold),this.scene=new Wje,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=(i=e.debug)!==null&&i!==void 0?i: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=(d=e.extrusionWidth)!==null&&d!==void 0?d:this.extrusionWidth,this.devMode=(u=e.devMode)!==null&&u!==void 0?u:this.devMode,this.stats=this.devMode?new jMe: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[f,x]of Object.entries(e.toolColors))this._toolColors[parseInt(f)]=new Dn(x)}if(e.disableGradient!==void 0&&(this.disableGradient=e.disableGradient),console.info("Using THREE r"+zP),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 rR({canvas:this.canvas,preserveDrawingBuffer:!0});else{if(!this.targetId)throw Error("Set either opts.canvas or opts.targetId");const f=document.getElementById(this.targetId);if(!f)throw new Error("Unable to find element "+this.targetId);this.renderer=new rR({preserveDrawingBuffer:!0}),this.canvas=this.renderer.domElement,f.appendChild(this.canvas)}this.camera=new Jo(25,this.canvas.offsetWidth/this.canvas.offsetHeight,10,5e3),this.camera.position.fromArray(this.initialCameraPosition);const m=this.camera.far,p=.8*m;this.scene.fog=new nI(this._backgroundColor,p,m),this.resize(),this.controls=new CMe(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?bx.defaultExtrusionColor:this._extrusionColor instanceof Dn?this._extrusionColor:(e=this._extrusionColor[this.state.t])!==null&&e!==void 0?e:bx.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 mMe(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 cMe(13421772,.3*Math.PI),n=new lMe(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 Qv;return n.name=e,n.quaternion.setFromEuler(new Vw(-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=g0.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 FE(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,i,s,o,l,c,d;if(e>this.maxLayerIndex)return;const u=this.layers[e],m={extrusion:[],travel:[],z:this.state.z,height:u.height};for(const p of u.commands)if(p.gcode!="g20"){if(p.gcode.startsWith("t")){this.doRenderExtrusion(m,e),m.extrusion=[];const f=p;this.state.t=f.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(p.gcode)>-1){const f=p,x={x:(n=f.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=f.params.y)!==null&&r!==void 0?r:this.state.y,z:(i=f.params.z)!==null&&i!==void 0?i:this.state.z,r:(s=f.params.r)!==null&&s!==void 0?s:this.state.r,e:(o=f.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=f.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=f.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((d=f.params.e)!==null&&d!==void 0?d:0)>0||this.nonTravelmoves.indexOf(p.gcode)>-1;(x.x!=this.state.x||x.y!=this.state.y||x.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(p.gcode=="g2"||p.gcode=="g3"||p.gcode=="g02"||p.gcode=="g03"?this.addArcSegment(m,this.state,x,v,p.gcode=="g2"||p.gcode=="g02"):this.addLineSegment(m,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(m,e)}doRenderExtrusion(e,n){var r,i;if(this.renderExtrusion){let s=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;s.getHSL(IE),s=new Dn().setHSL(IE.h,IE.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:s,l=(i=this._lastSegmentColor)!==null&&i!==void 0?i:o,c=e.extrusion.splice(-3),d=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...d,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...d,...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 TMe(this.buildVolume.x,10,this.buildVolume.y,10));const e=AMe(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 CN(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=g0.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,i){(i?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,i,s){const o=i?e.extrusion:e.travel,l=n.x,c=n.y,d=n.z,u=r.x,m=r.y,p=r.z;let f=r.r,x=r.i,v=r.j;if(f){const ne=u-l,ie=m-c,ee=Math.sqrt(Math.pow(ne/2,2)+Math.pow(ie/2,2));f=Math.max(f,ee);const ue=Math.pow(ne,2)+Math.pow(ie,2),le=Math.pow(f,2)-ue/4;let oe=Math.sqrt(le/ue);(s&&f<0||!s&&f>0)&&(oe=-oe),x=ne/2+ie*oe,v=ie/2-ne*oe}const g=l==u&&c==m,b=l+x,_=c+v,C=Math.sqrt(x*x+v*v),P=Math.atan2(-v,-x),N=Math.atan2(m-_,u-b);let A;g?A=2*Math.PI:(A=s?P-N:N-P,A<0&&(A+=2*Math.PI));let T=C*A/1.8;this.inches&&(T*=25),T<1&&(T=1);let F=A/T;F*=s?-1:1;const k=[];k.push({x:l,y:c,z:d});const D=(d-p)/T;let H=l,z=c,X=d,L=P;for(let ne=0;ne<T-1;ne++)L+=F,H=b+C*Math.cos(L),z=_+C*Math.sin(L),X+=D,k.push({x:H,y:z,z:X});k.push({x:r.x,y:r.y,z:r.z});for(let ne=0;ne<k.length-1;ne++)o.push(k[ne].x,k[ne].y,k[ne].z,k[ne+1].x,k[ne+1].y,k[ne+1].z)}addLine(e,n){var r;if(typeof this.lineWidth=="number"&&this.lineWidth>0)return void this.addThickLine(e,n);const i=new Ls;i.setAttribute("position",new ri(e,3)),this.disposables.push(i);const s=new Ww({color:n});this.disposables.push(s);const o=new $P(i,s);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let i=[];const s=[];for(let o=0;o<e.length;o+=6){const l=e.slice(o,o+9),c=new ct(l[0],l[1],l[2]),d=new ct(l[3],l[4],l[5]),u=new ct(l[6],l[7],l[8]);i.push(c),d.equals(u)||(i.push(d),s.push(i),i=[])}s.forEach((o=>{var l;const c=new MMe(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 i=new yJ;this.disposables.push(i);const s=new xJ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),i.setPositions(e);const o=new PMe(i,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=>FE(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const i=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(i.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],i=new aMe({color:e,wireframe:this._wireframe});this.disposables.push(i);const s=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new tMe(r.length,s,void 0,i);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return FE(this,void 0,void 0,(function*(){const i=e.getReader();let s,o="",l=0;do{console.debug("reading from stream"),s=yield i.read(),l+=(r=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const d=(c=s.value,new TextDecoder("utf-8").decode(c)),u=d.lastIndexOf(`
- `),m=d.slice(0,u);this.parser.parseGCode(o+m),o=d.slice(u)}while(!s.done);var c;console.debug("read from stream",l)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new F$(this):typeof this.devMode=="object"&&(this.devGui=new F$(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())}}bx.defaultExtrusionColor=new Dn("hotpink");function vJ({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:r=""}){const i=w.useRef(null),s=w.useRef(null),o=w.useRef(null),l=w.useRef(!1),[c,d]=w.useState(!0),[u,m]=w.useState(null),[p,f]=w.useState(!1),[x,v]=w.useState(0),[g,b]=w.useState(0),_=w.useMemo(()=>JSON.stringify(n),[n]);w.useEffect(()=>{if(!i.current||l.current)return;l.current=!0;const N=i.current,A=N.parentElement?.getBoundingClientRect();A&&(N.width=A.width,N.height=A.height);const T=n&&n.length>1,F=n?.[0]||"#00ae42",k=new bx({canvas:N,buildVolume:e,backgroundColor:1710618,extrusionColor:T?n:F,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});s.current=k;const D={},H=om();H&&(D.Authorization=`Bearer ${H}`),fetch(t,{headers:D}).then(async X=>{if(!X.ok)throw X.status===404&&(await X.json().catch(()=>({}))).detail?.includes("sliced")?(f(!0),new Error("not_sliced")):new Error("Failed to load G-code");return X.text()}).then(X=>{const L=new Set,ne=/^(\s*)T(\d+)(\s*;.*)?$/gim;let ie;for(;(ie=ne.exec(X))!==null;){const re=parseInt(ie[2],10);re<=15&&L.add(re)}const ee=new Map,ue=Array.from(L).sort((re,ce)=>re-ce);ue.forEach((re,ce)=>{ee.set(re,ce%8)});const le=[];ue.forEach((re,ce)=>{const xe=n?.[re]||"#00ae42";le[ce%8]=xe});const oe=X.split(`
- `).map(re=>{const ce=re.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(ce){const xe=parseInt(ce[2],10);if(xe>15)return`; FILTERED: ${re.trim()}`;const Ne=ee.get(xe)??0;return`${ce[1]}T${Ne}${ce[3]||""}`}return re}).join(`
- `);le.length>0&&(k.extrusionColor=le),k.processGCode(oe);const W=k.layers?.length||0;b(W),v(W),k.render(),d(!1)}).catch(X=>{X.message!=="not_sliced"&&m(X.message),d(!1)});const z=()=>{if(N.parentElement&&s.current){const X=N.parentElement.getBoundingClientRect();N.width=X.width,N.height=X.height,s.current.resize()}};return window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),o.current&&cancelAnimationFrame(o.current),s.current&&(s.current.dispose(),s.current=null),l.current=!1}},[t,_]);const C=w.useCallback(N=>{if(!s.current)return;const A=Math.max(1,Math.min(N,g));v(A),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{s.current&&(s.current.endLayer=A,s.current.render())})},[g]),P=N=>{C(parseInt(N.target.value,10))};return a.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[a.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("canvas",{ref:i,className:"w-full h-full"}),c&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsxs("div",{className:"text-center",children:[a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),p&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsxs("div",{className:"text-center max-w-sm px-4",children:[a.jsx(Jfe,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),a.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),a.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."})]})}),u&&!p&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:a.jsx("div",{className:"text-center text-red-400",children:a.jsx("p",{className:"text-sm",children:u})})})]}),!c&&!u&&!p&&g>0&&a.jsx("div",{className:"mt-4 px-2",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(aa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("button",{onClick:()=>C(x-1),disabled:x<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:a.jsx(dl,{className:"w-4 h-4"})}),a.jsx("input",{type:"range",min:1,max:g,value:x,onChange:P,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),a.jsx("button",{onClick:()=>C(x+1),disabled:x>=g,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:a.jsx(Ka,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[x," / ",g]})]})})]})}function EMe({printerId:t,filePath:e,filename:n,onClose:r}){const[i,s]=w.useState(null),[o,l]=w.useState([]),[c,d]=w.useState(!1),[u,m]=w.useState(null),p=n.toLowerCase().split(".").pop()||"",f=p==="3mf"||p==="stl",x=p==="gcode"||p==="3mf";w.useEffect(()=>{s(f?"3d":x?"gcode":null)},[f,x]),w.useEffect(()=>{l([]),m(null),f&&(d(!0),me.getPrinterFilePlates(t,e).then(b=>l(b.plates||[])).catch(()=>l([])).finally(()=>d(!1)))},[e,f,t]);const v=o.length>1,g=u==null?null:o.find(b=>b.index===u)??null;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6",onClick:r,children:a.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:b=>b.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:n}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>f&&s("3d"),disabled:!f,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${i==="3d"?"text-bambu-green border-b-2 border-bambu-green":f?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(mi,{className:"w-4 h-4"}),"3D Model",!f&&a.jsx("span",{className:"text-xs",children:"(not available)"})]}),a.jsxs("button",{onClick:()=>x&&s("gcode"),disabled:!x,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${i==="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:[a.jsx(Ms,{className:"w-4 h-4"}),"G-code Preview",!x&&a.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:i==="3d"&&f?a.jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[v&&a.jsxs("div",{className:"rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(mi,{className:"w-4 h-4"}),"Plates",c&&a.jsx(dt,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[a.jsxs("button",{type:"button",onClick:()=>m(null),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${u==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(mi,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:"All Plates"}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[o.length," plate",o.length!==1?"s":""]})]}),u==null&&a.jsx(xs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]}),o.map(b=>a.jsxs("button",{type:"button",onClick:()=>m(b.index),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${u===b.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[b.has_thumbnail?a.jsx("img",{src:me.getPrinterFilePlateThumbnail(t,b.index,e),alt:`Plate ${b.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(mi,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:b.name||`Plate ${b.index}`}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:b.objects.length>0?b.objects.slice(0,2).join(", ")+(b.objects.length>2?"…":""):`${b.filaments.length} filament${b.filaments.length!==1?"s":""}`})]}),u===b.index&&a.jsx(xs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},b.index))]}),g&&a.jsxs("div",{className:"mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1",children:[a.jsxs("span",{children:["Plate ",g.index]}),g.print_time_seconds!=null&&a.jsxs("span",{children:["ETA ",Math.round(g.print_time_seconds/60)," min"]}),g.filament_used_grams!=null&&a.jsxs("span",{children:[g.filament_used_grams.toFixed(1)," g"]}),g.filaments.length>0&&a.jsxs("span",{children:[g.filaments.length," filament",g.filaments.length!==1?"s":""]})]})]}),a.jsx("div",{className:"flex-1",children:a.jsx(IZ,{url:me.getPrinterFileDownloadUrl(t,e),fileType:p,selectedPlateId:u,className:"w-full h-full"})})]}):i==="gcode"&&x?a.jsx(vJ,{gcodeUrl:me.getPrinterFileGcodeUrl(t,e),className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function R$(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 DMe(t,e){if(e)return PQ;switch(t.toLowerCase().split(".").pop()||""){case"3mf":return Hh;case"gcode":return Ms;case"mp4":case"avi":return qh;case"png":case"jpg":case"jpeg":return rm;default:return AP}}const FMe=[{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 RMe({printerId:t,printerName:e,onClose:n}){const{t:r}=Rt(),{showToast:i}=bn(),s=sn(),[o,l]=w.useState("/"),[c,d]=w.useState(new Set),[u,m]=w.useState(""),[p,f]=w.useState([]),[x,v]=w.useState("name-asc"),[g,b]=w.useState(null),[_,C]=w.useState(null);w.useEffect(()=>{const ee=ue=>{ue.key==="Escape"&&n()};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[n]);const{data:P,isLoading:N,refetch:A}=Qe({queryKey:["printerFiles",t,o],queryFn:()=>me.getPrinterFiles(t,o),refetchInterval:3e4}),{data:T}=Qe({queryKey:["printerStorage",t],queryFn:()=>me.getPrinterStorage(t),staleTime:3e4}),F=it({mutationFn:async ee=>{for(const ue of ee)await me.deletePrinterFile(t,ue)},onSuccess:()=>{i(r("printerFiles.toast.filesDeleted",{count:p.length})),s.invalidateQueries({queryKey:["printerFiles",t]}),d(new Set),f([])},onError:ee=>{i(r("printerFiles.toast.deleteFailed",{error:ee.message}),"error")}}),k=ee=>{l(ee),d(new Set)},D=()=>{if(o==="/")return;const ee=o.split("/").filter(Boolean);ee.pop(),l(ee.length?"/"+ee.join("/"):"/"),d(new Set)},H=(ee,ue)=>{ue.stopPropagation(),d(le=>{const oe=new Set(le);return oe.has(ee)?oe.delete(ee):oe.add(ee),oe})},z=()=>{if(!P?.files)return;const ee=P.files.filter(ue=>!ue.is_directory&&(!u||ue.name.toLowerCase().includes(u.toLowerCase()))).map(ue=>ue.path);d(new Set(ee))},X=()=>{d(new Set)},L=async()=>{if(c.size===0)return;const ee=Array.from(c);if(ee.length===1){me.downloadPrinterFile(t,ee[0]).catch(ue=>{console.error("Printer file download failed:",ue)}),d(new Set);return}b({current:0,total:ee.length});try{const ue=await me.downloadPrinterFilesAsZip(t,ee),le=URL.createObjectURL(ue),oe=document.createElement("a");oe.href=le,oe.download=`${e.replace(/[^a-zA-Z0-9]/g,"_")}-files.zip`,document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),URL.revokeObjectURL(le),i(`Downloaded ${ee.length} files as ZIP`),d(new Set)}catch(ue){i(`Download failed: ${ue instanceof Error?ue.message:"Unknown error"}`,"error")}finally{b(null)}},ne=()=>{c.size!==0&&f(Array.from(c))},ie=[{path:"/",label:"Root"},{path:"/cache",label:"Cache"},{path:"/model",label:"Models"},{path:"/timelapse",label:"Timelapse"}];return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:n,children:[a.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:ee=>ee.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(rp,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("printerFiles.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e})]})]}),a.jsxs("div",{className:"flex items-center gap-4",children:[T&&(T.used_bytes!=null||T.free_bytes!=null)&&a.jsxs("div",{className:"text-sm text-bambu-gray flex items-center gap-2",children:[T.used_bytes!=null&&a.jsxs("span",{children:[r("printerFiles.storageUsed")," ",R$(T.used_bytes)]}),T.used_bytes!=null&&T.free_bytes!=null&&a.jsx("span",{className:"text-bambu-dark-tertiary",children:"|"}),T.free_bytes!=null&&a.jsxs("span",{children:[r("printerFiles.storageFree")," ",R$(T.free_bytes)]})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:"Close file manager","aria-label":"Close file manager",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[ie.map(ee=>a.jsx("button",{onClick:()=>{k(ee.path),m("")},className:`px-3 py-1 text-sm rounded-full transition-colors ${o===ee.path?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:ee.label},ee.path)),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:r("printerFiles.filterPlaceholder"),value:u,onChange:ee=>m(ee.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"})]}),a.jsxs("div",{className:"relative flex items-center gap-1",children:[a.jsx(fO,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("select",{value:x,onChange:ee=>v(ee.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:FMe.map(ee=>a.jsx("option",{value:ee.value,children:ee.label},ee.value))})]}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>A(),disabled:N,children:a.jsx(cr,{className:`w-4 h-4 ${N?"animate-spin":""}`})})]}),a.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0",children:[a.jsx("button",{onClick:D,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:a.jsx(dl,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-bambu-gray font-mono",children:o})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:N?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):P?.files?.length?a.jsx("div",{className:"space-y-1",children:[...P.files].filter(ee=>!u||ee.name.toLowerCase().includes(u.toLowerCase())).sort((ee,ue)=>{if(ee.is_directory&&!ue.is_directory)return-1;if(!ee.is_directory&&ue.is_directory)return 1;switch(x){case"name-asc":return ee.name.localeCompare(ue.name);case"name-desc":return ue.name.localeCompare(ee.name);case"size-asc":return ee.size-ue.size;case"size-desc":return ue.size-ee.size;case"date-asc":{const le=ee.mtime?er(ee.mtime)?.getTime()??0:0,oe=ue.mtime?er(ue.mtime)?.getTime()??0:0;return le-oe}case"date-desc":{const le=ee.mtime?er(ee.mtime)?.getTime()??0:0;return(ue.mtime?er(ue.mtime)?.getTime()??0:0)-le}default:return ee.name.localeCompare(ue.name)}}).map(ee=>{const ue=DMe(ee.name,ee.is_directory),le=c.has(ee.path);return a.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${le?"bg-bambu-green/20 border border-bambu-green/50":"hover:bg-bambu-dark-tertiary"}`,onClick:()=>{ee.is_directory&&k(ee.path)},children:[ee.is_directory?null:a.jsx("button",{onClick:oe=>H(ee.path,oe),className:"flex-shrink-0 text-bambu-gray hover:text-white",children:le?a.jsx(xs,{className:"w-5 h-5 text-bambu-green"}):a.jsx(to,{className:"w-5 h-5"})}),a.jsx(ue,{className:`w-5 h-5 flex-shrink-0 ${ee.is_directory?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:"flex-1 text-white truncate",children:ee.name}),!ee.is_directory&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:Co(ee.size)}),(ee.name.toLowerCase().endsWith(".3mf")||ee.name.toLowerCase().endsWith(".gcode")||ee.name.toLowerCase().endsWith(".stl"))&&a.jsx("button",{onClick:oe=>{oe.stopPropagation(),C({path:ee.path,name:ee.name})},className:"p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green",title:"3D View",children:a.jsx(mi,{className:"w-4 h-4"})})]}),ee.is_directory&&a.jsx(dl,{className:"w-4 h-4 text-bambu-gray rotate-180"})]},ee.path)})}):a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"No files in this directory"})}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("div",{className:"text-sm text-bambu-gray",children:c.size>0?`${c.size} selected`:u?`${P?.files?.filter(ee=>ee.name.toLowerCase().includes(u.toLowerCase())).length||0} of ${P?.files?.length||0} items`:`${P?.files?.length||0} items`}),P?.files?.some(ee=>!ee.is_directory)&&a.jsx("div",{className:"flex items-center gap-2",children:c.size>0?a.jsxs("button",{onClick:X,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(xxe,{className:"w-4 h-4"}),"Deselect All"]}):a.jsxs("button",{onClick:z,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(xs,{className:"w-4 h-4"}),"Select All"]})})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",disabled:c.size===0||g!==null,onClick:L,children:g?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),g.current,"/",g.total]}):a.jsxs(a.Fragment,{children:[a.jsx(ca,{className:"w-4 h-4"}),"Download",c.size>1?` (${c.size})`:""]})}),a.jsxs(Fe,{variant:"secondary",disabled:c.size===0||F.isPending,onClick:ne,className:"text-red-400 hover:text-red-300",children:[F.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),r("printerFiles.deleteButton"),c.size>1?` (${c.size})`:""]})]})]})]}),p.length>0&&a.jsx(_n,{title:p.length>1?r("printerFiles.deleteFiles",{count:p.length}):r("fileManager.deleteFile"),message:p.length>1?r("printerFiles.deleteFilesConfirm",{count:p.length}):r("printerFiles.deleteFileConfirm",{name:p[0].split("/").pop()}),confirmText:r("common.delete"),variant:"danger",onConfirm:()=>{F.mutate(p)},onCancel:()=>f([])}),_&&a.jsx(EMe,{printerId:t,filePath:_.path,filename:_.name,onClose:()=>C(null)})]})}function iI({on:t,className:e="w-5 h-5"}){const n=t?"#facc15":"none",r=t?"#78350f":"currentColor",i=t?1:0;return a.jsxs("svg",{viewBox:"0 0 32 32",fill:"none",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[a.jsxs("g",{stroke:r,opacity:i,children:[a.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),a.jsx("line",{x1:"6.1",y1:"6.1",x2:"8.9",y2:"8.9"}),a.jsx("line",{x1:"25.9",y1:"6.1",x2:"23.1",y2:"8.9"}),a.jsx("line",{x1:"2",y1:"16",x2:"6",y2:"16"}),a.jsx("line",{x1:"30",y1:"16",x2:"26",y2:"16"})]}),a.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}),a.jsx("path",{d:"M12 24h8",stroke:r}),a.jsx("path",{d:"M12 27h8",stroke:r}),a.jsx("path",{d:"M13 30h6",stroke:r})]})}const VP=({className:t})=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[a.jsx("rect",{x:"2",y:"15",width:"5",height:"5",rx:"0.5"}),a.jsx("rect",{x:"9.5",y:"15",width:"5",height:"5",rx:"0.5",fill:"currentColor",opacity:"0.3"}),a.jsx("rect",{x:"17",y:"15",width:"5",height:"5",rx:"0.5"}),a.jsx("path",{d:"M4 12 C4 6, 14 6, 14 12"}),a.jsx("polyline",{points:"12,10 14,12 12,14"})]});function sI({printerId:t,isOpen:e,onClose:n}){const{t:r}=Rt(),{showToast:i}=bn(),{hasPermission:s}=wr(),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=Qe({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),refetchInterval:3e4,enabled:e}),{data:m,refetch:p}=Qe({queryKey:["printableObjects",t],queryFn:()=>me.getPrintableObjects(t),enabled:e,refetchInterval:e?5e3:!1}),f=it({mutationFn:x=>me.skipObjects(t,x),onSuccess:x=>{i(x.message||r("printers.skipObjects.objectsSkipped")),l(null),p()},onError:x=>i(x.message||r("printers.toast.failedToSkipObjects"),"error")});return e?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:n,onKeyDown:x=>{x.key==="Escape"&&(c?d(!1):n())},tabIndex:-1,ref:x=>x?.focus(),children:[a.jsx("div",{className:"absolute inset-0 bg-black/50 z-0"}),a.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:[a.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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(VP,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:r("printers.skipObjects.title")})]}),a.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:a.jsx(Bt,{className:"w-4 h-4"})})]}),m?m.objects.length===0?a.jsxs("div",{className:"text-center py-8 px-4 text-bambu-gray",children:[a.jsx("p",{className:"text-sm",children:r("printers.noObjectsFound")}),a.jsx("p",{className:"text-xs mt-1 opacity-70",children:r("printers.objectsLoadedOnPrintStart")})]}):a.jsxs("div",{className:"flex flex-col overflow-hidden",children:[a.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:[a.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:a.jsx(wO,{className:"w-4 h-4 text-blue-500 dark:text-blue-400"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300",children:r("printers.skipObjects.matchIdsInfo")}),a.jsx("p",{className:"text-[10px] text-blue-500/70 dark:text-blue-300/60",children:r("printers.skipObjects.printerShowsIds")})]}),a.jsxs("div",{className:"flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray",children:[m.skipped_count,"/",m.total," ",r("printers.skipObjects.skipped")]})]}),(u?.layer_num??0)<=1&&a.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:[a.jsx(Wa,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0"}),a.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:r("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0})})]}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.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:a.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>d(!0),children:[u?.cover_url?a.jsx("img",{src:za(`${u.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"}):a.jsx("div",{className:"w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center",children:a.jsx(mi,{className:"w-8 h-8 text-gray-300 dark:text-bambu-gray/30"})}),a.jsx("div",{className:"absolute top-2 right-2 p-1 bg-black/60 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(MP,{className:"w-3.5 h-3.5 text-white"})}),m.objects.length>0&&a.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((x,v)=>{let g,b;if(x.x!=null&&x.y!=null&&m.bbox_all){const[_,C,P,N]=m.bbox_all,A=P-_,T=N-C,F=8,k=100-F*2;g=F+(x.x-_)/A*k,b=F+(N-x.y)/T*k,g=Math.max(5,Math.min(95,g)),b=Math.max(5,Math.min(95,b))}else if(x.x!=null&&x.y!=null)g=x.x/256*100,b=100-x.y/256*100,g=Math.max(5,Math.min(95,g)),b=Math.max(5,Math.min(95,b));else{const _=Math.ceil(Math.sqrt(m.objects.length)),C=Math.floor(v/_),P=v%_,N=Math.ceil(m.objects.length/_);g=15+P*(70/_)+35/_,b=15+C*(70/N)+35/N}return a.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:`${b}%`,transform:"translate(-50%, -50%)"},title:x.name,children:x.id},x.id)})}),a.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:m.objects.filter(x=>!x.skipped).length})})]})}),a.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:m.objects.map(x=>a.jsxs("div",{className:`
- flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary/50 last:border-0
- ${x.skipped?"bg-red-50 dark:bg-red-500/10":"hover:bg-gray-50 dark:hover:bg-bambu-dark/50"}
- `,children:[a.jsxs("div",{className:`
- w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center
- ${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"}
- `,children:[a.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}),a.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"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.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&&a.jsx("span",{className:"text-[10px] text-red-400/60",children:r("printers.willBeSkipped")})]}),x.skipped?a.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")}):a.jsx("button",{onClick:()=>l({id:x.id,name:x.name}),disabled:f.isPending||(u?.layer_num??0)<=1||!s("printers:control"),className:`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${(u?.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")?(u?.layer_num??0)<=1?r("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0}):r("printers.skipObjects.skip"):r("printers.permission.noControl"),children:r("printers.skipObjects.skip")})]},x.id))})]})]}):a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(dt,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&a.jsx(_n,{variant:"warning",title:r("printers.skipObjects.confirmTitle"),message:r("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:r("printers.skipObjects.skip"),isLoading:f.isPending,onConfirm:()=>f.mutate([o.id]),onCancel:()=>l(null)}),c&&m&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>d(!1),children:[a.jsx("button",{onClick:()=>d(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})}),a.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:x=>x.stopPropagation(),children:[u?.cover_url?a.jsx("img",{src:`${u.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):a.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:a.jsx(mi,{className:"w-16 h-16 text-gray-500"})}),m.objects.length>0&&a.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((x,v)=>{let g,b;if(x.x!=null&&x.y!=null&&m.bbox_all){const[_,C,P,N]=m.bbox_all,A=P-_,T=N-C,F=8,k=100-F*2;g=F+(x.x-_)/A*k,b=F+(N-x.y)/T*k,g=Math.max(5,Math.min(95,g)),b=Math.max(5,Math.min(95,b))}else if(x.x!=null&&x.y!=null)g=x.x/256*100,b=100-x.y/256*100,g=Math.max(5,Math.min(95,g)),b=Math.max(5,Math.min(95,b));else{const _=Math.ceil(Math.sqrt(m.objects.length)),C=Math.floor(v/_),P=v%_,N=Math.ceil(m.objects.length/_);g=15+P*(70/_)+35/_,b=15+C*(70/N)+35/N}return a.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:`${b}%`,transform:"translate(-50%, -50%)"},title:x.name,children:x.id},x.id)})}),a.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:m.objects.filter(x=>!x.skipped).length})})]})]})]}):null}const LMe="embeddedCameraState_",L$=5,OMe=2e3,IMe=3e4,zMe=5e3,zE={x:window.innerWidth-420,y:20,width:400,height:300};function UMe({printerId:t,printerName:e,viewerIndex:n=0,onClose:r}){const{t:i}=Rt(),s=sn(),{showToast:o}=bn(),{hasPermission:l}=wr(),c=`${LMe}${t}`,d=()=>{try{const qe=localStorage.getItem(c);if(qe){const Ze=JSON.parse(qe);return{x:Math.min(Math.max(0,Ze.x),window.innerWidth-100),y:Math.min(Math.max(0,Ze.y),window.innerHeight-100),width:Math.max(200,Math.min(Ze.width,window.innerWidth-20)),height:Math.max(150,Math.min(Ze.height,window.innerHeight-20))}}}catch{}const Pe=n*30;return{...zE,x:Math.max(0,zE.x-Pe),y:Math.max(0,zE.y+Pe)}},[u,m]=w.useState(d),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[g,b]=w.useState({x:0,y:0}),[_,C]=w.useState(!1),[P,N]=w.useState(!1),[A,T]=w.useState(1),[F,k]=w.useState({x:0,y:0}),[D,H]=w.useState(!1),[z,X]=w.useState({x:0,y:0}),[L,ne]=w.useState(null),[ie,ee]=w.useState(null),[ue,le]=w.useState(!1),[oe,W]=w.useState(!0),[re,ce]=w.useState(Date.now()),[xe,Ne]=w.useState(0),[$,Y]=w.useState(!1),[E,j]=w.useState(0),O=w.useRef(null),K=w.useRef(null),B=w.useRef(null),he=w.useRef(null),I=w.useRef(null),[V,Q]=w.useState(!1),{data:G}=Qe({queryKey:["printer",t],queryFn:()=>me.getPrinter(t),enabled:t>0}),{data:J}=Qe({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),se=it({mutationFn:Pe=>me.setChamberLight(t,Pe),onMutate:async Pe=>{await s.cancelQueries({queryKey:["printerStatus",t]});const qe=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],Ze=>({...Ze,chamber_light:Pe})),{previousStatus:qe}},onSuccess:(Pe,qe)=>{o(`Chamber light ${qe?"on":"off"}`)},onError:(Pe,qe,Ze)=>{Ze?.previousStatus&&s.setQueryData(["printerStatus",t],Ze.previousStatus),o(Pe.message||i("printers.toast.failedToControlChamberLight"),"error")}}),fe=(J?.state==="RUNNING"||J?.state==="PAUSE")&&(J?.printable_objects_count??0)>=2;w.useEffect(()=>{const Pe=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(u))},500);return()=>clearTimeout(Pe)},[u,c]);const pe=w.useRef(!1);w.useEffect(()=>{pe.current=!1;const Pe=`/api/v1/printers/${t}/camera/stop`,qe=()=>{if(t>0&&!pe.current){pe.current=!0;const ut={},vt=om();vt&&(ut.Authorization=`Bearer ${vt}`),fetch(Pe,{method:"POST",keepalive:!0,headers:ut}).catch(()=>{})}},Ze=K.current;return()=>{Ze&&(Ze.src=""),qe(),B.current&&clearTimeout(B.current),he.current&&clearInterval(he.current),I.current&&clearInterval(I.current)}},[t]),w.useEffect(()=>{if(oe){const Pe=setTimeout(()=>W(!1),3e3);return()=>clearTimeout(Pe)}},[oe,re]);const de=w.useCallback(()=>{if(xe>=L$){Y(!1),le(!0);return}const Pe=Math.min(OMe*Math.pow(2,xe),IMe);Y(!0),j(Math.ceil(Pe/1e3)),he.current=setInterval(()=>{j(qe=>qe<=1?(he.current&&clearInterval(he.current),0):qe-1)},1e3),B.current=setTimeout(()=>{Ne(qe=>qe+1),Y(!1),W(!0),le(!1),K.current&&(K.current.src=""),ce(Date.now())},Pe)},[xe]);w.useEffect(()=>{if(oe||$||_){I.current&&(clearInterval(I.current),I.current=null);return}return I.current=setInterval(async()=>{try{const Pe=await me.getCameraStatus(t);(Pe.stalled||!Pe.active&&!ue)&&(I.current&&(clearInterval(I.current),I.current=null),W(!1),de())}catch{}},zMe),()=>{I.current&&(clearInterval(I.current),I.current=null)}},[oe,ue,$,_,t,de]),w.useEffect(()=>{const Pe=()=>{const qe=!!document.fullscreenElement;N(qe),qe||(T(1),k({x:0,y:0}))};return document.addEventListener("fullscreenchange",Pe),()=>document.removeEventListener("fullscreenchange",Pe)},[]);const U=()=>{O.current&&(document.fullscreenElement?document.exitFullscreen():O.current.requestFullscreen())},R=()=>{T(Pe=>Math.min(Pe+.5,4))},ae=()=>{T(Pe=>{const qe=Math.max(Pe-.5,1);return qe===1&&k({x:0,y:0}),qe})},_e=Pe=>{Pe.preventDefault(),Pe.deltaY<0?R():ae()},Se=Pe=>{A>1&&(Pe.preventDefault(),H(!0),X({x:Pe.clientX-F.x,y:Pe.clientY-F.y}))},ye=w.useCallback(()=>{if(!O.current||!K.current)return{x:200,y:150};const Pe=O.current.getBoundingClientRect(),qe=Pe.width*(A-1)/2,Ze=Pe.height*(A-1)/2;return{x:Math.max(50,qe),y:Math.max(50,Ze)}},[A]),Ae=Pe=>{if(D&&A>1){const qe=Pe.clientX-z.x,Ze=Pe.clientY-z.y,ut=ye();k({x:Math.max(-ut.x,Math.min(ut.x,qe)),y:Math.max(-ut.y,Math.min(ut.y,Ze))})}},ve=()=>{H(!1)},je=Pe=>{if(Pe.length<2)return 0;const qe=Pe[0].clientX-Pe[1].clientX,Ze=Pe[0].clientY-Pe[1].clientY;return Math.sqrt(qe*qe+Ze*Ze)},Re=Pe=>Pe.length<2?{x:Pe[0].clientX,y:Pe[0].clientY}:{x:(Pe[0].clientX+Pe[1].clientX)/2,y:(Pe[0].clientY+Pe[1].clientY)/2},Ee=Pe=>{Pe.touches.length===2?(Pe.preventDefault(),ne(je(Pe.touches)),ee(Re(Pe.touches))):Pe.touches.length===1&&A>1&&(Pe.preventDefault(),H(!0),X({x:Pe.touches[0].clientX-F.x,y:Pe.touches[0].clientY-F.y}))},Te=Pe=>{if(Pe.touches.length===2&&L!==null){Pe.preventDefault();const qe=je(Pe.touches),Ze=qe/L;T(vt=>{const wt=Math.max(1,Math.min(4,vt*Ze));return wt===1&&k({x:0,y:0}),wt}),ne(qe);const ut=Re(Pe.touches);if(ie){const vt=ye();k(wt=>({x:Math.max(-vt.x,Math.min(vt.x,wt.x+(ut.x-ie.x))),y:Math.max(-vt.y,Math.min(vt.y,wt.y+(ut.y-ie.y)))}))}ee(ut)}else if(Pe.touches.length===1&&D&&A>1){Pe.preventDefault();const qe=Pe.touches[0].clientX-z.x,Ze=Pe.touches[0].clientY-z.y,ut=ye();k({x:Math.max(-ut.x,Math.min(ut.x,qe)),y:Math.max(-ut.y,Math.min(ut.y,Ze))})}},Me=Pe=>{Pe.touches.length<2&&(ne(null),ee(null)),Pe.touches.length===0&&H(!1)},Be=()=>{T(1),k({x:0,y:0})},Ke=()=>{W(!1),xe<L$?de():le(!0)},tt=()=>{W(!1),le(!1),Ne(0),Y(!1),B.current&&clearTimeout(B.current),he.current&&clearInterval(he.current)},te=()=>{W(!0),le(!1),Ne(0),Y(!1),B.current&&clearTimeout(B.current),he.current&&clearInterval(he.current);const Pe={},qe=om();qe&&(Pe.Authorization=`Bearer ${qe}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Pe}).catch(()=>{}),K.current&&(K.current.src=""),setTimeout(()=>ce(Date.now()),100)},Ie=Pe=>{Pe.target.closest(".no-drag")||(f(!0),b({x:Pe.clientX-u.x,y:Pe.clientY-u.y}))},be=Pe=>{if(Pe.target.closest(".no-drag"))return;const qe=Pe.touches[0];f(!0),b({x:qe.clientX-u.x,y:qe.clientY-u.y})},$e=Pe=>{Pe.stopPropagation(),v(!0)},He=Pe=>{Pe.stopPropagation(),v(!0)};w.useEffect(()=>{const Pe=ut=>{if(p)m(vt=>({...vt,x:Math.max(0,Math.min(ut.clientX-g.x,window.innerWidth-vt.width)),y:Math.max(0,Math.min(ut.clientY-g.y,window.innerHeight-vt.height))}));else if(x&&O.current){const vt=O.current.getBoundingClientRect();m(wt=>({...wt,width:Math.max(200,Math.min(ut.clientX-vt.left,window.innerWidth-wt.x-10)),height:Math.max(150,Math.min(ut.clientY-vt.top,window.innerHeight-wt.y-10))}))}},qe=ut=>{if(!p&&!x)return;ut.preventDefault();const vt=ut.touches[0];if(p)m(wt=>({...wt,x:Math.max(0,Math.min(vt.clientX-g.x,window.innerWidth-wt.width)),y:Math.max(0,Math.min(vt.clientY-g.y,window.innerHeight-wt.height))}));else if(x&&O.current){const wt=O.current.getBoundingClientRect();m($t=>({...$t,width:Math.max(200,Math.min(vt.clientX-wt.left,window.innerWidth-$t.x-10)),height:Math.max(150,Math.min(vt.clientY-wt.top,window.innerHeight-$t.y-10))}))}},Ze=()=>{f(!1),v(!1)};if(p||x)return document.addEventListener("mousemove",Pe),document.addEventListener("mouseup",Ze),document.addEventListener("touchmove",qe,{passive:!1}),document.addEventListener("touchend",Ze),document.addEventListener("touchcancel",Ze),()=>{document.removeEventListener("mousemove",Pe),document.removeEventListener("mouseup",Ze),document.removeEventListener("touchmove",qe),document.removeEventListener("touchend",Ze),document.removeEventListener("touchcancel",Ze)}},[p,x,g]);const ge=za(`/api/v1/printers/${t}/camera/stream?fps=15&t=${re}`);return a.jsxs("div",{ref:O,className:`${P?"fixed inset-0 z-[100]":"fixed z-40 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:P?void 0:{left:u.x,top:u.y,width:_?200:u.width,height:_?40:u.height,cursor:p?"grabbing":"default"},children:[a.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:Ie,onTouchStart:be,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[a.jsx($h,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:G?.name||e})]}),a.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[a.jsx("button",{onClick:()=>se.mutate(!J?.chamber_light),disabled:!J?.connected||se.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${J?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:l("printers:control")?i("camera.chamberLight"):i("printers.permission.noControl"),children:a.jsx(iI,{on:J?.chamber_light??!1,className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>Q(!0),disabled:!fe||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${fe&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?i(fe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):i("printers.permission.noControl"),children:a.jsx(VP,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:te,disabled:oe||$,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:a.jsx(cr,{className:`w-3.5 h-3.5 text-bambu-gray ${oe?"animate-spin":""}`})}),a.jsx("button",{onClick:U,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:P?"Exit fullscreen":"Fullscreen",children:P?a.jsx(jQ,{className:"w-3.5 h-3.5 text-bambu-gray"}):a.jsx(gge,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:()=>C(!_),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:_?"Expand":"Minimize",children:_?a.jsx(MP,{className:"w-3.5 h-3.5 text-bambu-gray"}):a.jsx(vO,{className:"w-3.5 h-3.5 text-bambu-gray"})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:a.jsx(Bt,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!_&&a.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:_e,onMouseMove:Ae,onMouseUp:ve,onMouseLeave:ve,onTouchStart:Ee,onTouchMove:Te,onTouchEnd:Me,style:{touchAction:"none"},children:[oe&&!$&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsx(cr,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),$&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-2",children:[a.jsx(Md,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",E,"s..."]})]})}),ue&&!$&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-2",children:[a.jsx(Rn,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Camera unavailable"}),a.jsx("button",{onClick:te,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:"Retry"})]})}),a.jsx("img",{ref:K,src:ge,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${A}) translate(${F.x/A}px, ${F.y/A}px) rotate(${G?.camera_rotation||0}deg)`,...G?.camera_rotation===90||G?.camera_rotation===270?{maxWidth:"100%",maxHeight:"100%"}:{},cursor:A>1?D?"grabbing":"grab":"default"},onError:Ke,onLoad:tt,onMouseDown:Se,draggable:!1},re),a.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:[a.jsx("button",{onClick:ae,disabled:A<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:a.jsx(CO,{className:"w-3.5 h-3.5 text-white"})}),a.jsxs("button",{onClick:Be,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(A*100),"%"]}),a.jsx("button",{onClick:R,disabled:A>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:a.jsx(NO,{className:"w-3.5 h-3.5 text-white"})})]}),!P&&a.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:$e,onTouchStart:He,title:"Drag to resize",children:a.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:a.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),a.jsx(sI,{printerId:t,isOpen:V,onClose:()=>Q(!1)})]})}function BMe({printerId:t,printerName:e,onClose:n}){const{t:r}=Rt(),i=sn(),[s,o]=w.useState(!0),[l,c]=w.useState(new Set),[d,u]=w.useState(""),[m,p]=w.useState("all"),f=w.useRef(null),{data:x,isLoading:v,refetch:g}=Qe({queryKey:["mqtt-logs",t],queryFn:()=>me.getMQTTLogs(t),refetchInterval:1e3}),b=it({mutationFn:()=>me.enableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),_=it({mutationFn:()=>me.disableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),C=it({mutationFn:()=>me.clearMQTTLogs(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}});w.useEffect(()=>{const D=H=>{H.key==="Escape"&&n()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[n]),w.useEffect(()=>{s&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[x?.logs,s]);const P=D=>{c(H=>{const z=new Set(H);return z.has(D)?z.delete(D):z.add(D),z})},N=D=>new Date(D).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),A=(D,H)=>{if(D==null)return"<empty>";const z=typeof D=="string"?JSON.parse(D):D,X=JSON.stringify(z,null,H?2:0);return!H&&X.length>100?X.substring(0,100)+"...":X},T=x?.logging_enabled??!1,F=w.useMemo(()=>x?.logs??[],[x?.logs]),k=w.useMemo(()=>F.filter(D=>{if(m!=="all"&&D.direction!==m)return!1;if(d.trim()){const H=d.toLowerCase(),z=D.topic.toLowerCase().includes(H),L=JSON.stringify(D.payload).toLowerCase().includes(H);return z||L}return!0}),[F,d,m]);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("mqttDebug.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[T?a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),disabled:_.isPending,children:[a.jsx(to,{className:"w-4 h-4"}),r("mqttDebug.stopLogging")]}):a.jsxs(Fe,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending,children:[a.jsx($i,{className:"w-4 h-4"}),r("mqttDebug.startLogging")]}),a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>C.mutate(),disabled:C.isPending||F.length===0,children:[a.jsx(rn,{className:"w-4 h-4"}),r("mqttDebug.clearLog")]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:v,children:a.jsx(cr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:s,onChange:D=>o(D.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[k.length,"/",F.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:r("mqttDebug.searchPlaceholder"),value:d,onChange:D=>u(D.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"}),d&&a.jsx("button",{onClick:()=>u(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>p("all"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${m==="all"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:r("mqttDebug.all")}),a.jsxs("button",{onClick:()=>p("in"),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${m==="in"?"bg-blue-500 text-white":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Cx,{className:"w-3 h-3"}),r("mqttDebug.incoming")]}),a.jsxs("button",{onClick:()=>p("out"),className:`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${m==="out"?"bg-green-500 text-white":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Wf,{className:"w-3 h-3"}),r("mqttDebug.outgoing")]})]})]})]}),a.jsx("div",{ref:f,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:F.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessages")}),!T&&a.jsx("p",{className:"text-sm",children:r("mqttDebug.startLoggingHint")})]}):k.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessagesMatch")}),a.jsx("p",{className:"text-sm",children:r("mqttDebug.adjustFilterHint")})]}):a.jsx("div",{className:"space-y-1",children:k.map((D,H)=>{const z=l.has(H),X=D.direction==="in";return a.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${z?"bg-bambu-dark-secondary":""}`,onClick:()=>P(H),children:[a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-bambu-gray shrink-0",children:N(D.timestamp)}),a.jsx("span",{className:`shrink-0 ${X?"text-blue-400":"text-green-400"}`,title:r(X?"mqttDebug.incoming":"mqttDebug.outgoing"),children:X?a.jsx(Cx,{className:"w-3 h-3"}):a.jsx(Wf,{className:"w-3 h-3"})}),a.jsx("span",{className:"text-purple-400 shrink-0",children:D.topic})]}),z?a.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:A(D.payload,!0)}):a.jsx("pre",{className:"mt-1 text-white/80 truncate",children:A(D.payload,!1)})]},H)})})}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-sm text-bambu-gray",children:T?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),r("mqttDebug.loggingActive")]}):a.jsx("span",{children:r("mqttDebug.loggingStopped")})}),a.jsx(Fe,{variant:"secondary",onClick:n,children:r("common.close")})]})]})})}function wJ(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 SJ(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 _J(t,e,n){return t.filter(r=>{if(r.required_filament_types&&r.required_filament_types.length>0&&e!==void 0&&!r.required_filament_types.every(i=>e.has(i.toUpperCase())))return!1;if(r.filament_overrides&&r.filament_overrides.length>0&&n!==void 0){const i=r.filament_overrides.filter(o=>o.force_color_match===!0),s=r.filament_overrides.filter(o=>o.force_color_match!==!0);if(i.length>0&&!i.every(l=>{const c=(l.type||"").toUpperCase(),d=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${d}`)})||s.length>0&&i.length===0&&!s.some(l=>{const c=(l.type||"").toUpperCase(),d=(l.color||"").replace("#","").toLowerCase().slice(0,6);return n.has(`${c}:${d}`)}))return!1}return!0})}function HMe({printerId:t,printerModel:e,awaitingPlateClear:n,requirePlateClear:r=!1,loadedFilamentTypes:i,loadedFilaments:s}){const{t:o}=Rt(),l=sn(),{showToast:c}=bn(),{hasPermission:d}=wr(),{data:u}=Qe({queryKey:["queue",t,"pending",e],queryFn:()=>me.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),m=it({mutationFn:()=>me.clearPlate(t),onSuccess:()=>{l.invalidateQueries({queryKey:["queue",t]}),l.invalidateQueries({queryKey:["printerStatus",t]}),c(o("queue.clearPlateSuccess"),"success")},onError:_=>{c(_.message,"error")}});w.useEffect(()=>{n||m.reset()},[n,m]);const p=u?_J(u,i,s):void 0,f=p?.filter(_=>!_.manual_start)??[],x=p?.length||0;if(x===0)return null;const v=f[0],g=p?.[0];if(r&&!!n&&f.length>0){const _=v||g;return a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[a.jsx(Yr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),a.jsx("p",{className:"text-sm text-white truncate",children:_?.archive_name||_?.library_file_name||`File #${_?.archive_id||_?.library_file_id}`})]}),x>1&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0",children:["+",x-1]})]}),m.isSuccess?a.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:[a.jsx(nl,{className:"w-4 h-4"}),o("queue.plateReady")]}):a.jsxs("button",{onClick:()=>m.mutate(),disabled:m.isPending||!d("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:[m.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(nl,{className:"w-4 h-4"}),o("queue.clearPlate")]})]})}return a.jsx(_o,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx(Yr,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:o("queue.nextInQueue")}),a.jsx("p",{className:"text-sm text-white truncate",children:g?.archive_name||g?.library_file_name||`File #${g?.archive_id||g?.library_file_id}`})]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),g?.scheduled_time?Gh(g.scheduled_time,"system",o):o("time.waiting")]}),x>1&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",x-1]}),a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function kJ(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=kJ(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function _r(){for(var t,e,n=0,r="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=kJ(t))&&(r&&(r+=" "),r+=e);return r}var qMe=["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 oI(t){if(typeof t!="string")return!1;var e=qMe;return e.includes(t)}var $Me=["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"],VMe=new Set($Me);function NJ(t){return typeof t!="string"?!1:VMe.has(t)}function CJ(t){return typeof t=="string"&&t.startsWith("data-")}function no(t){if(typeof t!="object"||t===null)return{};var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(NJ(n)||CJ(n))&&(e[n]=t[n]);return e}function ag(t){if(t==null)return null;if(w.isValidElement(t)&&typeof t.props=="object"&&t.props!==null){var e=t.props;return no(e)}return typeof t=="object"&&!Array.isArray(t)?no(t):null}function ys(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(NJ(n)||CJ(n)||oI(n))&&(e[n]=t[n]);return e}function GMe(t){return t==null?null:w.isValidElement(t)?ys(t.props):typeof t=="object"&&!Array.isArray(t)?ys(t):null}var WMe=["children","width","height","viewBox","className","style","title","desc"];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 KMe(t,e){if(t==null)return{};var n,r,i=XMe(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)&&(i[n]=t[n])}return i}function XMe(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 lI=w.forwardRef((t,e)=>{var{children:n,width:r,height:i,viewBox:s,className:o,style:l,title:c,desc:d}=t,u=KMe(t,WMe),m=s||{width:r,height:i,x:0,y:0},p=_r("recharts-surface",o);return w.createElement("svg",sR({},ys(u),{className:p,width:r,height:i,style:l,viewBox:"".concat(m.x," ").concat(m.y," ").concat(m.width," ").concat(m.height),ref:e}),w.createElement("title",null,c),w.createElement("desc",null,d),n)}),YMe=["children","className"];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)}function QMe(t,e){if(t==null)return{};var n,r,i=ZMe(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)&&(i[n]=t[n])}return i}function ZMe(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 Ea=w.forwardRef((t,e)=>{var{children:n,className:r}=t,i=QMe(t,YMe),s=_r("recharts-layer",r);return w.createElement("g",oR({className:s},ys(i),{ref:e}),n)}),PJ=w.createContext(null),JMe=()=>w.useContext(PJ);function la(t){return function(){return t}}const TJ=Math.cos,PN=Math.sin,Gc=Math.sqrt,TN=Math.PI,GP=2*TN,lR=Math.PI,cR=2*lR,cf=1e-6,eEe=cR-cf;function AJ(t){this._+=t[0];for(let e=1,n=t.length;e<n;++e)this._+=arguments[e]+t[e]}function tEe(t){let e=Math.floor(t);if(!(e>=0))throw new Error(`invalid digits: ${t}`);if(e>15)return AJ;const n=10**e;return function(r){this._+=r[0];for(let i=1,s=r.length;i<s;++i)this._+=Math.round(arguments[i]*n)/n+r[i]}}class nEe{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?AJ:tEe(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,i){this._append`Q${+e},${+n},${this._x1=+r},${this._y1=+i}`}bezierCurveTo(e,n,r,i,s,o){this._append`C${+e},${+n},${+r},${+i},${this._x1=+s},${this._y1=+o}`}arcTo(e,n,r,i,s){if(e=+e,n=+n,r=+r,i=+i,s=+s,s<0)throw new Error(`negative radius: ${s}`);let o=this._x1,l=this._y1,c=r-e,d=i-n,u=o-e,m=l-n,p=u*u+m*m;if(this._x1===null)this._append`M${this._x1=e},${this._y1=n}`;else if(p>cf)if(!(Math.abs(m*c-d*u)>cf)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let f=r-o,x=i-l,v=c*c+d*d,g=f*f+x*x,b=Math.sqrt(v),_=Math.sqrt(p),C=s*Math.tan((lR-Math.acos((v+p-g)/(2*b*_)))/2),P=C/_,N=C/b;Math.abs(P-1)>cf&&this._append`L${e+P*u},${n+P*m}`,this._append`A${s},${s},0,0,${+(m*f>u*x)},${this._x1=e+N*c},${this._y1=n+N*d}`}}arc(e,n,r,i,s,o){if(e=+e,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(i),c=r*Math.sin(i),d=e+l,u=n+c,m=1^o,p=o?i-s:s-i;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>cf||Math.abs(this._y1-u)>cf)&&this._append`L${d},${u}`,r&&(p<0&&(p=p%cR+cR),p>eEe?this._append`A${r},${r},0,1,${m},${e-l},${n-c}A${r},${r},0,1,${m},${this._x1=d},${this._y1=u}`:p>cf&&this._append`A${r},${r},0,${+(p>=lR)},${m},${this._x1=e+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(e,n,r,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+i}h${-r}Z`}toString(){return this._}}function cI(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 nEe(e)}function dI(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function jJ(t){this._context=t}jJ.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 WP(t){return new jJ(t)}function MJ(t){return t[0]}function EJ(t){return t[1]}function DJ(t,e){var n=la(!0),r=null,i=WP,s=null,o=cI(l);t=typeof t=="function"?t:t===void 0?MJ:la(t),e=typeof e=="function"?e:e===void 0?EJ:la(e);function l(c){var d,u=(c=dI(c)).length,m,p=!1,f;for(r==null&&(s=i(f=o())),d=0;d<=u;++d)!(d<u&&n(m=c[d],d,c))===p&&((p=!p)?s.lineStart():s.lineEnd()),p&&s.point(+t(m,d,c),+e(m,d,c));if(f)return s=null,f+""||null}return l.x=function(c){return arguments.length?(t=typeof c=="function"?c:la(+c),l):t},l.y=function(c){return arguments.length?(e=typeof c=="function"?c:la(+c),l):e},l.defined=function(c){return arguments.length?(n=typeof c=="function"?c:la(!!c),l):n},l.curve=function(c){return arguments.length?(i=c,r!=null&&(s=i(r)),l):i},l.context=function(c){return arguments.length?(c==null?r=s=null:s=i(r=c),l):r},l}function R1(t,e,n){var r=null,i=la(!0),s=null,o=WP,l=null,c=cI(d);t=typeof t=="function"?t:t===void 0?MJ:la(+t),e=typeof e=="function"?e:la(e===void 0?0:+e),n=typeof n=="function"?n:n===void 0?EJ:la(+n);function d(m){var p,f,x,v=(m=dI(m)).length,g,b=!1,_,C=new Array(v),P=new Array(v);for(s==null&&(l=o(_=c())),p=0;p<=v;++p){if(!(p<v&&i(g=m[p],p,m))===b)if(b=!b)f=p,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),x=p-1;x>=f;--x)l.point(C[x],P[x]);l.lineEnd(),l.areaEnd()}b&&(C[p]=+t(g,p,m),P[p]=+e(g,p,m),l.point(r?+r(g,p,m):C[p],n?+n(g,p,m):P[p]))}if(_)return l=null,_+""||null}function u(){return DJ().defined(i).curve(o).context(s)}return d.x=function(m){return arguments.length?(t=typeof m=="function"?m:la(+m),r=null,d):t},d.x0=function(m){return arguments.length?(t=typeof m=="function"?m:la(+m),d):t},d.x1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:la(+m),d):r},d.y=function(m){return arguments.length?(e=typeof m=="function"?m:la(+m),n=null,d):e},d.y0=function(m){return arguments.length?(e=typeof m=="function"?m:la(+m),d):e},d.y1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:la(+m),d):n},d.lineX0=d.lineY0=function(){return u().x(t).y(e)},d.lineY1=function(){return u().x(t).y(n)},d.lineX1=function(){return u().x(r).y(e)},d.defined=function(m){return arguments.length?(i=typeof m=="function"?m:la(!!m),d):i},d.curve=function(m){return arguments.length?(o=m,s!=null&&(l=o(s)),d):o},d.context=function(m){return arguments.length?(m==null?s=l=null:l=o(s=m),d):s},d}class FJ{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 rEe(t){return new FJ(t,!0)}function aEe(t){return new FJ(t,!1)}const uI={draw(t,e){const n=Gc(e/TN);t.moveTo(n,0),t.arc(0,0,n,0,GP)}},iEe={draw(t,e){const n=Gc(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()}},RJ=Gc(1/3),sEe=RJ*2,oEe={draw(t,e){const n=Gc(e/sEe),r=n*RJ;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},lEe={draw(t,e){const n=Gc(e),r=-n/2;t.rect(r,r,n,n)}},cEe=.8908130915292852,LJ=PN(TN/10)/PN(7*TN/10),dEe=PN(GP/10)*LJ,uEe=-TJ(GP/10)*LJ,mEe={draw(t,e){const n=Gc(e*cEe),r=dEe*n,i=uEe*n;t.moveTo(0,-n),t.lineTo(r,i);for(let s=1;s<5;++s){const o=GP*s/5,l=TJ(o),c=PN(o);t.lineTo(c*n,-l*n),t.lineTo(l*r-c*i,c*r+l*i)}t.closePath()}},UE=Gc(3),hEe={draw(t,e){const n=-Gc(e/(UE*3));t.moveTo(0,n*2),t.lineTo(-UE*n,-n),t.lineTo(UE*n,-n),t.closePath()}},Dl=-.5,Fl=Gc(3)/2,dR=1/Gc(12),pEe=(dR/2+1)*3,fEe={draw(t,e){const n=Gc(e/pEe),r=n/2,i=n*dR,s=r,o=n*dR+n,l=-s,c=o;t.moveTo(r,i),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(Dl*r-Fl*i,Fl*r+Dl*i),t.lineTo(Dl*s-Fl*o,Fl*s+Dl*o),t.lineTo(Dl*l-Fl*c,Fl*l+Dl*c),t.lineTo(Dl*r+Fl*i,Dl*i-Fl*r),t.lineTo(Dl*s+Fl*o,Dl*o-Fl*s),t.lineTo(Dl*l+Fl*c,Dl*c-Fl*l),t.closePath()}};function gEe(t,e){let n=null,r=cI(i);t=typeof t=="function"?t:la(t||uI),e=typeof e=="function"?e:la(e===void 0?64:+e);function i(){let s;if(n||(n=s=r()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),s)return n=null,s+""||null}return i.type=function(s){return arguments.length?(t=typeof s=="function"?s:la(s),i):t},i.size=function(s){return arguments.length?(e=typeof s=="function"?s:la(+s),i):e},i.context=function(s){return arguments.length?(n=s??null,i):n},i}function AN(){}function jN(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 OJ(t){this._context=t}OJ.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:jN(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:jN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function bEe(t){return new OJ(t)}function IJ(t){this._context=t}IJ.prototype={areaStart:AN,areaEnd:AN,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:jN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function xEe(t){return new IJ(t)}function zJ(t){this._context=t}zJ.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:jN(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function yEe(t){return new zJ(t)}function UJ(t){this._context=t}UJ.prototype={areaStart:AN,areaEnd:AN,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 vEe(t){return new UJ(t)}function O$(t){return t<0?-1:1}function I$(t,e,n){var r=t._x1-t._x0,i=e-t._x1,s=(t._y1-t._y0)/(r||i<0&&-0),o=(n-t._y1)/(i||r<0&&-0),l=(s*i+o*r)/(r+i);return(O$(s)+O$(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function z$(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function BE(t,e,n){var r=t._x0,i=t._y0,s=t._x1,o=t._y1,l=(s-r)/3;t._context.bezierCurveTo(r+l,i+l*e,s-l,o-l*n,s,o)}function MN(t){this._context=t}MN.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:BE(this,this._t0,z$(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,BE(this,z$(this,n=I$(this,t,e)),n);break;default:BE(this,this._t0,n=I$(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function BJ(t){this._context=new HJ(t)}(BJ.prototype=Object.create(MN.prototype)).point=function(t,e){MN.prototype.point.call(this,e,t)};function HJ(t){this._context=t}HJ.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,i,s){this._context.bezierCurveTo(e,t,r,n,s,i)}};function wEe(t){return new MN(t)}function SEe(t){return new BJ(t)}function qJ(t){this._context=t}qJ.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=U$(t),i=U$(e),s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(r[0][s],i[0][s],r[1][s],i[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 U$(t){var e,n=t.length-1,r,i=new Array(n),s=new Array(n),o=new Array(n);for(i[0]=0,s[0]=2,o[0]=t[0]+2*t[1],e=1;e<n-1;++e)i[e]=1,s[e]=4,o[e]=4*t[e]+2*t[e+1];for(i[n-1]=2,s[n-1]=7,o[n-1]=8*t[n-1]+t[n],e=1;e<n;++e)r=i[e]/s[e-1],s[e]-=r,o[e]-=r*o[e-1];for(i[n-1]=o[n-1]/s[n-1],e=n-2;e>=0;--e)i[e]=(o[e]-i[e+1])/s[e];for(s[n-1]=(t[n]+i[n-1])/2,e=0;e<n-1;++e)s[e]=2*t[e+1]-i[e+1];return[i,s]}function _Ee(t){return new qJ(t)}function KP(t,e){this._context=t,this._t=e}KP.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 kEe(t){return new KP(t,.5)}function NEe(t){return new KP(t,0)}function CEe(t){return new KP(t,1)}function ig(t,e){if((o=t.length)>1)for(var n=1,r,i,s=t[e[0]],o,l=s.length;n<o;++n)for(i=s,s=t[e[n]],r=0;r<l;++r)s[r][1]+=s[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function uR(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function PEe(t,e){return t[e]}function TEe(t){const e=[];return e.key=t,e}function AEe(){var t=la([]),e=uR,n=ig,r=PEe;function i(s){var o=Array.from(t.apply(this,arguments),TEe),l,c=o.length,d=-1,u;for(const m of s)for(l=0,++d;l<c;++l)(o[l][d]=[0,+r(m,o[l].key,d,s)]).data=m;for(l=0,u=dI(e(o));l<c;++l)o[u[l]].index=l;return n(o,u),o}return i.keys=function(s){return arguments.length?(t=typeof s=="function"?s:la(Array.from(s)),i):t},i.value=function(s){return arguments.length?(r=typeof s=="function"?s:la(+s),i):r},i.order=function(s){return arguments.length?(e=s==null?uR:typeof s=="function"?s:la(Array.from(s)),i):e},i.offset=function(s){return arguments.length?(n=s??ig,i):n},i}function jEe(t,e){if((r=t.length)>0){for(var n,r,i=0,s=t[0].length,o;i<s;++i){for(o=n=0;n<r;++n)o+=t[n][i][1]||0;if(o)for(n=0;n<r;++n)t[n][i][1]/=o}ig(t,e)}}function MEe(t,e){if((i=t.length)>0){for(var n=0,r=t[e[0]],i,s=r.length;n<s;++n){for(var o=0,l=0;o<i;++o)l+=t[o][n][1]||0;r[n][1]+=r[n][0]=-l/2}ig(t,e)}}function EEe(t,e){if(!(!((o=t.length)>0)||!((s=(i=t[e[0]]).length)>0))){for(var n=0,r=1,i,s,o;r<s;++r){for(var l=0,c=0,d=0;l<o;++l){for(var u=t[e[l]],m=u[r][1]||0,p=u[r-1][1]||0,f=(m-p)/2,x=0;x<l;++x){var v=t[e[x]],g=v[r][1]||0,b=v[r-1][1]||0;f+=g-b}c+=m,d+=f*m}i[r-1][1]+=i[r-1][0]=n,c&&(n-=d/c)}i[r-1][1]+=i[r-1][0]=n,ig(t,e)}}var HE={},qE={},B$;function DEe(){return B$||(B$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==="__proto__"}t.isUnsafeProperty=e})(qE)),qE}var $E={},H$;function $J(){return H$||(H$=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})($E)),$E}var VE={},q$;function mI(){return q$||(q$=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})(VE)),VE}var GE={},WE={},$$;function FEe(){return $$||($$=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})(WE)),WE}var V$;function hI(){return V$||(V$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=FEe(),n=mI();function r(i){if(Array.isArray(i))return i.map(n.toKey);if(typeof i=="symbol")return[i];i=e.toString(i);const s=[],o=i.length;if(o===0)return s;let l=0,c="",d="",u=!1;for(i.charCodeAt(0)===46&&(s.push(""),l++);l<o;){const m=i[l];d?m==="\\"&&l+1<o?(l++,c+=i[l]):m===d?d="":c+=m:u?m==='"'||m==="'"?d=m:m==="]"?(u=!1,s.push(c),c=""):c+=m:m==="["?(u=!0,c&&(s.push(c),c="")):m==="."?c&&(s.push(c),c=""):c+=m,l++}return c&&s.push(c),s}t.toPath=r})(GE)),GE}var G$;function pI(){return G$||(G$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=DEe(),n=$J(),r=mI(),i=hI();function s(l,c,d){if(l==null)return d;switch(typeof c){case"string":{if(e.isUnsafeProperty(c))return d;const u=l[c];return u===void 0?n.isDeepKey(c)?s(l,i.toPath(c),d):d:u}case"number":case"symbol":{typeof c=="number"&&(c=r.toKey(c));const u=l[c];return u===void 0?d:u}default:{if(Array.isArray(c))return o(l,c,d);if(Object.is(c?.valueOf(),-0)?c="-0":c=String(c),e.isUnsafeProperty(c))return d;const u=l[c];return u===void 0?d:u}}}function o(l,c,d){if(c.length===0)return d;let u=l;for(let m=0;m<c.length;m++){if(u==null||e.isUnsafeProperty(c[m]))return d;u=u[c[m]]}return u===void 0?d:u}t.get=s})(HE)),HE}var KE,W$;function REe(){return W$||(W$=1,KE=pI().get),KE}var LEe=REe();const sg=mc(LEe);var OEe=4;function Dh(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:OEe,n=10**e,r=Math.round(t*n)/n;return Object.is(r,-0)?0:r}function Ba(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((i,s,o)=>{var l=n[o-1];return typeof l=="string"?i+l+s:l!==void 0?i+Dh(l)+s:i+s},"")}var Bi=t=>t===0?0:t>0?1:-1,Bc=t=>typeof t=="number"&&t!=+t,og=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,an=t=>(typeof t=="number"||t instanceof Number)&&!Bc(t),lc=t=>an(t)||typeof t=="string",IEe=0,ew=t=>{var e=++IEe;return"".concat(t||"").concat(e)},Ds=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!an(e)&&typeof e!="string")return r;var s;if(og(e)){if(n==null)return r;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return Bc(s)&&(s=r),i&&n!=null&&s>n&&(s=n),s},VJ=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 Dr(t,e,n){return an(t)&&an(e)?Dh(t+n*(e-t)):e}function GJ(t,e,n){if(!(!t||!t.length))return t.find(r=>r&&(typeof e=="function"?e(r):sg(r,e))===n)}var Ca=t=>t===null||typeof t>"u",Kw=t=>Ca(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function Po(t){return t!=null}function gp(){}var zEe=["type","size","sizeType"];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 K$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).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?K$(Object(n),!0).forEach(function(r){UEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):K$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function UEe(t,e,n){return(e=BEe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function BEe(t){var e=HEe(t,"string");return typeof e=="symbol"?e:e+""}function HEe(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 qEe(t,e){if(t==null)return{};var n,r,i=$Ee(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)&&(i[n]=t[n])}return i}function $Ee(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 WJ={symbolCircle:uI,symbolCross:iEe,symbolDiamond:oEe,symbolSquare:lEe,symbolStar:mEe,symbolTriangle:hEe,symbolWye:fEe},VEe=Math.PI/180,GEe=t=>{var e="symbol".concat(Kw(t));return WJ[e]||uI},WEe=(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*VEe;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}},KEe=(t,e)=>{WJ["symbol".concat(Kw(t))]=e},fI=t=>{var{type:e="circle",size:n=64,sizeType:r="area"}=t,i=qEe(t,zEe),s=X$(X$({},i),{},{type:e,size:n,sizeType:r}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var p=GEe(o),f=gEe().type(p).size(WEe(n,r,o)),x=f();if(x!==null)return x},{className:c,cx:d,cy:u}=s,m=ys(s);return an(d)&&an(u)&&an(n)?w.createElement("path",mR({},m,{className:_r("recharts-symbols",c),transform:"translate(".concat(d,", ").concat(u,")"),d:l()})):null};fI.registerSymbol=KEe;var KJ=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,gI=(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(i=>{oI(i)&&(r[i]=(s=>n[i](n,s)))}),r},XEe=(t,e,n)=>r=>(t(e,n,r),null),Xw=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var r=null;return Object.keys(t).forEach(i=>{var s=t[i];oI(i)&&typeof s=="function"&&(r||(r={}),r[i]=XEe(s,e,n))}),r};function Y$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function YEe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Y$(Object(n),!0).forEach(function(r){QEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Y$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function QEe(t,e,n){return(e=ZEe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ZEe(t){var e=JEe(t,"string");return typeof e=="symbol"?e:e+""}function JEe(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 Da(t,e){var n=YEe({},t),r=e,i=Object.keys(e),s=i.reduce((o,l)=>(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return s}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 Q$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function e2e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Q$(Object(n),!0).forEach(function(r){t2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Q$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function t2e(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=r2e(t,"string");return typeof e=="symbol"?e:e+""}function r2e(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 Il=32,a2e={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle"};function i2e(t){var{data:e,iconType:n,inactiveColor:r}=t,i=Il/2,s=Il/6,o=Il/3,l=e.inactive?r:e.color,c=n??e.type;if(c==="none")return null;if(c==="plainline"){var d;return w.createElement("line",{strokeWidth:4,fill:"none",stroke:l,strokeDasharray:(d=e.payload)===null||d===void 0?void 0:d.strokeDasharray,x1:0,y1:i,x2:Il,y2:i,className:"recharts-legend-icon"})}if(c==="line")return w.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(i,"h").concat(o,`
- A`).concat(s,",").concat(s,",0,1,1,").concat(2*o,",").concat(i,`
- H`).concat(Il,"M").concat(2*o,",").concat(i,`
- A`).concat(s,",").concat(s,",0,1,1,").concat(o,",").concat(i),className:"recharts-legend-icon"});if(c==="rect")return w.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Il/8,"h").concat(Il,"v").concat(Il*3/4,"h").concat(-Il,"z"),className:"recharts-legend-icon"});if(w.isValidElement(e.legendIcon)){var u=e2e({},e);return delete u.legendIcon,w.cloneElement(e.legendIcon,u)}return w.createElement(fI,{fill:l,cx:i,cy:i,size:Il,sizeType:"diameter",type:c})}function s2e(t){var{payload:e,iconSize:n,layout:r,formatter:i,inactiveColor:s,iconType:o}=t,l={x:0,y:0,width:Il,height:Il},c={display:r==="horizontal"?"inline-block":"block",marginRight:10},d={display:"inline-block",verticalAlign:"middle",marginRight:4};return e.map((u,m)=>{var p=u.formatter||i,f=_r({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:u.inactive});if(u.type==="none")return null;var x=u.inactive?s:u.color,v=p?p(u.value,u,m):u.value;return w.createElement("li",EN({className:f,style:c,key:"legend-item-".concat(m)},Xw(t,u,m)),w.createElement(lI,{width:n,height:n,viewBox:l,style:d,"aria-label":"".concat(v," legend icon")},w.createElement(i2e,{data:u,iconType:o,inactiveColor:s})),w.createElement("span",{className:"recharts-legend-item-text",style:{color:x}},v))})}var o2e=t=>{var e=Da(t,a2e),{payload:n,layout:r,align:i}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?i:"left"};return w.createElement("ul",{className:"recharts-default-legend",style:s},w.createElement(s2e,EN({},e,{payload:n})))},XE={},YE={},Z$;function l2e(){return Z$||(Z$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){const i=new Map;for(let s=0;s<n.length;s++){const o=n[s],l=r(o,s,n);i.has(l)||i.set(l,o)}return Array.from(i.values())}t.uniqBy=e})(YE)),YE}var QE={},J$;function c2e(){return J$||(J$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return function(...i){return n.apply(this,i.slice(0,r))}}t.ary=e})(QE)),QE}var ZE={},eV;function XJ(){return eV||(eV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n}t.identity=e})(ZE)),ZE}var JE={},e2={},t2={},tV;function d2e(){return tV||(tV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Number.isSafeInteger(n)&&n>=0}t.isLength=e})(t2)),t2}var nV;function bI(){return nV||(nV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=d2e();function n(r){return r!=null&&typeof r!="function"&&e.isLength(r.length)}t.isArrayLike=n})(e2)),e2}var n2={},rV;function u2e(){return rV||(rV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(n2)),n2}var aV;function m2e(){return aV||(aV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=bI(),n=u2e();function r(i){return n.isObjectLike(i)&&e.isArrayLike(i)}t.isArrayLikeObject=r})(JE)),JE}var r2={},a2={},iV;function h2e(){return iV||(iV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pI();function n(r){return function(i){return e.get(i,r)}}t.property=n})(a2)),a2}var i2={},s2={},o2={},l2={},sV;function YJ(){return sV||(sV=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})(l2)),l2}var c2={},oV;function QJ(){return oV||(oV=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})(c2)),c2}var d2={},lV;function ZJ(){return lV||(lV=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})(d2)),d2}var cV;function p2e(){return cV||(cV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=YJ(),n=QJ(),r=ZJ();function i(u,m,p){return typeof p!="function"?i(u,m,()=>{}):s(u,m,function f(x,v,g,b,_,C){const P=p(x,v,g,b,_,C);return P!==void 0?!!P:s(x,v,f,C)},new Map)}function s(u,m,p,f){if(m===u)return!0;switch(typeof m){case"object":return o(u,m,p,f);case"function":return Object.keys(m).length>0?s(u,{...m},p,f):r.isEqualsSameValueZero(u,m);default:return e.isObject(u)?typeof m=="string"?m==="":!0:r.isEqualsSameValueZero(u,m)}}function o(u,m,p,f){if(m==null)return!0;if(Array.isArray(m))return c(u,m,p,f);if(m instanceof Map)return l(u,m,p,f);if(m instanceof Set)return d(u,m,p,f);const x=Object.keys(m);if(u==null||n.isPrimitive(u))return x.length===0;if(x.length===0)return!0;if(f?.has(m))return f.get(m)===u;f?.set(m,u);try{for(let v=0;v<x.length;v++){const g=x[v];if(!n.isPrimitive(u)&&!(g in u)||m[g]===void 0&&u[g]!==void 0||m[g]===null&&u[g]!==null||!p(u[g],m[g],g,u,m,f))return!1}return!0}finally{f?.delete(m)}}function l(u,m,p,f){if(m.size===0)return!0;if(!(u instanceof Map))return!1;for(const[x,v]of m.entries()){const g=u.get(x);if(p(g,v,x,u,m,f)===!1)return!1}return!0}function c(u,m,p,f){if(m.length===0)return!0;if(!Array.isArray(u))return!1;const x=new Set;for(let v=0;v<m.length;v++){const g=m[v];let b=!1;for(let _=0;_<u.length;_++){if(x.has(_))continue;const C=u[_];let P=!1;if(p(C,g,v,u,m,f)&&(P=!0),P){x.add(_),b=!0;break}}if(!b)return!1}return!0}function d(u,m,p,f){return m.size===0?!0:u instanceof Set?c([...u],[...m],p,f):!1}t.isMatchWith=i,t.isSetMatch=d})(o2)),o2}var dV;function JJ(){return dV||(dV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=p2e();function n(r,i){return e.isMatchWith(r,i,()=>{})}t.isMatch=n})(s2)),s2}var u2={},m2={},h2={},uV;function f2e(){return uV||(uV=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})(h2)),h2}var p2={},mV;function xI(){return mV||(mV=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})(p2)),p2}var f2={},hV;function eee(){return hV||(hV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",r="[object Number]",i="[object Boolean]",s="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",d="[object Set]",u="[object Array]",m="[object Function]",p="[object ArrayBuffer]",f="[object Object]",x="[object Error]",v="[object DataView]",g="[object Uint8Array]",b="[object Uint8ClampedArray]",_="[object Uint16Array]",C="[object Uint32Array]",P="[object BigUint64Array]",N="[object Int8Array]",A="[object Int16Array]",T="[object Int32Array]",F="[object BigInt64Array]",k="[object Float32Array]",D="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=p,t.arrayTag=u,t.bigInt64ArrayTag=F,t.bigUint64ArrayTag=P,t.booleanTag=i,t.dataViewTag=v,t.dateTag=l,t.errorTag=x,t.float32ArrayTag=k,t.float64ArrayTag=D,t.functionTag=m,t.int16ArrayTag=A,t.int32ArrayTag=T,t.int8ArrayTag=N,t.mapTag=c,t.numberTag=r,t.objectTag=f,t.regexpTag=e,t.setTag=d,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=_,t.uint32ArrayTag=C,t.uint8ArrayTag=g,t.uint8ClampedArrayTag=b})(f2)),f2}var g2={},pV;function g2e(){return pV||(pV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(g2)),g2}var fV;function tee(){return fV||(fV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=f2e(),n=xI(),r=eee(),i=QJ(),s=g2e();function o(u,m){return l(u,void 0,u,new Map,m)}function l(u,m,p,f=new Map,x=void 0){const v=x?.(u,m,p,f);if(v!==void 0)return v;if(i.isPrimitive(u))return u;if(f.has(u))return f.get(u);if(Array.isArray(u)){const g=new Array(u.length);f.set(u,g);for(let b=0;b<u.length;b++)g[b]=l(u[b],b,p,f,x);return Object.hasOwn(u,"index")&&(g.index=u.index),Object.hasOwn(u,"input")&&(g.input=u.input),g}if(u instanceof Date)return new Date(u.getTime());if(u instanceof RegExp){const g=new RegExp(u.source,u.flags);return g.lastIndex=u.lastIndex,g}if(u instanceof Map){const g=new Map;f.set(u,g);for(const[b,_]of u)g.set(b,l(_,b,p,f,x));return g}if(u instanceof Set){const g=new Set;f.set(u,g);for(const b of u)g.add(l(b,void 0,p,f,x));return g}if(typeof Buffer<"u"&&Buffer.isBuffer(u))return u.subarray();if(s.isTypedArray(u)){const g=new(Object.getPrototypeOf(u)).constructor(u.length);f.set(u,g);for(let b=0;b<u.length;b++)g[b]=l(u[b],b,p,f,x);return g}if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer)return u.slice(0);if(u instanceof DataView){const g=new DataView(u.buffer.slice(0),u.byteOffset,u.byteLength);return f.set(u,g),c(g,u,p,f,x),g}if(typeof File<"u"&&u instanceof File){const g=new File([u],u.name,{type:u.type});return f.set(u,g),c(g,u,p,f,x),g}if(typeof Blob<"u"&&u instanceof Blob){const g=new Blob([u],{type:u.type});return f.set(u,g),c(g,u,p,f,x),g}if(u instanceof Error){const g=new u.constructor;return f.set(u,g),g.message=u.message,g.name=u.name,g.stack=u.stack,g.cause=u.cause,c(g,u,p,f,x),g}if(u instanceof Boolean){const g=new Boolean(u.valueOf());return f.set(u,g),c(g,u,p,f,x),g}if(u instanceof Number){const g=new Number(u.valueOf());return f.set(u,g),c(g,u,p,f,x),g}if(u instanceof String){const g=new String(u.valueOf());return f.set(u,g),c(g,u,p,f,x),g}if(typeof u=="object"&&d(u)){const g=Object.create(Object.getPrototypeOf(u));return f.set(u,g),c(g,u,p,f,x),g}return u}function c(u,m,p=u,f,x){const v=[...Object.keys(m),...e.getSymbols(m)];for(let g=0;g<v.length;g++){const b=v[g],_=Object.getOwnPropertyDescriptor(u,b);(_==null||_.writable)&&(u[b]=l(m[b],b,p,f,x))}}function d(u){switch(n.getTag(u)){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})(m2)),m2}var gV;function b2e(){return gV||(gV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=tee();function n(r){return e.cloneDeepWithImpl(r,void 0,r,new Map,void 0)}t.cloneDeep=n})(u2)),u2}var bV;function x2e(){return bV||(bV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=JJ(),n=b2e();function r(i){return i=n.cloneDeep(i),s=>e.isMatch(s,i)}t.matches=r})(i2)),i2}var b2={},x2={},y2={},xV;function y2e(){return xV||(xV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=tee(),n=xI(),r=eee();function i(s,o){return e.cloneDeepWith(s,(l,c,d,u)=>{const m=o?.(l,c,d,u);if(m!==void 0)return m;if(typeof s=="object"){if(n.getTag(s)===r.objectTag&&typeof s.constructor!="function"){const p={};return u.set(s,p),e.copyProperties(p,s,d,u),p}switch(Object.prototype.toString.call(s)){case r.numberTag:case r.stringTag:case r.booleanTag:{const p=new s.constructor(s?.valueOf());return e.copyProperties(p,s),p}case r.argumentsTag:{const p={};return e.copyProperties(p,s),p.length=s.length,p[Symbol.iterator]=s[Symbol.iterator],p}default:return}}})}t.cloneDeepWith=i})(y2)),y2}var yV;function v2e(){return yV||(yV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=y2e();function n(r){return e.cloneDeepWith(r)}t.cloneDeep=n})(x2)),x2}var v2={},w2={},vV;function nee(){return vV||(vV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(r,i=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&r<i;case"symbol":return!1;case"string":return e.test(r)}}t.isIndex=n})(w2)),w2}var S2={},wV;function w2e(){return wV||(wV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=xI();function n(r){return r!==null&&typeof r=="object"&&e.getTag(r)==="[object Arguments]"}t.isArguments=n})(S2)),S2}var SV;function S2e(){return SV||(SV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=$J(),n=nee(),r=w2e(),i=hI();function s(o,l){let c;if(Array.isArray(l)?c=l:typeof l=="string"&&e.isDeepKey(l)&&o?.[l]==null?c=i.toPath(l):c=[l],c.length===0)return!1;let d=o;for(let u=0;u<c.length;u++){const m=c[u];if((d==null||!Object.hasOwn(d,m))&&!((Array.isArray(d)||r.isArguments(d))&&n.isIndex(m)&&m<d.length))return!1;d=d[m]}return!0}t.has=s})(v2)),v2}var _V;function _2e(){return _V||(_V=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=JJ(),n=mI(),r=v2e(),i=pI(),s=S2e();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(d){const u=i.get(d,l);return u===void 0?s.has(d,l):c===void 0?u===void 0:e.isMatch(u,c)}}t.matchesProperty=o})(b2)),b2}var kV;function k2e(){return kV||(kV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=XJ(),n=h2e(),r=x2e(),i=_2e();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?i.matchesProperty(o[0],o[1]):r.matches(o);case"string":case"symbol":case"number":return n.property(o)}}t.iteratee=s})(r2)),r2}var NV;function N2e(){return NV||(NV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=l2e(),n=c2e(),r=XJ(),i=m2e(),s=k2e();function o(l,c=r.identity){return i.isArrayLikeObject(l)?e.uniqBy(Array.from(l),n.ary(s.iteratee(c),1)):[]}t.uniqBy=o})(XE)),XE}var _2,CV;function C2e(){return CV||(CV=1,_2=N2e().uniqBy),_2}var P2e=C2e();const PV=mc(P2e);function ree(t,e,n){return e===!0?PV(t,n):typeof e=="function"?PV(t,e):t}var k2={exports:{}},N2={};var TV;function T2e(){if(TV)return N2;TV=1;var t=xg(),e=IY();function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,i=e.useSyncExternalStore,s=t.useRef,o=t.useEffect,l=t.useMemo,c=t.useDebugValue;return N2.useSyncExternalStoreWithSelector=function(d,u,m,p,f){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 b(A){if(!_){if(_=!0,C=A,A=p(A),f!==void 0&&v.hasValue){var T=v.value;if(f(T,A))return P=T}return P=A}if(T=P,r(C,A))return T;var F=p(A);return f!==void 0&&f(T,F)?(C=A,T):(C=A,P=F)}var _=!1,C,P,N=m===void 0?null:m;return[function(){return b(u())},N===null?void 0:function(){return b(N())}]},[u,m,p,f]);var g=i(d,x[0],x[1]);return o(function(){v.hasValue=!0,v.value=g},[g]),c(g),g},N2}var AV;function A2e(){return AV||(AV=1,k2.exports=T2e()),k2.exports}var aee=A2e(),yI=w.createContext(null),j2e=t=>t,ia=()=>{var t=w.useContext(yI);return t?t.store.dispatch:j2e},Fk=()=>{},M2e=()=>Fk,E2e=(t,e)=>t===e;function un(t){var e=w.useContext(yI),n=w.useMemo(()=>e?r=>{if(r!=null)return t(r)}:Fk,[e,t]);return aee.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:M2e,e?e.store.getState:Fk,e?e.store.getState:Fk,n,E2e)}function D2e(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function F2e(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function R2e(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 jV=t=>Array.isArray(t)?t:[t];function L2e(t){const e=Array.isArray(t[0])?t[0]:t;return R2e(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function O2e(t,e){const n=[],{length:r}=t;for(let i=0;i<r;i++)n.push(t[i].apply(null,e));return n}var I2e=class{constructor(t){this.value=t}deref(){return this.value}},z2e=typeof WeakRef<"u"?WeakRef:I2e,U2e=0,MV=1;function L1(){return{s:U2e,v:void 0,o:null,p:null}}function iee(t,e={}){let n=L1();const{resultEqualityCheck:r}=e;let i,s=0;function o(){let l=n;const{length:c}=arguments;for(let m=0,p=c;m<p;m++){const f=arguments[m];if(typeof f=="function"||typeof f=="object"&&f!==null){let x=l.o;x===null&&(l.o=x=new WeakMap);const v=x.get(f);v===void 0?(l=L1(),x.set(f,l)):l=v}else{let x=l.p;x===null&&(l.p=x=new Map);const v=x.get(f);v===void 0?(l=L1(),x.set(f,l)):l=v}}const d=l;let u;if(l.s===MV)u=l.v;else if(u=t.apply(null,arguments),s++,r){const m=i?.deref?.()??i;m!=null&&r(m,u)&&(u=m,s!==0&&s--),i=typeof u=="object"&&u!==null||typeof u=="function"?new z2e(u):u}return d.s=MV,d.v=u,u}return o.clearCache=()=>{n=L1(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function B2e(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,r=(...i)=>{let s=0,o=0,l,c={},d=i.pop();typeof d=="object"&&(c=d,d=i.pop()),D2e(d,`createSelector expects an output function after the inputs, but received: [${typeof d}]`);const u={...n,...c},{memoize:m,memoizeOptions:p=[],argsMemoize:f=iee,argsMemoizeOptions:x=[]}=u,v=jV(p),g=jV(x),b=L2e(i),_=m(function(){return s++,d.apply(null,arguments)},...v),C=f(function(){o++;const N=O2e(b,arguments);return l=_.apply(null,N),l},...g);return Object.assign(C,{resultFunc:d,memoizedResultFunc:_,dependencies:b,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:m,argsMemoize:f})};return Object.assign(r,{withTypes:()=>r}),r}var yt=B2e(iee),H2e=Object.assign((t,e=yt)=>{F2e(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:()=>H2e}),C2={},P2={},T2={},EV;function q2e(){return EV||(EV=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,i,s)=>{if(r!==i){const o=e(r),l=e(i);if(o===l&&o===0){if(r<i)return s==="desc"?1:-1;if(r>i)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(T2)),T2}var A2={},j2={},DV;function see(){return DV||(DV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(j2)),j2}var FV;function $2e(){return FV||(FV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=see(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function i(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=i})(A2)),A2}var RV;function V2e(){return RV||(RV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=q2e(),n=$2e(),r=hI();function i(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(f=>String(f));const d=(f,x)=>{let v=f;for(let g=0;g<x.length&&v!=null;++g)v=v[x[g]];return v},u=(f,x)=>x==null||f==null?x:typeof f=="object"&&"key"in f?Object.hasOwn(x,f.key)?x[f.key]:d(x,f.path):typeof f=="function"?f(x):Array.isArray(f)?d(x,f):typeof x=="object"?x[f]:x,m=o.map(f=>(Array.isArray(f)&&f.length===1&&(f=f[0]),f==null||typeof f=="function"||Array.isArray(f)||n.isKey(f)?f:{key:f,path:r.toPath(f)}));return s.map(f=>({original:f,criteria:m.map(x=>u(x,f))})).slice().sort((f,x)=>{for(let v=0;v<m.length;v++){const g=e.compareValues(f.criteria[v],x.criteria[v],l[v]);if(g!==0)return g}return 0}).map(f=>f.original)}t.orderBy=i})(P2)),P2}var M2={},LV;function G2e(){return LV||(LV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r=1){const i=[],s=Math.floor(r),o=(l,c)=>{for(let d=0;d<l.length;d++){const u=l[d];Array.isArray(u)&&c<s?o(u,c+1):i.push(u)}};return o(n,0),i}t.flatten=e})(M2)),M2}var E2={},OV;function oee(){return OV||(OV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=nee(),n=bI(),r=YJ(),i=ZJ();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)?i.isEqualsSameValueZero(c[l],o):!1}t.isIterateeCall=s})(E2)),E2}var IV;function W2e(){return IV||(IV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=V2e(),n=G2e(),r=oee();function i(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=i})(C2)),C2}var D2,zV;function K2e(){return zV||(zV=1,D2=W2e().sortBy),D2}var X2e=K2e();const XP=mc(X2e);var lee=t=>t.legend.settings,Y2e=t=>t.legend.size,Q2e=t=>t.legend.payload,Z2e=yt([Q2e,lee],(t,e)=>{var{itemSorter:n}=e,r=t.flat(1);return n?XP(r,n):r});function J2e(){return un(Z2e)}var O1=1;function cee(){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(i=>{if(i!=null){var s=i.getBoundingClientRect(),o={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(o.height-e.height)>O1||Math.abs(o.left-e.left)>O1||Math.abs(o.top-e.top)>O1||Math.abs(o.width-e.width)>O1)&&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 is(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 eDe=typeof Symbol=="function"&&Symbol.observable||"@@observable",UV=eDe,F2=()=>Math.random().toString(36).substring(7).split("").join("."),tDe={INIT:`@@redux/INIT${F2()}`,REPLACE:`@@redux/REPLACE${F2()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${F2()}`},DN=tDe;function vI(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 dee(t,e,n){if(typeof t!="function")throw new Error(is(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(is(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(is(1));return n(dee)(t,e)}let r=t,i=e,s=new Map,o=s,l=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((g,b)=>{o.set(b,g)}))}function u(){if(c)throw new Error(is(3));return i}function m(g){if(typeof g!="function")throw new Error(is(4));if(c)throw new Error(is(5));let b=!0;d();const _=l++;return o.set(_,g),function(){if(b){if(c)throw new Error(is(6));b=!1,d(),o.delete(_),s=null}}}function p(g){if(!vI(g))throw new Error(is(7));if(typeof g.type>"u")throw new Error(is(8));if(typeof g.type!="string")throw new Error(is(17));if(c)throw new Error(is(9));try{c=!0,i=r(i,g)}finally{c=!1}return(s=o).forEach(_=>{_()}),g}function f(g){if(typeof g!="function")throw new Error(is(10));r=g,p({type:DN.REPLACE})}function x(){const g=m;return{subscribe(b){if(typeof b!="object"||b===null)throw new Error(is(11));function _(){const P=b;P.next&&P.next(u())}return _(),{unsubscribe:g(_)}},[UV](){return this}}}return p({type:DN.INIT}),{dispatch:p,subscribe:m,getState:u,replaceReducer:f,[UV]:x}}function nDe(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:DN.INIT})>"u")throw new Error(is(12));if(typeof n(void 0,{type:DN.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(is(13))})}function uee(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 i;try{nDe(n)}catch(s){i=s}return function(o={},l){if(i)throw i;let c=!1;const d={};for(let u=0;u<r.length;u++){const m=r[u],p=n[m],f=o[m],x=p(f,l);if(typeof x>"u")throw l&&l.type,new Error(is(14));d[m]=x,c=c||x!==f}return c=c||r.length!==Object.keys(o).length,c?d:o}}function FN(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...r)=>e(n(...r)))}function rDe(...t){return e=>(n,r)=>{const i=e(n,r);let s=()=>{throw new Error(is(15))};const o={getState:i.getState,dispatch:(c,...d)=>s(c,...d)},l=t.map(c=>c(o));return s=FN(...l)(i.dispatch),{...i,dispatch:s}}}function mee(t){return vI(t)&&"type"in t&&typeof t.type=="string"}var hee=Symbol.for("immer-nothing"),BV=Symbol.for("immer-draftable"),ro=Symbol.for("immer-state");function Mc(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var al=Object,zx=al.getPrototypeOf,RN="constructor",YP="prototype",hR="configurable",LN="enumerable",Rk="writable",tw="value",dm=t=>!!t&&!!t[ro];function Hc(t){return t?pee(t)||ZP(t)||!!t[BV]||!!t[RN]?.[BV]||JP(t)||eT(t):!1}var aDe=al[YP][RN].toString(),HV=new WeakMap;function pee(t){if(!t||!wI(t))return!1;const e=zx(t);if(e===null||e===al[YP])return!0;const n=al.hasOwnProperty.call(e,RN)&&e[RN];if(n===Object)return!0;if(!Qb(n))return!1;let r=HV.get(n);return r===void 0&&(r=Function.toString.call(n),HV.set(n,r)),r===aDe}function QP(t,e,n=!0){Yw(t)===0?(n?Reflect.ownKeys(t):al.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((r,i)=>e(i,r,t))}function Yw(t){const e=t[ro];return e?e.type_:ZP(t)?1:JP(t)?2:eT(t)?3:0}var qV=(t,e,n=Yw(t))=>n===2?t.has(e):al[YP].hasOwnProperty.call(t,e),pR=(t,e,n=Yw(t))=>n===2?t.get(e):t[e],ON=(t,e,n,r=Yw(t))=>{r===2?t.set(e,n):r===3?t.add(n):t[e]=n};function iDe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var ZP=Array.isArray,JP=t=>t instanceof Map,eT=t=>t instanceof Set,wI=t=>typeof t=="object",Qb=t=>typeof t=="function",R2=t=>typeof t=="boolean";function sDe(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var Mu=t=>t.copy_||t.base_,SI=t=>t.modified_?t.copy_:t.base_;function fR(t,e){if(JP(t))return new Map(t);if(eT(t))return new Set(t);if(ZP(t))return Array[YP].slice.call(t);const n=pee(t);if(e===!0||e==="class_only"&&!n){const r=al.getOwnPropertyDescriptors(t);delete r[ro];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const o=i[s],l=r[o];l[Rk]===!1&&(l[Rk]=!0,l[hR]=!0),(l.get||l.set)&&(r[o]={[hR]:!0,[Rk]:!0,[LN]:l[LN],[tw]:t[o]})}return al.create(zx(t),r)}else{const r=zx(t);if(r!==null&&n)return{...t};const i=al.create(r);return al.assign(i,t)}}function _I(t,e=!1){return tT(t)||dm(t)||!Hc(t)||(Yw(t)>1&&al.defineProperties(t,{set:I1,add:I1,clear:I1,delete:I1}),al.freeze(t),e&&QP(t,(n,r)=>{_I(r,!0)},!1)),t}function oDe(){Mc(2)}var I1={[tw]:oDe};function tT(t){return t===null||!wI(t)?!0:al.isFrozen(t)}var IN="MapSet",gR="Patches",$V="ArrayMethods",fee={};function lg(t){const e=fee[t];return e||Mc(0,t),e}var VV=t=>!!fee[t],nw,gee=()=>nw,lDe=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:VV(IN)?lg(IN):void 0,arrayMethodsPlugin_:VV($V)?lg($V):void 0});function GV(t,e){e&&(t.patchPlugin_=lg(gR),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function bR(t){xR(t),t.drafts_.forEach(cDe),t.drafts_=null}function xR(t){t===nw&&(nw=t.parent_)}var WV=t=>nw=lDe(nw,t);function cDe(t){const e=t[ro];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function KV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[ro].modified_&&(bR(e),Mc(4)),Hc(t)&&(t=XV(e,t));const{patchPlugin_:i}=e;i&&i.generateReplacementPatches_(n[ro].base_,t,e)}else t=XV(e,n);return dDe(e,t,!0),bR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==hee?t:void 0}function XV(t,e){if(tT(e))return e;const n=e[ro];if(!n)return zN(e,t.handledSet_,t);if(!nT(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);yee(n,t)}return n.copy_}function dDe(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&_I(e,n)}function bee(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var nT=(t,e)=>t.scope_===e,uDe=[];function xee(t,e,n,r){const i=Mu(t),s=t.type_;if(r!==void 0&&pR(i,r,s)===e){ON(i,r,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;QP(i,(c,d)=>{if(dm(d)){const u=l.get(d)||[];u.push(c),l.set(d,u)}})}const o=t.draftLocations_.get(e)??uDe;for(const l of o)ON(i,l,n,s)}function mDe(t,e,n){t.callbacks_.push(function(i){const s=e;if(!s||!nT(s,i))return;i.mapSetPlugin_?.fixSetContents(s);const o=SI(s);xee(t,s.draft_??s,o,n),yee(s,i)})}function yee(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 i=r.getPath(t);i&&r.generatePatches_(t,i,e)}bee(t)}}function hDe(t,e,n){const{scope_:r}=t;if(dm(n)){const i=n[ro];nT(i,r)&&i.callbacks_.push(function(){Lk(t);const o=SI(i);xee(t,n,o,e)})}else Hc(n)&&t.callbacks_.push(function(){const s=Mu(t);t.type_===3?s.has(n)&&zN(n,r.handledSet_,r):pR(s,e,t.type_)===n&&r.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&zN(pR(t.copy_,e,t.type_),r.handledSet_,r)})}function zN(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||dm(t)||e.has(t)||!Hc(t)||tT(t)||(e.add(t),QP(t,(r,i)=>{if(dm(i)){const s=i[ro];if(nT(s,n)){const o=SI(s);ON(t,r,o,t.type_),bee(s)}}else Hc(i)&&zN(i,e,n)})),t}function pDe(t,e){const n=ZP(t),r={type_:n?1:0,scope_:e?e.scope_:gee(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=r,s=UN;n&&(i=[r],s=rw);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return r.draft_=l,r.revoke_=o,[l,r]}var UN={get(t,e){if(e===ro)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 i=Mu(t);if(!qV(i,e,t.type_))return fDe(t,i,e);const s=i[e];if(t.finalized_||!Hc(s)||r&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&sDe(e))return s;if(s===L2(t.base_,e)){Lk(t);const o=t.type_===1?+e:e,l=vR(t.scope_,s,t,o);return t.copy_[o]=l}return s},has(t,e){return e in Mu(t)},ownKeys(t){return Reflect.ownKeys(Mu(t))},set(t,e,n){const r=vee(Mu(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const i=L2(Mu(t),e),s=i?.[ro];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(iDe(n,i)&&(n!==void 0||qV(t.base_,e,t.type_)))return!0;Lk(t),yR(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),hDe(t,e,n)),!0},deleteProperty(t,e){return Lk(t),L2(t.base_,e)!==void 0||e in t.base_?(t.assigned_.set(e,!1),yR(t)):t.assigned_.delete(e),t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Mu(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{[Rk]:!0,[hR]:t.type_!==1||e!=="length",[LN]:r[LN],[tw]:n[e]}},defineProperty(){Mc(11)},getPrototypeOf(t){return zx(t.base_)},setPrototypeOf(){Mc(12)}},rw={};for(let t in UN){let e=UN[t];rw[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}rw.deleteProperty=function(t,e){return rw.set.call(this,t,e,void 0)};rw.set=function(t,e,n){return UN.set.call(this,t[0],e,n,t[0])};function L2(t,e){const n=t[ro];return(n?Mu(n):t)[e]}function fDe(t,e,n){const r=vee(e,n);return r?tw in r?r[tw]:r.get?.call(t.draft_):void 0}function vee(t,e){if(!(e in t))return;let n=zx(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=zx(n)}}function yR(t){t.modified_||(t.modified_=!0,t.parent_&&yR(t.parent_))}function Lk(t){t.copy_||(t.assigned_=new Map,t.copy_=fR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var gDe=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,r,i)=>{if(Qb(n)&&!Qb(r)){const o=r;r=n;const l=this;return function(d=o,...u){return l.produce(d,m=>r.call(this,m,...u))}}Qb(r)||Mc(6),i!==void 0&&!Qb(i)&&Mc(7);let s;if(Hc(n)){const o=WV(this),l=vR(o,n,void 0);let c=!0;try{s=r(l),c=!1}finally{c?bR(o):xR(o)}return GV(o,i),KV(s,o)}else if(!n||!wI(n)){if(s=r(n),s===void 0&&(s=n),s===hee&&(s=void 0),this.autoFreeze_&&_I(s,!0),i){const o=[],l=[];lg(gR).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),i(o,l)}return s}else Mc(1,n)},this.produceWithPatches=(n,r)=>{if(Qb(n))return(l,...c)=>this.produceWithPatches(l,d=>n(d,...c));let i,s;return[this.produce(n,r,(l,c)=>{i=l,s=c}),i,s]},R2(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),R2(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),R2(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Hc(e)||Mc(8),dm(e)&&(e=Ic(e));const n=WV(this),r=vR(n,e,void 0);return r[ro].isManual_=!0,xR(n),r}finishDraft(e,n){const r=e&&e[ro];(!r||!r.isManual_)&&Mc(9);const{scope_:i}=r;return GV(i,n),KV(void 0,i)}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 i=lg(gR).applyPatches_;return dm(e)?i(e,n):this.produce(e,s=>i(s,n))}};function vR(t,e,n,r){const[i,s]=JP(e)?lg(IN).proxyMap_(e,n):eT(e)?lg(IN).proxySet_(e,n):pDe(e,n);return(n?.scope_??gee()).drafts_.push(i),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&r!==void 0?mDe(n,s,r):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:d}=c;s.modified_&&d&&d.generatePatches_(s,[],c)}),i}function Ic(t){return dm(t)||Mc(10,t),wee(t)}function wee(t){if(!Hc(t)||tT(t))return t;const e=t[ro];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=fR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=fR(t,!0);return QP(n,(i,s)=>{ON(n,i,wee(s))},r),e&&(e.finalized_=!1),n}var bDe=new gDe,See=bDe.produce;function _ee(t){return({dispatch:n,getState:r})=>i=>s=>typeof s=="function"?s(n,r,t):i(s)}var xDe=_ee(),yDe=_ee,vDe=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?FN:FN.apply(null,arguments)};function cc(t,e){function n(...r){if(e){let i=e(...r);if(!i)throw new Error(ll(0));return{type:t,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:t,payload:r[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=r=>mee(r)&&r.type===t,n}var kee=class Zv extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,Zv.prototype)}static get[Symbol.species](){return Zv}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new Zv(...e[0].concat(this)):new Zv(...e.concat(this))}};function YV(t){return Hc(t)?See(t,()=>{}):t}function z1(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function wDe(t){return typeof t=="boolean"}var SDe=()=>function(e){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:s=!0}=e??{};let o=new kee;return n&&(wDe(n)?o.push(xDe):o.push(yDe(n.extraArgument))),o},Nee="RTK_autoBatch",Sa=()=>t=>({payload:t,meta:{[Nee]:!0}}),QV=t=>e=>{setTimeout(e,t)},Cee=(t={type:"raf"})=>e=>(...n)=>{const r=e(...n);let i=!0,s=!1,o=!1;const l=new Set,c=t.type==="tick"?queueMicrotask:t.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:QV(10):t.type==="callback"?t.queueNotification:QV(t.timeout),d=()=>{o=!1,s&&(s=!1,l.forEach(u=>u()))};return Object.assign({},r,{subscribe(u){const m=()=>i&&u(),p=r.subscribe(m);return l.add(u),()=>{p(),l.delete(u)}},dispatch(u){try{return i=!u?.meta?.[Nee],s=!i,s&&(o||(o=!0,c(d))),r.dispatch(u)}finally{i=!0}}})},_De=t=>function(n){const{autoBatch:r=!0}=n??{};let i=new kee(t);return r&&i.push(Cee(typeof r=="object"?r:void 0)),i};function kDe(t){const e=SDe(),{reducer:n=void 0,middleware:r,devTools:i=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(vI(n))l=uee(n);else throw new Error(ll(1));let c;typeof r=="function"?c=r(e):c=e();let d=FN;i&&(d=vDe({trace:!1,...typeof i=="object"&&i}));const u=rDe(...c),m=_De(u);let p=typeof o=="function"?o(m):m();const f=d(...p);return dee(l,s,f)}function Pee(t){const e={},n=[];let r;const i={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(ll(28));if(l in e)throw new Error(ll(29));return e[l]=o,i},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}),i},addMatcher(s,o){return n.push({matcher:s,reducer:o}),i},addDefaultCase(s){return r=s,i}};return t(i),[e,n,r]}function NDe(t){return typeof t=="function"}function CDe(t,e){let[n,r,i]=Pee(e),s;if(NDe(t))s=()=>YV(t());else{const l=YV(t);s=()=>l}function o(l=s(),c){let d=[n[c.type],...r.filter(({matcher:u})=>u(c)).map(({reducer:u})=>u)];return d.filter(u=>!!u).length===0&&(d=[i]),d.reduce((u,m)=>{if(m)if(dm(u)){const f=m(u,c);return f===void 0?u:f}else{if(Hc(u))return See(u,p=>m(p,c));{const p=m(u,c);if(p===void 0){if(u===null)return u;throw Error("A case reducer on a non-draftable value must not return undefined")}return p}}return u},l)}return o.getInitialState=s,o}var PDe="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",TDe=(t=21)=>{let e="",n=t;for(;n--;)e+=PDe[Math.random()*64|0];return e},ADe=Symbol.for("rtk-slice-createasyncthunk");function jDe(t,e){return`${t}/${e}`}function MDe({creators:t}={}){const e=t?.asyncThunk?.[ADe];return function(r){const{name:i,reducerPath:s=i}=r;if(!i)throw new Error(ll(11));const o=(typeof r.reducers=="function"?r.reducers(DDe()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(C,P){const N=typeof C=="string"?C:C.type;if(!N)throw new Error(ll(12));if(N in c.sliceCaseReducersByType)throw new Error(ll(13));return c.sliceCaseReducersByType[N]=P,d},addMatcher(C,P){return c.sliceMatchers.push({matcher:C,reducer:P}),d},exposeAction(C,P){return c.actionCreators[C]=P,d},exposeCaseReducer(C,P){return c.sliceCaseReducersByName[C]=P,d}};l.forEach(C=>{const P=o[C],N={reducerName:C,type:jDe(i,C),createNotation:typeof r.reducers=="function"};RDe(P)?ODe(N,P,d,e):FDe(N,P,d)});function u(){const[C={},P=[],N=void 0]=typeof r.extraReducers=="function"?Pee(r.extraReducers):[r.extraReducers],A={...C,...c.sliceCaseReducersByType};return CDe(r.initialState,T=>{for(let F in A)T.addCase(F,A[F]);for(let F of c.sliceMatchers)T.addMatcher(F.matcher,F.reducer);for(let F of P)T.addMatcher(F.matcher,F.reducer);N&&T.addDefaultCase(N)})}const m=C=>C,p=new Map,f=new WeakMap;let x;function v(C,P){return x||(x=u()),x(C,P)}function g(){return x||(x=u()),x.getInitialState()}function b(C,P=!1){function N(T){let F=T[C];return typeof F>"u"&&P&&(F=z1(f,N,g)),F}function A(T=m){const F=z1(p,P,()=>new WeakMap);return z1(F,T,()=>{const k={};for(const[D,H]of Object.entries(r.selectors??{}))k[D]=EDe(H,T,()=>z1(f,T,g),P);return k})}return{reducerPath:C,getSelectors:A,get selectors(){return A(N)},selectSlice:N}}const _={name:i,reducer:v,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:g,...b(s),injectInto(C,{reducerPath:P,...N}={}){const A=P??s;return C.inject({reducerPath:A,reducer:v},N),{..._,...b(A,!0)}}};return _}}function EDe(t,e,n,r){function i(s,...o){let l=e(s);return typeof l>"u"&&r&&(l=n()),t(l,...o)}return i.unwrapped=t,i}var Fo=MDe();function DDe(){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 FDe({type:t,reducerName:e,createNotation:n},r,i){let s,o;if("reducer"in r){if(n&&!LDe(r))throw new Error(ll(17));s=r.reducer,o=r.prepare}else s=r;i.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?cc(t,o):cc(t))}function RDe(t){return t._reducerDefinitionType==="asyncThunk"}function LDe(t){return t._reducerDefinitionType==="reducerWithPrepare"}function ODe({type:t,reducerName:e},n,r,i){if(!i)throw new Error(ll(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:d,options:u}=n,m=i(t,s,u);r.exposeAction(e,m),o&&r.addCase(m.fulfilled,o),l&&r.addCase(m.pending,l),c&&r.addCase(m.rejected,c),d&&r.addMatcher(m.settled,d),r.exposeCaseReducer(e,{fulfilled:o||U1,pending:l||U1,rejected:c||U1,settled:d||U1})}function U1(){}var IDe="task",Tee="listener",Aee="completed",kI="cancelled",zDe=`task-${kI}`,UDe=`task-${Aee}`,wR=`${Tee}-${kI}`,BDe=`${Tee}-${Aee}`,rT=class{constructor(t){this.code=t,this.message=`${IDe} ${kI} (reason: ${t})`}name="TaskAbortError";message},NI=(t,e)=>{if(typeof t!="function")throw new TypeError(ll(32))},BN=()=>{},jee=(t,e=BN)=>(t.catch(e),t),Mee=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),Rf=t=>{if(t.aborted)throw new rT(t.reason)};function Eee(t,e){let n=BN;return new Promise((r,i)=>{const s=()=>i(new rT(t.reason));if(t.aborted){s();return}n=Mee(t,s),e.finally(()=>n()).then(r,i)}).finally(()=>{n=BN})}var HDe=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof rT?"cancelled":"rejected",error:n}}finally{e?.()}},HN=t=>e=>jee(Eee(t,e).then(n=>(Rf(t),n))),Dee=t=>{const e=HN(t);return n=>e(new Promise(r=>setTimeout(r,n)))},{assign:xx}=Object,ZV={},aT="listenerMiddleware",qDe=(t,e)=>{const n=r=>Mee(t,()=>r.abort(t.reason));return(r,i)=>{NI(r);const s=new AbortController;n(s);const o=HDe(async()=>{Rf(t),Rf(s.signal);const l=await r({pause:HN(s.signal),delay:Dee(s.signal),signal:s.signal});return Rf(s.signal),l},()=>s.abort(UDe));return i?.autoJoin&&e.push(o.catch(BN)),{result:HN(t)(o),cancel(){s.abort(zDe)}}}},$De=(t,e)=>{const n=async(r,i)=>{Rf(e);let s=()=>{};const l=[new Promise((c,d)=>{let u=t({predicate:r,effect:(m,p)=>{p.unsubscribe(),c([m,p.getState(),p.getOriginalState()])}});s=()=>{u(),d()}})];i!=null&&l.push(new Promise(c=>setTimeout(c,i,null)));try{const c=await Eee(e,Promise.race(l));return Rf(e),c}finally{s()}};return(r,i)=>jee(n(r,i))},Fee=t=>{let{type:e,actionCreator:n,matcher:r,predicate:i,effect:s}=t;if(e)i=cc(e).match;else if(n)e=n.type,i=n.match;else if(r)i=r;else if(!i)throw new Error(ll(21));return NI(s),{predicate:i,type:e,effect:s}},Ree=xx(t=>{const{type:e,predicate:n,effect:r}=Fee(t);return{id:TDe(),effect:r,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(ll(22))}}},{withTypes:()=>Ree}),JV=(t,e)=>{const{type:n,effect:r,predicate:i}=Fee(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===i)&&s.effect===r)},SR=t=>{t.pending.forEach(e=>{e.abort(wR)})},VDe=(t,e)=>()=>{for(const n of e.keys())SR(n);t.clear()},e7=(t,e,n)=>{try{t(e,n)}catch(r){setTimeout(()=>{throw r},0)}},Lee=xx(cc(`${aT}/add`),{withTypes:()=>Lee}),GDe=cc(`${aT}/removeAll`),Oee=xx(cc(`${aT}/remove`),{withTypes:()=>Oee}),WDe=(...t)=>{console.error(`${aT}/error`,...t)},Qw=(t={})=>{const e=new Map,n=new Map,r=f=>{const x=n.get(f)??0;n.set(f,x+1)},i=f=>{const x=n.get(f)??1;x===1?n.delete(f):n.set(f,x-1)},{extra:s,onError:o=WDe}=t;NI(o);const l=f=>(f.unsubscribe=()=>e.delete(f.id),e.set(f.id,f),x=>{f.unsubscribe(),x?.cancelActive&&SR(f)}),c=f=>{const x=JV(e,f)??Ree(f);return l(x)};xx(c,{withTypes:()=>c});const d=f=>{const x=JV(e,f);return x&&(x.unsubscribe(),f.cancelActive&&SR(x)),!!x};xx(d,{withTypes:()=>d});const u=async(f,x,v,g)=>{const b=new AbortController,_=$De(c,b.signal),C=[];try{f.pending.add(b),r(f),await Promise.resolve(f.effect(x,xx({},v,{getOriginalState:g,condition:(P,N)=>_(P,N).then(Boolean),take:_,delay:Dee(b.signal),pause:HN(b.signal),extra:s,signal:b.signal,fork:qDe(b.signal,C),unsubscribe:f.unsubscribe,subscribe:()=>{e.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((P,N,A)=>{P!==b&&(P.abort(wR),A.delete(P))})},cancel:()=>{b.abort(wR),f.pending.delete(b)},throwIfCancelled:()=>{Rf(b.signal)}})))}catch(P){P instanceof rT||e7(o,P,{raisedBy:"effect"})}finally{await Promise.all(C),b.abort(BDe),i(f),f.pending.delete(b)}},m=VDe(e,n);return{middleware:f=>x=>v=>{if(!mee(v))return x(v);if(Lee.match(v))return c(v.payload);if(GDe.match(v)){m();return}if(Oee.match(v))return d(v.payload);let g=f.getState();const b=()=>{if(g===ZV)throw new Error(ll(23));return g};let _;try{if(_=x(v),e.size>0){const C=f.getState(),P=Array.from(e.values());for(const N of P){let A=!1;try{A=N.predicate(v,C,g)}catch(T){A=!1,e7(o,T,{raisedBy:"predicate"})}A&&u(N,v,f,b)}}}finally{g=ZV}return _},startListening:c,stopListening:d,clearListeners:m}};function ll(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 KDe={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},Iee=Fo({name:"chartLayout",initialState:KDe,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,i,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=(i=e.payload.bottom)!==null&&i!==void 0?i:0,t.margin.left=(s=e.payload.left)!==null&&s!==void 0?s:0},setScale(t,e){t.scale=e.payload}}}),{setMargin:XDe,setLayout:YDe,setChartSize:QDe,setScale:ZDe}=Iee.actions,JDe=Iee.reducer;function zee(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function Wn(t){return Number.isFinite(t)}function Dd(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function t7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function sx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?t7(Object(n),!0).forEach(function(r){e3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):t7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function e3e(t,e,n){return(e=t3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function t3e(t){var e=n3e(t,"string");return typeof e=="symbol"?e:e+""}function n3e(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,n){return Ca(t)||Ca(e)?n:lc(e)?sg(t,e,n):typeof e=="function"?e(t):n}var r3e=(t,e,n)=>{if(e&&n){var{width:r,height:i}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&an(t[s]))return sx(sx({},t),{},{[s]:t[s]+(r||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&an(t[o]))return sx(sx({},t),{},{[o]:t[o]+(i||0)})}return t},Wc=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",Uee=(t,e,n,r)=>{if(r)return t.map(l=>l.coordinate);var i,s,o=t.map(l=>(l.coordinate===e&&(i=!0),l.coordinate===n&&(s=!0),l.coordinate));return i||o.push(e),s||o.push(n),o},Bee=(t,e,n)=>{if(!t)return null;var{duplicateDomain:r,type:i,range:s,scale:o,realScaleType:l,isCategorical:c,categoricalDomain:d,tickCount:u,ticks:m,niceTicks:p,axisType:f}=t;if(!o)return null;var x=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,v=i==="category"&&o.bandwidth?o.bandwidth()/x:0;if(v=f==="angleAxis"&&s&&s.length>=2?Bi(s[0]-s[1])*2*v:v,m||p){var g=(m||p||[]).map((b,_)=>{var C=r?r.indexOf(b):b,P=o.map(C);return Wn(P)?{coordinate:P+v,value:b,offset:v,index:_}:null}).filter(Po);return g}return c&&d?d.map((b,_)=>{var C=o.map(b);return Wn(C)?{coordinate:C+v,value:b,index:_,offset:v}:null}).filter(Po):o.ticks&&u!=null?o.ticks(u).map((b,_)=>{var C=o.map(b);return Wn(C)?{coordinate:C+v,value:b,index:_,offset:v}:null}).filter(Po):o.domain().map((b,_)=>{var C=o.map(b);return Wn(C)?{coordinate:C+v,value:r?r[b]:b,index:_,offset:v}:null}).filter(Po)},a3e=(t,e)=>{if(!e||e.length!==2||!an(e[0])||!an(e[1]))return t;var n=Math.min(e[0],e[1]),r=Math.max(e[0],e[1]),i=[t[0],t[1]];return(!an(t[0])||t[0]<n)&&(i[0]=n),(!an(t[1])||t[1]>r)&&(i[1]=r),i[0]>r&&(i[0]=r),i[1]<n&&(i[1]=n),i},i3e=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 i=0;i<r;++i)for(var s=0,o=0,l=0;l<n;++l){var c=t[l],d=c?.[i];if(d!=null){var u=d[1],m=d[0],p=Bc(u)?m:u;p>=0?(d[0]=s,s+=p,d[1]=s):(d[0]=o,o+=p,d[1]=o)}}}},s3e=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 i=0;i<r;++i)for(var s=0,o=0;o<n;++o){var l=t[o],c=l?.[i];if(c!=null){var d=Bc(c[1])?c[0]:c[1];d>=0?(c[0]=s,s+=d,c[1]=s):(c[0]=0,c[1]=0)}}}},o3e={sign:i3e,expand:jEe,none:ig,silhouette:MEe,wiggle:EEe,positive:s3e},l3e=(t,e,n)=>{var r,i=(r=o3e[n])!==null&&r!==void 0?r:ig,s=AEe().keys(e).value((l,c)=>Number(Fr(l,c,0))).order(uR).offset(i),o=s(t);return o.forEach((l,c)=>{l.forEach((d,u)=>{var m=Fr(t[u],e[c],0);Array.isArray(m)&&m.length===2&&an(m[0])&&an(m[1])&&(d[0]=m[0],d[1]=m[1])})}),o};function Hee(t){return t==null?void 0:String(t)}function qN(t){var{axis:e,ticks:n,bandSize:r,entry:i,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!Ca(i[e.dataKey])){var l=GJ(n,"value",i[e.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[s]?n[s].coordinate+r/2:null}var c=Fr(i,Ca(o)?e.dataKey:o),d=e.scale.map(c);return an(d)?d:null}var n7=t=>{var{axis:e,ticks:n,offset:r,bandSize:i,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+r:null;var l=Fr(s,e.dataKey,e.scale.domain()[o]);if(Ca(l))return null;var c=e.scale.map(l);return an(c)?c-i/2+r:null},c3e=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var r=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return r<=0&&i>=0?0:i<0?i:r}return n[0]},d3e=t=>{var e=t.flat(2).filter(an);return[Math.min(...e),Math.max(...e)]},u3e=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],m3e=(t,e,n)=>{if(t!=null)return u3e(Object.keys(t).reduce((r,i)=>{var s=t[i];if(!s)return r;var{stackedData:o}=s,l=o.reduce((c,d)=>{var u=zee(d,e,n),m=d3e(u);return!Wn(m[0])||!Wn(m[1])?c:[Math.min(c[0],m[0]),Math.max(c[1],m[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},r7=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,a7=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,cp=(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 i=XP(e,u=>u.coordinate),s=1/0,o=1,l=i.length;o<l;o++){var c=i[o],d=i[o-1];s=Math.min((c?.coordinate||0)-(d?.coordinate||0),s)}return s===1/0?0:s}return n?void 0:0};function i7(t){var{tooltipEntrySettings:e,dataKey:n,payload:r,value:i,name:s}=t;return sx(sx({},e),{},{dataKey:n,payload:r,value:i,name:s})}function bp(t,e){if(t)return String(t);if(typeof e=="string")return e}var h3e=(t,e)=>{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},p3e=(t,e)=>e==="centric"?t.angle:t.radius,bm=t=>t.layout.width,xm=t=>t.layout.height,f3e=t=>t.layout.scale,qee=t=>t.layout.margin,iT=yt(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),sT=yt(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),$ee="data-recharts-item-index",Vee="data-recharts-item-id",Zw=60;function s7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function B1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?s7(Object(n),!0).forEach(function(r){g3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):s7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function g3e(t,e,n){return(e=b3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function b3e(t){var e=x3e(t,"string");return typeof e=="symbol"?e:e+""}function x3e(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 y3e=t=>t.brush.height;function v3e(t){var e=sT(t);return e.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var i=typeof r.width=="number"?r.width:Zw;return n+i}return n},0)}function w3e(t){var e=sT(t);return e.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var i=typeof r.width=="number"?r.width:Zw;return n+i}return n},0)}function S3e(t){var e=iT(t);return e.reduce((n,r)=>r.orientation==="top"&&!r.mirror&&!r.hide?n+r.height:n,0)}function _3e(t){var e=iT(t);return e.reduce((n,r)=>r.orientation==="bottom"&&!r.mirror&&!r.hide?n+r.height:n,0)}var Ti=yt([bm,xm,qee,y3e,v3e,w3e,S3e,_3e,lee,Y2e],(t,e,n,r,i,s,o,l,c,d)=>{var u={left:(n.left||0)+i,right:(n.right||0)+s},m={top:(n.top||0)+o,bottom:(n.bottom||0)+l},p=B1(B1({},m),u),f=p.bottom;p.bottom+=r,p=r3e(p,c,d);var x=t-p.left-p.right,v=e-p.top-p.bottom;return B1(B1({brushBottom:f},p),{},{width:Math.max(x,0),height:Math.max(v,0)})}),k3e=yt(Ti,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),CI=yt(bm,xm,(t,e)=>({x:0,y:0,width:t,height:e})),N3e=w.createContext(null),Ai=()=>w.useContext(N3e)!=null,oT=t=>t.brush,lT=yt([oT,Ti,qee],(t,e,n)=>({height:t.height,x:an(t.x)?t.x:e.left,y:an(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:an(t.width)?t.width:e.width})),O2={},I2={},z2={},o7;function C3e(){return o7||(o7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r,{signal:i,edges:s}={}){let o,l=null;const c=s!=null&&s.includes("leading"),d=s==null||s.includes("trailing"),u=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},m=()=>{d&&u(),v()};let p=null;const f=()=>{p!=null&&clearTimeout(p),p=setTimeout(()=>{p=null,m()},r)},x=()=>{p!==null&&(clearTimeout(p),p=null)},v=()=>{x(),o=void 0,l=null},g=()=>{u()},b=function(..._){if(i?.aborted)return;o=this,l=_;const C=p==null;f(),c&&C&&u()};return b.schedule=f,b.cancel=v,b.flush=g,i?.addEventListener("abort",v,{once:!0}),b}t.debounce=e})(z2)),z2}var l7;function P3e(){return l7||(l7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=C3e();function n(r,i=0,s={}){typeof s!="object"&&(s={});const{leading:o=!1,trailing:l=!0,maxWait:c}=s,d=Array(2);o&&(d[0]="leading"),l&&(d[1]="trailing");let u,m=null;const p=e.debounce(function(...v){u=r.apply(this,v),m=null},i,{edges:d}),f=function(...v){return c!=null&&(m===null&&(m=Date.now()),Date.now()-m>=c)?(u=r.apply(this,v),m=Date.now(),p.cancel(),p.schedule(),u):(p.apply(this,v),u)},x=()=>(p.flush(),u);return f.cancel=p.cancel,f.flush=x,f}t.debounce=n})(I2)),I2}var c7;function T3e(){return c7||(c7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=P3e();function n(r,i=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(r,i,{leading:o,maxWait:i,trailing:l})}t.throttle=n})(O2)),O2}var U2,d7;function A3e(){return d7||(d7=1,U2=T3e().throttle),U2}var j3e=A3e();const M3e=mc(j3e);var $N=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[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,()=>i[o++]))}},_d={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},Gee=(t,e,n)=>{var{width:r=_d.width,height:i=_d.height,aspect:s,maxHeight:o}=n,l=og(r)?t:Number(r),c=og(i)?e:Number(i);return s&&s>0&&(l?c=l/s:c&&(l=c*s),o&&c!=null&&c>o&&(c=o)),{calculatedWidth:l,calculatedHeight:c}},E3e={width:0,height:0,overflow:"visible"},D3e={width:0,overflowX:"visible"},F3e={height:0,overflowY:"visible"},R3e={},L3e=t=>{var{width:e,height:n}=t,r=og(e),i=og(n);return r&&i?E3e:r?D3e:i?F3e:R3e};function O3e(t){var{width:e,height:n,aspect:r}=t,i=e,s=n;return i===void 0&&s===void 0?(i=_d.width,s=_d.height):i===void 0?i=r&&r>0?void 0:_d.width:s===void 0&&(s=r&&r>0?void 0:_d.height),{width:i,height:s}}function _R(){return _R=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},_R.apply(null,arguments)}function u7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function m7(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){I3e(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 I3e(t,e,n){return(e=z3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function z3e(t){var e=U3e(t,"string");return typeof e=="symbol"?e:e+""}function U3e(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 Wee=w.createContext(_d.initialDimension);function B3e(t){return Dd(t.width)&&Dd(t.height)}function Kee(t){var{children:e,width:n,height:r}=t,i=w.useMemo(()=>({width:n,height:r}),[n,r]);return B3e(i)?w.createElement(Wee.Provider,{value:i},e):null}var PI=()=>w.useContext(Wee),H3e=w.forwardRef((t,e)=>{var{aspect:n,initialDimension:r=_d.initialDimension,width:i,height:s,minWidth:o=_d.minWidth,minHeight:l,maxHeight:c,children:d,debounce:u=_d.debounce,id:m,className:p,onResize:f,style:x={}}=t,v=w.useRef(null),g=w.useRef();g.current=f,w.useImperativeHandle(e,()=>v.current);var[b,_]=w.useState({containerWidth:r.width,containerHeight:r.height}),C=w.useCallback((F,k)=>{_(D=>{var H=Math.round(F),z=Math.round(k);return D.containerWidth===H&&D.containerHeight===z?D:{containerWidth:H,containerHeight:z}})},[]);w.useEffect(()=>{if(v.current==null||typeof ResizeObserver>"u")return gp;var F=z=>{var X,L=z[0];if(L!=null){var{width:ne,height:ie}=L.contentRect;C(ne,ie),(X=g.current)===null||X===void 0||X.call(g,ne,ie)}};u>0&&(F=M3e(F,u,{trailing:!0,leading:!1}));var k=new ResizeObserver(F),{width:D,height:H}=v.current.getBoundingClientRect();return C(D,H),k.observe(v.current),()=>{k.disconnect()}},[C,u]);var{containerWidth:P,containerHeight:N}=b;$N(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:A,calculatedHeight:T}=Gee(P,N,{width:i,height:s,aspect:n,maxHeight:c});return $N(A!=null&&A>0||T!=null&&T>0,`The width(%s) and height(%s) of chart should be greater than 0,
- please check the style of container, or the props width(%s) and height(%s),
- or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
- height and width.`,A,T,i,s,o,l,n),w.createElement("div",{id:m?"".concat(m):void 0,className:_r("recharts-responsive-container",p),style:m7(m7({},x),{},{width:i,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:v},w.createElement("div",{style:L3e({width:i,height:s})},w.createElement(Kee,{width:A,height:T},d)))}),Fh=w.forwardRef((t,e)=>{var n=PI();if(Dd(n.width)&&Dd(n.height))return t.children;var{width:r,height:i}=O3e({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=Gee(void 0,void 0,{width:r,height:i,aspect:t.aspect,maxHeight:t.maxHeight});return an(s)&&an(o)?w.createElement(Kee,{width:s,height:o},t.children):w.createElement(H3e,_R({},t,{width:r,height:i,ref:e}))});function TI(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 Jw=()=>{var t,e=Ai(),n=un(k3e),r=un(lT),i=(t=un(oT))===null||t===void 0?void 0:t.padding;return!e||!r||!i?n:{width:r.width-i.left-i.right,height:r.height-i.top-i.bottom,x:i.left,y:i.top}},q3e={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},Xee=()=>{var t;return(t=un(Ti))!==null&&t!==void 0?t:q3e},AI=()=>un(bm),jI=()=>un(xm),$3e=()=>un(t=>t.layout.margin),Sr=t=>t.layout.layoutType,xp=()=>un(Sr),MI=()=>{var t=xp();if(t==="horizontal"||t==="vertical")return t},Yee=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},V3e=()=>{var t=xp();return t!==void 0},eS=t=>{var e=ia(),n=Ai(),{width:r,height:i}=t,s=PI(),o=r,l=i;return s&&(o=s.width>0?s.width:r,l=s.height>0?s.height:i),w.useEffect(()=>{!n&&Dd(o)&&Dd(l)&&e(QDe({width:o,height:l}))},[e,n,o,l]),null},Qee=Symbol.for("immer-nothing"),h7=Symbol.for("immer-draftable"),hl=Symbol.for("immer-state");function Ec(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var aw=Object.getPrototypeOf;function Ux(t){return!!t&&!!t[hl]}function cg(t){return t?Zee(t)||Array.isArray(t)||!!t[h7]||!!t.constructor?.[h7]||tS(t)||dT(t):!1}var G3e=Object.prototype.constructor.toString(),p7=new WeakMap;function Zee(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=p7.get(n);return r===void 0&&(r=Function.toString.call(n),p7.set(n,r)),r===G3e}function VN(t,e,n=!0){cT(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((r,i)=>e(i,r,t))}function cT(t){const e=t[hl];return e?e.type_:Array.isArray(t)?1:tS(t)?2:dT(t)?3:0}function kR(t,e){return cT(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Jee(t,e,n){const r=cT(t);r===2?t.set(e,n):r===3?t.add(n):t[e]=n}function W3e(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function tS(t){return t instanceof Map}function dT(t){return t instanceof Set}function df(t){return t.copy_||t.base_}function NR(t,e){if(tS(t))return new Map(t);if(dT(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=Zee(t);if(e===!0||e==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(t);delete r[hl];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){const o=i[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(aw(t),r)}else{const r=aw(t);if(r!==null&&n)return{...t};const i=Object.create(r);return Object.assign(i,t)}}function EI(t,e=!1){return uT(t)||Ux(t)||!cg(t)||(cT(t)>1&&Object.defineProperties(t,{set:H1,add:H1,clear:H1,delete:H1}),Object.freeze(t),e&&Object.values(t).forEach(n=>EI(n,!0))),t}function K3e(){Ec(2)}var H1={value:K3e};function uT(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var X3e={};function dg(t){const e=X3e[t];return e||Ec(0,t),e}var iw;function ete(){return iw}function Y3e(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function f7(t,e){e&&(dg("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function CR(t){PR(t),t.drafts_.forEach(Q3e),t.drafts_=null}function PR(t){t===iw&&(iw=t.parent_)}function g7(t){return iw=Y3e(iw,t)}function Q3e(t){const e=t[hl];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function b7(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[hl].modified_&&(CR(e),Ec(4)),cg(t)&&(t=GN(e,t),e.parent_||WN(e,t)),e.patches_&&dg("Patches").generateReplacementPatches_(n[hl].base_,t,e.patches_,e.inversePatches_)):t=GN(e,n,[]),CR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==Qee?t:void 0}function GN(t,e,n){if(uT(e))return e;const r=t.immer_.shouldUseStrictIteration(),i=e[hl];if(!i)return VN(e,(s,o)=>x7(t,i,e,s,o,n),r),e;if(i.scope_!==t)return e;if(!i.modified_)return WN(t,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const s=i.copy_;let o=s,l=!1;i.type_===3&&(o=new Set(s),s.clear(),l=!0),VN(o,(c,d)=>x7(t,i,s,c,d,n,l),r),WN(t,s,!1),n&&t.patches_&&dg("Patches").generatePatches_(i,n,t.patches_,t.inversePatches_)}return i.copy_}function x7(t,e,n,r,i,s,o){if(i==null||typeof i!="object"&&!o)return;const l=uT(i);if(!(l&&!o)){if(Ux(i)){const c=s&&e&&e.type_!==3&&!kR(e.assigned_,r)?s.concat(r):void 0,d=GN(t,i,c);if(Jee(n,r,d),Ux(d))t.canAutoFreeze_=!1;else return}else o&&n.add(i);if(cg(i)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[r]===i&&l)return;GN(t,i),(!e||!e.scope_.parent_)&&typeof r!="symbol"&&(tS(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&WN(t,i)}}}function WN(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&EI(e,n)}function Z3e(t,e){const n=Array.isArray(t),r={type_:n?1:0,scope_:e?e.scope_:ete(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=r,s=DI;n&&(i=[r],s=sw);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return r.draft_=l,r.revoke_=o,l}var DI={get(t,e){if(e===hl)return t;const n=df(t);if(!kR(n,e))return J3e(t,n,e);const r=n[e];return t.finalized_||!cg(r)?r:r===B2(t.base_,e)?(H2(t),t.copy_[e]=AR(r,t)):r},has(t,e){return e in df(t)},ownKeys(t){return Reflect.ownKeys(df(t))},set(t,e,n){const r=tte(df(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const i=B2(df(t),e),s=i?.[hl];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if(W3e(n,i)&&(n!==void 0||kR(t.base_,e)))return!0;H2(t),TR(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 B2(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,H2(t),TR(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=df(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},defineProperty(){Ec(11)},getPrototypeOf(t){return aw(t.base_)},setPrototypeOf(){Ec(12)}},sw={};VN(DI,(t,e)=>{sw[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});sw.deleteProperty=function(t,e){return sw.set.call(this,t,e,void 0)};sw.set=function(t,e,n){return DI.set.call(this,t[0],e,n,t[0])};function B2(t,e){const n=t[hl];return(n?df(n):t)[e]}function J3e(t,e,n){const r=tte(e,n);return r?"value"in r?r.value:r.get?.call(t.draft_):void 0}function tte(t,e){if(!(e in t))return;let n=aw(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=aw(n)}}function TR(t){t.modified_||(t.modified_=!0,t.parent_&&TR(t.parent_))}function H2(t){t.copy_||(t.copy_=NR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var eFe=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,...d){return o.produce(c,u=>n.call(this,u,...d))}}typeof n!="function"&&Ec(6),r!==void 0&&typeof r!="function"&&Ec(7);let i;if(cg(e)){const s=g7(this),o=AR(e,void 0);let l=!0;try{i=n(o),l=!1}finally{l?CR(s):PR(s)}return f7(s,r),b7(i,s)}else if(!e||typeof e!="object"){if(i=n(e),i===void 0&&(i=e),i===Qee&&(i=void 0),this.autoFreeze_&&EI(i,!0),r){const s=[],o=[];dg("Patches").generateReplacementPatches_(e,i,s,o),r(s,o)}return i}else Ec(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let r,i;return[this.produce(e,n,(o,l)=>{r=o,i=l}),r,i]},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){cg(t)||Ec(8),Ux(t)&&(t=tFe(t));const e=g7(this),n=AR(t,void 0);return n[hl].isManual_=!0,PR(e),n}finishDraft(t,e){const n=t&&t[hl];(!n||!n.isManual_)&&Ec(9);const{scope_:r}=n;return f7(r,e),b7(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 i=e[n];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}n>-1&&(e=e.slice(n+1));const r=dg("Patches").applyPatches_;return Ux(t)?r(t,e):this.produce(t,i=>r(i,e))}};function AR(t,e){const n=tS(t)?dg("MapSet").proxyMap_(t,e):dT(t)?dg("MapSet").proxySet_(t,e):Z3e(t,e);return(e?e.scope_:ete()).drafts_.push(n),n}function tFe(t){return Ux(t)||Ec(10,t),nte(t)}function nte(t){if(!cg(t)||uT(t))return t;const e=t[hl];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=NR(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=NR(t,!0);return VN(n,(i,s)=>{Jee(n,i,nte(s))},r),e&&(e.finalized_=!1),n}var nFe=new eFe;nFe.produce;var rFe={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},rte=Fo({name:"legend",initialState:rFe,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:Sa()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Ic(t).payload.indexOf(n);i>-1&&(t.payload[i]=r)},prepare:Sa()},removeLegendPayload:{reducer(t,e){var n=Ic(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:Sa()}}}),{setLegendSize:y7,setLegendSettings:aFe,addLegendPayload:ate,replaceLegendPayload:ite,removeLegendPayload:ste}=rte.actions,iFe=rte.reducer,sFe=["contextPayload"];function jR(){return jR=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},jR.apply(null,arguments)}function v7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Bx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?v7(Object(n),!0).forEach(function(r){oFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):v7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function oFe(t,e,n){return(e=lFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function lFe(t){var e=cFe(t,"string");return typeof e=="symbol"?e:e+""}function cFe(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 dFe(t,e){if(t==null)return{};var n,r,i=uFe(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)&&(i[n]=t[n])}return i}function uFe(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 mFe(t){return t.value}function hFe(t){var{contextPayload:e}=t,n=dFe(t,sFe),r=ree(e,t.payloadUniqBy,mFe),i=Bx(Bx({},n),{},{payload:r});return w.isValidElement(t.content)?w.cloneElement(t.content,i):typeof t.content=="function"?w.createElement(t.content,i):w.createElement(o2e,i)}function pFe(t,e,n,r,i,s){var{layout:o,align:l,verticalAlign:c}=e,d,u;return(!t||(t.left===void 0||t.left===null)&&(t.right===void 0||t.right===null))&&(l==="center"&&o==="vertical"?d={left:((r||0)-s.width)/2}:d=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"?u={top:((i||0)-s.height)/2}:u=c==="bottom"?{bottom:n&&n.bottom||0}:{top:n&&n.top||0}),Bx(Bx({},d),u)}function fFe(t){var e=ia();return w.useEffect(()=>{e(aFe(t))},[e,t]),null}function gFe(t){var e=ia();return w.useEffect(()=>(e(y7(t)),()=>{e(y7({width:0,height:0}))}),[e,t]),null}function bFe(t,e,n,r){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||r}:null}var xFe={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function ote(t){var e=Da(t,xFe),n=J2e(),r=JMe(),i=$3e(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[d,u]=cee([n]),m=AI(),p=jI();if(m==null||p==null)return null;var f=m-(i?.left||0)-(i?.right||0),x=bFe(e.layout,o,s,f),v=c?l:Bx(Bx({position:"absolute",width:x?.width||s||"auto",height:x?.height||o||"auto"},pFe(l,e,i,m,p,d)),l),g=c??r;if(g==null||n==null)return null;var b=w.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:u},w.createElement(fFe,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&w.createElement(gFe,{width:d.width,height:d.height}),w.createElement(hFe,jR({},e,x,{margin:i,chartWidth:m,chartHeight:p,contextPayload:n})));return Ou.createPortal(b,g)}ote.displayName="Legend";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 w7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Av(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){yFe(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 yFe(t,e,n){return(e=vFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vFe(t){var e=wFe(t,"string");return typeof e=="symbol"?e:e+""}function wFe(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 SFe(t){return Array.isArray(t)&&lc(t[0])&&lc(t[1])?t.join(" ~ "):t}var Bb={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},_Fe=t=>{var{separator:e=Bb.separator,contentStyle:n,itemStyle:r,labelStyle:i=Bb.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:d,label:u,labelFormatter:m,accessibilityLayer:p=Bb.accessibilityLayer}=t,f=()=>{if(s&&s.length){var N={padding:0,margin:0},A=(l?XP(s,l):s).map((T,F)=>{if(T.type==="none")return null;var k=T.formatter||o||SFe,{value:D,name:H}=T,z=D,X=H;if(k){var L=k(D,H,T,F,s);if(Array.isArray(L))[z,X]=L;else if(L!=null)z=L;else return null}var ne=Av(Av({},Bb.itemStyle),{},{color:T.color||Bb.itemStyle.color},r);return w.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(F),style:ne},lc(X)?w.createElement("span",{className:"recharts-tooltip-item-name"},X):null,lc(X)?w.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,w.createElement("span",{className:"recharts-tooltip-item-value"},z),w.createElement("span",{className:"recharts-tooltip-item-unit"},T.unit||""))});return w.createElement("ul",{className:"recharts-tooltip-item-list",style:N},A)}return null},x=Av(Av({},Bb.contentStyle),n),v=Av({margin:0},i),g=!Ca(u),b=g?u:"",_=_r("recharts-default-tooltip",c),C=_r("recharts-tooltip-label",d);g&&m&&s!==void 0&&s!==null&&(b=m(u,s));var P=p?{role:"status","aria-live":"assertive"}:{};return w.createElement("div",MR({className:_,style:x},P),w.createElement("p",{className:C,style:v},w.isValidElement(b)?b:"".concat(b)),f())},jv="recharts-tooltip-wrapper",kFe={visibility:"hidden"};function NFe(t){var{coordinate:e,translateX:n,translateY:r}=t;return _r(jv,{["".concat(jv,"-right")]:an(n)&&e&&an(e.x)&&n>=e.x,["".concat(jv,"-left")]:an(n)&&e&&an(e.x)&&n<e.x,["".concat(jv,"-bottom")]:an(r)&&e&&an(e.y)&&r>=e.y,["".concat(jv,"-top")]:an(r)&&e&&an(e.y)&&r<e.y})}function S7(t){var{allowEscapeViewBox:e,coordinate:n,key:r,offset:i,position:s,reverseDirection:o,tooltipDimension:l,viewBox:c,viewBoxDimension:d}=t;if(s&&an(s[r]))return s[r];var u=n[r]-l-(i>0?i:0),m=n[r]+i;if(e[r])return o[r]?u:m;var p=c[r];if(p==null)return 0;if(o[r]){var f=u,x=p;return f<x?Math.max(m,p):Math.max(u,p)}if(d==null)return 0;var v=m+l,g=p+d;return v>g?Math.max(u,p):Math.max(m,p)}function CFe(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 PFe(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:r,offsetLeft:i,position:s,reverseDirection:o,tooltipBox:l,useTranslate3d:c,viewBox:d}=t,u,m,p;return l.height>0&&l.width>0&&n?(m=S7({allowEscapeViewBox:e,coordinate:n,key:"x",offset:i,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:d,viewBoxDimension:d.width}),p=S7({allowEscapeViewBox:e,coordinate:n,key:"y",offset:r,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:d,viewBoxDimension:d.height}),u=CFe({translateX:m,translateY:p,useTranslate3d:c})):u=kFe,{cssProperties:u,cssClasses:NFe({translateX:m,translateY:p,coordinate:n})}}function _7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function q1(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){ER(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 ER(t,e,n){return(e=TFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function TFe(t){var e=AFe(t,"string");return typeof e=="symbol"?e:e+""}function AFe(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 jFe extends w.PureComponent{constructor(){super(...arguments),ER(this,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0}}),ER(this,"handleKeyDown",e=>{if(e.key==="Escape"){var n,r,i,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:(i=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i: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:i,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:d,position:u,reverseDirection:m,useTranslate3d:p,viewBox:f,wrapperStyle:x,lastBoundingBox:v,innerRef:g,hasPortalFromProps:b}=this.props,_=typeof d=="number"?d:d.x,C=typeof d=="number"?d:d.y,{cssClasses:P,cssProperties:N}=PFe({allowEscapeViewBox:n,coordinate:o,offsetLeft:_,offsetTop:C,position:u,reverseDirection:m,tooltipBox:{height:v.height,width:v.width},useTranslate3d:p,viewBox:f}),A=b?{}:q1(q1({transition:c&&e?"transform ".concat(r,"ms ").concat(i):void 0},N),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),T=q1(q1({},A),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},x);return w.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:P,style:T,ref:g},s)}}var lte=()=>{var t;return(t=un(e=>e.rootProps.accessibilityLayer))!==null&&t!==void 0?t:!0};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 k7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).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?k7(Object(n),!0).forEach(function(r){MFe(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 MFe(t,e,n){return(e=EFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function EFe(t){var e=DFe(t,"string");return typeof e=="symbol"?e:e+""}function DFe(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 C7={curveBasisClosed:xEe,curveBasisOpen:yEe,curveBasis:bEe,curveBumpX:rEe,curveBumpY:aEe,curveLinearClosed:vEe,curveLinear:WP,curveMonotoneX:wEe,curveMonotoneY:SEe,curveNatural:_Ee,curveStep:kEe,curveStepAfter:CEe,curveStepBefore:NEe},KN=t=>Wn(t.x)&&Wn(t.y),P7=t=>t.base!=null&&KN(t.base)&&KN(t),Mv=t=>t.x,Ev=t=>t.y,FFe=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(Kw(t));if((n==="curveMonotone"||n==="curveBump")&&e){var r=C7["".concat(n).concat(e==="vertical"?"Y":"X")];if(r)return r}return C7[n]||WP},T7={connectNulls:!1,type:"linear"},RFe=t=>{var{type:e=T7.type,points:n=[],baseLine:r,layout:i,connectNulls:s=T7.connectNulls}=t,o=FFe(e,i),l=s?n.filter(KN):n;if(Array.isArray(r)){var c,d=n.map((x,v)=>N7(N7({},x),{},{base:r[v]}));i==="vertical"?c=R1().y(Ev).x1(Mv).x0(x=>x.base.x):c=R1().x(Mv).y1(Ev).y0(x=>x.base.y);var u=c.defined(P7).curve(o),m=s?d.filter(P7):d;return u(m)}var p;i==="vertical"&&an(r)?p=R1().y(Ev).x1(Mv).x0(r):an(r)?p=R1().x(Mv).y1(Ev).y0(r):p=DJ().x(Mv).y(Ev);var f=p.defined(KN).curve(o);return f(l)},yx=t=>{var{className:e,points:n,path:r,pathRef:i}=t,s=xp();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?RFe(o):r;return w.createElement("path",DR({},no(t),gI(t),{className:_r("recharts-curve",e),d:l===null?void 0:l,ref:i}))},LFe=["x","y","top","left","width","height","className"];function FR(){return FR=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},FR.apply(null,arguments)}function A7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function OFe(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){IFe(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 IFe(t,e,n){return(e=zFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function zFe(t){var e=UFe(t,"string");return typeof e=="symbol"?e:e+""}function UFe(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 BFe(t,e){if(t==null)return{};var n,r,i=HFe(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)&&(i[n]=t[n])}return i}function HFe(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 qFe=(t,e,n,r,i,s)=>"M".concat(t,",").concat(i,"v").concat(r,"M").concat(s,",").concat(e,"h").concat(n),$Fe=t=>{var{x:e=0,y:n=0,top:r=0,left:i=0,width:s=0,height:o=0,className:l}=t,c=BFe(t,LFe),d=OFe({x:e,y:n,top:r,left:i,width:s,height:o},c);return!an(e)||!an(n)||!an(s)||!an(o)||!an(r)||!an(i)?null:w.createElement("path",FR({},ys(d),{className:_r("recharts-cross",l),d:qFe(e,n,s,o,r,i)}))};function VFe(t,e,n,r){var i=r/2;return{stroke:"none",fill:"#ccc",x:t==="horizontal"?e.x-i:n.left+.5,y:t==="horizontal"?n.top+.5:e.y-i,width:t==="horizontal"?r:n.width-1,height:t==="horizontal"?n.height-1:r}}function j7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function M7(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){GFe(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 GFe(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=KFe(t,"string");return typeof e=="symbol"?e:e+""}function KFe(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 XFe=t=>t.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),cte=(t,e,n)=>t.map(r=>"".concat(XFe(r)," ").concat(e,"ms ").concat(n)).join(","),YFe=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,r)=>n.filter(i=>r.includes(i))),ow=(t,e)=>Object.keys(e).reduce((n,r)=>M7(M7({},n),{},{[r]:t(r,e[r])}),{});function E7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Si(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?E7(Object(n),!0).forEach(function(r){QFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):E7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function QFe(t,e,n){return(e=ZFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ZFe(t){var e=JFe(t,"string");return typeof e=="symbol"?e:e+""}function JFe(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 XN=(t,e,n)=>t+(e-t)*n,RR=t=>{var{from:e,to:n}=t;return e!==n},dte=(t,e,n)=>{var r=ow((i,s)=>{if(RR(s)){var[o,l]=t(s.from,s.to,s.velocity);return Si(Si({},s),{},{from:o,velocity:l})}return s},e);return n<1?ow((i,s)=>RR(s)&&r[i]!=null?Si(Si({},s),{},{velocity:XN(s.velocity,r[i].velocity,n),from:XN(s.from,r[i].from,n)}):s,e):dte(t,r,n-1)};function eRe(t,e,n,r,i,s){var o,l=r.reduce((p,f)=>Si(Si({},p),{},{[f]:{from:t[f],velocity:0,to:e[f]}}),{}),c=()=>ow((p,f)=>f.from,l),d=()=>!Object.values(l).filter(RR).length,u=null,m=p=>{o||(o=p);var f=p-o,x=f/n.dt;l=dte(n,l,x),i(Si(Si(Si({},t),e),c())),o=p,d()||(u=s.setTimeout(m))};return()=>(u=s.setTimeout(m),()=>{var p;(p=u)===null||p===void 0||p()})}function tRe(t,e,n,r,i,s,o){var l=null,c=i.reduce((m,p)=>{var f=t[p],x=e[p];return f==null||x==null?m:Si(Si({},m),{},{[p]:[f,x]})},{}),d,u=m=>{d||(d=m);var p=(m-d)/r,f=ow((v,g)=>XN(...g,n(p)),c);if(s(Si(Si(Si({},t),e),f)),p<1)l=o.setTimeout(u);else{var x=ow((v,g)=>XN(...g,n(1)),c);s(Si(Si(Si({},t),e),x))}};return()=>(l=o.setTimeout(u),()=>{var m;(m=l)===null||m===void 0||m()})}const nRe=(t,e,n,r,i,s)=>{var o=YFe(t,e);return n==null?()=>(i(Si(Si({},t),e)),()=>{}):n.isStepper===!0?eRe(t,e,n,o,i,s):tRe(t,e,n,r,o,i,s)};var YN=1e-4,ute=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],mte=(t,e)=>t.map((n,r)=>n*e**r).reduce((n,r)=>n+r),D7=(t,e)=>n=>{var r=ute(t,e);return mte(r,n)},rRe=(t,e)=>n=>{var r=ute(t,e),i=[...r.map((s,o)=>s*o).slice(1),0];return mte(i,n)},aRe=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 i=r.map(s=>parseFloat(s));return[i[0],i[1],i[2],i[3]]},iRe=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 i=aRe(n[0]);if(i)return i}}return n.length===4?n:[0,0,1,1]},sRe=(t,e,n,r)=>{var i=D7(t,n),s=D7(e,r),o=rRe(t,n),l=d=>d>1?1:d<0?0:d,c=d=>{for(var u=d>1?1:d,m=u,p=0;p<8;++p){var f=i(m)-u,x=o(m);if(Math.abs(f-u)<YN||x<YN)return s(m);m=l(m-f/x)}return s(m)};return c.isStepper=!1,c},F7=function(){return sRe(...iRe(...arguments))},oRe=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:r=8,dt:i=17}=e,s=(o,l,c)=>{var d=-(o-l)*n,u=c*r,m=c+(d-u)*i/1e3,p=c*i/1e3+o;return Math.abs(p-l)<YN&&Math.abs(m)<YN?[l,0]:[p,m]};return s.isStepper=!0,s.dt=i,s},lRe=t=>{if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return F7(t);case"spring":return oRe();default:if(t.split("(")[0]==="cubic-bezier")return F7(t)}return typeof t=="function"?t:null};function cRe(t){var e,n=()=>null,r=!1,i=null,s=o=>{if(!r){if(Array.isArray(o)){if(!o.length)return;var l=o,[c,...d]=l;if(typeof c=="number"){i=t.setTimeout(s.bind(null,d),c);return}s(c),i=t.setTimeout(s.bind(null,d));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,i&&(i(),i=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class dRe{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),i=null,s=o=>{o-r>=n?e(o):typeof requestAnimationFrame=="function"&&(i=requestAnimationFrame(s))};return i=requestAnimationFrame(s),()=>{i!=null&&cancelAnimationFrame(i)}}}function uRe(){return cRe(new dRe)}var mRe=w.createContext(uRe);function hRe(t,e){var n=w.useContext(mRe);return w.useMemo(()=>e??n(t),[t,e,n])}var pRe=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),nS={isSsr:pRe()},fRe={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},R7={t:0},q2={t:1};function py(t){var e=Da(t,fRe),{isActive:n,canBegin:r,duration:i,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:d}=e,u=n==="auto"?!nS.isSsr:n,m=hRe(e.animationId,e.animationManager),[p,f]=w.useState(u?R7:q2),x=w.useRef(null);return w.useEffect(()=>{u||f(q2)},[u]),w.useEffect(()=>{if(!u||!r)return gp;var v=nRe(R7,q2,lRe(s),i,f,m.getTimeoutController()),g=()=>{x.current=v()};return m.start([c,o,g,i,l]),()=>{m.stop(),x.current&&x.current(),l()}},[u,r,i,s,o,c,l,m]),d(p.t)}function fy(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=w.useRef(ew(e)),r=w.useRef(t);return r.current!==t&&(n.current=ew(e),r.current=t),n.current}var gRe=["radius"],bRe=["radius"],L7,O7,I7,z7,U7,B7,H7,q7,$7,V7;function G7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function W7(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){xRe(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 xRe(t,e,n){return(e=yRe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yRe(t){var e=vRe(t,"string");return typeof e=="symbol"?e:e+""}function vRe(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 QN(){return QN=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},QN.apply(null,arguments)}function K7(t,e){if(t==null)return{};var n,r,i=wRe(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)&&(i[n]=t[n])}return i}function wRe(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 od(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var X7=(t,e,n,r,i)=>{var s=Dh(n),o=Dh(r),l=Math.min(Math.abs(s)/2,Math.abs(o)/2),c=o>=0?1:-1,d=s>=0?1:-1,u=o>=0&&s>=0||o<0&&s<0?1:0,m;if(l>0&&Array.isArray(i)){for(var p=[0,0,0,0],f=0,x=4;f<x;f++){var v,g=(v=i[f])!==null&&v!==void 0?v:0;p[f]=g>l?l:g}m=Ba(L7||(L7=od(["M",",",""])),t,e+c*p[0]),p[0]>0&&(m+=Ba(O7||(O7=od(["A ",",",",0,0,",",",",",""])),p[0],p[0],u,t+d*p[0],e)),m+=Ba(I7||(I7=od(["L ",",",""])),t+n-d*p[1],e),p[1]>0&&(m+=Ba(z7||(z7=od(["A ",",",",0,0,",`,
- `,",",""])),p[1],p[1],u,t+n,e+c*p[1])),m+=Ba(U7||(U7=od(["L ",",",""])),t+n,e+r-c*p[2]),p[2]>0&&(m+=Ba(B7||(B7=od(["A ",",",",0,0,",`,
- `,",",""])),p[2],p[2],u,t+n-d*p[2],e+r)),m+=Ba(H7||(H7=od(["L ",",",""])),t+d*p[3],e+r),p[3]>0&&(m+=Ba(q7||(q7=od(["A ",",",",0,0,",`,
- `,",",""])),p[3],p[3],u,t,e+r-c*p[3])),m+="Z"}else if(l>0&&i===+i&&i>0){var b=Math.min(l,i);m=Ba($7||($7=od(["M ",",",`
- A `,",",",0,0,",",",",",`
- L `,",",`
- A `,",",",0,0,",",",",",`
- L `,",",`
- A `,",",",0,0,",",",",",`
- L `,",",`
- A `,",",",0,0,",",",","," Z"])),t,e+c*b,b,b,u,t+d*b,e,t+n-d*b,e,b,b,u,t+n,e+c*b,t+n,e+r-c*b,b,b,u,t+n-d*b,e+r,t+d*b,e+r,b,b,u,t,e+r-c*b)}else m=Ba(V7||(V7=od(["M ",","," h "," v "," h "," Z"])),t,e,n,r,-n);return m},Y7={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},hte=t=>{var e=Da(t,Y7),n=w.useRef(null),[r,i]=w.useState(-1);w.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var ee=n.current.getTotalLength();ee&&i(ee)}catch{}},[]);var{x:s,y:o,width:l,height:c,radius:d,className:u}=e,{animationEasing:m,animationDuration:p,animationBegin:f,isAnimationActive:x,isUpdateAnimationActive:v}=e,g=w.useRef(l),b=w.useRef(c),_=w.useRef(s),C=w.useRef(o),P=w.useMemo(()=>({x:s,y:o,width:l,height:c,radius:d}),[s,o,l,c,d]),N=fy(P,"rectangle-");if(s!==+s||o!==+o||l!==+l||c!==+c||l===0||c===0)return null;var A=_r("recharts-rectangle",u);if(!v){var T=ys(e),{radius:F}=T,k=K7(T,gRe);return w.createElement("path",QN({},k,{x:Dh(s),y:Dh(o),width:Dh(l),height:Dh(c),radius:typeof d=="number"?d:void 0,className:A,d:X7(s,o,l,c,d)}))}var D=g.current,H=b.current,z=_.current,X=C.current,L="0px ".concat(r===-1?1:r,"px"),ne="".concat(r,"px 0px"),ie=cte(["strokeDasharray"],p,typeof m=="string"?m:Y7.animationEasing);return w.createElement(py,{animationId:N,key:N,canBegin:r>0,duration:p,easing:m,isActive:v,begin:f},ee=>{var ue=Dr(D,l,ee),le=Dr(H,c,ee),oe=Dr(z,s,ee),W=Dr(X,o,ee);n.current&&(g.current=ue,b.current=le,_.current=oe,C.current=W);var re;x?ee>0?re={transition:ie,strokeDasharray:ne}:re={strokeDasharray:L}:re={strokeDasharray:ne};var ce=ys(e),{radius:xe}=ce,Ne=K7(ce,bRe);return w.createElement("path",QN({},Ne,{radius:typeof d=="number"?d:void 0,className:A,d:X7(oe,W,ue,le,d),ref:n,style:W7(W7({},re),e.style)}))})};function Q7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Z7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Q7(Object(n),!0).forEach(function(r){SRe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Q7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function SRe(t,e,n){return(e=_Re(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _Re(t){var e=kRe(t,"string");return typeof e=="symbol"?e:e+""}function kRe(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 ZN=Math.PI/180,NRe=t=>t*180/Math.PI,hi=(t,e,n,r)=>({x:t+Math.cos(-ZN*r)*n,y:e+Math.sin(-ZN*r)*n}),pte=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},CRe=(t,e)=>{var{x:n,y:r}=t,{x:i,y:s}=e;return Math.sqrt((n-i)**2+(r-s)**2)},PRe=(t,e)=>{var{x:n,y:r}=t,{cx:i,cy:s}=e,o=CRe({x:n,y:r},{x:i,y:s});if(o<=0)return{radius:o,angle:0};var l=(n-i)/o,c=Math.acos(l);return r>s&&(c=2*Math.PI-c),{radius:o,angle:NRe(c),angleInRadian:c}},TRe=t=>{var{startAngle:e,endAngle:n}=t,r=Math.floor(e/360),i=Math.floor(n/360),s=Math.min(r,i);return{startAngle:e-s*360,endAngle:n-s*360}},ARe=(t,e)=>{var{startAngle:n,endAngle:r}=e,i=Math.floor(n/360),s=Math.floor(r/360),o=Math.min(i,s);return t+o*360},jRe=(t,e)=>{var{chartX:n,chartY:r}=t,{radius:i,angle:s}=PRe({x:n,y:r},e),{innerRadius:o,outerRadius:l}=e;if(i<o||i>l||i===0)return null;var{startAngle:c,endAngle:d}=TRe(e),u=s,m;if(c<=d){for(;u>d;)u-=360;for(;u<c;)u+=360;m=u>=c&&u<=d}else{for(;u>c;)u-=360;for(;u<d;)u+=360;m=u>=d&&u<=c}return m?Z7(Z7({},e),{},{radius:i,angle:ARe(u,e)}):null};function fte(t){var{cx:e,cy:n,radius:r,startAngle:i,endAngle:s}=t,o=hi(e,n,r,i),l=hi(e,n,r,s);return{points:[o,l],cx:e,cy:n,radius:r,startAngle:i,endAngle:s}}var J7,eG,tG,nG,rG,aG,iG;function LR(){return LR=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},LR.apply(null,arguments)}function vf(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var MRe=(t,e)=>{var n=Bi(e-t),r=Math.min(Math.abs(e-t),359.999);return n*r},$1=t=>{var{cx:e,cy:n,radius:r,angle:i,sign:s,isExternal:o,cornerRadius:l,cornerIsExternal:c}=t,d=l*(o?1:-1)+r,u=Math.asin(l/d)/ZN,m=c?i:i+s*u,p=hi(e,n,d,m),f=hi(e,n,r,m),x=c?i-s*u:i,v=hi(e,n,d*Math.cos(u*ZN),x);return{center:p,circleTangency:f,lineTangency:v,theta:u}},gte=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:i,startAngle:s,endAngle:o}=t,l=MRe(s,o),c=s+l,d=hi(e,n,i,s),u=hi(e,n,i,c),m=Ba(J7||(J7=vf(["M ",",",`
- A `,",",`,0,
- `,",",`,
- `,",",`
- `])),d.x,d.y,i,i,+(Math.abs(l)>180),+(s>c),u.x,u.y);if(r>0){var p=hi(e,n,r,s),f=hi(e,n,r,c);m+=Ba(eG||(eG=vf(["L ",",",`
- A `,",",`,0,
- `,",",`,
- `,","," Z"])),f.x,f.y,r,r,+(Math.abs(l)>180),+(s<=c),p.x,p.y)}else m+=Ba(tG||(tG=vf(["L ",","," Z"])),e,n);return m},ERe=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:i,cornerRadius:s,forceCornerRadius:o,cornerIsExternal:l,startAngle:c,endAngle:d}=t,u=Bi(d-c),{circleTangency:m,lineTangency:p,theta:f}=$1({cx:e,cy:n,radius:i,angle:c,sign:u,cornerRadius:s,cornerIsExternal:l}),{circleTangency:x,lineTangency:v,theta:g}=$1({cx:e,cy:n,radius:i,angle:d,sign:-u,cornerRadius:s,cornerIsExternal:l}),b=l?Math.abs(c-d):Math.abs(c-d)-f-g;if(b<0)return o?Ba(nG||(nG=vf(["M ",",",`
- a`,",",",0,0,1,",`,0
- a`,",",",0,0,1,",`,0
- `])),p.x,p.y,s,s,s*2,s,s,-s*2):gte({cx:e,cy:n,innerRadius:r,outerRadius:i,startAngle:c,endAngle:d});var _=Ba(rG||(rG=vf(["M ",",",`
- A`,",",",0,0,",",",",",`
- A`,",",",0,",",",",",",",`
- A`,",",",0,0,",",",",",`
- `])),p.x,p.y,s,s,+(u<0),m.x,m.y,i,i,+(b>180),+(u<0),x.x,x.y,s,s,+(u<0),v.x,v.y);if(r>0){var{circleTangency:C,lineTangency:P,theta:N}=$1({cx:e,cy:n,radius:r,angle:c,sign:u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:A,lineTangency:T,theta:F}=$1({cx:e,cy:n,radius:r,angle:d,sign:-u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),k=l?Math.abs(c-d):Math.abs(c-d)-N-F;if(k<0&&s===0)return"".concat(_,"L").concat(e,",").concat(n,"Z");_+=Ba(aG||(aG=vf(["L",",",`
- A`,",",",0,0,",",",",",`
- A`,",",",0,",",",",",",",`
- A`,",",",0,0,",",",",","Z"])),T.x,T.y,s,s,+(u<0),A.x,A.y,r,r,+(k>180),+(u>0),C.x,C.y,s,s,+(u<0),P.x,P.y)}else _+=Ba(iG||(iG=vf(["L",",","Z"])),e,n);return _},DRe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},bte=t=>{var e=Da(t,DRe),{cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:d,endAngle:u,className:m}=e;if(s<i||d===u)return null;var p=_r("recharts-sector",m),f=s-i,x=Ds(o,f,0,!0),v;return x>0&&Math.abs(d-u)<360?v=ERe({cx:n,cy:r,innerRadius:i,outerRadius:s,cornerRadius:Math.min(x,f/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:d,endAngle:u}):v=gte({cx:n,cy:r,innerRadius:i,outerRadius:s,startAngle:d,endAngle:u}),w.createElement("path",LR({},ys(e),{className:p,d:v}))};function FRe(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(KJ(e)){if(t==="centric"){var{cx:r,cy:i,innerRadius:s,outerRadius:o,angle:l}=e,c=hi(r,i,s,l),d=hi(r,i,o,l);return[{x:c.x,y:c.y},{x:d.x,y:d.y}]}return fte(e)}}var $2={},V2={},G2={},sG;function RRe(){return sG||(sG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=see();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(G2)),G2}var oG;function LRe(){return oG||(oG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=RRe();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})(V2)),V2}var lG;function ORe(){return lG||(lG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=oee(),n=LRe();function r(i,s,o){o&&typeof o!="number"&&e.isIterateeCall(i,s,o)&&(s=o=void 0),i=n.toFinite(i),s===void 0?(s=i,i=0):s=n.toFinite(s),o=o===void 0?i<s?1:-1:n.toFinite(o);const l=Math.max(Math.ceil((s-i)/(o||1)),0),c=new Array(l);for(let d=0;d<l;d++)c[d]=i,i+=o;return c}t.range=r})($2)),$2}var W2,cG;function IRe(){return cG||(cG=1,W2=ORe().range),W2}var zRe=IRe();const xte=mc(zRe);function Zh(t,e){return t==null||e==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function URe(t,e){return t==null||e==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function FI(t){let e,n,r;t.length!==2?(e=Zh,n=(l,c)=>Zh(t(l),c),r=(l,c)=>t(l)-c):(e=t===Zh||t===URe?t:BRe,n=t,r=t);function i(l,c,d=0,u=l.length){if(d<u){if(e(c,c)!==0)return u;do{const m=d+u>>>1;n(l[m],c)<0?d=m+1:u=m}while(d<u)}return d}function s(l,c,d=0,u=l.length){if(d<u){if(e(c,c)!==0)return u;do{const m=d+u>>>1;n(l[m],c)<=0?d=m+1:u=m}while(d<u)}return d}function o(l,c,d=0,u=l.length){const m=i(l,c,d,u-1);return m>d&&r(l[m-1],c)>-r(l[m],c)?m-1:m}return{left:i,center:o,right:s}}function BRe(){return 0}function yte(t){return t===null?NaN:+t}function*HRe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const qRe=FI(Zh),rS=qRe.right;FI(yte).center;class dG extends Map{constructor(e,n=GRe){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,i]of e)this.set(r,i)}get(e){return super.get(uG(this,e))}has(e){return super.has(uG(this,e))}set(e,n){return super.set($Re(this,e),n)}delete(e){return super.delete(VRe(this,e))}}function uG({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function $Re({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function VRe({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function GRe(t){return t!==null&&typeof t=="object"?t.valueOf():t}function WRe(t=Zh){if(t===Zh)return vte;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 vte(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(t<e?-1:t>e?1:0)}const KRe=Math.sqrt(50),XRe=Math.sqrt(10),YRe=Math.sqrt(2);function JN(t,e,n){const r=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=KRe?10:s>=XRe?5:s>=YRe?2:1;let l,c,d;return i<0?(d=Math.pow(10,-i)/o,l=Math.round(t*d),c=Math.round(e*d),l/d<t&&++l,c/d>e&&--c,d=-d):(d=Math.pow(10,i)*o,l=Math.round(t/d),c=Math.round(e/d),l*d<t&&++l,c*d>e&&--c),c<l&&.5<=n&&n<2?JN(t,e,n*2):[l,c,d]}function OR(t,e,n){if(e=+e,t=+t,n=+n,!(n>0))return[];if(t===e)return[t];const r=e<t,[i,s,o]=r?JN(e,t,n):JN(t,e,n);if(!(s>=i))return[];const l=s-i+1,c=new Array(l);if(r)if(o<0)for(let d=0;d<l;++d)c[d]=(s-d)/-o;else for(let d=0;d<l;++d)c[d]=(s-d)*o;else if(o<0)for(let d=0;d<l;++d)c[d]=(i+d)/-o;else for(let d=0;d<l;++d)c[d]=(i+d)*o;return c}function IR(t,e,n){return e=+e,t=+t,n=+n,JN(t,e,n)[2]}function zR(t,e,n){e=+e,t=+t,n=+n;const r=e<t,i=r?IR(e,t,n):IR(t,e,n);return(r?-1:1)*(i<0?1/-i:i)}function mG(t,e){let n;for(const r of t)r!=null&&(n<r||n===void 0&&r>=r)&&(n=r);return n}function hG(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function wte(t,e,n=0,r=1/0,i){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(i=i===void 0?vte:WRe(i);r>n;){if(r-n>600){const c=r-n+1,d=e-n+1,u=Math.log(c),m=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*m*(c-m)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(e-d*m/c+p)),x=Math.min(r,Math.floor(e+(c-d)*m/c+p));wte(t,e,f,x,i)}const s=t[e];let o=n,l=r;for(Dv(t,n,e),i(t[r],s)>0&&Dv(t,n,r);o<l;){for(Dv(t,o,l),++o,--l;i(t[o],s)<0;)++o;for(;i(t[l],s)>0;)--l}i(t[n],s)===0?Dv(t,n,l):(++l,Dv(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function Dv(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function QRe(t,e,n){if(t=Float64Array.from(HRe(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return hG(t);if(e>=1)return mG(t);var r,i=(r-1)*e,s=Math.floor(i),o=mG(wte(t,s).subarray(0,s+1)),l=hG(t.subarray(s+1));return o+(l-o)*(i-s)}}function ZRe(t,e,n=yte){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,i=(r-1)*e,s=Math.floor(i),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(i-s)}}function JRe(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(i);++r<i;)s[r]=t+r*n;return s}function pc(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}function ym(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 UR=Symbol("implicit");function RI(){var t=new dG,e=[],n=[],r=UR;function i(s){let o=t.get(s);if(o===void 0){if(r!==UR)return r;t.set(s,o=e.push(s)-1)}return n[o%n.length]}return i.domain=function(s){if(!arguments.length)return e.slice();e=[],t=new dG;for(const o of s)t.has(o)||t.set(o,e.push(o)-1);return i},i.range=function(s){return arguments.length?(n=Array.from(s),i):n.slice()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return RI(e,n).unknown(r)},pc.apply(i,arguments),i}function LI(){var t=RI().unknown(void 0),e=t.domain,n=t.range,r=0,i=1,s,o,l=!1,c=0,d=0,u=.5;delete t.unknown;function m(){var p=e().length,f=i<r,x=f?i:r,v=f?r:i;s=(v-x)/Math.max(1,p-c+d*2),l&&(s=Math.floor(s)),x+=(v-x-s*(p-c))*u,o=s*(1-c),l&&(x=Math.round(x),o=Math.round(o));var g=JRe(p).map(function(b){return x+s*b});return n(f?g.reverse():g)}return t.domain=function(p){return arguments.length?(e(p),m()):e()},t.range=function(p){return arguments.length?([r,i]=p,r=+r,i=+i,m()):[r,i]},t.rangeRound=function(p){return[r,i]=p,r=+r,i=+i,l=!0,m()},t.bandwidth=function(){return o},t.step=function(){return s},t.round=function(p){return arguments.length?(l=!!p,m()):l},t.padding=function(p){return arguments.length?(c=Math.min(1,d=+p),m()):c},t.paddingInner=function(p){return arguments.length?(c=Math.min(1,p),m()):c},t.paddingOuter=function(p){return arguments.length?(d=+p,m()):d},t.align=function(p){return arguments.length?(u=Math.max(0,Math.min(1,p)),m()):u},t.copy=function(){return LI(e(),[r,i]).round(l).paddingInner(c).paddingOuter(d).align(u)},pc.apply(m(),arguments)}function Ste(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return Ste(e())},t}function eLe(){return Ste(LI.apply(null,arguments).paddingInner(1))}function OI(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function _te(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}function aS(){}var lw=.7,eC=1/lw,vx="\\s*([+-]?\\d+)\\s*",cw="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Td="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",tLe=/^#([0-9a-f]{3,8})$/,nLe=new RegExp(`^rgb\\(${vx},${vx},${vx}\\)$`),rLe=new RegExp(`^rgb\\(${Td},${Td},${Td}\\)$`),aLe=new RegExp(`^rgba\\(${vx},${vx},${vx},${cw}\\)$`),iLe=new RegExp(`^rgba\\(${Td},${Td},${Td},${cw}\\)$`),sLe=new RegExp(`^hsl\\(${cw},${Td},${Td}\\)$`),oLe=new RegExp(`^hsla\\(${cw},${Td},${Td},${cw}\\)$`),pG={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};OI(aS,dw,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:fG,formatHex:fG,formatHex8:lLe,formatHsl:cLe,formatRgb:gG,toString:gG});function fG(){return this.rgb().formatHex()}function lLe(){return this.rgb().formatHex8()}function cLe(){return kte(this).formatHsl()}function gG(){return this.rgb().formatRgb()}function dw(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=tLe.exec(t))?(n=e[1].length,e=parseInt(e[1],16),n===6?bG(e):n===3?new To(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?V1(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?V1(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=nLe.exec(t))?new To(e[1],e[2],e[3],1):(e=rLe.exec(t))?new To(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=aLe.exec(t))?V1(e[1],e[2],e[3],e[4]):(e=iLe.exec(t))?V1(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=sLe.exec(t))?vG(e[1],e[2]/100,e[3]/100,1):(e=oLe.exec(t))?vG(e[1],e[2]/100,e[3]/100,e[4]):pG.hasOwnProperty(t)?bG(pG[t]):t==="transparent"?new To(NaN,NaN,NaN,0):null}function bG(t){return new To(t>>16&255,t>>8&255,t&255,1)}function V1(t,e,n,r){return r<=0&&(t=e=n=NaN),new To(t,e,n,r)}function dLe(t){return t instanceof aS||(t=dw(t)),t?(t=t.rgb(),new To(t.r,t.g,t.b,t.opacity)):new To}function BR(t,e,n,r){return arguments.length===1?dLe(t):new To(t,e,n,r??1)}function To(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}OI(To,BR,_te(aS,{brighter(t){return t=t==null?eC:Math.pow(eC,t),new To(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?lw:Math.pow(lw,t),new To(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new To(Lf(this.r),Lf(this.g),Lf(this.b),tC(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:xG,formatHex:xG,formatHex8:uLe,formatRgb:yG,toString:yG}));function xG(){return`#${wf(this.r)}${wf(this.g)}${wf(this.b)}`}function uLe(){return`#${wf(this.r)}${wf(this.g)}${wf(this.b)}${wf((isNaN(this.opacity)?1:this.opacity)*255)}`}function yG(){const t=tC(this.opacity);return`${t===1?"rgb(":"rgba("}${Lf(this.r)}, ${Lf(this.g)}, ${Lf(this.b)}${t===1?")":`, ${t})`}`}function tC(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Lf(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function wf(t){return t=Lf(t),(t<16?"0":"")+t.toString(16)}function vG(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new Dc(t,e,n,r)}function kte(t){if(t instanceof Dc)return new Dc(t.h,t.s,t.l,t.opacity);if(t instanceof aS||(t=dw(t)),!t)return new Dc;if(t instanceof Dc)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-i,c=(s+i)/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+i:2-s-i,o*=60):l=c>0&&c<1?0:o,new Dc(o,l,c,t.opacity)}function mLe(t,e,n,r){return arguments.length===1?kte(t):new Dc(t,e,n,r??1)}function Dc(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}OI(Dc,mLe,_te(aS,{brighter(t){return t=t==null?eC:Math.pow(eC,t),new Dc(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?lw:Math.pow(lw,t),new Dc(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,i=2*n-r;return new To(K2(t>=240?t-240:t+120,i,r),K2(t,i,r),K2(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Dc(wG(this.h),G1(this.s),G1(this.l),tC(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=tC(this.opacity);return`${t===1?"hsl(":"hsla("}${wG(this.h)}, ${G1(this.s)*100}%, ${G1(this.l)*100}%${t===1?")":`, ${t})`}`}}));function wG(t){return t=(t||0)%360,t<0?t+360:t}function G1(t){return Math.max(0,Math.min(1,t||0))}function K2(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 II=t=>()=>t;function hLe(t,e){return function(n){return t+n*e}}function pLe(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 fLe(t){return(t=+t)==1?Nte:function(e,n){return n-e?pLe(e,n,t):II(isNaN(e)?n:e)}}function Nte(t,e){var n=e-t;return n?hLe(t,n):II(isNaN(t)?e:t)}const SG=(function t(e){var n=fLe(e);function r(i,s){var o=n((i=BR(i)).r,(s=BR(s)).r),l=n(i.g,s.g),c=n(i.b,s.b),d=Nte(i.opacity,s.opacity);return function(u){return i.r=o(u),i.g=l(u),i.b=c(u),i.opacity=d(u),i+""}}return r.gamma=t,r})(1);function gLe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),i;return function(s){for(i=0;i<n;++i)r[i]=t[i]*(1-s)+e[i]*s;return r}}function bLe(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function xLe(t,e){var n=e?e.length:0,r=t?Math.min(n,t.length):0,i=new Array(r),s=new Array(n),o;for(o=0;o<r;++o)i[o]=gy(t[o],e[o]);for(;o<n;++o)s[o]=e[o];return function(l){for(o=0;o<r;++o)s[o]=i[o](l);return s}}function yLe(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}function nC(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}function vLe(t,e){var n={},r={},i;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(i in e)i in t?n[i]=gy(t[i],e[i]):r[i]=e[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var HR=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,X2=new RegExp(HR.source,"g");function wLe(t){return function(){return t}}function SLe(t){return function(e){return t(e)+""}}function _Le(t,e){var n=HR.lastIndex=X2.lastIndex=0,r,i,s,o=-1,l=[],c=[];for(t=t+"",e=e+"";(r=HR.exec(t))&&(i=X2.exec(e));)(s=i.index)>n&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(i=i[0])?l[o]?l[o]+=i:l[++o]=i:(l[++o]=null,c.push({i:o,x:nC(r,i)})),n=X2.lastIndex;return n<e.length&&(s=e.slice(n),l[o]?l[o]+=s:l[++o]=s),l.length<2?c[0]?SLe(c[0].x):wLe(e):(e=c.length,function(d){for(var u=0,m;u<e;++u)l[(m=c[u]).i]=m.x(d);return l.join("")})}function gy(t,e){var n=typeof e,r;return e==null||n==="boolean"?II(e):(n==="number"?nC:n==="string"?(r=dw(e))?(e=r,SG):_Le:e instanceof dw?SG:e instanceof Date?yLe:bLe(e)?gLe:Array.isArray(e)?xLe:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?vLe:nC)(t,e)}function zI(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}function kLe(t,e){e===void 0&&(e=t,t=gy);for(var n=0,r=e.length-1,i=e[0],s=new Array(r<0?0:r);n<r;)s[n]=t(i,i=e[++n]);return function(o){var l=Math.max(0,Math.min(r-1,Math.floor(o*=r)));return s[l](o-l)}}function NLe(t){return function(){return t}}function rC(t){return+t}var _G=[0,1];function Xs(t){return t}function qR(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:NLe(isNaN(e)?NaN:.5)}function CLe(t,e){var n;return t>e&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function PLe(t,e,n){var r=t[0],i=t[1],s=e[0],o=e[1];return i<r?(r=qR(i,r),s=n(o,s)):(r=qR(r,i),s=n(s,o)),function(l){return s(r(l))}}function TLe(t,e,n){var r=Math.min(t.length,e.length)-1,i=new Array(r),s=new Array(r),o=-1;for(t[r]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<r;)i[o]=qR(t[o],t[o+1]),s[o]=n(e[o],e[o+1]);return function(l){var c=rS(t,l,1,r)-1;return s[c](i[c](l))}}function iS(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function mT(){var t=_G,e=_G,n=gy,r,i,s,o=Xs,l,c,d;function u(){var p=Math.min(t.length,e.length);return o!==Xs&&(o=CLe(t[0],t[p-1])),l=p>2?TLe:PLe,c=d=null,m}function m(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(r),e,n)))(r(o(p)))}return m.invert=function(p){return o(i((d||(d=l(e,t.map(r),nC)))(p)))},m.domain=function(p){return arguments.length?(t=Array.from(p,rC),u()):t.slice()},m.range=function(p){return arguments.length?(e=Array.from(p),u()):e.slice()},m.rangeRound=function(p){return e=Array.from(p),n=zI,u()},m.clamp=function(p){return arguments.length?(o=p?!0:Xs,u()):o!==Xs},m.interpolate=function(p){return arguments.length?(n=p,u()):n},m.unknown=function(p){return arguments.length?(s=p,m):s},function(p,f){return r=p,i=f,u()}}function UI(){return mT()(Xs,Xs)}function ALe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function aC(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 Hx(t){return t=aC(Math.abs(t)),t?t[1]:NaN}function jLe(t,e){return function(n,r){for(var i=n.length,s=[],o=0,l=t[0],c=0;i>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(i-=l,i+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function MLe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var ELe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function uw(t){if(!(e=ELe.exec(t)))throw new Error("invalid format: "+t);var e;return new BI({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]})}uw.prototype=BI.prototype;function BI(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+""}BI.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 DLe(t){e:for(var e=t.length,n=1,r=-1,i;n<e;++n)switch(t[n]){case".":r=i=n;break;case"0":r===0&&(r=n),i=n;break;default:if(!+t[n])break e;r>0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(i+1):t}var iC;function FLe(t,e){var n=aC(t,e);if(!n)return iC=void 0,t.toPrecision(e);var r=n[0],i=n[1],s=i-(iC=Math.max(-8,Math.min(8,Math.floor(i/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")+aC(t,Math.max(0,e+s-1))[0]}function kG(t,e){var n=aC(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}const NG={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:ALe,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)=>kG(t*100,e),r:kG,s:FLe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function CG(t){return t}var PG=Array.prototype.map,TG=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function RLe(t){var e=t.grouping===void 0||t.thousands===void 0?CG:jLe(PG.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?CG:MLe(PG.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 d(m,p){m=uw(m);var f=m.fill,x=m.align,v=m.sign,g=m.symbol,b=m.zero,_=m.width,C=m.comma,P=m.precision,N=m.trim,A=m.type;A==="n"?(C=!0,A="g"):NG[A]||(P===void 0&&(P=12),N=!0,A="g"),(b||f==="0"&&x==="=")&&(b=!0,f="0",x="=");var T=(p&&p.prefix!==void 0?p.prefix:"")+(g==="$"?n:g==="#"&&/[boxX]/.test(A)?"0"+A.toLowerCase():""),F=(g==="$"?r:/[%p]/.test(A)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),k=NG[A],D=/[defgprs%]/.test(A);P=P===void 0?6:/[gprs]/.test(A)?Math.max(1,Math.min(21,P)):Math.max(0,Math.min(20,P));function H(z){var X=T,L=F,ne,ie,ee;if(A==="c")L=k(z)+L,z="";else{z=+z;var ue=z<0||1/z<0;if(z=isNaN(z)?c:k(Math.abs(z),P),N&&(z=DLe(z)),ue&&+z==0&&v!=="+"&&(ue=!1),X=(ue?v==="("?v:l:v==="-"||v==="("?"":v)+X,L=(A==="s"&&!isNaN(z)&&iC!==void 0?TG[8+iC/3]:"")+L+(ue&&v==="("?")":""),D){for(ne=-1,ie=z.length;++ne<ie;)if(ee=z.charCodeAt(ne),48>ee||ee>57){L=(ee===46?i+z.slice(ne+1):z.slice(ne))+L,z=z.slice(0,ne);break}}}C&&!b&&(z=e(z,1/0));var le=X.length+z.length+L.length,oe=le<_?new Array(_-le+1).join(f):"";switch(C&&b&&(z=e(oe+z,oe.length?_-L.length:1/0),oe=""),x){case"<":z=X+z+L+oe;break;case"=":z=X+oe+z+L;break;case"^":z=oe.slice(0,le=oe.length>>1)+X+z+L+oe.slice(le);break;default:z=oe+X+z+L;break}return s(z)}return H.toString=function(){return m+""},H}function u(m,p){var f=Math.max(-8,Math.min(8,Math.floor(Hx(p)/3)))*3,x=Math.pow(10,-f),v=d((m=uw(m),m.type="f",m),{suffix:TG[8+f/3]});return function(g){return v(x*g)}}return{format:d,formatPrefix:u}}var W1,HI,Cte;LLe({thousands:",",grouping:[3],currency:["$",""]});function LLe(t){return W1=RLe(t),HI=W1.format,Cte=W1.formatPrefix,W1}function OLe(t){return Math.max(0,-Hx(Math.abs(t)))}function ILe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Hx(e)/3)))*3-Hx(Math.abs(t)))}function zLe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Hx(e)-Hx(t))+1}function Pte(t,e,n,r){var i=zR(t,e,n),s;switch(r=uw(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=ILe(i,o))&&(r.precision=s),Cte(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=zLe(i,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=OLe(i))&&(r.precision=s-(r.type==="%")*2);break}}return HI(r)}function yp(t){var e=t.domain;return t.ticks=function(n){var r=e();return OR(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var i=e();return Pte(i[0],i[i.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),i=0,s=r.length-1,o=r[i],l=r[s],c,d,u=10;for(l<o&&(d=o,o=l,l=d,d=i,i=s,s=d);u-- >0;){if(d=IR(o,l,n),d===c)return r[i]=o,r[s]=l,e(r);if(d>0)o=Math.floor(o/d)*d,l=Math.ceil(l/d)*d;else if(d<0)o=Math.ceil(o*d)/d,l=Math.floor(l*d)/d;else break;c=d}return t},t}function Tte(){var t=UI();return t.copy=function(){return iS(t,Tte())},pc.apply(t,arguments),yp(t)}function Ate(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,rC),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return Ate(t).unknown(e)},t=arguments.length?Array.from(t,rC):[0,1],yp(n)}function jte(t,e){t=t.slice();var n=0,r=t.length-1,i=t[n],s=t[r],o;return s<i&&(o=n,n=r,r=o,o=i,i=s,s=o),t[n]=e.floor(i),t[r]=e.ceil(s),t}function AG(t){return Math.log(t)}function jG(t){return Math.exp(t)}function ULe(t){return-Math.log(-t)}function BLe(t){return-Math.exp(-t)}function HLe(t){return isFinite(t)?+("1e"+t):t<0?0:t}function qLe(t){return t===10?HLe:t===Math.E?Math.exp:e=>Math.pow(t,e)}function $Le(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 MG(t){return(e,n)=>-t(-e,n)}function qI(t){const e=t(AG,jG),n=e.domain;let r=10,i,s;function o(){return i=$Le(r),s=qLe(r),n()[0]<0?(i=MG(i),s=MG(s),t(ULe,BLe)):t(AG,jG),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 d=c[0],u=c[c.length-1];const m=u<d;m&&([d,u]=[u,d]);let p=i(d),f=i(u),x,v;const g=l==null?10:+l;let b=[];if(!(r%1)&&f-p<g){if(p=Math.floor(p),f=Math.ceil(f),d>0){for(;p<=f;++p)for(x=1;x<r;++x)if(v=p<0?x/s(-p):x*s(p),!(v<d)){if(v>u)break;b.push(v)}}else for(;p<=f;++p)for(x=r-1;x>=1;--x)if(v=p>0?x/s(-p):x*s(p),!(v<d)){if(v>u)break;b.push(v)}b.length*2<g&&(b=OR(d,u,g))}else b=OR(p,f,Math.min(f-p,g)).map(s);return m?b.reverse():b},e.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=uw(c)).precision==null&&(c.trim=!0),c=HI(c)),l===1/0)return c;const d=Math.max(1,r*l/e.ticks().length);return u=>{let m=u/s(Math.round(i(u)));return m*r<r-.5&&(m*=r),m<=d?c(u):""}},e.nice=()=>n(jte(n(),{floor:l=>s(Math.floor(i(l))),ceil:l=>s(Math.ceil(i(l)))})),e}function Mte(){const t=qI(mT()).domain([1,10]);return t.copy=()=>iS(t,Mte()).base(t.base()),pc.apply(t,arguments),t}function EG(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function DG(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function $I(t){var e=1,n=t(EG(e),DG(e));return n.constant=function(r){return arguments.length?t(EG(e=+r),DG(e)):e},yp(n)}function Ete(){var t=$I(mT());return t.copy=function(){return iS(t,Ete()).constant(t.constant())},pc.apply(t,arguments)}function FG(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function VLe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function GLe(t){return t<0?-t*t:t*t}function VI(t){var e=t(Xs,Xs),n=1;function r(){return n===1?t(Xs,Xs):n===.5?t(VLe,GLe):t(FG(n),FG(1/n))}return e.exponent=function(i){return arguments.length?(n=+i,r()):n},yp(e)}function GI(){var t=VI(mT());return t.copy=function(){return iS(t,GI()).exponent(t.exponent())},pc.apply(t,arguments),t}function WLe(){return GI.apply(null,arguments).exponent(.5)}function RG(t){return Math.sign(t)*t*t}function KLe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Dte(){var t=UI(),e=[0,1],n=!1,r;function i(s){var o=KLe(t(s));return isNaN(o)?r:n?Math.round(o):o}return i.invert=function(s){return t.invert(RG(s))},i.domain=function(s){return arguments.length?(t.domain(s),i):t.domain()},i.range=function(s){return arguments.length?(t.range((e=Array.from(s,rC)).map(RG)),i):e.slice()},i.rangeRound=function(s){return i.range(s).round(!0)},i.round=function(s){return arguments.length?(n=!!s,i):n},i.clamp=function(s){return arguments.length?(t.clamp(s),i):t.clamp()},i.unknown=function(s){return arguments.length?(r=s,i):r},i.copy=function(){return Dte(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},pc.apply(i,arguments),yp(i)}function Fte(){var t=[],e=[],n=[],r;function i(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o<l;)n[o-1]=ZRe(t,o/l);return s}function s(o){return o==null||isNaN(o=+o)?r:e[rS(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(Zh),i()},s.range=function(o){return arguments.length?(e=Array.from(o),i()):e.slice()},s.unknown=function(o){return arguments.length?(r=o,s):r},s.quantiles=function(){return n.slice()},s.copy=function(){return Fte().domain(t).range(e).unknown(r)},pc.apply(s,arguments)}function Rte(){var t=0,e=1,n=1,r=[.5],i=[0,1],s;function o(c){return c!=null&&c<=c?i[rS(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=(i=Array.from(c)).length-1,l()):i.slice()},o.invertExtent=function(c){var d=i.indexOf(c);return d<0?[NaN,NaN]:d<1?[t,r[0]]:d>=n?[r[n-1],e]:[r[d-1],r[d]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return Rte().domain([t,e]).range(i).unknown(s)},pc.apply(yp(o),arguments)}function Lte(){var t=[.5],e=[0,1],n,r=1;function i(s){return s!=null&&s<=s?e[rS(t,s,0,r)]:n}return i.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},i.unknown=function(s){return arguments.length?(n=s,i):n},i.copy=function(){return Lte().domain(t).range(e).unknown(n)},pc.apply(i,arguments)}const Y2=new Date,Q2=new Date;function ji(t,e,n,r){function i(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return i.floor=s=>(t(s=new Date(+s)),s),i.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),i.round=s=>{const o=i(s),l=i.ceil(s);return s-o<l-s?o:l},i.offset=(s,o)=>(e(s=new Date(+s),o==null?1:Math.floor(o)),s),i.range=(s,o,l)=>{const c=[];if(s=i.ceil(s),l=l==null?1:Math.floor(l),!(s<o)||!(l>0))return c;let d;do c.push(d=new Date(+s)),e(s,l),t(s);while(d<s&&s<o);return c},i.filter=s=>ji(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&&(i.count=(s,o)=>(Y2.setTime(+s),Q2.setTime(+o),t(Y2),t(Q2),Math.floor(n(Y2,Q2))),i.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?i.filter(r?o=>r(o)%s===0:o=>i.count(0,o)%s===0):i)),i}const sC=ji(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);sC.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?ji(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):sC);sC.range;const $u=1e3,Yl=$u*60,Vu=Yl*60,um=Vu*24,WI=um*7,LG=um*30,Z2=um*365,Sf=ji(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*$u)},(t,e)=>(e-t)/$u,t=>t.getUTCSeconds());Sf.range;const KI=ji(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*$u)},(t,e)=>{t.setTime(+t+e*Yl)},(t,e)=>(e-t)/Yl,t=>t.getMinutes());KI.range;const XI=ji(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*Yl)},(t,e)=>(e-t)/Yl,t=>t.getUTCMinutes());XI.range;const YI=ji(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*$u-t.getMinutes()*Yl)},(t,e)=>{t.setTime(+t+e*Vu)},(t,e)=>(e-t)/Vu,t=>t.getHours());YI.range;const QI=ji(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Vu)},(t,e)=>(e-t)/Vu,t=>t.getUTCHours());QI.range;const sS=ji(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Yl)/um,t=>t.getDate()-1);sS.range;const hT=ji(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/um,t=>t.getUTCDate()-1);hT.range;const Ote=ji(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/um,t=>Math.floor(t/um));Ote.range;function kg(t){return ji(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())*Yl)/WI)}const pT=kg(0),oC=kg(1),XLe=kg(2),YLe=kg(3),qx=kg(4),QLe=kg(5),ZLe=kg(6);pT.range;oC.range;XLe.range;YLe.range;qx.range;QLe.range;ZLe.range;function Ng(t){return ji(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)/WI)}const fT=Ng(0),lC=Ng(1),JLe=Ng(2),eOe=Ng(3),$x=Ng(4),tOe=Ng(5),nOe=Ng(6);fT.range;lC.range;JLe.range;eOe.range;$x.range;tOe.range;nOe.range;const ZI=ji(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());ZI.range;const JI=ji(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());JI.range;const mm=ji(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());mm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ji(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)});mm.range;const hm=ji(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());hm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:ji(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)});hm.range;function Ite(t,e,n,r,i,s){const o=[[Sf,1,$u],[Sf,5,5*$u],[Sf,15,15*$u],[Sf,30,30*$u],[s,1,Yl],[s,5,5*Yl],[s,15,15*Yl],[s,30,30*Yl],[i,1,Vu],[i,3,3*Vu],[i,6,6*Vu],[i,12,12*Vu],[r,1,um],[r,2,2*um],[n,1,WI],[e,1,LG],[e,3,3*LG],[t,1,Z2]];function l(d,u,m){const p=u<d;p&&([d,u]=[u,d]);const f=m&&typeof m.range=="function"?m:c(d,u,m),x=f?f.range(d,+u+1):[];return p?x.reverse():x}function c(d,u,m){const p=Math.abs(u-d)/m,f=FI(([,,g])=>g).right(o,p);if(f===o.length)return t.every(zR(d/Z2,u/Z2,m));if(f===0)return sC.every(Math.max(zR(d,u,m),1));const[x,v]=o[p/o[f-1][2]<o[f][2]/p?f-1:f];return x.every(v)}return[l,c]}const[rOe,aOe]=Ite(hm,JI,fT,Ote,QI,XI),[iOe,sOe]=Ite(mm,ZI,pT,sS,YI,KI);function J2(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 eD(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 Fv(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function oOe(t){var e=t.dateTime,n=t.date,r=t.time,i=t.periods,s=t.days,o=t.shortDays,l=t.months,c=t.shortMonths,d=Rv(i),u=Lv(i),m=Rv(s),p=Lv(s),f=Rv(o),x=Lv(o),v=Rv(l),g=Lv(l),b=Rv(c),_=Lv(c),C={a:ee,A:ue,b:le,B:oe,c:null,d:HG,e:HG,f:jOe,g:UOe,G:HOe,H:POe,I:TOe,j:AOe,L:zte,m:MOe,M:EOe,p:W,q:re,Q:VG,s:GG,S:DOe,u:FOe,U:ROe,V:LOe,w:OOe,W:IOe,x:null,X:null,y:zOe,Y:BOe,Z:qOe,"%":$G},P={a:ce,A:xe,b:Ne,B:$,c:null,d:qG,e:qG,f:WOe,g:rIe,G:iIe,H:$Oe,I:VOe,j:GOe,L:Bte,m:KOe,M:XOe,p:Y,q:E,Q:VG,s:GG,S:YOe,u:QOe,U:ZOe,V:JOe,w:eIe,W:tIe,x:null,X:null,y:nIe,Y:aIe,Z:sIe,"%":$G},N={a:D,A:H,b:z,B:X,c:L,d:UG,e:UG,f:_Oe,g:zG,G:IG,H:BG,I:BG,j:yOe,L:SOe,m:xOe,M:vOe,p:k,q:bOe,Q:NOe,s:COe,S:wOe,u:mOe,U:hOe,V:pOe,w:uOe,W:fOe,x:ne,X:ie,y:zG,Y:IG,Z:gOe,"%":kOe};C.x=A(n,C),C.X=A(r,C),C.c=A(e,C),P.x=A(n,P),P.X=A(r,P),P.c=A(e,P);function A(j,O){return function(K){var B=[],he=-1,I=0,V=j.length,Q,G,J;for(K instanceof Date||(K=new Date(+K));++he<V;)j.charCodeAt(he)===37&&(B.push(j.slice(I,he)),(G=OG[Q=j.charAt(++he)])!=null?Q=j.charAt(++he):G=Q==="e"?" ":"0",(J=O[Q])&&(Q=J(K,G)),B.push(Q),I=he+1);return B.push(j.slice(I,he)),B.join("")}}function T(j,O){return function(K){var B=Fv(1900,void 0,1),he=F(B,j,K+="",0),I,V;if(he!=K.length)return null;if("Q"in B)return new Date(B.Q);if("s"in B)return new Date(B.s*1e3+("L"in B?B.L:0));if(O&&!("Z"in B)&&(B.Z=0),"p"in B&&(B.H=B.H%12+B.p*12),B.m===void 0&&(B.m="q"in B?B.q:0),"V"in B){if(B.V<1||B.V>53)return null;"w"in B||(B.w=1),"Z"in B?(I=eD(Fv(B.y,0,1)),V=I.getUTCDay(),I=V>4||V===0?lC.ceil(I):lC(I),I=hT.offset(I,(B.V-1)*7),B.y=I.getUTCFullYear(),B.m=I.getUTCMonth(),B.d=I.getUTCDate()+(B.w+6)%7):(I=J2(Fv(B.y,0,1)),V=I.getDay(),I=V>4||V===0?oC.ceil(I):oC(I),I=sS.offset(I,(B.V-1)*7),B.y=I.getFullYear(),B.m=I.getMonth(),B.d=I.getDate()+(B.w+6)%7)}else("W"in B||"U"in B)&&("w"in B||(B.w="u"in B?B.u%7:"W"in B?1:0),V="Z"in B?eD(Fv(B.y,0,1)).getUTCDay():J2(Fv(B.y,0,1)).getDay(),B.m=0,B.d="W"in B?(B.w+6)%7+B.W*7-(V+5)%7:B.w+B.U*7-(V+6)%7);return"Z"in B?(B.H+=B.Z/100|0,B.M+=B.Z%100,eD(B)):J2(B)}}function F(j,O,K,B){for(var he=0,I=O.length,V=K.length,Q,G;he<I;){if(B>=V)return-1;if(Q=O.charCodeAt(he++),Q===37){if(Q=O.charAt(he++),G=N[Q in OG?O.charAt(he++):Q],!G||(B=G(j,K,B))<0)return-1}else if(Q!=K.charCodeAt(B++))return-1}return B}function k(j,O,K){var B=d.exec(O.slice(K));return B?(j.p=u.get(B[0].toLowerCase()),K+B[0].length):-1}function D(j,O,K){var B=f.exec(O.slice(K));return B?(j.w=x.get(B[0].toLowerCase()),K+B[0].length):-1}function H(j,O,K){var B=m.exec(O.slice(K));return B?(j.w=p.get(B[0].toLowerCase()),K+B[0].length):-1}function z(j,O,K){var B=b.exec(O.slice(K));return B?(j.m=_.get(B[0].toLowerCase()),K+B[0].length):-1}function X(j,O,K){var B=v.exec(O.slice(K));return B?(j.m=g.get(B[0].toLowerCase()),K+B[0].length):-1}function L(j,O,K){return F(j,e,O,K)}function ne(j,O,K){return F(j,n,O,K)}function ie(j,O,K){return F(j,r,O,K)}function ee(j){return o[j.getDay()]}function ue(j){return s[j.getDay()]}function le(j){return c[j.getMonth()]}function oe(j){return l[j.getMonth()]}function W(j){return i[+(j.getHours()>=12)]}function re(j){return 1+~~(j.getMonth()/3)}function ce(j){return o[j.getUTCDay()]}function xe(j){return s[j.getUTCDay()]}function Ne(j){return c[j.getUTCMonth()]}function $(j){return l[j.getUTCMonth()]}function Y(j){return i[+(j.getUTCHours()>=12)]}function E(j){return 1+~~(j.getUTCMonth()/3)}return{format:function(j){var O=A(j+="",C);return O.toString=function(){return j},O},parse:function(j){var O=T(j+="",!1);return O.toString=function(){return j},O},utcFormat:function(j){var O=A(j+="",P);return O.toString=function(){return j},O},utcParse:function(j){var O=T(j+="",!0);return O.toString=function(){return j},O}}}var OG={"-":"",_:" ",0:"0"},Vi=/^\s*\d+/,lOe=/^%/,cOe=/[\\^$*+?|[\]().{}]/g;function jr(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",s=i.length;return r+(s<n?new Array(n-s+1).join(e)+i:i)}function dOe(t){return t.replace(cOe,"\\$&")}function Rv(t){return new RegExp("^(?:"+t.map(dOe).join("|")+")","i")}function Lv(t){return new Map(t.map((e,n)=>[e.toLowerCase(),n]))}function uOe(t,e,n){var r=Vi.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function mOe(t,e,n){var r=Vi.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function hOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function pOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function fOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function IG(t,e,n){var r=Vi.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function zG(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function gOe(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 bOe(t,e,n){var r=Vi.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function xOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function UG(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function yOe(t,e,n){var r=Vi.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function BG(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function vOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function wOe(t,e,n){var r=Vi.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function SOe(t,e,n){var r=Vi.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function _Oe(t,e,n){var r=Vi.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function kOe(t,e,n){var r=lOe.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function NOe(t,e,n){var r=Vi.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function COe(t,e,n){var r=Vi.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function HG(t,e){return jr(t.getDate(),e,2)}function POe(t,e){return jr(t.getHours(),e,2)}function TOe(t,e){return jr(t.getHours()%12||12,e,2)}function AOe(t,e){return jr(1+sS.count(mm(t),t),e,3)}function zte(t,e){return jr(t.getMilliseconds(),e,3)}function jOe(t,e){return zte(t,e)+"000"}function MOe(t,e){return jr(t.getMonth()+1,e,2)}function EOe(t,e){return jr(t.getMinutes(),e,2)}function DOe(t,e){return jr(t.getSeconds(),e,2)}function FOe(t){var e=t.getDay();return e===0?7:e}function ROe(t,e){return jr(pT.count(mm(t)-1,t),e,2)}function Ute(t){var e=t.getDay();return e>=4||e===0?qx(t):qx.ceil(t)}function LOe(t,e){return t=Ute(t),jr(qx.count(mm(t),t)+(mm(t).getDay()===4),e,2)}function OOe(t){return t.getDay()}function IOe(t,e){return jr(oC.count(mm(t)-1,t),e,2)}function zOe(t,e){return jr(t.getFullYear()%100,e,2)}function UOe(t,e){return t=Ute(t),jr(t.getFullYear()%100,e,2)}function BOe(t,e){return jr(t.getFullYear()%1e4,e,4)}function HOe(t,e){var n=t.getDay();return t=n>=4||n===0?qx(t):qx.ceil(t),jr(t.getFullYear()%1e4,e,4)}function qOe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+jr(e/60|0,"0",2)+jr(e%60,"0",2)}function qG(t,e){return jr(t.getUTCDate(),e,2)}function $Oe(t,e){return jr(t.getUTCHours(),e,2)}function VOe(t,e){return jr(t.getUTCHours()%12||12,e,2)}function GOe(t,e){return jr(1+hT.count(hm(t),t),e,3)}function Bte(t,e){return jr(t.getUTCMilliseconds(),e,3)}function WOe(t,e){return Bte(t,e)+"000"}function KOe(t,e){return jr(t.getUTCMonth()+1,e,2)}function XOe(t,e){return jr(t.getUTCMinutes(),e,2)}function YOe(t,e){return jr(t.getUTCSeconds(),e,2)}function QOe(t){var e=t.getUTCDay();return e===0?7:e}function ZOe(t,e){return jr(fT.count(hm(t)-1,t),e,2)}function Hte(t){var e=t.getUTCDay();return e>=4||e===0?$x(t):$x.ceil(t)}function JOe(t,e){return t=Hte(t),jr($x.count(hm(t),t)+(hm(t).getUTCDay()===4),e,2)}function eIe(t){return t.getUTCDay()}function tIe(t,e){return jr(lC.count(hm(t)-1,t),e,2)}function nIe(t,e){return jr(t.getUTCFullYear()%100,e,2)}function rIe(t,e){return t=Hte(t),jr(t.getUTCFullYear()%100,e,2)}function aIe(t,e){return jr(t.getUTCFullYear()%1e4,e,4)}function iIe(t,e){var n=t.getUTCDay();return t=n>=4||n===0?$x(t):$x.ceil(t),jr(t.getUTCFullYear()%1e4,e,4)}function sIe(){return"+0000"}function $G(){return"%"}function VG(t){return+t}function GG(t){return Math.floor(+t/1e3)}var Hb,qte,$te;oIe({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 oIe(t){return Hb=oOe(t),qte=Hb.format,Hb.parse,$te=Hb.utcFormat,Hb.utcParse,Hb}function lIe(t){return new Date(t)}function cIe(t){return t instanceof Date?+t:+new Date(+t)}function e4(t,e,n,r,i,s,o,l,c,d){var u=UI(),m=u.invert,p=u.domain,f=d(".%L"),x=d(":%S"),v=d("%I:%M"),g=d("%I %p"),b=d("%a %d"),_=d("%b %d"),C=d("%B"),P=d("%Y");function N(A){return(c(A)<A?f:l(A)<A?x:o(A)<A?v:s(A)<A?g:r(A)<A?i(A)<A?b:_:n(A)<A?C:P)(A)}return u.invert=function(A){return new Date(m(A))},u.domain=function(A){return arguments.length?p(Array.from(A,cIe)):p().map(lIe)},u.ticks=function(A){var T=p();return t(T[0],T[T.length-1],A??10)},u.tickFormat=function(A,T){return T==null?N:d(T)},u.nice=function(A){var T=p();return(!A||typeof A.range!="function")&&(A=e(T[0],T[T.length-1],A??10)),A?p(jte(T,A)):u},u.copy=function(){return iS(u,e4(t,e,n,r,i,s,o,l,c,d))},u}function dIe(){return pc.apply(e4(iOe,sOe,mm,ZI,pT,sS,YI,KI,Sf,qte).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function uIe(){return pc.apply(e4(rOe,aOe,hm,JI,fT,hT,QI,XI,Sf,$te).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function gT(){var t=0,e=1,n,r,i,s,o=Xs,l=!1,c;function d(m){return m==null||isNaN(m=+m)?c:o(i===0?.5:(m=(s(m)-n)*i,l?Math.max(0,Math.min(1,m)):m))}d.domain=function(m){return arguments.length?([t,e]=m,n=s(t=+t),r=s(e=+e),i=n===r?0:1/(r-n),d):[t,e]},d.clamp=function(m){return arguments.length?(l=!!m,d):l},d.interpolator=function(m){return arguments.length?(o=m,d):o};function u(m){return function(p){var f,x;return arguments.length?([f,x]=p,o=m(f,x),d):[o(0),o(1)]}}return d.range=u(gy),d.rangeRound=u(zI),d.unknown=function(m){return arguments.length?(c=m,d):c},function(m){return s=m,n=m(t),r=m(e),i=n===r?0:1/(r-n),d}}function vp(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function Vte(){var t=yp(gT()(Xs));return t.copy=function(){return vp(t,Vte())},ym.apply(t,arguments)}function Gte(){var t=qI(gT()).domain([1,10]);return t.copy=function(){return vp(t,Gte()).base(t.base())},ym.apply(t,arguments)}function Wte(){var t=$I(gT());return t.copy=function(){return vp(t,Wte()).constant(t.constant())},ym.apply(t,arguments)}function t4(){var t=VI(gT());return t.copy=function(){return vp(t,t4()).exponent(t.exponent())},ym.apply(t,arguments)}function mIe(){return t4.apply(null,arguments).exponent(.5)}function Kte(){var t=[],e=Xs;function n(r){if(r!=null&&!isNaN(r=+r))return e((rS(t,r,1)-1)/(t.length-1))}return n.domain=function(r){if(!arguments.length)return t.slice();t=[];for(let i of r)i!=null&&!isNaN(i=+i)&&t.push(i);return t.sort(Zh),n},n.interpolator=function(r){return arguments.length?(e=r,n):e},n.range=function(){return t.map((r,i)=>e(i/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(i,s)=>QRe(t,s/r))},n.copy=function(){return Kte(e).domain(t)},ym.apply(n,arguments)}function bT(){var t=0,e=.5,n=1,r=1,i,s,o,l,c,d=Xs,u,m=!1,p;function f(v){return isNaN(v=+v)?p:(v=.5+((v=+u(v))-s)*(r*v<r*s?l:c),d(m?Math.max(0,Math.min(1,v)):v))}f.domain=function(v){return arguments.length?([t,e,n]=v,i=u(t=+t),s=u(e=+e),o=u(n=+n),l=i===s?0:.5/(s-i),c=s===o?0:.5/(o-s),r=s<i?-1:1,f):[t,e,n]},f.clamp=function(v){return arguments.length?(m=!!v,f):m},f.interpolator=function(v){return arguments.length?(d=v,f):d};function x(v){return function(g){var b,_,C;return arguments.length?([b,_,C]=g,d=kLe(v,[b,_,C]),f):[d(0),d(.5),d(1)]}}return f.range=x(gy),f.rangeRound=x(zI),f.unknown=function(v){return arguments.length?(p=v,f):p},function(v){return u=v,i=v(t),s=v(e),o=v(n),l=i===s?0:.5/(s-i),c=s===o?0:.5/(o-s),r=s<i?-1:1,f}}function Xte(){var t=yp(bT()(Xs));return t.copy=function(){return vp(t,Xte())},ym.apply(t,arguments)}function Yte(){var t=qI(bT()).domain([.1,1,10]);return t.copy=function(){return vp(t,Yte()).base(t.base())},ym.apply(t,arguments)}function Qte(){var t=$I(bT());return t.copy=function(){return vp(t,Qte()).constant(t.constant())},ym.apply(t,arguments)}function n4(){var t=VI(bT());return t.copy=function(){return vp(t,n4()).exponent(t.exponent())},ym.apply(t,arguments)}function hIe(){return n4.apply(null,arguments).exponent(.5)}const Jv=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:LI,scaleDiverging:Xte,scaleDivergingLog:Yte,scaleDivergingPow:n4,scaleDivergingSqrt:hIe,scaleDivergingSymlog:Qte,scaleIdentity:Ate,scaleImplicit:UR,scaleLinear:Tte,scaleLog:Mte,scaleOrdinal:RI,scalePoint:eLe,scalePow:GI,scaleQuantile:Fte,scaleQuantize:Rte,scaleRadial:Dte,scaleSequential:Vte,scaleSequentialLog:Gte,scaleSequentialPow:t4,scaleSequentialQuantile:Kte,scaleSequentialSqrt:mIe,scaleSequentialSymlog:Wte,scaleSqrt:WLe,scaleSymlog:Ete,scaleThreshold:Lte,scaleTime:dIe,scaleUtc:uIe,tickFormat:Pte},Symbol.toStringTag,{value:"Module"}));var vm=t=>t.chartData,xT=yt([vm],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),r4=(t,e,n,r)=>r?xT(t):vm(t),Zte=(t,e,n)=>n?xT(t):vm(t);function pm(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(Wn(e)&&Wn(n))return!0}return!1}function WG(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function Jte(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,i,s;if(Wn(n))i=n;else if(typeof n=="function")return;if(Wn(r))s=r;else if(typeof r=="function")return;var o=[i,s];if(pm(o))return o}}function pIe(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(pm(r))return WG(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[i,s]=t,o,l;if(i==="auto")e!=null&&(o=Math.min(...e));else if(an(i))o=i;else if(typeof i=="function")try{e!=null&&(o=i(e?.[0]))}catch{}else if(typeof i=="string"&&r7.test(i)){var c=r7.exec(i);if(c==null||c[1]==null||e==null)o=void 0;else{var d=+c[1];o=e[0]-d}}else o=e?.[0];if(s==="auto")e!=null&&(l=Math.max(...e));else if(an(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&a7.test(s)){var u=a7.exec(s);if(u==null||u[1]==null||e==null)l=void 0;else{var m=+u[1];l=e[1]+m}}else l=e?.[1];var p=[o,l];if(pm(p))return e==null?p:WG(p,e,n)}}}var by=1e9,fIe={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},i4,_a=!0,dc="[DecimalError] ",Of=dc+"Invalid argument: ",a4=dc+"Exponent out of range: ",xy=Math.floor,uf=Math.pow,gIe=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,el,Ii=1e7,xa=7,ene=9007199254740991,cC=xy(ene/xa),pn={};pn.absoluteValue=pn.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};pn.comparedTo=pn.cmp=function(t){var e,n,r,i,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,i=t.d.length,e=0,n=r<i?r:i;e<n;++e)if(s.d[e]!==t.d[e])return s.d[e]>t.d[e]^s.s<0?1:-1;return r===i?0:r>i^s.s<0?1:-1};pn.decimalPlaces=pn.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*xa;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};pn.dividedBy=pn.div=function(t){return Zu(this,new this.constructor(t))};pn.dividedToIntegerBy=pn.idiv=function(t){var e=this,n=e.constructor;return ra(Zu(e,new n(t),0,1),n.precision)};pn.equals=pn.eq=function(t){return!this.cmp(t)};pn.exponent=function(){return gi(this)};pn.greaterThan=pn.gt=function(t){return this.cmp(t)>0};pn.greaterThanOrEqualTo=pn.gte=function(t){return this.cmp(t)>=0};pn.isInteger=pn.isint=function(){return this.e>this.d.length-2};pn.isNegative=pn.isneg=function(){return this.s<0};pn.isPositive=pn.ispos=function(){return this.s>0};pn.isZero=function(){return this.s===0};pn.lessThan=pn.lt=function(t){return this.cmp(t)<0};pn.lessThanOrEqualTo=pn.lte=function(t){return this.cmp(t)<1};pn.logarithm=pn.log=function(t){var e,n=this,r=n.constructor,i=r.precision,s=i+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(el))throw Error(dc+"NaN");if(n.s<1)throw Error(dc+(n.s?"NaN":"-Infinity"));return n.eq(el)?new r(0):(_a=!1,e=Zu(mw(n,s),mw(t,s),s),_a=!0,ra(e,i))};pn.minus=pn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?rne(e,t):tne(e,(t.s=-t.s,t))};pn.modulo=pn.mod=function(t){var e,n=this,r=n.constructor,i=r.precision;if(t=new r(t),!t.s)throw Error(dc+"NaN");return n.s?(_a=!1,e=Zu(n,t,0,1).times(t),_a=!0,n.minus(e)):ra(new r(n),i)};pn.naturalExponential=pn.exp=function(){return nne(this)};pn.naturalLogarithm=pn.ln=function(){return mw(this)};pn.negated=pn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};pn.plus=pn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?tne(e,t):rne(e,(t.s=-t.s,t))};pn.precision=pn.sd=function(t){var e,n,r,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Of+t);if(e=gi(i)+1,r=i.d.length-1,n=r*xa+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};pn.squareRoot=pn.sqrt=function(){var t,e,n,r,i,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(dc+"NaN")}for(t=gi(l),_a=!1,i=Math.sqrt(+l),i==0||i==1/0?(e=kd(l.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=xy((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(i.toString()),n=c.precision,i=o=n+3;;)if(s=r,r=s.plus(Zu(l,s,o+2)).times(.5),kd(s.d).slice(0,o)===(e=kd(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),i==o&&e=="4999"){if(ra(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return _a=!0,ra(r,n)};pn.times=pn.mul=function(t){var e,n,r,i,s,o,l,c,d,u=this,m=u.constructor,p=u.d,f=(t=new m(t)).d;if(!u.s||!t.s)return new m(0);for(t.s*=u.s,n=u.e+t.e,c=p.length,d=f.length,c<d&&(s=p,p=f,f=s,o=c,c=d,d=o),s=[],o=c+d,r=o;r--;)s.push(0);for(r=d;--r>=0;){for(e=0,i=c+r;i>r;)l=s[i]+f[r]*p[i-r-1]+e,s[i--]=l%Ii|0,e=l/Ii|0;s[i]=(s[i]+e)%Ii|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,_a?ra(t,m.precision):t};pn.toDecimalPlaces=pn.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(Fd(t,0,by),e===void 0?e=r.rounding:Fd(e,0,8),ra(n,t+gi(n)+1,e))};pn.toExponential=function(t,e){var n,r=this,i=r.constructor;return t===void 0?n=ug(r,!0):(Fd(t,0,by),e===void 0?e=i.rounding:Fd(e,0,8),r=ra(new i(r),t+1,e),n=ug(r,!0,t+1)),n};pn.toFixed=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?ug(i):(Fd(t,0,by),e===void 0?e=s.rounding:Fd(e,0,8),r=ra(new s(i),t+gi(i)+1,e),n=ug(r.abs(),!1,t+gi(r)+1),i.isneg()&&!i.isZero()?"-"+n:n)};pn.toInteger=pn.toint=function(){var t=this,e=t.constructor;return ra(new e(t),gi(t)+1,e.rounding)};pn.toNumber=function(){return+this};pn.toPower=pn.pow=function(t){var e,n,r,i,s,o,l=this,c=l.constructor,d=12,u=+(t=new c(t));if(!t.s)return new c(el);if(l=new c(l),!l.s){if(t.s<1)throw Error(dc+"Infinity");return l}if(l.eq(el))return l;if(r=c.precision,t.eq(el))return ra(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=u<0?-u:u)<=ene){for(i=new c(el),e=Math.ceil(r/xa+4),_a=!1;n%2&&(i=i.times(l),XG(i.d,e)),n=xy(n/2),n!==0;)l=l.times(l),XG(l.d,e);return _a=!0,t.s<0?new c(el).div(i):ra(i,r)}}else if(s<0)throw Error(dc+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,_a=!1,i=t.times(mw(l,r+d)),_a=!0,i=nne(i),i.s=s,i};pn.toPrecision=function(t,e){var n,r,i=this,s=i.constructor;return t===void 0?(n=gi(i),r=ug(i,n<=s.toExpNeg||n>=s.toExpPos)):(Fd(t,1,by),e===void 0?e=s.rounding:Fd(e,0,8),i=ra(new s(i),t,e),n=gi(i),r=ug(i,t<=n||n<=s.toExpNeg,t)),r};pn.toSignificantDigits=pn.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(Fd(t,1,by),e===void 0?e=r.rounding:Fd(e,0,8)),ra(new r(n),t,e)};pn.toString=pn.valueOf=pn.val=pn.toJSON=pn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=gi(t),n=t.constructor;return ug(t,e<=n.toExpNeg||e>=n.toExpPos)};function tne(t,e){var n,r,i,s,o,l,c,d,u=t.constructor,m=u.precision;if(!t.s||!e.s)return e.s||(e=new u(t)),_a?ra(e,m):e;if(c=t.d,d=e.d,o=t.e,i=e.e,c=c.slice(),s=o-i,s){for(s<0?(r=c,s=-s,l=d.length):(r=d,i=o,l=c.length),o=Math.ceil(m/xa),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=d.length,l-s<0&&(s=l,r=d,d=c,c=r),n=0;s;)n=(c[--s]=c[s]+d[s]+n)/Ii|0,c[s]%=Ii;for(n&&(c.unshift(n),++i),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=i,_a?ra(e,m):e}function Fd(t,e,n){if(t!==~~t||t<e||t>n)throw Error(Of+t)}function kd(t){var e,n,r,i=t.length-1,s="",o=t[0];if(i>0){for(s+=o,e=1;e<i;e++)r=t[e]+"",n=xa-r.length,n&&(s+=bh(n)),s+=r;o=t[e],r=o+"",n=xa-r.length,n&&(s+=bh(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}var Zu=(function(){function t(r,i){var s,o=0,l=r.length;for(r=r.slice();l--;)s=r[l]*i+o,r[l]=s%Ii|0,o=s/Ii|0;return o&&r.unshift(o),r}function e(r,i,s,o){var l,c;if(s!=o)c=s>o?1:-1;else for(l=c=0;l<s;l++)if(r[l]!=i[l]){c=r[l]>i[l]?1:-1;break}return c}function n(r,i,s){for(var o=0;s--;)r[s]-=o,o=r[s]<i[s]?1:0,r[s]=o*Ii+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o){var l,c,d,u,m,p,f,x,v,g,b,_,C,P,N,A,T,F,k=r.constructor,D=r.s==i.s?1:-1,H=r.d,z=i.d;if(!r.s)return new k(r);if(!i.s)throw Error(dc+"Division by zero");for(c=r.e-i.e,T=z.length,N=H.length,f=new k(D),x=f.d=[],d=0;z[d]==(H[d]||0);)++d;if(z[d]>(H[d]||0)&&--c,s==null?_=s=k.precision:o?_=s+(gi(r)-gi(i))+1:_=s,_<0)return new k(0);if(_=_/xa+2|0,d=0,T==1)for(u=0,z=z[0],_++;(d<N||u)&&_--;d++)C=u*Ii+(H[d]||0),x[d]=C/z|0,u=C%z|0;else{for(u=Ii/(z[0]+1)|0,u>1&&(z=t(z,u),H=t(H,u),T=z.length,N=H.length),P=T,v=H.slice(0,T),g=v.length;g<T;)v[g++]=0;F=z.slice(),F.unshift(0),A=z[0],z[1]>=Ii/2&&++A;do u=0,l=e(z,v,T,g),l<0?(b=v[0],T!=g&&(b=b*Ii+(v[1]||0)),u=b/A|0,u>1?(u>=Ii&&(u=Ii-1),m=t(z,u),p=m.length,g=v.length,l=e(m,v,p,g),l==1&&(u--,n(m,T<p?F:z,p))):(u==0&&(l=u=1),m=z.slice()),p=m.length,p<g&&m.unshift(0),n(v,m,g),l==-1&&(g=v.length,l=e(z,v,T,g),l<1&&(u++,n(v,T<g?F:z,g))),g=v.length):l===0&&(u++,v=[0]),x[d++]=u,l&&v[0]?v[g++]=H[P]||0:(v=[H[P]],g=1);while((P++<N||v[0]!==void 0)&&_--)}return x[0]||x.shift(),f.e=c,ra(f,o?s+gi(f)+1:s)}})();function nne(t,e){var n,r,i,s,o,l,c=0,d=0,u=t.constructor,m=u.precision;if(gi(t)>16)throw Error(a4+gi(t));if(!t.s)return new u(el);for(_a=!1,l=m,o=new u(.03125);t.abs().gte(.1);)t=t.times(o),d+=5;for(r=Math.log(uf(2,d))/Math.LN10*2+5|0,l+=r,n=i=s=new u(el),u.precision=l;;){if(i=ra(i.times(t),l),n=n.times(++c),o=s.plus(Zu(i,n,l)),kd(o.d).slice(0,l)===kd(s.d).slice(0,l)){for(;d--;)s=ra(s.times(s),l);return u.precision=m,e==null?(_a=!0,ra(s,m)):s}s=o}}function gi(t){for(var e=t.e*xa,n=t.d[0];n>=10;n/=10)e++;return e}function tD(t,e,n){if(e>t.LN10.sd())throw _a=!0,n&&(t.precision=n),Error(dc+"LN10 precision limit exceeded");return ra(new t(t.LN10),e)}function bh(t){for(var e="";t--;)e+="0";return e}function mw(t,e){var n,r,i,s,o,l,c,d,u,m=1,p=10,f=t,x=f.d,v=f.constructor,g=v.precision;if(f.s<1)throw Error(dc+(f.s?"NaN":"-Infinity"));if(f.eq(el))return new v(0);if(e==null?(_a=!1,d=g):d=e,f.eq(10))return e==null&&(_a=!0),tD(v,d);if(d+=p,v.precision=d,n=kd(x),r=n.charAt(0),s=gi(f),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(t),n=kd(f.d),r=n.charAt(0),m++;s=gi(f),r>1?(f=new v("0."+n),s++):f=new v(r+"."+n.slice(1))}else return c=tD(v,d+2,g).times(s+""),f=mw(new v(r+"."+n.slice(1)),d-p).plus(c),v.precision=g,e==null?(_a=!0,ra(f,g)):f;for(l=o=f=Zu(f.minus(el),f.plus(el),d),u=ra(f.times(f),d),i=3;;){if(o=ra(o.times(u),d),c=l.plus(Zu(o,new v(i),d)),kd(c.d).slice(0,d)===kd(l.d).slice(0,d))return l=l.times(2),s!==0&&(l=l.plus(tD(v,d+2,g).times(s+""))),l=Zu(l,new v(m),d),v.precision=g,e==null?(_a=!0,ra(l,g)):l;l=c,i+=2}}function KG(t,e){var n,r,i;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(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(r,i),e){if(i-=r,n=n-r-1,t.e=xy(n/xa),t.d=[],r=(n+1)%xa,n<0&&(r+=xa),r<i){for(r&&t.d.push(+e.slice(0,r)),i-=xa;r<i;)t.d.push(+e.slice(r,r+=xa));e=e.slice(r),r=xa-e.length}else r-=i;for(;r--;)e+="0";if(t.d.push(+e),_a&&(t.e>cC||t.e<-cC))throw Error(a4+n)}else t.s=0,t.e=0,t.d=[0];return t}function ra(t,e,n){var r,i,s,o,l,c,d,u,m=t.d;for(o=1,s=m[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=xa,i=e,d=m[u=0];else{if(u=Math.ceil((r+1)/xa),s=m.length,u>=s)return t;for(d=s=m[u],o=1;s>=10;s/=10)o++;r%=xa,i=r-xa+o}if(n!==void 0&&(s=uf(10,o-i-1),l=d/s%10|0,c=e<0||m[u+1]!==void 0||d%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?i>0?d/uf(10,o-i):0:m[u-1])%10&1||n==(t.s<0?8:7))),e<1||!m[0])return c?(s=gi(t),m.length=1,e=e-s-1,m[0]=uf(10,(xa-e%xa)%xa),t.e=xy(-e/xa)||0):(m.length=1,m[0]=t.e=t.s=0),t;if(r==0?(m.length=u,s=1,u--):(m.length=u+1,s=uf(10,xa-r),m[u]=i>0?(d/uf(10,o-i)%uf(10,i)|0)*s:0),c)for(;;)if(u==0){(m[0]+=s)==Ii&&(m[0]=1,++t.e);break}else{if(m[u]+=s,m[u]!=Ii)break;m[u--]=0,s=1}for(r=m.length;m[--r]===0;)m.pop();if(_a&&(t.e>cC||t.e<-cC))throw Error(a4+gi(t));return t}function rne(t,e){var n,r,i,s,o,l,c,d,u,m,p=t.constructor,f=p.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new p(t),_a?ra(e,f):e;if(c=t.d,m=e.d,r=e.e,d=t.e,c=c.slice(),o=d-r,o){for(u=o<0,u?(n=c,o=-o,l=m.length):(n=m,r=d,l=c.length),i=Math.max(Math.ceil(f/xa),l)+2,o>i&&(o=i,n.length=1),n.reverse(),i=o;i--;)n.push(0);n.reverse()}else{for(i=c.length,l=m.length,u=i<l,u&&(l=i),i=0;i<l;i++)if(c[i]!=m[i]){u=c[i]<m[i];break}o=0}for(u&&(n=c,c=m,m=n,e.s=-e.s),l=c.length,i=m.length-l;i>0;--i)c[l++]=0;for(i=m.length;i>o;){if(c[--i]<m[i]){for(s=i;s&&c[--s]===0;)c[s]=Ii-1;--c[s],c[i]+=Ii}c[i]-=m[i]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--r;return c[0]?(e.d=c,e.e=r,_a?ra(e,f):e):new p(0)}function ug(t,e,n){var r,i=gi(t),s=kd(t.d),o=s.length;return e?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+bh(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(i<0?"e":"e+")+i):i<0?(s="0."+bh(-i-1)+s,n&&(r=n-o)>0&&(s+=bh(r))):i>=o?(s+=bh(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+bh(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=bh(r))),t.s<0?"-"+s:s}function XG(t,e){if(t.length>e)return t.length=e,!0}function ane(t){var e,n,r;function i(s){var o=this;if(!(o instanceof i))return new i(s);if(o.constructor=i,s instanceof i){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(Of+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 KG(o,s.toString())}else if(typeof s!="string")throw Error(Of+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,gIe.test(s))KG(o,s);else throw Error(Of+s)}if(i.prototype=pn,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=ane,i.config=i.set=bIe,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 i.config(t),i}function bIe(t){if(!t||typeof t!="object")throw Error(dc+"Object expected");var e,n,r,i=["precision",1,by,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e<i.length;e+=3)if((r=t[n=i[e]])!==void 0)if(xy(r)===r&&r>=i[e+1]&&r<=i[e+2])this[n]=r;else throw Error(Of+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(Of+n+": "+r);return this}var i4=ane(fIe);el=new i4(1);const zr=i4;function ine(t){var e;return t===0?e=1:e=Math.floor(new zr(t).abs().log(10).toNumber())+1,e}function sne(t,e,n){for(var r=new zr(t),i=0,s=[];r.lt(e)&&i<1e5;)s.push(r.toNumber()),r=r.add(n),i++;return s}var one=t=>{var[e,n]=t,[r,i]=[e,n];return e>n&&([r,i]=[n,e]),[r,i]},lne=(t,e,n)=>{if(t.lte(0))return new zr(0);var r=ine(t.toNumber()),i=new zr(10).pow(r),s=t.div(i),o=r!==1?.05:.1,l=new zr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(i);return e?new zr(c.toNumber()):new zr(Math.ceil(c.toNumber()))},xIe=(t,e,n)=>{var r=new zr(1),i=new zr(t);if(!i.isint()&&n){var s=Math.abs(t);s<1?(r=new zr(10).pow(ine(t)-1),i=new zr(Math.floor(i.div(r).toNumber())).mul(r)):s>1&&(i=new zr(Math.floor(t)))}else t===0?i=new zr(Math.floor((e-1)/2)):n||(i=new zr(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c<e;c++)l.push(i.add(new zr(c-o).mul(r)).toNumber());return l},cne=function(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new zr(0),tickMin:new zr(0),tickMax:new zr(0)};var o=lne(new zr(n).sub(e).div(r-1),i,s),l;e<=0&&n>=0?l=new zr(0):(l=new zr(e).add(n).div(2),l=l.sub(new zr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),d=Math.ceil(new zr(n).sub(l).div(o).toNumber()),u=c+d+1;return u>r?cne(e,n,r,i,s+1):(u<r&&(d=n>0?d+(r-u):d,c=n>0?c:c+(r-u)),{step:o,tickMin:l.sub(new zr(c).mul(o)),tickMax:l.add(new zr(d).mul(o))})},yIe=function(e){var[n,r]=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),[l,c]=one([n,r]);if(l===-1/0||c===1/0){var d=c===1/0?[l,...Array(i-1).fill(1/0)]:[...Array(i-1).fill(-1/0),c];return n>r?d.reverse():d}if(l===c)return xIe(l,i,s);var{step:u,tickMin:m,tickMax:p}=cne(l,c,o,s,0),f=sne(m,p.add(new zr(.1).mul(u)),u);return n>r?f.reverse():f},vIe=function(e,n){var[r,i]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=one([r,i]);if(o===-1/0||l===1/0)return[r,i];if(o===l)return[o];var c=Math.max(n,2),d=lne(new zr(l).sub(o).div(c-1),s,0),u=[...sne(new zr(o),new zr(l),d),l];return s===!1&&(u=u.map(m=>Math.round(m))),r>i?u.reverse():u},dne=t=>t.rootProps.maxBarSize,wIe=t=>t.rootProps.barGap,une=t=>t.rootProps.barCategoryGap,SIe=t=>t.rootProps.barSize,oS=t=>t.rootProps.stackOffset,mne=t=>t.rootProps.reverseStackOrder,s4=t=>t.options.chartName,o4=t=>t.rootProps.syncId,hne=t=>t.rootProps.syncMethod,l4=t=>t.options.eventEmitter,_Ie=t=>t.rootProps.baseValue,Ga={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},nf={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},ld={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},yT=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function vT(t,e,n){if(n!=="auto")return n;if(t!=null)return Wc(t,e)?"category":"number"}function YG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function dC(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){kIe(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 kIe(t,e,n){return(e=NIe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function NIe(t){var e=CIe(t,"string");return typeof e=="symbol"?e:e+""}function CIe(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 QG={allowDataOverflow:nf.allowDataOverflow,allowDecimals:nf.allowDecimals,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:nf.angleAxisId,includeHidden:!1,name:void 0,reversed:nf.reversed,scale:nf.scale,tick:nf.tick,tickCount:void 0,ticks:void 0,type:nf.type,unit:void 0},ZG={allowDataOverflow:ld.allowDataOverflow,allowDecimals:ld.allowDecimals,allowDuplicatedCategory:ld.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:ld.radiusAxisId,includeHidden:ld.includeHidden,name:void 0,reversed:ld.reversed,scale:ld.scale,tick:ld.tick,tickCount:ld.tickCount,ticks:void 0,type:ld.type,unit:void 0},PIe=(t,e)=>{if(e!=null)return t.polarAxis.angleAxis[e]},c4=yt([PIe,Yee],(t,e)=>{var n;if(t!=null)return t;var r=(n=vT(e,"angleAxis",QG.type))!==null&&n!==void 0?n:"category";return dC(dC({},QG),{},{type:r})}),TIe=(t,e)=>t.polarAxis.radiusAxis[e],d4=yt([TIe,Yee],(t,e)=>{var n;if(t!=null)return t;var r=(n=vT(e,"radiusAxis",ZG.type))!==null&&n!==void 0?n:"category";return dC(dC({},ZG),{},{type:r})}),wT=t=>t.polarOptions,u4=yt([bm,xm,Ti],pte),pne=yt([wT,u4],(t,e)=>{if(t!=null)return Ds(t.innerRadius,e,0)}),fne=yt([wT,u4],(t,e)=>{if(t!=null)return Ds(t.outerRadius,e,e*.8)}),AIe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},gne=yt([wT],AIe);yt([c4,gne],yT);var bne=yt([u4,pne,fne],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});yt([d4,bne],yT);var xne=yt([Sr,wT,pne,fne,bm,xm],(t,e,n,r,i,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:d}=e;return{cx:Ds(o,i,i/2),cy:Ds(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:d,clockWise:!1}}}),Fa=(t,e)=>e,lS=(t,e,n)=>n;function ST(t){return t?.id}function yne(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:i,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,d=(c=l.data)!==null&&c!==void 0?c:r;if(!(d==null||d.length===0)){var u=ST(l);d.forEach((m,p)=>{var f=s==null||i?p:String(Fr(m,s,null)),x=Fr(m,l.dataKey,0),v;o.has(f)?v=o.get(f):v={},Object.assign(v,{[u]:x}),o.set(f,v)})}}),Array.from(o.values())}function _T(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var kT=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function NT(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function jIe(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 Gi=t=>{var e=Sr(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},yy=t=>t.tooltip.settings.axisId;function MIe(t){if(t in Jv)return Jv[t]();var e="scale".concat(Kw(t));if(e in Jv)return Jv[e]()}function JG(t){var e=t.ticks,n=t.bandwidth,r=t.range(),i=[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})(()=>i),rangeMin:()=>i[0],rangeMax:()=>i[1],isInRange(s){var o=i[0],l=i[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 e9(t,e,n){if(typeof t=="function")return JG(t.copy().domain(e).range(n));if(t!=null){var r=MIe(t);if(r!=null)return r.domain(e).range(n),JG(r)}}var vne=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!pm(e)){for(var n,r,i=0;i<e.length;i++){var s=e[i];Wn(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 t9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function uC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?t9(Object(n),!0).forEach(function(r){EIe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):t9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function EIe(t,e,n){return(e=DIe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function DIe(t){var e=FIe(t,"string");return typeof e=="symbol"?e:e+""}function FIe(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 $R=[0,"auto"],Li={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},wne=(t,e)=>t.cartesianAxis.xAxis[e],Bd=(t,e)=>{var n=wne(t,e);return n??Li},Oi={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:$R,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:Zw},Sne=(t,e)=>t.cartesianAxis.yAxis[e],Hd=(t,e)=>{var n=Sne(t,e);return n??Oi},RIe={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:""},m4=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??RIe},Ya=(t,e,n)=>{switch(e){case"xAxis":return Bd(t,n);case"yAxis":return Hd(t,n);case"zAxis":return m4(t,n);case"angleAxis":return c4(t,n);case"radiusAxis":return d4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},LIe=(t,e,n)=>{switch(e){case"xAxis":return Bd(t,n);case"yAxis":return Hd(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},vy=(t,e,n)=>{switch(e){case"xAxis":return Bd(t,n);case"yAxis":return Hd(t,n);case"angleAxis":return c4(t,n);case"radiusAxis":return d4(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},_ne=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function h4(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 cS=t=>t.graphicalItems.cartesianItems,OIe=yt([Fa,lS],h4),p4=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),dS=yt([cS,Ya,OIe],p4,{memoizeOptions:{resultEqualityCheck:NT}}),kne=yt([dS],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(_T)),Nne=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),IIe=yt([dS],Nne),f4=t=>t.map(e=>e.data).filter(Boolean).flat(1),zIe=yt([dS],f4,{memoizeOptions:{resultEqualityCheck:NT}}),g4=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:i}=e;return t.length>0?t:n.slice(r,i+1)},b4=yt([zIe,r4],g4),x4=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:Fr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(i=>({value:Fr(i,r)}))):t.map(r=>({value:r})),CT=yt([b4,Ya,dS],x4);function Cne(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function Ok(t){if(lc(t)||t instanceof Date){var e=Number(t);if(Wn(e))return e}}function n9(t){if(Array.isArray(t)){var e=[Ok(t[0]),Ok(t[1])];return pm(e)?e:void 0}var n=Ok(t);if(n!=null)return[n,n]}function fm(t){return t.map(Ok).filter(Po)}function UIe(t,e,n){return!n||typeof e!="number"||Bc(e)?[]:n.length?fm(n.flatMap(r=>{var i=Fr(t,r.dataKey),s,o;if(Array.isArray(i)?[s,o]=i:s=o=i,!(!Wn(s)||!Wn(o)))return[e-s,e+o]})):[]}var Mi=t=>{var e=Gi(t),n=yy(t);return vy(t,e,n)},uS=yt([Mi],t=>t?.dataKey),BIe=yt([kne,r4,Mi],yne),Pne=(t,e,n,r)=>{var i={},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},i);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,d=r?[...c].reverse():c,u=d.map(ST);return[l,{stackedData:l3e(t,u,n),graphicalItems:d}]}))},mC=yt([BIe,kne,oS,mne],Pne),Tne=(t,e,n,r)=>{var{dataStartIndex:i,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=m3e(t,i,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},HIe=yt([Ya],t=>t.allowDataOverflow),y4=t=>{var e;if(t==null||!("domain"in t))return $R;if(t.domain!=null)return t.domain;if("ticks"in t&&t.ticks!=null){if(t.type==="number"){var n=fm(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:$R},v4=yt([Ya],y4),w4=yt([v4,HIe],Jte),qIe=yt([mC,vm,Fa,w4],Tne,{memoizeOptions:{resultEqualityCheck:kT}}),PT=t=>t.errorBars,$Ie=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>Cne(n,r)),hC=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];var i=n.filter(Boolean);if(i.length!==0){var s=i.flat(),o=Math.min(...s),l=Math.max(...s);return[o,l]}},S4=(t,e,n,r,i)=>{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var d,u,m=(d=r[c.id])===null||d===void 0?void 0:d.filter(b=>Cne(i,b)),p=Fr(l,(u=e.dataKey)!==null&&u!==void 0?u:c.dataKey),f=UIe(l,p,m);if(f.length>=2){var x=Math.min(...f),v=Math.max(...f);(s==null||x<s)&&(s=x),(o==null||v>o)&&(o=v)}var g=n9(p);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=n9(Fr(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]))}),Wn(s)&&Wn(o))return[s,o]},VIe=yt([b4,Ya,IIe,PT,Fa],S4,{memoizeOptions:{resultEqualityCheck:kT}});function GIe(t){var{value:e}=t;if(lc(e)||e instanceof Date)return e}var WIe=(t,e,n)=>{var r=t.map(GIe).filter(i=>i!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&VJ(r))?xte(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},Ane=t=>t.referenceElements.dots,wy=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),KIe=yt([Ane,Fa,lS],wy),jne=t=>t.referenceElements.areas,XIe=yt([jne,Fa,lS],wy),Mne=t=>t.referenceElements.lines,YIe=yt([Mne,Fa,lS],wy),Ene=(t,e)=>{if(t!=null){var n=fm(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},QIe=yt(KIe,Fa,Ene),Dne=(t,e)=>{if(t!=null){var n=fm(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)]}},ZIe=yt([XIe,Fa],Dne);function JIe(t){var e;if(t.x!=null)return fm([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:fm(n)}function e4e(t){var e;if(t.y!=null)return fm([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:fm(n)}var Fne=(t,e)=>{if(t!=null){var n=t.flatMap(r=>e==="xAxis"?JIe(r):e4e(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},t4e=yt([YIe,Fa],Fne),n4e=yt(QIe,t4e,ZIe,(t,e,n)=>hC(t,n,e)),_4=(t,e,n,r,i,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",d=c?hC(r,s,i):hC(s,i);return pIe(e,d,t.allowDataOverflow)},r4e=yt([Ya,v4,w4,qIe,VIe,n4e,Sr,Fa],_4,{memoizeOptions:{resultEqualityCheck:kT}}),a4e=[0,1],k4=(t,e,n,r,i,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,d=Wc(e,s);if(d&&l==null){var u;return xte(0,(u=n?.length)!==null&&u!==void 0?u:0)}return c==="category"?WIe(r,t,d):i==="expand"?a4e:o}},N4=yt([Ya,Sr,b4,CT,oS,Fa,r4e],k4);function i4e(t){return t in Jv}var Rne=(t,e,n)=>{if(t!=null){var{scale:r,type:i}=t;if(r==="auto")return i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!e)?"point":i==="category"?"band":"linear";if(typeof r=="string"){var s="scale".concat(Kw(r));return i4e(s)?s:"point"}}},wp=yt([Ya,_ne,s4],Rne);function C4(t,e,n,r){if(!(n==null||r==null))return typeof t.scale=="function"?e9(t.scale,n,r):e9(e,n,r)}var P4=(t,e,n)=>{var r=y4(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&pm(t))return yIe(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&pm(t))return vIe(t,e.tickCount,e.allowDecimals)}},T4=yt([N4,vy,wp],P4),A4=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&pm(e)&&Array.isArray(n)&&n.length>0){var i,s,o=e[0],l=(i=n[0])!==null&&i!==void 0?i:0,c=e[1],d=(s=n[n.length-1])!==null&&s!==void 0?s:0;return[Math.min(o,l),Math.max(c,d)]}return e},s4e=yt([Ya,N4,T4,Fa],A4),o4e=yt(CT,Ya,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(fm(t.map(m=>m.value))).sort((m,p)=>m-p),i=r[0],s=r[r.length-1];if(i==null||s==null)return 1/0;var o=s-i;if(o===0)return 1/0;for(var l=0;l<r.length-1;l++){var c=r[l],d=r[l+1];if(!(c==null||d==null)){var u=d-c;n=Math.min(n,u)}}return n/o}}),Lne=yt(o4e,Sr,une,Ti,(t,e,n,r,i)=>i,(t,e,n,r,i)=>{if(!Wn(t))return 0;var s=e==="vertical"?r.height:r.width;if(i==="gap")return t*s/2;if(i==="no-gap"){var o=Ds(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),l4e=(t,e,n)=>{var r=Bd(t,e);return r==null||typeof r.padding!="string"?0:Lne(t,"xAxis",e,n,r.padding)},c4e=(t,e,n)=>{var r=Hd(t,e);return r==null||typeof r.padding!="string"?0:Lne(t,"yAxis",e,n,r.padding)},d4e=yt(Bd,l4e,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:i}=t;return typeof i=="string"?{left:e,right:e}:{left:((n=i.left)!==null&&n!==void 0?n:0)+e,right:((r=i.right)!==null&&r!==void 0?r:0)+e}}),u4e=yt(Hd,c4e,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:i}=t;return typeof i=="string"?{top:e,bottom:e}:{top:((n=i.top)!==null&&n!==void 0?n:0)+e,bottom:((r=i.bottom)!==null&&r!==void 0?r:0)+e}}),m4e=yt([Ti,d4e,lT,oT,(t,e,n)=>n],(t,e,n,r,i)=>{var{padding:s}=r;return i?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),h4e=yt([Ti,Sr,u4e,lT,oT,(t,e,n)=>n],(t,e,n,r,i,s)=>{var{padding:o}=i;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]}),mS=(t,e,n,r)=>{var i;switch(e){case"xAxis":return m4e(t,n,r);case"yAxis":return h4e(t,n,r);case"zAxis":return(i=m4(t,n))===null||i===void 0?void 0:i.range;case"angleAxis":return gne(t);case"radiusAxis":return bne(t,n);default:return}},One=yt([Ya,mS],yT),p4e=yt([wp,s4e],vne),Vx=yt([Ya,wp,p4e,One],C4);yt([dS,PT,Fa],$Ie);function Ine(t,e){return t.id<e.id?-1:t.id>e.id?1:0}var TT=(t,e)=>e,AT=(t,e,n)=>n,f4e=yt(iT,TT,AT,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(Ine)),g4e=yt(sT,TT,AT,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(Ine)),zne=(t,e)=>({width:t.width,height:e.height}),b4e=(t,e)=>{var n=typeof e.width=="number"?e.width:Zw;return{width:n,height:t.height}},Une=yt(Ti,Bd,zne),x4e=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},y4e=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},v4e=yt(xm,Ti,f4e,TT,AT,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=zne(e,l);o==null&&(o=x4e(e,r,t));var d=r==="top"&&!i||r==="bottom"&&i;s[l.id]=o-Number(d)*c.height,o+=(d?-1:1)*c.height}),s}),w4e=yt(bm,Ti,g4e,TT,AT,(t,e,n,r,i)=>{var s={},o;return n.forEach(l=>{var c=b4e(e,l);o==null&&(o=y4e(e,r,t));var d=r==="left"&&!i||r==="right"&&i;s[l.id]=o-Number(d)*c.width,o+=(d?-1:1)*c.width}),s}),S4e=(t,e)=>{var n=Bd(t,e);if(n!=null)return v4e(t,n.orientation,n.mirror)},_4e=yt([Ti,Bd,S4e,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:t.left,y:0}:{x:t.left,y:i}}}),k4e=(t,e)=>{var n=Hd(t,e);if(n!=null)return w4e(t,n.orientation,n.mirror)},N4e=yt([Ti,Hd,k4e,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var i=n?.[r];return i==null?{x:0,y:t.top}:{x:i,y:t.top}}}),Bne=yt(Ti,Hd,(t,e)=>{var n=typeof e.width=="number"?e.width:Zw;return{width:n,height:t.height}}),r9=(t,e,n)=>{switch(e){case"xAxis":return Une(t,n).width;case"yAxis":return Bne(t,n).height;default:return}},Hne=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:i,type:s,dataKey:o}=n,l=Wc(t,r),c=e.map(d=>d.value);if(o&&l&&s==="category"&&i&&VJ(c))return c}},j4=yt([Sr,CT,Ya,Fa],Hne),qne=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:i,scale:s}=n,o=Wc(t,r);if(o&&(i==="number"||s!=="auto"))return e.map(l=>l.value)}},M4=yt([Sr,CT,vy,Fa],qne),a9=yt([Sr,LIe,wp,Vx,j4,M4,mS,T4,Fa],(t,e,n,r,i,s,o,l,c)=>{if(e!=null){var d=Wc(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:i,isCategorical:d,niceTicks:l,range:o,realScaleType:n,scale:r}}}),C4e=(t,e,n,r,i,s,o,l,c)=>{if(!(e==null||r==null)){var d=Wc(t,c),{type:u,ticks:m,tickCount:p}=e,f=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,x=u==="category"&&r.bandwidth?r.bandwidth()/f:0;x=c==="angleAxis"&&s!=null&&s.length>=2?Bi(s[0]-s[1])*2*x:x;var v=m||i;return v?v.map((g,b)=>{var _=o?o.indexOf(g):g,C=r.map(_);return Wn(C)?{index:b,coordinate:C+x,value:g,offset:x}:null}).filter(Po):d&&l?l.map((g,b)=>{var _=r.map(g);return Wn(_)?{coordinate:_+x,value:g,index:b,offset:x}:null}).filter(Po):r.ticks?r.ticks(p).map((g,b)=>{var _=r.map(g);return Wn(_)?{coordinate:_+x,value:g,index:b,offset:x}:null}).filter(Po):r.domain().map((g,b)=>{var _=r.map(g);return Wn(_)?{coordinate:_+x,value:o?o[g]:g,index:b,offset:x}:null}).filter(Po)}},$ne=yt([Sr,vy,wp,Vx,T4,mS,j4,M4,Fa],C4e),P4e=(t,e,n,r,i,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=Wc(t,o),{tickCount:c}=e,d=0;return d=o==="angleAxis"&&r?.length>=2?Bi(r[0]-r[1])*2*d:d,l&&s?s.map((u,m)=>{var p=n.map(u);return Wn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(Po):n.ticks?n.ticks(c).map((u,m)=>{var p=n.map(u);return Wn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(Po):n.domain().map((u,m)=>{var p=n.map(u);return Wn(p)?{coordinate:p+d,value:i?i[u]:u,index:m,offset:d}:null}).filter(Po)}},Rd=yt([Sr,vy,Vx,mS,j4,M4,Fa],P4e),Ld=yt(Ya,Vx,(t,e)=>{if(!(t==null||e==null))return uC(uC({},t),{},{scale:e})}),T4e=yt([Ya,wp,N4,One],C4);yt((t,e,n)=>m4(t,n),T4e,(t,e)=>{if(!(t==null||e==null))return uC(uC({},t),{},{scale:e})});var A4e=yt([Sr,iT,sT],(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}}),Vne=t=>t.options.defaultTooltipEventType,Gne=t=>t.options.validateTooltipEventTypes;function Wne(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function E4(t,e){var n=Vne(t),r=Gne(t);return Wne(e,n,r)}function j4e(t){return un(e=>E4(e,t))}var Kne=(t,e)=>{var n,r=Number(e);if(!(Bc(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},M4e=t=>t.tooltip.settings,kh={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},E4e={itemInteraction:{click:kh,hover:kh},axisInteraction:{click:kh,hover:kh},keyboardInteraction:kh,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}},Xne=Fo({name:"tooltip",initialState:E4e,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:Sa()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Ic(t).tooltipItemPayloads.indexOf(n);i>-1&&(t.tooltipItemPayloads[i]=r)},prepare:Sa()},removeTooltipEntrySettings:{reducer(t,e){var n=Ic(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:Sa()},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:D4e,replaceTooltipEntrySettings:F4e,removeTooltipEntrySettings:R4e,setTooltipSettingsState:L4e,setActiveMouseOverItemIndex:Yne,mouseLeaveItem:O4e,mouseLeaveChart:Qne,setActiveClickItemIndex:I4e,setMouseOverAxisIndex:Zne,setMouseClickAxisIndex:z4e,setSyncInteraction:VR,setKeyboardInteraction:GR}=Xne.actions,U4e=Xne.reducer;function i9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function K1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?i9(Object(n),!0).forEach(function(r){B4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):i9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function B4e(t,e,n){return(e=H4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function H4e(t){var e=q4e(t,"string");return typeof e=="symbol"?e:e+""}function q4e(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 $4e(t,e,n){return e==="axis"?n==="click"?t.axisInteraction.click:t.axisInteraction.hover:n==="click"?t.itemInteraction.click:t.itemInteraction.hover}function V4e(t){return t.index!=null}var Jne=(t,e,n,r)=>{if(e==null)return kh;var i=$4e(t,e,n);if(i==null)return kh;if(i.active)return i;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(V4e(i)){if(s)return K1(K1({},i),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return K1(K1({},kh),{},{coordinate:i.coordinate})};function G4e(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 W4e(t,e){var n=G4e(t),r=e[0],i=e[1];if(n===void 0)return!1;var s=Math.min(r,i),o=Math.max(r,i);return n>=s&&n<=o}function K4e(t,e,n){if(n==null||e==null)return!0;var r=Fr(t,e);return r==null||!pm(n)?!0:W4e(r,n)}var D4=(t,e,n,r)=>{var i=t?.index;if(i==null)return null;var s=Number(i);if(!Wn(s))return i;var o=0,l=1/0;e.length>0&&(l=e.length-1);var c=Math.max(o,Math.min(s,l)),d=e[c];return d==null||K4e(d,n,r)?String(c):null},ere=(t,e,n,r,i,s,o)=>{if(s!=null){var l=o[0],c=l?.getPosition(s);if(c!=null)return c;var d=i?.[Number(s)];if(d)return n==="horizontal"?{x:d.coordinate,y:(r.top+e)/2}:{x:(r.left+t)/2,y:d.coordinate}}},tre=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var i;if(n==="hover"?i=t.itemInteraction.hover.graphicalItemId:i=t.itemInteraction.click.graphicalItemId,i==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)===i})},nre=t=>t.options.tooltipPayloadSearcher,Sy=t=>t.tooltip;function s9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function o9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?s9(Object(n),!0).forEach(function(r){X4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):s9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function X4e(t,e,n){return(e=Y4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Y4e(t){var e=Q4e(t,"string");return typeof e=="symbol"?e:e+""}function Q4e(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 Z4e(t,e){return t??e}var rre=(t,e,n,r,i,s,o)=>{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:d,dataEndIndex:u}=n,m=[];return t.reduce((p,f)=>{var x,{dataDefinedOnItem:v,settings:g}=f,b=Z4e(v,l),_=Array.isArray(b)?zee(b,d,u):b,C=(x=g?.dataKey)!==null&&x!==void 0?x:r,P=g?.nameKey,N;if(r&&Array.isArray(_)&&!Array.isArray(_[0])&&o==="axis"?N=GJ(_,r,i):N=s(_,e,c,P),Array.isArray(N))N.forEach(T=>{var F=o9(o9({},g),{},{name:T.name,unit:T.unit,color:void 0,fill:void 0});p.push(i7({tooltipEntrySettings:F,dataKey:T.dataKey,payload:T.payload,value:Fr(T.payload,T.dataKey),name:T.name}))});else{var A;p.push(i7({tooltipEntrySettings:g,dataKey:C,payload:N,value:Fr(N,C),name:(A=Fr(N,P))!==null&&A!==void 0?A:g?.name}))}return p},m)}},F4=yt([Mi,_ne,s4],Rne),J4e=yt([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),eze=yt([Gi,yy],h4),_y=yt([J4e,Mi,eze],p4,{memoizeOptions:{resultEqualityCheck:NT}}),tze=yt([_y],t=>t.filter(_T)),nze=yt([_y],f4,{memoizeOptions:{resultEqualityCheck:NT}}),ky=yt([nze,vm],g4),rze=yt([tze,vm,Mi],yne),R4=yt([ky,Mi,_y],x4),are=yt([Mi],y4),aze=yt([Mi],t=>t.allowDataOverflow),ire=yt([are,aze],Jte),ize=yt([_y],t=>t.filter(_T)),sze=yt([rze,ize,oS,mne],Pne),oze=yt([sze,vm,Gi,ire],Tne),lze=yt([_y],Nne),cze=yt([ky,Mi,lze,PT,Gi],S4,{memoizeOptions:{resultEqualityCheck:kT}}),dze=yt([Ane,Gi,yy],wy),uze=yt([dze,Gi],Ene),mze=yt([jne,Gi,yy],wy),hze=yt([mze,Gi],Dne),pze=yt([Mne,Gi,yy],wy),fze=yt([pze,Gi],Fne),gze=yt([uze,fze,hze],hC),bze=yt([Mi,are,ire,oze,cze,gze,Sr,Gi],_4),hS=yt([Mi,Sr,ky,R4,oS,Gi,bze],k4),xze=yt([hS,Mi,F4],P4),yze=yt([Mi,hS,xze,Gi],A4),sre=t=>{var e=Gi(t),n=yy(t),r=!1;return mS(t,e,n,r)},ore=yt([Mi,sre],yT),lre=yt([Mi,F4,yze,ore],C4),vze=yt([Sr,R4,Mi,Gi],Hne),wze=yt([Sr,R4,Mi,Gi],qne),Sze=(t,e,n,r,i,s,o,l)=>{if(e){var{type:c}=e,d=Wc(t,l);if(r){var u=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,m=c==="category"&&r.bandwidth?r.bandwidth()/u:0;return m=l==="angleAxis"&&i!=null&&i?.length>=2?Bi(i[0]-i[1])*2*m:m,d&&o?o.map((p,f)=>{var x=r.map(p);return Wn(x)?{coordinate:x+m,value:p,index:f,offset:m}:null}).filter(Po):r.domain().map((p,f)=>{var x=r.map(p);return Wn(x)?{coordinate:x+m,value:s?s[p]:p,index:f,offset:m}:null}).filter(Po)}}},wm=yt([Sr,Mi,F4,lre,sre,vze,wze,Gi],Sze),L4=yt([Vne,Gne,M4e],(t,e,n)=>Wne(n.shared,t,e)),cre=t=>t.tooltip.settings.trigger,O4=t=>t.tooltip.settings.defaultIndex,pS=yt([Sy,L4,cre,O4],Jne),dp=yt([pS,ky,uS,hS],D4),dre=yt([wm,dp],Kne),I4=yt([pS],t=>{if(t)return t.dataKey}),_ze=yt([pS],t=>{if(t)return t.graphicalItemId}),ure=yt([Sy,L4,cre,O4],tre),kze=yt([bm,xm,Sr,Ti,wm,O4,ure],ere),Nze=yt([pS,kze],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),Cze=yt([pS],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),Pze=yt([ure,dp,vm,uS,dre,nre,L4],rre),Tze=yt([Pze],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function l9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function c9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?l9(Object(n),!0).forEach(function(r){Aze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):l9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Aze(t,e,n){return(e=jze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function jze(t){var e=Mze(t,"string");return typeof e=="symbol"?e:e+""}function Mze(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 Eze=()=>un(Mi),Dze=()=>{var t=Eze(),e=un(wm),n=un(lre);return cp(!t||!n?void 0:c9(c9({},t),{},{scale:n}),e)};function d9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function qb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?d9(Object(n),!0).forEach(function(r){Fze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):d9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Fze(t,e,n){return(e=Rze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Rze(t){var e=Lze(t,"string");return typeof e=="symbol"?e:e+""}function Lze(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 Oze=(t,e,n,r)=>{var i=e.find(s=>s&&s.index===n);if(i){if(t==="horizontal")return{x:i.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:i.coordinate}}return{x:0,y:0}},Ize=(t,e,n,r)=>{var i=e.find(d=>d&&d.index===n);if(i){if(t==="centric"){var s=i.coordinate,{radius:o}=r;return qb(qb(qb({},r),hi(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=i.coordinate,{angle:c}=r;return qb(qb(qb({},r),hi(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 zze(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 mre=(t,e,n,r,i)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(r==="angleAxis"&&i!=null&&Math.abs(Math.abs(i[1]-i[0])-360)<=1e-6)for(var l=0;l<o;l++){var c,d,u,m,p,f=l>0?(c=n[l-1])===null||c===void 0?void 0:c.coordinate:(d=n[o-1])===null||d===void 0?void 0:d.coordinate,x=(u=n[l])===null||u===void 0?void 0:u.coordinate,v=l>=o-1?(m=n[0])===null||m===void 0?void 0:m.coordinate:(p=n[l+1])===null||p===void 0?void 0:p.coordinate,g=void 0;if(!(f==null||x==null||v==null))if(Bi(x-f)!==Bi(v-x)){var b=[];if(Bi(v-x)===Bi(i[1]-i[0])){g=v;var _=x+i[1]-i[0];b[0]=Math.min(_,(_+f)/2),b[1]=Math.max(_,(_+f)/2)}else{g=f;var C=v+i[1]-i[0];b[0]=Math.min(x,(C+x)/2),b[1]=Math.max(x,(C+x)/2)}var P=[Math.min(x,(g+x)/2),Math.max(x,(g+x)/2)];if(t>P[0]&&t<=P[1]||t>=b[0]&&t<=b[1]){var N;return(N=n[l])===null||N===void 0?void 0:N.index}}else{var A=Math.min(f,v),T=Math.max(f,v);if(t>(A+x)/2&&t<=(T+x)/2){var F;return(F=n[l])===null||F===void 0?void 0:F.index}}}else if(e)for(var k=0;k<o;k++){var D=e[k];if(D!=null){var H=e[k+1],z=e[k-1];if(k===0&&H!=null&&t<=(D.coordinate+H.coordinate)/2||k===o-1&&z!=null&&t>(D.coordinate+z.coordinate)/2||k>0&&k<o-1&&z!=null&&H!=null&&t>(D.coordinate+z.coordinate)/2&&t<=(D.coordinate+H.coordinate)/2)return D.index}}return-1},hre=()=>un(s4),z4=(t,e)=>e,pre=(t,e,n)=>n,U4=(t,e,n,r)=>r,Uze=yt(wm,t=>XP(t,e=>e.coordinate)),B4=yt([Sy,z4,pre,U4],Jne),H4=yt([B4,ky,uS,hS],D4),Bze=(t,e,n)=>{if(e!=null){var r=Sy(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},fre=yt([Sy,z4,pre,U4],tre),pC=yt([bm,xm,Sr,Ti,wm,U4,fre],ere),Hze=yt([B4,pC],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),gre=yt([wm,H4],Kne),qze=yt([fre,H4,vm,uS,gre,nre,z4],rre),$ze=yt([B4,H4],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),Vze=(t,e,n,r,i,s,o)=>{if(!(!t||!n||!r||!i)&&zze(t,o)){var l=h3e(t,e),c=mre(l,s,i,n,r),d=Oze(e,i,c,t);return{activeIndex:String(c),activeCoordinate:d}}},Gze=(t,e,n,r,i,s,o)=>{if(!(!t||!r||!i||!s||!n)){var l=jRe(t,n);if(l){var c=p3e(l,e),d=mre(c,o,s,r,i),u=Ize(e,s,d,l);return{activeIndex:String(d),activeCoordinate:u}}}},Wze=(t,e,n,r,i,s,o,l)=>{if(!(!t||!e||!r||!i||!s))return e==="horizontal"||e==="vertical"?Vze(t,e,r,i,s,o,l):Gze(t,e,n,r,i,s,o)},Kze=yt(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}}),Xze=yt(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(Ga)),n=Array.from(new Set(e));return n.sort((r,i)=>r-i)},{memoizeOptions:{resultEqualityCheck:jIe}});function u9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function m9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?u9(Object(n),!0).forEach(function(r){Yze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):u9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Yze(t,e,n){return(e=Qze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Qze(t){var e=Zze(t,"string");return typeof e=="symbol"?e:e+""}function Zze(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 Jze={},e5e={zIndexMap:Object.values(Ga).reduce((t,e)=>m9(m9({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),Jze)},t5e=new Set(Object.values(Ga));function n5e(t){return t5e.has(t)}var bre=Fo({name:"zIndex",initialState:e5e,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:Sa()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!n5e(n)&&delete t.zIndexMap[n])},prepare:Sa()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:r,isPanorama:i}=e.payload;t.zIndexMap[n]?i?t.zIndexMap[n].panoramaElement=r:t.zIndexMap[n].element=r:t.zIndexMap[n]={consumers:0,element:i?void 0:r,panoramaElement:i?r:void 0}},prepare:Sa()},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:Sa()}}}),{registerZIndexPortal:r5e,unregisterZIndexPortal:a5e,registerZIndexPortalElement:i5e,unregisterZIndexPortalElement:s5e}=bre.actions,o5e=bre.reducer;function Os(t){var{zIndex:e,children:n}=t,r=V3e(),i=r&&e!==void 0&&e!==0,s=Ai(),o=ia();w.useLayoutEffect(()=>i?(o(r5e({zIndex:e})),()=>{o(a5e({zIndex:e}))}):gp,[o,e,i]);var l=un(c=>Kze(c,e,s));return i?l?Ou.createPortal(n,l):null:n}function WR(){return WR=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},WR.apply(null,arguments)}function h9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function X1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?h9(Object(n),!0).forEach(function(r){l5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):h9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function l5e(t,e,n){return(e=c5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function c5e(t){var e=d5e(t,"string");return typeof e=="symbol"?e:e+""}function d5e(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 u5e(t){var{cursor:e,cursorComp:n,cursorProps:r}=t;return w.isValidElement(e)?w.cloneElement(e,r):w.createElement(n,r)}function m5e(t){var e,{coordinate:n,payload:r,index:i,offset:s,tooltipAxisBandSize:o,layout:l,cursor:c,tooltipEventType:d,chartName:u}=t,m=n,p=r,f=i;if(!c||!m||u!=="ScatterChart"&&d!=="axis")return null;var x,v,g;if(u==="ScatterChart")x=m,v=$Fe,g=Ga.cursorLine;else if(u==="BarChart")x=VFe(l,m,s,o),v=hte,g=Ga.cursorRectangle;else if(l==="radial"&&KJ(m)){var{cx:b,cy:_,radius:C,startAngle:P,endAngle:N}=fte(m);x={cx:b,cy:_,startAngle:P,endAngle:N,innerRadius:C,outerRadius:C},v=bte,g=Ga.cursorLine}else x={points:FRe(l,m,s)},v=yx,g=Ga.cursorLine;var A=typeof c=="object"&&"className"in c?c.className:void 0,T=X1(X1(X1(X1({stroke:"#ccc",pointerEvents:"none"},s),x),ag(c)),{},{payload:p,payloadIndex:f,className:_r("recharts-tooltip-cursor",A)});return w.createElement(Os,{zIndex:(e=t.zIndex)!==null&&e!==void 0?e:g},w.createElement(u5e,{cursor:c,cursorComp:v,cursorProps:T}))}function h5e(t){var e=Dze(),n=Xee(),r=xp(),i=hre();return e==null||n==null||r==null||i==null?null:w.createElement(m5e,WR({},t,{offset:n,layout:r,tooltipAxisBandSize:e,chartName:i}))}var xre=w.createContext(null),p5e=()=>w.useContext(xre),nD={exports:{}},p9;function f5e(){return p9||(p9=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,d,u){this.fn=c,this.context=d,this.once=u||!1}function s(c,d,u,m,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,m||c,p),x=n?n+d:d;return c._events[x]?c._events[x].fn?c._events[x]=[c._events[x],f]:c._events[x].push(f):(c._events[x]=f,c._eventsCount++),c}function o(c,d){--c._eventsCount===0?c._events=new r:delete c._events[d]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var d=[],u,m;if(this._eventsCount===0)return d;for(m in u=this._events)e.call(u,m)&&d.push(n?m.slice(1):m);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},l.prototype.listeners=function(d){var u=n?n+d:d,m=this._events[u];if(!m)return[];if(m.fn)return[m.fn];for(var p=0,f=m.length,x=new Array(f);p<f;p++)x[p]=m[p].fn;return x},l.prototype.listenerCount=function(d){var u=n?n+d:d,m=this._events[u];return m?m.fn?1:m.length:0},l.prototype.emit=function(d,u,m,p,f,x){var v=n?n+d:d;if(!this._events[v])return!1;var g=this._events[v],b=arguments.length,_,C;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),b){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,m),!0;case 4:return g.fn.call(g.context,u,m,p),!0;case 5:return g.fn.call(g.context,u,m,p,f),!0;case 6:return g.fn.call(g.context,u,m,p,f,x),!0}for(C=1,_=new Array(b-1);C<b;C++)_[C-1]=arguments[C];g.fn.apply(g.context,_)}else{var P=g.length,N;for(C=0;C<P;C++)switch(g[C].once&&this.removeListener(d,g[C].fn,void 0,!0),b){case 1:g[C].fn.call(g[C].context);break;case 2:g[C].fn.call(g[C].context,u);break;case 3:g[C].fn.call(g[C].context,u,m);break;case 4:g[C].fn.call(g[C].context,u,m,p);break;default:if(!_)for(N=1,_=new Array(b-1);N<b;N++)_[N-1]=arguments[N];g[C].fn.apply(g[C].context,_)}}return!0},l.prototype.on=function(d,u,m){return s(this,d,u,m,!1)},l.prototype.once=function(d,u,m){return s(this,d,u,m,!0)},l.prototype.removeListener=function(d,u,m,p){var f=n?n+d:d;if(!this._events[f])return this;if(!u)return o(this,f),this;var x=this._events[f];if(x.fn)x.fn===u&&(!p||x.once)&&(!m||x.context===m)&&o(this,f);else{for(var v=0,g=[],b=x.length;v<b;v++)(x[v].fn!==u||p&&!x[v].once||m&&x[v].context!==m)&&g.push(x[v]);g.length?this._events[f]=g.length===1?g[0]:g:o(this,f)}return this},l.prototype.removeAllListeners=function(d){var u;return d?(u=n?n+d:d,this._events[u]&&o(this,u)):(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})(nD)),nD.exports}var g5e=f5e();const b5e=mc(g5e);var hw=new b5e,KR="recharts.syncEvent.tooltip",f9="recharts.syncEvent.brush",jT=(t,e)=>{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!Bc(n))return t[n]}},x5e={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},yre=Fo({name:"options",initialState:x5e,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),y5e=yre.reducer,{createEventEmitter:v5e}=yre.actions;function w5e(t){return t.tooltip.syncInteraction}var S5e={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},vre=Fo({name:"chartData",initialState:S5e,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:g9,setDataStartEndIndexes:_5e,setComputedData:bst}=vre.actions,k5e=vre.reducer,N5e=["x","y"];function b9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function $b(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?b9(Object(n),!0).forEach(function(r){C5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):b9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function C5e(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=T5e(t,"string");return typeof e=="symbol"?e:e+""}function T5e(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 A5e(t,e){if(t==null)return{};var n,r,i=j5e(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)&&(i[n]=t[n])}return i}function j5e(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 M5e(){var t=un(o4),e=un(l4),n=ia(),r=un(hne),i=un(wm),s=xp(),o=Jw(),l=un(c=>c.rootProps.className);w.useEffect(()=>{if(t==null)return gp;var c=(d,u,m)=>{if(e!==m&&t===d){if(r==="index"){var p;if(o&&u!==null&&u!==void 0&&(p=u.payload)!==null&&p!==void 0&&p.coordinate&&u.payload.sourceViewBox){var f=u.payload.coordinate,{x,y:v}=f,g=A5e(f,N5e),{x:b,y:_,width:C,height:P}=u.payload.sourceViewBox,N=$b($b({},g),{},{x:o.x+(C?(x-b)/C:0)*o.width,y:o.y+(P?(v-_)/P:0)*o.height});n($b($b({},u),{},{payload:$b($b({},u.payload),{},{coordinate:N})}))}else n(u);return}if(i!=null){var A;if(typeof r=="function"){var T={activeTooltipIndex:u.payload.index==null?void 0:Number(u.payload.index),isTooltipActive:u.payload.active,activeIndex:u.payload.index==null?void 0:Number(u.payload.index),activeLabel:u.payload.label,activeDataKey:u.payload.dataKey,activeCoordinate:u.payload.coordinate},F=r(i,T);A=i[F]}else r==="value"&&(A=i.find(ie=>String(ie.value)===u.payload.label));var{coordinate:k}=u.payload;if(A==null||u.payload.active===!1||k==null||o==null){n(VR({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:D,y:H}=k,z=Math.min(D,o.x+o.width),X=Math.min(H,o.y+o.height),L={x:s==="horizontal"?A.coordinate:z,y:s==="horizontal"?X:A.coordinate},ne=VR({active:u.payload.active,coordinate:L,dataKey:u.payload.dataKey,index:String(A.index),label:u.payload.label,sourceViewBox:u.payload.sourceViewBox,graphicalItemId:u.payload.graphicalItemId});n(ne)}}};return hw.on(KR,c),()=>{hw.off(KR,c)}},[l,n,e,t,r,i,s,o])}function E5e(){var t=un(o4),e=un(l4),n=ia();w.useEffect(()=>{if(t==null)return gp;var r=(i,s,o)=>{e!==o&&t===i&&n(_5e(s))};return hw.on(f9,r),()=>{hw.off(f9,r)}},[n,e,t])}function D5e(){var t=ia();w.useEffect(()=>{t(v5e())},[t]),M5e(),E5e()}function F5e(t,e,n,r,i,s){var o=un(f=>Bze(f,t,e)),l=un(l4),c=un(o4),d=un(hne),u=un(w5e),m=u?.active,p=Jw();w.useEffect(()=>{if(!m&&c!=null&&l!=null){var f=VR({active:s,coordinate:n,dataKey:o,index:i,label:typeof r=="number"?String(r):r,sourceViewBox:p,graphicalItemId:void 0});hw.emit(KR,c,f,l)}},[m,n,o,i,r,l,c,d,s,p])}function x9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function y9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?x9(Object(n),!0).forEach(function(r){R5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):x9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function R5e(t,e,n){return(e=L5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function L5e(t){var e=O5e(t,"string");return typeof e=="symbol"?e:e+""}function O5e(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 I5e(t){return t.dataKey}function z5e(t,e){return w.isValidElement(t)?w.cloneElement(t,e):typeof t=="function"?w.createElement(t,e):w.createElement(_Fe,e)}var v9=[],U5e={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 Rh(t){var e,n,r=Da(t,U5e),{active:i,allowEscapeViewBox:s,animationDuration:o,animationEasing:l,content:c,filterNull:d,isAnimationActive:u,offset:m,payloadUniqBy:p,position:f,reverseDirection:x,useTranslate3d:v,wrapperStyle:g,cursor:b,shared:_,trigger:C,defaultIndex:P,portal:N,axisId:A}=r,T=ia(),F=typeof P=="number"?String(P):P;w.useEffect(()=>{T(L4e({shared:_,trigger:C,axisId:A,active:i,defaultIndex:F}))},[T,_,C,A,i,F]);var k=Jw(),D=lte(),H=j4e(_),{activeIndex:z,isActive:X}=(e=un(Y=>$ze(Y,H,C,F)))!==null&&e!==void 0?e:{},L=un(Y=>qze(Y,H,C,F)),ne=un(Y=>gre(Y,H,C,F)),ie=un(Y=>Hze(Y,H,C,F)),ee=L,ue=p5e(),le=(n=i??X)!==null&&n!==void 0?n:!1,[oe,W]=cee([ee,le]),re=H==="axis"?ne:void 0;F5e(H,C,ie,re,z,le);var ce=N??ue;if(ce==null||k==null||H==null)return null;var xe=ee??v9;le||(xe=v9),d&&xe.length&&(xe=ree(xe.filter(Y=>Y.value!=null&&(Y.hide!==!0||r.includeHidden)),p,I5e));var Ne=xe.length>0,$=w.createElement(jFe,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:u,active:le,coordinate:ie,hasPayload:Ne,offset:m,position:f,reverseDirection:x,useTranslate3d:v,viewBox:k,wrapperStyle:g,lastBoundingBox:oe,innerRef:W,hasPortalFromProps:!!N},z5e(c,y9(y9({},r),{},{payload:xe,label:re,active:le,activeIndex:z,coordinate:ie,accessibilityLayer:D})));return w.createElement(w.Fragment,null,Ou.createPortal($,ce),le&&w.createElement(h5e,{cursor:b,tooltipEventType:H,coordinate:ie,payload:xe,index:z}))}var Gx=t=>null;Gx.displayName="Cell";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=q5e(t,"string");return typeof e=="symbol"?e:e+""}function q5e(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 $5e{constructor(e){B5e(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 w9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function V5e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?w9(Object(n),!0).forEach(function(r){G5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):w9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function G5e(t,e,n){return(e=W5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function W5e(t){var e=K5e(t,"string");return typeof e=="symbol"?e:e+""}function K5e(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 X5e={cacheSize:2e3,enableCache:!0},wre=V5e({},X5e),S9=new $5e(wre.cacheSize),Y5e={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},_9="recharts_measurement_span";function Q5e(t,e){var n=e.fontSize||"",r=e.fontFamily||"",i=e.fontWeight||"",s=e.fontStyle||"",o=e.letterSpacing||"",l=e.textTransform||"";return"".concat(t,"|").concat(n,"|").concat(r,"|").concat(i,"|").concat(s,"|").concat(o,"|").concat(l)}var k9=(t,e)=>{try{var n=document.getElementById(_9);n||(n=document.createElement("span"),n.setAttribute("id",_9),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,Y5e,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},b0=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||nS.isSsr)return{width:0,height:0};if(!wre.enableCache)return k9(e,n);var r=Q5e(e,n),i=S9.get(r);if(i)return i;var s=k9(e,n);return S9.set(r,s),s},Sre;function Z5e(t,e,n){return(e=J5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function J5e(t){var e=eUe(t,"string");return typeof e=="symbol"?e:e+""}function eUe(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 N9=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,C9=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,tUe=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,nUe=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,rUe={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},aUe=["cm","mm","pt","pc","in","Q","px"];function iUe(t){return aUe.includes(t)}var ox="NaN";function sUe(t,e){return t*rUe[e]}class ls{static parse(e){var n,[,r,i]=(n=nUe.exec(e))!==null&&n!==void 0?n:[];return r==null?ls.NaN:new ls(parseFloat(r),i??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Bc(e)&&(this.unit=""),n!==""&&!tUe.test(n)&&(this.num=NaN,this.unit=""),iUe(n)&&(this.num=sUe(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new ls(NaN,""):new ls(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new ls(NaN,""):new ls(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new ls(NaN,""):new ls(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new ls(NaN,""):new ls(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Bc(this.num)}}Sre=ls;Z5e(ls,"NaN",new Sre(NaN,""));function _re(t){if(t==null||t.includes(ox))return ox;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,i,s]=(n=N9.exec(e))!==null&&n!==void 0?n:[],o=ls.parse(r??""),l=ls.parse(s??""),c=i==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return ox;e=e.replace(N9,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var d,[,u,m,p]=(d=C9.exec(e))!==null&&d!==void 0?d:[],f=ls.parse(u??""),x=ls.parse(p??""),v=m==="+"?f.add(x):f.subtract(x);if(v.isNaN())return ox;e=e.replace(C9,v.toString())}return e}var P9=/\(([^()]*)\)/;function oUe(t){for(var e=t,n;(n=P9.exec(e))!=null;){var[,r]=n;e=e.replace(P9,_re(r))}return e}function lUe(t){var e=t.replace(/\s+/g,"");return e=oUe(e),e=_re(e),e}function cUe(t){try{return lUe(t)}catch{return ox}}function rD(t){var e=cUe(t.slice(5,-1));return e===ox?"":e}var dUe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],uUe=["dx","dy","angle","className","breakAll"];function XR(){return XR=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},XR.apply(null,arguments)}function T9(t,e){if(t==null)return{};var n,r,i=mUe(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)&&(i[n]=t[n])}return i}function mUe(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 kre=/[ \f\n\r\t\v\u2028\u2029]+/,Nre=t=>{var{children:e,breakAll:n,style:r}=t;try{var i=[];Ca(e)||(n?i=e.toString().split(""):i=e.toString().split(kre));var s=i.map(l=>({word:l,width:b0(l,r).width})),o=n?0:b0(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function hUe(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var Cre=(t,e,n,r)=>t.reduce((i,s)=>{var{word:o,width:l}=s,c=i[i.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 d={words:[o],width:l};i.push(d)}return i},[]),Pre=t=>t.reduce((e,n)=>e.width>n.width?e:n),pUe="…",A9=(t,e,n,r,i,s,o,l)=>{var c=t.slice(0,e),d=Nre({breakAll:n,style:r,children:c+pUe});if(!d)return[!1,[]];var u=Cre(d.wordsWithComputedWidth,s,o,l),m=u.length>i||Pre(u).width>Number(s);return[m,u]},fUe=(t,e,n,r,i)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,d=an(s),u=String(o),m=Cre(e,r,n,i);if(!d||i)return m;var p=m.length>s||Pre(m).width>Number(r);if(!p)return m;for(var f=0,x=u.length-1,v=0,g;f<=x&&v<=u.length-1;){var b=Math.floor((f+x)/2),_=b-1,[C,P]=A9(u,_,c,l,s,r,n,i),[N]=A9(u,b,c,l,s,r,n,i);if(!C&&!N&&(f=b+1),C&&N&&(x=b-1),!C&&N){g=P;break}v++}return g||m},j9=t=>{var e=Ca(t)?[]:t.toString().split(kre);return[{words:e,width:void 0}]},gUe=t=>{var{width:e,scaleToFit:n,children:r,style:i,breakAll:s,maxLines:o}=t;if((e||n)&&!nS.isSsr){var l,c,d=Nre({breakAll:s,children:r,style:i});if(d){var{wordsWithComputedWidth:u,spaceWidth:m}=d;l=u,c=m}else return j9(r);return fUe({breakAll:s,children:r,maxLines:o,style:i},l,c,e,!!n)}return j9(r)},Tre="#808080",bUe={angle:0,breakAll:!1,capHeight:"0.71em",fill:Tre,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},MT=w.forwardRef((t,e)=>{var n=Da(t,bUe),{x:r,y:i,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:d,verticalAnchor:u}=n,m=T9(n,dUe),p=w.useMemo(()=>gUe({breakAll:m.breakAll,children:m.children,maxLines:m.maxLines,scaleToFit:c,style:m.style,width:m.width}),[m.breakAll,m.children,m.maxLines,c,m.style,m.width]),{dx:f,dy:x,angle:v,className:g,breakAll:b}=m,_=T9(m,uUe);if(!lc(r)||!lc(i)||p.length===0)return null;var C=Number(r)+(an(f)?f:0),P=Number(i)+(an(x)?x:0);if(!Wn(C)||!Wn(P))return null;var N;switch(u){case"start":N=rD("calc(".concat(o,")"));break;case"middle":N=rD("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:N=rD("calc(".concat(p.length-1," * -").concat(s,")"));break}var A=[],T=p[0];if(c&&T!=null){var F=T.width,{width:k}=m;A.push("scale(".concat(an(k)&&an(F)?k/F:1,")"))}return v&&A.push("rotate(".concat(v,", ").concat(C,", ").concat(P,")")),A.length&&(_.transform=A.join(" ")),w.createElement("text",XR({},ys(_),{ref:e,x:C,y:P,className:_r("recharts-text",g),textAnchor:d,fill:l.includes("url")?Tre:l}),p.map((D,H)=>{var z=D.words.join(b?"":" ");return w.createElement("tspan",{x:C,dy:H===0?N:s,key:"".concat(z,"-").concat(H)},z)}))});MT.displayName="Text";function M9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function cd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?M9(Object(n),!0).forEach(function(r){xUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):M9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function xUe(t,e,n){return(e=yUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yUe(t){var e=vUe(t,"string");return typeof e=="symbol"?e:e+""}function vUe(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 wUe=t=>{var{viewBox:e,position:n,offset:r=0,parentViewBox:i}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:d}=TI(e),u=s,m=s+(c-d)/2,p=(u+m)/2,f=(c+d)/2,x=u+c/2,v=l>=0?1:-1,g=v*r,b=v>0?"end":"start",_=v>0?"start":"end",C=c>=0?1:-1,P=C*r,N=C>0?"end":"start",A=C>0?"start":"end",T=i;if(n==="top"){var F={x:u+c/2,y:o-g,horizontalAnchor:"middle",verticalAnchor:b};return T&&(F.height=Math.max(o-T.y,0),F.width=c),F}if(n==="bottom"){var k={x:m+d/2,y:o+l+g,horizontalAnchor:"middle",verticalAnchor:_};return T&&(k.height=Math.max(T.y+T.height-(o+l),0),k.width=d),k}if(n==="left"){var D={x:p-P,y:o+l/2,horizontalAnchor:N,verticalAnchor:"middle"};return T&&(D.width=Math.max(D.x-T.x,0),D.height=l),D}if(n==="right"){var H={x:p+f+P,y:o+l/2,horizontalAnchor:A,verticalAnchor:"middle"};return T&&(H.width=Math.max(T.x+T.width-H.x,0),H.height=l),H}var z=T?{width:f,height:l}:{};return n==="insideLeft"?cd({x:p+P,y:o+l/2,horizontalAnchor:A,verticalAnchor:"middle"},z):n==="insideRight"?cd({x:p+f-P,y:o+l/2,horizontalAnchor:N,verticalAnchor:"middle"},z):n==="insideTop"?cd({x:u+c/2,y:o+g,horizontalAnchor:"middle",verticalAnchor:_},z):n==="insideBottom"?cd({x:m+d/2,y:o+l-g,horizontalAnchor:"middle",verticalAnchor:b},z):n==="insideTopLeft"?cd({x:u+P,y:o+g,horizontalAnchor:A,verticalAnchor:_},z):n==="insideTopRight"?cd({x:u+c-P,y:o+g,horizontalAnchor:N,verticalAnchor:_},z):n==="insideBottomLeft"?cd({x:m+P,y:o+l-g,horizontalAnchor:A,verticalAnchor:b},z):n==="insideBottomRight"?cd({x:m+d-P,y:o+l-g,horizontalAnchor:N,verticalAnchor:b},z):n&&typeof n=="object"&&(an(n.x)||og(n.x))&&(an(n.y)||og(n.y))?cd({x:s+Ds(n.x,f),y:o+Ds(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},z):cd({x,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},z)},SUe=["labelRef"],_Ue=["content"];function E9(t,e){if(t==null)return{};var n,r,i=kUe(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)&&(i[n]=t[n])}return i}function kUe(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 D9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function e0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?D9(Object(n),!0).forEach(function(r){NUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):D9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function NUe(t,e,n){return(e=CUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function CUe(t){var e=PUe(t,"string");return typeof e=="symbol"?e:e+""}function PUe(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 Lu(){return Lu=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},Lu.apply(null,arguments)}var Are=w.createContext(null),jre=t=>{var{x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o,children:l}=t,c=w.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:i,width:s,height:o}),[e,n,r,i,s,o]);return w.createElement(Are.Provider,{value:c},l)},Mre=()=>{var t=w.useContext(Are),e=Jw();return t||(e?TI(e):void 0)},TUe=w.createContext(null),AUe=()=>{var t=w.useContext(TUe),e=un(xne);return t||e},jUe=t=>{var{value:e,formatter:n}=t,r=Ca(t.children)?e:t.children;return typeof n=="function"?n(r):r},q4=t=>t!=null&&typeof t=="function",MUe=(t,e)=>{var n=Bi(e-t),r=Math.min(Math.abs(e-t),360);return n*r},EUe=(t,e,n,r,i)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:d,outerRadius:u,startAngle:m,endAngle:p,clockWise:f}=i,x=(d+u)/2,v=MUe(m,p),g=v>=0?1:-1,b,_;switch(e){case"insideStart":b=m+g*s,_=f;break;case"insideEnd":b=p-g*s,_=!f;break;case"end":b=p+g*s,_=f;break;default:throw new Error("Unsupported position ".concat(e))}_=v<=0?_:!_;var C=hi(l,c,x,b),P=hi(l,c,x,b+(_?1:-1)*359),N="M".concat(C.x,",").concat(C.y,`
- A`).concat(x,",").concat(x,",0,1,").concat(_?0:1,`,
- `).concat(P.x,",").concat(P.y),A=Ca(t.id)?ew("recharts-radial-line-"):t.id;return w.createElement("text",Lu({},r,{dominantBaseline:"central",className:_r("recharts-radial-bar-label",o)}),w.createElement("defs",null,w.createElement("path",{id:A,d:N})),w.createElement("textPath",{xlinkHref:"#".concat(A)},n))},DUe=(t,e,n)=>{var{cx:r,cy:i,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,d=(l+c)/2;if(n==="outside"){var{x:u,y:m}=hi(r,i,o+e,d);return{x:u,y:m,textAnchor:u>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:i,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:f,y:x}=hi(r,i,p,d);return{x:f,y:x,textAnchor:"middle",verticalAnchor:"middle"}},Ik=t=>t!=null&&"cx"in t&&an(t.cx),FUe={angle:0,offset:5,zIndex:Ga.label,position:"middle",textBreakAll:!1};function RUe(t){if(!Ik(t))return t;var{cx:e,cy:n,outerRadius:r}=t,i=r*2;return{x:e-r,y:n-r,width:i,upperWidth:i,lowerWidth:i,height:i}}function xh(t){var e=Da(t,FUe),{viewBox:n,parentViewBox:r,position:i,value:s,children:o,content:l,className:c="",textBreakAll:d,labelRef:u}=e,m=AUe(),p=Mre(),f=i==="center"?p:m??p,x,v,g;n==null?x=f:Ik(n)?x=n:x=TI(n);var b=RUe(x);if(!x||Ca(s)&&Ca(o)&&!w.isValidElement(l)&&typeof l!="function")return null;var _=e0(e0({},e),{},{viewBox:x});if(w.isValidElement(l)){var{labelRef:C}=_,P=E9(_,SUe);return w.cloneElement(l,P)}if(typeof l=="function"){var{content:N}=_,A=E9(_,_Ue);if(v=w.createElement(l,A),w.isValidElement(v))return v}else v=jUe(e);var T=ys(e);if(Ik(x)){if(i==="insideStart"||i==="insideEnd"||i==="end")return EUe(e,i,v,T,x);g=DUe(x,e.offset,e.position)}else{if(!b)return null;var F=wUe({viewBox:b,position:i,offset:e.offset,parentViewBox:Ik(r)?void 0:r});g=e0(e0({x:F.x,y:F.y,textAnchor:F.horizontalAnchor,verticalAnchor:F.verticalAnchor},F.width!==void 0?{width:F.width}:{}),F.height!==void 0?{height:F.height}:{})}return w.createElement(Os,{zIndex:e.zIndex},w.createElement(MT,Lu({ref:u,className:_r("recharts-label",c)},T,g,{textAnchor:hUe(T.textAnchor)?T.textAnchor:g.textAnchor,breakAll:d}),v))}xh.displayName="Label";var LUe=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?w.createElement(xh,Lu({key:"label-implicit"},r)):lc(t)?w.createElement(xh,Lu({key:"label-implicit",value:t},r)):w.isValidElement(t)?t.type===xh?w.cloneElement(t,e0({key:"label-implicit"},r)):w.createElement(xh,Lu({key:"label-implicit",content:t},r)):q4(t)?w.createElement(xh,Lu({key:"label-implicit",content:t},r)):t&&typeof t=="object"?w.createElement(xh,Lu({},t,{key:"label-implicit"},r)):null};function Ere(t){var{label:e,labelRef:n}=t,r=Mre();return LUe(e,r,n)||null}var aD={},iD={},F9;function OUe(){return F9||(F9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(iD)),iD}var sD={},R9;function IUe(){return R9||(R9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(sD)),sD}var L9;function zUe(){return L9||(L9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=OUe(),n=IUe(),r=bI();function i(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=i})(aD)),aD}var oD,O9;function UUe(){return O9||(O9=1,oD=zUe().last),oD}var BUe=UUe();const HUe=mc(BUe);var qUe=["valueAccessor"],$Ue=["dataKey","clockWise","id","textBreakAll","zIndex"];function fC(){return fC=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},fC.apply(null,arguments)}function I9(t,e){if(t==null)return{};var n,r,i=VUe(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)&&(i[n]=t[n])}return i}function VUe(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 GUe=t=>Array.isArray(t.value)?HUe(t.value):t.value,Dre=w.createContext(void 0),$4=Dre.Provider,Fre=w.createContext(void 0),WUe=Fre.Provider;function KUe(){return w.useContext(Dre)}function XUe(){return w.useContext(Fre)}function zk(t){var{valueAccessor:e=GUe}=t,n=I9(t,qUe),{dataKey:r,clockWise:i,id:s,textBreakAll:o,zIndex:l}=n,c=I9(n,$Ue),d=KUe(),u=XUe(),m=d||u;return!m||!m.length?null:w.createElement(Os,{zIndex:l??Ga.label},w.createElement(Ea,{className:"recharts-label-list"},m.map((p,f)=>{var x,v=Ca(r)?e(p,f):Fr(p.payload,r),g=Ca(s)?{}:{id:"".concat(s,"-").concat(f)};return w.createElement(xh,fC({key:"label-".concat(f)},ys(p),c,g,{fill:(x=n.fill)!==null&&x!==void 0?x:p.fill,parentViewBox:p.parentViewBox,value:v,textBreakAll:o,viewBox:p.viewBox,index:f,zIndex:0}))})))}zk.displayName="LabelList";function ET(t){var{label:e}=t;return e?e===!0?w.createElement(zk,{key:"labelList-implicit"}):w.isValidElement(e)||q4(e)?w.createElement(zk,{key:"labelList-implicit",content:e}):typeof e=="object"?w.createElement(zk,fC({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function YR(){return YR=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},YR.apply(null,arguments)}var Rre=t=>{var{cx:e,cy:n,r,className:i}=t,s=_r("recharts-dot",i);return an(e)&&an(n)&&an(r)?w.createElement("circle",YR({},no(t),gI(t),{className:s,cx:e,cy:n,r})):null},Lre=t=>t.graphicalItems.polarItems,YUe=yt([Fa,lS],h4),DT=yt([Lre,Ya,YUe],p4),QUe=yt([DT],f4),FT=yt([QUe,xT],g4),ZUe=yt([FT,Ya,DT],x4);yt([FT,Ya,DT],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(i=>{var s,o=Fr(r,(s=e.dataKey)!==null&&s!==void 0?s:i.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:Fr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var z9=()=>{},JUe=yt([FT,Ya,DT,PT,Fa],S4),eBe=yt([Ya,v4,w4,z9,JUe,z9,Sr,Fa],_4),Ore=yt([Ya,Sr,FT,ZUe,oS,Fa,eBe],k4),tBe=yt([Ore,vy,wp],P4),nBe=yt([Ya,Ore,tBe,Fa],A4);yt([wp,nBe],vne);var rBe={radiusAxis:{},angleAxis:{}},Ire=Fo({name:"polarAxis",initialState:rBe,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:xst,removeRadiusAxis:yst,addAngleAxis:vst,removeAngleAxis:wst}=Ire.actions,aBe=Ire.reducer;function zre(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function U9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function B9(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?U9(Object(n),!0).forEach(function(r){iBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):U9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function iBe(t,e,n){return(e=sBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function sBe(t){var e=oBe(t,"string");return typeof e=="symbol"?e:e+""}function oBe(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 lBe=(t,e)=>e,V4=yt([Lre,lBe],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),cBe=[],G4=(t,e,n)=>n?.length===0?cBe:n,Ure=yt([xT,V4,G4],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var i;if(e?.data!=null&&e.data.length>0?i=e.data:i=r,(!i||!i.length)&&n!=null&&(i=n.map(s=>B9(B9({},e.presentationProps),s.props))),i!=null)return i}}),dBe=yt([Ure,V4,G4],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,i)=>{var s,o=Fr(r,e.nameKey,e.name),l;return n!=null&&(s=n[i])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[i].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:bp(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),uBe=yt([Ure,V4,G4,Ti],(t,e,n,r)=>{if(!(e==null||t==null))return m8e({offset:r,pieSettings:e,displayedData:t,cells:n})}),lD={exports:{}},$r={};var H9;function mBe(){if(H9)return $r;H9=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=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"),d=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.view_transition"),f=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 i:case r:case c:case d:case p:return v;default:switch(v=v&&v.$$typeof,v){case o:case l:case m:case u:return v;case s:return v;default:return g}}case e:return g}}}return $r.ContextConsumer=s,$r.ContextProvider=o,$r.Element=t,$r.ForwardRef=l,$r.Fragment=n,$r.Lazy=m,$r.Memo=u,$r.Portal=e,$r.Profiler=i,$r.StrictMode=r,$r.Suspense=c,$r.SuspenseList=d,$r.isContextConsumer=function(v){return x(v)===s},$r.isContextProvider=function(v){return x(v)===o},$r.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===t},$r.isForwardRef=function(v){return x(v)===l},$r.isFragment=function(v){return x(v)===n},$r.isLazy=function(v){return x(v)===m},$r.isMemo=function(v){return x(v)===u},$r.isPortal=function(v){return x(v)===e},$r.isProfiler=function(v){return x(v)===i},$r.isStrictMode=function(v){return x(v)===r},$r.isSuspense=function(v){return x(v)===c},$r.isSuspenseList=function(v){return x(v)===d},$r.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===i||v===r||v===c||v===d||typeof v=="object"&&v!==null&&(v.$$typeof===m||v.$$typeof===u||v.$$typeof===o||v.$$typeof===s||v.$$typeof===l||v.$$typeof===f||v.getModuleId!==void 0)},$r.typeOf=x,$r}var q9;function hBe(){return q9||(q9=1,lD.exports=mBe()),lD.exports}var pBe=hBe(),$9=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",V9=null,cD=null,Bre=t=>{if(t===V9&&Array.isArray(cD))return cD;var e=[];return w.Children.forEach(t,n=>{Ca(n)||(pBe.isFragment(n)?e=e.concat(Bre(n.props.children)):e.push(n))}),cD=e,V9=t,e};function W4(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(i=>$9(i)):r=[$9(e)],Bre(t).forEach(i=>{var s=sg(i,"type.displayName")||sg(i,"type.name");s&&r.indexOf(s)!==-1&&n.push(i)}),n}var K4=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,dD={},G9;function fBe(){return G9||(G9=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 i=n[Symbol.toStringTag];return i==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${i}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})(dD)),dD}var uD,W9;function gBe(){return W9||(W9=1,uD=fBe().isPlainObject),uD}var bBe=gBe();const xBe=mc(bBe);var K9,X9,Y9,Q9,Z9;function J9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function eW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?J9(Object(n),!0).forEach(function(r){yBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):J9(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function yBe(t,e,n){return(e=vBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vBe(t){var e=wBe(t,"string");return typeof e=="symbol"?e:e+""}function wBe(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 gC(){return gC=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},gC.apply(null,arguments)}function Ov(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var tW=(t,e,n,r,i)=>{var s=n-r,o;return o=Ba(K9||(K9=Ov(["M ",",",""])),t,e),o+=Ba(X9||(X9=Ov(["L ",",",""])),t+n,e),o+=Ba(Y9||(Y9=Ov(["L ",",",""])),t+n-s/2,e+i),o+=Ba(Q9||(Q9=Ov(["L ",",",""])),t+n-s/2-r,e+i),o+=Ba(Z9||(Z9=Ov(["L ",","," Z"])),t,e),o},SBe={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},_Be=t=>{var e=Da(t,SBe),{x:n,y:r,upperWidth:i,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:d,animationBegin:u,isUpdateAnimationActive:m}=e,p=w.useRef(null),[f,x]=w.useState(-1),v=w.useRef(i),g=w.useRef(s),b=w.useRef(o),_=w.useRef(n),C=w.useRef(r),P=fy(t,"trapezoid-");if(w.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var L=p.current.getTotalLength();L&&x(L)}catch{}},[]),n!==+n||r!==+r||i!==+i||s!==+s||o!==+o||i===0&&s===0||o===0)return null;var N=_r("recharts-trapezoid",l);if(!m)return w.createElement("g",null,w.createElement("path",gC({},ys(e),{className:N,d:tW(n,r,i,s,o)})));var A=v.current,T=g.current,F=b.current,k=_.current,D=C.current,H="0px ".concat(f===-1?1:f,"px"),z="".concat(f,"px 0px"),X=cte(["strokeDasharray"],d,c);return w.createElement(py,{animationId:P,key:P,canBegin:f>0,duration:d,easing:c,isActive:m,begin:u},L=>{var ne=Dr(A,i,L),ie=Dr(T,s,L),ee=Dr(F,o,L),ue=Dr(k,n,L),le=Dr(D,r,L);p.current&&(v.current=ne,g.current=ie,b.current=ee,_.current=ue,C.current=le);var oe=L>0?{transition:X,strokeDasharray:z}:{strokeDasharray:H};return w.createElement("path",gC({},ys(e),{className:N,d:tW(ue,le,ne,ie,ee),ref:p,style:eW(eW({},oe),e.style)}))})},kBe=["option","shapeType","activeClassName"];function NBe(t,e){if(t==null)return{};var n,r,i=CBe(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)&&(i[n]=t[n])}return i}function CBe(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 nW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).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?nW(Object(n),!0).forEach(function(r){PBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):nW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function PBe(t,e,n){return(e=TBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function TBe(t){var e=ABe(t,"string");return typeof e=="symbol"?e:e+""}function ABe(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 jBe(t,e){return bC(bC({},e),t)}function MBe(t,e){return t==="symbols"}function rW(t){var{shapeType:e,elementProps:n}=t;switch(e){case"rectangle":return w.createElement(hte,n);case"trapezoid":return w.createElement(_Be,n);case"sector":return w.createElement(bte,n);case"symbols":if(MBe(e))return w.createElement(fI,n);break;case"curve":return w.createElement(yx,n);default:return null}}function EBe(t){return w.isValidElement(t)?t.props:t}function X4(t){var{option:e,shapeType:n,activeClassName:r="recharts-active-shape"}=t,i=NBe(t,kBe),s;if(w.isValidElement(e))s=w.cloneElement(e,bC(bC({},i),EBe(e)));else if(typeof e=="function")s=e(i,i.index);else if(xBe(e)&&typeof e!="boolean"){var o=jBe(e,i);s=w.createElement(rW,{shapeType:n,elementProps:o})}else{var l=i;s=w.createElement(rW,{shapeType:n,elementProps:l})}return i.isActive?w.createElement(Ea,{className:r},s):s}var Y4=(t,e,n)=>{var r=ia();return(i,s)=>o=>{t?.(i,s,o),r(Yne({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}},Q4=t=>{var e=ia();return(n,r)=>i=>{t?.(n,r,i),e(O4e())}},Z4=(t,e,n)=>{var r=ia();return(i,s)=>o=>{t?.(i,s,o),r(I4e({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}};function RT(t){var{tooltipEntrySettings:e}=t,n=ia(),r=Ai(),i=w.useRef(null);return w.useLayoutEffect(()=>{r||(i.current===null?n(D4e(e)):i.current!==e&&n(F4e({prev:i.current,next:e})),i.current=e)},[e,n,r]),w.useLayoutEffect(()=>()=>{i.current&&(n(R4e(i.current)),i.current=null)},[n]),null}function J4(t){var{legendPayload:e}=t,n=ia(),r=Ai(),i=w.useRef(null);return w.useLayoutEffect(()=>{r||(i.current===null?n(ate(e)):i.current!==e&&n(ite({prev:i.current,next:e})),i.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{i.current&&(n(ste(i.current)),i.current=null)},[n]),null}function DBe(t){var{legendPayload:e}=t,n=ia(),r=un(Sr),i=w.useRef(null);return w.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(i.current===null?n(ate(e)):i.current!==e&&n(ite({prev:i.current,next:e})),i.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{i.current&&(n(ste(i.current)),i.current=null)},[n]),null}var mD,FBe=()=>{var[t]=w.useState(()=>ew("uid-"));return t},RBe=(mD=Dde.useId)!==null&&mD!==void 0?mD:FBe;function LBe(t,e){var n=RBe();return e||(t?"".concat(t,"-").concat(n):n)}var OBe=w.createContext(void 0),LT=t=>{var{id:e,type:n,children:r}=t,i=LBe("recharts-".concat(n),e);return w.createElement(OBe.Provider,{value:i},r(i))},IBe={cartesianItems:[],polarItems:[]},Hre=Fo({name:"graphicalItems",initialState:IBe,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:Sa()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,i=Ic(t).cartesianItems.indexOf(n);i>-1&&(t.cartesianItems[i]=r)},prepare:Sa()},removeCartesianGraphicalItem:{reducer(t,e){var n=Ic(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:Sa()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:Sa()},removePolarGraphicalItem:{reducer(t,e){var n=Ic(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:Sa()}}}),{addCartesianGraphicalItem:zBe,replaceCartesianGraphicalItem:UBe,removeCartesianGraphicalItem:BBe,addPolarGraphicalItem:HBe,removePolarGraphicalItem:qBe}=Hre.actions,$Be=Hre.reducer,VBe=t=>{var e=ia(),n=w.useRef(null);return w.useLayoutEffect(()=>{n.current===null?e(zBe(t)):n.current!==t&&e(UBe({prev:n.current,next:t})),n.current=t},[e,t]),w.useLayoutEffect(()=>()=>{n.current&&(e(BBe(n.current)),n.current=null)},[e]),null},ez=w.memo(VBe);function GBe(t){var e=ia();return w.useLayoutEffect(()=>(e(HBe(t)),()=>{e(qBe(t))}),[e,t]),null}var WBe=["key"],KBe=["onMouseEnter","onClick","onMouseLeave"],XBe=["id"],YBe=["id"];function aW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ha(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?aW(Object(n),!0).forEach(function(r){QBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):aW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function QBe(t,e,n){return(e=ZBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ZBe(t){var e=JBe(t,"string");return typeof e=="symbol"?e:e+""}function JBe(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 up(){return up=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},up.apply(null,arguments)}function OT(t,e){if(t==null)return{};var n,r,i=e8e(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)&&(i[n]=t[n])}return i}function e8e(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 t8e(t){var e=w.useMemo(()=>W4(t.children,Gx),[t.children]),n=un(r=>dBe(r,t.id,e));return n==null?null:w.createElement(DBe,{legendPayload:n})}var n8e=w.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:i,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:r.map(p=>p.tooltipPayload),getPosition:p=>{var f;return(f=r[Number(p)])===null||f===void 0?void 0:f.tooltipPosition},settings:{stroke:i,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:bp(l,e),hide:c,type:d,color:o,unit:"",graphicalItemId:u}};return w.createElement(RT,{tooltipEntrySettings:m})}),r8e=(t,e)=>t>e?"start":t<e?"end":"middle",a8e=(t,e,n)=>Ds(typeof e=="function"?e(t):e,n,n*.8),i8e=(t,e,n)=>{var{top:r,left:i,width:s,height:o}=e,l=pte(s,o),c=i+Ds(t.cx,s,s/2),d=r+Ds(t.cy,o,o/2),u=Ds(t.innerRadius,l,0),m=a8e(n,t.outerRadius,l),p=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:d,innerRadius:u,outerRadius:m,maxRadius:p}},s8e=(t,e)=>{var n=Bi(e-t),r=Math.min(Math.abs(e-t),360);return n*r},o8e=(t,e)=>{if(w.isValidElement(t))return w.cloneElement(t,e);if(typeof t=="function")return t(e);var n=_r("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,i=OT(e,WBe);return w.createElement(yx,up({},i,{type:"linear",className:n}))},l8e=(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 i=_r("recharts-pie-label-text",zre(t));return w.createElement(MT,up({},e,{alignmentBaseline:"middle",className:i}),r)};function c8e(t){var{sectors:e,props:n,showLabels:r}=t,{label:i,labelLine:s,dataKey:o}=n;if(!r||!i||!e)return null;var l=no(n),c=ag(i),d=ag(s),u=typeof i=="object"&&"offsetRadius"in i&&typeof i.offsetRadius=="number"&&i.offsetRadius||20,m=e.map((p,f)=>{var x=(p.startAngle+p.endAngle)/2,v=hi(p.cx,p.cy,p.outerRadius+u,x),g=Ha(Ha(Ha(Ha({},l),p),{},{stroke:"none"},c),{},{index:f,textAnchor:r8e(v.x,p.cx)},v),b=Ha(Ha(Ha(Ha({},l),p),{},{fill:"none",stroke:p.fill},d),{},{index:f,points:[hi(p.cx,p.cy,p.outerRadius,x),v],key:"line"});return w.createElement(Os,{zIndex:Ga.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(f)},w.createElement(Ea,null,s&&o8e(s,b),l8e(i,g,Fr(p,o))))});return w.createElement(Ea,{className:"recharts-pie-labels"},m)}function d8e(t){var{sectors:e,props:n,showLabels:r}=t,{label:i}=n;return typeof i=="object"&&i!=null&&"position"in i?w.createElement(ET,{label:i}):w.createElement(c8e,{sectors:e,props:n,showLabels:r})}function u8e(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:i,shape:s,id:o}=t,l=un(dp),c=un(I4),d=un(_ze),{onMouseEnter:u,onClick:m,onMouseLeave:p}=i,f=OT(i,KBe),x=Y4(u,i.dataKey,o),v=Q4(p),g=Z4(m,i.dataKey,o);return e==null||e.length===0?null:w.createElement(w.Fragment,null,e.map((b,_)=>{if(b?.startAngle===0&&b?.endAngle===0&&e.length!==1)return null;var C=d==null||d===o,P=String(_)===l&&(c==null||i.dataKey===c)&&C,N=l?r:null,A=n&&P?n:N,T=Ha(Ha({},b),{},{stroke:b.stroke,tabIndex:-1,[$ee]:_,[Vee]:o});return w.createElement(Ea,up({key:"sector-".concat(b?.startAngle,"-").concat(b?.endAngle,"-").concat(b.midAngle,"-").concat(_),tabIndex:-1,className:"recharts-pie-sector"},Xw(f,b,_),{onMouseEnter:x(b,_),onMouseLeave:v(b,_),onClick:g(b,_)}),w.createElement(X4,up({option:s??A,index:_,shapeType:"sector",isActive:P},T)))}))}function m8e(t){var e,{pieSettings:n,displayedData:r,cells:i,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:d,nameKey:u,tooltipType:m}=n,p=Math.abs(n.minAngle),f=s8e(l,c),x=Math.abs(f),v=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,g=r.filter(A=>Fr(A,d,0)!==0).length,b=(x>=360?g:g-1)*v,_=x-g*p-b,C=r.reduce((A,T)=>{var F=Fr(T,d,0);return A+(an(F)?F:0)},0),P;if(C>0){var N;P=r.map((A,T)=>{var F=Fr(A,d,0),k=Fr(A,u,T),D=i8e(n,s,A),H=(an(F)?F:0)/C,z,X=Ha(Ha({},A),i&&i[T]&&i[T].props);T?z=N.endAngle+Bi(f)*v*(F!==0?1:0):z=l;var L=z+Bi(f)*((F!==0?p:0)+H*_),ne=(z+L)/2,ie=(D.innerRadius+D.outerRadius)/2,ee=[{name:k,value:F,payload:X,dataKey:d,type:m,graphicalItemId:n.id}],ue=hi(D.cx,D.cy,ie,ne);return N=Ha(Ha(Ha(Ha({},n.presentationProps),{},{percent:H,cornerRadius:typeof o=="string"?parseFloat(o):o,name:k,tooltipPayload:ee,midAngle:ne,middleRadius:ie,tooltipPosition:ue},X),D),{},{value:F,dataKey:d,startAngle:z,endAngle:L,payload:X,paddingAngle:Bi(f)*v}),N})}return P}function h8e(t){var{showLabels:e,sectors:n,children:r}=t,i=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(WUe,{value:e?i:void 0},r)}function p8e(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:d,inactiveShape:u,onAnimationStart:m,onAnimationEnd:p}=e,f=fy(e,"recharts-pie-"),x=n.current,[v,g]=w.useState(!1),b=w.useCallback(()=>{typeof p=="function"&&p(),g(!1)},[p]),_=w.useCallback(()=>{typeof m=="function"&&m(),g(!0)},[m]);return w.createElement(h8e,{showLabels:!v,sectors:i},w.createElement(py,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:_,onAnimationEnd:b,key:f},C=>{var P,N=[],A=i&&i[0],T=(P=A?.startAngle)!==null&&P!==void 0?P:0;return i?.forEach((F,k)=>{var D=x&&x[k],H=k>0?sg(F,"paddingAngle",0):0;if(D){var z=Dr(D.endAngle-D.startAngle,F.endAngle-F.startAngle,C),X=Ha(Ha({},F),{},{startAngle:T+H,endAngle:T+z+H});N.push(X),T=X.endAngle}else{var{endAngle:L,startAngle:ne}=F,ie=Dr(0,L-ne,C),ee=Ha(Ha({},F),{},{startAngle:T+H,endAngle:T+ie+H});N.push(ee),T=ee.endAngle}}),n.current=N,w.createElement(Ea,null,w.createElement(u8e,{sectors:N,activeShape:d,inactiveShape:u,allOtherPieProps:e,shape:e.shape,id:r}))}),w.createElement(d8e,{showLabels:!v,sectors:i,props:e}),e.children)}var f8e={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:Ga.area};function g8e(t){var{id:e}=t,n=OT(t,XBe),{hide:r,className:i,rootTabIndex:s}=t,o=w.useMemo(()=>W4(t.children,Gx),[t.children]),l=un(u=>uBe(u,e,o)),c=w.useRef(null),d=_r("recharts-pie",i);return r||l==null?(c.current=null,w.createElement(Ea,{tabIndex:s,className:d})):w.createElement(Os,{zIndex:t.zIndex},w.createElement(n8e,{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(Ea,{tabIndex:s,className:d},w.createElement(p8e,{props:Ha(Ha({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function QR(t){var e=Da(t,f8e),{id:n}=e,r=OT(e,YBe),i=no(r);return w.createElement(LT,{id:n,type:"pie"},s=>w.createElement(w.Fragment,null,w.createElement(GBe,{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:i,maxRadius:e.maxRadius}),w.createElement(t8e,up({},r,{id:s})),w.createElement(g8e,up({},r,{id:s}))))}QR.displayName="Pie";var b8e=["points"];function iW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function hD(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?iW(Object(n),!0).forEach(function(r){x8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):iW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function x8e(t,e,n){return(e=y8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y8e(t){var e=v8e(t,"string");return typeof e=="symbol"?e:e+""}function v8e(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 xC(){return xC=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},xC.apply(null,arguments)}function w8e(t,e){if(t==null)return{};var n,r,i=S8e(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)&&(i[n]=t[n])}return i}function S8e(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 _8e(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 i=_r(r,typeof e!="boolean"?e.className:""),s=n??{},{points:o}=s,l=w8e(s,b8e);return w.createElement(Rre,xC({},l,{className:i}))}function k8e(t,e){return t==null?!1:e?!0:t.length===1}function qre(t){var{points:e,dot:n,className:r,dotClassName:i,dataKey:s,baseProps:o,needClip:l,clipPathId:c,zIndex:d=Ga.scatter}=t;if(!k8e(e,n))return null;var u=K4(n),m=GMe(n),p=e.map((x,v)=>{var g,b,_=hD(hD(hD({r:3},o),m),{},{index:v,cx:(g=x.x)!==null&&g!==void 0?g:void 0,cy:(b=x.y)!==null&&b!==void 0?b:void 0,dataKey:s,value:x.value,payload:x.payload,points:e});return w.createElement(_8e,{key:"dot-".concat(v),option:n,dotProps:_,className:i})}),f={};return l&&c!=null&&(f.clipPath="url(#clipPath-".concat(u?"":"dots-").concat(c,")")),w.createElement(Os,{zIndex:d},w.createElement(Ea,xC({className:r},f),p))}function sW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function oW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?sW(Object(n),!0).forEach(function(r){N8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):sW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function N8e(t,e,n){return(e=C8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function C8e(t){var e=P8e(t,"string");return typeof e=="symbol"?e:e+""}function P8e(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 $re=0,T8e={xAxis:{},yAxis:{},zAxis:{}},Vre=Fo({name:"cartesianAxis",initialState:T8e,reducers:{addXAxis:{reducer(t,e){t.xAxis[e.payload.id]=e.payload},prepare:Sa()},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:Sa()},removeXAxis:{reducer(t,e){delete t.xAxis[e.payload.id]},prepare:Sa()},addYAxis:{reducer(t,e){t.yAxis[e.payload.id]=e.payload},prepare:Sa()},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:Sa()},removeYAxis:{reducer(t,e){delete t.yAxis[e.payload.id]},prepare:Sa()},addZAxis:{reducer(t,e){t.zAxis[e.payload.id]=e.payload},prepare:Sa()},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:Sa()},removeZAxis:{reducer(t,e){delete t.zAxis[e.payload.id]},prepare:Sa()},updateYAxisWidth(t,e){var{id:n,width:r}=e.payload,i=t.yAxis[n];if(i){var s,o=i.widthHistory||[];if(o.length===3&&o[0]===o[2]&&r===o[1]&&r!==i.width&&Math.abs(r-((s=o[0])!==null&&s!==void 0?s:0))<=1)return;var l=[...o,r].slice(-3);t.yAxis[n]=oW(oW({},i),{},{width:r,widthHistory:l})}}}}),{addXAxis:A8e,replaceXAxis:j8e,removeXAxis:M8e,addYAxis:E8e,replaceYAxis:D8e,removeYAxis:F8e,addZAxis:Sst,replaceZAxis:_st,removeZAxis:kst,updateYAxisWidth:R8e}=Vre.actions,L8e=Vre.reducer,O8e=yt([Ti],t=>({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),I8e=yt([O8e,bm,xm],(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)}}),IT=()=>un(I8e),z8e=()=>un(Tze);function lW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function pD(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?lW(Object(n),!0).forEach(function(r){U8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function U8e(t,e,n){return(e=B8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function B8e(t){var e=H8e(t,"string");return typeof e=="symbol"?e:e+""}function H8e(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 q8e=t=>{var{point:e,childIndex:n,mainColor:r,activeDot:i,dataKey:s,clipPath:o}=t;if(i===!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=pD(pD(pD({},l),ag(i)),gI(i)),d;return w.isValidElement(i)?d=w.cloneElement(i,c):typeof i=="function"?d=i(c):d=w.createElement(Rre,c),w.createElement(Ea,{className:"recharts-active-dot",clipPath:o},d)};function ZR(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:i,clipPath:s,zIndex:o=Ga.activeDot}=t,l=un(dp),c=z8e();if(e==null||c==null)return null;var d=e.find(u=>c.includes(u.payload));return Ca(d)?null:w.createElement(Os,{zIndex:o},w.createElement(q8e,{point:d,childIndex:Number(l),mainColor:n,dataKey:i,activeDot:r,clipPath:s}))}var cW=(t,e,n)=>{var r=n??t;if(!Ca(r))return Ds(r,e,0)},$8e=(t,e,n)=>{var r={},i=t.filter(_T),s=t.filter(d=>d.stackId==null),o=i.reduce((d,u)=>{var m=d[u.stackId];return m==null&&(m=[]),m.push(u),d[u.stackId]=m,d},r),l=Object.entries(o).map(d=>{var u,[m,p]=d,f=p.map(v=>v.dataKey),x=cW(e,n,(u=p[0])===null||u===void 0?void 0:u.barSize);return{stackId:m,dataKeys:f,barSize:x}}),c=s.map(d=>{var u=[d.dataKey].filter(p=>p!=null),m=cW(e,n,d.barSize);return{stackId:void 0,dataKeys:u,barSize:m}});return[...l,...c]};function dW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Y1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?dW(Object(n),!0).forEach(function(r){V8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):dW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function V8e(t,e,n){return(e=G8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function G8e(t){var e=W8e(t,"string");return typeof e=="symbol"?e:e+""}function W8e(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 K8e(t,e,n,r,i){var s,o=r.length;if(!(o<1)){var l=Ds(t,n,0,!0),c,d=[];if(Wn((s=r[0])===null||s===void 0?void 0:s.barSize)){var u=!1,m=n/o,p=r.reduce((_,C)=>_+(C.barSize||0),0);p+=(o-1)*l,p>=n&&(p-=(o-1)*l,l=0),p>=n&&m>0&&(u=!0,m*=.9,p=o*m);var f=(n-p)/2>>0,x={offset:f-l,size:0};c=r.reduce((_,C)=>{var P,N={stackId:C.stackId,dataKeys:C.dataKeys,position:{offset:x.offset+x.size+l,size:u?m:(P=C.barSize)!==null&&P!==void 0?P:0}},A=[..._,N];return x=N.position,A},d)}else{var v=Ds(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 b=Wn(i)?Math.min(g,i):g;c=r.reduce((_,C,P)=>[..._,{stackId:C.stackId,dataKeys:C.dataKeys,position:{offset:v+(g+l)*P+(g-b)/2,size:b}}],d)}return c}}var X8e=(t,e,n,r,i,s,o)=>{var l=Ca(o)?e:o,c=K8e(n,r,i!==s?i:s,t,l);return i!==s&&c!=null&&(c=c.map(d=>Y1(Y1({},d),{},{position:Y1(Y1({},d.position),{},{offset:d.position.offset-i/2})}))),c},Y8e=(t,e)=>{var n=ST(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var i=t[r];if(i){var{stackedData:s}=i;if(s)return s.find(o=>o.key===n)}}}},Q8e=(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 Z8e(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&Wn(t.zIndex)?t.zIndex:e}var Gre=t=>{var{chartData:e}=t,n=ia(),r=Ai();return w.useEffect(()=>r?()=>{}:(n(g9(e)),()=>{n(g9(void 0))}),[e,n,r]),null},uW={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},Wre=Fo({name:"brush",initialState:uW,reducers:{setBrushSettings(t,e){return e.payload==null?uW:e.payload}}}),{setBrushSettings:Nst}=Wre.actions,J8e=Wre.reducer,eHe=(t,e)=>{var{x:n,y:r}=t,{x:i,y:s}=e;return{x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},tHe=t=>{var{x1:e,y1:n,x2:r,y2:i}=t;return eHe({x:e,y:n},{x:r,y:i})};function nHe(t){return(t%180+180)%180}var rHe=function(e){var{width:n,height:r}=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=nHe(i),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)},aHe={dots:[],areas:[],lines:[]},Kre=Fo({name:"referenceElements",initialState:aHe,reducers:{addDot:(t,e)=>{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Ic(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=Ic(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=Ic(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:Cst,removeDot:Pst,addArea:Tst,removeArea:Ast,addLine:iHe,removeLine:sHe}=Kre.actions,oHe=Kre.reducer,Xre=w.createContext(void 0),lHe=t=>{var{children:e}=t,[n]=w.useState("".concat(ew("recharts"),"-clip")),r=IT();if(r==null)return null;var{x:i,y:s,width:o,height:l}=r;return w.createElement(Xre.Provider,{value:n},w.createElement("defs",null,w.createElement("clipPath",{id:n},w.createElement("rect",{x:i,y:s,height:l,width:o}))),e)},cHe=()=>w.useContext(Xre);class dHe{constructor(e){var{x:n,y:r}=e;this.xAxisScale=n,this.yAxisScale=r}map(e,n){var r,i,{position:s}=n;return{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:0,y:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:0}}mapWithFallback(e,n){var r,i,{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:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:l}}isInRange(e){var{x:n,y:r}=e,i=n==null||this.xAxisScale.isInRange(n),s=r==null||this.yAxisScale.isInRange(r);return i&&s}}function mW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function hW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?mW(Object(n),!0).forEach(function(r){uHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):mW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function uHe(t,e,n){return(e=mHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mHe(t){var e=hHe(t,"string");return typeof e=="symbol"?e:e+""}function hHe(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 yC(){return yC=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},yC.apply(null,arguments)}var pHe=(t,e)=>{var n;if(w.isValidElement(t))n=w.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!Wn(e.x1)||!Wn(e.y1)||!Wn(e.x2)||!Wn(e.y2))return null;n=w.createElement("line",yC({},e,{className:"recharts-reference-line-line"}))}return n},fHe=(t,e,n,r,i,s)=>{var{x:o,width:l}=s,c=i.map(t,{position:n});if(!Wn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?d.reverse():d},gHe=(t,e,n,r,i,s)=>{var{y:o,height:l}=s,c=i.map(t,{position:n});if(!Wn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?d.reverse():d},bHe=(t,e,n,r)=>{var i=[r.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&i.some(s=>!r.isInRange(s))?null:i},xHe=(t,e,n,r,i,s,o)=>{var{x:l,y:c,segment:d,ifOverflow:u}=o,m=lc(l),p=lc(c);return p?fHe(c,u,r,s,e,n):m?gHe(l,u,r,i,t,n):d!=null&&d.length===2?bHe(d,u,r,new dHe({x:t,y:e})):null};function yHe(t){var e=ia();return w.useEffect(()=>(e(iHe(t)),()=>{e(sHe(t))})),null}function vHe(t){var{xAxisId:e,yAxisId:n,shape:r,className:i,ifOverflow:s}=t,o=Ai(),l=cHe(),c=un(T=>Bd(T,e)),d=un(T=>Hd(T,n)),u=un(T=>Vx(T,"xAxis",e,o)),m=un(T=>Vx(T,"yAxis",n,o)),p=Jw();if(!l||!p||c==null||d==null||u==null||m==null)return null;var f=xHe(u,m,p,t.position,c.orientation,d.orientation,t);if(!f)return null;var x=f[0],v=f[1];if(x==null||v==null)return null;var{x:g,y:b}=x,{x:_,y:C}=v,P=s==="hidden"?"url(#".concat(l,")"):void 0,N=hW(hW({clipPath:P},ys(t)),{},{x1:g,y1:b,x2:_,y2:C}),A=tHe({x1:g,y1:b,x2:_,y2:C});return w.createElement(Os,{zIndex:t.zIndex},w.createElement(Ea,{className:_r("recharts-reference-line",i)},pHe(r,N),w.createElement(jre,yC({},A,{lowerWidth:A.width,upperWidth:A.width}),w.createElement(Ere,{label:t.label}),t.children)))}var wHe={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:Ga.line};function t0(t){var e=Da(t,wHe);return w.createElement(w.Fragment,null,w.createElement(yHe,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),w.createElement(vHe,e))}t0.displayName="ReferenceLine";function Yre(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;r<t.length;r+=e){var i=t[r];i!==void 0&&n.push(i)}return n}function SHe(t,e,n){var r={width:t.width+e.width,height:t.height+e.height};return rHe(r,n)}function _He(t,e,n){var r=n==="width",{x:i,y:s,width:o,height:l}=t;return e===1?{start:r?i:s,end:r?i+o:s+l}:{start:r?i+o:s+l,end:r?i:s}}function pw(t,e,n,r,i){if(t*e<t*r||t*e>t*i)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-i)<=0}function kHe(t,e){return Yre(t,e+1)}function NHe(t,e,n,r,i){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,d=1,u=o,m=function(){var x=r?.[c];if(x===void 0)return{v:Yre(r,d)};var v=c,g,b=()=>(g===void 0&&(g=n(x,v)),g),_=x.coordinate,C=c===0||pw(t,_,b,u,l);C||(c=0,u=o,d+=1),C&&(u=_+t*(b()/2+i),c+=d)},p;d<=s.length;)if(p=m(),p)return p.v;return[]}function CHe(t,e,n,r,i){var s=(r||[]).slice(),o=s.length;if(o===0)return[];for(var{start:l,end:c}=e,d=1;d<=o;d++){for(var u=(o-1)%d,m=l,p=!0,f=function(){var P=r[v];if(P==null)return 0;var N=v,A,T=()=>(A===void 0&&(A=n(P,N)),A),F=P.coordinate,k=v===u||pw(t,F,T,m,c);if(!k)return p=!1,1;k&&(m=F+t*(T()/2+i))},x,v=u;v<o&&(x=f(),!(x!==0&&x===1));v+=d);if(p){for(var g=[],b=u;b<o;b+=d){var _=r[b];_!=null&&g.push(_)}return g}}return[]}function pW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ps(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?pW(Object(n),!0).forEach(function(r){PHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function PHe(t,e,n){return(e=THe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function THe(t){var e=AHe(t,"string");return typeof e=="symbol"?e:e+""}function AHe(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 jHe(t,e,n,r,i){for(var s=(r||[]).slice(),o=s.length,{start:l}=e,{end:c}=e,d=function(p){var f=s[p];if(f==null)return 1;var x=f,v,g=()=>(v===void 0&&(v=n(f,p)),v);if(p===o-1){var b=t*(x.coordinate+t*g()/2-c);s[p]=x=Ps(Ps({},x),{},{tickCoord:b>0?x.coordinate-b*t:x.coordinate})}else s[p]=x=Ps(Ps({},x),{},{tickCoord:x.coordinate});if(x.tickCoord!=null){var _=pw(t,x.tickCoord,g,l,c);_&&(c=x.tickCoord-t*(g()/2+i),s[p]=Ps(Ps({},x),{},{isShow:!0}))}},u=o-1;u>=0;u--)d(u);return s}function MHe(t,e,n,r,i,s){var o=(r||[]).slice(),l=o.length,{start:c,end:d}=e;if(s){var u=r[l-1];if(u!=null){var m=n(u,l-1),p=t*(u.coordinate+t*m/2-d);if(o[l-1]=u=Ps(Ps({},u),{},{tickCoord:p>0?u.coordinate-p*t:u.coordinate}),u.tickCoord!=null){var f=pw(t,u.tickCoord,()=>m,c,d);f&&(d=u.tickCoord-t*(m/2+i),o[l-1]=Ps(Ps({},u),{},{isShow:!0}))}}}for(var x=s?l-1:l,v=function(_){var C=o[_];if(C==null)return 1;var P=C,N,A=()=>(N===void 0&&(N=n(C,_)),N);if(_===0){var T=t*(P.coordinate-t*A()/2-c);o[_]=P=Ps(Ps({},P),{},{tickCoord:T<0?P.coordinate-T*t:P.coordinate})}else o[_]=P=Ps(Ps({},P),{},{tickCoord:P.coordinate});if(P.tickCoord!=null){var F=pw(t,P.tickCoord,A,c,d);F&&(c=P.tickCoord+t*(A()/2+i),o[_]=Ps(Ps({},P),{},{isShow:!0}))}},g=0;g<x;g++)v(g);return o}function tz(t,e,n){var{tick:r,ticks:i,viewBox:s,minTickGap:o,orientation:l,interval:c,tickFormatter:d,unit:u,angle:m}=t;if(!i||!i.length||!r)return[];if(an(c)||nS.isSsr){var p;return(p=kHe(i,an(c)?c:0))!==null&&p!==void 0?p:[]}var f=[],x=l==="top"||l==="bottom"?"width":"height",v=u&&x==="width"?b0(u,{fontSize:e,letterSpacing:n}):{width:0,height:0},g=(N,A)=>{var T=typeof d=="function"?d(N.value,A):N.value;return x==="width"?SHe(b0(T,{fontSize:e,letterSpacing:n}),v,m):b0(T,{fontSize:e,letterSpacing:n})[x]},b=i[0],_=i[1],C=i.length>=2&&b!=null&&_!=null?Bi(_.coordinate-b.coordinate):1,P=_He(s,C,x);return c==="equidistantPreserveStart"?NHe(C,P,g,i,o):c==="equidistantPreserveEnd"?CHe(C,P,g,i,o):(c==="preserveStart"||c==="preserveStartEnd"?f=MHe(C,P,g,i,o,c==="preserveStartEnd"):f=jHe(C,P,g,i,o),f.filter(N=>N.isShow))}var EHe=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:i=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(u=>{if(u){var m=u.getBoundingClientRect();m.width>o&&(o=m.width)}});var l=n?n.getBoundingClientRect().width:0,c=i+s,d=o+c+l+(n?r:0);return Math.round(d)}return 0},DHe=["axisLine","width","height","className","hide","ticks","axisType"];function FHe(t,e){if(t==null)return{};var n,r,i=RHe(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)&&(i[n]=t[n])}return i}function RHe(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 mg(){return mg=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},mg.apply(null,arguments)}function fW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ua(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?fW(Object(n),!0).forEach(function(r){LHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):fW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function LHe(t,e,n){return(e=OHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function OHe(t){var e=IHe(t,"string");return typeof e=="symbol"?e:e+""}function IHe(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 Ju={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:Ga.axis};function zHe(t){var{x:e,y:n,width:r,height:i,orientation:s,mirror:o,axisLine:l,otherSvgProps:c}=t;if(!l)return null;var d=Ua(Ua(Ua({},c),no(l)),{},{fill:"none"});if(s==="top"||s==="bottom"){var u=+(s==="top"&&!o||s==="bottom"&&o);d=Ua(Ua({},d),{},{x1:e,y1:n+u*i,x2:e+r,y2:n+u*i})}else{var m=+(s==="left"&&!o||s==="right"&&o);d=Ua(Ua({},d),{},{x1:e+m*r,y1:n,x2:e+m*r,y2:n+i})}return w.createElement("line",mg({},d,{className:_r("recharts-cartesian-axis-line",sg(l,"className"))}))}function UHe(t,e,n,r,i,s,o,l,c){var d,u,m,p,f,x,v=l?-1:1,g=t.tickSize||o,b=an(t.tickCoord)?t.tickCoord:t.coordinate;switch(s){case"top":d=u=t.coordinate,p=n+ +!l*i,m=p-v*g,x=m-v*c,f=b;break;case"left":m=p=t.coordinate,u=e+ +!l*r,d=u-v*g,f=d-v*c,x=b;break;case"right":m=p=t.coordinate,u=e+ +l*r,d=u+v*g,f=d+v*c,x=b;break;default:d=u=t.coordinate,p=n+ +l*i,m=p+v*g,x=m+v*c,f=b;break}return{line:{x1:d,y1:m,x2:u,y2:p},tick:{x:f,y:x}}}function BHe(t,e){switch(t){case"left":return e?"start":"end";case"right":return e?"end":"start";default:return"middle"}}function HHe(t,e){switch(t){case"left":case"right":return"middle";case"top":return e?"start":"end";default:return e?"end":"start"}}function qHe(t){var{option:e,tickProps:n,value:r}=t,i,s=_r(n.className,"recharts-cartesian-axis-tick-value");if(w.isValidElement(e))i=w.cloneElement(e,Ua(Ua({},n),{},{className:s}));else if(typeof e=="function")i=e(Ua(Ua({},n),{},{className:s}));else{var o="recharts-cartesian-axis-tick-value";typeof e!="boolean"&&(o=_r(o,zre(e))),i=w.createElement(MT,mg({},n,{className:o}),r)}return i}var $He=w.forwardRef((t,e)=>{var{ticks:n=[],tick:r,tickLine:i,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:d,orientation:u,mirror:m,x:p,y:f,width:x,height:v,tickSize:g,tickMargin:b,fontSize:_,letterSpacing:C,getTicksConfig:P,events:N,axisType:A}=t,T=tz(Ua(Ua({},P),{},{ticks:n}),_,C),F=BHe(u,m),k=HHe(u,m),D=no(P),H=ag(r),z={};typeof i=="object"&&(z=i);var X=Ua(Ua({},D),{},{fill:"none"},z),L=T.map(ee=>Ua({entry:ee},UHe(ee,p,f,x,v,u,g,m,b))),ne=L.map(ee=>{var{entry:ue,line:le}=ee;return w.createElement(Ea,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(ue.value,"-").concat(ue.coordinate,"-").concat(ue.tickCoord)},i&&w.createElement("line",mg({},X,le,{className:_r("recharts-cartesian-axis-tick-line",sg(i,"className"))})))}),ie=L.map((ee,ue)=>{var le,oe,{entry:W,tick:re}=ee,ce=Ua(Ua(Ua(Ua({verticalAnchor:k},D),{},{textAnchor:F,stroke:"none",fill:s},re),{},{index:ue,payload:W,visibleTicksCount:T.length,tickFormatter:o,padding:c},d),{},{angle:(le=(oe=d?.angle)!==null&&oe!==void 0?oe:D.angle)!==null&&le!==void 0?le:0}),xe=Ua(Ua({},ce),H);return w.createElement(Ea,mg({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(W.value,"-").concat(W.coordinate,"-").concat(W.tickCoord)},Xw(N,W,ue)),r&&w.createElement(qHe,{option:r,tickProps:xe,value:"".concat(typeof o=="function"?o(W.value,ue):W.value).concat(l||"")}))});return w.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(A,"-ticks")},ie.length>0&&w.createElement(Os,{zIndex:Ga.label},w.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(A,"-tick-labels"),ref:e},ie)),ne.length>0&&w.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(A,"-tick-lines")},ne))}),VHe=w.forwardRef((t,e)=>{var{axisLine:n,width:r,height:i,className:s,hide:o,ticks:l,axisType:c}=t,d=FHe(t,DHe),[u,m]=w.useState(""),[p,f]=w.useState(""),x=w.useRef(null);w.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var g;return EHe({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 b=g.getElementsByClassName("recharts-cartesian-axis-tick-value");x.current=b;var _=b[0];if(_){var C=window.getComputedStyle(_),P=C.fontSize,N=C.letterSpacing;(P!==u||N!==p)&&(m(P),f(N))}}},[u,p]);return o||r!=null&&r<=0||i!=null&&i<=0?null:w.createElement(Os,{zIndex:t.zIndex},w.createElement(Ea,{className:_r("recharts-cartesian-axis",s)},w.createElement(zHe,{x:t.x,y:t.y,width:r,height:i,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:no(t)}),w.createElement($He,{ref:v,axisType:c,events:d,fontSize:u,getTicksConfig:t,height:t.height,letterSpacing:p,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(jre,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},w.createElement(Ere,{label:t.label,labelRef:t.labelRef}),t.children)))}),nz=w.forwardRef((t,e)=>{var n=Da(t,Ju);return w.createElement(VHe,mg({},n,{ref:e}))});nz.displayName="CartesianAxis";var GHe=["x1","y1","x2","y2","key"],WHe=["offset"],KHe=["xAxisId","yAxisId"],XHe=["xAxisId","yAxisId"];function gW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function js(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gW(Object(n),!0).forEach(function(r){YHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function YHe(t,e,n){return(e=QHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function QHe(t){var e=ZHe(t,"string");return typeof e=="symbol"?e:e+""}function ZHe(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 _f(){return _f=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},_f.apply(null,arguments)}function vC(t,e){if(t==null)return{};var n,r,i=JHe(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)&&(i[n]=t[n])}return i}function JHe(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 e6e=t=>{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:i,width:s,height:o,ry:l}=t;return w.createElement("rect",{x:r,y:i,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Qre(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 i,{x1:s,y1:o,x2:l,y2:c,key:d}=n,u=vC(n,GHe),m=(i=no(u))!==null&&i!==void 0?i:{},{offset:p}=m,f=vC(m,WHe);r=w.createElement("line",_f({},f,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:d}))}return r}function t6e(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=vC(t,KHe),c=i.map((d,u)=>{var m=js(js({},l),{},{x1:e,y1:d,x2:e+n,y2:d,key:"line-".concat(u),index:u});return w.createElement(Qre,{key:"line-".concat(u),option:r,lineItemProps:m})});return w.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function n6e(t){var{y:e,height:n,vertical:r=!0,verticalPoints:i}=t;if(!r||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=vC(t,XHe),c=i.map((d,u)=>{var m=js(js({},l),{},{x1:d,y1:e,x2:d,y2:e+n,key:"line-".concat(u),index:u});return w.createElement(Qre,{option:r,lineItemProps:m,key:"line-".concat(u)})});return w.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function r6e(t){var{horizontalFill:e,fillOpacity:n,x:r,y:i,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var d=l.map(m=>Math.round(m+i-i)).sort((m,p)=>m-p);i!==d[0]&&d.unshift(0);var u=d.map((m,p)=>{var f=d[p+1],x=f==null,v=x?i+o-m:f-m;if(v<=0)return null;var g=p%e.length;return w.createElement("rect",{key:"react-".concat(p),y:m,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"},u)}function a6e(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:i,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var d=c.map(m=>Math.round(m+i-i)).sort((m,p)=>m-p);i!==d[0]&&d.unshift(0);var u=d.map((m,p)=>{var f=d[p+1],x=f==null,v=x?i+o-m:f-m;if(v<=0)return null;var g=p%n.length;return w.createElement("rect",{key:"react-".concat(p),x:m,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"},u)}var i6e=(t,e)=>{var{xAxis:n,width:r,height:i,offset:s}=t;return Uee(tz(js(js(js({},Ju),n),{},{ticks:Bee(n),viewBox:{x:0,y:0,width:r,height:i}})),s.left,s.left+s.width,e)},s6e=(t,e)=>{var{yAxis:n,width:r,height:i,offset:s}=t;return Uee(tz(js(js(js({},Ju),n),{},{ticks:Bee(n),viewBox:{x:0,y:0,width:r,height:i}})),s.top,s.top+s.height,e)},o6e={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Ga.grid};function kf(t){var e=AI(),n=jI(),r=Xee(),i=js(js({},Da(t,o6e)),{},{x:an(t.x)?t.x:r.left,y:an(t.y)?t.y:r.top,width:an(t.width)?t.width:r.width,height:an(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:d,height:u,syncWithTicks:m,horizontalValues:p,verticalValues:f}=i,x=Ai(),v=un(k=>a9(k,"xAxis",s,x)),g=un(k=>a9(k,"yAxis",o,x));if(!Dd(d)||!Dd(u)||!an(l)||!an(c))return null;var b=i.verticalCoordinatesGenerator||i6e,_=i.horizontalCoordinatesGenerator||s6e,{horizontalPoints:C,verticalPoints:P}=i;if((!C||!C.length)&&typeof _=="function"){var N=p&&p.length,A=_({yAxis:g?js(js({},g),{},{ticks:N?p:g.ticks}):void 0,width:e??d,height:n??u,offset:r},N?!0:m);$N(Array.isArray(A),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof A,"]")),Array.isArray(A)&&(C=A)}if((!P||!P.length)&&typeof b=="function"){var T=f&&f.length,F=b({xAxis:v?js(js({},v),{},{ticks:T?f:v.ticks}):void 0,width:e??d,height:n??u,offset:r},T?!0:m);$N(Array.isArray(F),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof F,"]")),Array.isArray(F)&&(P=F)}return w.createElement(Os,{zIndex:i.zIndex},w.createElement("g",{className:"recharts-cartesian-grid"},w.createElement(e6e,{fill:i.fill,fillOpacity:i.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),w.createElement(r6e,_f({},i,{horizontalPoints:C})),w.createElement(a6e,_f({},i,{verticalPoints:P})),w.createElement(t6e,_f({},i,{offset:r,horizontalPoints:C,xAxis:v,yAxis:g})),w.createElement(n6e,_f({},i,{offset:r,verticalPoints:P,xAxis:v,yAxis:g}))))}kf.displayName="CartesianGrid";var l6e={},Zre=Fo({name:"errorBars",initialState:l6e,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:i}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?i:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(i=>i.dataKey!==r.dataKey||i.direction!==r.direction))}}}),{addErrorBar:jst,replaceErrorBar:Mst,removeErrorBar:Est}=Zre.actions,c6e=Zre.reducer,d6e=["children"];function u6e(t,e){if(t==null)return{};var n,r,i=m6e(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)&&(i[n]=t[n])}return i}function m6e(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 h6e={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},p6e=w.createContext(h6e);function Jre(t){var{children:e}=t,n=u6e(t,d6e);return w.createElement(p6e.Provider,{value:n},e)}function zT(t,e){var n,r,i=un(d=>Bd(d,t)),s=un(d=>Hd(d,e)),o=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:Li.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:Oi.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function rz(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,i=IT(),{needClipX:s,needClipY:o,needClip:l}=zT(e,n);if(!l||!i)return null;var{x:c,y:d,width:u,height:m}=i;return w.createElement("clipPath",{id:"clipPath-".concat(r)},w.createElement("rect",{x:s?c:c-u/2,y:o?d:d-m/2,width:s?u:u*2,height:o?m:m*2}))}var eae=(t,e,n,r)=>Ld(t,"xAxis",e,r),tae=(t,e,n,r)=>Rd(t,"xAxis",e,r),nae=(t,e,n,r)=>Ld(t,"yAxis",n,r),rae=(t,e,n,r)=>Rd(t,"yAxis",n,r),f6e=yt([Sr,eae,nae,tae,rae],(t,e,n,r,i)=>Wc(t,"xAxis")?cp(e,r,!1):cp(n,i,!1)),g6e=(t,e,n,r,i)=>i;function b6e(t){return t.type==="line"}var x6e=yt([cS,g6e],(t,e)=>t.filter(b6e).find(n=>n.id===e)),y6e=yt([Sr,eae,nae,tae,rae,x6e,f6e,r4],(t,e,n,r,i,s,o,l)=>{var{chartData:c,dataStartIndex:d,dataEndIndex:u}=l;if(!(s==null||e==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:m,data:p}=s,f;if(p!=null&&p.length>0?f=p:f=c?.slice(d,u+1),f!=null)return iqe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:m,bandSize:o,displayedData:f})}});function aae(t){var e=ag(t),n=3,r=2;if(e!=null){var{r:i,strokeWidth:s}=e,o=Number(i),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 fD={exports:{}},gD={};var bW;function v6e(){if(bW)return gD;bW=1;var t=xg();function e(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var n=typeof Object.is=="function"?Object.is:e,r=t.useSyncExternalStore,i=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return gD.useSyncExternalStoreWithSelector=function(c,d,u,m,p){var f=i(null);if(f.current===null){var x={hasValue:!1,value:null};f.current=x}else x=f.current;f=o(function(){function g(N){if(!b){if(b=!0,_=N,N=m(N),p!==void 0&&x.hasValue){var A=x.value;if(p(A,N))return C=A}return C=N}if(A=C,n(_,N))return A;var T=m(N);return p!==void 0&&p(A,T)?(_=N,A):(_=N,C=T)}var b=!1,_,C,P=u===void 0?null:u;return[function(){return g(d())},P===null?void 0:function(){return g(P())}]},[d,u,m,p]);var v=r(c,f[0],f[1]);return s(function(){x.hasValue=!0,x.value=v},[v]),l(v),v},gD}var xW;function w6e(){return xW||(xW=1,fD.exports=v6e()),fD.exports}w6e();function S6e(t){t()}function _6e(){let t=null,e=null;return{clear(){t=null,e=null},notify(){S6e(()=>{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 i=e={callback:n,next:null,prev:e};return i.prev?i.prev.next=i:t=i,function(){!r||t===null||(r=!1,i.next?i.next.prev=i.prev:e=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}var yW={notify(){},get:()=>[]};function k6e(t,e){let n,r=yW,i=0,s=!1;function o(v){u();const g=r.subscribe(v);let b=!1;return()=>{b||(b=!0,g(),m())}}function l(){r.notify()}function c(){x.onStateChange&&x.onStateChange()}function d(){return s}function u(){i++,n||(n=t.subscribe(c),r=_6e())}function m(){i--,n&&i===0&&(n(),n=void 0,r.clear(),r=yW)}function p(){s||(s=!0,u())}function f(){s&&(s=!1,m())}const x={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:p,tryUnsubscribe:f,getListeners:()=>r};return x}var N6e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C6e=N6e(),P6e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",T6e=P6e(),A6e=()=>C6e||T6e?w.useLayoutEffect:w.useEffect,j6e=A6e();function vW(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function M6e(t,e){if(vW(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 i=0;i<n.length;i++)if(!Object.prototype.hasOwnProperty.call(e,n[i])||!vW(t[n[i]],e[n[i]]))return!1;return!0}var E6e=Symbol.for("react-redux-context"),D6e=typeof globalThis<"u"?globalThis:{};function F6e(){if(!w.createContext)return{};const t=D6e[E6e]??=new Map;let e=t.get(w.createContext);return e||(e=w.createContext(null),t.set(w.createContext,e)),e}var R6e=F6e();function L6e(t){const{children:e,context:n,serverState:r,store:i}=t,s=w.useMemo(()=>{const c=k6e(i);return{store:i,subscription:c,getServerState:r?()=>r:void 0}},[i,r]),o=w.useMemo(()=>i.getState(),[i]);j6e(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==i.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||R6e;return w.createElement(l.Provider,{value:s},e)}var O6e=L6e,I6e=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function z6e(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function fS(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(I6e.has(r)){if(t[r]==null&&e[r]==null)continue;if(!M6e(t[r],e[r]))return!1}else if(!z6e(t[r],e[r]))return!1;return!0}var U6e=["id"],B6e=["type","layout","connectNulls","needClip","shape"],H6e=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function fw(){return fw=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},fw.apply(null,arguments)}function wW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function gd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?wW(Object(n),!0).forEach(function(r){q6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):wW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function q6e(t,e,n){return(e=$6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $6e(t){var e=V6e(t,"string");return typeof e=="symbol"?e:e+""}function V6e(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 az(t,e){if(t==null)return{};var n,r,i=G6e(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)&&(i[n]=t[n])}return i}function G6e(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 W6e=t=>{var{dataKey:e,name:n,stroke:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:bp(n,e),payload:t}]},K6e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:gp,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:bp(o,e),hide:l,type:d,color:r,unit:c,graphicalItemId:u}};return w.createElement(RT,{tooltipEntrySettings:m})}),iae=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function X6e(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],i=0;i<e;++i)r=[...r,...n];return r}var Y6e=(t,e,n)=>{var r=n.reduce((f,x)=>f+x);if(!r)return iae(e,t);for(var i=Math.floor(t/r),s=t%r,o=e-t,l=[],c=0,d=0;c<n.length;d+=(u=n[c])!==null&&u!==void 0?u:0,++c){var u,m=n[c];if(m!=null&&d+m>s){l=[...n.slice(0,c),s-d];break}}var p=l.length%2===0?[0,o]:[o];return[...X6e(n,i),...l,...p].map(f=>"".concat(f,"px")).join(", ")};function Q6e(t){var{clipPathId:e,points:n,props:r}=t,{dot:i,dataKey:s,needClip:o}=r,{id:l}=r,c=az(r,U6e),d=no(c);return w.createElement(qre,{points:n,dot:i,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:d,needClip:o,clipPathId:e})}function Z6e(t){var{showLabels:e,children:n,points:r}=t,i=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 gd(gd({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return w.createElement($4,{value:e?i:void 0},n)}function SW(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:i,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:d,shape:u}=s,m=az(s,B6e),p=gd(gd({},ys(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:d?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:i??s.strokeDasharray});return w.createElement(w.Fragment,null,r?.length>1&&w.createElement(X4,fw({shapeType:"curve",option:u},p,{pathRef:n})),w.createElement(Q6e,{points:r,clipPathId:e,props:s}))}function J6e(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function eqe(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:i,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,animateNewValues:p,width:f,height:x,onAnimationEnd:v,onAnimationStart:g}=n,b=i.current,_=fy(o,"recharts-line-"),C=w.useRef(_),[P,N]=w.useState(!1),A=!P,T=w.useCallback(()=>{typeof v=="function"&&v(),N(!1)},[v]),F=w.useCallback(()=>{typeof g=="function"&&g(),N(!0)},[g]),k=J6e(r.current),D=w.useRef(0);C.current!==_&&(D.current=s.current,C.current=_);var H=D.current;return w.createElement(Z6e,{points:o,showLabels:A},n.children,w.createElement(py,{animationId:_,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:T,onAnimationStart:F,key:_},z=>{var X=Dr(H,k+H,z),L=Math.min(X,k),ne;if(c)if(l){var ie="".concat(l).split(/[,\s]+/gim).map(le=>parseFloat(le));ne=Y6e(L,k,ie)}else ne=iae(k,L);else ne=l==null?void 0:String(l);if(z>0&&k>0&&(i.current=o,s.current=Math.max(s.current,L)),b){var ee=b.length/o.length,ue=z===1?o:o.map((le,oe)=>{var W=Math.floor(oe*ee);if(b[W]){var re=b[W];return gd(gd({},le),{},{x:Dr(re.x,le.x,z),y:Dr(re.y,le.y,z)})}return p?gd(gd({},le),{},{x:Dr(f*2,le.x,z),y:Dr(x/2,le.y,z)}):gd(gd({},le),{},{x:le.x,y:le.y})});return i.current=ue,w.createElement(SW,{props:n,points:ue,clipPathId:e,pathRef:r,strokeDasharray:ne})}return w.createElement(SW,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:ne})}),w.createElement(ET,{label:n.label}))}function tqe(t){var{clipPathId:e,props:n}=t,r=w.useRef(null),i=w.useRef(0),s=w.useRef(null);return w.createElement(eqe,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:i,pathRef:s})}var nqe=(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:Fr(t.payload,e)}};class rqe extends w.Component{render(){var{hide:e,dot:n,points:r,className:i,xAxisId:s,yAxisId:o,top:l,left:c,width:d,height:u,id:m,needClip:p,zIndex:f}=this.props;if(e)return null;var x=_r("recharts-line",i),v=m,{r:g,strokeWidth:b}=aae(n),_=K4(n),C=g*2+b,P=p?"url(#clipPath-".concat(_?"":"dots-").concat(v,")"):void 0;return w.createElement(Os,{zIndex:f},w.createElement(Ea,{className:x},p&&w.createElement("defs",null,w.createElement(rz,{clipPathId:v,xAxisId:s,yAxisId:o}),!_&&w.createElement("clipPath",{id:"clipPath-dots-".concat(v)},w.createElement("rect",{x:c-C/2,y:l-C/2,width:d+C,height:u+C}))),w.createElement(Jre,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:nqe,errorBarOffset:0},w.createElement(tqe,{props:this.props,clipPathId:v}))),w.createElement(ZR,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:P}))}}var sae={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:Ga.line,type:"linear"};function aqe(t){var e=Da(t,sae),{activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:d,isAnimationActive:u,label:m,legendType:p,xAxisId:f,yAxisId:x,id:v}=e,g=az(e,H6e),{needClip:b}=zT(f,x),_=IT(),C=xp(),P=Ai(),N=un(D=>y6e(D,f,x,P,v));if(C!=="horizontal"&&C!=="vertical"||N==null||_==null)return null;var{height:A,width:T,x:F,y:k}=_;return w.createElement(rqe,fw({},g,{id:v,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:s,animationEasing:o,isAnimationActive:u,hide:d,label:m,legendType:p,xAxisId:f,yAxisId:x,points:N,layout:C,height:A,width:T,left:F,top:k,needClip:b}))}function iqe(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((d,u)=>{var m=Fr(d,o);if(e==="horizontal"){var p=qN({axis:n,ticks:i,bandSize:l,entry:d,index:u}),f=Ca(m)?null:r.scale.map(m);return{x:p,y:f??null,value:m,payload:d}}var x=Ca(m)?null:n.scale.map(m),v=qN({axis:r,ticks:s,bandSize:l,entry:d,index:u});return x==null||v==null?null:{x,y:v,value:m,payload:d}}).filter(Boolean)}function sqe(t){var e=Da(t,sae),n=Ai();return w.createElement(LT,{id:e.id,type:"line"},r=>w.createElement(w.Fragment,null,w.createElement(J4,{legendPayload:W6e(e)}),w.createElement(K6e,{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(ez,{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(aqe,fw({},e,{id:r}))))}var oae=w.memo(sqe,fS);oae.displayName="Line";function qd(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:$re}function $d(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:$re}var lae=(t,e,n)=>Ld(t,"xAxis",qd(t,e),n),cae=(t,e,n)=>Rd(t,"xAxis",qd(t,e),n),dae=(t,e,n)=>Ld(t,"yAxis",$d(t,e),n),uae=(t,e,n)=>Rd(t,"yAxis",$d(t,e),n),oqe=yt([Sr,lae,dae,cae,uae],(t,e,n,r,i)=>Wc(t,"xAxis")?cp(e,r,!1):cp(n,i,!1)),lqe=(t,e)=>e,mae=yt([cS,lqe],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),hae=t=>{var e=Sr(t),n=Wc(e,"xAxis");return n?"yAxis":"xAxis"},cqe=(t,e)=>{var n=hae(t);return n==="yAxis"?$d(t,e):qd(t,e)},dqe=(t,e,n)=>mC(t,hae(t),cqe(t,e),n),uqe=yt([mae,dqe],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:r}=t,i=ST(t);if(!(r==null||i==null)){var s=(n=e[r])===null||n===void 0?void 0:n.stackedData,o=s?.find(l=>l.key===i);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),mqe=yt([Sr,lae,dae,cae,uae,uqe,Zte,oqe,mae,_Ie],(t,e,n,r,i,s,o,l,c,d)=>{var{chartData:u,dataStartIndex:m,dataEndIndex:p}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||i==null||r.length===0||i.length===0||l==null)){var{data:f}=c,x;if(f&&f.length>0?x=f:x=u?.slice(m,p+1),x!=null)return Mqe({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataStartIndex:m,areaSettings:c,stackedData:s,displayedData:x,chartBaseValue:d,bandSize:l})}}),hqe=["id"],pqe=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function If(){return If=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},If.apply(null,arguments)}function pae(t,e){if(t==null)return{};var n,r,i=fqe(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)&&(i[n]=t[n])}return i}function fqe(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 _W(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function lx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_W(Object(n),!0).forEach(function(r){gqe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_W(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function gqe(t,e,n){return(e=bqe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function bqe(t){var e=xqe(t,"string");return typeof e=="symbol"?e:e+""}function xqe(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 wC(t,e){return t&&t!=="none"?t:e}var yqe=t=>{var{dataKey:e,name:n,stroke:r,fill:i,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:wC(r,i),value:bp(n,e),payload:t}]},vqe=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:gp,settings:{stroke:r,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:bp(o,e),hide:l,type:d,color:wC(r,s),unit:c,graphicalItemId:u}};return w.createElement(RT,{tooltipEntrySettings:m})});function wqe(t){var{clipPathId:e,points:n,props:r}=t,{needClip:i,dot:s,dataKey:o}=r,l=no(r);return w.createElement(qre,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:i,clipPathId:e})}function Sqe(t){var{showLabels:e,children:n,points:r}=t,i=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 lx(lx({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return w.createElement($4,{value:e?i:void 0},n)}function kW(t){var{points:e,baseLine:n,needClip:r,clipPathId:i,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:d,isRange:u}=s,{id:m}=s,p=pae(s,hqe),f=no(p),x=ys(p);return w.createElement(w.Fragment,null,e?.length>1&&w.createElement(Ea,{clipPath:r?"url(#clipPath-".concat(i,")"):void 0},w.createElement(yx,If({},x,{id:m,points:e,connectNulls:d,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&w.createElement(yx,If({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:e})),c!=="none"&&u&&w.createElement(yx,If({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:n}))),w.createElement(wqe,{points:e,props:p,clipPathId:i}))}function _qe(t){var e,n,{alpha:r,baseLine:i,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(!Wn(l)||!Wn(c))return null;var d=r*Math.abs(l-c),u=Math.max(...s.map(m=>m.x||0));return an(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.x||0),u)),an(u)?w.createElement("rect",{x:0,y:l<c?l:l-d,width:u+(o?parseInt("".concat(o),10):1),height:Math.floor(d)}):null}function kqe(t){var e,n,{alpha:r,baseLine:i,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(!Wn(l)||!Wn(c))return null;var d=r*Math.abs(l-c),u=Math.max(...s.map(m=>m.y||0));return an(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.y||0),u)),an(u)?w.createElement("rect",{x:l<c?l:l-d,y:0,width:d,height:Math.floor(u+(o?parseInt("".concat(o),10):1))}):null}function Nqe(t){var{alpha:e,layout:n,points:r,baseLine:i,strokeWidth:s}=t;return n==="vertical"?w.createElement(_qe,{alpha:e,points:r,baseLine:i,strokeWidth:s}):w.createElement(kqe,{alpha:e,points:r,baseLine:i,strokeWidth:s})}function Cqe(t){var{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s}=t,{points:o,baseLine:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,onAnimationStart:p,onAnimationEnd:f}=r,x=w.useMemo(()=>({points:o,baseLine:l}),[o,l]),v=fy(x,"recharts-area-"),g=MI(),[b,_]=w.useState(!1),C=!b,P=w.useCallback(()=>{typeof f=="function"&&f(),_(!1)},[f]),N=w.useCallback(()=>{typeof p=="function"&&p(),_(!0)},[p]);if(g==null)return null;var A=i.current,T=s.current;return w.createElement(Sqe,{showLabels:C,points:o},r.children,w.createElement(py,{animationId:v,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:P,onAnimationStart:N,key:v},F=>{if(A){var k=A.length/o.length,D=F===1?o:o.map((z,X)=>{var L=Math.floor(X*k);if(A[L]){var ne=A[L];return lx(lx({},z),{},{x:Dr(ne.x,z.x,F),y:Dr(ne.y,z.y,F)})}return z}),H;return an(l)?H=Dr(T,l,F):Ca(l)||Bc(l)?H=Dr(T,0,F):H=l.map((z,X)=>{var L=Math.floor(X*k);if(Array.isArray(T)&&T[L]){var ne=T[L];return lx(lx({},z),{},{x:Dr(ne.x,z.x,F),y:Dr(ne.y,z.y,F)})}return z}),F>0&&(i.current=D,s.current=H),w.createElement(kW,{points:D,baseLine:H,needClip:e,clipPathId:n,props:r})}return F>0&&(i.current=o,s.current=l),w.createElement(Ea,null,c&&w.createElement("defs",null,w.createElement("clipPath",{id:"animationClipPath-".concat(n)},w.createElement(Nqe,{alpha:F,points:o,baseLine:l,layout:g,strokeWidth:r.strokeWidth}))),w.createElement(Ea,{clipPath:"url(#animationClipPath-".concat(n,")")},w.createElement(kW,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),w.createElement(ET,{label:r.label}))}function Pqe(t){var{needClip:e,clipPathId:n,props:r}=t,i=w.useRef(null),s=w.useRef();return w.createElement(Cqe,{needClip:e,clipPathId:n,props:r,previousPointsRef:i,previousBaselineRef:s})}class Tqe extends w.PureComponent{render(){var{hide:e,dot:n,points:r,className:i,top:s,left:o,needClip:l,xAxisId:c,yAxisId:d,width:u,height:m,id:p,baseLine:f,zIndex:x}=this.props;if(e)return null;var v=_r("recharts-area",i),g=p,{r:b,strokeWidth:_}=aae(n),C=K4(n),P=b*2+_,N=l?"url(#clipPath-".concat(C?"":"dots-").concat(g,")"):void 0;return w.createElement(Os,{zIndex:x},w.createElement(Ea,{className:v},l&&w.createElement("defs",null,w.createElement(rz,{clipPathId:g,xAxisId:c,yAxisId:d}),!C&&w.createElement("clipPath",{id:"clipPath-dots-".concat(g)},w.createElement("rect",{x:o-P/2,y:s-P/2,width:u+P,height:m+P}))),w.createElement(Pqe,{needClip:l,clipPathId:g,props:this.props})),w.createElement(ZR,{points:r,mainColor:wC(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}),this.props.isRange&&Array.isArray(f)&&w.createElement(ZR,{points:f,mainColor:wC(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}))}}var fae={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:Ga.area};function Aqe(t){var e,n=Da(t,fae),{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:d,fillOpacity:u,hide:m,isAnimationActive:p,legendType:f,stroke:x,xAxisId:v,yAxisId:g}=n,b=pae(n,pqe),_=xp(),C=hre(),{needClip:P}=zT(v,g),N=Ai(),{points:A,isRange:T,baseLine:F}=(e=un(L=>mqe(L,t.id,N)))!==null&&e!==void 0?e:{},k=IT();if(_!=="horizontal"&&_!=="vertical"||k==null||C!=="AreaChart"&&C!=="ComposedChart")return null;var{height:D,width:H,x:z,y:X}=k;return!A||!A.length?null:w.createElement(Tqe,If({},b,{activeDot:r,animationBegin:i,animationDuration:s,animationEasing:o,baseLine:F,connectNulls:l,dot:c,fill:d,fillOpacity:u,height:D,hide:m,layout:_,isAnimationActive:p==="auto"?!nS.isSsr:p,isRange:T,legendType:f,needClip:P,points:A,stroke:x,width:H,left:z,top:X,xAxisId:v,yAxisId:g}))}var jqe=(t,e,n,r,i)=>{var s=n??e;if(an(s))return s;var o=t==="horizontal"?i:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),d=Math.min(l[0],l[1]);return s==="dataMin"?d: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 Mqe(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:i,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:d,dataStartIndex:u,xAxisTicks:m,yAxisTicks:p,bandSize:f}=t,x=i&&i.length,v=jqe(s,o,n,l,c),g=s==="horizontal",b=!1,_=d.map((P,N)=>{var A,T,F,k;if(x)k=i[u+N];else{var D=Fr(P,r);Array.isArray(D)?(k=D,b=!0):k=[v,D]}var H=(A=(T=k)===null||T===void 0?void 0:T[1])!==null&&A!==void 0?A:null,z=H==null||x&&!e&&Fr(P,r)==null;if(g){var X;return{x:qN({axis:l,ticks:m,bandSize:f,entry:P,index:N}),y:z?null:(X=c.scale.map(H))!==null&&X!==void 0?X:null,value:k,payload:P}}return{x:z?null:(F=l.scale.map(H))!==null&&F!==void 0?F:null,y:qN({axis:c,ticks:p,bandSize:f,entry:P,index:N}),value:k,payload:P}}),C;return x||b?C=_.map(P=>{var N,A=Array.isArray(P.value)?P.value[0]:null;if(g){var T;return{x:P.x,y:A!=null&&P.y!=null&&(T=c.scale.map(A))!==null&&T!==void 0?T:null,payload:P.payload}}return{x:A!=null&&(N=l.scale.map(A))!==null&&N!==void 0?N:null,y:P.y,payload:P.payload}}):C=g?c.scale.map(v):l.scale.map(v),{points:_,baseLine:C??0,isRange:b}}function Eqe(t){var e=Da(t,fae),n=Ai();return w.createElement(LT,{id:e.id,type:"area"},r=>w.createElement(w.Fragment,null,w.createElement(J4,{legendPayload:yqe(e)}),w.createElement(vqe,{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(ez,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:Hee(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),w.createElement(Aqe,If({},e,{id:r}))))}var gae=w.memo(Eqe,fS);gae.displayName="Area";var Dqe="Invariant failed";function Fqe(t,e){throw new Error(Dqe)}function JR(){return JR=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},JR.apply(null,arguments)}function SC(t){return w.createElement(X4,JR({shapeType:"rectangle",activeClassName:"recharts-active-bar"},t))}var Rqe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(r,i)=>{if(an(e))return e;var s=an(r)||Ca(r);return s?e(r,i):(s||Fqe(),n)}},Lqe=(t,e,n)=>n,Oqe=(t,e)=>e,gS=yt([cS,Oqe],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),Iqe=yt([gS],t=>t?.maxBarSize),zqe=(t,e,n,r)=>r,Uqe=yt([Sr,cS,qd,$d,Lqe],(t,e,n,r,i)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===i).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),Bqe=(t,e,n)=>{var r=Sr(t),i=qd(t,e),s=$d(t,e);if(!(i==null||s==null))return r==="horizontal"?mC(t,"yAxis",s,n):mC(t,"xAxis",i,n)},Hqe=(t,e)=>{var n=Sr(t),r=qd(t,e),i=$d(t,e);if(!(r==null||i==null))return n==="horizontal"?r9(t,"xAxis",r):r9(t,"yAxis",i)},qqe=yt([Uqe,SIe,Hqe],$8e),$qe=(t,e,n)=>{var r,i,s=gS(t,e);if(s==null)return 0;var o=qd(t,e),l=$d(t,e);if(o==null||l==null)return 0;var c=Sr(t),d=dne(t),{maxBarSize:u}=s,m=Ca(u)?d:u,p,f;return c==="horizontal"?(p=Ld(t,"xAxis",o,n),f=Rd(t,"xAxis",o,n)):(p=Ld(t,"yAxis",l,n),f=Rd(t,"yAxis",l,n)),(r=(i=cp(p,f,!0))!==null&&i!==void 0?i:m)!==null&&r!==void 0?r:0},bae=(t,e,n)=>{var r=Sr(t),i=qd(t,e),s=$d(t,e);if(!(i==null||s==null)){var o,l;return r==="horizontal"?(o=Ld(t,"xAxis",i,n),l=Rd(t,"xAxis",i,n)):(o=Ld(t,"yAxis",s,n),l=Rd(t,"yAxis",s,n)),cp(o,l)}},Vqe=yt([qqe,dne,wIe,une,$qe,bae,Iqe],X8e),Gqe=(t,e,n)=>{var r=qd(t,e);if(r!=null)return Ld(t,"xAxis",r,n)},Wqe=(t,e,n)=>{var r=$d(t,e);if(r!=null)return Ld(t,"yAxis",r,n)},Kqe=(t,e,n)=>{var r=qd(t,e);if(r!=null)return Rd(t,"xAxis",r,n)},Xqe=(t,e,n)=>{var r=$d(t,e);if(r!=null)return Rd(t,"yAxis",r,n)},Yqe=yt([Vqe,gS],Q8e),Qqe=yt([Bqe,gS],Y8e),Zqe=yt([Ti,CI,Gqe,Wqe,Kqe,Xqe,Yqe,Sr,Zte,bae,Qqe,gS,zqe],(t,e,n,r,i,s,o,l,c,d,u,m,p)=>{var{chartData:f,dataStartIndex:x,dataEndIndex:v}=c;if(!(m==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||i==null||s==null||d==null)){var{data:g}=m,b;if(g!=null&&g.length>0?b=g:b=f?.slice(x,v+1),b!=null)return C$e({layout:l,barSettings:m,pos:o,parentViewBox:e,bandSize:d,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:s,stackedData:u,displayedData:b,offset:t,cells:p,dataStartIndex:x})}}),Jqe=["index"];function eL(){return eL=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},eL.apply(null,arguments)}function e$e(t,e){if(t==null)return{};var n,r,i=t$e(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)&&(i[n]=t[n])}return i}function t$e(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 xae=w.createContext(void 0),n$e=t=>{var e=w.useContext(xae);if(e!=null)return e.stackId;if(t!=null)return Hee(t)},r$e=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),a$e=t=>{var e=w.useContext(xae);if(e!=null){var{stackId:n}=e;return"url(#".concat(r$e(n,t),")")}},yae=t=>{var{index:e}=t,n=e$e(t,Jqe),r=a$e(e);return w.createElement(Ea,eL({className:"recharts-bar-stack-layer",clipPath:r},n))},i$e=["onMouseEnter","onMouseLeave","onClick"],s$e=["value","background","tooltipPosition"],o$e=["id"],l$e=["onMouseEnter","onClick","onMouseLeave"];function gm(){return gm=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},gm.apply(null,arguments)}function NW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Ks(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?NW(Object(n),!0).forEach(function(r){c$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):NW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function c$e(t,e,n){return(e=d$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function d$e(t){var e=u$e(t,"string");return typeof e=="symbol"?e:e+""}function u$e(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 _C(t,e){if(t==null)return{};var n,r,i=m$e(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)&&(i[n]=t[n])}return i}function m$e(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 h$e=t=>{var{dataKey:e,name:n,fill:r,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:r,value:bp(n,e),payload:t}]},p$e=w.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:i,name:s,hide:o,unit:l,tooltipType:c,id:d}=t,u={dataDefinedOnItem:void 0,getPosition:gp,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:e,nameKey:void 0,name:bp(s,e),hide:o,type:c,color:i,unit:l,graphicalItemId:d}};return w.createElement(RT,{tooltipEntrySettings:u})});function f$e(t){var e=un(dp),{data:n,dataKey:r,background:i,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,d=_C(s,i$e),u=Y4(o,r,s.id),m=Q4(l),p=Z4(c,r,s.id);if(!i||n==null)return null;var f=ag(i);return w.createElement(Os,{zIndex:Z8e(i,Ga.barBackground)},n.map((x,v)=>{var{value:g,background:b,tooltipPosition:_}=x,C=_C(x,s$e);if(!b)return null;var P=u(x,v),N=m(x,v),A=p(x,v),T=Ks(Ks(Ks(Ks(Ks({option:i,isActive:String(v)===e},C),{},{fill:"#eee"},b),f),Xw(d,x,v)),{},{onMouseEnter:P,onMouseLeave:N,onClick:A,dataKey:r,index:v,className:"recharts-bar-background-rectangle"});return w.createElement(SC,gm({key:"background-bar-".concat(v)},T))}))}function g$e(t){var{showLabels:e,children:n,rects:r}=t,i=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return Ks(Ks({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return w.createElement($4,{value:e?i:void 0},n)}function b$e(t){var{shape:e,activeBar:n,baseProps:r,entry:i,index:s,dataKey:o}=t,l=un(dp),c=un(I4),d=n&&String(s)===l&&(c==null||o===c),u=d?n:e;return d?w.createElement(Os,{zIndex:Ga.activeBar},w.createElement(yae,{index:s},w.createElement(SC,gm({},r,{name:String(r.name)},i,{isActive:d,option:u,index:s,dataKey:o})))):w.createElement(SC,gm({},r,{name:String(r.name)},i,{isActive:d,option:u,index:s,dataKey:o}))}function x$e(t){var{shape:e,baseProps:n,entry:r,index:i,dataKey:s}=t;return w.createElement(SC,gm({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:i,dataKey:s}))}function y$e(t){var e,{data:n,props:r}=t,i=(e=no(r))!==null&&e!==void 0?e:{},{id:s}=i,o=_C(i,o$e),{shape:l,dataKey:c,activeBar:d}=r,{onMouseEnter:u,onClick:m,onMouseLeave:p}=r,f=_C(r,l$e),x=Y4(u,c,s),v=Q4(p),g=Z4(m,c,s);return n?w.createElement(w.Fragment,null,n.map((b,_)=>w.createElement(yae,gm({index:_,key:"rectangle-".concat(b?.x,"-").concat(b?.y,"-").concat(b?.value,"-").concat(_),className:"recharts-bar-rectangle"},Xw(f,b,_),{onMouseEnter:x(b,_),onMouseLeave:v(b,_),onClick:g(b,_)}),d?w.createElement(b$e,{shape:l,activeBar:d,baseProps:o,entry:b,index:_,dataKey:c}):w.createElement(x$e,{shape:l,baseProps:o,entry:b,index:_,dataKey:c})))):null}function v$e(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:d,onAnimationStart:u}=e,m=n.current,p=fy(e,"recharts-bar-"),[f,x]=w.useState(!1),v=!f,g=w.useCallback(()=>{typeof d=="function"&&d(),x(!1)},[d]),b=w.useCallback(()=>{typeof u=="function"&&u(),x(!0)},[u]);return w.createElement(g$e,{showLabels:v,rects:r},w.createElement(py,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:g,onAnimationStart:b,key:p},_=>{var C=_===1?r:r?.map((P,N)=>{var A=m&&m[N];if(A)return Ks(Ks({},P),{},{x:Dr(A.x,P.x,_),y:Dr(A.y,P.y,_),width:Dr(A.width,P.width,_),height:Dr(A.height,P.height,_)});if(i==="horizontal"){var T=Dr(0,P.height,_),F=Dr(P.stackedBarStart,P.y,_);return Ks(Ks({},P),{},{y:F,height:T})}var k=Dr(0,P.width,_),D=Dr(P.stackedBarStart,P.x,_);return Ks(Ks({},P),{},{width:k,x:D})});return _>0&&(n.current=C??null),C==null?null:w.createElement(Ea,null,w.createElement(y$e,{props:e,data:C}))}),w.createElement(ET,{label:e.label}),e.children)}function w$e(t){var e=w.useRef(null);return w.createElement(v$e,{previousRectanglesRef:e,props:t})}var vae=0,S$e=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:Fr(t,e)}};class _$e extends w.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:i,xAxisId:s,yAxisId:o,needClip:l,background:c,id:d}=this.props;if(e||n==null)return null;var u=_r("recharts-bar",i),m=d;return w.createElement(Ea,{className:u,id:d},l&&w.createElement("defs",null,w.createElement(rz,{clipPathId:m,xAxisId:s,yAxisId:o})),w.createElement(Ea,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(m,")"):void 0},w.createElement(f$e,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),w.createElement(w$e,this.props)))}}var k$e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:vae,xAxisId:0,yAxisId:0,zIndex:Ga.bar};function N$e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u}=t,{needClip:m}=zT(e,n),p=xp(),f=Ai(),x=W4(t.children,Gx),v=un(_=>Zqe(_,t.id,f,x));if(p!=="vertical"&&p!=="horizontal")return null;var g,b=v?.[0];return b==null||b.height==null||b.width==null?g=0:g=p==="vertical"?b.height/2:b.width/2,w.createElement(Jre,{xAxisId:e,yAxisId:n,data:v,dataPointFormatter:S$e,errorBarOffset:g},w.createElement(_$e,gm({},t,{layout:p,needClip:m,data:v,xAxisId:e,yAxisId:n,hide:r,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u})))}function C$e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:i,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:d,stackedData:u,displayedData:m,offset:p,cells:f,parentViewBox:x,dataStartIndex:v}=t,g=e==="horizontal"?l:o,b=u?g.scale.domain():null,_=c3e({numericAxis:g}),C=g.scale.map(_);return m.map((P,N)=>{var A,T,F,k,D,H;if(u){var z=u[N+v];if(z==null)return null;A=a3e(z,b)}else A=Fr(P,n),Array.isArray(A)||(A=[_,A]);var X=Rqe(r,vae)(A[1],N);if(e==="horizontal"){var L,ne=l.scale.map(A[0]),ie=l.scale.map(A[1]);if(ne==null||ie==null)return null;T=n7({axis:o,ticks:c,bandSize:s,offset:i.offset,entry:P,index:N}),F=(L=ie??ne)!==null&&L!==void 0?L:void 0,k=i.size;var ee=ne-ie;if(D=Bc(ee)?0:ee,H={x:T,y:p.top,width:k,height:p.height},Math.abs(X)>0&&Math.abs(D)<Math.abs(X)){var ue=Bi(D||X)*(Math.abs(X)-Math.abs(D));F-=ue,D+=ue}}else{var le=o.scale.map(A[0]),oe=o.scale.map(A[1]);if(le==null||oe==null)return null;if(T=le,F=n7({axis:l,ticks:d,bandSize:s,offset:i.offset,entry:P,index:N}),k=oe-le,D=i.size,H={x:p.left,y:F,width:p.width,height:D},Math.abs(X)>0&&Math.abs(k)<Math.abs(X)){var W=Bi(k||X)*(Math.abs(X)-Math.abs(k));k+=W}}if(T==null||F==null||k==null||D==null)return null;var re=Ks(Ks({},P),{},{stackedBarStart:C,x:T,y:F,width:k,height:D,value:u?A:A[1],payload:P,background:H,tooltipPosition:{x:T+k/2,y:F+D/2},parentViewBox:x},f&&f[N]&&f[N].props);return re}).filter(Boolean)}function P$e(t){var e=Da(t,k$e),n=n$e(e.stackId),r=Ai();return w.createElement(LT,{id:e.id,type:"bar"},i=>w.createElement(w.Fragment,null,w.createElement(J4,{legendPayload:h$e(e)}),w.createElement(p$e,{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:i}),w.createElement(ez,{type:"bar",id:i,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(Os,{zIndex:e.zIndex},w.createElement(N$e,gm({},e,{id:i})))))}var Zb=w.memo(P$e,fS);Zb.displayName="Bar";var T$e=["domain","range"],A$e=["domain","range"];function CW(t,e){if(t==null)return{};var n,r,i=j$e(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)&&(i[n]=t[n])}return i}function j$e(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 PW(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 wae(t,e){if(t===e)return!0;var{domain:n,range:r}=t,i=CW(t,T$e),{domain:s,range:o}=e,l=CW(e,A$e);return!PW(n,s)||!PW(r,o)?!1:fS(i,l)}var M$e=["type"],E$e=["dangerouslySetInnerHTML","ticks","scale"],D$e=["id","scale"];function tL(){return tL=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},tL.apply(null,arguments)}function TW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function AW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?TW(Object(n),!0).forEach(function(r){F$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):TW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function F$e(t,e,n){return(e=R$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function R$e(t){var e=L$e(t,"string");return typeof e=="symbol"?e:e+""}function L$e(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 nL(t,e){if(t==null)return{};var n,r,i=O$e(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)&&(i[n]=t[n])}return i}function O$e(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 I$e(t){var e=ia(),n=w.useRef(null),r=MI(),{type:i}=t,s=nL(t,M$e),o=vT(r,"xAxis",i),l=w.useMemo(()=>{if(o!=null)return AW(AW({},s),{},{type:o})},[s,o]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(A8e(l)):n.current!==l&&e(j8e({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(M8e(n.current)),n.current=null)},[e]),null}var z$e=t=>{var{xAxisId:e,className:n}=t,r=un(CI),i=Ai(),s="xAxis",o=un(b=>$ne(b,s,e,i)),l=un(b=>Une(b,e)),c=un(b=>_4e(b,e)),d=un(b=>wne(b,e));if(l==null||c==null||d==null)return null;var{dangerouslySetInnerHTML:u,ticks:m,scale:p}=t,f=nL(t,E$e),{id:x,scale:v}=d,g=nL(d,D$e);return w.createElement(nz,tL({},f,g,{x:c.x,y:c.y,width:l.width,height:l.height,className:_r("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:o,axisType:s}))},U$e={allowDataOverflow:Li.allowDataOverflow,allowDecimals:Li.allowDecimals,allowDuplicatedCategory:Li.allowDuplicatedCategory,angle:Li.angle,axisLine:Ju.axisLine,height:Li.height,hide:!1,includeHidden:Li.includeHidden,interval:Li.interval,label:!1,minTickGap:Li.minTickGap,mirror:Li.mirror,orientation:Li.orientation,padding:Li.padding,reversed:Li.reversed,scale:Li.scale,tick:Li.tick,tickCount:Li.tickCount,tickLine:Ju.tickLine,tickSize:Ju.tickSize,type:Li.type,xAxisId:0},B$e=t=>{var e=Da(t,U$e);return w.createElement(w.Fragment,null,w.createElement(I$e,{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(z$e,e))},Nf=w.memo(B$e,wae);Nf.displayName="XAxis";var H$e=["type"],q$e=["dangerouslySetInnerHTML","ticks","scale"],$$e=["id","scale"];function rL(){return rL=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},rL.apply(null,arguments)}function jW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function MW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?jW(Object(n),!0).forEach(function(r){V$e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):jW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function V$e(t,e,n){return(e=G$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function G$e(t){var e=W$e(t,"string");return typeof e=="symbol"?e:e+""}function W$e(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 aL(t,e){if(t==null)return{};var n,r,i=K$e(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)&&(i[n]=t[n])}return i}function K$e(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 X$e(t){var e=ia(),n=w.useRef(null),r=MI(),{type:i}=t,s=aL(t,H$e),o=vT(r,"yAxis",i),l=w.useMemo(()=>{if(o!=null)return MW(MW({},s),{},{type:o})},[o,s]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(E8e(l)):n.current!==l&&e(D8e({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(F8e(n.current)),n.current=null)},[e]),null}function Y$e(t){var{yAxisId:e,className:n,width:r,label:i}=t,s=w.useRef(null),o=w.useRef(null),l=un(CI),c=Ai(),d=ia(),u="yAxis",m=un(A=>Bne(A,e)),p=un(A=>N4e(A,e)),f=un(A=>$ne(A,u,e,c)),x=un(A=>Sne(A,e));if(w.useLayoutEffect(()=>{if(!(r!=="auto"||!m||q4(i)||w.isValidElement(i)||x==null)){var A=s.current;if(A){var T=A.getCalculatedWidth();Math.round(m.width)!==Math.round(T)&&d(R8e({id:e,width:T}))}}},[f,m,d,i,e,r,x]),m==null||p==null||x==null)return null;var{dangerouslySetInnerHTML:v,ticks:g,scale:b}=t,_=aL(t,q$e),{id:C,scale:P}=x,N=aL(x,$$e);return w.createElement(nz,rL({},_,N,{ref:s,labelRef:o,x:p.x,y:p.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:m.width,height:m.height,className:_r("recharts-".concat(u," ").concat(u),n),viewBox:l,ticks:f,axisType:u}))}var Q$e={allowDataOverflow:Oi.allowDataOverflow,allowDecimals:Oi.allowDecimals,allowDuplicatedCategory:Oi.allowDuplicatedCategory,angle:Oi.angle,axisLine:Ju.axisLine,hide:!1,includeHidden:Oi.includeHidden,interval:Oi.interval,label:!1,minTickGap:Oi.minTickGap,mirror:Oi.mirror,orientation:Oi.orientation,padding:Oi.padding,reversed:Oi.reversed,scale:Oi.scale,tick:Oi.tick,tickCount:Oi.tickCount,tickLine:Ju.tickLine,tickSize:Ju.tickSize,type:Oi.type,width:Oi.width,yAxisId:0},Z$e=t=>{var e=Da(t,Q$e);return w.createElement(w.Fragment,null,w.createElement(X$e,{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(Y$e,e))},Cf=w.memo(Z$e,wae);Cf.displayName="YAxis";var J$e=(t,e)=>e,iz=yt([J$e,Sr,xne,Gi,ore,wm,Uze,Ti],Wze),sz=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)}},Sae=cc("mouseClick"),_ae=Qw();_ae.startListening({actionCreator:Sae,effect:(t,e)=>{var n=t.payload,r=iz(e.getState(),sz(n));r?.activeIndex!=null&&e.dispatch(z4e({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var iL=cc("mouseMove"),kae=Qw(),Q1=null;kae.startListening({actionCreator:iL,effect:(t,e)=>{var n=t.payload;Q1!==null&&cancelAnimationFrame(Q1);var r=sz(n);Q1=requestAnimationFrame(()=>{var i=e.getState(),s=E4(i,i.tooltip.settings.shared);if(s==="axis"){var o=iz(i,r);o?.activeIndex!=null?e.dispatch(Zne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(Qne())}Q1=null})}});function eVe(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 EW={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},Nae=Fo({name:"rootProps",initialState:EW,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:EW.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}}}),tVe=Nae.reducer,{updateOptions:nVe}=Nae.actions,rVe=null,aVe={updatePolarOptions:(t,e)=>e.payload},Cae=Fo({name:"polarOptions",initialState:rVe,reducers:aVe}),{updatePolarOptions:iVe}=Cae.actions,sVe=Cae.reducer,Pae=cc("keyDown"),Tae=cc("focus"),oz=Qw();oz.startListening({actionCreator:Pae,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=D4(i,ky(n),uS(n),hS(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=wm(n);if(s==="Enter"){var d=pC(n,"axis","hover",String(i.index));e.dispatch(GR({active:!i.active,activeIndex:i.index,activeCoordinate:d}));return}var u=A4e(n),m=u==="left-to-right"?1:-1,p=s==="ArrowRight"?1:-1,f=l+p*m;if(!(c==null||f>=c.length||f<0)){var x=pC(n,"axis","hover",String(f));e.dispatch(GR({active:!0,activeIndex:f.toString(),activeCoordinate:x}))}}}}}});oz.startListening({actionCreator:Tae,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:i}=n.tooltip;if(!i.active&&i.index==null){var s="0",o=pC(n,"axis","hover",String(s));e.dispatch(GR({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Ol=cc("externalEvent"),Aae=Qw(),bD=new Map;Aae.startListening({actionCreator:Ol,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var i=r.type,s=bD.get(i);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:Nze(l),activeDataKey:I4(l),activeIndex:dp(l),activeLabel:dre(l),activeTooltipIndex:dp(l),isTooltipActive:Cze(l)};n(c,r)}finally{bD.delete(i)}});bD.set(i,o)}}});var oVe=yt([Sy],t=>t.tooltipItemPayloads),lVe=yt([oVe,(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:i}=r;if(i!=null)return i(e)}}}),jae=cc("touchMove"),Mae=Qw();Mae.startListening({actionCreator:jae,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),i=E4(r,r.tooltip.settings.shared);if(i==="axis"){var s=n.touches[0];if(s==null)return;var o=iz(r,sz({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(Zne({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate}))}else if(i==="item"){var l,c=n.touches[0];if(document.elementFromPoint==null||c==null)return;var d=document.elementFromPoint(c.clientX,c.clientY);if(!d||!d.getAttribute)return;var u=d.getAttribute($ee),m=(l=d.getAttribute(Vee))!==null&&l!==void 0?l:void 0,p=_y(r).find(v=>v.id===m);if(u==null||p==null||m==null)return;var{dataKey:f}=p,x=lVe(r,u,m);e.dispatch(Yne({activeDataKey:f,activeIndex:u,activeCoordinate:x,activeGraphicalItemId:m}))}}}});var cVe=uee({brush:J8e,cartesianAxis:L8e,chartData:k5e,errorBars:c6e,graphicalItems:$Be,layout:JDe,legend:iFe,options:y5e,polarAxis:aBe,polarOptions:sVe,referenceElements:oHe,rootProps:tVe,tooltip:U4e,zIndex:o5e}),dVe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return kDe({reducer:cVe,preloadedState:e,middleware:r=>{var i;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((i="es6")!==null&&i!==void 0?i:"")}).concat([_ae.middleware,kae.middleware,oz.middleware,Aae.middleware,Mae.middleware])},enhancers:r=>{var i=r;return typeof r=="function"&&(i=r()),i.concat(Cee({type:"raf"}))},devTools:{serialize:{replacer:eVe},name:"recharts-".concat(n)}})};function Eae(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,i=Ai(),s=w.useRef(null);if(i)return n;s.current==null&&(s.current=dVe(e,r));var o=yI;return w.createElement(O6e,{context:o,store:s.current},n)}function uVe(t){var{layout:e,margin:n}=t,r=ia(),i=Ai();return w.useEffect(()=>{i||(r(YDe(e)),r(XDe(n)))},[r,i,e,n]),null}var Dae=w.memo(uVe,fS);function Fae(t){var e=ia();return w.useEffect(()=>{e(nVe(t))},[e,t]),null}function DW(t){var{zIndex:e,isPanorama:n}=t,r=w.useRef(null),i=ia();return w.useLayoutEffect(()=>(r.current&&i(i5e({zIndex:e,element:r.current,isPanorama:n})),()=>{i(s5e({zIndex:e,isPanorama:n}))}),[i,e,n]),w.createElement("g",{tabIndex:-1,ref:r})}function FW(t){var{children:e,isPanorama:n}=t,r=un(Xze);if(!r||r.length===0)return e;var i=r.filter(o=>o<0),s=r.filter(o=>o>0);return w.createElement(w.Fragment,null,i.map(o=>w.createElement(DW,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>w.createElement(DW,{key:o,zIndex:o,isPanorama:n})))}var mVe=["children"];function hVe(t,e){if(t==null)return{};var n,r,i=pVe(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)&&(i[n]=t[n])}return i}function pVe(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 kC(){return kC=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},kC.apply(null,arguments)}var fVe={width:"100%",height:"100%",display:"block"},gVe=w.forwardRef((t,e)=>{var n=AI(),r=jI(),i=lte();if(!Dd(n)||!Dd(r))return null;var{children:s,otherAttributes:o,title:l,desc:c}=t,d,u;return o!=null&&(typeof o.tabIndex=="number"?d=o.tabIndex:d=i?0:void 0,typeof o.role=="string"?u=o.role:u=i?"application":void 0),w.createElement(lI,kC({},o,{title:l,desc:c,role:u,tabIndex:d,width:n,height:r,style:fVe,ref:e}),s)}),bVe=t=>{var{children:e}=t,n=un(lT);if(!n)return null;var{width:r,height:i,y:s,x:o}=n;return w.createElement(lI,{width:r,height:i,x:o,y:s},e)},RW=w.forwardRef((t,e)=>{var{children:n}=t,r=hVe(t,mVe),i=Ai();return i?w.createElement(bVe,null,w.createElement(FW,{isPanorama:!0},n)):w.createElement(gVe,kC({ref:e},r),w.createElement(FW,{isPanorama:!1},n))});function xVe(){var t=ia(),[e,n]=w.useState(null),r=un(f3e);return w.useEffect(()=>{if(e!=null){var i=e.getBoundingClientRect(),s=i.width/e.offsetWidth;Wn(s)&&s!==r&&t(ZDe(s))}},[e,t,r]),n}function LW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function yVe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?LW(Object(n),!0).forEach(function(r){vVe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):LW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function vVe(t,e,n){return(e=wVe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wVe(t){var e=SVe(t,"string");return typeof e=="symbol"?e:e+""}function SVe(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 Jh(){return Jh=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},Jh.apply(null,arguments)}var _Ve=()=>(D5e(),null);function NC(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var kVe=w.forwardRef((t,e)=>{var n,r,i=w.useRef(null),[s,o]=w.useState({containerWidth:NC((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:NC((r=t.style)===null||r===void 0?void 0:r.height)}),l=w.useCallback((d,u)=>{o(m=>{var p=Math.round(d),f=Math.round(u);return m.containerWidth===p&&m.containerHeight===f?m:{containerWidth:p,containerHeight:f}})},[]),c=w.useCallback(d=>{if(typeof e=="function"&&e(d),d!=null&&typeof ResizeObserver<"u"){var{width:u,height:m}=d.getBoundingClientRect();l(u,m);var p=x=>{var v=x[0];if(v!=null){var{width:g,height:b}=v.contentRect;l(g,b)}},f=new ResizeObserver(p);f.observe(d),i.current=f}},[e,l]);return w.useEffect(()=>()=>{var d=i.current;d?.disconnect()},[l]),w.createElement(w.Fragment,null,w.createElement(eS,{width:s.containerWidth,height:s.containerHeight}),w.createElement("div",Jh({ref:c},t)))}),NVe=w.forwardRef((t,e)=>{var{width:n,height:r}=t,[i,s]=w.useState({containerWidth:NC(n),containerHeight:NC(r)}),o=w.useCallback((c,d)=>{s(u=>{var m=Math.round(c),p=Math.round(d);return u.containerWidth===m&&u.containerHeight===p?u:{containerWidth:m,containerHeight:p}})},[]),l=w.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:d,height:u}=c.getBoundingClientRect();o(d,u)}},[e,o]);return w.createElement(w.Fragment,null,w.createElement(eS,{width:i.containerWidth,height:i.containerHeight}),w.createElement("div",Jh({ref:l},t)))}),CVe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return w.createElement(w.Fragment,null,w.createElement(eS,{width:n,height:r}),w.createElement("div",Jh({ref:e},t)))}),PVe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return typeof n=="string"||typeof r=="string"?w.createElement(NVe,Jh({},t,{ref:e})):typeof n=="number"&&typeof r=="number"?w.createElement(CVe,Jh({},t,{width:n,height:r,ref:e})):w.createElement(w.Fragment,null,w.createElement(eS,{width:n,height:r}),w.createElement("div",Jh({ref:e},t)))});function TVe(t){return t?kVe:PVe}var AVe=w.forwardRef((t,e)=>{var{children:n,className:r,height:i,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:d,onMouseLeave:u,onMouseMove:m,onMouseUp:p,onTouchEnd:f,onTouchMove:x,onTouchStart:v,style:g,width:b,responsive:_,dispatchTouchEvents:C=!0}=t,P=w.useRef(null),N=ia(),[A,T]=w.useState(null),[F,k]=w.useState(null),D=xVe(),H=PI(),z=H?.width>0?H.width:b,X=H?.height>0?H.height:i,L=w.useCallback(j=>{D(j),typeof e=="function"&&e(j),T(j),k(j),j!=null&&(P.current=j)},[D,e,T,k]),ne=w.useCallback(j=>{N(Sae(j)),N(Ol({handler:s,reactEvent:j}))},[N,s]),ie=w.useCallback(j=>{N(iL(j)),N(Ol({handler:d,reactEvent:j}))},[N,d]),ee=w.useCallback(j=>{N(Qne()),N(Ol({handler:u,reactEvent:j}))},[N,u]),ue=w.useCallback(j=>{N(iL(j)),N(Ol({handler:m,reactEvent:j}))},[N,m]),le=w.useCallback(()=>{N(Tae())},[N]),oe=w.useCallback(j=>{N(Pae(j.key))},[N]),W=w.useCallback(j=>{N(Ol({handler:o,reactEvent:j}))},[N,o]),re=w.useCallback(j=>{N(Ol({handler:l,reactEvent:j}))},[N,l]),ce=w.useCallback(j=>{N(Ol({handler:c,reactEvent:j}))},[N,c]),xe=w.useCallback(j=>{N(Ol({handler:p,reactEvent:j}))},[N,p]),Ne=w.useCallback(j=>{N(Ol({handler:v,reactEvent:j}))},[N,v]),$=w.useCallback(j=>{C&&N(jae(j)),N(Ol({handler:x,reactEvent:j}))},[N,C,x]),Y=w.useCallback(j=>{N(Ol({handler:f,reactEvent:j}))},[N,f]),E=TVe(_);return w.createElement(xre.Provider,{value:A},w.createElement(PJ.Provider,{value:F},w.createElement(E,{width:z??g?.width,height:X??g?.height,className:_r("recharts-wrapper",r),style:yVe({position:"relative",cursor:"default",width:z,height:X},g),onClick:ne,onContextMenu:W,onDoubleClick:re,onFocus:le,onKeyDown:oe,onMouseDown:ce,onMouseEnter:ie,onMouseLeave:ee,onMouseMove:ue,onMouseUp:xe,onTouchEnd:Y,onTouchMove:$,onTouchStart:Ne,ref:L},w.createElement(_Ve,null),n)))}),jVe=["width","height","responsive","children","className","style","compact","title","desc"];function MVe(t,e){if(t==null)return{};var n,r,i=EVe(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)&&(i[n]=t[n])}return i}function EVe(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 Rae=w.forwardRef((t,e)=>{var{width:n,height:r,responsive:i,children:s,className:o,style:l,compact:c,title:d,desc:u}=t,m=MVe(t,jVe),p=no(m);return c?w.createElement(w.Fragment,null,w.createElement(eS,{width:n,height:r}),w.createElement(RW,{otherAttributes:p,title:d,desc:u},s)):w.createElement(AVe,{className:o,style:l,width:n,height:r,responsive:i??!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(RW,{otherAttributes:p,title:d,desc:u,ref:e},w.createElement(lHe,null,s)))});function sL(){return sL=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},sL.apply(null,arguments)}var DVe={top:5,right:5,bottom:5,left:5},FVe={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:DVe,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},lz=w.forwardRef(function(e,n){var r,i=Da(e.categoricalChartProps,FVe),{chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,categoricalChartProps:d}=e,u={chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return w.createElement(Eae,{preloadedState:{options:u},reduxStoreName:(r=d.id)!==null&&r!==void 0?r:s},w.createElement(Gre,{chartData:d.data}),w.createElement(Dae,{layout:i.layout,margin:i.margin}),w.createElement(Fae,{baseValue:i.baseValue,accessibilityLayer:i.accessibilityLayer,barCategoryGap:i.barCategoryGap,maxBarSize:i.maxBarSize,stackOffset:i.stackOffset,barGap:i.barGap,barSize:i.barSize,syncId:i.syncId,syncMethod:i.syncMethod,className:i.className,reverseStackOrder:i.reverseStackOrder}),w.createElement(Rae,sL({},i,{ref:n})))}),RVe=["axis"],LVe=w.forwardRef((t,e)=>w.createElement(lz,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:RVe,tooltipPayloadSearcher:jT,categoricalChartProps:t,ref:e})),OVe=["axis","item"],Z1=w.forwardRef((t,e)=>w.createElement(lz,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:OVe,tooltipPayloadSearcher:jT,categoricalChartProps:t,ref:e}));function IVe(t){var e=ia();return w.useEffect(()=>{e(iVe(t))},[e,t]),null}var zVe=["layout"];function oL(){return oL=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},oL.apply(null,arguments)}function UVe(t,e){if(t==null)return{};var n,r,i=BVe(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)&&(i[n]=t[n])}return i}function BVe(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 HVe={top:5,right:5,bottom:5,left:5},Lae={accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:HVe,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},qVe=w.forwardRef(function(e,n){var r,i=Da(e.categoricalChartProps,Lae),{layout:s}=i,o=UVe(i,zVe),{chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u}=e,m={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u,eventEmitter:void 0};return w.createElement(Eae,{preloadedState:{options:m},reduxStoreName:(r=i.id)!==null&&r!==void 0?r:l},w.createElement(Gre,{chartData:i.data}),w.createElement(Dae,{layout:s,margin:i.margin}),w.createElement(Fae,{baseValue:void 0,accessibilityLayer:i.accessibilityLayer,barCategoryGap:i.barCategoryGap,maxBarSize:i.maxBarSize,stackOffset:i.stackOffset,barGap:i.barGap,barSize:i.barSize,syncId:i.syncId,syncMethod:i.syncMethod,className:i.className,reverseStackOrder:i.reverseStackOrder}),w.createElement(IVe,{cx:i.cx,cy:i.cy,startAngle:i.startAngle,endAngle:i.endAngle,innerRadius:i.innerRadius,outerRadius:i.outerRadius}),w.createElement(Rae,oL({},o,{ref:n})))});function OW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function IW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?OW(Object(n),!0).forEach(function(r){$Ve(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):OW(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function $Ve(t,e,n){return(e=VVe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function VVe(t){var e=GVe(t,"string");return typeof e=="symbol"?e:e+""}function GVe(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 WVe=["item"],KVe=IW(IW({},Lae),{},{layout:"centric",startAngle:0,endAngle:360}),zW=w.forwardRef((t,e)=>{var n=Da(t,KVe);return w.createElement(qVe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:WVe,tooltipPayloadSearcher:jT,categoricalChartProps:n,ref:e})}),XVe=["axis"],YVe=w.forwardRef((t,e)=>w.createElement(lz,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:XVe,tooltipPayloadSearcher:jT,categoricalChartProps:t,ref:e}));const UW=[{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 QVe({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:i,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Rt(),{mode:d}=wg(),[u,m]=w.useState("24h"),[p,f]=w.useState(o),x=d==="dark",{data:v}=Qe({queryKey:["settings"],queryFn:me.getSettings}),g=v?.time_format||"system";w.useEffect(()=>{if(!t)return;const Y=E=>{E.key==="Escape"&&e()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[t,e]);const b=UW.find(Y=>Y.value===u)?.hours||24,{data:_,isLoading:C,error:P}=Qe({queryKey:["ams-history",n,i,b],queryFn:()=>me.getAMSHistory(n,i,b),enabled:t,refetchInterval:6e4});if(!t)return null;const N=_?.data.map(Y=>({time:(er(Y.recorded_at)||new Date).getTime(),humidity:Y.humidity,temperature:Y.temperature}))||[],A=Date.now()-b*60*60*1e3,T=Date.now(),F=[...N];if(F.length>0){const Y=F[0];Y.time>A&&F.unshift({...Y,time:A});const E=F[F.length-1];E.time<T&&F.push({...E,time:T})}const k=l?.humidityGood||40,D=l?.humidityFair||60,H=l?.tempGood||30,z=l?.tempFair||35,X=F[F.length-1],L=X?.humidity,ne=X?.temperature,ie=Y=>{const E=Y.filter(I=>I!=null);if(E.length<4)return"stable";const j=E.slice(0,Math.floor(E.length/4)),O=E.slice(-Math.floor(E.length/4)),K=j.reduce((I,V)=>I+V,0)/j.length,he=O.reduce((I,V)=>I+V,0)/O.length-K;return Math.abs(he)<2?"stable":he>0?"up":"down"},ee=ie(F.map(Y=>Y.humidity)),ue=ie(F.map(Y=>Y.temperature)),le=({trend:Y})=>Y==="up"?a.jsx(Q3,{className:"w-4 h-4 text-red-400"}):Y==="down"?a.jsx(_O,{className:"w-4 h-4 text-green-400"}):a.jsx(cN,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),oe=Y=>Y==null?"#9ca3af":Y<=k?"#22a352":Y<=D?"#d4a017":"#c62828",W=Y=>Y==null?"#9ca3af":Y<=H?"#22a352":Y<=z?"#d4a017":"#c62828",re=x?"#2d2d2d":"#ffffff",ce=x?"#1d1d1d":"#f3f4f6",xe=x?"#3d3d3d":"#e5e7eb",Ne=x?"#ffffff":"#111827",$=x?"#9ca3af":"#4b5563";return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:re},onClick:Y=>Y.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:xe},children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold",style:{color:Ne},children:[s," ",c("common.history","History")]}),a.jsx("p",{className:"text-sm",style:{color:$},children:r})]}),a.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:$},children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[a.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[a.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:ce},children:[a.jsxs("button",{onClick:()=>f("humidity"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="humidity"?"bg-blue-600 text-white":""}`,style:p!=="humidity"?{color:$}:void 0,children:[a.jsx(yO,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),a.jsxs("button",{onClick:()=>f("temperature"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${p==="temperature"?"bg-orange-600 text-white":""}`,style:p!=="temperature"?{color:$}:void 0,children:[a.jsx(qw,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),a.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:ce},children:UW.map(Y=>a.jsx("button",{onClick:()=>m(Y.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${u===Y.value?"bg-bambu-green text-white":""}`,style:u!==Y.value?{color:$}:void 0,children:Y.label},Y.value))})]}),a.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:oe(L)},children:L!=null?`${L}%`:"—"}),a.jsx(le,{trend:ee})]})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:Ne},children:_?.avg_humidity!=null?`${_.avg_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-green-500",children:_?.min_humidity!=null?`${_.min_humidity}%`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_humidity!=null?`${_.max_humidity}%`:"—"})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.current","Current")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-2xl font-bold",style:{color:W(ne)},children:ne!=null?`${ne}°C`:"—"}),a.jsx(le,{trend:ue})]})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.average","Average")}),a.jsx("p",{className:"text-2xl font-bold",style:{color:Ne},children:_?.avg_temperature!=null?`${_.avg_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.min","Min")}),a.jsx("p",{className:"text-2xl font-bold text-blue-500",children:_?.min_temperature!=null?`${_.min_temperature}°C`:"—"})]}),a.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:ce},children:[a.jsx("p",{className:"text-xs",style:{color:$},children:c("common.max","Max")}),a.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_temperature!=null?`${_.max_temperature}°C`:"—"})]})]})}),a.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:ce},children:C?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:$},children:c("common.loading","Loading...")}):P?a.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):F.length===0?a.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:$},children:c("common.noData","No data available for this time range")}):a.jsx(Fh,{width:"100%",height:300,children:a.jsxs(LVe,{data:F,children:[a.jsx(kf,{strokeDasharray:"3 3",stroke:x?"#3d3d3d":"#e5e7eb"}),a.jsx(Nf,{dataKey:"time",type:"number",domain:[Date.now()-b*60*60*1e3,Date.now()],tickFormatter:Y=>{const E=new Date(Y);return b>24?E.toLocaleDateString([],{day:"numeric",month:"short"}):E.toLocaleTimeString([],q0({hour:"2-digit",minute:"2-digit"},g))},stroke:x?"#9ca3af":"#6b7280",tick:{fontSize:12}}),a.jsx(Cf,{stroke:x?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:Y=>p==="humidity"?`${Y}%`:`${Y}°C`}),a.jsx(Rh,{contentStyle:{backgroundColor:x?"#2d2d2d":"#ffffff",border:`1px solid ${x?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:x?"#fff":"#000"},labelFormatter:Y=>new Date(Y).toLocaleString(void 0,q0({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},g)),formatter:Y=>[p==="humidity"?`${Y??0}%`:`${Y??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),a.jsx(ote,{}),p==="humidity"?a.jsxs(a.Fragment,{children:[a.jsx(t0,{y:k,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(t0,{y:D,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):a.jsxs(a.Fragment,{children:[a.jsx(t0,{y:H,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),a.jsx(t0,{y:z,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),a.jsx(oae,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),a.jsx("div",{className:"text-xs text-center",style:{color:$},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}function xD({data:t,children:e,disabled:n,className:r="",spoolman:i,inventory:s,configureSlot:o}){const{t:l}=Rt(),[c,d]=w.useState(!1),[u,m]=w.useState("top"),[p,f]=w.useState(!1),[x,v]=w.useState(!1),g=w.useRef(null),b=w.useRef(null),_=w.useRef(null),C=()=>{const D=t.trayUuid;D&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(D).then(()=>{f(!0),setTimeout(()=>f(!1),2e3)}).catch(()=>{P(D)}):P(D))},P=D=>{const H=document.createElement("textarea");H.value=D,H.style.position="fixed",H.style.opacity="0",document.body.appendChild(H),H.select();try{document.execCommand("copy"),f(!0),setTimeout(()=>f(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(H)};w.useEffect(()=>{if(c&&g.current&&b.current){const D=g.current.getBoundingClientRect(),H=b.current.offsetHeight,X=D.top-56,L=window.innerHeight-D.bottom;X<H+12&&L>X?m("bottom"):m("top")}},[c]);const N=()=>{n||(_.current&&clearTimeout(_.current),_.current=setTimeout(()=>d(!0),80))},A=()=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>d(!1),100)};w.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const T=D=>D<=15?"#ef4444":D<=30?"#f97316":D<=50?"#eab308":"#22c55e",F=t.colorHex?`#${t.colorHex.replace("#","")}`:null,k=s?.assignedSpool?.remainingWeightGrams??null;return a.jsxs("div",{ref:g,className:`relative ${r}`,onMouseEnter:N,onMouseLeave:A,children:[e,c&&a.jsxs("div",{ref:b,className:`
- absolute left-1/2 -translate-x-1/2 z-[60]
- ${u==="top"?"bottom-full mb-2":"top-full mt-2"}
- animate-in fade-in-0 zoom-in-95 duration-150
- `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsxs("div",{className:`
- w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
- rounded-lg shadow-xl overflow-hidden
- backdrop-blur-sm
- `,children:[a.jsxs("div",{className:"h-12 relative overflow-hidden",style:{backgroundColor:F||"#3d3d3d"},children:[a.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-white/10 to-transparent"}),a.jsx("div",{className:`
- absolute inset-0 flex items-center justify-center
- font-semibold text-sm tracking-wide
- ${VQ(F)?"text-black/80":"text-white/90"}
- `,children:t.colorName}),a.jsx("div",{className:`
- absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
- ${t.vendor==="Bambu Lab"?"bg-black/60 text-white":"bg-black/50 text-white/90"}
- `,children:t.vendor==="Bambu Lab"?"BBL":"GEN"})]}),a.jsxs("div",{className:"p-3 space-y-2.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.profile")}),a.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[120px]",children:t.profile})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.kFactor")}),a.jsx("span",{className:"text-xs text-bambu-green font-mono font-bold",children:t.kFactor})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1",children:[a.jsx(yO,{className:"w-3 h-3"}),l("ams.fill")]}),a.jsxs("span",{className:"text-xs text-white font-semibold flex items-center gap-1",children:[a.jsx("span",{children:t.fillLevel!==null?`${t.fillLevel}%`:"—"}),k!==null&&t.fillLevel!==null&&a.jsxs("span",{className:"text-[9px] text-bambu-gray font-normal",children:["• ",k,"g"]}),t.fillSource==="spoolman"&&t.fillLevel!==null&&a.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("spoolman.fillSourceLabel")}),t.fillSource==="inventory"&&t.fillLevel!==null&&a.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("inventory.fillSourceLabel")})]})]}),a.jsx("div",{className:"h-1.5 bg-black/40 rounded-full overflow-hidden",children:t.fillLevel!==null?a.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${t.fillLevel}%`,backgroundColor:T(t.fillLevel)}}):a.jsx("div",{className:"h-full w-full bg-bambu-gray/30 rounded-full"})})]}),i?.enabled&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("spoolman.spoolId")}),t.trayUuid?a.jsxs("button",{onClick:D=>{D.stopPropagation(),C()},className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",title:"Copy spool UUID",children:[a.jsxs("span",{className:"font-mono text-[10px] truncate max-w-[80px]",children:[t.trayUuid.slice(0,8),"..."]}),p?a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}):a.jsx(Fs,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"—"})]}),i.linkedSpoolId&&i.spoolmanUrl&&a.jsxs(a.Fragment,{children:[a.jsxs("a",{href:`${i.spoolmanUrl.replace(/\/$/,"")}/spool/show/${i.linkedSpoolId}`,target:"_blank",rel:"noopener noreferrer",onClick:D=>D.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:[a.jsx(na,{className:"w-3.5 h-3.5"}),l("spoolman.openInSpoolman")]}),i.onUnlinkSpool&&(t.vendor!=="Bambu Lab"||i.syncMode==="manual")&&a.jsxs("button",{onClick:D=>{D.stopPropagation(),v(!0)},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",title:l("spoolman.unlinkSpool"),children:[a.jsx(ap,{className:"w-3.5 h-3.5"}),l("spoolman.unlinkSpool")]})]}),!i.linkedSpoolId&&a.jsxs("button",{onClick:D=>{D.stopPropagation(),i.onLinkSpool&&i.onLinkSpool?.()},disabled:!i.onLinkSpool,className:`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors ${i.onLinkSpool?"bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green":"bg-bambu-gray/10 text-bambu-gray cursor-not-allowed"}`,children:[a.jsx(Ku,{className:"w-3.5 h-3.5"}),l("spoolman.linkToSpoolman")]})]}),s&&t.vendor!=="Bambu Lab"&&a.jsx("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:s.assignedSpool?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(ja,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("inventory.assigned")})]}),a.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&&a.jsxs("button",{onClick:D=>{D.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:[a.jsx(ap,{className:"w-3.5 h-3.5"}),l("inventory.unassignSpool")]})]}):s.onAssignSpool?a.jsxs("button",{onClick:D=>{D.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:[a.jsx(ja,{className:"w-3.5 h-3.5"}),l("inventory.assignSpool")]}):null}),o?.enabled&&a.jsx("div",{className:`${i?.enabled&&t.trayUuid?"":"pt-2 mt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("button",{onClick:D=>{D.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:[a.jsx(jd,{className:"w-3.5 h-3.5"}),l("ams.configure")]})})]})]}),a.jsx("div",{className:`
- absolute left-1/2 -translate-x-1/2 w-0 h-0
- border-l-[6px] border-l-transparent
- border-r-[6px] border-r-transparent
- ${u==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
- `})]}),x&&a.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",onClick:()=>v(!1),children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),a.jsx("div",{className:"relative bg-bambu-dark-secondary rounded-lg shadow-xl w-full max-w-sm mx-4 border border-bambu-dark-tertiary",onClick:D=>D.stopPropagation(),children:a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx("h3",{className:"text-base font-semibold text-white",children:l("spoolman.unlinkConfirmTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:l("spoolman.unlinkConfirmMessage")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-bambu-dark hover:bg-bambu-dark-tertiary text-white",children:l("common.cancel")}),a.jsx("button",{onClick:()=>{i?.onUnlinkSpool?.(),v(!1)},className:"flex-1 px-3 py-2 text-sm font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:l("spoolman.unlinkSpool")})]})]})})]})]})}function yD({children:t,className:e="",configureSlot:n,inventory:r}){const{t:i}=Rt(),[s,o]=w.useState(!1),l=w.useRef(null),c=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!0),80)},d=()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>o(!1),100)};return w.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),a.jsxs("div",{className:`relative ${e}`,onMouseEnter:c,onMouseLeave:d,children:[t,s&&a.jsxs("div",{className:`
- absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50
- animate-in fade-in-0 zoom-in-95 duration-150
- `,children:[a.jsxs("div",{className:`
- bg-bambu-dark-secondary border border-bambu-dark-tertiary
- rounded-md shadow-lg overflow-hidden
- `,children:[a.jsx("div",{className:"px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap",children:i("ams.emptySlot")}),n?.enabled&&a.jsx("div",{className:"px-2 pb-2",children:a.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:i("ams.configureSlot"),children:[a.jsx(jd,{className:"w-3.5 h-3.5"}),i("ams.configure")]})}),r?.onAssignSpool&&a.jsx("div",{className:"px-2 pb-2",children:a.jsxs("button",{onClick:u=>{u.stopPropagation(),r.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:[a.jsx(ja,{className:"w-3.5 h-3.5"}),i("inventory.assignSpool")]})})]}),a.jsx("div",{className:`
- absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
- border-l-[5px] border-l-transparent
- border-r-[5px] border-r-transparent
- border-t-[5px] border-t-bambu-dark-tertiary
- `})]})]})}function Oae({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:i,amsId:s,trayId:o}){const{t:l}=Rt(),c=sn(),{showToast:d}=bn(),[u,m]=w.useState(""),p=r||n,{data:f,isLoading:x}=Qe({queryKey:["unlinked-spools"],queryFn:me.getUnlinkedSpools,enabled:t}),v=w.useMemo(()=>f?f.filter(b=>{if(!u)return!0;const _=u.toLowerCase();return b.filament_name&&b.filament_name.toLowerCase().includes(_)||b.filament_vendor&&b.filament_vendor.toLowerCase().includes(_)||b.filament_material&&b.filament_material.toLowerCase().includes(_)||String(b.id).includes(_)}):[],[f,u]),g=it({mutationFn:b=>me.linkSpool(b,{spoolTag:p,printerId:i,amsId:s,trayId:o}),onSuccess:()=>{c.invalidateQueries({queryKey:["unlinked-spools"]}),c.invalidateQueries({queryKey:["linked-spools"]}),d(l("spoolman.linkSuccess"),"success"),e()},onError:b=>{d(b.message||l("spoolman.linkFailed"),"error")}});return t?a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ly,{className:"w-5 h-5 text-bambu-green"}),l("spoolman.selectSpool")]}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",i]})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-white/10",children:[a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:u,onChange:b=>m(b.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"})]}),(r||n)&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:r||n,children:["Tag: ",r||n]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:x?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):v.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):v.map(b=>a.jsxs("button",{onClick:()=>g.mutate(b.id),disabled:g.isPending||!p,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[a.jsx("span",{className:"w-6 h-6 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:b.filament_color_hex?`#${b.filament_color_hex}`:"#808080"}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm text-white font-medium truncate",children:b.filament_name||l("spoolman.spoolId")}),a.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[b.filament_vendor?`${b.filament_vendor} · `:"",b.filament_material||"Unknown"," · #",b.id]})]}),a.jsx("span",{className:"text-xs text-bambu-gray",children:b.remaining_weight!=null?`${Math.round(b.remaining_weight)}g`:"—"})]},b.id))}),a.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:a.jsx(Fe,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function Iae({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:i,trayInfo:s}){const{t:o}=Rt(),l=sn(),{showToast:c}=bn(),[d,u]=w.useState(!1),[m,p]=w.useState(null);w.useEffect(()=>{p(null)},[d]);const[f,x]=w.useState(""),[v,g]=w.useState(null),[b,_]=w.useState(!1),[C,P]=w.useState(null);w.useEffect(()=>{t&&u(!1)},[t]);const{data:N,isLoading:A}=Qe({queryKey:["inventory-spools"],queryFn:()=>me.getSpools(),enabled:t}),{data:T}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),enabled:t}),{data:F}=Qe({queryKey:["settings"],queryFn:()=>me.getSettings(),enabled:t}),k=it({mutationFn:le=>me.assignSpool({spool_id:le,printer_id:n,ams_id:r,tray_id:i}),onSuccess:le=>{l.setQueryData(["spool-assignments"],oe=>{const W=(oe||[]).filter(re=>!(re.printer_id===n&&re.ams_id===r&&re.tray_id===i));return W.push(le),W}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),_(!1),g(null),P(null),e()},onError:le=>{c(`${o("inventory.assignFailed")}: ${le.message}`,"error")}}),D=le=>(le??"").trim().toUpperCase(),H=(le,oe)=>{const W=D(le),re=D(oe);return!W||!re?"none":W===re?"exact":re.includes(W)||W.includes(re)?"partial":"none"},z=(le,oe)=>{const W=D(le),re=D(oe);return!W||!re?!1:W===re};if(!t)return null;const X=new Set((T||[]).filter(le=>!(le.printer_id===n&&le.ams_id===r&&le.tray_id===i)).map(le=>le.spool_id)),L=r===254||r===255,ne=N?.filter(le=>!X.has(le.id)&&(L||!le.tag_uid&&!le.tray_uuid));let ie=ne;if(!d&&(s?.profile||s?.type)){const le=D(s.profile||s.type);ie=ie?.filter(oe=>{const W=D(oe.slicer_filament_name||oe.slicer_filament);return le&&W&&W===le})}if(f&&ie){const le=f.toLowerCase();ie=ie.filter(oe=>oe.material.toLowerCase().includes(le)||(oe.brand?.toLowerCase().includes(le)??!1)||(oe.color_name?.toLowerCase().includes(le)??!1)||(oe.subtype?.toLowerCase().includes(le)??!1))}const ee=()=>{if(!m)return;const le=N?.find(oe=>oe.id===m);if(!le){c(o("inventory.assignFailed"),"error");return}if(!F?.disable_filament_warnings&&s){const oe=s.material||s.type,W=H(le.material,oe),re=le.slicer_filament_name||le.slicer_filament,ce=s.profile||s.type,xe=z(re,ce);if(W!=="exact"||!xe){let Ne="profile";W==="none"&&!xe?Ne="material_profile":W==="partial"&&!xe?Ne="partial_profile":W==="none"?Ne="material":W==="partial"&&(Ne="partial"),g(m),P({type:Ne,spoolMaterial:le.material||"",trayMaterial:oe||"",spoolProfile:re||void 0,trayProfile:ce||void 0}),_(!0);return}}k.mutate(m)},ue=()=>{v&&(k.mutate(v),_(!1),g(null))};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-2xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ja,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto",children:[s&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${s.color}`}}),a.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),a.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:f,onChange:le=>x(le.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"})]}),a.jsx("div",{children:A?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):ie&&ie.length>0?a.jsx("div",{className:"max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2",children:ie.map(le=>a.jsxs("button",{onClick:()=>p(le.id),title:le.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${m===le.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[le.brand?`${le.brand} `:"",le.material,le.subtype?` ${le.subtype}`:""]}),a.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[le.rgba&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${le.rgba.substring(0,6)}`}}),a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:le.color_name||""})]}),le.label_weight&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[Math.max(0,Math.round(le.label_weight-le.weight_used))," / ",le.label_weight,"g"]})]},le.id))}):ne&&ne.length===0?a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:o("inventory.noManualSpools")})}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),a.jsxs("div",{className:"flex justify-between items-center p-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{id:"disable-filtering-toggle",type:"checkbox",checked:d,onChange:()=>u(le=>!le),className:"accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary"}),a.jsx("label",{htmlFor:"disable-filtering-toggle",className:"text-xs text-bambu-gray select-none cursor-pointer",children:o("inventory.showAllSpools")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Fe,{onClick:ee,disabled:!m||k.isPending,children:k.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):a.jsxs(a.Fragment,{children:[a.jsx(ja,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]})]}),k.isError&&a.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:k.error.message})]})]}),b&&s&&m&&C&&(()=>{let le="";return C.type==="material"?le=o("inventory.assignMismatchMessage",{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:s.location}):C.type==="partial"?le=o("inventory.assignPartialMismatchMessage",{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:s.location}):C.type==="material_profile"?le=`${o("inventory.assignMismatchMessage",{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:s.location})}
- ${o("inventory.assignProfileMismatchMessage",{spoolProfile:C.spoolProfile||o("common.unknown"),trayProfile:C.trayProfile||o("common.unknown"),location:s.location})}`:C.type==="partial_profile"?le=`${o("inventory.assignPartialMismatchMessage",{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:s.location})}
- ${o("inventory.assignProfileMismatchMessage",{spoolProfile:C.spoolProfile||o("common.unknown"),trayProfile:C.trayProfile||o("common.unknown"),location:s.location})}`:C.type==="profile"&&(le=o("inventory.assignProfileMismatchMessage",{spoolProfile:C.spoolProfile||o("common.unknown"),trayProfile:C.trayProfile||o("common.unknown"),location:s.location})),a.jsx(_n,{title:o("inventory.assignMismatchTitle"),message:le,confirmText:o("inventory.assignMismatchConfirm"),variant:"warning",isLoading:k.isPending,onConfirm:ue,onCancel:()=>{k.isPending||(_(!1),g(null),P(null))}})})()]})}function BW(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 i=String.fromCharCode(65+n);return r?`HT-${i}`:`AMS-${i}`}function J1(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 x0=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function HW(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){const s=n.slice(r.index+r[0].length);for(const o of x0)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,r.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of x0){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",d=l[1]?.trim()||"";return{material:s,brand:c,variant:d}}}const i=e.split(/\s+/);return i.length>=2?{material:i[1],brand:i[0],variant:i.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function ZVe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const JVe={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"},qW=[{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"}],$W=[{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 VW(t){const e=t.toLowerCase().trim();return JVe[e]||null}function e7e(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 zae({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=Rt(),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,x]=w.useState(""),[v,g]=w.useState(""),[b,_]=w.useState(""),[C,P]=w.useState(!1),[N,A]=w.useState(!1),T=w.useRef(""),{data:F,isLoading:k,isError:D}=Qe({queryKey:["cloudSettings"],queryFn:()=>me.getCloudSettings(),enabled:t,retry:!1}),{data:H,isLoading:z}=Qe({queryKey:["localPresets"],queryFn:()=>me.getLocalPresets(),enabled:t}),{data:X,isLoading:L}=Qe({queryKey:["builtinFilaments"],queryFn:()=>me.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:ne,isLoading:ie}=Qe({queryKey:["kprofiles",n,i],queryFn:()=>me.getKProfiles(n,i),enabled:t&&!!n}),{data:ee}=Qe({queryKey:["colorCatalog"],queryFn:()=>me.getColorCatalog(),enabled:t,staleTime:1/0}),ue=it({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const j=d.startsWith("local_"),O=d.startsWith("builtin_"),K=j?parseInt(d.replace("local_",""),10):null,B=O?d.replace("builtin_",""):null,he=j?H?.filament.find(je=>je.id===K):null,I=O?X?.find(je=>je.filament_id===B):null,V=!j&&!O?F?.filament.find(je=>je.setting_id===d):null;if(!j&&!O&&!V)throw new Error("Selected preset not found");if(j&&!he)throw new Error("Selected local preset not found");if(O&&!I)throw new Error("Selected builtin preset not found");const Q=j?he.name:O?I.name:V.name,G=HW(Q),J=m?.slot_id??-1,se=f||r.trayColor?.slice(0,6)||"FFFFFF",fe=Q.replace(/@.+$/,"").trim();let pe,de;const U=G.material.toUpperCase();if(j){const je=(x0.includes(U)?U:he?.filament_type||G.material||"").toUpperCase(),Re={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"};pe=Re[je]||Re[je.replace(/[-\s]?CF$/,"")]||Re[je.replace(/\+$/,"")]||Re[je.split(/[-\s]/)[0]]||"",de=""}else if(O)pe=B,de="";else if(pe=J1(d),de=d,!d.startsWith("GFS"))try{const je=await me.getCloudSettingDetail(d);je.filament_id?pe=je.filament_id:je.base_id&&(pe=J1(je.base_id),console.log(`Derived tray_info_idx from base_id: ${je.base_id} -> ${pe}`))}catch(je){console.warn("Failed to fetch preset detail for filament_id:",je)}let R=j&&he?.nozzle_temp_min?he.nozzle_temp_min:190,ae=j&&he?.nozzle_temp_max?he.nozzle_temp_max:230;if(!j||O||!he?.nozzle_temp_min&&!he?.nozzle_temp_max){const je=(j?x0.includes(U)?U:he?.filament_type||G.material||"":G.material).toUpperCase();je.includes("PLA")?(R=190,ae=230):je.includes("PETG")?(R=220,ae=260):je.includes("ABS")||je.includes("ASA")?(R=240,ae=280):je.includes("TPU")?(R=200,ae=240):je==="PCTG"?(R=220,ae=260):je.includes("PC")?(R=260,ae=300):(je.includes("PA")||je.includes("NYLON"))&&(R=250,ae=290)}const _e=m?.k_value?parseFloat(m.k_value):0,Se=j?x0.includes(U)?U:he?.filament_type||G.material||"PLA":G.material||"PLA",ye=await me.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:pe,tray_type:Se,tray_sub_brands:fe,tray_color:se+"FF",nozzle_temp_min:R,nozzle_temp_max:ae,cali_idx:J,nozzle_diameter:i,setting_id:de,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:_e}),Ae=j?`local_${K}`:O?`builtin_${B}`:d,ve=j?"local":O?"builtin":"cloud";try{await me.saveSlotPreset(n,r.amsId,r.trayId,Ae,fe,ve)}catch(je){console.warn("Failed to save slot preset mapping:",je)}return ye},onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),le=it({mutationFn:async()=>me.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),oe=w.useMemo(()=>{const j=b.toLowerCase(),O=[],K=new Set,B=r.savedPresetId,he=r.trayInfoIdx;if(F?.filament)for(const I of F.filament){K.add(I.setting_id);const Q=B===I.setting_id||he&&(I.setting_id===he||J1(I.setting_id)===he);if(!(j&&!I.name.toLowerCase().includes(j))){if(!Q&&s){const G=e7e(I.name);if(G&&G.toUpperCase()!==s.toUpperCase())continue}O.push({id:I.setting_id,name:I.name,source:"cloud",isUser:ZVe(I.setting_id)})}}if(H?.filament)for(const I of H.filament){const V=`local_${I.id}`;j&&!I.name.toLowerCase().includes(j)||O.push({id:V,name:I.name,source:"local",isUser:!1})}if(X)for(const I of X){if(K.has(I.filament_id))continue;const V=I.filament_id.startsWith("GF")?"GFS"+I.filament_id.slice(2):I.filament_id;K.has(V)||(!j||I.name.toLowerCase().includes(j))&&O.push({id:`builtin_${I.filament_id}`,name:I.name,source:"builtin",isUser:!1})}return O.sort((I,V)=>{const Q={cloud:0,local:1,builtin:2};return I.source!==V.source?Q[I.source]-Q[V.source]:I.isUser&&!V.isUser?-1:!I.isUser&&V.isUser?1:I.name.localeCompare(V.name)})},[F?.filament,H?.filament,X,b,s,r.savedPresetId,r.trayInfoIdx]),W=w.useMemo(()=>{if(!d)return null;let j=null;if(d.startsWith("local_")){const B=parseInt(d.replace("local_",""),10);j=H?.filament.find(I=>I.id===B)?.name||null}else if(d.startsWith("builtin_")){const B=d.replace("builtin_","");j=X?.find(I=>I.filament_id===B)?.name||null}else F?.filament&&(j=F.filament.find(he=>he.setting_id===d)?.name||null);if(!j)return null;let O=j.replace(/@.+$/,"").trim();O.startsWith("# ")&&(O=O.slice(2).trim());const K=HW(O);return{fullName:O,material:K.material,brand:K.brand}},[d,F?.filament,H?.filament,X]),re=W?.fullName||"",ce=w.useMemo(()=>{if(!ee||!W)return[];const{fullName:j,brand:O}=W,K=j.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return ee.filter(B=>{const he=(B.material||"").toUpperCase(),I=B.manufacturer.toUpperCase();if(!(he===K.toUpperCase()||he.includes(K.toUpperCase())||K.toUpperCase().includes(he)))return!1;if(O){const Q=O.toUpperCase();if(!I.includes(Q)&&!Q.includes(I))return!1}return!0})},[ee,W]),xe=w.useMemo(()=>{if(!ne?.profiles||!W)return[];const{fullName:j,material:O,brand:K}=W,B=j.toUpperCase(),he=O.toUpperCase(),I=K.toUpperCase();if(!he||he.length<2)return[];const V=ne.profiles.filter(G=>{const J=G.name.toUpperCase();if(I)return!(!J.includes(I)||!J.includes(he));if(J.includes(B)||J.includes(he))return!0;const fe={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[he]||[];for(const pe of fe)if(J.includes(pe))return!0;return!1}),Q=new Map;for(const G of V){const J=`${G.name}|${G.k_value}`,se=Q.get(J);se?r.extruderId!==void 0&&G.extruder_id===r.extruderId&&se.extruder_id!==r.extruderId&&Q.set(J,G):Q.set(J,G)}return Array.from(Q.values())},[ne?.profiles,W,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&F?.filament){let j=F.filament.find(O=>O.setting_id===r.trayInfoIdx);j||(j=F.filament.find(O=>J1(O.setting_id)===r.trayInfoIdx)),j&&u(j.setting_id)}else if(r.trayInfoIdx&&X?.length){const j=r.trayInfoIdx,O=X.find(K=>K.filament_id===j);O&&u(`builtin_${O.filament_id}`)}if(r.trayColor){const j=r.trayColor.slice(0,6);j&&x(j)}}else u(""),p(null),x(""),g(""),_(""),P(!1),T.current=""},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,F?.filament,X]),w.useEffect(()=>{if(xe.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const j=xe.find(O=>O.slot_id===r.caliIdx);if(j){p(j);return}}p(xe[0])}else p(null)},[d,xe,r.caliIdx]);const Ne=w.useCallback(j=>{j.key==="Escape"&&e()},[e]);w.useEffect(()=>{if(t)return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[t,Ne]);const $=k&&!D||z||L||ie;if(w.useEffect(()=>{if(!$&&d&&d!==T.current){const j=requestAnimationFrame(()=>{const K=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);K&&(T.current=d,K.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(j)}},[d,$]),!t)return null;const Y=d&&!ue.isPending,E=f||r.trayColor?.slice(0,6)||"FFFFFF";return a.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jd,{className:"w-5 h-5 text-bambu-blue"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&a.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[a.jsx("span",{className:"text-white/30",children:"|"}),r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:BW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&a.jsxs("span",{children:["(",r.traySubBrands,")"]})]})]}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[C&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:a.jsxs("div",{className:"text-center space-y-3",children:[a.jsx(nl,{className:"w-16 h-16 text-bambu-green mx-auto"}),a.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),a.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),a.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:BW(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&a.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),$?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?a.jsxs("div",{className:"flex gap-4 h-full",children:[a.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:b,onChange:j=>_(j.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 shrink-0"}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:oe.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):oe.map(j=>a.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:j.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]}),a.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),re&&a.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:re})})]}),xe.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m?.name||"",onChange:j=>{const O=xe.find(K=>K.name===j.target.value);p(O||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:[a.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),xe.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):a.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:c("configureAmsSlot.selectFilamentFirst")}),m&&a.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),ce.length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:ce.map(j=>a.jsxs("button",{onClick:()=>{const O=j.hex_color.replace("#","").toUpperCase();x(O),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),a.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[qW.map(j=>a.jsx("button",{onClick:()=>{x(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),a.jsx("button",{onClick:()=>A(!N),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:c(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:$W.map(j=>a.jsx("button",{onClick:()=>{x(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${E}`}}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:j=>{const O=j.target.value;g(O);const K=VW(O);if(K)x(K);else{const B=O.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(he=>he+he).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&&a.jsx("button",{onClick:()=>{x(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:b,onChange:j=>_(j.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"}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:oe.length===0?a.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):oe.map(j=>a.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-white text-sm truncate",children:j.name}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),re&&a.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:re})})]}),xe.length>0?a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:m?.name||"",onChange:j=>{const O=xe.find(K=>K.name===j.target.value);p(O||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:[a.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),xe.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):a.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:c("configureAmsSlot.selectFilamentFirst")}),m&&a.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),ce.length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:ce.map(j=>a.jsxs("button",{onClick:()=>{const O=j.hex_color.replace("#","").toUpperCase();x(O),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),a.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[qW.map(j=>a.jsx("button",{onClick:()=>{x(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),a.jsx("button",{onClick:()=>A(!N),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:c(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:$W.map(j=>a.jsx("button",{onClick:()=>{x(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${E}`}}),a.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:j=>{const O=j.target.value;g(O);const K=VW(O);if(K)x(K);else{const B=O.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();B.length===6?x(B):B.length===3&&x(B.split("").map(he=>he+he).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&&a.jsx("button",{onClick:()=>{x(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),a.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>le.mutate(),disabled:le.isPending||ue.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:le.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):a.jsxs(a.Fragment,{children:[a.jsx(eo,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),a.jsx(Fe,{onClick:()=>ue.mutate(),disabled:!Y,children:ue.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):a.jsxs(a.Fragment,{children:[a.jsx(jd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ue.isError||le.isError)&&a.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:ue.error?.message||le.error?.message})]})]})}function Uae({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:r,autoUpload:i,validateFile:s,accept:o}){const{t:l}=Rt(),[c,d]=w.useState([]),[u,m]=w.useState(!1),[p,f]=w.useState(!1),[x,v]=w.useState(!0),[g,b]=w.useState(!1),[_,C]=w.useState(!0),[P,N]=w.useState(null),A=w.useRef(null),T=oe=>{oe.preventDefault(),m(!0)},F=oe=>{oe.preventDefault(),m(!1)},k=oe=>{oe.preventDefault(),m(!1),X(Array.from(oe.dataTransfer.files))},D=oe=>{oe.target.files&&X(Array.from(oe.target.files))},H=(oe,W)=>{d(re=>re.map(ce=>ce.file===oe?{...ce,...W}:ce))},z=async oe=>{f(!0);for(const W of oe)if(W.status==="pending"){H(W.file,{status:"uploading"});try{if(W.isZip){const re=await me.extractZipFile(W.file,t,x,g,_);H(W.file,{status:re.errors.length>0&&re.extracted===0?"error":"success",extractedCount:re.extracted,error:re.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:re.errors.length}):void 0})}else{const re=await me.uploadLibraryFile(W.file,t,_);H(W.file,{status:"success"});const ce=r?.(re);if(ce){N(ce),d([]),f(!1);return}}}catch(re){H(W.file,{status:"error",error:re instanceof Error?re.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},X=oe=>{if(N(null),s)for(const re of oe){const ce=s(re);if(ce){N(ce);return}}const W=oe.map(re=>({file:re,status:"pending",isZip:re.name.toLowerCase().endsWith(".zip"),is3mf:re.name.toLowerCase().endsWith(".3mf")}));d(re=>[...re,...W]),i&&oe.length>0&&z(W)},L=oe=>{d(W=>W.filter((re,ce)=>ce!==oe))},ne=c.some(oe=>oe.isZip&&oe.status==="pending"),ie=c.some(oe=>oe.file.name.toLowerCase().endsWith(".stl")&&oe.status==="pending"),ee=c.some(oe=>oe.is3mf&&oe.status==="pending"),ue=c.filter(oe=>oe.status==="pending").length,le=c.length>0&&ue===0&&!p;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("div",{onDragOver:T,onDragLeave:F,onDrop:k,onClick:()=>A.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[a.jsx(Ma,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("p",{className:"text-white font-medium",children:l(u?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),a.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),a.jsx("input",{ref:A,type:"file",multiple:!0,accept:o,className:"hidden",onChange:D}),ne&&a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Qs,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),a.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:x,onChange:oe=>v(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:g,onChange:oe=>b(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),ee&&a.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Ar,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),a.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(ie||ne)&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(rm,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),a.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(ne&&!ie?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),a.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:_,onChange:oe=>C(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((oe,W)=>a.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[oe.isZip?a.jsx(Qs,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):a.jsx(AP,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:oe.file.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(oe.file.size/1024/1024).toFixed(2)," MB",oe.isZip&&oe.status==="pending"&&a.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),oe.extractedCount!==void 0&&a.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:oe.extractedCount})]})]})]}),oe.status==="pending"&&a.jsx("button",{onClick:()=>L(W),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray"})}),oe.status==="uploading"&&a.jsx(dt,{className:"w-4 h-4 text-bambu-green animate-spin"}),oe.status==="success"&&a.jsx(xr,{className:"w-4 h-4 text-green-500"}),oe.status==="error"&&a.jsx("span",{title:oe.error,children:a.jsx(Na,{className:"w-4 h-4 text-red-500"})})]},W))}),P&&a.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Na,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-sm text-red-300",children:P})]})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:e,children:l("common.cancel")}),!le&&a.jsx(Fe,{onClick:()=>z(c),disabled:ue===0||p,children:p?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ma,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ue>0?`(${ue})`:""]})})]})]})})}function GW(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Va(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const t7e=[["PA-CF","PA12-CF","PAHT-CF"]],Bae={};for(const t of t7e){const e=t[0];for(const n of t)Bae[n.toUpperCase()]=e.toUpperCase()}function CC(t){if(!t)return"";const e=t.toUpperCase();return Bae[e]??e}function vD(t,e){return CC(t)===CC(e)}function Ad(t,e,n=40){const r=Va(t),i=Va(e);if(!r||!i||r.length<6||i.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(i.substring(0,2),16),d=parseInt(i.substring(2,4),16),u=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=n}function bS(t,e,n,r){if(r)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`${i}${e+1}`}function Wx(t,e,n){return n?254+e:t>=128?t:t*4+e}function wx(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function Uk(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 WW(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function n7e(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(16).toUpperCase().padStart(8,"0")}function Eu(t,e,n){return`${n7e(t)}${WW(e,4)}${WW(n,4)}`}function KW(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(er(t)?.getTime()??0)>e}function r7e(t,e,n,r){let i=Hae(e,t.nozzle_id);r&&(i=[...i].sort((c,d)=>{const u=(c.remain??-1)>=0?c.remain??-1:101,m=(d.remain??-1)>=0?d.remain??-1:101;return u-m}));const s=i.find(c=>!n.has(c.globalTrayId)&&vD(c.type,t.type)&&Va(c.color)===Va(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&vD(c.type,t.type)&&Ad(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&vD(c.type,t.type));return s??o??l}function Hae(t,e){return t.filter(n=>e==null||n.extruderId===e)}function xS(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=GW(o.tray_color);e.push({type:o.tray_type,color:l,colorName:Zl(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:bS(i.id,o.id,s,!1),globalTrayId:Wx(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:n?.[String(i.id)],remain:o.remain??-1})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=GW(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:Zl(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",traySubBrands:i.tray_sub_brands||"",extruderId:r?255-o:void 0,remain:i.remain??-1})}return e}function XW(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=xS(e);if(r.length===0)return;const i=new Set,s=t.filaments.map(c=>{const d=c.tray_info_idx||"";let u=r.filter(g=>!i.has(g.globalTrayId));c.nozzle_id!=null&&(u=u.filter(g=>g.extruderId===c.nozzle_id)),n&&(u=[...u].sort((g,b)=>{const _=g.remain>=0?g.remain:101,C=b.remain>=0?b.remain:101;return _-C}));let m,p,f,x;if(d){const g=u.filter(b=>b.trayInfoIdx===d);g.length===1?m=g[0]:g.length>1&&(n&&g.sort((b,_)=>{const C=b.remain>=0?b.remain:101,P=_.remain>=0?_.remain:101;return C-P}),p=g.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase()&&Va(b.color)===Va(c.color)),p||(f=g.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase()&&Ad(b.color,c.color))),!p&&!f&&(x=g.find(b=>b.type?.toUpperCase()===c.type?.toUpperCase())))}!m&&!p&&!f&&!x&&(p=u.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase()&&Va(g.color)===Va(c.color)),p||(f=u.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase()&&Ad(g.color,c.color))),!p&&!f&&(x=u.find(g=>g.type?.toUpperCase()===c.type?.toUpperCase())));const v=m||p||f||x||void 0;return v&&i.add(v.globalTrayId),{slot_id:c.slot_id,globalTrayId:v?.globalTrayId??-1}}),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}function a7e(t){return w.useMemo(()=>xS(t),[t])}function qae(t,e,n,r){const i=a7e(e),s=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const d=new Set(Object.values(n));return t.filaments.map(u=>{const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const T=n[m],F=i.find(k=>k.globalTrayId===T);if(F){const k=F.type?.toUpperCase()===u.type?.toUpperCase(),D=Va(F.color)===Va(u.color)||Ad(F.color,u.color);let H;return k&&D?H="match":k?H="type_only":H="mismatch",{...u,loaded:F,hasFilament:!0,typeMatch:k,colorMatch:D,status:H,isManual:!0}}}const p=u.tray_info_idx||"";let f=i.filter(T=>!d.has(T.globalTrayId));u.nozzle_id!=null&&(f=f.filter(T=>T.extruderId===u.nozzle_id)),r&&(f=[...f].sort((T,F)=>{const k=T.remain>=0?T.remain:101,D=F.remain>=0?F.remain:101;return k-D}));let x,v,g,b;if(p){const T=f.filter(F=>F.trayInfoIdx===p);T.length===1?x=T[0]:T.length>1&&(r&&T.sort((F,k)=>{const D=F.remain>=0?F.remain:101,H=k.remain>=0?k.remain:101;return D-H}),v=T.find(F=>F.type?.toUpperCase()===u.type?.toUpperCase()&&Va(F.color)===Va(u.color)),v||(g=T.find(F=>F.type?.toUpperCase()===u.type?.toUpperCase()&&Ad(F.color,u.color))),!v&&!g&&(b=T.find(F=>F.type?.toUpperCase()===u.type?.toUpperCase())))}!x&&!v&&!g&&!b&&(v=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Va(T.color)===Va(u.color)),v||(g=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Ad(T.color,u.color))),!v&&!g&&(b=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())));const _=x||v||g||b||void 0;_&&d.add(_.globalTrayId);const C=!!_,P=C,N=!!x||!!v||!!g;let A;return x||v||g?A="match":b?A="type_only":A="mismatch",{...u,loaded:_,hasFilament:C,typeMatch:P,colorMatch:N,status:A,isManual:!1}})},[t,i,n,r]),o=w.useMemo(()=>{if(s.length===0)return;const d=Math.max(...s.map(m=>m.slot_id||0));if(d<=0)return;const u=new Array(d).fill(-1);return s.forEach(m=>{m.slot_id&&m.slot_id>0&&(u[m.slot_id-1]=m.loaded?.globalTrayId??-1)}),u},[s]),l=s.some(d=>d.status==="mismatch"),c=s.some(d=>d.status==="type_only");return{loadedFilaments:i,filamentComparison:s,amsMapping:o,hasTypeMismatch:l,hasColorMismatch:c}}function i7e(t,e,n,r){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let i=0,s=0,o=0;const l=new Set(Object.values(n));for(const u of t){const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const b=n[m],_=e.find(C=>C.globalTrayId===b);if(_){const C=_.type?.toUpperCase()===u.type?.toUpperCase(),P=Va(_.color)===Va(u.color)||Ad(_.color,u.color);C&&P?i++:C?s++:o++;continue}}let p=e.filter(b=>!l.has(b.globalTrayId));if(u.nozzle_id!=null){const b=p.filter(_=>_.extruderId===u.nozzle_id);b.length>0&&(p=b)}r&&(p=[...p].sort((b,_)=>{const C=b.remain>=0?b.remain:101,P=_.remain>=0?_.remain:101;return C-P}));const f=p.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Va(b.color)===Va(u.color)),x=f?void 0:p.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Ad(b.color,u.color)),v=f||x?void 0:p.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()),g=f??x??v;g&&l.add(g.globalTrayId),f||x?i++:v?s++:o++}const c=t.length;let d="full";return o>0?d="missing":s>0&&(d="partial"),{exactMatches:i,typeOnlyMatches:s,missingTypes:o,totalSlots:c,status:d}}function s7e(t,e,n,r){if(!t?.filaments||t.filaments.length===0)return;const i=xS(e);if(i.length===0)return;const s=new Set(Object.values(n)),o=[];for(const d of t.filaments){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){o.push({slot_id:u,globalTrayId:n[u]});continue}let m=i.filter(g=>!s.has(g.globalTrayId));if(d.nozzle_id!=null){const g=m.filter(b=>b.extruderId===d.nozzle_id);g.length>0&&(m=g)}r&&(m=[...m].sort((g,b)=>{const _=g.remain>=0?g.remain:101,C=b.remain>=0?b.remain:101;return _-C}));const p=m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Va(g.color)===Va(d.color)),f=p?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Ad(g.color,d.color)),x=p||f?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??x;v&&s.add(v.globalTrayId),o.push({slot_id:u,globalTrayId:v?.globalTrayId??-1})}const l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}const YW={useDefault:!0,manualMappings:{},autoConfigured:!1};function o7e(t,e,n,r,i,s,o){const l=fp({queries:t.map(v=>({queryKey:["printer-status",v],queryFn:()=>me.getPrinterStatus(v),enabled:t.length>0,staleTime:5e3}))}),c=w.useMemo(()=>t.map((v,g)=>{const b=l[g],_=b?.data,P=e?.find(H=>H.id===v)?.name||`Printer ${v}`,N=xS(_),A=i[v]||YW,T=XW(n,_,o),F=A.useDefault?r:A.manualMappings,k=s7e(n,_,F,o),D=i7e(n?.filaments,N,F,o);return{printerId:v,printerName:P,status:_,isLoading:b?.isLoading??!1,loadedFilaments:N,autoMapping:T,finalMapping:k,matchStatus:D.status,exactMatches:D.exactMatches,typeOnlyMatches:D.typeOnlyMatches,missingTypes:D.missingTypes,totalSlots:D.totalSlots,config:A}}),[t,l,e,n,i,r,o]),d=l.some(v=>v.isLoading),u=(v,g)=>{s(b=>({...b,[v]:{...b[v]||YW,...g}}))},m=v=>{const g=c.find(C=>C.printerId===v);if(!g||!g.status||!n?.filaments)return;const b=XW(n,g.status,o);if(!b)return;const _={};b.forEach((C,P)=>{C!==-1&&(_[P+1]=C)}),u(v,{useDefault:!1,manualMappings:_,autoConfigured:!0})},p=()=>{for(const v of t)m(v)},f=v=>c.find(b=>b.printerId===v)?.finalMapping,x=c.every(v=>v.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:x}}const $ae={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$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function So(t){return $ae[t.toUpperCase()]||t}const l7e=Object.entries($ae).map(([t,e])=>({code:t,label:`${t} (${e})`}));function c7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Rt(),c=sn(),[d,u]=w.useState(!1),[m,p]=w.useState(o),{data:f}=Qe({queryKey:["printer-status",t],queryFn:()=>me.getPrinterStatus(t),enabled:!!t}),{data:x}=Qe({queryKey:["spool-assignments",t],queryFn:()=>me.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:b,hasColorMismatch:_}=qae(e,f,n),C=w.useMemo(()=>{const z=new Map;for(const X of x||[]){const L=X.ams_id===255,ne=Wx(X.ams_id,X.tray_id,L);z.set(ne,X.spool?.cost_per_kg??null)}return z},[x]),P=w.useMemo(()=>{const z=new Map;for(const X of x||[]){const L=X.ams_id===255,ne=Wx(X.ams_id,X.tray_id,L),ie=X.spool;if(!ie){z.set(ne,null);continue}z.set(ne,Math.max(0,Math.round((ie.label_weight??0)-(ie.weight_used??0))))}return z},[x]),N=w.useMemo(()=>{let z=0;for(const X of g){const L=X.loaded?.globalTrayId;if(L==null)continue;const ie=C.get(L)??null??s;ie>0&&(z+=X.used_grams/1e3*ie)}return z},[g,C,s]),A=w.useMemo(()=>Array.from(C.values()).some(z=>z!=null&&z>0),[C]),T=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(z=>z.nozzle_id!=null)??!1;if(!T||!f)return null;const k=b?"#f97316":_?"#facc15":"#00ae42",D=(z,X)=>{if(z>0)if(X===""){const L={...n};delete L[z],r(L)}else r({...n,[z]:parseInt(X,10)})},H=async()=>{u(!0);try{await me.refreshPrinterStatus(t),await new Promise(z=>setTimeout(z,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(U0,{className:"w-4 h-4",fill:k,stroke:"none"}),a.jsx("span",{children:l("printModal.filamentMapping")}),b?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?a.jsx(ac,{className:"w-4 h-4 ml-auto"}):a.jsx(Un,{className:"w-4 h-4 ml-auto"})]}),m&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:H,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:d,children:[a.jsx(cr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((z,X)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${z.type} - ${Zl(z.color)}`,children:a.jsx(U0,{className:"w-3 h-3",fill:z.color,stroke:z.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[F&&z.nozzle_id!=null&&a.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:z.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:z.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),z.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",z.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:z.loaded?.globalTrayId??"",onChange:L=>D(z.slot_id||0,L.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 ${z.status==="match"?"border-bambu-green/50 text-bambu-green":z.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${z.isManual?"ring-1 ring-blue-400/50":""}`,title:z.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(L=>z.nozzle_id==null||L.extruderId===z.nozzle_id).map(L=>{const ne=P.get(L.globalTrayId),ie=ne!=null?l("printModal.slotRemainingShort",{grams:ne,defaultValue:` - ${ne}g left`}):"";return a.jsxs("option",{value:L.globalTrayId,className:"bg-bambu-dark text-white",children:[L.label,": ",L.traySubBrands||L.type," (",L.colorName,")",ie]},L.globalTrayId)})]}),z.status==="match"?a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}):z.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Rn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Rn,{className:"w-3 h-3 text-orange-400"})})]},X)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:N>0||A?`${i}${N.toFixed(2)}`:"N/A"})]}),b&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function d7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=Rt(),l=w.useMemo(()=>{const u={};for(const m of e){const p=CC(m.type);u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],r(p)}else{const[p,f]=m.split("|");r({...n,[u]:{type:p,color:f}})}};return a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:a.jsx("span",{children:o("printModal.filamentOverride")})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(u=>{const m=n[u.slot_id],p=!!m,f=l[CC(u.type)]||[],x=u.nozzle_id!=null?f.filter(v=>v.extruder_id==null||v.extruder_id===u.nozzle_id):f;return a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[a.jsx("span",{title:`${o("printModal.originalFilament")}: ${u.type} - ${Zl(u.color)}`,children:a.jsx(U0,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:v=>d(u.slot_id,v.target.value),disabled:x.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 ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[a.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",u.type," (",Zl(u.color),")"]}),x.map((v,g)=>a.jsxs("option",{value:`${v.type}|${v.color}`,className:"bg-bambu-dark text-white",children:[v.tray_sub_brands||v.type," (",Zl(v.color),")"]},`${v.type}-${v.color}-${v.tray_sub_brands}-${g}`))]}),p?a.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:a.jsx(eo,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]}),a.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[a.jsx("input",{type:"checkbox",checked:i?.[u.slot_id]??!1,onChange:v=>s?.(u.slot_id,v.target.checked),className:"accent-bambu-green w-3 h-3"}),a.jsx(Iw,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function u7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:r,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=Rt();if(!e||t.length<=1)return null;const c=n.size===t.length;return a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(aa,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(Rn,{className:"w-3 h-3"}),"Selection required"]}),o&&i&&s&&a.jsx("button",{type:"button",onClick:c?s:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(d=>{const u=n.has(d.index);return a.jsxs("button",{type:"button",onClick:()=>r(d.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(u?a.jsx(xs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):a.jsx(to,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?a.jsx("img",{src:za(d.thumbnail_url),alt:`Plate ${d.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(aa,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:d.name||`Plate ${d.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[d.objects.length>0?d.objects.slice(0,3).join(", ")+(d.objects.length>3?"...":""):`${d.filaments.length} filament${d.filaments.length!==1?"s":""}`,d.print_time_seconds!=null?` • ${ps(d.print_time_seconds)}`:""]})]}),!o&&u&&a.jsx(Rr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const m7e=new Set(["IDLE","FINISH","FAILED"]);function h7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=sn(),[i,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await me.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings)),g=r.getQueryData(["settings"]);p=r7e(d,t.loadedFilaments,v,g?.prefer_lowest_filament)}let x="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),g=Va(p.color)===Va(d.color)||Ad(p.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:p,status:x,isManual:f}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.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:i,children:[a.jsx(cr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:m,isManual:p},f)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${d.type} - ${Zl(d.color)}`,children:a.jsx(U0,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),a.jsxs("span",{className:"text-white truncate",children:[d.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?.globalTrayId??"",onChange:x=>o(d.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 ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),Hae(t.loadedFilaments,d.nozzle_id).map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.traySubBrands||x.type," (",x.colorName,")"]},x.globalTrayId))]}),m==="match"?a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Rn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Rn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function p7e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:x,targetLocation:v,onTargetLocationChange:g,slicedForModel:b}){const[_,C]=w.useState(!1),P=s?t:t.filter(re=>re.is_active),N=fp({queries:P.map(re=>({queryKey:["printerStatus",re.id],queryFn:()=>me.getPrinterStatus(re.id),staleTime:5e3}))}),A=w.useMemo(()=>{const re=new Map;return P.forEach((ce,xe)=>{const Ne=N[xe];Ne?.data&&re.set(ce.id,Ne.data)}),re},[P,N]),T=re=>{const ce=A.get(re);return ce?ce.connected?!m7e.has(ce.state??""):!0:!1},F=re=>{const ce=A.get(re);if(!ce)return null;if(!ce.connected)return"Offline";const xe=ce.state;return xe?xe==="RUNNING"?ce.stg_cur_name||"Printing":xe==="PREPARE"?"Preparing":xe==="PAUSE"?"Paused":xe==="IDLE"?"Idle":xe==="FINISH"?"Finished":xe==="FAILED"?"Failed":xe:null},k=w.useMemo(()=>{if(m!=="printer"||!b||_)return P;const re=P.filter(ce=>ce.model===b);return re.length>0?re:P},[P,m,b,_]),D=P.length-k.length,H=w.useMemo(()=>{const re=P.map(ce=>ce.model).filter(ce=>!!ce);return[...new Set(re)].sort()},[P]),z=w.useMemo(()=>{if(!f)return[];const re=P.filter(ce=>ce.model===f&&ce.location).map(ce=>ce.location).filter(ce=>!!ce);return[...new Set(re)].sort()},[P,f]),X=p&&x&&H.length>0,L=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(k.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Wa,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const ne=re=>{o&&T(re)||(i?e.includes(re)?n(e.filter(ce=>ce!==re)):n([...e,re]):n([re]))},ie=()=>{const re=o?k.filter(ce=>!T(ce.id)):k;n(re.map(ce=>ce.id))},ee=()=>{n([])},ue=(re,ce,xe)=>{xe.stopPropagation(),!(!d||!u)&&(ce?d(re):u(re,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},le=re=>e.includes(re),oe=e.length,W=re=>l?.find(ce=>ce.printerId===re);return a.jsxs("div",{className:"space-y-2 mb-6",children:[X&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{p("printer"),x(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[a.jsx(Ar,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const re=b&&H.includes(b)?b:H[0];x(re)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="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:[a.jsx(Fu,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",b||"Model"]})]})]}),m==="model"&&X&&a.jsxs("div",{className:"space-y-3 mb-4",children:[!b&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:re=>{x(re.target.value||null),g&&g(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:[a.jsx("option",{value:"",children:"Select a model..."}),H.map(re=>a.jsx("option",{value:re,children:re},re))]})]}),f&&z.length>0&&g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:v||"",onChange:re=>g(re.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:[a.jsx("option",{value:"",children:"Any location"}),z.map(re=>a.jsx("option",{value:re,children:re},re))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&i&&k.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:oe===0?"Select printers":`${oe} printer${oe!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[oe<k.length&&a.jsx("button",{type:"button",onClick:ie,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),oe>0&&a.jsx("button",{type:"button",onClick:ee,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&k.map(re=>{const ce=le(re.id),xe=W(re.id),Ne=xe&&!xe.config.useDefault,$=T(re.id),Y=o&&$,E=F(re.id);return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>ne(re.id),disabled:Y,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Y?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":ce?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${re.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${Y?"bg-bambu-dark-tertiary":ce?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Ar,{className:`w-5 h-5 ${Y?"text-bambu-gray/50":ce?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:`font-medium ${Y?"text-bambu-gray":"text-white"}`,children:[re.name,!re.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[re.model||"Unknown model"," • ",re.ip_address]})]}),E&&a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${$?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:E}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${Y?"border-bambu-gray/30":ce?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:ce&&a.jsx(Rr,{className:"w-3 h-3 text-white"})})]}),ce&&L&&xe&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:j=>j.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:Ne,onChange:j=>ue(re.id,j.target.checked,j),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"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${xe.matchStatus==="full"?"text-bambu-green":xe.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",xe.exactMatches,"/",xe.totalSlots," matched)"]}),xe.isLoading&&a.jsx(cr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),Ne&&a.jsxs("button",{type:"button",onClick:j=>{j.stopPropagation(),d(re.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:[a.jsx(zQ,{className:"w-3 h-3"}),"Auto"]})]}),Ne&&a.jsx(h7e,{printerResult:xe,filamentReqs:c.filaments,onUpdateConfig:j=>u(re.id,j)})]})]},re.id)}),m==="printer"&&D>0&&!_&&a.jsxs("button",{type:"button",onClick:()=>C(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(Rn,{className:"w-3 h-3 text-yellow-400"}),D," other printer",D>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&b&&a.jsx("button",{type:"button",onClick:()=>C(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",b," printers"]})}),m==="printer"&&oe===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const f7e=[{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 g7e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(Hw,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(ac,{className:"w-4 h-4 ml-auto"}):a.jsx(Un,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:f7e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.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:a.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 b7e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=Rt(),[d,u]=w.useState(""),[m,p]=w.useState(""),[f,x]=w.useState(!0),[v,g]=w.useState(!0),b=w.useRef(null),_=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){_.current=!1;return}if(!_.current){_.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:eF(k)})),u(J3(k,n)),p(MH(k,r)),x(!0),g(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const C=k=>{e({...t,scheduleType:k})},P=(k,D)=>{const H=kye(k,n),z=Nye(D);x(!!H),g(!!z),H&&z&&(H.setHours(z.hours,z.minutes,0,0),H>new Date&&e({...t,scheduledTime:eF(H)}))},N=k=>{u(k),P(k,m)},A=k=>{p(k),P(d,k)},T=k=>{const D=k.target.value;if(D){const H=new Date(D);isNaN(H.getTime())||(u(J3(H,n)),p(MH(H,r)),x(!0),g(!0),e({...t,scheduledTime:D}))}},F=()=>{b.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.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:()=>C("asap"),children:[a.jsx(Qn,{className:"w-4 h-4"}),"ASAP"]}),a.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:()=>C("scheduled"),children:[a.jsx(Yr,{className:"w-4 h-4"}),"Scheduled"]}),a.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:()=>C("manual"),children:[a.jsx(AQ,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${f?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:d,onChange:k=>N(k.target.value),placeholder:wye(n)}),a.jsx("button",{type:"button",onClick:F,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(Yr,{className:"w-4 h-4"})}),a.jsx("input",{ref:b,type:"datetime-local",className:"absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none",value:t.scheduledTime,onChange:T,tabIndex:-1})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${v?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:k=>A(k.target.value),placeholder:Sye(r)})})]}),(!f||!v)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.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"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[a.jsx(Ud,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),l&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"gcodeInjection",checked:t.gcodeInjection,onChange:k=>e({...t,gcodeInjection:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"gcodeInjection",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(oy,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),s&&t.scheduleType!=="manual"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"staggerEnabled",checked:t.staggerEnabled,onChange:k=>e({...t,staggerEnabled:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"staggerEnabled",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(aa,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),t.staggerEnabled&&a.jsxs("div",{className:"ml-6 space-y-3",children:[a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerGroupSize","Group size")}),a.jsx("input",{type:"number",min:1,max:o,value:t.staggerGroupSize,onChange:k=>e({...t,staggerGroupSize:Math.max(1,parseInt(k.target.value)||1)}),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"})]}),a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerInterval","Interval (min)")}),a.jsx("input",{type:"number",min:1,max:60,value:t.staggerIntervalMinutes,onChange:k=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(k.target.value)||1)}),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"})]})]}),o>0&&(()=>{const k=Math.ceil(o/t.staggerGroupSize),D=o%t.staggerGroupSize,H=(k-1)*t.staggerIntervalMinutes;return a.jsxs("p",{className:"text-xs text-bambu-gray",children:[c("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:o,groups:k,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),D!==0&&t.staggerGroupSize<o?` (${c("printModal.staggerLastGroup","last group: {{count}}",{count:D})})`:"",k>1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:H})})`:""]})})()]})]}),a.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 Tc={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},wD={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function ec({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c}){const{t:d}=Rt(),u=sn(),{showToast:m}=bn(),{hasPermission:p}=wr(),f=!!n&&!e,[x,v]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[g,b]=w.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),_=g.size===1?[...g][0]:null,[C,P]=w.useState(1),[N,A]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Tc.bed_levelling,flow_cali:i.flow_cali??Tc.flow_cali,vibration_cali:i.vibration_cali??Tc.vibration_cali,layer_inspect:i.layer_inspect??Tc.layer_inspect,timelapse:i.timelapse??Tc.timelapse}:Tc),[T,F]=w.useState(()=>{if(t==="edit-queue-item"&&i){let pt="asap";i.manual_start?pt="manual":i.scheduled_time&&!KW(i.scheduled_time)&&(pt="scheduled");let Wt="";if(i.scheduled_time&&!KW(i.scheduled_time)){const Ut=er(i.scheduled_time)??new Date;Wt=eF(Ut)}return{scheduleType:pt,scheduledTime:Wt,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:wD.staggerGroupSize,staggerIntervalMinutes:wD.staggerIntervalMinutes}}return wD}),[k,D]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const pt={};return i.ams_mapping.forEach((Wt,Ut)=>{Wt!==-1&&(pt[Ut+1]=Wt)}),pt}return{}}),[H,z]=w.useState({}),[X,L]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ne,ie]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[ee,ue]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[le,oe]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const pt={};for(const Wt of i.filament_overrides)pt[Wt.slot_id]={type:Wt.type,color:Wt.color};return pt}return{}}),[W,re]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const pt={};for(const Wt of i.filament_overrides)pt[Wt.slot_id]=Wt.force_color_match===!0;return pt}return{}}),[ce]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[xe]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[Ne,$]=w.useState(!1),[Y,E]=w.useState({current:0,total:0}),[j,O]=w.useState(null),[K,B]=w.useState(new Set),he=x.length,I=x.length>0?x[0]:null,{data:V}=Qe({queryKey:["settings"],queryFn:me.getSettings}),Q=w.useRef(!1);w.useEffect(()=>{!V||Q.current||t==="edit-queue-item"||(Q.current=!0,A({bed_levelling:V.default_bed_levelling??Tc.bed_levelling,flow_cali:V.default_flow_cali??Tc.flow_cali,vibration_cali:V.default_vibration_cali??Tc.vibration_cali,layer_inspect:V.default_layer_inspect??Tc.layer_inspect,timelapse:V.default_timelapse??Tc.timelapse}))},[V,t]);const G=w.useRef(!1);w.useEffect(()=>{!V||G.current||t==="edit-queue-item"||(G.current=!0,F(pt=>({...pt,staggerGroupSize:V.stagger_group_size??pt.staggerGroupSize,staggerIntervalMinutes:V.stagger_interval_minutes??pt.staggerIntervalMinutes})))},[V,t]);const J=So(V?.currency||"USD"),se=V?.default_filament_cost??0,{data:fe,isLoading:pe}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:de}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&X==="printer"||f&&t==="reprint"}),{data:U}=Qe({queryKey:["archive",e],queryFn:()=>me.getArchive(e),enabled:!!e&&!f}),{data:R}=Qe({queryKey:["library-file",n],queryFn:()=>me.getLibraryFile(n),enabled:f&&!!n}),ae=U?.sliced_for_model||R?.sliced_for_model||null,{data:_e,isError:Se}=Qe({queryKey:["archive-plates",e],queryFn:()=>me.getArchivePlates(e),enabled:!!e&&!f,retry:!1}),{data:ye}=Qe({queryKey:["library-file-plates",n],queryFn:()=>me.getLibraryFilePlates(n),enabled:f&&!!n}),Ae=f?ye:_e,{data:ve,isError:je}=Qe({queryKey:["archive-filaments",e,_],queryFn:()=>me.getArchiveFilamentRequirements(e,_??void 0),enabled:!!e&&!f&&(_!==null||!Ae?.is_multi_plate),retry:!1}),{data:Re}=Qe({queryKey:["library-file-filaments",n,_],queryFn:()=>me.getLibraryFileFilamentRequirements(n,_??void 0),enabled:f&&!!n&&(_!==null||!Ae?.is_multi_plate)}),Ee=!f&&(Se||je),Te=f?Re:ve,Me=w.useMemo(()=>{if(!(_===null||!Ae?.plates?.length))return Ae.plates.find(pt=>pt.index===_)?.name||void 0},[Ae,_]),{data:Be}=Qe({queryKey:["available-filaments",ne,ee],queryFn:()=>me.getAvailableFilaments(ne,ee??void 0),enabled:X==="model"&&!!ne}),{data:Ke}=Qe({queryKey:["printer-status",I],queryFn:()=>me.getPrinterStatus(I),enabled:!!I}),{amsMapping:tt}=qae(Te,Ke,k,V?.prefer_lowest_filament),te=o7e(x,fe,Te,k,H,z,V?.prefer_lowest_filament);w.useEffect(()=>{Ae?.plates&&Ae.plates.length>=1&&g.size===0&&b(new Set([Ae.plates[0].index]))},[Ae,g.size]),w.useEffect(()=>{if(t==="edit-queue-item")return;const pt=fe?.filter(Wt=>Wt.is_active)||[];pt.length===1&&x.length===0&&v([pt[0].id])},[t,fe,x.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(x.sort())!==JSON.stringify(ce.sort())||_!==xe)&&(D({}),z({}),B(new Set)):(D({}),z({}),B(new Set))},[t,x,_,ce,xe]);const[Ie,be]=w.useState(ne),[$e,He]=w.useState(_);w.useEffect(()=>{(ne!==Ie||_!==$e)&&(be(ne),He(_),(t!=="edit-queue-item"||Ie!==null)&&(oe({}),re({})))},[ne,_,Ie,$e,t]),w.useEffect(()=>{if(!V?.per_printer_mapping_expanded||x.length<=1)return;const pt=x.filter(Wt=>{if(K.has(Wt))return!1;const Ut=te.printerResults.find(ze=>ze.printerId===Wt);return Ut&&Ut.status&&!Ut.isLoading});pt.length>0&&(B(Wt=>{const Ut=new Set(Wt);return pt.forEach(ze=>Ut.add(ze)),Ut}),pt.forEach(Wt=>{te.autoConfigurePrinter(Wt)}))},[V?.per_printer_mapping_expanded,x,K,te]),w.useEffect(()=>{const pt=Wt=>{Wt.key==="Escape"&&!Ne&&o()};return window.addEventListener("keydown",pt),()=>window.removeEventListener("keydown",pt)},[o,Ne]);const ge=Ae?.is_multi_plate??!1,Pe=Ae?.plates??[],qe=w.useMemo(()=>{const pt=new Map;return de&&de.forEach(Wt=>{const Ut=Wt.ams_id===255,ze=Wx(Wt.ams_id,Wt.tray_id,Ut),st=pt.get(Wt.printer_id)??new Map;st.set(ze,Wt),pt.set(Wt.printer_id,st)}),pt},[de]),Ze=w.useMemo(()=>{if(!j||j.length===0)return"";const pt=j.map(Wt=>d("printModal.insufficientFilamentLine",{printer:Wt.printerName,slot:Wt.slotLabel,required:Math.round(Wt.requiredGrams),remaining:Math.round(Wt.remainingGrams)}));return[d("printModal.insufficientFilamentMessage"),...pt].join(`
- `)},[j,d]),ut=it({mutationFn:pt=>me.addToQueue(pt)}),vt=it({mutationFn:pt=>me.updateQueueItem(i.id,pt),onSuccess:()=>{u.invalidateQueries({queryKey:["queue"]}),m("Queue item updated"),l?.(),o()},onError:pt=>{m(pt.message||"Failed to update queue item","error")}}),wt=T.staggerEnabled&&x.length>1,$t=async(pt,Wt)=>{if(pt?.preventDefault(),!Wt?.skipFilamentCheck&&!V?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&X==="printer"){const Ce=[],We=Te?.filaments??[];if(We.length>0&&qe.size>0){const Je=(Xe,Ye)=>!Number.isFinite(Xe)||Xe<=0||!Number.isFinite(Ye)||Ye<0?null:Math.max(0,Xe-Ye);for(const Xe of x){const Ye=x.length>1?te.getFinalMapping(Xe):tt;if(!Ye)continue;const St=x.length>1?te.printerResults.find(gt=>gt.printerId===Xe)?.status:Ke,et=xS(St),jt=new Map(et.map(gt=>[gt.globalTrayId,gt.label])),bt=qe.get(Xe),Ve=fe?.find(gt=>gt.id===Xe)?.name??`Printer ${Xe}`;bt&&We.forEach(gt=>{if(!gt.slot_id||gt.slot_id<=0)return;const Et=Ye[gt.slot_id-1];if(!Number.isFinite(Et)||Et<0)return;const on=bt.get(Et)?.spool;if(!on)return;const fn=Je(on.label_weight,on.weight_used);fn!==null&&(fn>=gt.used_grams||Ce.push({printerName:Ve,slotLabel:jt.get(Et)??`Slot ${gt.slot_id}`,requiredGrams:gt.used_grams,remainingGrams:fn}))})}}if(Ce.length>0){O(Ce);return}}if(X==="printer"&&x.length===0){m("Please select at least one printer","error");return}if(X==="model"&&!ne){m("Please select a target printer model","error");return}$(!0);const Ut=g.size>1?Pe.filter(Ce=>g.has(Ce.index)):[null],ze=X==="model"?Ut.length:x.length*Ut.length;E({current:0,total:ze});const st={success:0,failed:0,errors:[]},ht=Ce=>{if(x.length>1){const We=H[Ce];if(We&&!We.useDefault)return te.getFinalMapping(Ce)}return tt},Le=(()=>{const Ce=[];if(Te?.filaments)for(const We of Te.filaments){const Je=le[We.slot_id],Xe=W[We.slot_id]??!1,Ye=Je?.type??We.type,St=Je?.color??We.color;(Je||Xe)&&Ce.push({slot_id:We.slot_id,type:Ye,color:St,color_name:Zl(St),force_color_match:Xe})}else for(const[We,{type:Je,color:Xe}]of Object.entries(le)){const Ye=parseInt(We,10),St=W[Ye]??!1;Ce.push({slot_id:Ye,type:Je,color:Xe,color_name:Zl(Xe),force_color_match:St})}return Ce.length>0?Ce:void 0})(),Oe=(Ce,We)=>({printer_id:X==="printer"?Ce:null,target_model:X==="model"?ne:null,target_location:X==="model"?ee:null,filament_overrides:X==="model"?Le:void 0,archive_id:f?void 0:e,library_file_id:f?n:void 0,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,gcode_injection:T.gcodeInjection,manual_start:T.scheduleType==="manual",ams_mapping:Ce?ht(Ce):void 0,plate_id:We!==void 0?We:_,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():void 0,...N,project_id:c??void 0});if(X==="model"){if(t==="reprint"){m("Model-based assignment only works with queue mode","error"),$(!1);return}let Ce=0;for(const We of Ut){Ce++,E({current:Ce,total:ze});const Je=We?We.index:_;try{if(t==="edit-queue-item"&&!We){const Xe={printer_id:null,target_model:ne,target_location:ee,filament_overrides:Le||null,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,gcode_injection:T.gcodeInjection,manual_start:T.scheduleType==="manual",ams_mapping:void 0,plate_id:Je,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():null,...N};await vt.mutateAsync(Xe)}else{const Xe=Oe(null,Je);Xt>1&&(Xe.quantity=Xt),await ut.mutateAsync(Xe)}st.success++}catch(Xe){st.failed++;const Ye=We?We.name||`Plate ${We.index}`:"";st.errors.push(Ye?`${Ye}: ${Xe.message}`:Xe.message)}}}else{const Ce=T.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&x.length>1,We=Ce?T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).getTime():Date.now():0;let Je=0;for(const Xe of Ut){const Ye=Xe?Xe.index:_;for(let St=0;St<x.length;St++){const et=x[St];Je++,E({current:Je,total:ze});try{if(t==="reprint"&&!Ce){const jt=ht(et);if(f?await me.printLibraryFile(n,et,{plate_id:_??void 0,plate_name:Me,ams_mapping:jt,...N,project_id:c}):await me.reprintArchive(e,et,{plate_id:_??void 0,plate_name:Me,ams_mapping:jt,...N}),Xt>1){const bt=Oe(et,Ye);bt.quantity=Xt-1,await ut.mutateAsync(bt)}}else if(t==="edit-queue-item"&&Je===1){const jt=ht(et),bt={printer_id:et,target_model:null,target_location:null,require_previous_success:T.requirePreviousSuccess,auto_off_after:T.autoOffAfter,gcode_injection:T.gcodeInjection,manual_start:T.scheduleType==="manual",ams_mapping:jt,plate_id:Ye,scheduled_time:T.scheduleType==="scheduled"&&T.scheduledTime?new Date(T.scheduledTime).toISOString():null,...N};await vt.mutateAsync(bt)}else{const jt=Oe(et,Ye);if(Xt>1&&(jt.quantity=Xt),Ce){const bt=Math.floor(St/T.staggerGroupSize);if(bt>0){const Ve=bt*T.staggerIntervalMinutes*6e4;jt.scheduled_time=new Date(We+Ve).toISOString()}}await ut.mutateAsync(jt)}st.success++}catch(jt){st.failed++;const bt=fe?.find(Et=>Et.id===et)?.name||`Printer ${et}`,Ve=Xe?Xe.name||`Plate ${Xe.index}`:"",gt=Ve?`${bt} (${Ve})`:bt;st.errors.push(`${gt}: ${jt.message}`)}}}}$(!1),st.failed===0?(t==="reprint"&&wt?m(d("queue.itemsQueued",{count:st.success})):t!=="reprint"&&(t==="edit-queue-item"?m("Queue item updated"):st.success===1?m(X==="model"?`Queued for any ${ne}`:d("queue.printQueued")):m(d("queue.itemsQueued",{count:st.success}))),u.invalidateQueries({queryKey:["queue"]}),l?.(),o()):st.success===0?m(`Failed: ${st.errors[0]}`,"error"):(m(`${st.success} succeeded, ${st.failed} failed`,"error"),u.invalidateQueries({queryKey:["queue"]}))},Qt=Ne||vt.isPending,en=w.useMemo(()=>!(Qt||X==="printer"&&x.length===0||X==="model"&&!ne||X==="model"&&t==="reprint"||ge&&g.size===0),[x.length,X,ne,t,ge,g.size,Qt]),Xt=X==="printer"&&x.length>1?1:C,Ge=(()=>{const pt=x.length;if(t==="reprint"){const Wt=wt&&pt>1;let Ut=Wt?d("printModal.staggerToPrinters",{count:pt,defaultValue:"Stagger to {{count}} printers"}):pt>1?d("queue.printToPrinters",{count:pt}):d("queue.print");return Xt>1&&(Ut=`${Ut} ×${Xt}`),{title:d(f?"queue.print":"queue.reprint"),icon:Ar,submitText:Ut,submitIcon:Wt?Yr:Ar,loadingText:Y.total>1?d("queue.sendingProgress",{current:Y.current,total:Y.total}):d("queue.sending")}}if(t==="add-to-queue"){let Wt=d("queue.addToQueue");return g.size>1?Wt=d("queue.queueSelectedPlates",{count:g.size}):pt>1&&(Wt=d("queue.queueToPrinters",{count:pt})),Xt>1&&(Wt=`${Wt} ×${Xt}`),{title:d("queue.schedulePrint"),icon:Yr,submitText:Wt,submitIcon:Yr,loadingText:Y.total>1?d("queue.addingProgress",{current:Y.current,total:Y.total}):d("queue.adding")}}return{title:d("queue.editQueueItem"),icon:ai,submitText:d("common.save"),submitIcon:ai,loadingText:Y.total>1?d("queue.savingProgress",{current:Y.current,total:Y.total}):d("common.saving")}})(),Ft=Ge.icon,Yt=Ge.submitIcon,Pt=I&&g.size<=1&&(f||(ge?_!==null:!0));return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:Ne?void 0:o,children:[a.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:pt=>pt.stopPropagation(),children:a.jsxs(Mt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ft,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:Ge.title})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:o,disabled:Ne,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:$t,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to"," ",s?.length===1&&fe?a.jsx("span",{className:"text-white",children:fe.find(pt=>pt.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(u7e,{plates:Pe,isMultiPlate:ge,selectedPlates:g,onToggle:pt=>{b(Wt=>{const Ut=new Set(Wt);return t==="add-to-queue"?Ut.has(pt)?Ut.delete(pt):Ut.add(pt):(Ut.clear(),Ut.add(pt)),Ut})},onSelectAll:t==="add-to-queue"?()=>b(new Set(Pe.map(pt=>pt.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>b(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&a.jsx(p7e,{printers:fe||[],selectedPrinterIds:x,onMultiSelect:v,isLoading:pe,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:te.printerResults,filamentReqs:Te,onAutoConfigurePrinter:te.autoConfigurePrinter,onUpdatePrinterConfig:te.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":X,onAssignmentModeChange:t!=="reprint"?L:void 0,targetModel:ne,onTargetModelChange:t!=="reprint"?ie:void 0,targetLocation:ee,onTargetLocationChange:t!=="reprint"?ue:void 0,slicedForModel:ae}),X==="model"&&ne&&Te&&Be&&Be.length>0&&a.jsx(d7e,{filamentReqs:Te,availableFilaments:Be,overrides:le,onChange:oe,forceColorMatch:W,onForceColorMatchChange:(pt,Wt)=>re(Ut=>({...Ut,[pt]:Wt}))}),ae&&X==="printer"&&x.length===1&&(()=>{const pt=fe?.find(Wt=>Wt.id===x[0]);return pt&&pt.model&&ae!==pt.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",ae,", but printing on ",pt.model]})]}):null})(),Ee&&a.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:[a.jsx(Wa,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Pt&&!Ee&&x.length===1&&a.jsx(c7e,{printerId:I,filamentReqs:Te,manualMappings:k,onManualMappingChange:D,defaultExpanded:!!s?.length||(V?.per_printer_mapping_expanded??!1),currencySymbol:J,defaultCostPerKg:se}),(t==="reprint"||he>0||X==="model"&&ne)&&a.jsx(g7e,{options:N,onChange:A,defaultExpanded:!!s?.length}),t!=="edit-queue-item"&&(X==="model"||x.length<=1)&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("label",{htmlFor:"printQuantity",className:"text-sm text-bambu-gray whitespace-nowrap",children:d("queue.quantity","Quantity")}),a.jsx("input",{id:"printQuantity",type:"number",min:1,max:999,value:C,onChange:pt=>P(Math.max(1,Math.min(999,parseInt(pt.target.value)||1))),className:"w-20 px-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green"}),C>1&&a.jsx("span",{className:"text-xs text-bambu-gray",children:d("queue.quantityHint","Creates {{count}} queue items",{count:C})})]}),t==="reprint"&&X==="printer"&&x.length>1&&a.jsxs("div",{className:"space-y-2 pb-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"staggerEnabledReprint",checked:T.staggerEnabled,onChange:pt=>F({...T,staggerEnabled:pt.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"staggerEnabledReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(aa,{className:"w-3.5 h-3.5"}),d("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),T.staggerEnabled&&(()=>{const pt=T.staggerGroupSize,Wt=T.staggerIntervalMinutes,Ut=Math.ceil(x.length/pt),ze=(Ut-1)*Wt;return a.jsxs("p",{className:"ml-6 text-xs text-bambu-gray",children:[d("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:x.length,groups:Ut,size:pt,interval:Wt}),Ut>1?` (${d("printModal.staggerTotal","total: {{minutes}} min",{minutes:ze})})`:""]})})()]}),t!=="reprint"&&a.jsx(b7e,{options:T,onChange:F,dateFormat:V?.date_format||"system",timeFormat:V?.time_format||"system",canControlPrinter:p("printers:control"),showStagger:t==="add-to-queue"&&X==="printer"&&x.length>1,printerCount:x.length,hasGcodeSnippets:!!V?.gcode_snippets}),t==="reprint"&&!!V?.gcode_snippets&&Xt>1&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:T.gcodeInjection,onChange:pt=>F({...T,gcodeInjection:pt.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"gcodeInjectionReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[a.jsx(oy,{className:"w-3.5 h-3.5"}),d("printModal.gcodeInjection","Inject auto-print G-code")]})]}),vt.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:vt.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:Ne,children:"Cancel"}),a.jsx(Fe,{type:"submit",disabled:!en,className:"flex-1",children:Qt?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),Ge.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(Yt,{className:"w-4 h-4"}),Ge.submitText]})})]})]})]})}),j&&j.length>0&&a.jsx(_n,{title:d("printModal.insufficientFilamentTitle"),message:Ze,confirmText:d("printModal.printAnyway"),cancelText:d("common.cancel"),variant:"warning",onConfirm:()=>{O(null),$t(void 0,{skipFilamentCheck:!0})},onCancel:()=>O(null)})]})}function QW({value:t}){const{t:e}=Rt(),[n,r]=w.useState(!1),i=async()=>{try{await navigator.clipboard.writeText(t),r(!0),setTimeout(()=>r(!1),2e3)}catch{}};return a.jsx("button",{onClick:i,className:"ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:e(n?"printers.copied":"printers.copyToClipboard"),children:n?a.jsx(Rr,{className:"w-3.5 h-3.5 text-bambu-green"}):a.jsx(Fs,{className:"w-3.5 h-3.5"})})}function x7e({printer:t,status:e,totalPrintHours:n,onClose:r}){const{t:i}=Rt();w.useEffect(()=>{const o=l=>{l.key==="Escape"&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[r]);const s=[];if(s.push({label:i("printers.model"),value:t.model??"—"}),s.push({label:i("common.status"),value:a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${e?.connected?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?.connected?"bg-bambu-green":"bg-red-400"}`}),e?.connected?i("printers.status.available"):i("printers.status.offline")]})}),e?.state){const o={IDLE:"printers.status.idle",RUNNING:"printers.status.printing",PAUSE:"printers.status.paused",FINISH:"printers.status.finished",FAILED:"printers.status.error"};s.push({label:i("printers.state"),value:i(o[e.state]??"printers.status.unknown")})}if(s.push({label:i("printers.ipAddress"),value:a.jsxs("span",{className:"flex items-center",children:[a.jsx("span",{className:"font-mono",children:t.ip_address}),a.jsx(QW,{value:t.ip_address})]})}),s.push({label:i("printers.serialNumber"),value:a.jsxs("span",{className:"flex items-center",children:[a.jsx("span",{className:"font-mono truncate",children:t.serial_number}),a.jsx(QW,{value:t.serial_number})]})}),e?.wired_network)s.push({label:i("printers.networkLabel","Network"),value:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(gO,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-bambu-green",children:i("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=SJ(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(RQ,{className:`w-4 h-4 ${o.color}`}),a.jsx("span",{className:o.color,children:i(o.labelKey)}),a.jsxs("span",{className:"text-bambu-gray text-xs",children:["(",e.wifi_signal," dBm)"]})]})})}return s.push({label:i("printers.firmware"),value:e?.firmware_version??"—"}),e?.developer_mode!=null&&s.push({label:i("printers.developerMode"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.developer_mode?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.developer_mode?i("printers.enabled"):i("printers.disabled")})}),s.push({label:i("printers.nozzleCount"),value:t.nozzle_count}),e?.sdcard!=null&&s.push({label:i("printers.sdCard"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.sdcard?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.sdcard?i("printers.inserted"):i("printers.notInserted")})}),s.push({label:i("printers.autoArchive"),value:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.auto_archive?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:t.auto_archive?i("printers.enabled"):i("printers.disabled")})}),n!=null&&n>0&&s.push({label:i("printers.totalPrintHours"),value:`${Math.round(n)}h`}),t.location&&s.push({label:i("printers.sort.location"),value:t.location}),s.push({label:i("printers.addedOn"),value:Qf(t.created_at)}),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:r,children:a.jsx(At,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"flex justify-center mb-4",children:a.jsx("img",{src:wJ(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),a.jsx("div",{className:"space-y-0",children:s.map((o,l)=>a.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[a.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),a.jsx("span",{className:"text-sm text-white text-right",children:o.value})]},l))})]})})})}function y7e(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 SD({trayColor:t,trayType:e,isEmpty:n,slotNumber:r}){return a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center",style:{backgroundColor:t?`#${t}`:e?"#333":"transparent",borderColor:n?"#666":"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:a.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&y7e(t)?"#000":"#fff"},children:r})})}function v7e(t,e){const n=t.split(".").map(i=>parseInt(i,10)||0),r=e.split(".").map(i=>parseInt(i,10)||0);for(;n.length<4;)n.push(0);for(;r.length<4;)r.push(0);for(let i=0;i<4;i++)if(n[i]!==r[i])return n[i]-r[i];return 0}function ZW(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function _D(t){return(t??.02).toFixed(3)}function JW({side:t}){const{mode:e}=wg(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return a.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 Vae(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 Gae(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function Wae({slot:t,index:e,activeStatus:n,filamentName:r,children:i}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&u.current&&m.current){const P=u.current.getBoundingClientRect(),N=m.current.offsetHeight,T=P.top-56,F=window.innerHeight-P.bottom;T<N+12&&F>T?d("bottom"):d("top")}},[o]);const v=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const b=AO(t.filament_color),_=Vae(t.nozzle_type,s),C=Gae(t.nozzle_type,s);return a.jsxs("div",{ref:u,className:"relative",onMouseEnter:v,onMouseLeave:g,children:[i,o&&a.jsxs("div",{ref:m,className:`
- absolute left-1/2 -translate-x-1/2 z-50
- ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
- animate-in fade-in-0 zoom-in-95 duration-150
- `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsx("div",{className:"w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:f?a.jsxs("div",{className:"px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap",children:["Slot ",e+1," — Empty"]}):a.jsxs("div",{className:"p-2.5 space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.nozzle_diameter," mm"]})]}),_&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleType")}),a.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[100px]",children:_})]}),C&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFlow")}),a.jsx("span",{className:"text-xs text-white font-semibold",children:C})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleStatus")}),a.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&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.wear,"%"]})]}),t.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.max_temp,"°C"]})]}),t.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate max-w-[80px]",children:t.serial_number})]}),(b||t.filament_type)&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFilament")}),a.jsxs("div",{className:"flex items-center gap-1",children:[b&&a.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:b}}),a.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:r||t.filament_type||t.filament_id||""})]})]})]})}),a.jsx("div",{className:`
- absolute left-1/2 -translate-x-1/2 w-0 h-0
- border-l-[6px] border-l-transparent
- border-r-[6px] border-r-transparent
- ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
- `})]})]})}function w7e({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:r,children:i}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,d]=w.useState("top"),u=w.useRef(null),m=w.useRef(null),p=w.useRef(null);w.useEffect(()=>{if(o&&u.current&&m.current){const g=u.current.getBoundingClientRect(),b=m.current.offsetHeight,C=g.top-56,P=window.innerHeight-g.bottom;C<b+12&&P>C?d("bottom"):d("top")}},[o]);const f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},x=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};if(w.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),!t&&!e)return a.jsx(a.Fragment,{children:i});const v=(g,b)=>{const _=n===b,C=Vae(g.nozzle_type,s),P=Gae(g.nozzle_type,s),N=AO(g.filament_color),A=g.filament_id?r?.[g.filament_id]?.name:void 0;return a.jsxs("div",{className:"flex-1 space-y-1.5",children:[a.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${_?"text-amber-400":"text-bambu-gray"}`,children:s(b==="L"?"common.left":"common.right")}),g.nozzle_diameter&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.nozzle_diameter," mm"]})]}),C&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:C})]}),P&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),a.jsx("span",{className:"text-[10px] text-white font-semibold",children:P})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),a.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&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.wear,"%"]})]}),b==="R"&&g.max_temp>0&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),a.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.max_temp,"°C"]})]}),b==="R"&&g.serial_number&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),a.jsx("span",{className:"text-[10px] text-white font-mono",children:g.serial_number})]}),(N||g.filament_type||g.filament_id)&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),a.jsxs("div",{className:"flex items-center gap-1",children:[N&&a.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:N}}),a.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:A||g.filament_type||g.filament_id||""})]})]})]})};return a.jsxs("div",{ref:u,className:"relative flex-1",onMouseEnter:f,onMouseLeave:x,children:[i,o&&a.jsxs("div",{ref:m,className:`
- absolute left-1/2 -translate-x-1/2 z-50
- ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
- animate-in fade-in-0 zoom-in-95 duration-150
- `,style:{maxWidth:"calc(100vw - 24px)"},children:[a.jsx("div",{className:"w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:a.jsxs("div",{className:"p-2.5 flex gap-3",children:[t&&v(t,"L"),t&&e&&a.jsx("div",{className:"w-px bg-bambu-dark-tertiary/50"}),e&&v(e,"R")]})}),a.jsx("div",{className:`
- absolute left-1/2 -translate-x-1/2 w-0 h-0
- border-l-[6px] border-l-transparent
- border-r-[6px] border-r-transparent
- ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
- `})]})]})}function S7e({slots:t,filamentInfo:e}){const{t:n}=Rt(),r=t.filter(l=>l.id>=2),i=6,s=16,o=Array.from({length:i},(l,c)=>r.find(d=>d.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 a.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:[a.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),a.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const d=!l.nozzle_diameter&&!l.nozzle_type,u=d?null:AO(l.filament_color),m=u?VQ(l.filament_color):!1;return a.jsx(Wae,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:a.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${d?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:u?{backgroundColor:u}:void 0,children:a.jsx("span",{className:`text-[10px] font-semibold ${d?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:u&&!m?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:d?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function eK({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.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 _7e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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 k7e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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 N7e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function C7e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.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 P7e({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.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 kD({className:t,color:e,isHeating:n}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return n?a.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),a.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:i,strokeWidth:"1",fill:"none"})]}):a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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:i,strokeWidth:"1",fill:"none"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function tK({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof n=="number"?n:60;let c,d;isNaN(s)?(c="#C3C2C1",d="Unknown"):s<=o?(c="#22a352",d="Good"):s<=l?(c="#d4a017",d="Fair"):(c="#c62828",d="Bad");let u;return isNaN(s)||s<=o?u=eK:s<=l?u=_7e:u=k7e,a.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${d}${r?" (click for history)":""}`,children:[a.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function nK({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:i}){const s=typeof e=="number"?e:28,o=typeof n=="number"?n:35;let l,c,d;return t<=s?(l="#22a352",c="Good",d=N7e):t<=o?(l="#d4a017",c="Fair",d=C7e):(l="#c62828",c="Bad",d=P7e),a.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:[a.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),a.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Rl(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,i=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function ND(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function T7e({url:t,printName:e}){const{t:n}=Rt(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!1),d=w.useMemo(()=>{if(!t)return null;const u=t.includes("?")?"&":"?";return za(`${t}${u}v=${encodeURIComponent(e||Date.now().toString())}`)},[t,e]);return w.useEffect(()=>{i(!1),o(!1)},[d]),a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&r?"cursor-pointer":""}`,onClick:()=>d&&r&&c(!0),children:d&&!s?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:d,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!r&&a.jsx(mi,{className:"w-8 h-8 text-bambu-gray"})]}):a.jsx(mi,{className:"w-8 h-8 text-bambu-gray"})}),l&&d&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:a.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[a.jsx("img",{src:d,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&a.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function A7e({printers:t}){const{t:e}=Rt(),n=sn(),[r,i]=w.useState(0);w.useEffect(()=>{let c=!1;const d=n.getQueryCache().subscribe(()=>{c||(c=!0,requestAnimationFrame(()=>{i(u=>u+1),c=!1}))});return()=>d()},[n]);const{counts:s,nextFinish:o}=w.useMemo(()=>{let c=0,d=0,u=0,m=0,p=0,f=0,x=0,v=null,g=null,b=0;return t?.forEach(_=>{const C=n.getQueryData(["printerStatus",_.id]);if(C===void 0)f++;else if(!C.connected)p++;else switch(C.hms_errors&&Uu(C.hms_errors).length>0&&x++,C.state){case"RUNNING":c++,C.remaining_time!=null&&C.remaining_time>0&&(g===null||C.remaining_time<g)&&(g=C.remaining_time,v=_.name,b=C.progress||0);break;case"PAUSE":d++;break;case"FINISH":u++;break;case"FAILED":x++;break;default:m++;break}}),{counts:{printing:c,paused:d,finished:u,idle:m,offline:p,loading:f,error:x,total:t?.length||0},nextFinish:v&&g?{name:v,remainingMin:g,progress:b}:null}},[t,n,r]);if(!t?.length)return null;const l=[{count:s.printing,dot:"bg-bambu-green animate-pulse",label:e("printers.status.printing").toLowerCase()},{count:s.paused,dot:"bg-status-warning",label:e("printers.status.paused","paused").toLowerCase()},{count:s.finished,dot:"bg-blue-400",label:e("printers.status.finished","finished").toLowerCase()},{count:s.idle,dot:s.idle>0?"bg-bambu-green":"bg-gray-500",label:e("printers.status.available").toLowerCase()},{count:s.error,dot:"bg-status-error",label:e("printers.status.problem").toLowerCase()},{count:s.offline,dot:"bg-gray-400",label:e("printers.status.offline").toLowerCase()}];return a.jsxs("div",{className:"flex flex-wrap items-center gap-4 gap-y-2 text-sm",children:[l.map(({count:c,dot:d,label:u})=>c>0&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${d}`}),a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white font-medium",children:c})," ",u]})]},u)),o&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),a.jsx("span",{className:"text-white font-medium",children:o.name})]}),a.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[a.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),a.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",ps(o.remainingMin*60),")"]})]})]})]})]})}function CD(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 y0(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"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 rK({ams:t,printerId:e,label:n,amsLabels:r,canEdit:i,onSaved:s,children:o}){const{t:l}=Rt(),[c,d]=w.useState(!1),[u,m]=w.useState("top"),[p,f]=w.useState(""),[x,v]=w.useState(!1),[g,b]=w.useState(null),[_,C]=w.useState(!1),P=w.useRef(null),N=w.useRef(null),A=w.useRef(null);w.useEffect(()=>{c&&(f(r?.[t.id]??""),b(null),requestAnimationFrame(()=>{if(P.current&&N.current){const H=P.current.getBoundingClientRect(),z=H.top-56,X=window.innerHeight-H.bottom;m(z<N.current.offsetHeight+12&&X>z?"bottom":"top")}}))},[c,r,t.id]);const T=()=>{A.current&&clearTimeout(A.current),A.current=setTimeout(()=>d(!0),80)},F=()=>{A.current&&clearTimeout(A.current),_||(A.current=setTimeout(()=>d(!1),200))};w.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const k=async()=>{if(i){v(!0),b(null);try{const H=p.trim();H?await me.saveAmsLabel(e,t.id,H,t.serial_number):await me.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(H){b(H instanceof Error?H.message:String(H))}finally{v(!1)}}},D=async()=>{if(i){v(!0),b(null);try{await me.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(H){b(H instanceof Error?H.message:String(H))}finally{v(!1)}}};return a.jsxs("div",{ref:P,className:"relative inline-block",onMouseEnter:T,onMouseLeave:F,children:[o,c&&a.jsx("div",{ref:N,className:`
- absolute left-0 z-50
- ${u==="top"?"bottom-full mb-2":"top-full mt-2"}
- animate-in fade-in-0 zoom-in-95 duration-150
- `,style:{maxWidth:"calc(100vw - 24px)"},onMouseEnter:T,onMouseLeave:F,children:a.jsxs("div",{className:"w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm p-2.5 space-y-2",children:[a.jsx("div",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:n}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.serialNumber")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.serial_number||"—"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.firmwareVersion")}),a.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.sw_ver||"—"})]}),a.jsx("div",{className:"h-px bg-bambu-dark-tertiary/50"}),a.jsxs("div",{className:"space-y-1",children:[a.jsx("span",{className:"text-[10px] text-bambu-gray font-medium block",children:l("printers.amsPopup.friendlyName")}),a.jsx("input",{type:"text",value:p,onChange:H=>i&&f(H.target.value),onKeyDown:H=>H.key==="Enter"&&k(),onFocus:()=>C(!0),onBlur:()=>{C(!1),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>d(!1),200)},placeholder:i?l("printers.amsPopup.friendlyNamePlaceholder"):r?.[t.id]||"—",disabled:!i,title:i?void 0:l("printers.amsPopup.noEditPermission"),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-xs text-white placeholder-bambu-gray/60 focus:outline-none focus:border-bambu-green disabled:opacity-50 disabled:cursor-not-allowed",maxLength:100}),i&&a.jsxs("div",{className:"space-y-1",children:[g&&a.jsx("p",{className:"text-[10px] text-red-400 break-words",children:g}),a.jsxs("div",{className:"flex gap-1 justify-end",children:[a.jsx("button",{onClick:k,disabled:x,className:"px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50",children:l("printers.amsPopup.save")}),r?.[t.id]&&a.jsx("button",{onClick:D,disabled:x,className:"px-2 py-0.5 text-[10px] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50",children:l("printers.amsPopup.clear")})]})]})]})]})})]})}const lL={PLA:{n3f:45,n3s:45,n3f_hours:12,n3s_hours:12},PETG:{n3f:65,n3s:65,n3f_hours:12,n3s_hours:12},TPU:{n3f:65,n3s:75,n3f_hours:12,n3s_hours:18},ABS:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},ASA:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},PA:{n3f:65,n3s:85,n3f_hours:12,n3s_hours:12},PC:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},PVA:{n3f:65,n3s:85,n3f_hours:12,n3s_hours:18}};function aK({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:r="expanded",cardSize:i=2,amsThresholds:s,spoolmanEnabled:o=!1,linkedSpools:l,spoolmanUrl:c,spoolmanSyncMode:d,onGetAssignment:u,onUnassignSpool:m,timeFormat:p="system",cameraViewMode:f="window",onOpenEmbeddedCamera:x,checkPrinterFirmware:v=!0,dryingPresets:g=lL,requirePlateClear:b=!1,selectionMode:_=!1,isSelected:C=!1,onToggleSelect:P}){const{t:N}=Rt(),A=sn(),T=Do(),{showToast:F}=bn(),{hasPermission:k}=wr(),[D,H]=w.useState(!1),[z,X]=w.useState(!1),[L,ne]=w.useState(!0),[ie,ee]=w.useState(!1),[ue,le]=w.useState(!1),[oe,W]=w.useState(!1),[re,ce]=w.useState(!1),[xe,Ne]=w.useState(!1),[$,Y]=w.useState(!1),[E,j]=w.useState(!1),[O,K]=w.useState(!1),[B,he]=w.useState(null),[I,V]=w.useState(null),[Q,G]=w.useState(!1),[J,se]=w.useState(!1),[fe,pe]=w.useState(!1),[de,U]=w.useState(!1),R=w.useCallback(()=>U(!1),[]),[ae,_e]=w.useState(null),[Se,ye]=w.useState(null),[Ae,ve]=w.useState("n3f"),[je,Re]=w.useState("PLA"),[Ee,Te]=w.useState(50),[Me,Be]=w.useState(4),[Ke,tt]=w.useState(!1),[te,Ie]=w.useState(null),[be,$e]=w.useState(!1),[He,ge]=w.useState(!1),Pe=w.useRef(0),[qe,Ze]=w.useState(null),[ut,vt]=w.useState(null),[wt,$t]=w.useState(null),[Qt,en]=w.useState(null),[Xt,tn]=w.useState(!1),[Ge,Ft]=w.useState(null),[Yt,Pt]=w.useState(!1),[pt,Wt]=w.useState(!1),[Ut,ze]=w.useState(null),[st,ht]=w.useState(!1),[rt,Le]=w.useState(!1),{data:Oe}=Qe({queryKey:["printerStatus",t.id],queryFn:()=>me.getPrinterStatus(t.id),refetchInterval:3e4}),{data:Ce}=Qe({queryKey:["firmwareUpdate",t.id],queryFn:()=>kk.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:v&&k("firmware:read")}),We=w.useMemo(()=>{const mt=new Set;if(Oe?.ams)for(const Ht of Oe.ams)for(const Jt of Ht.tray||[])Jt.tray_info_idx&&mt.add(Jt.tray_info_idx);for(const Ht of Oe?.vt_tray??[])Ht.tray_info_idx&&mt.add(Ht.tray_info_idx);if(Oe?.nozzle_rack)for(const Ht of Oe.nozzle_rack)Ht.filament_id&&mt.add(Ht.filament_id);return Array.from(mt)},[Oe?.ams,Oe?.vt_tray,Oe?.nozzle_rack]),Je=w.useMemo(()=>{const mt=new Set;if(Oe?.ams)for(const Ht of Oe.ams)for(const Jt of Ht.tray||[])Jt.tray_type&&mt.add(Jt.tray_type.toUpperCase());for(const Ht of Oe?.vt_tray??[])Ht.tray_type&&mt.add(Ht.tray_type.toUpperCase());return mt},[Oe?.ams,Oe?.vt_tray]),Xe=w.useMemo(()=>{const mt=new Set;if(Oe?.ams){for(const Ht of Oe.ams)for(const Jt of Ht.tray||[])if(Jt.tray_type&&Jt.tray_color){const ot=Jt.tray_color.replace("#","").toLowerCase().slice(0,6);mt.add(`${Jt.tray_type.toUpperCase()}:${ot}`)}}for(const Ht of Oe?.vt_tray??[])if(Ht.tray_type&&Ht.tray_color){const Jt=Ht.tray_color.replace("#","").toLowerCase().slice(0,6);mt.add(`${Ht.tray_type.toUpperCase()}:${Jt}`)}return mt},[Oe?.ams,Oe?.vt_tray]),{data:Ye}=Qe({queryKey:["filamentInfo",We],queryFn:()=>me.getFilamentInfo(We),enabled:We.length>0,staleTime:300*1e3}),{data:St}=Qe({queryKey:["slotPresets",t.id],queryFn:()=>me.getSlotPresets(t.id),staleTime:120*1e3}),{data:et,refetch:jt}=Qe({queryKey:["amsLabels",t.id],queryFn:()=>me.getAmsLabels(t.id),staleTime:300*1e3}),[bt,Ve]=w.useState(null);w.useEffect(()=>{Oe?.wifi_signal!=null&&Ve(Oe.wifi_signal)},[Oe?.wifi_signal]);const gt=Oe?.wifi_signal??bt,Et=w.useRef(void 0);w.useEffect(()=>{Oe?.connected!==void 0&&(Et.current=Oe.connected)},[Oe?.connected]);const Gt=Oe?.connected??Et.current,on=w.useRef({});w.useEffect(()=>{Oe?.ams_extruder_map&&Object.keys(Oe.ams_extruder_map).length>0&&(on.current=Oe.ams_extruder_map)},[Oe?.ams_extruder_map]);const fn=Oe?.ams_extruder_map&&Object.keys(Oe.ams_extruder_map).length>0?Oe.ams_extruder_map:on.current,Ln=w.useRef([]);w.useEffect(()=>{Oe?.ams&&Oe.ams.length>0&&(Ln.current=Oe.ams)},[Oe?.ams]);const yn=Oe?.ams&&Oe.ams.length>0?Oe.ams:Ln.current,hn=w.useRef(void 0),xn=Oe?.tray_now;xn!==void 0&&xn!==255?hn.current=xn:xn===255&&(hn.current=void 0);const Nn=xn!==void 0&&xn!==255?xn:hn.current,{data:Pn}=Qe({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>me.getSmartPlugByPrinter(t.id)}),{data:Nr}=Qe({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>me.getScriptPlugsByPrinter(t.id)}),{data:Sn}=Qe({queryKey:["smartPlugStatus",Pn?.id],queryFn:()=>Pn?me.getSmartPlugStatus(Pn.id):null,enabled:!!Pn,refetchInterval:1e4}),{data:Pa}=Qe({queryKey:["queue",t.id,"pending"],queryFn:()=>me.getQueue(t.id,"pending")}),On=w.useMemo(()=>Pa?.length?_J(Pa,Je,Xe).length:0,[Pa,Je,Xe]),{data:ya}=Qe({queryKey:["queue",t.id,"printing"],queryFn:()=>me.getQueue(t.id,"printing"),enabled:Oe?.state==="RUNNING"}),{data:ua}=Qe({queryKey:["currentPrintUser",t.id],queryFn:()=>me.getCurrentPrintUser(t.id),enabled:Oe?.state==="RUNNING"}),Zr=ya?.[0]?.created_by_username||ua?.username,{data:sa}=Qe({queryKey:["archives",t.id,"last"],queryFn:()=>me.getArchives(t.id,1,0),enabled:Oe?.connected&&Oe?.state!=="RUNNING"}),Ta=sa?.[0],Wi=e&&Gt===!1,_m=it({mutationFn:mt=>me.deletePrinter(t.id,mt.deleteArchives),onSuccess:()=>{A.invalidateQueries({queryKey:["printers"]}),A.invalidateQueries({queryKey:["archives"]}),A.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:mt=>F(mt.message||N("printers.toast.failedToDelete"),"error")}),Vd=it({mutationFn:()=>me.connectPrinter(t.id),onSuccess:()=>{A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),fl=it({mutationFn:()=>me.refreshPrinterStatus(t.id),onSuccess:()=>{A.invalidateQueries({queryKey:["printerStatus",t.id]}),F(N("printers.forceRefreshSuccess"),"success")},onError:mt=>F(mt.message||N("printers.toast.failedToSendCommand"),"error")}),xt=it({mutationFn:mt=>me.unlinkSpool(mt),onSuccess:mt=>{F(N("spoolman.unlinkSuccess")||mt?.message,"success"),A.invalidateQueries({queryKey:["linked-spools"]}),A.invalidateQueries({queryKey:["unlinked-spools"]})},onError:mt=>{F(mt.message||N("spoolman.unlinkFailed"),"error")}}),Kn=it({mutationFn:({amsId:mt,temp:Ht,duration:Jt,filament:ot,rotateTray:Bn})=>me.startDrying(t.id,mt,Ht,Jt,ot,Bn),onSuccess:()=>{ye(null),A.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:mt=>F(mt.message||N("printers.toast.failedToSendCommand"),"error")}),Zn=it({mutationFn:mt=>me.stopDrying(t.id,mt),onSuccess:()=>{A.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:mt=>F(mt.message||N("printers.toast.failedToSendCommand"),"error")}),qt=it({mutationFn:mt=>Pn?me.controlSmartPlug(Pn.id,mt):Promise.reject("No plug"),onSuccess:()=>{A.invalidateQueries({queryKey:["smartPlugStatus",Pn?.id]})}}),Kc=it({mutationFn:mt=>Pn?me.updateSmartPlug(Pn.id,{auto_off:mt}):Promise.reject("No plug"),onSuccess:()=>{A.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),A.invalidateQueries({queryKey:["smart-plugs"]})}}),Ki=it({mutationFn:({id:mt,action:Ht})=>me.controlSmartPlug(mt,Ht),onSuccess:()=>{F(N("printers.toast.scriptTriggered"))},onError:mt=>F(mt.message||N("printers.toast.failedToRunScript"),"error")}),gl=it({mutationFn:()=>me.stopPrint(t.id),onSuccess:()=>{F(N("printers.toast.printStopped")),A.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:mt=>F(mt.message||N("printers.toast.failedToStopPrint"),"error")}),fc=it({mutationFn:()=>me.pausePrint(t.id),onSuccess:()=>{F(N("printers.toast.printPaused")),A.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:mt=>F(mt.message||N("printers.toast.failedToPausePrint"),"error")}),Qa=it({mutationFn:()=>me.resumePrint(t.id),onSuccess:()=>{F(N("printers.toast.printResumed")),A.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:mt=>F(mt.message||N("printers.toast.failedToResumePrint"),"error")}),km=it({mutationFn:mt=>me.setChamberLight(t.id,mt),onMutate:async mt=>{await A.cancelQueries({queryKey:["printerStatus",t.id]});const Ht=A.getQueryData(["printerStatus",t.id]);return A.setQueryData(["printerStatus",t.id],Jt=>({...Jt,chamber_light:mt})),{previousStatus:Ht}},onSuccess:(mt,Ht)=>{F(`Chamber light ${Ht?"on":"off"}`)},onError:(mt,Ht,Jt)=>{Jt?.previousStatus&&A.setQueryData(["printerStatus",t.id],Jt.previousStatus),F(mt.message||N("printers.toast.failedToControlChamberLight"),"error")}}),Cp=it({mutationFn:mt=>me.setPrintSpeed(t.id,mt),onMutate:async mt=>{await A.cancelQueries({queryKey:["printerStatus",t.id]});const Ht=A.getQueryData(["printerStatus",t.id]);return A.setQueryData(["printerStatus",t.id],Jt=>({...Jt,speed_level:mt})),{previousStatus:Ht}},onError:(mt,Ht,Jt)=>{Jt?.previousStatus&&A.setQueryData(["printerStatus",t.id],Jt.previousStatus),F(mt.message||N("printers.toast.failedToSetSpeed"),"error")}}),Gd=it({mutationFn:mt=>me.setAirductMode(t.id,mt),onMutate:async mt=>{await A.cancelQueries({queryKey:["printerStatus",t.id]});const Ht=A.getQueryData(["printerStatus",t.id]);return A.setQueryData(["printerStatus",t.id],Jt=>({...Jt,airduct_mode:mt==="cooling"?0:1})),{previousStatus:Ht}},onError:(mt,Ht,Jt)=>{Jt?.previousStatus&&A.setQueryData(["printerStatus",t.id],Jt.previousStatus),F(mt.message||N("printers.toast.failedToSendCommand"),"error")}}),Xi=it({mutationFn:mt=>me.updatePrinter(t.id,{plate_detection_enabled:mt}),onSuccess:()=>{A.invalidateQueries({queryKey:["printers"]}),F(Xi.variables?N("printers.toast.plateCheckEnabled"):N("printers.toast.plateCheckDisabled"))},onError:mt=>F(mt.message||N("printers.toast.failedToUpdateSetting"),"error")}),Nm=(Oe?.state==="RUNNING"||Oe?.state==="PAUSE")&&(Oe?.printable_objects_count??0)>=2,{data:vs}=Qe({queryKey:["printableObjects",t.id],queryFn:()=>me.getPrintableObjects(t.id),enabled:J||Nm,refetchInterval:J?5e3:Nm?3e4:!1}),[Yi,zs]=w.useState(null),bl=w.useRef(!1),Za=w.useRef(null),xl=w.useRef(!1),Wd=it({mutationFn:({amsId:mt,slotId:Ht})=>me.refreshAmsSlot(t.id,mt,Ht),onMutate:({amsId:mt,slotId:Ht})=>{Za.current&&clearTimeout(Za.current),bl.current=!1,xl.current=!1,zs({amsId:mt,slotId:Ht}),setTimeout(()=>{xl.current=!0},2e3),Za.current=setTimeout(()=>{zs(null)},3e4)},onSuccess:mt=>{F(mt.message||N("printers.toast.rfidRereadInitiated"))},onError:mt=>{F(mt.message||N("printers.toast.failedToRereadRfid"),"error"),Za.current&&clearTimeout(Za.current),zs(null)}}),[yl,xi]=w.useState(null),[Us,gc]=w.useState(null),Oo=async()=>{try{const mt=await me.getPlateReferences(t.id);xi(mt)}catch{}},Pp=()=>{Xi.mutate(!t.plate_detection_enabled)},vl=async()=>{Pt(!0),Ft(null);const mt=Oe?.chamber_light===!1;Le(mt),mt&&(await me.setChamberLight(t.id,!0),await new Promise(Ht=>setTimeout(Ht,2500)));try{const Ht=await me.checkPlateEmpty(t.id,{includeDebugImage:!0});Ft(Ht),Oo()}catch(Ht){F(Ht instanceof Error?Ht.message:N("printers.toast.failedToCheckPlate"),"error"),mt&&(await me.setChamberLight(t.id,!1),Le(!1))}finally{Pt(!1)}},co=w.useCallback(async()=>{Ft(null),rt&&(await me.setChamberLight(t.id,!1),Le(!1))},[rt,t.id]),wl=async mt=>{Wt(!0);try{const Ht=await me.calibratePlateDetection(t.id,{label:mt});if(Ht.success){F(Ht.message||N("printers.toast.calibrationSaved"),"success"),Oo();const Jt=await me.checkPlateEmpty(t.id,{includeDebugImage:!0});Ft(Jt)}else F(Ht.message||N("printers.toast.calibrationFailed"),"error")}catch(Ht){F(Ht instanceof Error?Ht.message:N("printers.toast.calibrationFailed"),"error")}finally{Wt(!1)}},Io=async(mt,Ht)=>{try{await me.updatePlateReferenceLabel(t.id,mt,Ht),gc(null),Oo()}catch(Jt){F(Jt instanceof Error?Jt.message:N("printers.toast.failedToUpdateLabel"),"error")}},Xc=async mt=>{try{await me.deletePlateReference(t.id,mt),F(N("printers.toast.referenceDeleted"),"success"),Oo();const Ht=await me.checkPlateEmpty(t.id,{includeDebugImage:!0});Ft(Ht)}catch(Ht){F(Ht instanceof Error?Ht.message:N("printers.toast.failedToDeleteReference"),"error")}},Cm=async()=>{if(Ut){ht(!0);try{await me.updatePrinter(t.id,{plate_detection_roi:Ut}),F(N("printers.toast.detectionAreaSaved"),"success"),ze(null);const mt=await me.checkPlateEmpty(t.id,{includeDebugImage:!0});Ft(mt)}catch(mt){F(mt instanceof Error?mt.message:N("printers.toast.failedToSaveDetectionArea"),"error")}finally{ht(!1)}}};w.useEffect(()=>{const mt=Ht=>{Ht.key==="Escape"&&Ge&&co()};return window.addEventListener("keydown",mt),()=>window.removeEventListener("keydown",mt)},[Ge,co]);const uo=w.useRef(null);w.useEffect(()=>{if(!Yi)return;const mt=Oe?.ams_status_main??0;return mt!==0&&(bl.current=!0,uo.current&&(clearTimeout(uo.current),uo.current=null)),bl.current&&mt===0&&(xl.current?(Za.current&&clearTimeout(Za.current),zs(null)):uo.current||(uo.current=setTimeout(()=>{Za.current&&clearTimeout(Za.current),zs(null)},2e3))),()=>{uo.current&&clearTimeout(uo.current)}},[Oe?.ams_status_main,Yi]);const[mo,zo]=w.useState(null);if(Wi)return null;const Tg=()=>{switch(i){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"}},kn=()=>{switch(i){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"}},Ay=()=>{switch(i){case 1:return"mb-2";case 2:return"mb-4";case 3:return"mb-5";case 4:return"mb-6";default:return"mb-4"}},Yc=Gt&&Oe?.state!=="RUNNING"&&Oe?.state!=="PAUSE"&&k("printers:control"),Ag=mt=>{mt.preventDefault(),Pe.current++,Pe.current===1&&$e(!0)},Pm=mt=>{mt.preventDefault(),mt.dataTransfer.dropEffect=Yc?"copy":"none"},jg=mt=>{mt.preventDefault(),Pe.current--,Pe.current===0&&$e(!1)},jy=async mt=>{if(mt.preventDefault(),Pe.current=0,$e(!1),!Yc)return;const Jt=Array.from(mt.dataTransfer.files)[0];if(!Jt)return;const ot=Jt.name.toLowerCase();if(!ot.endsWith(".gcode")&&!ot.includes(".gcode.")){F(N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed"),"error");return}ge(!0);try{const Bn=await me.uploadLibraryFile(Jt,null),we=Bn.metadata?.sliced_for_model,_t=y0(t.model);if(we&&_t&&we.toLowerCase()!==_t.toLowerCase()){await me.deleteLibraryFile(Bn.id).catch(()=>{}),F(N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:we,printerModel:_t}),"error");return}_e({id:Bn.id,filename:Bn.filename})}catch{F(N("common.uploadFailed","Upload failed"),"error")}finally{ge(!1)}};return a.jsxs(At,{className:`relative ${C?"ring-2 ring-bambu-green":""} ${_?"cursor-pointer":""}`,onDragEnter:Ag,onDragOver:Pm,onDragLeave:jg,onDrop:jy,children:[_&&a.jsx("div",{className:"absolute inset-0 z-20 flex items-start p-2",onClick:mt=>{mt.stopPropagation(),P?.(t.id)},children:C?a.jsx(xs,{className:"w-5 h-5 text-bambu-green"}):a.jsx(to,{className:"w-5 h-5 text-bambu-gray"})}),(be||He)&&a.jsx("div",{className:`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${He?"bg-bambu-green/10 border-bambu-green/50":Yc?"bg-bambu-green/10 border-bambu-green":"bg-red-500/10 border-red-500/50"}`,children:a.jsx("div",{className:"text-center",children:He?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-sm font-medium text-bambu-green",children:N("common.uploading","Uploading...")})]}):Yc?a.jsxs(a.Fragment,{children:[a.jsx(Ar,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green"}),a.jsx("p",{className:"text-sm font-medium text-bambu-green",children:N("printers.dropToPrint","Drop to print")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Bt,{className:"w-8 h-8 mx-auto mb-2 text-red-400"}),a.jsx("p",{className:"text-sm font-medium text-red-400",children:N("printers.cannotPrint","Printer busy")})]})})}),a.jsxs(Mt,{className:i>=3?"p-5":"",children:[a.jsxs("div",{className:Ay(),children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("img",{src:wJ(t.model),alt:t.model||N("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${Tg()}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-semibold text-white ${kn()}`,children:t.name}),r==="compact"&&(()=>{const mt=Oe?.connected&&Oe.hms_errors?Uu(Oe.hms_errors):[],Ht=mt.some(we=>we.severity<=2),Jt=mt.length>0,ot=Oe?.connected?Ht?"bg-status-error":Jt?"bg-status-warning":"bg-status-ok":"bg-status-error",Bn=Oe?.connected?Jt?`${mt.length} HMS ${mt.length===1?"error":"errors"}`:N("printers.connection.connected"):N("printers.connection.offline");return a.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${ot}`,title:Bn})})()]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",r==="expanded"&&Oe?.nozzles&&Oe.nozzles[0]?.nozzle_diameter&&a.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:Oe.nozzles[0].nozzle_type||"Nozzle",children:["• ",Oe.nozzles[0].nozzle_diameter,"mm"]}),r==="expanded"&&n&&n.total_print_hours>0&&a.jsxs("span",{className:"ml-2 text-bambu-gray",children:[a.jsx(Qn,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),a.jsxs("div",{className:"relative flex-shrink-0",children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>H(!D),children:a.jsx(Bh,{className:"w-4 h-4"})}),D&&a.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:[a.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")&&(ee(!0),H(!1))},title:k("printers:update")?void 0:N("printers.permission.noEdit"),children:[a.jsx(ai,{className:"w-4 h-4"}),N("common.edit")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{U(!0),H(!1)},children:[a.jsx(fs,{className:"w-4 h-4"}),N("printers.printerInformation")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{Vd.mutate(),H(!1)},children:[a.jsx(cr,{className:"w-4 h-4"}),N("printers.reconnect")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50",disabled:fl.isPending,onClick:()=>{fl.mutate(),H(!1)},children:[a.jsx(H0,{className:`w-4 h-4 ${fl.isPending?"animate-spin":""}`}),N("printers.forceRefresh")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{W(!0),H(!1)},children:[a.jsx(IQ,{className:"w-4 h-4"}),N("printers.mqttDebug")]}),a.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")&&(X(!0),H(!1))},title:k("printers:delete")?void 0:N("printers.permission.noDelete"),children:[a.jsx(rn,{className:"w-4 h-4"}),N("common.delete")]})]})]})]}),r==="expanded"&&a.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[a.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${Oe?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[Oe?.connected?a.jsx(ly,{className:"w-3 h-3"}):a.jsx(ap,{className:"w-3 h-3"}),Oe?.connected?N("printers.connection.connected"):N("printers.connection.offline")]}),Oe?.connected&&Oe?.wired_network&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok",title:N("printers.connection.ethernet","Ethernet"),children:[a.jsx(gO,{className:"w-3 h-3"}),N("printers.connection.ethernet","Ethernet")]}),Oe?.connected&&!Oe?.wired_network&>!=null&&a.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${gt>=-50||gt>=-60?"bg-status-ok/20 text-status-ok":gt>=-70?"bg-status-warning/20 text-status-warning":gt>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${gt} dBm - ${N(SJ(gt).labelKey)}`,children:[a.jsx(RQ,{className:"w-3 h-3"}),gt,"dBm"]}),Oe?.connected&&(()=>{const mt=Oe.hms_errors?Uu(Oe.hms_errors):[];return a.jsxs("button",{onClick:()=>Y(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${mt.length>0?mt.some(Ht=>Ht.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:N("printers.clickToViewHmsErrors"),children:[a.jsx(Rn,{className:"w-3 h-3"}),mt.length>0?mt.length:"OK"]})})(),n&&a.jsxs("button",{onClick:()=>T("/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`:N("printers.maintenanceUpToDate"),children:[a.jsx(Yf,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),On>0&&a.jsxs("button",{onClick:()=>T("/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:N("printers.queue.inQueue",{count:On}),children:[a.jsx(aa,{className:"w-3 h-3"}),On]}),v&&Ce?.current_version&&Ce?.latest_version?a.jsxs("button",{onClick:()=>tn(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${Ce.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:Ce.update_available?N("printers.firmwareUpdateAvailable",{current:Ce.current_version,latest:Ce.latest_version}):N("printers.firmwareUpToDate",{version:Ce.current_version}),children:[Ce.update_available?a.jsx(ca,{className:"w-3 h-3"}):a.jsx(xr,{className:"w-3 h-3"}),Ce.current_version]}):Oe?.firmware_version?a.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:Oe.firmware_version}):null,Oe?.connected&&a.jsx("span",{className:`flex items-center px-2 py-1 rounded-full text-xs ${Oe.sdcard?"bg-status-ok/20 text-status-ok":"bg-red-500/20 text-red-400"}`,title:`${N("printers.sdCard")}: ${Oe.sdcard?N("printers.inserted"):N("printers.notInserted")}`,children:a.jsx(rp,{className:"w-3 h-3"})}),Oe?.connected&&["X1C","X1","X1E","P1S","P1P","P2S","H2D","H2D Pro","H2C","H2S"].includes(t.model??"")&&a.jsx("span",{className:`flex items-center px-2 py-1 rounded-full text-xs ${Oe.door_open?"bg-yellow-500/20 text-yellow-400":"bg-status-ok/20 text-status-ok"}`,title:Oe.door_open?N("printers.door.open"):N("printers.door.closed"),children:Oe.door_open?a.jsx(Ife,{className:"w-3 h-3"}):a.jsx(Lfe,{className:"w-3 h-3"})})]})]}),z&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(At,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:a.jsx(Rn,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:N("printers.confirm.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:N("printers.confirm.deleteMessage",{name:t.name})})]})]}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:a.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:L,onChange:mt=>ne(mt.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"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:N("printers.deleteArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:N(L?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{X(!1),ne(!0)},children:N("common.cancel")}),a.jsx(Fe,{variant:"danger",onClick:()=>{_m.mutate({deleteArchives:L}),X(!1),ne(!0)},children:"Delete"})]})]})})}),Oe?.connected&&a.jsxs(a.Fragment,{children:[r==="compact"?a.jsx("div",{className:"mt-2",children:Oe.state==="RUNNING"||Oe.state==="PAUSE"?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:`${Oe.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-1.5 rounded-full transition-all`,style:{width:`${Oe.progress||0}%`}})}),a.jsxs("span",{className:"text-xs text-white",children:[Math.round(Oe.progress||0),"%"]})]}):a.jsx("p",{className:"text-xs text-bambu-gray",children:CD(Oe.state,Oe.stg_cur_name)})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[a.jsxs("button",{onClick:()=>se(!0),disabled:!(Oe.state==="RUNNING"||Oe.state==="PAUSE")||(Oe.printable_objects_count??0)<2||!k("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(Oe.state==="RUNNING"||Oe.state==="PAUSE")&&(Oe.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")?Oe.state==="RUNNING"||Oe.state==="PAUSE"?(Oe.printable_objects_count??0)>=2?N("printers.skipObjects.tooltip"):N("printers.skipObjects.requiresMultiple"):N("printers.skipObjects.onlyWhilePrinting"):N("printers.permission.noControl"),children:[a.jsx(VP,{className:"w-4 h-4"}),vs&&vs.skipped_count>0&&a.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:vs.skipped_count})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(T7e,{url:Oe.state==="RUNNING"||Oe.state==="PAUSE"?Oe.cover_url:null,printName:(Oe.state==="RUNNING"||Oe.state==="PAUSE")&&ZW(Oe.subtask_name||Oe.current_print||null,Oe.gcode_file,N)||void 0}),a.jsx("div",{className:"flex-1 min-w-0",children:Oe.current_print&&(Oe.state==="RUNNING"||Oe.state==="PAUSE")?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:CD(Oe.state,Oe.stg_cur_name)}),a.jsx("p",{className:"text-white text-sm mb-2 truncate",children:ZW(Oe.subtask_name||Oe.current_print||null,Oe.gcode_file,N)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:`${Oe.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-2 rounded-full transition-all`,style:{width:`${Oe.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(Oe.progress||0),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[Oe.remaining_time!=null&&Oe.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),ps(Oe.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:N("printers.estimatedCompletion"),children:["ETA ",jO(Oe.remaining_time,p,N)]})]}),Oe.layer_num!=null&&Oe.total_layers!=null&&Oe.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(aa,{className:"w-3 h-3"}),Oe.layer_num,"/",Oe.total_layers]}),Zr&&a.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${Zr}`,children:[a.jsx(sm,{className:"w-3 h-3"}),Zr]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:N("printers.sort.status")}),a.jsx("p",{className:"text-white text-sm mb-2",children:CD(Oe.state,Oe.stg_cur_name)}),a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),a.jsx("span",{className:"text-bambu-gray",children:"—"})]}),Ta?a.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:Ta.print_name||Ta.filename,children:["Last: ",Ta.print_name||Ta.filename,Ta.completed_at&&a.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",Qf(Ta.completed_at,{month:"short",day:"numeric"})]})]}):a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.readyToPrint")})]})})]})]}),a.jsx(HMe,{printerId:t.id,printerModel:t.model,printerState:Oe.state,awaitingPlateClear:Oe.awaiting_plate_clear,requirePlateClear:b,loadedFilamentTypes:Je,loadedFilaments:Xe})]}),Oe.temperatures&&r==="expanded"&&(()=>{const mt=Oe.temperatures.nozzle_heating||Oe.temperatures.nozzle_2_heating||!1,Ht=Oe.temperatures.bed_heating||!1,Jt=Oe.temperatures.chamber_heating||!1,ot=t.nozzle_count===2||Oe.temperatures.nozzle_2!==void 0,Bn=Oe.active_extruder===1?"L":"R",we=Oe.nozzle_rack?.find(mn=>mn.id===1),_t=Oe.nozzle_rack?.find(mn=>mn.id===0),ln=_t||we;return a.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[a.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:[a.jsx(kD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:mt}),Oe.temperatures.nozzle_2!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Oe.temperatures.nozzle||0),"° / ",Math.round(Oe.temperatures.nozzle_2||0),"°"]})]}):ln?a.jsx(Wae,{slot:ln,index:0,activeStatus:!0,filamentName:ln.filament_id?Ye?.[ln.filament_id]?.name:void 0,children:a.jsxs("div",{className:"cursor-default",children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Oe.temperatures.nozzle||0),"°C"]})]})}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Oe.temperatures.nozzle||0),"°C"]})]})]}),a.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:[a.jsx(kD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:Ht}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.bed")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Oe.temperatures.bed||0),"°C"]})]}),Oe.temperatures.chamber!==void 0&&a.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:[a.jsx(kD,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:Jt}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.chamber")}),a.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(Oe.temperatures.chamber||0),"°C"]})]}),ot&&a.jsx(w7e,{leftSlot:we,rightSlot:_t,activeNozzle:Bn,filamentInfo:Ye,children:a.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:N("printers.activeNozzle",{nozzle:N(Bn==="L"?"common.left":"common.right")}),children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("span",{className:`text-[11px] font-bold ${Bn==="L"?"text-amber-400":"text-gray-500"}`,children:["L",we?.nozzle_diameter?` ${we.nozzle_diameter}`:""]}),a.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),a.jsxs("span",{className:`text-[11px] font-bold ${Bn==="R"?"text-amber-400":"text-gray-500"}`,children:["R",_t?.nozzle_diameter?` ${_t.nozzle_diameter}`:""]})]}),a.jsx("p",{className:"text-[9px] text-bambu-gray",children:N("printers.temperatures.nozzle")})]})}),Oe.nozzle_rack&&Oe.nozzle_rack.some(mn=>mn.id>=2)&&a.jsx(S7e,{slots:Oe.nozzle_rack,filamentInfo:Ye})]})})(),r==="expanded"&&(()=>{const mt=Oe.state==="RUNNING",Ht=Oe.state==="PAUSE",Jt=mt||Ht,ot=gl.isPending||fc.isPending||Qa.isPending,Bn=Oe.cooling_fan_speed,we=Oe.big_fan1_speed,_t=Oe.big_fan2_speed;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.controls")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 max-[550px]:items-start",children:[a.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:[a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${Bn&&Bn>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:N("printers.fans.partCooling"),children:[a.jsx(CQ,{className:`w-3.5 h-3.5 ${Bn&&Bn>0?"text-cyan-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${Bn&&Bn>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[Bn??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${we&&we>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:N("printers.fans.auxiliary"),children:[a.jsx(BQ,{className:`w-3.5 h-3.5 ${we&&we>0?"text-blue-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${we&&we>0?"text-blue-400":"text-bambu-gray/50"}`,children:[we??0,"%"]})]}),a.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${_t&&_t>0?"bg-green-500/10":"bg-bambu-dark"}`,title:N("printers.fans.chamber"),children:[a.jsx(spe,{className:`w-3.5 h-3.5 ${_t&&_t>0?"text-green-400":"text-bambu-gray/50"}`}),a.jsxs("span",{className:`text-[10px] ${_t&&_t>0?"text-green-400":"text-bambu-gray/50"}`,children:[_t??0,"%"]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-gray/30"}),["P2S","H2D","H2C","H2S"].includes(t.model??"")&&(()=>{const ln=Oe.airduct_mode===1,mn=ln?Au:SH,zt=ln?"text-orange-400":"text-sky-400",dn=ln?"bg-orange-500/10 hover:bg-orange-500/20":"bg-sky-500/10 hover:bg-sky-500/20";return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>V(I===t.id?null:t.id),disabled:!k("printers:control"),className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${dn} disabled:opacity-50 disabled:cursor-not-allowed`,title:N("printers.airduct.title"),children:[a.jsx(mn,{className:`w-3.5 h-3.5 ${zt}`}),a.jsx("span",{className:`text-[10px] ${zt}`,children:N(ln?"printers.airduct.heating":"printers.airduct.cooling")})]}),I===t.id&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>V(null)}),a.jsx("div",{className:"absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg py-1 min-w-[130px]",children:[{mode:"cooling",label:N("printers.airduct.cooling"),modeId:0},{mode:"heating",label:N("printers.airduct.heating"),modeId:1}].map(({mode:mr,label:Vn,modeId:yi})=>a.jsxs("button",{onClick:()=>{Gd.mutate(mr),V(null)},className:`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${Oe.airduct_mode===yi?"text-bambu-green bg-bambu-green/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[mr==="heating"?a.jsx(Au,{className:"w-3 h-3"}):a.jsx(SH,{className:"w-3 h-3"}),Vn]},mr))})]})]})})(),(()=>{const mn={1:"50%",2:"100%",3:"124%",4:"166%"}[Oe.speed_level]||"100%";return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>he(B===t.id?null:t.id),disabled:!Jt||!k("printers:control"),className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${Jt?"bg-amber-500/10 hover:bg-amber-500/20":"bg-bambu-dark cursor-not-allowed"}`,title:Jt?N("printers.speed.title"):void 0,children:[a.jsx(Fw,{className:`w-3.5 h-3.5 ${Jt?"text-amber-400":"text-bambu-gray/50"}`}),a.jsx("span",{className:`text-[10px] ${Jt?"text-amber-400":"text-bambu-gray/50"}`,children:mn})]}),B===t.id&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>he(null)}),a.jsx("div",{className:"absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg py-1 min-w-[130px]",children:[{mode:1,label:N("printers.speed.silent")},{mode:2,label:N("printers.speed.standard")},{mode:3,label:N("printers.speed.sport")},{mode:4,label:N("printers.speed.ludicrous")}].map(({mode:zt,label:dn})=>a.jsx("button",{onClick:()=>{Cp.mutate(zt),he(null)},className:`w-full text-left px-3 py-1.5 text-xs transition-colors ${Oe.speed_level===zt?"text-bambu-green bg-bambu-green/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:dn},zt))})]})]})})()]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 max-[550px]:self-start",children:[a.jsxs("button",{onClick:()=>j(!0),disabled:!Jt||ot||!k("printers:control"),className:`
- flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
- transition-colors
- ${Jt&&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"}
- `,title:k("printers:control")?N("printers.stop"):N("printers.permission.noControl"),children:[a.jsx(to,{className:"w-3 h-3"}),N("printers.stop")]}),a.jsxs("button",{onClick:()=>Ht?G(!0):K(!0),disabled:!Jt||ot||!k("printers:control"),className:`
- flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
- transition-colors
- ${Jt&&k("printers:control")?Ht?"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"}
- `,title:k("printers:control")?N(Ht?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[Ht?a.jsx($i,{className:"w-3 h-3"}):a.jsx(zw,{className:"w-3 h-3"}),N(Ht?"printers.resume":"printers.pause")]})]})]})]})})(),(yn?.length>0||Oe.vt_tray.length>0)&&r==="expanded"&&(()=>{const mt=yn.filter(ot=>ot.tray.length>1),Ht=yn.filter(ot=>ot.tray.length===1),Jt=t.nozzle_count===2||Oe?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[mt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:mt.map(ot=>{const Bn=fn[String(ot.id)],we=ot.id>=128?ot.id-128:ot.id,_t=Bn!==void 0?Bn:we,ln=_t===1,mn=_t===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(rK,{ams:ot,printerId:t.id,label:Rl(ot.id,ot.tray.length),amsLabels:et,canEdit:k("printers:update"),onSaved:jt,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:et?.[ot.id]||Rl(ot.id,ot.tray.length)})}),Jt&&(ln||mn)&&a.jsx(JW,{side:ln?"L":"R"})]}),(ot.humidity!=null||ot.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ot.humidity!=null&&a.jsx(tK,{humidity:ot.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Ze({amsId:ot.id,amsLabel:Rl(ot.id,ot.tray.length),mode:"humidity"}),compact:!0}),ot.temp!=null&&a.jsx(nK,{temp:ot.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Ze({amsId:ot.id,amsLabel:Rl(ot.id,ot.tray.length),mode:"temperature"}),compact:!0}),Oe.supports_drying&&(ot.module_type==="n3f"||ot.module_type==="n3s")&&k("printers:control")&&a.jsx("button",{disabled:!!(ot.dry_sf_reason?.length&&ot.dry_time===0),onClick:zt=>{if(ot.dry_time>0)Zn.mutate(ot.id);else if(Se===ot.id)ye(null);else{const mr=(ot.tray.find(Sl=>Sl.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Vn=g[mr]||g.PLA,yi=ot.module_type;Re(mr),Te(Vn[yi]||Vn.n3f),Be(yi==="n3s"?Vn.n3s_hours:Vn.n3f_hours),tt(!1),ve(ot.module_type),ye(ot.id);const Bs=zt.currentTarget.getBoundingClientRect();Ie({top:Bs.bottom+4,left:Math.max(8,Bs.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ot.dry_time>0?"bg-amber-500/20 text-amber-400":ot.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ot.dry_time>0?N("printers.drying.stop"):ot.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Au,{className:"w-3 h-3"})})]})]}),ot.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Au,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:ot.dry_time>=60?`${Math.floor(ot.dry_time/60)}h ${ot.dry_time%60}m`:`${ot.dry_time}m`})}),a.jsx("button",{onClick:()=>Zn.mutate(ot.id),disabled:Zn.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(zt=>{const dn=ot.tray[zt]||ot.tray.find(In=>In.id===zt),mr=dn?.tray_type&&dn.remain>=0,Vn=!dn?.tray_type,yi=ot.id*4+zt,Bs=Nn===yi,Sl=dn?.tray_info_idx?Ye?.[dn.tray_info_idx]:null,ma=St?.[yi],Ja=(dn?.tray_uuid||dn?.tag_uid||Eu(t.serial_number,ot.id,zt))?.toUpperCase(),bc=Ja?l?.[Ja]:void 0,Qi=Uk(bc),ho=u?.(t.id,ot.id,zt),xc=(()=>{const In=ho?.spool;return In&&In.label_weight>0&&In.weight_used!=null?Math.round(Math.max(0,In.label_weight-In.weight_used)/In.label_weight*100):null})(),oa=xc===0&&mr&&dn.remain>0?null:xc,po=Qi??oa??(mr?dn.remain:null),Qc=Qi!==null?"spoolman":oa!==null?"inventory":mr?"ams":void 0,ha=dn?.tray_type?{vendor:ND(dn)?"Bambu Lab":"Generic",profile:ma?.preset_name||Sl?.name||ho?.spool?.slicer_filament_name||dn.tray_sub_brands||dn.tray_type,colorName:Zl(dn.tray_color||""),colorHex:dn.tray_color||null,kFactor:_D(dn.k),fillLevel:po,trayUuid:dn.tray_uuid||null,tagUid:dn.tag_uid||null,fillSource:Qc}:null,Kd=Yi?.amsId===ot.id&&Yi?.slotId===zt,Tp=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Vn?"opacity-50":""} ${Bs?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(SD,{trayColor:dn?.tray_color,trayType:dn?.tray_type,isEmpty:Vn,slotNumber:zt+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:dn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:po!==null&&po>=0&&!Vn&&dn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${po}%`,backgroundColor:wx(po)}})})]});return a.jsxs("div",{className:"relative group",children:[Kd&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(cr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Oe?.state!=="RUNNING"&&a.jsx("button",{onClick:In=>{In.stopPropagation(),zo(mo?.amsId===ot.id&&mo?.slotId===zt?null:{amsId:ot.id,slotId:zt})},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:N("printers.slotOptions"),children:a.jsx(Bh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Oe?.state!=="RUNNING"&&mo?.amsId===ot.id&&mo?.slotId===zt&&a.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:a.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:In=>{In.stopPropagation(),k("printers:ams_rfid")&&(Wd.mutate({amsId:ot.id,slotId:zt}),zo(null))},disabled:Kd||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(cr,{className:`w-3 h-3 ${Kd?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ha?a.jsx(xD,{data:ha,spoolman:{enabled:o,linkedSpoolId:Ja?l?.[Ja]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const In=(ha.trayUuid||ha.tagUid||Eu(t.serial_number,ot.id,zt)).toUpperCase();vt({tagUid:ha.tagUid||In,trayUuid:ha.trayUuid||"",printerId:t.id,amsId:ot.id,trayId:zt})}:void 0,onUnlinkSpool:bc?.id?()=>xt.mutate(bc.id):void 0},inventory:o?void 0:(()=>{const In=u?.(t.id,ot.id,zt);return{assignedSpool:In?.spool?{id:In.spool.id,material:In.spool.material,brand:In.spool.brand,color_name:In.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(In.spool.label_weight-In.spool.weight_used))}:null,onAssignSpool:ha.vendor!=="Bambu Lab"?()=>$t({printerId:t.id,amsId:ot.id,trayId:zt,trayInfo:{type:dn?.tray_type||ha.profile,material:dn?.tray_type??void 0,profile:ha.profile,color:ha.colorHex||"",location:`${Rl(ot.id,ot.tray.length)} Slot ${zt+1}`}}):void 0,onUnassignSpool:In&&ha.vendor!=="Bambu Lab"?()=>m?.(t.id,ot.id,zt):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>en({amsId:ot.id,trayId:zt,trayCount:ot.tray.length,trayType:dn?.tray_type||void 0,trayColor:dn?.tray_color||void 0,traySubBrands:dn?.tray_sub_brands||void 0,trayInfoIdx:dn?.tray_info_idx||void 0,extruderId:Bn,caliIdx:dn?.cali_idx,savedPresetId:ma?.preset_id})},children:Tp}):a.jsx(yD,{configureSlot:dn?.state===10?{enabled:k("printers:control"),onConfigure:()=>en({amsId:ot.id,trayId:zt,trayCount:ot.tray.length,extruderId:Bn})}:void 0,inventory:dn?.state===10&&!o?{onAssignSpool:()=>$t({printerId:t.id,amsId:ot.id,trayId:zt,trayInfo:{type:"",color:"",location:`${Rl(ot.id,ot.tray.length)} Slot ${zt+1}`}})}:void 0,children:Tp})]},zt)})})]},ot.id)})}),(Ht.length>0||Oe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ht.map(ot=>{const Bn=fn[String(ot.id)],we=ot.id>=128?ot.id-128:ot.id,_t=Bn!==void 0?Bn:we,ln=_t===1,mn=_t===0,zt=ot.tray[0],dn=zt?.tray_type&&zt.remain>=0,mr=!zt?.tray_type,Vn=Wx(ot.id,zt?.id??0,!1),yi=Nn===Vn,Bs=zt?.tray_info_idx?Ye?.[zt.tray_info_idx]:null,Sl=St?.[Vn],ma=zt?.id??0,Ja=(zt?.tray_uuid||zt?.tag_uid||Eu(t.serial_number,ot.id,ma))?.toUpperCase(),bc=Ja?l?.[Ja]:void 0,Qi=Uk(bc),ho=u?.(t.id,ot.id,ma),xc=(()=>{const In=ho?.spool;return In&&In.label_weight>0&&In.weight_used!=null?Math.round(Math.max(0,In.label_weight-In.weight_used)/In.label_weight*100):null})(),oa=xc===0&&dn&&zt.remain>0?null:xc,po=Qi??oa??(dn?zt.remain:null),Qc=Qi!==null?"spoolman":oa!==null?"inventory":dn?"ams":void 0,ha=zt?.tray_type?{vendor:ND(zt)?"Bambu Lab":"Generic",profile:Sl?.preset_name||Bs?.name||ho?.spool?.slicer_filament_name||zt.tray_sub_brands||zt.tray_type,colorName:Zl(zt.tray_color||""),colorHex:zt.tray_color||null,kFactor:_D(zt.k),fillLevel:po,trayUuid:zt.tray_uuid||null,tagUid:zt.tag_uid||null,fillSource:Qc}:null,Kd=Yi?.amsId===ot.id&&Yi?.slotId===ma,Tp=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${mr?"opacity-50":""} ${yi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(SD,{trayColor:zt?.tray_color,trayType:zt?.tray_type,isEmpty:mr,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:zt?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:po!==null&&po>=0&&!mr&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${po}%`,backgroundColor:wx(po)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(rK,{ams:ot,printerId:t.id,label:Rl(ot.id,ot.tray.length),amsLabels:et,canEdit:k("printers:update"),onSaved:jt,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:et?.[ot.id]||Rl(ot.id,ot.tray.length)})}),Jt&&(ln||mn)&&a.jsx(JW,{side:ln?"L":"R"}),Oe.supports_drying&&(ot.module_type==="n3f"||ot.module_type==="n3s")&&k("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:In=>{if(ot.dry_time>0)Zn.mutate(ot.id);else if(Se===ot.id)ye(null);else{const Tm=(ot.tray.find(PS=>PS.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Zc=g[Tm]||g.PLA,CS=ot.module_type;Re(Tm),Te(Zc[CS]||Zc.n3f),Be(CS==="n3s"?Zc.n3s_hours:Zc.n3f_hours),tt(!1),ve(ot.module_type),ye(ot.id);const Ap=In.currentTarget.getBoundingClientRect();Ie({top:Ap.bottom+4,left:Math.max(8,Ap.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ot.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ot.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Au,{className:"w-3 h-3"})})})]}),ot.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Au,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ot.dry_time>=60?`${Math.floor(ot.dry_time/60)}h ${ot.dry_time%60}m`:`${ot.dry_time}m`}),a.jsx("button",{onClick:()=>Zn.mutate(ot.id),disabled:Zn.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Kd&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(cr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Oe?.state!=="RUNNING"&&a.jsx("button",{onClick:In=>{In.stopPropagation(),zo(mo?.amsId===ot.id&&mo?.slotId===ma?null:{amsId:ot.id,slotId:ma})},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:N("printers.slotOptions"),children:a.jsx(Bh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Oe?.state!=="RUNNING"&&mo?.amsId===ot.id&&mo?.slotId===ma&&a.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:a.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:In=>{In.stopPropagation(),k("printers:ams_rfid")&&(Wd.mutate({amsId:ot.id,slotId:ma}),zo(null))},disabled:Kd||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(cr,{className:`w-3 h-3 ${Kd?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ha?a.jsx(xD,{data:ha,spoolman:{enabled:o,linkedSpoolId:Ja?l?.[Ja]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const In=(ha.trayUuid||ha.tagUid||Eu(t.serial_number,ot.id,ma)).toUpperCase();vt({tagUid:ha.tagUid||In,trayUuid:ha.trayUuid||"",printerId:t.id,amsId:ot.id,trayId:ma})}:void 0,onUnlinkSpool:bc?.id?()=>xt.mutate(bc.id):void 0},inventory:o?void 0:(()=>{const In=u?.(t.id,ot.id,ma);return{assignedSpool:In?.spool?{id:In.spool.id,material:In.spool.material,brand:In.spool.brand,color_name:In.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(In.spool.label_weight-In.spool.weight_used))}:null,onAssignSpool:ha.vendor!=="Bambu Lab"?()=>$t({printerId:t.id,amsId:ot.id,trayId:ma,trayInfo:{type:zt?.tray_type||ha.profile,material:zt?.tray_type??void 0,profile:ha.profile,color:ha.colorHex||"",location:Rl(ot.id,ot.tray.length)}}):void 0,onUnassignSpool:In&&ha.vendor!=="Bambu Lab"?()=>m?.(t.id,ot.id,ma):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>en({amsId:ot.id,trayId:ma,trayCount:ot.tray.length,trayType:zt?.tray_type||void 0,trayColor:zt?.tray_color||void 0,traySubBrands:zt?.tray_sub_brands||void 0,trayInfoIdx:zt?.tray_info_idx||void 0,extruderId:Bn,caliIdx:zt?.cali_idx,savedPresetId:Sl?.preset_id})},children:Tp}):a.jsx(yD,{configureSlot:zt?.state===10?{enabled:k("printers:control"),onConfigure:()=>en({amsId:ot.id,trayId:ma,trayCount:ot.tray.length,extruderId:Bn})}:void 0,inventory:zt?.state===10&&!o?{onAssignSpool:()=>$t({printerId:t.id,amsId:ot.id,trayId:ma,trayInfo:{type:"",color:"",location:Rl(ot.id,ot.tray.length)}})}:void 0,children:Tp})]}),(ot.humidity!=null||ot.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ot.temp!=null&&a.jsx(nK,{temp:ot.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Ze({amsId:ot.id,amsLabel:Rl(ot.id,ot.tray.length),mode:"temperature"}),compact:!0}),ot.humidity!=null&&a.jsx(tK,{humidity:ot.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Ze({amsId:ot.id,amsLabel:Rl(ot.id,ot.tray.length),mode:"humidity"}),compact:!0})]})]})]},ot.id)}),Oe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Oe.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${Oe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Oe.vt_tray].sort((ot,Bn)=>(ot.id??254)-(Bn.id??254)).map(ot=>{const Bn=ot.id??254,we=Jt&&Nn===254?Bn===254&&Oe.active_extruder===1||Bn===255&&Oe.active_extruder===0:Nn===Bn,_t=Bn-254,ln=Jt?N(Bn===254?"printers.extL":"printers.extR"):"",mn=ot.tray_info_idx?Ye?.[ot.tray_info_idx]:null,zt=St?.[1020+_t],dn=(ot.tray_uuid||ot.tag_uid||Eu(t.serial_number,255,_t))?.toUpperCase(),mr=dn?l?.[dn]:void 0,Vn=Uk(mr),yi=u?.(t.id,255,_t),Bs=(()=>{const oa=yi?.spool;return oa&&oa.label_weight>0&&oa.weight_used!=null?Math.round(Math.max(0,oa.label_weight-oa.weight_used)/oa.label_weight*100):null})(),Sl=ot.tray_type&&ot.remain>=0,ma=Bs===0&&Sl&&ot.remain>0?null:Bs,Ja=Vn??ma??(Sl?ot.remain:null),bc=Vn!==null?"spoolman":ma!==null?"inventory":Sl?"ams":void 0,Qi={vendor:ND(ot)?"Bambu Lab":"Generic",profile:zt?.preset_name||mn?.name||yi?.spool?.slicer_filament_name||ot.tray_sub_brands||ot.tray_type||"Unknown",colorName:Zl(ot.tray_color||""),colorHex:ot.tray_color||null,kFactor:_D(ot.k),fillLevel:Ja,trayUuid:ot.tray_uuid||null,tagUid:ot.tag_uid||null,fillSource:bc},ho=!ot.tray_type,xc=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${ho?"opacity-50":""} ${we?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(SD,{trayColor:ot.tray_color,trayType:ot.tray_type,isEmpty:ho,slotNumber:_t+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${ho?"text-white/40":"text-white"}`,children:ot.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ja!==null&&Ja>=0&&!ho&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ja}%`,backgroundColor:wx(Ja)}})}),ln&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:ln})]});return a.jsx("div",{className:"relative group",children:ho?a.jsx(yD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>en({amsId:255,trayId:_t,trayCount:1,extruderId:Jt?Bn===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>$t({printerId:t.id,amsId:255,trayId:_t,trayInfo:{type:"",color:"",location:ln||N("printers.external")}})},children:xc}):a.jsx(xD,{data:Qi,spoolman:{enabled:o,linkedSpoolId:dn?l?.[dn]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const oa=(Qi.trayUuid||Qi.tagUid||Eu(t.serial_number,255,_t)).toUpperCase();vt({tagUid:Qi.tagUid||oa,trayUuid:Qi.trayUuid||"",printerId:t.id,amsId:255,trayId:_t})}:void 0,onUnlinkSpool:mr?.id?()=>xt.mutate(mr.id):void 0},inventory:o?void 0:(()=>{const oa=u?.(t.id,255,_t);return{assignedSpool:oa?.spool?{id:oa.spool.id,material:oa.spool.material,brand:oa.spool.brand,color_name:oa.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(oa.spool.label_weight-oa.spool.weight_used))}:null,onAssignSpool:()=>$t({printerId:t.id,amsId:255,trayId:_t,trayInfo:{type:ot.tray_type||Qi.profile,material:ot.tray_type??void 0,profile:Qi.profile,color:Qi.colorHex||"",location:ln||N("printers.external")}}),onUnassignSpool:oa?()=>m?.(t.id,255,_t):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>en({amsId:255,trayId:_t,trayCount:1,trayType:ot.tray_type||void 0,trayColor:ot.tray_color||void 0,traySubBrands:ot.tray_sub_brands||void 0,trayInfoIdx:ot.tray_info_idx||void 0,extruderId:Jt?Bn===254?1:0:void 0,caliIdx:ot.cali_idx,savedPresetId:zt?.preset_id})},children:xc})},Bn)})})]})]})]})]})})()]}),Pn&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(ic,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Pn.name}),Sn&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Sn.state==="ON"?"bg-bambu-green/20 text-bambu-green":Sn.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Sn.state||"?",Sn.state==="ON"&&Sn.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Sn.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>ce(!0),disabled:qt.isPending||Sn?.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")?Sn?.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:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Ud,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>Ne(!0),disabled:qt.isPending||Sn?.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")?Sn?.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:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Uw,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Pn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Pn.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Kc.mutate(!Pn.auto_off),disabled:Kc.isPending||Pn.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?Pn.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?Pn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Pn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Pn.auto_off||Pn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Nr&&Nr.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Rw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Nr.map(mt=>{const Ht=mt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>Ki.mutate({id:mt.id,action:Ht?"on":"toggle"}),disabled:Ki.isPending,title:`${Ht?"Run":"Toggle"} ${mt.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:[a.jsx($i,{className:"w-2.5 h-2.5"}),mt.name]},mt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>km.mutate(!Oe?.chamber_light),disabled:!Oe?.connected||km.isPending||!k("printers:control"),title:k("printers:control")?Oe?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:Oe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(iI,{on:Oe?.chamber_light??!1,className:`w-4 h-4 ${Oe?.chamber_light?"text-yellow-400":""}`})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&x)x(t.id,t.name);else{const mt=localStorage.getItem("cameraWindowState"),Ht=mt?JSON.parse(mt):{width:640,height:400},Jt=[`width=${Ht.width}`,`height=${Ht.height}`,Ht.left!==void 0?`left=${Ht.left}`:"",Ht.top!==void 0?`top=${Ht.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Jt)}},disabled:!Oe?.connected||!k("camera:view"),title:k("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(kO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:Pp,disabled:!Oe?.connected||Xi.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("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:Xi.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(uN,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:vl,disabled:!Oe?.connected||Yt||!k("printers:update"),title:k("printers:update")?N("printers.plateDetection.manageCalibration"):N("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:Yt?a.jsx(dt,{className:"w-3 h-3 animate-spin"}):a.jsx(Un,{className:"w-3 h-3"})})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>le(!0),disabled:!Gt||!k("printers:files"),title:k("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(rp,{className:"w-4 h-4"}),N("printers.files")]}),Gt&&Oe?.state!=="RUNNING"&&Oe?.state!=="PAUSE"&&a.jsxs(Fe,{size:"sm",onClick:()=>pe(!0),disabled:!k("printers:control"),title:k("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Ar,{className:"w-4 h-4"}),N("common.print")]})]})]}),ue&&a.jsx(RMe,{printerId:t.id,printerName:t.name,onClose:()=>le(!1)}),fe&&a.jsx(Uae,{folderId:null,onClose:()=>pe(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:mt=>{const Ht=mt.name.toLowerCase();if(!Ht.endsWith(".gcode")&&!Ht.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:mt=>{const Ht=mt.metadata?.sliced_for_model,Jt=y0(t.model);if(Ht&&Jt&&Ht.toLowerCase()!==Jt.toLowerCase())return me.deleteLibraryFile(mt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Ht,printerModel:Jt});_e({id:mt.id,filename:mt.filename})}}),ae&&a.jsx(ec,{mode:"reprint",libraryFileId:ae.id,archiveName:ae.filename,initialSelectedPrinterIds:[t.id],onClose:()=>_e(null),onSuccess:()=>_e(null)}),oe&&a.jsx(BMe,{printerId:t.id,printerName:t.name,onClose:()=>W(!1)}),de&&a.jsx(x7e,{printer:t,status:Oe,totalPrintHours:n?.total_print_hours,onClose:R}),Ge&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>co(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:mt=>mt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[Ge.needs_calibration?a.jsx(uN,{className:"w-5 h-5 text-blue-500"}):Ge.is_empty?a.jsx(xr,{className:"w-5 h-5 text-green-500"}):a.jsx(Na,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Ge.reference_count!==void 0&&Ge.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Ge.reference_count,"/",Ge.max_references," refs"]})]}),a.jsx("button",{onClick:()=>co(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${Ge.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${Ge.is_empty?"text-green-400":"text-yellow-400"}`,children:Ge.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(Ge.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",Ge.difference_percent.toFixed(1),"%"]})]}),Ge.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:Ge.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Ge.message})]}),yl&&yl.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:yl.references.length,max:yl.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:yl.references.map(mt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.getPlateReferenceThumbnailUrl(t.id,mt.index),alt:mt.label||`Reference ${mt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>Xc(mt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:N("printers.plateDetection.deleteReference"),children:a.jsx(Bt,{className:"w-3 h-3 text-white"})}),Us?.index===mt.index?a.jsx("input",{type:"text",value:Us.label,onChange:Ht=>gc({...Us,label:Ht.target.value}),onBlur:()=>Io(mt.index,Us.label),onKeyDown:Ht=>{Ht.key==="Enter"&&Io(mt.index,Us.label),Ht.key==="Escape"&&gc(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:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>gc({index:mt.index,label:mt.label}),title:mt.label?N("printers.plateDetection.clickToEdit",{label:mt.label}):N("printers.plateDetection.clickToAddLabel"),children:mt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:mt.timestamp?er(mt.timestamp)?.toLocaleDateString()??"":""})]},mt.index))})]}),!Ge.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),Ut?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>ze(null),disabled:st,children:N("common.cancel")}),a.jsx(Fe,{size:"sm",onClick:Cm,disabled:st,children:st?a.jsx(dt,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:()=>ze(Ge.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(ai,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),Ut?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:Ut.x,onChange:mt=>ze({...Ut,x:parseFloat(mt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Ut.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:Ut.y,onChange:mt=>ze({...Ut,y:parseFloat(mt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Ut.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:Ut.w,onChange:mt=>ze({...Ut,w:parseFloat(mt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Ut.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:Ut.h,onChange:mt=>ze({...Ut,h:parseFloat(mt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(Ut.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Ge.roi?.x||.15)*100),"%, Y=",Math.round((Ge.roi?.y||.35)*100),"%, W=",Math.round((Ge.roi?.w||.7)*100),"%, H=",Math.round((Ge.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Fe,{variant:"ghost",onClick:()=>co(),children:N("common.cancel")}),a.jsx(Fe,{onClick:()=>wl(),disabled:pt,children:pt?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Fe,{variant:"ghost",onClick:()=>wl(),disabled:pt,children:pt?"Adding...":`Add Reference (${yl?.references.length||0}/${yl?.max_references||5})`}),a.jsx(Fe,{onClick:()=>co(),children:"Close"})]})})]})}),re&&Pn&&a.jsx(_n,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{qt.mutate("on"),ce(!1)},onCancel:()=>ce(!1)}),xe&&Pn&&a.jsx(_n,{title:N("printers.confirm.powerOffTitle"),message:Oe?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{qt.mutate("off"),Ne(!1)},onCancel:()=>Ne(!1)}),E&&a.jsx(_n,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{gl.mutate(),j(!1)},onCancel:()=>j(!1)}),O&&a.jsx(_n,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{fc.mutate(),K(!1)},onCancel:()=>K(!1)}),Q&&a.jsx(_n,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Qa.mutate(),G(!1)},onCancel:()=>G(!1)}),a.jsx(sI,{printerId:t.id,isOpen:J,onClose:()=>se(!1)}),$&&a.jsx(Oye,{printerName:t.name,errors:Oe?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:k}),qe&&a.jsx(QVe,{isOpen:!!qe,onClose:()=>Ze(null),printerId:t.id,printerName:t.name,amsId:qe.amsId,amsLabel:qe.amsLabel,initialMode:qe.mode,thresholds:s}),ut&&a.jsx(Oae,{isOpen:!!ut,onClose:()=>vt(null),tagUid:ut.tagUid,trayUuid:ut.trayUuid,printerId:ut.printerId,amsId:ut.amsId,trayId:ut.trayId}),wt&&a.jsx(Iae,{isOpen:!!wt,onClose:()=>$t(null),printerId:wt.printerId,amsId:wt.amsId,trayId:wt.trayId,trayInfo:wt.trayInfo}),Qt&&a.jsx(zae,{isOpen:!!Qt,onClose:()=>en(null),printerId:t.id,slotInfo:Qt,printerModel:y0(t.model)||void 0,onSuccess:()=>{A.invalidateQueries({queryKey:["slotPresets",t.id]}),A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ie&&a.jsx(E7e,{printer:t,onClose:()=>ee(!1)}),Xt&&Ce&&a.jsx(M7e,{printer:t,firmwareInfo:Ce,onClose:()=>tn(!1)}),mo&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>zo(null)}),Se!==null&&te&&(()=>{const mt=Ae==="n3s"?85:65,Ht=35,Jt=mt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>ye(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:te.top,left:te.left},onClick:ot=>ot.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Au,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:je,onChange:ot=>{const Bn=ot.target.value;Re(Bn);const we=g[Bn];we&&(Te(we[Ae==="n3s"?"n3s":"n3f"]),Be(Ae==="n3s"?we.n3s_hours:we.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(g).map(ot=>a.jsx("option",{value:ot,children:ot},ot))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:mt,value:Ee,onChange:ot=>Te(Math.min(mt,Math.max(45,Number(ot.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:Ht,max:Jt,value:Ee,onChange:ot=>Te(Math.min(mt,Math.max(45,Number(ot.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[mt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:Me,onChange:ot=>Be(Math.min(24,Math.max(1,Number(ot.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:Me,onChange:ot=>Be(Number(ot.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ke,onChange:ot=>tt(ot.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{Se!==null&&Kn.mutate({amsId:Se,temp:Ee,duration:Me,filament:je,rotateTray:Ke})},disabled:Kn.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:Kn.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function j7e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[g,b]=w.useState([]),[_,C]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{rd.getInfo().then(k=>{v(k.is_docker),k.subnets.length>0&&(b(k.subnets),C(k.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(k=>!n.includes(k.serial)),T=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(x){await rd.startSubnetScan(_);const k=setInterval(async()=>{try{const D=await rd.getScanStatus();N({scanned:D.scanned,total:D.total});const H=await rd.getDiscoveredPrinters();d(H),D.running||(clearInterval(k),l(!1),f(!0))}catch(D){console.error("Failed to get scan status:",D)}},500)}else{await rd.startDiscovery(10);const k=setInterval(async()=>{try{const D=await rd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get discovered printers:",D)}},1e3);setTimeout(async()=>{clearInterval(k);try{await rd.stopDiscovery()}catch{}l(!1),f(!0);try{const D=await rd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get final discovered printers:",D)}},1e4)}}catch(k){console.error("Failed to start discovery:",k),m(k instanceof Error?k.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},F=k=>{const D=k.serial.startsWith("unknown-")?"":k.serial;s({...i,name:k.name||"",serial_number:D,ip_address:k.ip_address,model:y0(k.model)}),d([])};return w.useEffect(()=>()=>{rd.stopDiscovery().catch(()=>{}),rd.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const k=D=>{D.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:k=>k.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.length>0?a.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:k=>C(k.target.value),disabled:o,children:g.map(k=>a.jsx("option",{value:k,children:k},k))}):a.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:k=>C(k.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Fe,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),x&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(kr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(k=>a.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:()=>F(k),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:k.name||k.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[y0(k.model)||r("printers.discovery.unknown")," • ",k.ip_address,k.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Un,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},k.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:k=>{k.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.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:i.name,onChange:k=>s({...i,name:k.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.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:i.ip_address,onChange:k=>s({...i,ip_address:k.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.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:i.serial_number,onChange:k=>s({...i,serial_number:k.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.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:i.access_code,onChange:k=>s({...i,access_code:k.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.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:i.model||"",onChange:k=>s({...i,model:k.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.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:i.location||"",onChange:k=>s({...i,location:k.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:k=>s({...i,auto_archive:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Fe,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function M7e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=sn(),{showToast:s}=bn(),{hasPermission:o}=wr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[x,v]=w.useState(e.update_available?e.latest_version:null),{data:g,isLoading:b}=Qe({queryKey:["firmwarePrepare",t.id,x],queryFn:()=>kk.prepareUpload(t.id,x??void 0),staleTime:3e4,enabled:!!x&&l&&!u}),_=it({mutationFn:()=>kk.startUpload(t.id,x??void 0),onSuccess:()=>{m(!0);const P=setInterval(async()=>{try{const N=await kk.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(P),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(P)},onError:P=>{s(r("printers.firmwareModal.uploadFailed",{error:P.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const C=()=>{d(null),_.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(At,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ca,{className:"w-5 h-5 text-orange-400"}):a.jsx(xr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const P=x?e.available_versions?.find(F=>F.version===x):null,N=x??e.latest_version,A=P?.release_notes??e.release_notes,T=!!N&&N!==e.current_version;return a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${T?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),T&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),A&&a.jsxs("details",{className:"mt-3 text-sm",open:!T,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${T?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:A})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:r("printers.firmwareModal.availableVersions")}),a.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(P=>{const N=e.current_version===P.version,A=x===P.version,T=e.current_version?v7e(P.version,e.current_version):0,F=N?r("printers.firmwareModal.currentBadge"):T>0?r("printers.firmwareModal.newerBadge"):r("printers.firmwareModal.olderBadge"),k=N?"text-bambu-gray":T>0?"text-orange-400":"text-blue-400";return a.jsxs("button",{type:"button",disabled:!P.file_available||!l||N,onClick:()=>v(P.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${A?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!P.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-white",children:P.version}),a.jsx("span",{className:`text-xs ${k}`,children:F})]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":P.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?r("printers.firmwareModal.installed"):P.file_available?r("printers.firmwareModal.usable"):r("printers.firmwareModal.unavailable")})]},P.version)})})]}),x?b?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):g&&!u&&!c?a.jsx("div",{className:"mb-4",children:g.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(mi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:g.errors.map((P,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Wa,{className:"w-4 h-4 flex-shrink-0"}),P]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.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}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Fe,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),g?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(Fe,{onClick:C,disabled:_.isPending,children:_.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ca,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function E7e({printer:t,onClose:e}){const{t:n}=Rt(),r=sn(),{showToast:i}=bn(),[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=it({mutationFn:d=>me.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={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&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.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:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.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:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.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:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.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:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.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:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Fe,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function D7e(t){const{data:e}=Qe({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function F7e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=D7e(t.id),{data:s}=Qe({queryKey:["smartPlugStatus",e.id],queryFn:()=>me.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.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||"?"})]}),a.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:[a.jsx(Ud,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function R7e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,x]=w.useState(()=>{const te=localStorage.getItem("printerCardSize");return te?parseInt(te,10):2}),v=f===1?"compact":"expanded",[g,b]=w.useState(""),[_,C]=w.useState("all"),[P,N]=w.useState("all"),[A,T]=w.useState(0),F=sn(),{showToast:k}=bn(),{hasPermission:D}=wr(),[H,z]=w.useState(()=>{const te=localStorage.getItem("openEmbeddedCameras");if(te)try{const Ie=JSON.parse(te);return new Map(Ie.map(be=>[be.id,be]))}catch{return new Map}return new Map});w.useEffect(()=>{const te=Array.from(H.values());te.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(te)):localStorage.removeItem("openEmbeddedCameras")},[H]);const{data:X,isLoading:L}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:ne}=Qe({queryKey:["settings"],queryFn:me.getSettings}),ie=w.useMemo(()=>{if(ne?.drying_presets)try{const te=JSON.parse(ne.drying_presets);if(typeof te=="object"&&te!==null&&Object.keys(te).length>0)return{...lL,...te}}catch{}return lL},[ne?.drying_presets]);w.useEffect(()=>{ne?.camera_view_mode==="window"&&H.size>0&&z(new Map)},[ne?.camera_view_mode,H.size]);const{data:ee}=Qe({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),{data:ue}=Qe({queryKey:["maintenanceOverview"],queryFn:me.getMaintenanceOverview,staleTime:60*1e3}),{data:le}=Qe({queryKey:["spoolman-status"],queryFn:me.getSpoolmanStatus,staleTime:60*1e3}),oe=le?.enabled&&le?.connected,{data:W}=Qe({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings,enabled:!!oe,staleTime:60*1e3}),re=W?.spoolman_sync_mode,{data:ce}=Qe({queryKey:["unlinked-spools"],queryFn:me.getUnlinkedSpools,enabled:!!oe,staleTime:30*1e3}),xe=ce&&ce.length>0,{data:Ne}=Qe({queryKey:["linked-spools"],queryFn:me.getLinkedSpools,enabled:!!oe,staleTime:30*1e3}),$=Ne?.linked,{data:Y}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),enabled:D("inventory:view_assignments"),staleTime:30*1e3}),E=it({mutationFn:({printerId:te,amsId:Ie,trayId:be})=>me.unassignSpool(te,Ie,be),onSuccess:()=>{F.invalidateQueries({queryKey:["spool-assignments"]})}}),j=(te,Ie,be)=>Y?.find($e=>$e.printer_id===te&&$e.ams_id===Number(Ie)&&$e.tray_id===Number(be)),O=ue?.reduce((te,Ie)=>(te[Ie.printer_id]={due_count:Ie.due_count,warning_count:Ie.warning_count,total_print_hours:Ie.total_print_hours},te),{})||{},K=ee?.reduce((te,Ie)=>(Ie.printer_id&&(te[Ie.printer_id]=Ie),te),{})||{},B=it({mutationFn:me.createPrinter,onSuccess:()=>{F.invalidateQueries({queryKey:["printers"]}),F.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:te=>k(te.message||t("printers.toast.failedToAdd"),"error")}),he=it({mutationFn:te=>me.controlSmartPlug(te,"on"),onSuccess:()=>{F.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[I,V]=w.useState(new Set),[Q,G]=w.useState(!1),[J,se]=w.useState(null),[fe,pe]=w.useState(!1),de=Q||I.size>0,U=w.useCallback(te=>{V(Ie=>{const be=new Set(Ie);return be.has(te)?be.delete(te):be.add(te),be})},[]),R=w.useCallback(()=>{V(new Set),G(!1)},[]);w.useEffect(()=>{const te=Ie=>{Ie.key==="Escape"&&de&&R()};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[de,R]);const ae=w.useCallback(async te=>{pe(!0);const be=Array.from(I).filter(qe=>{const Ze=F.getQueryData(["printerStatus",qe]);if(!Ze?.connected)return!1;switch(te){case"stop":return Ze.state==="RUNNING"||Ze.state==="PAUSE";case"pause":return Ze.state==="RUNNING";case"resume":return Ze.state==="PAUSE";case"clearPlate":return!!Ze.awaiting_plate_clear;case"clearHMS":return Ze.hms_errors&&Uu(Ze.hms_errors).length>0;default:return!1}});if(be.length===0){k(t("printers.bulk.noneApplicable"),"error"),pe(!1),se(null);return}const $e={stop:me.stopPrint,pause:me.pausePrint,resume:me.resumePrint,clearPlate:me.clearPlate,clearHMS:me.clearHMSErrors}[te],He=await Promise.allSettled(be.map(qe=>$e(qe))),ge=He.filter(qe=>qe.status==="fulfilled").length,Pe=He.filter(qe=>qe.status==="rejected").length;Pe===0?k(t("printers.bulk.success",{action:t(`printers.bulk.actions.${te}`),count:ge})):k(t("printers.bulk.partial",{succeeded:ge,failed:Pe}),"error"),be.forEach(qe=>{F.invalidateQueries({queryKey:["printerStatus",qe]})}),pe(!1),se(null)},[I,F,k,t]),_e=w.useCallback(te=>{te==="stop"||te==="pause"||te==="clearPlate"?se(te):ae(te)},[ae]),Se=()=>{const te=!r;i(te),localStorage.setItem("hideDisconnectedPrinters",String(te))},ye=te=>{u(te),localStorage.setItem("printerSortBy",te)},Ae=()=>{const te=!m;p(te),localStorage.setItem("printerSortAsc",String(te))},ve=()=>{switch(f){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"}},je=["S","M","L","XL"];w.useEffect(()=>F.getQueryCache().subscribe(Ie=>{Ie.type==="updated"&&Array.isArray(Ie.query.queryKey)&&Ie.query.queryKey[0]==="printerStatus"&&T(be=>be+1)}),[F]);const Re=w.useMemo(()=>{if(!X)return[];let te=X;if(g.trim()){const Ie=g.trim().toLowerCase();te=te.filter(be=>be.name.toLowerCase().includes(Ie)||(be.model||"").toLowerCase().includes(Ie)||(be.location||"").toLowerCase().includes(Ie)||(be.serial_number||"").toLowerCase().includes(Ie))}return P!=="all"&&(te=te.filter(Ie=>(Ie.location||"")===P)),_!=="all"&&(te=te.filter(Ie=>{const be=F.getQueryData(["printerStatus",Ie.id]);if(!be?.connected)return _==="offline";const $e=be.hms_errors?Uu(be.hms_errors):[];switch(_){case"printing":return be.state==="RUNNING";case"paused":return be.state==="PAUSE";case"finished":return be.state==="FINISH";case"error":return be.state==="FAILED"||$e.length>0;case"idle":return be.state!=="RUNNING"&&be.state!=="PAUSE"&&be.state!=="FINISH"&&be.state!=="FAILED"&&$e.length===0;case"offline":return!1;default:return!0}})),te},[X,g,_,P,F,A]),Ee=w.useMemo(()=>X?[...new Set(X.map(te=>te.location||"").filter(Boolean))].sort():[],[X]),Te=w.useMemo(()=>{const te=[...Re];switch(d){case"name":te.sort((Ie,be)=>Ie.name.localeCompare(be.name));break;case"model":te.sort((Ie,be)=>(Ie.model||"").localeCompare(be.model||""));break;case"location":te.sort((Ie,be)=>{const $e=Ie.location||"",He=be.location||"";return!$e&&He?1:$e&&!He?-1:$e.localeCompare(He)||Ie.name.localeCompare(be.name)});break;case"status":te.sort((Ie,be)=>{const $e=F.getQueryData(["printerStatus",Ie.id]),He=F.getQueryData(["printerStatus",be.id]),ge=Pe=>Pe?.connected?(Pe.hms_errors?Uu(Pe.hms_errors):[]).length>0?0:Pe.state==="RUNNING"?1:2:3;return ge($e)-ge(He)});break}return m||te.reverse(),te},[Re,d,m,F]),Me=w.useCallback(()=>{V(new Set(Te.map(te=>te.id))),G(!0)},[Te]),Be=w.useCallback(te=>{V(Ie=>{const be=new Set(Ie);return Te.forEach($e=>{const He=F.getQueryData(["printerStatus",$e.id]);if(He)switch(te){case"printing":He.connected&&He.state==="RUNNING"&&be.add($e.id);break;case"paused":He.connected&&He.state==="PAUSE"&&be.add($e.id);break;case"finished":He.connected&&He.state==="FINISH"&&be.add($e.id);break;case"idle":He.connected&&He.state!=="RUNNING"&&He.state!=="PAUSE"&&He.state!=="FINISH"&&He.state!=="FAILED"&&be.add($e.id);break;case"error":He.connected&&(He.state==="FAILED"||He.hms_errors&&Uu(He.hms_errors).length>0)&&be.add($e.id);break;case"offline":He.connected||be.add($e.id);break}}),be}),G(!0)},[Te,F]),Ke=w.useCallback(te=>{V(Ie=>{const be=new Set(Ie);return Te.filter($e=>($e.location||"")===te).forEach($e=>be.add($e.id)),be}),G(!0)},[Te]),tt=w.useMemo(()=>{if(d!=="location")return null;const te={};return Te.forEach(Ie=>{const be=Ie.location||"Ungrouped";te[be]||(te[be]=[]),te[be].push(Ie)}),te},[d,Te]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(A7e,{printers:X}),X&&X.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:g,onChange:te=>b(te.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 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"}),g&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>b(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:te=>ye(te.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:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ae,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(Wf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Cx,{className:"w-4 h-4 text-bambu-gray"})})]}),X&&X.length>0&&a.jsxs("select",{value:_,onChange:te=>C(te.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:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),X&&X.length>0&&Ee.length>0&&a.jsxs("select",{value:P,onChange:te=>N(te.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:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Ee.map(te=>a.jsx("option",{value:te,children:te},te))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:je.map((te,Ie)=>{const be=Ie+1,$e=f===be;return a.jsx("button",{onClick:()=>{x(be),localStorage.setItem("printerCardSize",String(be))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ie===0?"rounded-l-lg":""} ${Ie===je.length-1?"rounded-r-lg":""} ${$e?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(te==="S"?"printers.cardSize.small":te==="M"?"printers.cardSize.medium":te==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:te},te)})}),a.jsx("button",{onClick:()=>{de?R():G(!0)},className:`p-1.5 rounded-lg transition-colors ${de?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!D("printers:control"),children:a.jsx(xs,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:Se,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(K).length>0&&a.jsxs("div",{className:"relative",children:[a.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:[a.jsx(Ud,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Un,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.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:[a.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")}),X?.filter(te=>K[te.id]).map(te=>a.jsx(F7e,{printer:te,plug:K[te.id],onPowerOn:Ie=>{c(Ie),he.mutate(Ie)},isPowering:l===K[te.id]?.id},te.id)),X?.filter(te=>K[te.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Fe,{onClick:()=>n(!0),disabled:!D("printers:create"),title:D("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),L?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):X?.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Fe,{onClick:()=>n(!0),disabled:!D("printers:create"),title:D("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Te.length===0&&(g.trim()||_!=="all"||P!=="all")?a.jsx(At,{children:a.jsx(Mt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):tt?a.jsx("div",{className:"space-y-6",children:Object.entries(tt).map(([te,Ie])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),te,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ie.length,")"]}),de&&a.jsx("button",{onClick:()=>Ke(te==="Ungrouped"?"":te),className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ve()}`,children:Ie.map(be=>a.jsx(aK,{printer:be,hideIfDisconnected:r,maintenanceInfo:O[be.id],viewMode:v,cardSize:f,amsThresholds:ne?{humidityGood:Number(ne.ams_humidity_good)||40,humidityFair:Number(ne.ams_humidity_fair)||60,tempGood:Number(ne.ams_temp_good)||28,tempFair:Number(ne.ams_temp_fair)||35}:void 0,spoolmanEnabled:oe,hasUnlinkedSpools:xe,linkedSpools:$,spoolmanUrl:le?.url,spoolmanSyncMode:re,onGetAssignment:j,onUnassignSpool:($e,He,ge)=>E.mutate({printerId:$e,amsId:He,trayId:ge}),timeFormat:ne?.time_format||"system",cameraViewMode:ne?.camera_view_mode||"window",onOpenEmbeddedCamera:($e,He)=>z(ge=>new Map(ge).set($e,{id:$e,name:He})),checkPrinterFirmware:ne?.check_printer_firmware!==!1,dryingPresets:ie,requirePlateClear:ne?.require_plate_clear===!0,selectionMode:de,isSelected:I.has(be.id),onToggleSelect:U},be.id))})]},te))}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ve()}`,children:Te.map(te=>a.jsx(aK,{printer:te,hideIfDisconnected:r,maintenanceInfo:O[te.id],viewMode:v,cardSize:f,spoolmanEnabled:oe,hasUnlinkedSpools:xe,linkedSpools:$,spoolmanUrl:le?.url,spoolmanSyncMode:re,onGetAssignment:j,onUnassignSpool:(Ie,be,$e)=>E.mutate({printerId:Ie,amsId:be,trayId:$e}),amsThresholds:ne?{humidityGood:Number(ne.ams_humidity_good)||40,humidityFair:Number(ne.ams_humidity_fair)||60,tempGood:Number(ne.ams_temp_good)||28,tempFair:Number(ne.ams_temp_fair)||35}:void 0,timeFormat:ne?.time_format||"system",cameraViewMode:ne?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ie,be)=>z($e=>new Map($e).set(Ie,{id:Ie,name:be})),checkPrinterFirmware:ne?.check_printer_firmware!==!1,dryingPresets:ie,requirePlateClear:ne?.require_plate_clear===!0,selectionMode:de,isSelected:I.has(te.id),onToggleSelect:U},te.id))}),e&&a.jsx(j7e,{onClose:()=>n(!1),onAdd:te=>B.mutate(te),existingSerials:X?.map(te=>te.serial_number)||[]}),de&&X&&a.jsx(zye,{selectedIds:I,printers:X,onClose:R,onSelectAll:Me,onSelectByLocation:Ke,onSelectByState:Be,onAction:_e,actionPending:fe}),J==="stop"&&a.jsx(_n,{title:t("printers.bulk.confirm.stopTitle",{count:I.size}),message:t("printers.bulk.confirm.stopMessage",{count:I.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:fe,onConfirm:()=>ae("stop"),onCancel:()=>se(null)}),J==="pause"&&a.jsx(_n,{title:t("printers.bulk.confirm.pauseTitle",{count:I.size}),message:t("printers.bulk.confirm.pauseMessage",{count:I.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:fe,onConfirm:()=>ae("pause"),onCancel:()=>se(null)}),J==="clearPlate"&&a.jsx(_n,{title:t("printers.bulk.confirm.clearPlateTitle",{count:I.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:I.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:fe,onConfirm:()=>ae("clearPlate"),onCancel:()=>se(null)}),Array.from(H.values()).map((te,Ie)=>a.jsx(UMe,{printerId:te.id,printerName:te.name,viewerIndex:Ie,onClose:()=>z(be=>{const $e=new Map(be);return $e.delete(te.id),$e})},te.id))]})}function L7e(){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 Pf(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:L7e()==="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 iK=768;function Kae(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<iK:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${iK-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function cz({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Qe({queryKey:["settings"],queryFn:me.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,x]=w.useState(!0),[v,g]=w.useState(null),[b,_]=w.useState(!1),[C,P]=w.useState(null),[N,A]=w.useState(0),[T,F]=w.useState(!1),[k,D]=w.useState(null),[H,z]=w.useState(!1),[X,L]=w.useState(!1),ne=w.useRef(null),ie=w.useRef(null),ee=10,ue=160,le=240,oe=.35;w.useEffect(()=>{const pe=de=>{de.key==="Escape"&&i()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[i]),w.useEffect(()=>{if(x(!0),c){const pe=(r||"").toLowerCase(),de=pe==="3mf"||pe==="stl",U=pe==="gcode"||pe==="3mf";p({has_model:de,has_gcode:U,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(de?"3d":U?"gcode":null),x(!1);return}if(!t){p(null),u(null),x(!1);return}me.getArchiveCapabilities(t).then(pe=>{p(pe),pe.has_model?u("3d"):pe.has_gcode&&u("gcode"),x(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),P(null),A(0),c){const pe=(r||"").toLowerCase();if(!e||pe!=="3mf"){g(null),_(!1);return}me.getLibraryFilePlates(e).then(de=>g(de)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}me.getArchivePlates(t).then(pe=>g(pe)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const W=w.useMemo(()=>v?.plates??[],[v]),re=(v?.is_multi_plate??!1)&&W.length>1,ce=T&&re,xe=C==null?null:W.find(pe=>pe.index===C)??null,Ne=pe=>pe.object_count??pe.objects?.length??0,$=W.reduce((pe,de)=>pe+Ne(de),0),Y=xe?Ne(xe):$,E=xe?s("modelViewer.plateNumber",{number:xe.index}):s("modelViewer.allPlates"),j=W.length>0,O=w.useRef(null),K=w.useRef(null),[B,he]=w.useState(10),[I,V]=w.useState(3),Q=W.length>B,G=Math.max(1,Math.ceil(W.length/B)),J=Q?W.slice(N*B,(N+1)*B):W;w.useEffect(()=>{if(!ce){he(10),V(3);return}const pe=O.current,de=K.current;if(!pe||!de)return;let U=0;const R=()=>{const Se=de.clientWidth,Ae=Math.floor(Se/210),ve=Math.max(3,Math.min(5,Ae||3));V(te=>te===ve?te:ve);const je=window.getComputedStyle(pe),Re=Number.parseFloat(je.rowGap||"0"),Te=pe.querySelector("button")?.getBoundingClientRect().height??44,Me=de.clientHeight,Ke=Math.max(1,Math.floor((Me+Re)/(Te+Re)))*ve,tt=Math.max(1,Ke-1);he(te=>te===tt?te:tt)},ae=()=>{U&&cancelAnimationFrame(U),U=requestAnimationFrame(R)};ae();const _e=new ResizeObserver(ae);return _e.observe(de),_e.observe(pe),()=>{U&&cancelAnimationFrame(U),_e.disconnect()}},[ce,W.length]),w.useEffect(()=>{if(!Q){A(0);return}A(pe=>Math.min(pe,G-1))},[W.length,Q,G]),w.useEffect(()=>{if(!Q||C==null)return;const pe=W.findIndex(U=>U.index===C);if(pe<0)return;const de=Math.floor(pe/B);A(U=>U===de?U:de)},[W,B,C,Q]),w.useEffect(()=>{if(!ce){D(null),L(!1);return}if(X)return;const pe=ne.current,de=ie.current;if(!pe||!de)return;const U=pe.clientHeight;if(!U)return;const R=Math.max(le,U*oe),ae=Math.max(ue,U-ee-R),_e=Math.min(de.scrollHeight,ae);D(Math.max(ue,_e))},[ce,X,W.length,N,ee,ue,le,oe]),w.useEffect(()=>{if(!H)return;const pe=U=>{const R=ne.current;if(!R)return;const ae=R.getBoundingClientRect(),_e=ae.height;if(!_e)return;const Se=Math.max(le,_e*oe),ye=Math.max(ue,_e-ee-Se),Ae=Math.min(ye,Math.max(ue,U.clientY-ae.top));D(Ae)},de=()=>{z(!1),L(!0)};return document.addEventListener("mousemove",pe),document.addEventListener("mouseup",de),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",pe),document.removeEventListener("mouseup",de),document.body.style.cursor="",document.body.style.userSelect=""}},[H,ee,ue,le,oe]);const se=c?(r||"").toLowerCase()==="3mf":!0,fe=async()=>{if(!se)return;const pe=n||"model";try{if(c){const{token:de}=await me.createLibrarySlicerToken(e),U=me.getLibrarySlicerDownloadUrl(e,de,pe);Pf(`${window.location.origin}${U}`,l)}else{const{token:de}=await me.createArchiveSlicerToken(t),U=me.getArchiveSlicerDownloadUrl(t,de,pe);Pf(`${window.location.origin}${U}`,l)}}catch{if(c){const de=`${window.location.origin}${me.getLibraryFileDownloadUrl(e)}`;Pf(de,l)}else{const de=`${window.location.origin}${me.getArchiveForSlicer(t,pe)}`;Pf(de,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${T?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${T?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:pe=>pe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[E,": ",s("modelViewer.objectCount",{count:Y})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:fe,disabled:!se,children:[a.jsx(na,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>F(pe=>!pe),title:T?"Exit fullscreen":"Enter fullscreen",children:T?a.jsx(vO,{className:"w-4 h-4"}):a.jsx(MP,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),m&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(mi,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(ffe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?a.jsxs("div",{ref:ne,className:`w-full h-full flex flex-col ${ce?"gap-0 min-h-0":"gap-3"}`,children:[re&&a.jsxs("div",{ref:ie,style:ce&&k!=null?{height:k}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${ce?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(aa,{className:"w-4 h-4"}),s("modelViewer.plates"),b&&a.jsx(dt,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:ce?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:K,className:ce?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:O,className:ce?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:ce?{gridTemplateColumns:`repeat(${I}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>P(null),className:`flex items-center rounded-lg border text-left transition-colors ${ce?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ce?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(aa,{className:`${ce?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ce?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${ce?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:W.length})})]}),C==null&&a.jsx(Rr,{className:`${ce?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),J.map(pe=>a.jsxs("button",{type:"button",onClick:()=>P(pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${ce?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C===pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[pe.has_thumbnail&&pe.thumbnail_url?a.jsx("img",{src:pe.thumbnail_url,alt:`Plate ${pe.index}`,className:`${ce?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ce?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(aa,{className:`${ce?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ce?"text-xs":"text-sm"} text-white font-medium truncate`,children:pe.name||s("modelViewer.plateNumber",{number:pe.index})}),a.jsx("p",{className:`${ce?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:pe.object_count??pe.objects?.length??0})})]}),C===pe.index&&a.jsx(Rr,{className:`${ce?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},pe.index))]})}),(xe||Q)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[xe&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:xe.index})}),xe.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(xe.print_time_seconds/60)})}),xe.filament_used_grams!=null&&a.jsxs("span",{children:[xe.filament_used_grams.toFixed(1)," g"]}),xe.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:xe.filaments.length})})]}),Q&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${xe?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:N+1,total:G})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.max(pe-1,0)),disabled:N===0,className:`px-2 py-1 rounded border text-xs ${N===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 de=Math.max(0,N-Math.floor(2.5));const U=Math.min(G,de+5);U-de<5&&(de=Math.max(0,U-5));const R=Array.from({length:U-de},(ae,_e)=>de+_e);return a.jsxs(a.Fragment,{children:[de>0&&a.jsx("button",{type:"button",onClick:()=>A(0),className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),de>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(ae=>a.jsx("button",{type:"button",onClick:()=>A(ae),className:`px-2 py-1 rounded border text-xs ${N===ae?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ae+1},ae)),U<G-1&&a.jsx("span",{className:"px-1",children:"…"}),U<G&&a.jsx("button",{type:"button",onClick:()=>A(G-1),className:`px-2 py-1 rounded border text-xs ${N===G-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:G})]})})(),a.jsx("button",{type:"button",onClick:()=>A(pe=>Math.min(pe+1,G-1)),disabled:N>=G-1,className:`px-2 py-1 rounded border text-xs ${N>=G-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")})]})]})]})]})]}),ce&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:pe=>{pe.preventDefault(),z(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${H?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${ce?"min-h-0":""}`,children:a.jsx(IZ,{url:c?me.getLibraryFileDownloadUrl(e):m.has_source?me.getSource3mfDownloadUrl(t):me.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:C,className:"w-full h-full"})})]}):d==="gcode"&&m?a.jsx(vJ,{gcodeUrl:c?me.getLibraryFileGcodeUrl(e):me.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function O7e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=sn(),{showToast:i}=bn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=it({mutationFn:N=>me.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(T=>{const F=N.results.find(D=>D.filename===T.file.name),k=N.errors.find(D=>D.filename===T.file.name);return F?{...T,status:"success",archiveId:F.id}:k?{...T,status:"error",error:k.error}:T})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),x=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const A=Array.from(N.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))])},[]),g=w.useCallback(N=>{const A=Array.from(N.target.files||[]).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),b=w.useCallback(N=>{l(A=>A.filter((T,F)=>F!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(A=>A.status==="pending");N.length!==0&&(l(A=>A.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(N.map(A=>A.file)))},C=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.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:f,onDragLeave:x,onDrop:v,children:[a.jsx(Ma,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Fe,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(AP,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>b(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Bt,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(dt,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(xr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(Wa,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${A}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Fe,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(Fe,{onClick:_,disabled:C===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ma,{className:"w-4 h-4"}),n("uploadModal.upload")," ",C>0&&`(${C})`]})})]})]})})})}const I7e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],z7e=["completed","failed","aborted","printing"];function Xae({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const j=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=sn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[b,_]=w.useState(t.status),[C,P]=w.useState(t.quantity??1),[N,A]=w.useState(t.photos||[]),[T,F]=w.useState(t.external_url||""),[k,D]=w.useState(!1),[H,z]=w.useState(!1),X=w.useRef(null),L=w.useRef(null),ne=w.useRef(null),{data:ie}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:ee}=Qe({queryKey:["projects"],queryFn:()=>me.getProjects()}),{data:ue}=Qe({queryKey:["tags"],queryFn:me.getTags,enabled:n.length===0}),le=n.length>0?n:ue?.map(j=>j.name)||[],oe=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),re=le.filter(j=>!oe.includes(j)&&(W===""||j.toLowerCase().includes(W))),ce=j=>{let O;if(W&&!le.includes(W)?O=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:O=oe,!O.includes(j)){const K=[...O,j].join(", ");x(K)}ne.current!==null&&clearTimeout(ne.current),X.current?.focus()},xe=j=>{const O=oe.filter(K=>K!==j).join(", ");x(O)},Ne=it({mutationFn:j=>me.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async j=>{const O=j.target.files?.[0];if(O){D(!0);try{const K=await me.uploadArchivePhoto(t.id,O);A(K.photos),i.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{D(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const O=await me.deleteArchivePhoto(t.id,j);A(O.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(O){console.error("Failed to delete photo:",O)}},E=j=>{j.preventDefault();const O={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:C,external_url:T||null};b!==t.status&&(O.status=b),b==="failed"||b==="aborted"?O.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(O.failure_reason=null),Ne.mutate(O)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.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:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",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 focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.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:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ie?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Es,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.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:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),ee?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Mge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:C,onChange:j=>P(Math.max(1,parseInt(j.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.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")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(ly,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:T,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 focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),oe.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(im,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>xe(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:X,type:"text",value:f,onChange:j=>x(j.target.value),onFocus:()=>{ne.current!==null&&clearTimeout(ne.current),z(!0)},onBlur:()=>{ne.current=window.setTimeout(()=>z(!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:oe.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),H&&re.length>0&&a.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:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?r("editArchive.matchingTags",{query:W}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:re.map(j=>a.jsx("button",{type:"button",onClick:()=>ce(j),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:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:b,onChange:j=>{_(j.target.value),j.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:z7e.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(b==="failed"||b==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>g(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:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),I7e.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Tx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(rn,{className:"w-3 h-3 text-white"})})]},j)),a.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:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:k}),k?a.jsx(dt,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(or,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Fe,{type:"submit",disabled:Ne.isPending,className:"flex-1",children:[a.jsx(gs,{className:"w-4 h-4"}),Ne.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Yae({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const g=C=>{i.current&&!i.current.contains(C.target)&&r()},b=C=>{C.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",b),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",b),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const g=i.current.getBoundingClientRect(),b=window.innerWidth,_=window.innerHeight,C=8;let P=t,N=e;t+g.width>b-C&&(P=Math.max(C,b-g.width-C)),P<C&&(P=C),e+g.height>_-C&&(N=Math.max(C,_-g.height-C)),N<C&&(N=C);const A=180,T=b-P-g.width,F=P;m(T<A&&F>A),d({x:P,y:N,visible:!0})}},[t,e]);const x=(g,b)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=b.getBoundingClientRect(),C=window.innerHeight,P=300,T=C-_.top-8<P&&_.top>P;f(F=>({...F,[g]:T?"bottom":"top"})),o(g)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,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,b)=>{if(g.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},b);const _=g.submenu&&g.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:C=>_&&x(b,C.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:C=>_&&x(b,C.currentTarget.parentElement),onClick:()=>{_?o(s===b?null:b):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===b?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),a.jsx("span",{className:"flex-1",children:g.label}),_&&a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===b&&a.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] ${u?"right-full mr-1":"left-full ml-1"} ${p[b]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((C,P)=>a.jsxs("button",{onClick:()=>{C.disabled||(C.onClick(),r())},disabled:C.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${C.disabled?"text-bambu-gray cursor-not-allowed":C.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[C.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:C.icon}),C.label]},P))})]},b)})})}function U7e({selectedIds:t,existingTags:e,onClose:n}){const r=sn(),{showToast:i}=bn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=it({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const b of t)try{const _=await me.getArchive(b),C=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...C,...v])]:P=C.filter(N=>!l.has(N)),await me.updateArchive(b,{tags:P.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${b}:`,_),new Error(`Failed on archive ${b}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:b})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${b.length} tag${b.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(g=>{const b=new Set(g);return b.has(v)?b.delete(v):b.add(v),b})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(im,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(Fe,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.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}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(or,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(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&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Bt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Fe,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Fe,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(im,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function B7e({selectedIds:t,onClose:e}){const n=sn(),{showToast:r}=bn(),{data:i,isLoading:s}=Qe({queryKey:["projects"],queryFn:()=>me.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=it({mutationFn:async u=>(await me.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=it({mutationFn:async()=>{for(const u of t)await me.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Es,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,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:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Na,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(dt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,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:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(Es,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(dt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Fe,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function H7e(t,e){return new Date(t,e+1,0).getDate()}function q7e(t,e){return new Date(t,e,1).getDay()}const $7e=["January","February","March","April","May","June","July","August","September","October","November","December"],V7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function G7e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(A=>{const T=er(A.completed_at||A.created_at)||new Date,F=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,k=N.get(F)||[];k.push(A),N.set(F,k)}),N},[t]),f=H7e(o,i),x=q7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},b=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N<x;N++)_.push(null);for(let N=1;N<=f;N++)_.push(N);const C=c?p.get(c)||[]:[],P=N=>{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(dl,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[$7e[i]," ",o]}),a.jsx("button",{onClick:b,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"})]}),a.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ka,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:V7e.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,A)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,F=p.get(T)||[],k=F.length>0,D=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),H=T===c,z=F.filter(L=>L.status==="completed").length,X=F.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P(H?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":D?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":k?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${D&&!H?"text-bambu-green":""}`,children:N}),k&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${X>0&&z===0?"bg-red-400":X>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const A=er(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const A=er(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const A=er(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.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"})}),C.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:C.map(N=>{const A=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:me.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,F)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},F))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Qae({archiveId:t,archiveName:e,onClose:n}){const r=me.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Fe,{onClick:i,className:"w-full",children:[a.jsx(ca,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Zae({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=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",f),()=>window.removeEventListener("keydown",f)},[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 d=n[s],u=me.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(ca,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Fe,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(rn,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(dl,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),s<n.length-1&&a.jsx("button",{onClick:()=>o(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Ka,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,x)=>a.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:a.jsx("img",{src:me.getArchivePhotoUrl(t,f),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(_n,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}const{entries:Jae,setPrototypeOf:sK,isFrozen:W7e,getPrototypeOf:K7e,getOwnPropertyDescriptor:X7e}=Object;let{freeze:ao,seal:uc,create:Bk}=Object,{apply:cL,construct:dL}=typeof Reflect<"u"&&Reflect;ao||(ao=function(e){return e});uc||(uc=function(e){return e});cL||(cL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s<r;s++)i[s-2]=arguments[s];return e.apply(n,i)});dL||(dL=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});const ek=io(Array.prototype.forEach),Y7e=io(Array.prototype.lastIndexOf),oK=io(Array.prototype.pop),Iv=io(Array.prototype.push),Q7e=io(Array.prototype.splice),Hk=io(String.prototype.toLowerCase),PD=io(String.prototype.toString),TD=io(String.prototype.match),zv=io(String.prototype.replace),Z7e=io(String.prototype.indexOf),J7e=io(String.prototype.trim),Qo=io(Object.prototype.hasOwnProperty),$s=io(RegExp.prototype.test),Uv=eGe(TypeError);function io(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return cL(t,e,r)}}function eGe(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return dL(t,n)}}function dr(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hk;sK&&sK(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(W7e(e)||(e[r]=s),i=s)}t[i]=!0}return t}function tGe(t){for(let e=0;e<t.length;e++)Qo(t,e)||(t[e]=null);return t}function dd(t){const e=Bk(null);for(const[n,r]of Jae(t))Qo(t,n)&&(Array.isArray(r)?e[n]=tGe(r):r&&typeof r=="object"&&r.constructor===Object?e[n]=dd(r):e[n]=r);return e}function Bv(t,e){for(;t!==null;){const r=X7e(t,e);if(r){if(r.get)return io(r.get);if(typeof r.value=="function")return io(r.value)}t=K7e(t)}function n(){return null}return n}const lK=ao(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),AD=ao(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),jD=ao(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),nGe=ao(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),MD=ao(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),rGe=ao(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),cK=ao(["#text"]),dK=ao(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),ED=ao(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),uK=ao(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),tk=ao(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),aGe=uc(/\{\{[\w\W]*|[\w\W]*\}\}/gm),iGe=uc(/<%[\w\W]*|[\w\W]*%>/gm),sGe=uc(/\$\{[\w\W]*/gm),oGe=uc(/^data-[\-\w.\u00B7-\uFFFF]+$/),lGe=uc(/^aria-[\-\w]+$/),eie=uc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),cGe=uc(/^(?:\w+script|data):/i),dGe=uc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),tie=uc(/^html$/i),uGe=uc(/^[a-z][.\w]*(-[.\w]+)+$/i);var mK=Object.freeze({__proto__:null,ARIA_ATTR:lGe,ATTR_WHITESPACE:dGe,CUSTOM_ELEMENT:uGe,DATA_ATTR:oGe,DOCTYPE_NAME:tie,ERB_EXPR:iGe,IS_ALLOWED_URI:eie,IS_SCRIPT_OR_DATA:cGe,MUSTACHE_EXPR:aGe,TMPLIT_EXPR:sGe});const Hv={element:1,text:3,progressingInstruction:7,comment:8,document:9},mGe=function(){return typeof window>"u"?null:window},hGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},hK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function nie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:mGe();const e=rt=>nie(rt);if(e.version="3.3.3",e.removed=[],!t||!t.document||t.document.nodeType!==Hv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,x=c.prototype,v=Bv(x,"cloneNode"),g=Bv(x,"remove"),b=Bv(x,"nextSibling"),_=Bv(x,"childNodes"),C=Bv(x,"parentNode");if(typeof o=="function"){const rt=n.createElement("template");rt.content&&rt.content.ownerDocument&&(n=rt.content.ownerDocument)}let P,N="";const{implementation:A,createNodeIterator:T,createDocumentFragment:F,getElementsByTagName:k}=n,{importNode:D}=r;let H=hK();e.isSupported=typeof Jae=="function"&&typeof C=="function"&&A&&A.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:X,TMPLIT_EXPR:L,DATA_ATTR:ne,ARIA_ATTR:ie,IS_SCRIPT_OR_DATA:ee,ATTR_WHITESPACE:ue,CUSTOM_ELEMENT:le}=mK;let{IS_ALLOWED_URI:oe}=mK,W=null;const re=dr({},[...lK,...AD,...jD,...MD,...cK]);let ce=null;const xe=dr({},[...dK,...ED,...uK,...tk]);let Ne=Object.seal(Bk(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),$=null,Y=null;const E=Object.seal(Bk(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,O=!0,K=!1,B=!0,he=!1,I=!0,V=!1,Q=!1,G=!1,J=!1,se=!1,fe=!1,pe=!0,de=!1;const U="user-content-";let R=!0,ae=!1,_e={},Se=null;const ye=dr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ae=null;const ve=dr({},["audio","video","img","source","image","track"]);let je=null;const Re=dr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ee="http://www.w3.org/1998/Math/MathML",Te="http://www.w3.org/2000/svg",Me="http://www.w3.org/1999/xhtml";let Be=Me,Ke=!1,tt=null;const te=dr({},[Ee,Te,Me],PD);let Ie=dr({},["mi","mo","mn","ms","mtext"]),be=dr({},["annotation-xml"]);const $e=dr({},["title","style","font","a","script"]);let He=null;const ge=["application/xhtml+xml","text/html"],Pe="text/html";let qe=null,Ze=null;const ut=n.createElement("form"),vt=function(Le){return Le instanceof RegExp||Le instanceof Function},wt=function(){let Le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ze&&Ze===Le)){if((!Le||typeof Le!="object")&&(Le={}),Le=dd(Le),He=ge.indexOf(Le.PARSER_MEDIA_TYPE)===-1?Pe:Le.PARSER_MEDIA_TYPE,qe=He==="application/xhtml+xml"?PD:Hk,W=Qo(Le,"ALLOWED_TAGS")?dr({},Le.ALLOWED_TAGS,qe):re,ce=Qo(Le,"ALLOWED_ATTR")?dr({},Le.ALLOWED_ATTR,qe):xe,tt=Qo(Le,"ALLOWED_NAMESPACES")?dr({},Le.ALLOWED_NAMESPACES,PD):te,je=Qo(Le,"ADD_URI_SAFE_ATTR")?dr(dd(Re),Le.ADD_URI_SAFE_ATTR,qe):Re,Ae=Qo(Le,"ADD_DATA_URI_TAGS")?dr(dd(ve),Le.ADD_DATA_URI_TAGS,qe):ve,Se=Qo(Le,"FORBID_CONTENTS")?dr({},Le.FORBID_CONTENTS,qe):ye,$=Qo(Le,"FORBID_TAGS")?dr({},Le.FORBID_TAGS,qe):dd({}),Y=Qo(Le,"FORBID_ATTR")?dr({},Le.FORBID_ATTR,qe):dd({}),_e=Qo(Le,"USE_PROFILES")?Le.USE_PROFILES:!1,j=Le.ALLOW_ARIA_ATTR!==!1,O=Le.ALLOW_DATA_ATTR!==!1,K=Le.ALLOW_UNKNOWN_PROTOCOLS||!1,B=Le.ALLOW_SELF_CLOSE_IN_ATTR!==!1,he=Le.SAFE_FOR_TEMPLATES||!1,I=Le.SAFE_FOR_XML!==!1,V=Le.WHOLE_DOCUMENT||!1,J=Le.RETURN_DOM||!1,se=Le.RETURN_DOM_FRAGMENT||!1,fe=Le.RETURN_TRUSTED_TYPE||!1,G=Le.FORCE_BODY||!1,pe=Le.SANITIZE_DOM!==!1,de=Le.SANITIZE_NAMED_PROPS||!1,R=Le.KEEP_CONTENT!==!1,ae=Le.IN_PLACE||!1,oe=Le.ALLOWED_URI_REGEXP||eie,Be=Le.NAMESPACE||Me,Ie=Le.MATHML_TEXT_INTEGRATION_POINTS||Ie,be=Le.HTML_INTEGRATION_POINTS||be,Ne=Le.CUSTOM_ELEMENT_HANDLING||{},Le.CUSTOM_ELEMENT_HANDLING&&vt(Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ne.tagNameCheck=Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&vt(Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ne.attributeNameCheck=Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&typeof Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ne.allowCustomizedBuiltInElements=Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),he&&(O=!1),se&&(J=!0),_e&&(W=dr({},cK),ce=Bk(null),_e.html===!0&&(dr(W,lK),dr(ce,dK)),_e.svg===!0&&(dr(W,AD),dr(ce,ED),dr(ce,tk)),_e.svgFilters===!0&&(dr(W,jD),dr(ce,ED),dr(ce,tk)),_e.mathMl===!0&&(dr(W,MD),dr(ce,uK),dr(ce,tk))),Qo(Le,"ADD_TAGS")||(E.tagCheck=null),Qo(Le,"ADD_ATTR")||(E.attributeCheck=null),Le.ADD_TAGS&&(typeof Le.ADD_TAGS=="function"?E.tagCheck=Le.ADD_TAGS:(W===re&&(W=dd(W)),dr(W,Le.ADD_TAGS,qe))),Le.ADD_ATTR&&(typeof Le.ADD_ATTR=="function"?E.attributeCheck=Le.ADD_ATTR:(ce===xe&&(ce=dd(ce)),dr(ce,Le.ADD_ATTR,qe))),Le.ADD_URI_SAFE_ATTR&&dr(je,Le.ADD_URI_SAFE_ATTR,qe),Le.FORBID_CONTENTS&&(Se===ye&&(Se=dd(Se)),dr(Se,Le.FORBID_CONTENTS,qe)),Le.ADD_FORBID_CONTENTS&&(Se===ye&&(Se=dd(Se)),dr(Se,Le.ADD_FORBID_CONTENTS,qe)),R&&(W["#text"]=!0),V&&dr(W,["html","head","body"]),W.table&&(dr(W,["tbody"]),delete $.tbody),Le.TRUSTED_TYPES_POLICY){if(typeof Le.TRUSTED_TYPES_POLICY.createHTML!="function")throw Uv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Le.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Uv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Le.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=hGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));ao&&ao(Le),Ze=Le}},$t=dr({},[...AD,...jD,...nGe]),Qt=dr({},[...MD,...rGe]),en=function(Le){let Oe=C(Le);(!Oe||!Oe.tagName)&&(Oe={namespaceURI:Be,tagName:"template"});const Ce=Hk(Le.tagName),We=Hk(Oe.tagName);return tt[Le.namespaceURI]?Le.namespaceURI===Te?Oe.namespaceURI===Me?Ce==="svg":Oe.namespaceURI===Ee?Ce==="svg"&&(We==="annotation-xml"||Ie[We]):!!$t[Ce]:Le.namespaceURI===Ee?Oe.namespaceURI===Me?Ce==="math":Oe.namespaceURI===Te?Ce==="math"&&be[We]:!!Qt[Ce]:Le.namespaceURI===Me?Oe.namespaceURI===Te&&!be[We]||Oe.namespaceURI===Ee&&!Ie[We]?!1:!Qt[Ce]&&($e[Ce]||!$t[Ce]):!!(He==="application/xhtml+xml"&&tt[Le.namespaceURI]):!1},Xt=function(Le){Iv(e.removed,{element:Le});try{C(Le).removeChild(Le)}catch{g(Le)}},tn=function(Le,Oe){try{Iv(e.removed,{attribute:Oe.getAttributeNode(Le),from:Oe})}catch{Iv(e.removed,{attribute:null,from:Oe})}if(Oe.removeAttribute(Le),Le==="is")if(J||se)try{Xt(Oe)}catch{}else try{Oe.setAttribute(Le,"")}catch{}},Ge=function(Le){let Oe=null,Ce=null;if(G)Le="<remove></remove>"+Le;else{const Xe=TD(Le,/^[\r\n\t ]+/);Ce=Xe&&Xe[0]}He==="application/xhtml+xml"&&Be===Me&&(Le='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Le+"</body></html>");const We=P?P.createHTML(Le):Le;if(Be===Me)try{Oe=new p().parseFromString(We,He)}catch{}if(!Oe||!Oe.documentElement){Oe=A.createDocument(Be,"template",null);try{Oe.documentElement.innerHTML=Ke?N:We}catch{}}const Je=Oe.body||Oe.documentElement;return Le&&Ce&&Je.insertBefore(n.createTextNode(Ce),Je.childNodes[0]||null),Be===Me?k.call(Oe,V?"html":"body")[0]:V?Oe.documentElement:Je},Ft=function(Le){return T.call(Le.ownerDocument||Le,Le,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Yt=function(Le){return Le instanceof m&&(typeof Le.nodeName!="string"||typeof Le.textContent!="string"||typeof Le.removeChild!="function"||!(Le.attributes instanceof u)||typeof Le.removeAttribute!="function"||typeof Le.setAttribute!="function"||typeof Le.namespaceURI!="string"||typeof Le.insertBefore!="function"||typeof Le.hasChildNodes!="function")},Pt=function(Le){return typeof l=="function"&&Le instanceof l};function pt(rt,Le,Oe){ek(rt,Ce=>{Ce.call(e,Le,Oe,Ze)})}const Wt=function(Le){let Oe=null;if(pt(H.beforeSanitizeElements,Le,null),Yt(Le))return Xt(Le),!0;const Ce=qe(Le.nodeName);if(pt(H.uponSanitizeElement,Le,{tagName:Ce,allowedTags:W}),I&&Le.hasChildNodes()&&!Pt(Le.firstElementChild)&&$s(/<[/\w!]/g,Le.innerHTML)&&$s(/<[/\w!]/g,Le.textContent)||Le.nodeType===Hv.progressingInstruction||I&&Le.nodeType===Hv.comment&&$s(/<[/\w]/g,Le.data))return Xt(Le),!0;if(!(E.tagCheck instanceof Function&&E.tagCheck(Ce))&&(!W[Ce]||$[Ce])){if(!$[Ce]&&ze(Ce)&&(Ne.tagNameCheck instanceof RegExp&&$s(Ne.tagNameCheck,Ce)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Ce)))return!1;if(R&&!Se[Ce]){const We=C(Le)||Le.parentNode,Je=_(Le)||Le.childNodes;if(Je&&We){const Xe=Je.length;for(let Ye=Xe-1;Ye>=0;--Ye){const St=v(Je[Ye],!0);St.__removalCount=(Le.__removalCount||0)+1,We.insertBefore(St,b(Le))}}}return Xt(Le),!0}return Le instanceof c&&!en(Le)||(Ce==="noscript"||Ce==="noembed"||Ce==="noframes")&&$s(/<\/no(script|embed|frames)/i,Le.innerHTML)?(Xt(Le),!0):(he&&Le.nodeType===Hv.text&&(Oe=Le.textContent,ek([z,X,L],We=>{Oe=zv(Oe,We," ")}),Le.textContent!==Oe&&(Iv(e.removed,{element:Le.cloneNode()}),Le.textContent=Oe)),pt(H.afterSanitizeElements,Le,null),!1)},Ut=function(Le,Oe,Ce){if(Y[Oe]||pe&&(Oe==="id"||Oe==="name")&&(Ce in n||Ce in ut))return!1;if(!(O&&!Y[Oe]&&$s(ne,Oe))){if(!(j&&$s(ie,Oe))){if(!(E.attributeCheck instanceof Function&&E.attributeCheck(Oe,Le))){if(!ce[Oe]||Y[Oe]){if(!(ze(Le)&&(Ne.tagNameCheck instanceof RegExp&&$s(Ne.tagNameCheck,Le)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Le))&&(Ne.attributeNameCheck instanceof RegExp&&$s(Ne.attributeNameCheck,Oe)||Ne.attributeNameCheck instanceof Function&&Ne.attributeNameCheck(Oe,Le))||Oe==="is"&&Ne.allowCustomizedBuiltInElements&&(Ne.tagNameCheck instanceof RegExp&&$s(Ne.tagNameCheck,Ce)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Ce))))return!1}else if(!je[Oe]){if(!$s(oe,zv(Ce,ue,""))){if(!((Oe==="src"||Oe==="xlink:href"||Oe==="href")&&Le!=="script"&&Z7e(Ce,"data:")===0&&Ae[Le])){if(!(K&&!$s(ee,zv(Ce,ue,"")))){if(Ce)return!1}}}}}}}return!0},ze=function(Le){return Le!=="annotation-xml"&&TD(Le,le)},st=function(Le){pt(H.beforeSanitizeAttributes,Le,null);const{attributes:Oe}=Le;if(!Oe||Yt(Le))return;const Ce={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0};let We=Oe.length;for(;We--;){const Je=Oe[We],{name:Xe,namespaceURI:Ye,value:St}=Je,et=qe(Xe),jt=St;let bt=Xe==="value"?jt:J7e(jt);if(Ce.attrName=et,Ce.attrValue=bt,Ce.keepAttr=!0,Ce.forceKeepAttr=void 0,pt(H.uponSanitizeAttribute,Le,Ce),bt=Ce.attrValue,de&&(et==="id"||et==="name")&&(tn(Xe,Le),bt=U+bt),I&&$s(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,bt)){tn(Xe,Le);continue}if(et==="attributename"&&TD(bt,"href")){tn(Xe,Le);continue}if(Ce.forceKeepAttr)continue;if(!Ce.keepAttr){tn(Xe,Le);continue}if(!B&&$s(/\/>/i,bt)){tn(Xe,Le);continue}he&&ek([z,X,L],gt=>{bt=zv(bt,gt," ")});const Ve=qe(Le.nodeName);if(!Ut(Ve,et,bt)){tn(Xe,Le);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ye)switch(f.getAttributeType(Ve,et)){case"TrustedHTML":{bt=P.createHTML(bt);break}case"TrustedScriptURL":{bt=P.createScriptURL(bt);break}}if(bt!==jt)try{Ye?Le.setAttributeNS(Ye,Xe,bt):Le.setAttribute(Xe,bt),Yt(Le)?Xt(Le):oK(e.removed)}catch{tn(Xe,Le)}}pt(H.afterSanitizeAttributes,Le,null)},ht=function rt(Le){let Oe=null;const Ce=Ft(Le);for(pt(H.beforeSanitizeShadowDOM,Le,null);Oe=Ce.nextNode();)pt(H.uponSanitizeShadowNode,Oe,null),Wt(Oe),st(Oe),Oe.content instanceof s&&rt(Oe.content);pt(H.afterSanitizeShadowDOM,Le,null)};return e.sanitize=function(rt){let Le=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Oe=null,Ce=null,We=null,Je=null;if(Ke=!rt,Ke&&(rt="<!-->"),typeof rt!="string"&&!Pt(rt))if(typeof rt.toString=="function"){if(rt=rt.toString(),typeof rt!="string")throw Uv("dirty is not a string, aborting")}else throw Uv("toString is not a function");if(!e.isSupported)return rt;if(Q||wt(Le),e.removed=[],typeof rt=="string"&&(ae=!1),ae){if(rt.nodeName){const St=qe(rt.nodeName);if(!W[St]||$[St])throw Uv("root node is forbidden and cannot be sanitized in-place")}}else if(rt instanceof l)Oe=Ge("<!---->"),Ce=Oe.ownerDocument.importNode(rt,!0),Ce.nodeType===Hv.element&&Ce.nodeName==="BODY"||Ce.nodeName==="HTML"?Oe=Ce:Oe.appendChild(Ce);else{if(!J&&!he&&!V&&rt.indexOf("<")===-1)return P&&fe?P.createHTML(rt):rt;if(Oe=Ge(rt),!Oe)return J?null:fe?N:""}Oe&&G&&Xt(Oe.firstChild);const Xe=Ft(ae?rt:Oe);for(;We=Xe.nextNode();)Wt(We),st(We),We.content instanceof s&&ht(We.content);if(ae)return rt;if(J){if(se)for(Je=F.call(Oe.ownerDocument);Oe.firstChild;)Je.appendChild(Oe.firstChild);else Je=Oe;return(ce.shadowroot||ce.shadowrootmode)&&(Je=D.call(r,Je,!0)),Je}let Ye=V?Oe.outerHTML:Oe.innerHTML;return V&&W["!doctype"]&&Oe.ownerDocument&&Oe.ownerDocument.doctype&&Oe.ownerDocument.doctype.name&&$s(tie,Oe.ownerDocument.doctype.name)&&(Ye="<!DOCTYPE "+Oe.ownerDocument.doctype.name+`>
- `+Ye),he&&ek([z,X,L],St=>{Ye=zv(Ye,St," ")}),P&&fe?P.createHTML(Ye):Ye},e.setConfig=function(){let rt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wt(rt),Q=!0},e.clearConfig=function(){Ze=null,Q=!1},e.isValidAttribute=function(rt,Le,Oe){Ze||wt({});const Ce=qe(rt),We=qe(Le);return Ut(Ce,We,Oe)},e.addHook=function(rt,Le){typeof Le=="function"&&Iv(H[rt],Le)},e.removeHook=function(rt,Le){if(Le!==void 0){const Oe=Y7e(H[rt],Le);return Oe===-1?void 0:Q7e(H[rt],Oe,1)[0]}return oK(H[rt])},e.removeHooks=function(rt){H[rt]=[]},e.removeAllHooks=function(){H=hK()},e}var rie=nie();function ss(t){this.content=t}ss.prototype={constructor:ss,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,i=r.find(t),s=r.content.slice();return i==-1?s.push(n||t,e):(s[i+1]=e,n&&(s[i]=n)),new ss(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 ss(n)},addToStart:function(t,e){return new ss([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new ss(n)},addBefore:function(t,e,n){var r=this.remove(e),i=r.content.slice(),s=r.find(t);return i.splice(s==-1?i.length:s,0,e,n),new ss(i)},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=ss.from(t),t.size?new ss(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=ss.from(t),t.size?new ss(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=ss.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}};ss.from=function(t){if(t instanceof ss)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new ss(e)};function aie(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=aie(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function iie(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),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 d=0,u=Math.min(o.text.length,l.text.length);for(;d<u&&o.text[o.text.length-d-1]==l.text[l.text.length-d-1];)d++,n--,r--;return{a:n,b:r}}if(o.content.size||l.content.size){let d=iie(o.content,l.content,n-1,r-1);if(d)return d}n-=c,r-=c}}class Vt{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,i=0,s){for(let o=0,l=0;l<n;o++){let c=this.content[o],d=l+c.nodeSize;if(d>e&&r(c,i+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)i.push(e.content[s]);return new Vt(i,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let r=[],i=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),i+=l.nodeSize),o=c}return new Vt(r,i)}cutByIndex(e,n){return e==n?Vt.empty:e==0&&n==this.content.length?this:new Vt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new Vt(i,s)}addToStart(e){return new Vt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Vt(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 i=this.content[n];e(i,r,n),r+=i.nodeSize}}findDiffStart(e,n=0){return aie(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return iie(this,e,n,r)}findIndex(e){if(e==0)return nk(0,e);if(e==this.size)return nk(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 i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?nk(n+1,s):nk(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 Vt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Vt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Vt.empty;let n,r=0;for(let i=0;i<e.length;i++){let s=e[i];r+=s.nodeSize,i&&s.isText&&e[i-1].sameMarkup(s)?(n||(n=e.slice(0,i)),n[n.length-1]=s.withText(n[n.length-1].text+s.text)):n&&n.push(s)}return new Vt(n||e,r)}static from(e){if(!e)return Vt.empty;if(e instanceof Vt)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Vt([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}Vt.empty=new Vt([],0);const DD={index:0,offset:0};function nk(t,e){return DD.index=t,DD.offset=e,DD}function PC(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(!PC(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!PC(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let ta=class uL{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,r=!1;for(let i=0;i<e.length;i++){let s=e[i];if(this.eq(s))return e;if(this.type.excludes(s.type))n||(n=e.slice(0,i));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,i)),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&&PC(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 i=r.create(n.attrs);return r.checkAttrs(i.attrs),i}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 uL.none;if(e instanceof uL)return[e];let n=e.slice();return n.sort((r,i)=>r.type.rank-i.type.rank),n}};ta.none=[];class TC extends Error{}class cn{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=oie(this.content,e+this.openStart,n);return r&&new cn(r,this.openStart,this.openEnd)}removeBetween(e,n){return new cn(sie(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 cn.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new cn(Vt.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=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)i++;return new cn(e,r,i)}}cn.empty=new cn(Vt.empty,0,0);function sie(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==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(sie(s.content,e-i-1,n-i-1)))}function oie(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=oie(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function pGe(t,e,n){if(n.openStart>t.depth)throw new TC("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new TC("Inconsistent open depths");return lie(t,e,n,0)}function lie(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r<t.depth-n.openStart){let o=lie(t,e,n,r+1);return s.copy(s.content.replaceChild(i,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 Uf(o,l.cut(0,t.parentOffset).append(n.content).append(l.cut(e.parentOffset)))}else{let{start:o,end:l}=fGe(n,t);return Uf(s,die(t,o,l,e,r))}else return Uf(s,AC(t,e,r))}function cie(t,e){if(!e.type.compatibleContent(t.type))throw new TC("Cannot join "+e.type.name+" onto "+t.type.name)}function mL(t,e,n){let r=t.node(n);return cie(r,e.node(n)),r}function zf(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 v0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(zf(t.nodeAfter,r),s++));for(let l=s;l<o;l++)zf(i.child(l),r);e&&e.depth==n&&e.textOffset&&zf(e.nodeBefore,r)}function Uf(t,e){return t.type.checkContent(e),t.copy(e)}function die(t,e,n,r,i){let s=t.depth>i&&mL(t,e,i+1),o=r.depth>i&&mL(n,r,i+1),l=[];return v0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(cie(s,o),zf(Uf(s,die(t,e,n,r,i+1)),l)):(s&&zf(Uf(s,AC(t,e,i+1)),l),v0(e,n,i,l),o&&zf(Uf(o,AC(n,r,i+1)),l)),v0(r,null,i,l),new Vt(l)}function AC(t,e,n){let r=[];if(v0(null,t,n,r),t.depth>n){let i=mL(t,e,n+1);zf(Uf(i,AC(t,e,n+1)),r)}return v0(e,null,n,r),new Vt(r)}function fGe(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy(Vt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class gw{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],i=e.child(n);return r?e.child(n).cut(r):i}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],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)i+=r.child(s).nodeSize;return i}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return ta.none;if(this.textOffset)return e.child(n).marks;let r=e.maybeChild(n-1),i=e.maybeChild(n);if(!r){let l=r;r=i,i=l}let s=r.marks;for(var o=0;o<s.length;o++)s[o].type.spec.inclusive===!1&&(!i||!s[o].isInSet(i.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,i=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!i||!r[s].isInSet(i.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 jC(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=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new gw(n,r,s)}static resolveCached(e,n){let r=pK.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 pK.set(e,r=new gGe);let i=r.elts[r.i]=gw.resolve(e,n);return r.i=(r.i+1)%bGe,i}}class gGe{constructor(){this.elts=[],this.i=0}}const bGe=12,pK=new WeakMap;class jC{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 xGe=Object.create(null);class zc{constructor(e,n,r,i=ta.none){this.type=e,this.attrs=n,this.marks=i,this.content=r||Vt.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,i=0){this.content.nodesBetween(e,n,r,i,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,i){return this.content.textBetween(e,n,r,i)}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&&PC(this.attrs,n||e.defaultAttrs||xGe)&&ta.sameSet(this.marks,r||ta.none)}copy(e=null){return e==this.content?this:new zc(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new zc(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 cn.empty;let i=this.resolve(e),s=this.resolve(n),o=r?0:i.sharedDepth(n),l=i.start(o),d=i.node(o).content.cut(i.pos-l,s.pos-l);return new cn(d,i.depth-o,s.depth-o)}replace(e,n,r){return pGe(this.resolve(e),this.resolve(n),r)}nodeAt(e){for(let n=this;;){let{index:r,offset:i}=n.content.findIndex(e);if(n=n.maybeChild(r),!n)return null;if(i==e||n.isText)return n;e-=i+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 i=this.content.child(n-1);return{node:i,index:n-1,offset:r-i.nodeSize}}resolve(e){return gw.resolveCached(this,e)}resolveNoCache(e){return gw.resolve(this,e)}rangeHasMark(e,n,r){let i=!1;return n>e&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}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()+")"),uie(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=Vt.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;c<s;c++)if(!this.type.allowsMarks(r.child(c).marks))return!1;return!0}canReplaceWith(e,n,r,i){if(i&&!this.type.allowsMarks(i))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=ta.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(!ta.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 i=Vt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}}zc.prototype.text=void 0;class MC extends zc{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):uie(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 MC(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new MC(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 uie(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class hg{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new yGe(e,n);if(r.next==null)return hg.empty;let i=mie(r);r.next&&r.err("Unexpected trailing text");let s=CGe(NGe(i));return PGe(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 i=this;for(let s=n;i&&s<r;s++)i=i.matchType(e.child(s).type);return i}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 i=[this];function s(o,l){let c=o.matchFragment(e,r);if(c&&(!n||c.validEnd))return Vt.from(l.map(d=>d.createAndFill()));for(let d=0;d<o.next.length;d++){let{type:u,next:m}=o.next[d];if(!(u.isText||u.hasRequiredAttrs())&&i.indexOf(m)==-1){i.push(m);let p=s(m,l.concat(u));if(p)return p}}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 i=r.shift(),s=i.match;if(s.matchType(e)){let o=[];for(let l=i;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)&&(!i.type||c.validEnd)&&(r.push({match:l.contentMatch,type:l,via:i}),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 i=0;i<r.next.length;i++)e.indexOf(r.next[i].next)==-1&&n(r.next[i].next)}return n(this),e.map((r,i)=>{let s=i+(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(`
- `)}}hg.empty=new hg(!0);class yGe{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 mie(t){let e=[];do e.push(vGe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function vGe(t){let e=[];do e.push(wGe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function wGe(t){let e=kGe(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=SGe(t,e);else break;return e}function fK(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function SGe(t,e){let n=fK(t),r=n;return t.eat(",")&&(t.next!="}"?r=fK(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function _Ge(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function kGe(t){if(t.eat("(")){let e=mie(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=_Ge(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 NGe(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;i(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(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 d=0;d<o.min;d++){let u=n();i(s(o.expr,c),u),c=u}if(o.max==-1)i(s(o.expr,c),c);else for(let d=o.min;d<o.max;d++){let u=n();r(c,u),i(s(o.expr,c),u),c=u}return[r(c)]}else{if(o.type=="name")return[r(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function hie(t,e){return e-t}function gK(t,e){let n=[];return r(e),n.sort(hie);function r(i){let s=t[i];if(s.length==1&&!s[0].term)return r(s[0].to);n.push(i);for(let o=0;o<s.length;o++){let{term:l,to:c}=s[o];!l&&n.indexOf(c)==-1&&r(c)}}}function CGe(t){let e=Object.create(null);return n(gK(t,0));function n(r){let i=[];r.forEach(o=>{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u<i.length;u++)i[u][0]==l&&(d=i[u][1]);gK(t,c).forEach(u=>{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[r.join(",")]=new hg(r.indexOf(t.length-1)>-1);for(let o=0;o<i.length;o++){let l=i[o][1].sort(hie);s.next.push({type:i[o][0],next:e[l.join(",")]||n(l)})}return s}}function PGe(t,e){for(let n=0,r=[t];n<r.length;n++){let i=r[n],s=!i.validEnd,o=[];for(let l=0;l<i.next.length;l++){let{type:c,next:d}=i.next[l];o.push(c.name),s&&!(c.isText||c.hasRequiredAttrs())&&(s=!1),r.indexOf(d)==-1&&r.push(d)}s&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function pie(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 fie(t,e){let n=Object.create(null);for(let r in t){let i=e&&e[r];if(i===void 0){let s=t[r];if(s.hasDefault)i=s.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=i}return n}function gie(t,e,n,r){for(let i in e)if(!(i in t))throw new RangeError(`Unsupported attribute ${i} for ${n} of type ${i}`);for(let i in t){let s=t[i];s.validate&&s.validate(e[i])}}function bie(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new AGe(t,r,e[r]);return n}let bK=class xie{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=bie(e,r.attrs),this.defaultAttrs=pie(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==hg.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:fie(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new zc(this,this.computeAttrs(e),Vt.from(n),ta.setFrom(r))}createChecked(e=null,n,r){return n=Vt.from(n),this.checkContent(n),new zc(this,this.computeAttrs(e),n,ta.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Vt.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),s=i&&i.fillBefore(Vt.empty,!0);return s?new zc(this,e,n.append(s),ta.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){gie(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:ta.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,o)=>r[s]=new xie(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");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 TGe(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class AGe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?TGe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class UT{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=bie(e,i.attrs),this.excluded=null;let s=pie(this.attrs);this.instance=s?new ta(this,s):null}create(e=null){return!e&&this.instance?this.instance:new ta(this,fie(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new UT(s,i++,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){gie(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class yie{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=ss.from(e.nodes),n.marks=ss.from(e.marks||{}),this.nodes=bK.compile(this.spec.nodes,this),this.marks=UT.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=hg.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?xK(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:xK(this,o.split(" "))}this.nodeFromJSON=i=>zc.fromJSON(this,i),this.markFromJSON=i=>ta.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof bK){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,i)}text(e,n){let r=this.nodes.text;return new MC(r,r.defaultAttrs,e,ta.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 xK(t,e){let n=[];for(let r=0;r<e.length;r++){let i=e[r],s=t.marks[i],o=s;if(s)n.push(s);else for(let l in t.marks){let c=t.marks[l];(i=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(i)>-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function jGe(t){return t.tag!=null}function MGe(t){return t.style!=null}let w0=class hL{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(jGe(i))this.tags.push(i);else if(MGe(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new vK(this,n,!1);return r.addAll(e,ta.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new vK(this,n,!0);return r.addAll(e,ta.none,n.from,n.to),cn.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;i<this.tags.length;i++){let s=this.tags[i];if(FGe(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,i){for(let s=i?this.styles.indexOf(i)+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(i){let s=i.priority==null?50:i.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,i)}for(let i in e.marks){let s=e.marks[i].spec.parseDOM;s&&s.forEach(o=>{r(o=wK(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=wK(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new hL(e,hL.schemaRules(e)))}};const vie={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},EGe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},wie={ol:!0,ul:!0},bw=1,pL=2,S0=4;function yK(t,e,n){return e!=null?(e?bw:0)|(e==="full"?pL:0):t&&t.whitespace=="pre"?bw|pL:n&~S0}class rk{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=ta.none,this.match=s||(o&S0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Vt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&bw)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=Vt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Vt.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&&!vie.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class vK{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=yK(null,n.preserveWhitespace,0)|(r?S0:0);i?s=new rk(i.type,i.attrs,ta.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new rk(null,null,ta.none,!0,null,o):s=new rk(e.schema.topNodeType,null,ta.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,i=this.top,s=i.options&pL?"full":this.localPreserveWS||(i.options&bw)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
- `);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=i.content[i.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 i=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let o=e.nodeName.toLowerCase(),l;wie.hasOwnProperty(o)&&this.parser.normalizeLists&&DGe(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(l=this.parser.matchTag(e,this,r));e:if(c?c.ignore:EGe.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 d,u=this.needsBlock;if(vie.hasOwnProperty(o))s.content.length&&s.content[0].isInline&&this.open&&(this.open--,s=this.top),d=!0,s.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,n);break e}let m=c&&c.skip?n:this.readStyles(e,n);m&&this.addAll(e,m),d&&this.sync(s),this.needsBlock=u}else{let d=this.readStyles(e,n);d&&this.addElementByRule(e,c,d,c.consuming===!1?l:void 0)}this.localPreserveWS=i}leafFallback(e,n){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
- `),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 i=0;i<this.parser.matchedStyles.length;i++){let s=this.parser.matchedStyles[i],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(d=>!c.clearMark(d)):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,i){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(i)this.addElement(e,r,i);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,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],d=c.findWrapping(e);if(d&&(!i||i.length>d.length+l)&&(i=d,s=c,!d.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o<i.length;o++)n=this.enterInner(i[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 i=this.findPlace(e,n,r);if(i){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let o=ta.none;for(let l of i.concat(e.marks))(s.type?s.type.allowsMarkType(l.type):SK(l.type,e.type))&&(o=l.addToSet(o));return s.content.push(e.mark(o)),!0}return!1}enter(e,n,r,i){let s=this.findPlace(e.create(n),r,!1);return s&&(s=this.enterInner(e,n,r,!0,i)),s}enterInner(e,n,r,i=!1,s){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(e);let l=yK(e,s,o.options);o.options&S0&&o.content.length==0&&(l|=S0);let c=ta.none;return r=r.filter(d=>(o.type?o.type.allowsMarkType(d.type):SK(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new rk(e,n,c,i,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|=bw)}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 i=r.length-1;i>=0;i--)e+=r[i].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 i=0;i<this.find.length;i++)this.find[i].pos==null&&e.nodeType==1&&e.contains(this.find[i].node)&&n.compareDocumentPosition(this.find[i].node)&(r?2:4)&&(this.find[i].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,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let d=n[l];if(d==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let u=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!u||u.name!=d&&!u.isInGroup(d))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 DGe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&wie.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function FGe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function wK(t){let e={};for(let n in t)e[n]=t[n];return e}function SK(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c<l.edgeCount;c++){let{type:d,next:u}=l.edge(c);if(d==e||s.indexOf(u)<0&&o(u))return!0}};if(o(i.contentMatch))return!0}}class Cg{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=FD(n).createDocumentFragment());let i=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 d=o.marks[c];if(!this.marks[d.type.name]){c++;continue}if(!d.eq(s[l][0])||d.type.spec.spanning===!1)break;l++,c++}for(;l<s.length;)i=s.pop()[1];for(;c<o.marks.length;){let d=o.marks[c++],u=this.serializeMark(d,o.isInline,n);u&&(s.push([d,i]),i.appendChild(u.dom),i=u.contentDOM||u.dom)}}i.appendChild(this.serializeNodeInner(o,n))}),r}serializeNodeInner(e,n){let{dom:r,contentDOM:i}=qk(FD(n),this.nodes[e.type.name](e),null,e.attrs);if(i){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,i)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let i=e.marks.length-1;i>=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&qk(FD(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return qk(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Cg(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=_K(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return _K(e.marks)}}function _K(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function FD(t){return t.document||window.document}const kK=new WeakMap;function RGe(t){let e=kK.get(t);return e===void 0&&kK.set(t,e=LGe(t)),e}function LGe(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 i=0;i<r.length;i++)n(r[i]);else for(let i in r)n(r[i])}return n(t),e}function qk(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 i=e[0],s;if(typeof i!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(s=RGe(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=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),d=e[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let m in d)if(d[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=u;m<e.length;m++){let p=e[m];if(p===0){if(m<e.length-1||m>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:x}=qk(t,p,n,r);if(c.appendChild(f),x){if(l)throw new RangeError("Multiple content holes");l=x}}}return{dom:c,contentDOM:l}}const Sie=65535,_ie=Math.pow(2,16);function OGe(t,e){return t+e*_ie}function NK(t){return t&Sie}function IGe(t){return(t-(t&Sie))/_ie}const kie=1,Nie=2,$k=4,Cie=8;class fL{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Cie)>0}get deletedBefore(){return(this.delInfo&(kie|$k))>0}get deletedAfter(){return(this.delInfo&(Nie|$k))>0}get deletedAcross(){return(this.delInfo&$k)>0}}class tl{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&tl.empty)return tl.empty}recover(e){let n=0,r=NK(e);if(!this.inverted)for(let i=0;i<r;i++)n+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[r*3]+n+IGe(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 i=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?i:0);if(c>e)break;let d=this.ranges[l+s],u=this.ranges[l+o],m=c+d;if(e<=m){let p=d?e==c?-1:e==m?1:n:n,f=c+i+(p<0?0:u);if(r)return f;let x=e==(n<0?c:m)?null:OGe(l/3,e-c),v=e==c?Nie:e==m?kie:$k;return(n<0?e!=c:e!=m)&&(v|=Cie),new fL(f,v,x)}i+=u-d}return r?e+i:new fL(e+i,0,null)}touches(e,n){let r=0,i=NK(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 d=this.ranges[l+s],u=c+d;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-d}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i<this.ranges.length;i+=3){let o=this.ranges[i],l=o-(this.inverted?s:0),c=o+(this.inverted?0:s),d=this.ranges[i+n],u=this.ranges[i+r];e(l,l+d,c,c+u),s+=u-d}}invert(){return new tl(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?tl.empty:new tl(e<0?[0,-e,0]:[0,0,e])}}tl.empty=new tl([]);class xw{constructor(e,n,r=0,i=e?e.length:0){this.mirror=n,this.from=r,this.to=i,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new xw(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 i=e.getMirror(n);this.appendMap(e._maps[n],i!=null&&i<n?r+i: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 i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new xw;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 i=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}}i|=l.delInfo,e=l.pos}return r?e:new fL(e,i,null)}}const RD=Object.create(null);class Is{getMap(){return tl.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=RD[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 RD)throw new RangeError("Duplicate use of step JSON ID "+e);return RD[e]=n,n.prototype.jsonID=e,n}}class pi{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new pi(e,null)}static fail(e){return new pi(null,e)}static fromReplace(e,n,r,i){try{return pi.ok(e.replace(n,r,i))}catch(s){if(s instanceof TC)return pi.fail(s.message);throw s}}}function dz(t,e,n){let r=[];for(let i=0;i<t.childCount;i++){let s=t.child(i);s.content.size&&(s=s.copy(dz(s.content,e,s))),s.isInline&&(s=e(s,n,i)),r.push(s)}return Vt.fromArray(r)}class Lh extends Is{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),i=r.node(r.sharedDepth(this.to)),s=new cn(dz(n.content,(o,l)=>!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),n.openStart,n.openEnd);return pi.fromReplace(e,this.from,this.to,s)}invert(){return new Oc(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 Lh(n.pos,r.pos,this.mark)}merge(e){return e instanceof Lh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Lh(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 Lh(n.from,n.to,e.markFromJSON(n.mark))}}Is.jsonID("addMark",Lh);class Oc extends Is{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 cn(dz(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return pi.fromReplace(e,this.from,this.to,r)}invert(){return new Lh(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 Oc(n.pos,r.pos,this.mark)}merge(e){return e instanceof Oc&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Oc(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 Oc(n.from,n.to,e.markFromJSON(n.mark))}}Is.jsonID("removeMark",Oc);class Oh extends Is{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return pi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return pi.fromReplace(e,this.pos,this.pos+1,new cn(Vt.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 i=0;i<n.marks.length;i++)if(!n.marks[i].isInSet(r))return new Oh(this.pos,n.marks[i]);return new Oh(this.pos,this.mark)}}return new pg(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Oh(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 Oh(n.pos,e.markFromJSON(n.mark))}}Is.jsonID("addNodeMark",Oh);class pg extends Is{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return pi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return pi.fromReplace(e,this.pos,this.pos+1,new cn(Vt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Oh(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new pg(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 pg(n.pos,e.markFromJSON(n.mark))}}Is.jsonID("removeNodeMark",pg);class Ui extends Is{constructor(e,n,r,i=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=i}apply(e){return this.structure&&gL(e,this.from,this.to)?pi.fail("Structure replace would overwrite content"):pi.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new tl([this.from,this.to-this.from,this.slice.size])}invert(e){return new Ui(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 Ui(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Ui)||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?cn.empty:new cn(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Ui(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?cn.empty:new cn(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Ui(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 Ui(n.from,n.to,cn.fromJSON(e,n.slice),!!n.structure)}}Is.jsonID("replace",Ui);class Hi extends Is{constructor(e,n,r,i,s,o,l=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=i,this.slice=s,this.insert=o,this.structure=l}apply(e){if(this.structure&&(gL(e,this.from,this.gapFrom)||gL(e,this.gapTo,this.to)))return pi.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return pi.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?pi.fromReplace(e,this.from,this.to,r):pi.fail("Content does not fit in gap")}getMap(){return new tl([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 Hi(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),i=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||i<n.pos||s>r.pos?null:new Hi(n.pos,r.pos,i,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 Hi(n.from,n.to,n.gapFrom,n.gapTo,cn.fromJSON(e,n.slice),n.insert,!!n.structure)}}Is.jsonID("replaceAround",Hi);function gL(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function zGe(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let m=c.marks;if(!r.isInSet(m)&&u.type.allowsMarkType(r.type)){let p=Math.max(d,e),f=Math.min(d+c.nodeSize,n),x=r.addToSet(m);for(let v=0;v<m.length;v++)m[v].isInSet(x)||(o&&o.to==p&&o.mark.eq(m[v])?o.to=f:i.push(o=new Oc(p,f,m[v])));l&&l.to==p?l.to=f:s.push(l=new Lh(p,f,r))}}),i.forEach(c=>t.step(c)),s.forEach(c=>t.step(c))}function UGe(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof UT){let d=o.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let d=Math.min(l+o.nodeSize,n);for(let u=0;u<c.length;u++){let m=c[u],p;for(let f=0;f<i.length;f++){let x=i[f];x.step==s-1&&m.eq(i[f].style)&&(p=x)}p?(p.to=d,p.step=s):i.push({style:m,from:Math.max(l,e),to:d,step:s})}}}),i.forEach(o=>t.step(new Oc(o.from,o.to,o.style)))}function uz(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c<s.childCount;c++){let d=s.child(c),u=l+d.nodeSize,m=r.matchType(d.type);if(!m)o.push(new Ui(l,u,cn.empty));else{r=m;for(let p=0;p<d.marks.length;p++)n.allowsMarkType(d.marks[p].type)||t.step(new Oc(l,u,d.marks[p]));if(i&&d.isText&&n.whitespace!="pre"){let p,f=/\r?\n|\r/g,x;for(;p=f.exec(d.text);)x||(x=new cn(Vt.from(n.schema.text(" ",n.allowedMarks(d.marks))),0,0)),o.push(new Ui(l+p.index,l+p.index+p[0].length,x))}}l=u}if(!r.validEnd){let c=r.fillBefore(Vt.empty,!0);t.replace(l,l,new cn(c,0,0))}for(let c=o.length-1;c>=0;c--)t.step(o[c])}function BGe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ny(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(r<t.depth&&o.canReplace(l,c,n))return r;if(r==0||o.type.spec.isolating||!BGe(o,l,c))break;l&&(i=1),c<o.childCount&&(s=1)}return null}function HGe(t,e,n){let{$from:r,$to:i,depth:s}=e,o=r.before(s+1),l=i.after(s+1),c=o,d=l,u=Vt.empty,m=0;for(let x=s,v=!1;x>n;x--)v||r.index(x)>0?(v=!0,u=Vt.from(r.node(x).copy(u)),m++):c--;let p=Vt.empty,f=0;for(let x=s,v=!1;x>n;x--)v||i.after(x+1)<i.end(x)?(v=!0,p=Vt.from(i.node(x).copy(p)),f++):d++;t.step(new Hi(c,d,o,l,new cn(u.append(p),m,f),u.size-m,!0))}function mz(t,e,n=null,r=t){let i=qGe(t,e),s=i&&$Ge(r,e);return s?i.map(CK).concat({type:e,attrs:n}).concat(s.map(CK)):null}function CK(t){return{type:t,attrs:null}}function qGe(t,e){let{parent:n,startIndex:r,endIndex:i}=t,s=n.contentMatchAt(r).findWrapping(e);if(!s)return null;let o=s.length?s[0]:e;return n.canReplaceWith(r,i,o)?s:null}function $Ge(t,e){let{parent:n,startIndex:r,endIndex:i}=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 d=r;c&&d<i;d++)c=c.matchType(n.child(d).type);return!c||!c.validEnd?null:o}function VGe(t,e,n){let r=Vt.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=Vt.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new Hi(i,s,i,s,new cn(r,0,0),n.length,!0))}function GGe(t,e,n,r,i){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 i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&WGe(t.doc,t.mapping.slice(s).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!x?d=!1:!f&&x&&(d=!0)}d===!1&&Tie(t,o,l,s),uz(t,t.mapping.slice(s).map(l,1),r,void 0,d===null);let u=t.mapping.slice(s),m=u.map(l,1),p=u.map(l+o.nodeSize,1);return t.step(new Hi(m,p,m+1,p-1,new cn(Vt.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&Pie(t,o,l,s),!1}})}function Pie(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Tie(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(`
- `))}})}function WGe(t,e,n){let r=t.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function KGe(t,e,n,r,i){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,i||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 Hi(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new cn(Vt.from(o),0,0),1,!0))}function em(t,e,n=1,r){let i=t.resolve(e),s=i.depth-n,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let d=i.depth-1,u=n-2;d>s;d--,u--){let m=i.node(d),p=i.index(d);if(m.type.spec.isolating)return!1;let f=m.content.cutByIndex(p,m.childCount),x=r&&r[u+1];x&&(f=f.replaceChild(0,x.type.create(x.attrs)));let v=r&&r[u]||m;if(!m.canReplace(p+1,m.childCount)||!v.type.validContent(f))return!1}let l=i.indexAfter(s),c=r&&r[0];return i.node(s).canReplaceWith(l,l,c?c.type:i.node(s+1).type)}function XGe(t,e,n=1,r){let i=t.doc.resolve(e),s=Vt.empty,o=Vt.empty;for(let l=i.depth,c=i.depth-n,d=n-1;l>c;l--,d--){s=Vt.from(i.node(l).copy(s));let u=r&&r[d];o=Vt.from(u?u.type.create(u.attrs,o):i.node(l).copy(o))}t.step(new Ui(e,e,new cn(s.append(o),n,n),!0))}function Sp(t,e){let n=t.resolve(e),r=n.index();return Aie(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function YGe(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let i=0;i<e.childCount;i++){let s=e.child(i),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 Aie(t,e){return!!(t&&e&&!t.isLeaf&&YGe(t,e))}function BT(t,e,n=-1){let r=t.resolve(e);for(let i=r.depth;;i--){let s,o,l=r.index(i);if(i==r.depth?(s=r.nodeBefore,o=r.nodeAfter):n>0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&Aie(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=n<0?r.before(i):r.after(i)}}function QGe(t,e,n){let r=null,{linebreakReplacement:i}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(i&&o.inlineContent){let u=o.whitespace=="pre",m=!!o.contentMatch.matchType(i);u&&!m?r=!1:!u&&m&&(r=!0)}let l=t.steps.length;if(r===!1){let u=t.doc.resolve(e+n);Tie(t,u.node(),u.before(),l)}o.inlineContent&&uz(t,e+n-1,o,s.node().contentMatchAt(s.index()),r==null);let c=t.mapping.slice(l),d=c.map(e-n);if(t.step(new Ui(d,c.map(e+n,-1),cn.empty,!0)),r===!0){let u=t.doc.resolve(d);Pie(t,u.node(),u.before(),t.steps.length)}return t}function ZGe(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 i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,n))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,n))return r.after(i+1);if(s<r.node(i).childCount)return null}return null}function jie(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let i=n.content;for(let s=0;s<n.openStart;s++)i=i.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),d=r.node(o),u=!1;if(s==1)u=d.canReplace(c,c,i);else{let m=d.contentMatchAt(c).findWrapping(i.firstChild.type);u=m&&d.canReplaceWith(c,c,m[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function HT(t,e,n=e,r=cn.empty){if(e==n&&!r.size)return null;let i=t.resolve(e),s=t.resolve(n);return Mie(i,s,r)?new Ui(e,n,r):new JGe(i,s,r).fit()}function Mie(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class JGe{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Vt.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=Vt.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new cn(s,o,l);return e>-1?new Hi(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ui(r.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,i=this.unplaced.openEnd;r<e;r++){let s=n.firstChild;if(n.childCount>1&&(i=0),s.type.spec.isolating&&i<=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 i,s=null;r?(s=LD(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:d}=this.frontier[l],u,m=null;if(n==1&&(o?d.matchType(o.type)||(m=d.fillBefore(Vt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:m};if(n==2&&o&&(u=d.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:u};if(s&&d.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=LD(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new cn(e,n+1,Math.max(r,i.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,i=LD(e,n);if(i.childCount<=1&&n>0){let s=e.size-n<=n+i.size;this.unplaced=new cn(n0(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new cn(n0(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:i,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,d=0,u=[],{match:m,type:p}=this.frontier[n];if(i){for(let v=0;v<i.childCount;v++)u.push(i.child(v));m=m.matchFragment(i)}let f=l.size+e-(o.content.size-o.openEnd);for(;d<l.childCount;){let v=l.child(d),g=m.matchType(v.type);if(!g)break;d++,(d>1||c==0||v.content.size)&&(m=g,u.push(Eie(v.mark(p.allowedMarks(v.marks)),d==1?c:0,d==l.childCount?f:-1)))}let x=d==l.childCount;x||(f=-1),this.placed=r0(this.placed,n,Vt.from(u)),this.frontier[n].match=m,x&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,g=l;v<f;v++){let b=g.lastChild;this.frontier.push({type:b.type,match:b.contentMatchAt(b.childCount)}),g=b.content}this.unplaced=x?e==0?cn.empty:new cn(n0(o.content,e-1,1),e-1,f<0?o.openEnd:e-1):new cn(n0(o.content,e,d),o.openStart,o.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],n;if(!e.type.isTextblock||!OD(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,i=this.$to.after(r);for(;r>1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),o=OD(e,n,i,r,s);if(o){for(let l=n-1;l>=0;l--){let{match:c,type:d}=this.frontier[l],u=OD(e,l,d,c,!0);if(!u||u.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=r0(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=r0(this.placed,this.depth,Vt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Vt.empty,!0);n.childCount&&(this.placed=r0(this.placed,this.frontier.length,n))}}function n0(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(n0(t.firstChild.content,e-1,n)))}function r0(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(r0(t.lastChild.content,e-1,n)))}function LD(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function Eie(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,Eie(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(Vt.empty,!0)))),t.copy(r)}function OD(t,e,n,r,i){let s=t.node(e),o=i?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&&!e9e(n,s.content,o)?l:null}function e9e(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function t9e(t){return t.spec.defining||t.spec.definingForContent}function n9e(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let i=t.doc.resolve(e),s=t.doc.resolve(n);if(Mie(i,s,r))return t.step(new Ui(e,n,r));let o=Fie(i,s);o[o.length-1]==0&&o.pop();let l=-(i.depth+1);o.unshift(l);for(let p=i.depth,f=i.pos-1;p>0;p--,f--){let x=i.node(p).type.spec;if(x.defining||x.definingAsContext||x.isolating)break;o.indexOf(p)>-1?l=p:i.before(p)==f&&o.splice(1,0,-p)}let c=o.indexOf(l),d=[],u=r.openStart;for(let p=r.content,f=0;;f++){let x=p.firstChild;if(d.push(x),f==r.openStart)break;p=x.content}for(let p=u-1;p>=0;p--){let f=d[p],x=t9e(f.type);if(x&&!f.sameMarkup(i.node(Math.abs(l)-1)))u=p;else if(x||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+u+1)%(r.openStart+1),x=d[f];if(x)for(let v=0;v<o.length;v++){let g=o[(v+c)%o.length],b=!0;g<0&&(b=!1,g=-g);let _=i.node(g-1),C=i.index(g-1);if(_.canReplaceWith(C,C,x.type,x.marks))return t.replace(i.before(g),b?s.after(g):n,new cn(Die(r.content,0,r.openStart,f),f,r.openEnd))}}let m=t.steps.length;for(let p=o.length-1;p>=0&&(t.replace(e,n,r),!(t.steps.length>m));p--){let f=o[p];f<0||(e=i.before(f),n=s.after(f))}}function Die(t,e,n,r,i){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(Die(s.content,e+1,n,r,s)))}if(e>r){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Vt.empty,!0))}return t}function r9e(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=ZGe(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new cn(Vt.from(r),0,0))}function a9e(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n),s=Fie(r,i);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),i.end(l));if(l>0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&i.end(o)-n!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function Fie(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let s=t.start(i);if(s<t.pos-(t.depth-i)||e.end(i)>e.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&n.push(i)}return n}class Sx extends Is{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 pi.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 i=n.type.create(r,null,n.marks);return pi.fromReplace(e,this.pos,this.pos+1,new cn(Vt.from(i),0,n.isLeaf?0:1))}getMap(){return tl.empty}invert(e){return new Sx(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 Sx(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 Sx(n.pos,n.attr,n.value)}}Is.jsonID("attr",Sx);class yw extends Is{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return pi.ok(r)}getMap(){return tl.empty}invert(e){return new yw(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 yw(n.attr,n.value)}}Is.jsonID("docAttr",yw);let Kx=class extends Error{};Kx=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Kx.prototype=Object.create(Error.prototype);Kx.prototype.constructor=Kx;Kx.prototype.name="TransformError";class Rie{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new xw}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Kx(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 i=this.mapping.maps[r];r&&(e=i.map(e,1),n=i.map(n,-1)),i.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=cn.empty){let i=HT(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new cn(Vt.from(r),0,0))}delete(e,n){return this.replace(e,n,cn.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return n9e(this,e,n,r),this}replaceRangeWith(e,n,r){return r9e(this,e,n,r),this}deleteRange(e,n){return a9e(this,e,n),this}lift(e,n){return HGe(this,e,n),this}join(e,n=1){return QGe(this,e,n),this}wrap(e,n){return VGe(this,e,n),this}setBlockType(e,n=e,r,i=null){return GGe(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return KGe(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new Sx(e,n,r)),this}setDocAttribute(e,n){return this.step(new yw(e,n)),this}addNodeMark(e,n){return this.step(new Oh(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 ta)n.isInSet(r.marks)&&this.step(new pg(e,n));else{let i=r.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new pg(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return XGe(this,e,n,r),this}addMark(e,n,r){return zGe(this,e,n,r),this}removeMark(e,n,r){return UGe(this,e,n,r),this}clearIncompatible(e,n,r){return uz(this,e,n,r),this}}const ID=Object.create(null);class ir{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new i9e(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=cn.empty){let r=n.content.lastChild,i=null;for(let l=0;l<n.openEnd;l++)i=r,r=r.lastChild;let s=e.steps.length,o=this.ranges;for(let l=0;l<o.length;l++){let{$from:c,$to:d}=o[l],u=e.mapping.slice(s);e.replaceRange(u.map(c.pos),u.map(d.pos),l?cn.empty:n),l==0&&AK(e,s,(r?r.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:o,$to:l}=i[s],c=e.mapping.slice(r),d=c.map(o.pos),u=c.map(l.pos);s?e.deleteRange(d,u):(e.replaceRangeWith(d,u,n),AK(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let i=e.parent.inlineContent?new $n(e):Jb(e.node(0),e.parent,e.pos,e.index(),n,r);if(i)return i;for(let s=e.depth-1;s>=0;s--){let o=n<0?Jb(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Jb(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 cl(e.node(0))}static atStart(e){return Jb(e,e,0,0,1)||new cl(e)}static atEnd(e){return Jb(e,e,e.content.size,e.childCount,-1)||new cl(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=ID[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 ID)throw new RangeError("Duplicate use of selection JSON ID "+e);return ID[e]=n,n.prototype.jsonID=e,n}getBookmark(){return $n.between(this.$anchor,this.$head).getBookmark()}}ir.prototype.visible=!0;class i9e{constructor(e,n){this.$from=e,this.$to=n}}let PK=!1;function TK(t){!PK&&!t.parent.inlineContent&&(PK=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class $n extends ir{constructor(e,n=e){TK(e),TK(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 ir.near(r);let i=e.resolve(n.map(this.anchor));return new $n(i.parent.inlineContent?i:r,r)}replace(e,n=cn.empty){if(super.replace(e,n),n==cn.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof $n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new qT(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 $n(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let s=ir.findFrom(n,r,!0)||ir.findFrom(n,-r,!0);if(s)n=s.$head;else return ir.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(ir.findFrom(e,-r,!0)||ir.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=i<0&&(e=n))),new $n(e,n)}}ir.jsonID("text",$n);class qT{constructor(e,n){this.anchor=e,this.head=n}map(e){return new qT(e.map(this.anchor),e.map(this.head))}resolve(e){return $n.between(e.resolve(this.anchor),e.resolve(this.head))}}class Mn extends ir{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:i}=n.mapResult(this.anchor),s=e.resolve(i);return r?ir.near(s):new Mn(s)}content(){return new cn(Vt.from(this.node),0,0)}eq(e){return e instanceof Mn&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new hz(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Mn(e.resolve(n.anchor))}static create(e,n){return new Mn(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}Mn.prototype.visible=!1;ir.jsonID("node",Mn);class hz{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new qT(r,r):new hz(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&Mn.isSelectable(r)?new Mn(n):ir.near(n)}}class cl extends ir{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=cn.empty){if(n==cn.empty){e.delete(0,e.doc.content.size);let r=ir.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new cl(e)}map(e){return new cl(e)}eq(e){return e instanceof cl}getBookmark(){return s9e}}ir.jsonID("all",cl);const s9e={map(){return this},resolve(t){return new cl(t)}};function Jb(t,e,n,r,i,s=!1){if(e.inlineContent)return $n.create(t,n);for(let o=r-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&Mn.isSelectable(l))return Mn.create(t,n-(i<0?l.nodeSize:0))}else{let c=Jb(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function AK(t,e,n){let r=t.steps.length-1;if(r<e)return;let i=t.steps[r];if(!(i instanceof Ui||i instanceof Hi))return;let s=t.mapping.maps[r],o;s.forEach((l,c,d,u)=>{o==null&&(o=u)}),t.setSelection(ir.near(t.doc.resolve(o),n))}const jK=1,ak=2,MK=4;class o9e extends Rie{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|jK)&~ak,this.storedMarks=null,this}get selectionSet(){return(this.updated&jK)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=ak,this}ensureMarks(e){return ta.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&ak)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~ak,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)||ta.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.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,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(ir.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|=MK,this}get scrolledIntoView(){return(this.updated&MK)>0}}function EK(t,e){return!e||!t?t:t.bind(e)}class a0{constructor(e,n,r){this.name=e,this.init=EK(n.init,r),this.apply=EK(n.apply,r)}}const l9e=[new a0("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new a0("selection",{init(t,e){return t.selection||ir.atStart(e.doc)},apply(t){return t.selection}}),new a0("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new a0("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class zD{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=l9e.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 a0(r.key,r.spec.state,r))})}}class cx{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 i=this.config.plugins[r];if(i.spec.filterTransaction&&!i.spec.filterTransaction.call(i,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),i=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=i?i[o].n:0,d=i?i[o].state:this,u=c<n.length&&l.spec.appendTransaction.call(l,c?n.slice(c):n,d,r);if(u&&r.filterTransaction(u,o)){if(u.setMeta("appendedTransaction",e),!i){i=[];for(let m=0;m<this.config.plugins.length;m++)i.push(m<o?{state:r,n:n.length}:{state:this,n:0})}n.push(u),r=r.applyInner(u),s=!0}i&&(i[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 cx(this.config),r=this.config.fields;for(let i=0;i<r.length;i++){let s=r[i];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new o9e(this)}static create(e){let n=new zD(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new cx(n);for(let i=0;i<n.fields.length;i++)r[n.fields[i].name]=n.fields[i].init(e,r);return r}reconfigure(e){let n=new zD(this.schema,e.plugins),r=n.fields,i=new cx(n);for(let s=0;s<r.length;s++){let o=r[s].name;i[o]=this.hasOwnProperty(o)?this[o]:r[s].init(e,i)}return i}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 i=e[r],s=i.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(i,this[i.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 i=new zD(e.schema,e.plugins),s=new cx(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=zc.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=ir.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],d=c.spec.state;if(c.key==o.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=d.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function Lie(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=Lie(i,e,{})),n[r]=i}return n}class Ra{constructor(e){this.spec=e,this.props={},e.props&&Lie(e.props,this,this.props),this.key=e.key?e.key.key:Oie("plugin")}getState(e){return e[this.key]}}const UD=Object.create(null);function Oie(t){return t in UD?t+"$"+ ++UD[t]:(UD[t]=0,t+"$")}class Ei{constructor(e="key"){this.key=Oie(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const pz=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Iie(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const zie=(t,e,n)=>{let r=Iie(t,n);if(!r)return!1;let i=fz(r);if(!i){let o=r.blockRange(),l=o&&Ny(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Kie(t,i,e,-1))return!0;if(r.parent.content.size==0&&(Xx(s,"end")||Mn.isSelectable(s)))for(let o=r.depth;;o--){let l=HT(t.doc,r.before(o),r.after(o),cn.empty);if(l&&l.slice.size<l.to-l.from){if(e){let c=t.tr.step(l);c.setSelection(Xx(s,"end")?ir.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):Mn.create(c.doc,i.pos-s.nodeSize)),e(c.scrollIntoView())}return!0}if(o==1||r.node(o-1).childCount>1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},c9e=(t,e,n)=>{let r=Iie(t,n);if(!r)return!1;let i=fz(r);return i?Uie(t,i,e):!1},d9e=(t,e,n)=>{let r=Hie(t,n);if(!r)return!1;let i=gz(r);return i?Uie(t,i,e):!1};function Uie(t,e,n){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let d=HT(t.doc,s,c,cn.empty);if(!d||d.from!=s||d instanceof Ui&&d.slice.size>=c-s)return!1;if(n){let u=t.tr.step(d);u.setSelection($n.create(u.doc,s)),n(u.scrollIntoView())}return!0}function Xx(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 Bie=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=fz(r)}let o=s&&s.nodeBefore;return!o||!Mn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Mn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function fz(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 Hie(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const qie=(t,e,n)=>{let r=Hie(t,n);if(!r)return!1;let i=gz(r);if(!i)return!1;let s=i.nodeAfter;if(Kie(t,i,e,1))return!0;if(r.parent.content.size==0&&(Xx(s,"start")||Mn.isSelectable(s))){let o=HT(t.doc,r.before(),r.after(),cn.empty);if(o&&o.slice.size<o.to-o.from){if(e){let l=t.tr.step(o);l.setSelection(Xx(s,"start")?ir.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):Mn.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos,i.pos+s.nodeSize).scrollIntoView()),!0):!1},$ie=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;s=gz(r)}let o=s&&s.nodeAfter;return!o||!Mn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Mn.create(t.doc,s.pos)).scrollIntoView()),!0)};function gz(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 u9e=(t,e)=>{let n=t.selection,r=n instanceof Mn,i;if(r){if(n.node.isTextblock||!Sp(t.doc,n.from))return!1;i=n.from}else if(i=BT(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);r&&s.setSelection(Mn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},m9e=(t,e)=>{let n=t.selection,r;if(n instanceof Mn){if(n.node.isTextblock||!Sp(t.doc,n.to))return!1;r=n.to}else if(r=BT(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},h9e=(t,e)=>{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),s=i&&Ny(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},Vie=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
- `).scrollIntoView()),!0)};function bz(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 p9e=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=bz(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(ir.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},Gie=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof cl||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=bz(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,l=t.tr.insert(o,s.createAndFill());l.setSelection($n.create(l.doc,o+1)),e(l.scrollIntoView())}return!0},Wie=(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(em(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ny(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function f9e(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof Mn&&e.selection.node.isBlock)return!r.parentOffset||!em(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,d=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){c=r.end(f)==r.pos+(r.depth-f),d=r.start(f)==r.pos-(r.depth-f),l=bz(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),s.unshift(c&&l?{type:l}:null),o=f;break}else{if(f==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof $n||e.selection instanceof cl)&&u.deleteSelection();let m=u.mapping.map(r.pos),p=em(u.doc,m,s.length,s);if(p||(s[0]=l?{type:l}:null,p=em(u.doc,m,s.length,s)),!p)return!1;if(u.split(m,s.length,s),!c&&d&&r.node(o).type!=l){let f=u.mapping.map(r.before(o)),x=u.doc.resolve(f);l&&r.node(o-1).canReplaceWith(x.index(),x.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return n&&n(u.scrollIntoView()),!0}}const g9e=f9e(),b9e=(t,e)=>{let{$from:n,to:r}=t.selection,i,s=n.sharedDepth(r);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(Mn.create(t.doc,i))),!0)};function x9e(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.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)||!(i.isTextblock||Sp(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Kie(t,e,n,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&x9e(t,e,n))return!0;let d=!c&&e.parent.canReplace(e.index(),e.index()+1);if(d&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let f=e.pos+s.nodeSize,x=Vt.empty;for(let b=o.length-1;b>=0;b--)x=Vt.from(o[b].create(null,x));x=Vt.from(i.copy(x));let v=t.tr.step(new Hi(e.pos-1,f,e.pos,f,new cn(x,1,0),o.length,!0)),g=v.doc.resolve(f+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&Sp(v.doc,g.pos)&&v.join(g.pos),n(v.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&c?null:ir.findFrom(e,1),m=u&&u.$from.blockRange(u.$to),p=m&&Ny(m);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(m,p).scrollIntoView()),!0;if(d&&Xx(s,"start",!0)&&Xx(i,"end")){let f=i,x=[];for(;x.push(f),!f.isTextblock;)f=f.lastChild;let v=s,g=1;for(;!v.isTextblock;v=v.firstChild)g++;if(f.canReplace(f.childCount,f.childCount,v.content)){if(n){let b=Vt.empty;for(let C=x.length-1;C>=0;C--)b=Vt.from(x[C].copy(b));let _=t.tr.step(new Hi(e.pos-x.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new cn(b,x.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function Xie(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection($n.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const y9e=Xie(-1),v9e=Xie(1);function w9e(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&mz(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function DK(t,e=null){return function(n,r){let i=!1;for(let s=0;s<n.selection.ranges.length&&!i;s++){let{$from:{pos:o},$to:{pos:l}}=n.selection.ranges[s];n.doc.nodesBetween(o,l,(c,d)=>{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)i=!0;else{let u=n.doc.resolve(d),m=u.index();i=u.parent.canReplaceWith(m,m+1,t)}})}if(!i)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 xz(...t){return function(e,n,r){for(let i=0;i<t.length;i++)if(t[i](e,n,r))return!0;return!1}}xz(pz,zie,Bie);xz(pz,qie,$ie);xz(Vie,Gie,Wie,g9e);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function S9e(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s);if(!o)return!1;let l=r?n.tr:null;return _9e(l,o,t,e)?(r&&r(l.scrollIntoView()),!0):!1}}function _9e(t,e,n,r=null){let i=!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 jC(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new jC(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=mz(s,n,r,e);return l?(t&&k9e(t,e,l,i,n),!0):!1}function k9e(t,e,n,r,i){let s=Vt.empty;for(let u=n.length-1;u>=0;u--)s=Vt.from(n[u].type.create(n[u].attrs,s));t.step(new Hi(e.start-(r?2:0),e.end,e.start,e.end,new cn(s,0,0),n.length,!0));let o=0;for(let u=0;u<n.length;u++)n[u].type==i&&(o=u+1);let l=n.length-o,c=e.start+n.length-(r?2:0),d=e.parent;for(let u=e.startIndex,m=e.endIndex,p=!0;u<m;u++,p=!1)!p&&em(t.doc,c,l)&&(t.split(c,l),c+=2*l),c+=d.child(u).nodeSize;return t}function N9e(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,o=>o.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?C9e(e,n,t,s):P9e(e,n,s):!0:!1}}function C9e(t,e,n,r){let i=t.tr,s=r.end,o=r.$to.end(r.depth);s<o&&(i.step(new Hi(s-1,o,s,o,new cn(Vt.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new jC(i.doc.resolve(r.$from.pos),i.doc.resolve(o),r.depth));const l=Ny(r);if(l==null)return!1;i.lift(r,l);let c=i.doc.resolve(i.mapping.map(s,-1)-1);return Sp(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&i.join(c.pos),e(i.scrollIntoView()),!0}function P9e(t,e,n){let r=t.tr,i=n.parent;for(let f=n.end,x=n.endIndex-1,v=n.startIndex;x>v;x--)f-=i.child(x).nodeSize,r.delete(f-1,f+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==i.childCount,d=s.node(-1),u=s.index(-1);if(!d.canReplace(u+(l?0:1),u+1,o.content.append(c?Vt.empty:Vt.from(i))))return!1;let m=s.pos,p=m+o.nodeSize;return r.step(new Hi(m-(l?1:0),p+(c?1:0),m+1,p-1,new cn((l?Vt.empty:Vt.from(i.copy(Vt.empty))).append(c?Vt.empty:Vt.from(i.copy(Vt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function T9e(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,d=>d.childCount>0&&d.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 d=c.lastChild&&c.lastChild.type==l.type,u=Vt.from(d?t.create():null),m=new cn(Vt.from(t.create(null,Vt.from(l.type.create(null,u)))),d?3:1,0),p=s.start,f=s.end;n(e.tr.step(new Hi(p-(d?3:1),f,p,f,m,1,!0)).scrollIntoView())}return!0}}const ms=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Yx=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let bL=null;const ju=function(t,e,n){let r=bL||(bL=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},A9e=function(){bL=null},fg=function(t,e,n,r){return n&&(FK(t,e,n,r,-1)||FK(t,e,n,r,1))},j9e=/^(img|br|input|textarea|hr)$/i;function FK(t,e,n,r,i){for(var s;;){if(t==n&&e==r)return!0;if(e==(i<0?0:Wl(t))){let o=t.parentNode;if(!o||o.nodeType!=1||yS(t)||j9e.test(t.nodeName)||t.contentEditable=="false")return!1;e=ms(t)+(i<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else t=o,e=i<0?Wl(t):0}else return!1}}function Wl(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function M9e(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=Wl(t)}else if(t.parentNode&&!yS(t))e=ms(t),t=t.parentNode;else return null}}function E9e(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&&!yS(t))e=ms(t)+1,t=t.parentNode;else return null}}function D9e(t,e,n){for(let r=e==0,i=e==Wl(t);r||i;){if(t==n)return!0;let s=ms(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,i=i&&s==Wl(t)}}function yS(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 $T=function(t){return t.focusNode&&fg(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function bf(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function F9e(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function R9e(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(Wl(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(Wl(r.startContainer),r.startOffset)}}}const Od=typeof navigator<"u"?navigator:null,RK=typeof document<"u"?document:null,_p=Od&&Od.userAgent||"",xL=/Edge\/(\d+)/.exec(_p),Yie=/MSIE \d/.exec(_p),yL=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(_p),Eo=!!(Yie||yL||xL),ep=Yie?document.documentMode:yL?+yL[1]:xL?+xL[1]:0,tc=!Eo&&/gecko\/(\d+)/i.test(_p);tc&&+(/Firefox\/(\d+)/.exec(_p)||[0,0])[1];const vL=!Eo&&/Chrome\/(\d+)/.exec(_p),bs=!!vL,Qie=vL?+vL[1]:0,Rs=!Eo&&!!Od&&/Apple Computer/.test(Od.vendor),Qx=Rs&&(/Mobile\/\w+/.test(_p)||!!Od&&Od.maxTouchPoints>2),Bl=Qx||(Od?/Mac/.test(Od.platform):!1),Zie=Od?/Win/.test(Od.platform):!1,Gu=/Android \d/.test(_p),vS=!!RK&&"webkitFontSmoothing"in RK.documentElement.style,L9e=vS?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function O9e(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 Su(t,e){return typeof t=="number"?t:t[e]}function I9e(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 LK(t,e,n){let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=Yx(o);continue}let l=o,c=l==s.body,d=c?O9e(s):I9e(l),u=0,m=0;if(e.top<d.top+Su(r,"top")?m=-(d.top-e.top+Su(i,"top")):e.bottom>d.bottom-Su(r,"bottom")&&(m=e.bottom-e.top>d.bottom-d.top?e.top+Su(i,"top")-d.top:e.bottom-d.bottom+Su(i,"bottom")),e.left<d.left+Su(r,"left")?u=-(d.left-e.left+Su(i,"left")):e.right>d.right-Su(r,"right")&&(u=e.right-d.right+Su(i,"right")),u||m)if(c)s.defaultView.scrollBy(u,m);else{let f=l.scrollLeft,x=l.scrollTop;m&&(l.scrollTop+=m),u&&(l.scrollLeft+=u);let v=l.scrollLeft-f,g=l.scrollTop-x;e={left:e.left-v,top:e.top-g,right:e.right-v,bottom:e.bottom-g}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:Yx(o)}}function z9e(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;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,i=c.top;break}}return{refDOM:r,refTop:i,stack:Jie(t.dom)}}function Jie(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Yx(r));return e}function U9e({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;ese(n,r==0?0:r-e)}function ese(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:i,left:s}=t[n];r.scrollTop!=i+e&&(r.scrollTop=i+e),r.scrollLeft!=s&&(r.scrollLeft=s)}}let Vb=null;function B9e(t){if(t.setActive)return t.setActive();if(Vb)return t.focus(Vb);let e=Jie(t);t.focus(Vb==null?{get preventScroll(){return Vb={preventScroll:!0},!0}}:void 0),Vb||(Vb=!1,ese(e,0))}function tse(t,e){let n,r=2e8,i,s=0,o=e.top,l=e.top,c,d;for(let u=t.firstChild,m=0;u;u=u.nextSibling,m++){let p;if(u.nodeType==1)p=u.getClientRects();else if(u.nodeType==3)p=ju(u).getClientRects();else continue;for(let f=0;f<p.length;f++){let x=p[f];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=u,r=v,i=v&&n.nodeType==3?{left:x.right<e.left?x.right:x.left,top:e.top}:e,u.nodeType==1&&v&&(s=m+(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=u,d={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=m+1)}}return!n&&c&&(n=c,i=d,r=0),n&&n.nodeType==3?H9e(n,i):!n||r&&n.nodeType==1?{node:t,offset:s}:tse(n,i)}function H9e(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let o=hh(r,1);if(o.top!=o.bottom&&yz(e,o)){i={node:t,offset:s+(e.left>=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function yz(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function q9e(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function $9e(t,e,n){let{node:r,offset:i}=tse(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,i,s)}function V9e(t,e,n,r){let i=-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?i=l.posBefore:(!o&&c.right<r.left||c.bottom<r.top)&&(i=l.posAfter),o=!0),!l.contentDOM&&i<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 i>-1?i:t.docView.posFromDOM(e,n,-1)}function nse(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let i=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),s=i;;){let o=t.childNodes[s];if(o.nodeType==1){let l=o.getClientRects();for(let c=0;c<l.length;c++){let d=l[c];if(yz(e,d))return nse(o,e,d)}}if((s=(s+1)%r)==i)break}return t}function G9e(t,e){let n=t.dom.ownerDocument,r,i=0,s=R9e(n,e.left,e.top);s&&({node:r,offset:i}=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 d=t.dom.getBoundingClientRect();if(!yz(e,d)||(o=nse(t.dom,e,d),!o))return null}if(Rs)for(let d=o;r&&d;d=Yx(d))d.draggable&&(r=void 0);if(o=q9e(o,e),r){if(tc&&r.nodeType==1&&(i=Math.min(i,r.childNodes.length),i<r.childNodes.length)){let u=r.childNodes[i],m;u.nodeName=="IMG"&&(m=u.getBoundingClientRect()).right<=e.left&&m.bottom>e.top&&i++}let d;vS&&i&&r.nodeType==1&&(d=r.childNodes[i-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=V9e(t,r,i,e))}l==null&&(l=$9e(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function OK(t){return t.top<t.bottom||t.left<t.right}function hh(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(OK(r))return r}return Array.prototype.find.call(n,OK)||t.getBoundingClientRect()}const W9e=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function rse(t,e,n){let{node:r,offset:i,atom:s}=t.docView.domFromPos(e,n<0?-1:1),o=vS||tc;if(r.nodeType==3)if(o&&(W9e.test(r.nodeValue)||(n<0?!i:i==r.nodeValue.length))){let c=hh(ju(r,i,i),n);if(tc&&i&&/\s/.test(r.nodeValue[i-1])&&i<r.nodeValue.length){let d=hh(ju(r,i-1,i-1),-1);if(d.top==c.top){let u=hh(ju(r,i,i+1),-1);if(u.top!=c.top)return qv(u,u.left<d.left)}}return c}else{let c=i,d=i,u=n<0?1:-1;return n<0&&!i?(d++,u=-1):n>=0&&i==r.nodeValue.length?(c--,u=1):n<0?c--:d++,qv(hh(ju(r,c,d),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==Wl(r))){let c=r.childNodes[i-1];if(c.nodeType==1)return BD(c.getBoundingClientRect(),!1)}if(s==null&&i<Wl(r)){let c=r.childNodes[i];if(c.nodeType==1)return BD(c.getBoundingClientRect(),!0)}return BD(r.getBoundingClientRect(),n>=0)}if(s==null&&i&&(n<0||i==Wl(r))){let c=r.childNodes[i-1],d=c.nodeType==3?ju(c,Wl(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return qv(hh(d,1),!1)}if(s==null&&i<Wl(r)){let c=r.childNodes[i];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let d=c?c.nodeType==3?ju(c,0,o?0:1):c.nodeType==1?c:null:null;if(d)return qv(hh(d,-1),!0)}return qv(hh(r.nodeType==3?ju(r):r,-n),n>=0)}function qv(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 BD(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 ase(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function K9e(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return ase(t,e,()=>{let{node:s}=t.docView.domFromPos(i.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=rse(t,i.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=ju(l,0,l.nodeValue.length).getClientRects();else continue;for(let d=0;d<c.length;d++){let u=c[d];if(u.bottom>u.top+1&&(n=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}const X9e=/[\u0590-\u08ac]/;function Y9e(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=t.domSelection();return l?!X9e.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:ase(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:m}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let f=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:x,focusOffset:v}=t.domSelectionRange(),g=x&&!f.contains(x.nodeType==1?x:x.parentNode)||c==x&&d==v;try{l.collapse(u,m),c&&(c!=u||d!=m)&&l.extend&&l.extend(c,d)}catch{}return p!=null&&(l.caretBidiLevel=p),g}):r.pos==r.start()||r.pos==r.end()}let IK=null,zK=null,UK=!1;function Q9e(t,e,n){return IK==e&&zK==n?UK:(IK=e,zK=n,UK=n=="up"||n=="down"?K9e(t,e,n):Y9e(t,e,n))}const nc=0,BK=1,Tf=2,Id=3;class wS{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=nc,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 i=this.children[n];if(i==e)return r;r+=i.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 i;if(e==this.dom&&this.contentDOM)i=n>ms(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),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 i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let i=this.children[n],s=r+i.size;if(r==e&&s!=r){for(;!i.border&&i.children.length;)for(let o=0;o<i.children.length;o++){let l=i.children[o];if(l.size){i=l;break}}return i}if(e<s)return i.descAt(e-r-i.border);r=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,i=0;for(let s=0;r<this.children.length;r++){let o=this.children[r],l=s+o.size;if(l>e||o instanceof sse){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof ise&&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?ms(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?ms(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 i=-1,s=-1;for(let o=r,l=0;;l++){let c=this.children[l],d=o+c.size;if(i==-1&&e<=d){let u=o+c.border;if(e>=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,u);e=o;for(let m=l;m>0;m--){let p=this.children[m-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){i=ms(p.dom)+1;break}e-=p.size}i==-1&&(i=0)}if(i>-1&&(d>n||l==this.children.length-1)){n=d;for(let u=l+1;u<this.children.length;u++){let m=this.children[u];if(m.size&&m.dom.parentNode==this.contentDOM&&!m.emptyChildAt(-1)){s=ms(m.dom);break}n+=m.size}s==-1&&(s=this.contentDOM.childNodes.length);break}o=d}return{node:this.contentDOM,from:e,to:n,fromOffset:i,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,i=!1){let s=Math.min(e,n),o=Math.max(e,n);for(let f=0,x=0;f<this.children.length;f++){let v=this.children[f],g=x+v.size;if(s>x&&o<g)return v.setSelection(e-x-v.border,n-x-v.border,r,i);x=g}let l=this.domFromPos(e,e?-1:1),c=n==e?l:this.domFromPos(n,n?-1:1),d=r.root.getSelection(),u=r.domSelectionRange(),m=!1;if((tc||Rs)&&e==n){let{node:f,offset:x}=l;if(f.nodeType==3){if(m=!!(x&&f.nodeValue[x-1]==`
- `),m&&x==f.nodeValue.length)for(let v=f,g;v;v=v.parentNode){if(g=v.nextSibling){g.nodeName=="BR"&&(l=c={node:g.parentNode,offset:ms(g)+1});break}let b=v.pmViewDesc;if(b&&b.node&&b.node.isBlock)break}}else{let v=f.childNodes[x-1];m=v&&(v.nodeName=="BR"||v.contentEditable=="false")}}if(tc&&u.focusNode&&u.focusNode!=c.node&&u.focusNode.nodeType==1){let f=u.focusNode.childNodes[u.focusOffset];f&&f.contentEditable=="false"&&(i=!0)}if(!(i||m&&Rs)&&fg(l.node,l.offset,u.anchorNode,u.anchorOffset)&&fg(c.node,c.offset,u.focusNode,u.focusOffset))return;let p=!1;if((d.extend||e==n)&&!(m&&tc)){d.collapse(l.node,l.offset);try{e!=n&&d.extend(c.node,c.offset),p=!0}catch{}}if(!p){if(e>n){let x=l;l=c,c=x}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(l.node,l.offset),d.removeAllRanges(),d.addRange(f)}}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,i=0;i<this.children.length;i++){let s=this.children[i],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?Tf:BK,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Id:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Tf:Id}r=o}this.dirty=Tf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Tf:BK;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class ise extends wS{constructor(e,n,r,i){let s,o=n.type.toDOM;if(typeof o=="function"&&(o=o(r,()=>{if(!s)return i;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==nc&&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 Z9e extends wS{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}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 gg extends wS{constructor(e,n,r,i,s){super(e,[],r,i),this.mark=n,this.spec=s}static create(e,n,r,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,r);return(!o||!o.dom)&&(o=Cg.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new gg(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Id||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Id&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=nc){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=nc}}slice(e,n,r){let i=gg.create(this.parent,this.mark,!0,r),s=this.children,o=this.size;n<o&&(s=SL(s,n,o,r)),e>0&&(s=SL(s,0,e,r));for(let l=0;l<s.length;l++)s[l].parent=i;return i.children=s,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class tp extends wS{constructor(e,n,r,i,s,o,l,c,d){super(e,[],s,o),this.node=n,this.outerDeco=r,this.innerDeco=i,this.nodeDOM=l}static create(e,n,r,i,s,o){let l=s.nodeViews[n.type.name],c,d=l&&l(n,s,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=d&&d.dom,m=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:m}=Cg.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!m&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let p=u;return u=cse(u,r,n),d?c=new J9e(e,n,r,i,u,m||null,p,d,s,o+1):n.isText?new VT(e,n,r,i,u,p,s):new tp(e,n,r,i,u,m||null,p,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=()=>Vt.empty)}return e}matchesNode(e,n,r){return this.dirty==nc&&e.eq(this.node)&&EC(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,i=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new tWe(this,o&&o.node,e);aWe(this.node,this.innerDeco,(d,u,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,e,u):d.type.side>=0&&!m&&c.syncToMarks(u==this.node.childCount?ta.none:this.node.child(u).marks,r,e,u),c.placeWidget(d,e,i)},(d,u,m,p)=>{c.syncToMarks(d.marks,r,e,p);let f;c.findNodeMatch(d,u,m,p)||l&&e.state.selection.from>i&&e.state.selection.to<i+d.nodeSize&&(f=c.findIndexWithChild(s.node))>-1&&c.updateNodeAt(d,u,m,f,e)||c.updateNextNode(d,u,m,e,p,i)||c.addNode(d,u,m,e,i),i+=d.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==Tf)&&(o&&this.protectLocalComposition(e,o),ose(this.contentDOM,this.children,e),Qx&&iWe(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof $n)||r<n||i>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=sWe(this.node.content,o,r-n,i-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:i}){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 Z9e(this,s,n,i);e.input.compositionNodes.push(o),this.children=SL(this.children,r,r+i.length,e,o)}update(e,n,r,i){return this.dirty==Id||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=nc}updateOuterDeco(e){if(EC(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=lse(this.dom,this.nodeDOM,wL(this.outerDeco,this.node,n),wL(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 HK(t,e,n,r,i){cse(r,e,t);let s=new tp(void 0,t,e,n,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class VT extends tp{constructor(e,n,r,i,s,o,l){super(e,n,r,i,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,i){return this.dirty==Id||this.dirty!=nc&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=nc||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=nc,!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 i=this.node.cut(e,n),s=document.createTextNode(i.text);return new VT(this.parent,i,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=Id)}get domAtom(){return!1}isText(e){return this.node.text==e}}class sse extends wS{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==nc&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class J9e extends tp{constructor(e,n,r,i,s,o,l,c,d,u){super(e,n,r,i,s,o,l,d,u),this.spec=c}update(e,n,r,i){if(this.dirty==Id)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,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}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 ose(t,e,n){let r=t.firstChild,i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=o.dom;if(l.parentNode==t){for(;l!=r;)r=qK(r),i=!0;r=r.nextSibling}else i=!0,t.insertBefore(l,r);if(o instanceof gg){let c=r?r.previousSibling:t.lastChild;ose(o.contentDOM,o.children,n),r=c?c.nextSibling:t.firstChild}}for(;r;)r=qK(r),i=!0;i&&n.trackWrites==t&&(n.trackWrites=null)}const _0=function(t){t&&(this.nodeName=t)};_0.prototype=Object.create(null);const Af=[new _0];function wL(t,e,n){if(t.length==0)return Af;let r=n?Af[0]:new _0,i=[r];for(let s=0;s<t.length;s++){let o=t[s].type.attrs;if(o){o.nodeName&&i.push(r=new _0(o.nodeName));for(let l in o){let c=o[l];c!=null&&(n&&i.length==1&&i.push(r=new _0(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 i}function lse(t,e,n,r){if(n==Af&&r==Af)return e;let i=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&&i!=t&&(c=i.parentNode)&&c.nodeName.toLowerCase()==o.nodeName||(c=document.createElement(o.nodeName),c.pmIsDeco=!0,c.appendChild(i),l=Af[0]),i=c}eWe(i,l||Af[0],o)}return i}function eWe(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):[],i=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<r.length;s++)i.indexOf(r[s])==-1&&t.classList.remove(r[s]);for(let s=0;s<i.length;s++)r.indexOf(i[s])==-1&&t.classList.add(i[s]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;for(;i=r.exec(e.style);)t.style.removeProperty(i[1])}n.style&&(t.style.cssText+=n.style)}}function cse(t,e,n){return lse(t,t,Af,wL(e,n,t.nodeType!=1))}function EC(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 qK(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class tWe{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=nWe(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,i){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=nc,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,d=this.top.children.length;i<this.preMatch.index&&(d=Math.min(this.index+3,d));for(let u=this.index;u<d;u++){let m=this.top.children[u];if(m.matchesMark(e[o])&&!this.isLocked(m.dom)){c=u;break}}if(c>-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=gg.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-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 d=this.top.children[l];if(d.matchesNode(e,n,r)&&!this.preMatch.matched.has(d)){s=l;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,r,i,s){let o=this.top.children[i];return o.dirty==Id&&o.dom==o.contentDOM&&(o.dirty=Tf),o.update(e,n,r,s)?(this.destroyBetween(this.index,i),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 i=this.index;i<this.top.children.length;i++)if(this.top.children[i]==r)return i}return-1}e=n}}updateNextNode(e,n,r,i,s,o){for(let l=this.index;l<this.top.children.length;l++){let c=this.top.children[l];if(c instanceof tp){let d=this.preMatch.matched.get(c);if(d!=null&&d!=s)return!1;let u=c.dom,m,p=this.isLocked(u)&&!(e.isText&&c.node&&c.node.isText&&c.nodeDOM.nodeValue==e.text&&c.dirty!=Id&&EC(n,c.outerDeco));if(!p&&c.update(e,n,r,i))return this.destroyBetween(this.index,l),c.dom!=u&&(this.changed=!0),this.index++,!0;if(!p&&(m=this.recreateWrapper(c,e,n,r,i,o)))return this.destroyBetween(this.index,l),this.top.children[this.index]=m,m.contentDOM&&(m.dirty=Tf,m.updateChildren(i,o+1),m.dirty=nc),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,i,s,o){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!EC(r,e.outerDeco)||!i.eq(e.innerDeco))return null;let l=tp.create(this.top,n,r,i,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,i,s){let o=tp.create(this.top,e,n,r,i,s);o.contentDOM&&o.updateChildren(i,s+1),this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(e,n,r){let i=this.index<this.top.children.length?this.top.children[this.index]:null;if(i&&i.matchesWidget(e)&&(e==i.widget||!i.widget.type.toDOM.parentNode))this.index++;else{let s=new ise(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 gg;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof VT)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Rs||bs)&&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 i=new sse(this.top,[],r,null);n!=this.top?n.children.push(i):n.children.splice(this.index++,0,i),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function nWe(t,e){let n=e,r=n.children.length,i=t.childCount,s=new Map,o=[];e:for(;i>0;){let l;for(;;)if(r){let d=n.children[r-1];if(d instanceof gg)n=d,r=d.children.length;else{l=d,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(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function rWe(t,e){return t.type.side-e.type.side}function aWe(t,e,n,r){let i=e.locals(t),s=0;if(i.length==0){for(let d=0;d<t.childCount;d++){let u=t.child(d);r(u,i,e.forChild(s,u),d),s+=u.nodeSize}return}let o=0,l=[],c=null;for(let d=0;;){let u,m;for(;o<i.length&&i[o].to==s;){let g=i[o++];g.widget&&(u?(m||(m=[u])).push(g):u=g)}if(u)if(m){m.sort(rWe);for(let g=0;g<m.length;g++)n(m[g],d,!!c)}else n(u,d,!!c);let p,f;if(c)f=-1,p=c,c=null;else if(d<t.childCount)f=d,p=t.child(d++);else break;for(let g=0;g<l.length;g++)l[g].to<=s&&l.splice(g--,1);for(;o<i.length&&i[o].from<=s&&i[o].to>s;)l.push(i[o++]);let x=s+p.nodeSize;if(p.isText){let g=x;o<i.length&&i[o].from<g&&(g=i[o].from);for(let b=0;b<l.length;b++)l[b].to<g&&(g=l[b].to);g<x&&(c=p.cut(g-s),p=p.cut(0,g-s),x=g,f=-1)}else for(;o<i.length&&i[o].to<x;)o++;let v=p.isInline&&!p.isLeaf?l.filter(g=>!g.inline):l.slice();r(p,v,e.forChild(s,p),f),s=x}}function iWe(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 sWe(t,e,n,r){for(let i=0,s=0;i<t.childCount&&s<=r;){let o=t.child(i++),l=s;if(s+=o.nodeSize,!o.isText)continue;let c=o.text;for(;i<t.childCount;){let d=t.child(i++);if(s+=d.nodeSize,!d.isText)break;c+=d.text}if(s>=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l<r?c.lastIndexOf(e,r-l-1):-1;if(d>=0&&d+e.length+l>=n)return l+d;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function SL(t,e,n,r,i){let s=[];for(let o=0,l=0;o<t.length;o++){let c=t[o],d=l,u=l+=c.size;d>=n||u<=e?s.push(c):(d<e&&s.push(c.slice(0,e-d,r)),i&&(s.push(i),i=void 0),u>n&&s.push(c.slice(n-d,c.size,r)))}return s}function vz(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),s=i&&i.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,d;if($T(n)){for(c=o;i&&!i.node;)i=i.parent;let m=i.node;if(i&&m.isAtom&&Mn.isSelectable(m)&&i.parent&&!(m.isInline&&D9e(n.focusNode,n.focusOffset,i.dom))){let p=i.posBefore;d=new Mn(o==p?l:r.resolve(p))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let m=o,p=o;for(let f=0;f<n.rangeCount;f++){let x=n.getRangeAt(f);m=Math.min(m,t.docView.posFromDOM(x.startContainer,x.startOffset,1)),p=Math.max(p,t.docView.posFromDOM(x.endContainer,x.endOffset,-1))}if(m<0)return null;[c,o]=p==t.state.selection.anchor?[p,m]:[m,p],l=r.resolve(o)}else c=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let u=r.resolve(c);if(!d){let m=e=="pointer"||t.state.selection.head<l.pos&&!s?1:-1;d=wz(t,u,l,m)}return d}function dse(t){return t.editable?t.hasFocus():mse(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function tm(t,e=!1){let n=t.state.selection;if(use(t,n),!!dse(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&bs){let r=t.domSelectionRange(),i=t.domObserver.currentSelection;if(r.anchorNode&&i.anchorNode&&fg(r.anchorNode,r.anchorOffset,i.anchorNode,i.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)lWe(t);else{let{anchor:r,head:i}=n,s,o;$K&&!(n instanceof $n)&&(n.$from.parent.inlineContent||(s=VK(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(o=VK(t,n.to))),t.docView.setSelection(r,i,t,e),$K&&(s&&GK(s),o&&GK(o)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&oWe(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const $K=Rs||bs&&Qie<63;function VK(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),i=r<n.childNodes.length?n.childNodes[r]:null,s=r?n.childNodes[r-1]:null;if(Rs&&i&&i.contentEditable=="false")return HD(i);if((!i||i.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(i)return HD(i);if(s)return HD(s)}}function HD(t){return t.contentEditable="true",Rs&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function GK(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function oWe(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,i=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!dse(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function lWe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,ms(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Eo&&ep<=11&&(n.disabled=!0,n.disabled=!1)}function use(t,e){if(e instanceof Mn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(WK(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else WK(t)}function WK(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function wz(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||$n.between(e,n,r)}function KK(t){return t.editable&&!t.hasFocus()?!1:mse(t)}function mse(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 cWe(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return fg(e.node,e.offset,n.anchorNode,n.anchorOffset)}function _L(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&ir.findFrom(s,e)}function yh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function XK(t,e,n){let r=t.state.selection;if(r instanceof $n)if(n.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return yh(t,new $n(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=_L(t.state,e);return i&&i instanceof Mn?yh(t,i):!1}else if(!(Bl&&n.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?Mn.isSelectable(s)?yh(t,new Mn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):vS?yh(t,new $n(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Mn&&r.node.isInline)return yh(t,new $n(e>0?r.$to:r.$from));{let i=_L(t.state,e);return i?yh(t,i):!1}}}function DC(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function k0(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Gb(t,e){return e<0?dWe(t):uWe(t)}function dWe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,s,o=!1;for(tc&&n.nodeType==1&&r<DC(n)&&k0(n.childNodes[r],-1)&&(o=!0);;)if(r>0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(k0(l,-1))i=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(hse(n))break;{let l=n.previousSibling;for(;l&&k0(l,-1);)i=n.parentNode,s=ms(l),l=l.previousSibling;if(l)n=l,r=DC(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?kL(t,n,r):i&&kL(t,i,s)}function uWe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=DC(n),s,o;for(;;)if(r<i){if(n.nodeType!=1)break;let l=n.childNodes[r];if(k0(l,1))s=n,o=++r;else break}else{if(hse(n))break;{let l=n.nextSibling;for(;l&&k0(l,1);)s=l.parentNode,o=ms(l)+1,l=l.nextSibling;if(l)n=l,r=0,i=DC(n);else{if(n=n.parentNode,n==t.dom)break;r=i=0}}}s&&kL(t,s,o)}function hse(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function mWe(t,e){for(;t&&e==t.childNodes.length&&!yS(t);)e=ms(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 hWe(t,e){for(;t&&!e&&!yS(t);)e=ms(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 kL(t,e,n){if(e.nodeType!=3){let s,o;(o=mWe(e,n))?(e=o,n=0):(s=hWe(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if($T(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:i}=t;setTimeout(()=>{t.state==i&&tm(t)},50)}function YK(t,e){let n=t.state.doc.resolve(e);if(!(bs||Zie)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o<i.bottom&&Math.abs(s.left-i.left)>1)return s.left<i.left?"ltr":"rtl"}if(e<n.end()){let s=t.coordsAtPos(e+1),o=(s.top+s.bottom)/2;if(o>i.top&&o<i.bottom&&Math.abs(s.left-i.left)>1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function QK(t,e,n){let r=t.state.selection;if(r instanceof $n&&!r.empty||n.indexOf("s")>-1||Bl&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=_L(t.state,e);if(o&&o instanceof Mn)return yh(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof cl?ir.near(o,e):ir.findFrom(o,e);return l?yh(t,l):!1}return!1}function ZK(t,e){if(!(t.state.selection instanceof $n))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)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 JK(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function pWe(t){if(!Rs||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;JK(t,r,"true"),setTimeout(()=>JK(t,r,"false"),20)}return!1}function fWe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function gWe(t,e){let n=e.keyCode,r=fWe(e);if(n==8||Bl&&n==72&&r=="c")return ZK(t,-1)||Gb(t,-1);if(n==46&&!e.shiftKey||Bl&&n==68&&r=="c")return ZK(t,1)||Gb(t,1);if(n==13||n==27)return!0;if(n==37||Bl&&n==66&&r=="c"){let i=n==37?YK(t,t.state.selection.from)=="ltr"?-1:1:-1;return XK(t,i,r)||Gb(t,i)}else if(n==39||Bl&&n==70&&r=="c"){let i=n==39?YK(t,t.state.selection.from)=="ltr"?1:-1:1;return XK(t,i,r)||Gb(t,i)}else{if(n==38||Bl&&n==80&&r=="c")return QK(t,-1,r)||Gb(t,-1);if(n==40||Bl&&n==78&&r=="c")return pWe(t)||QK(t,1,r)||Gb(t,1);if(r==(Bl?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Sz(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=t.someProp("clipboardSerializer")||Cg.fromSchema(t.state.schema),l=yse(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let d=c.firstChild,u,m=0;for(;d&&d.nodeType==1&&(u=xse[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let x=l.createElement(u[f]);for(;c.firstChild;)x.appendChild(c.firstChild);c.appendChild(x),m++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${i} ${s}${m?` -${m}`:""} ${JSON.stringify(n)}`);let p=t.someProp("clipboardTextSerializer",f=>f(e,t))||e.content.textBetween(0,e.content.size,`
- `);return{dom:c,text:p,slice:e}}function pse(t,e,n,r,i){let s=i.parent.type.spec.code,o,l;if(!n&&!e)return null;let c=!!e&&(r||s||!n);if(c){if(t.someProp("transformPastedText",p=>{e=p(e,s||r,t)}),s)return l=new cn(Vt.from(t.state.schema.text(e.replace(/\r\n?/g,`
- `))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let m=t.someProp("clipboardTextParser",p=>p(e,i,r,t));if(m)l=m;else{let p=i.marks(),{schema:f}=t.state,x=Cg.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let g=o.appendChild(document.createElement("p"));v&&g.appendChild(x.serializeNode(f.text(v,p)))})}}else t.someProp("transformPastedHTML",m=>{n=m(n,t)}),o=vWe(n),vS&&wWe(o);let d=o&&o.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let m=+u[3];m>0;m--){let p=o.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;o=p}if(l||(l=(t.someProp("clipboardParser")||t.someProp("domParser")||w0.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:i,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!bWe.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)l=SWe(eX(l,+u[1],+u[2]),u[4]);else if(l=cn.maxOpen(xWe(l.content,i),!0),l.openStart||l.openEnd){let m=0,p=0;for(let f=l.content.firstChild;m<l.openStart&&!f.type.spec.isolating;m++,f=f.firstChild);for(let f=l.content.lastChild;p<l.openEnd&&!f.type.spec.isolating;p++,f=f.lastChild);l=eX(l,m,p)}return t.someProp("transformPasted",m=>{l=m(l,t,c)}),l}const bWe=/^(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 xWe(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let i=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=i.findWrapping(l.type),d;if(!c)return o=null;if(d=o.length&&s.length&&gse(c,s,l,o[o.length-1],0))o[o.length-1]=d;else{o.length&&(o[o.length-1]=bse(o[o.length-1],s.length));let u=fse(l,c);o.push(u),i=i.matchType(u.type),s=c}}),o)return Vt.from(o)}return t}function fse(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,Vt.from(t));return t}function gse(t,e,n,r,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let s=gse(t,e,n,r.lastChild,i+1);if(s)return r.copy(r.content.replaceChild(r.childCount-1,s));if(r.contentMatchAt(r.childCount).matchType(i==t.length-1?n.type:t[i+1]))return r.copy(r.content.append(Vt.from(fse(n,t,i+1))))}}function bse(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,bse(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(Vt.empty,!0);return t.copy(n.append(r))}function NL(t,e,n,r,i,s){let o=e<0?t.firstChild:t.lastChild,l=o.content;return t.childCount>1&&(s=0),i<r-1&&(l=NL(l,e,n,r,i+1,s)),i>=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(Vt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function eX(t,e,n){return e<t.openStart&&(t=new cn(NL(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new cn(NL(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const xse={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 tX=null;function yse(){return tX||(tX=document.implementation.createHTMLDocument("title"))}let qD=null;function yWe(t){let e=window.trustedTypes;return e?(qD||(qD=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),qD.createHTML(t)):t}function vWe(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=yse().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),i;if((i=r&&xse[r[1].toLowerCase()])&&(t=i.map(s=>"<"+s+">").join("")+t+i.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=yWe(t),i)for(let s=0;s<i.length;s++)n=n.querySelector(i[s])||n;return n}function wWe(t){let e=t.querySelectorAll(bs?"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 SWe(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:i,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;i=Vt.from(c.create(r[l+1],i)),s++,o++}return new cn(i,s,o)}const so={},oo={},_We={touchstart:!0,touchmove:!0};class kWe{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 NWe(t){for(let e in so){let n=so[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{PWe(t,r)&&!_z(t,r)&&(t.editable||!(r.type in oo))&&n(t,r)},_We[e]?{passive:!0}:void 0)}Rs&&t.dom.addEventListener("input",()=>null),CL(t)}function Ih(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function CWe(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 CL(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>_z(t,r))})}function _z(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function PWe(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 TWe(t,e){!_z(t,e)&&so[e.type]&&(t.editable||!(e.type in oo))&&so[e.type](t,e)}oo.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!wse(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Gu&&bs&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Qx&&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",i=>i(t,bf(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||gWe(t,n)?n.preventDefault():Ih(t,"key")};oo.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};oo.keypress=(t,e)=>{let n=e;if(wse(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Bl&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof $n)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,i,s))&&t.dispatch(s()),n.preventDefault()}};function GT(t){return{left:t.clientX,top:t.clientY}}function AWe(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function kz(t,e,n,r,i){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),i,!0):l(t,n,s.node(o),s.before(o),i,!1)))return!0;return!1}function _x(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 jWe(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&Mn.isSelectable(r)?(_x(t,new Mn(n)),!0):!1}function MWe(t,e){if(e==-1)return!1;let n=t.state.selection,r,i;n instanceof Mn&&(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(Mn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?i=s.before(n.$from.depth):i=s.before(o);break}}return i!=null?(_x(t,Mn.create(t.state.doc,i)),!0):!1}function EWe(t,e,n,r,i){return kz(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(i?MWe(t,n):jWe(t,n))}function DWe(t,e,n,r){return kz(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",i=>i(t,e,r))}function FWe(t,e,n,r){return kz(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",i=>i(t,e,r))||RWe(t,n,r)}function RWe(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(_x(t,$n.create(r,0,r.content.size)),!0):!1;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)_x(t,$n.create(r,l+1,l+1+o.content.size));else if(Mn.isSelectable(o))_x(t,Mn.create(r,l));else continue;return!0}}function Nz(t){return FC(t)}const vse=Bl?"metaKey":"ctrlKey";so.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Nz(t),i=Date.now(),s="singleClick";i-t.input.lastClick.time<500&&AWe(n,t.input.lastClick)&&!n[vse]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:i,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(GT(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new LWe(t,o,n,!!r)):(s=="doubleClick"?DWe:FWe)(t,o.pos,o.inside,n)?n.preventDefault():Ih(t,"pointer"))};class LWe{constructor(e,n,r,i){this.view=e,this.pos=n,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[vse],this.allowDefault=r.shiftKey;let s,o;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),o=n.inside;else{let u=e.state.doc.resolve(n.pos);s=u.parent,o=u.depth?u.before():0}const l=i?null:r.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||d instanceof Mn&&d.from<=o&&d.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&tc&&!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)),Ih(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(()=>tm(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(GT(e))),this.updateAllowDefault(e),this.allowDefault||!n?Ih(this.view,"pointer"):EWe(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Rs&&this.mightDrag&&!this.mightDrag.node.isAtom||bs&&!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)?(_x(this.view,ir.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):Ih(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ih(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)}}so.touchstart=t=>{t.input.lastTouch=Date.now(),Nz(t),Ih(t,"pointer")};so.touchmove=t=>{t.input.lastTouch=Date.now(),Ih(t,"pointer")};so.contextmenu=t=>Nz(t);function wse(t,e){return t.composing?!0:Rs&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const OWe=Gu?5e3:-1;oo.compositionstart=oo.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof $n&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||bs&&Zie&&IWe(t)))t.markCursor=t.state.storedMarks||n.marks(),FC(t,!0),t.markCursor=null;else if(FC(t,!e.selection.empty),tc&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}t.input.composing=!0}Sse(t,OWe)};function IWe(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"}oo.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++,Sse(t,20))};function Sse(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>FC(t),e))}function _se(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=UWe());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function zWe(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=M9e(e.focusNode,e.focusOffset),r=E9e(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let i=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!i||!i.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 UWe(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function FC(t,e=!1){if(!(Gu&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),_se(t),e||t.docView&&t.docView.dirty){let n=vz(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 BWe(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(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const vw=Eo&&ep<15||Qx&&L9e<604;so.copy=oo.cut=(t,e)=>{let n=e,r=t.state.selection,i=n.type=="cut";if(r.empty)return;let s=vw?null:n.clipboardData,o=r.content(),{dom:l,text:c}=Sz(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):BWe(t,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function HWe(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function qWe(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 i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?ww(t,r.value,null,i,e):ww(t,r.textContent,r.innerHTML,i,e)},50)}function ww(t,e,n,r,i){let s=pse(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,i,s||cn.empty)))return!0;if(!s)return!1;let o=HWe(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 kse(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," "):""}oo.paste=(t,e)=>{let n=e;if(t.composing&&!Gu)return;let r=vw?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&ww(t,kse(r),r.getData("text/html"),i,n)?n.preventDefault():qWe(t,n)};class Nse{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const $We=Bl?"altKey":"ctrlKey";function Cse(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[$We]}so.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let i=t.state.selection,s=i.empty?null:t.posAtCoords(GT(n)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof Mn?i.to-1:i.to))){if(r&&r.mightDrag)o=Mn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let m=t.docView.nearestDesc(n.target,!0);m&&m.node.type.spec.draggable&&m!=t.docView&&(o=Mn.create(t.state.doc,m.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:d,slice:u}=Sz(t,l);(!n.dataTransfer.files.length||!bs||Qie>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(vw?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",vw||n.dataTransfer.setData("text/plain",d),t.dragging=new Nse(u,Cse(t,n),o)};so.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};oo.dragover=oo.dragenter=(t,e)=>e.preventDefault();oo.drop=(t,e)=>{try{VWe(t,e,t.dragging)}finally{t.dragging=null}};function VWe(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(GT(e));if(!r)return;let i=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",f=>{s=f(s,t,!1)}):s=pse(t,kse(e.dataTransfer),vw?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(n&&Cse(t,e));if(t.someProp("handleDrop",f=>f(t,e,s||cn.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?jie(t.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let c=t.state.tr;if(o){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(l),u=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,m=c.doc;if(u?c.replaceRangeWith(d,d,s.content.firstChild):c.replaceRange(d,d,s),c.doc.eq(m))return;let p=c.doc.resolve(d);if(u&&Mn.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new Mn(p));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((x,v,g,b)=>f=b),c.setSelection(wz(t,p,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}so.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())&&tm(t)},20))};so.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)};so.beforeinput=(t,e)=>{if(bs&&Gu&&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,bf(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let t in oo)so[t]=oo[t];function Sw(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 RC{constructor(e,n){this.toDOM=e,this.spec=n||Bf,this.side=this.spec.side||0}map(e,n,r,i){let{pos:s,deleted:o}=e.mapResult(n.from+i,this.side<0?-1:1);return o?null:new Ys(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof RC&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Sw(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class np{constructor(e,n){this.attrs=e,this.spec=n||Bf}map(e,n,r,i){let s=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new Ys(s,o,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof np&&Sw(this.attrs,e.attrs)&&Sw(this.spec,e.spec)}static is(e){return e.type instanceof np}destroy(){}}class Cz{constructor(e,n){this.attrs=e,this.spec=n||Bf}map(e,n,r,i){let s=e.mapResult(n.from+i,1);if(s.deleted)return null;let o=e.mapResult(n.to+i,-1);return o.deleted||o.pos<=s.pos?null:new Ys(s.pos-r,o.pos-r,this)}valid(e,n){let{index:r,offset:i}=e.content.findIndex(n.from),s;return i==n.from&&!(s=e.child(r)).isText&&i+s.nodeSize==n.to}eq(e){return this==e||e instanceof Cz&&Sw(this.attrs,e.attrs)&&Sw(this.spec,e.spec)}destroy(){}}class Ys{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new Ys(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 Ys(e,e,new RC(n,r))}static inline(e,n,r,i){return new Ys(e,n,new np(r,i))}static node(e,n,r,i){return new Ys(e,n,new Cz(r,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof np}get widget(){return this.type instanceof RC}}const ex=[],Bf={};class Aa{constructor(e,n){this.local=e.length?e:ex,this.children=n.length?n:ex}static create(e,n){return n.length?LC(n,e,0,Bf):Ts}find(e,n,r){let i=[];return this.findInner(e??0,n??1e9,i,0,r),i}findInner(e,n,r,i,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+i,l.to+i))}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,i+l,s)}}map(e,n,r){return this==Ts||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Bf)}mapInner(e,n,r,i,s){let o;for(let l=0;l<this.local.length;l++){let c=this.local[l].map(e,r,i);c&&c.type.valid(n,c)?(o||(o=[])).push(c):s.onRemove&&s.onRemove(this.local[l].spec)}return this.children.length?GWe(this.children,o||[],e,n,r,i,s):o?new Aa(o.sort(Hf),ex):Ts}add(e,n){return n.length?this==Ts?Aa.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let i,s=0;e.forEach((l,c)=>{let d=c+r,u;if(u=Tse(n,l,d)){for(i||(i=this.children.slice());s<i.length&&i[s]<c;)s+=3;i[s]==c?i[s+2]=i[s+2].addInner(l,u,d+1):i.splice(s,0,c,c+l.nodeSize,LC(u,l,d+1,Bf)),s+=3}});let o=Pse(s?Ase(n):n,-r);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||o.splice(l--,1);return new Aa(o.length?this.local.concat(o).sort(Hf):this.local,i||this.children)}remove(e){return e.length==0||this==Ts?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,i=this.local;for(let s=0;s<r.length;s+=3){let o,l=r[s]+n,c=r[s+1]+n;for(let u=0,m;u<e.length;u++)(m=e[u])&&m.from>l&&m.to<c&&(e[u]=null,(o||(o=[])).push(m));if(!o)continue;r==this.children&&(r=this.children.slice());let d=r[s+2].removeInner(o,l+1);d!=Ts?r[s+2]=d:(r.splice(s,3),s-=3)}if(i.length){for(let s=0,o;s<e.length;s++)if(o=e[s])for(let l=0;l<i.length;l++)i[l].eq(o,n)&&(i==this.local&&(i=this.local.slice()),i.splice(l--,1))}return r==this.children&&i==this.local?this:i.length||r.length?new Aa(i,r):Ts}forChild(e,n){if(this==Ts)return this;if(n.isLeaf)return Aa.empty;let r,i;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 np){let d=Math.max(s,c.from)-s,u=Math.min(o,c.to)-s;d<u&&(i||(i=[])).push(c.copy(d,u))}}if(i){let l=new Aa(i.sort(Hf),ex);return r?new Nh([l,r]):l}return r||Ts}eq(e){if(this==e)return!0;if(!(e instanceof Aa)||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 Pz(this.localsInner(e))}localsInner(e){if(this==Ts)return ex;if(e.inlineContent||!this.local.some(np.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof np||n.push(this.local[r]);return n}forEachSet(e){e(this)}}Aa.empty=new Aa([],[]);Aa.removeOverlap=Pz;const Ts=Aa.empty;class Nh{constructor(e){this.members=e}map(e,n){const r=this.members.map(i=>i.map(e,n,Bf));return Nh.from(r)}forChild(e,n){if(n.isLeaf)return Aa.empty;let r=[];for(let i=0;i<this.members.length;i++){let s=this.members[i].forChild(e,n);s!=Ts&&(s instanceof Nh?r=r.concat(s.members):r.push(s))}return Nh.from(r)}eq(e){if(!(e instanceof Nh)||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 i=0;i<this.members.length;i++){let s=this.members[i].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?Pz(r?n:n.sort(Hf)):ex}static from(e){switch(e.length){case 0:return Ts;case 1:return e[0];default:return new Nh(e.every(n=>n instanceof Aa)?e:e.reduce((n,r)=>n.concat(r instanceof Aa?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function GWe(t,e,n,r,i,s,o){let l=t.slice();for(let d=0,u=s;d<n.maps.length;d++){let m=0;n.maps[d].forEach((p,f,x,v)=>{let g=v-x-(f-p);for(let b=0;b<l.length;b+=3){let _=l[b+1];if(_<0||p>_+u-m)continue;let C=l[b]+u-m;f>=C?l[b+1]=p<=C?-2:-1:p>=u&&g&&(l[b]+=g,l[b+1]+=g)}m+=g}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d<l.length;d+=3)if(l[d+1]<0){if(l[d+1]==-2){c=!0,l[d+1]=-1;continue}let u=n.map(t[d]+s),m=u-i;if(m<0||m>=r.content.size){c=!0;continue}let p=n.map(t[d+1]+s,-1),f=p-i,{index:x,offset:v}=r.content.findIndex(m),g=r.maybeChild(x);if(g&&v==m&&v+g.nodeSize==f){let b=l[d+2].mapInner(n,g,u+1,t[d]+s+1,o);b!=Ts?(l[d]=m,l[d+1]=f,l[d+2]=b):(l[d+1]=-2,c=!0)}else c=!0}if(c){let d=WWe(l,t,e,n,i,s,o),u=LC(d,r,0,o);e=u.local;for(let m=0;m<l.length;m+=3)l[m+1]<0&&(l.splice(m,3),m-=3);for(let m=0,p=0;m<u.children.length;m+=3){let f=u.children[m];for(;p<l.length&&l[p]<f;)p+=3;l.splice(p,0,u.children[m],u.children[m+1],u.children[m+2])}}return new Aa(e.sort(Hf),l)}function Pse(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let i=t[r];n.push(new Ys(i.from+e,i.to+e,i.type))}return n}function WWe(t,e,n,r,i,s,o){function l(c,d){for(let u=0;u<c.local.length;u++){let m=c.local[u].map(r,i,d);m?n.push(m):o.onRemove&&o.onRemove(c.local[u].spec)}for(let u=0;u<c.children.length;u+=3)l(c.children[u+2],c.children[u]+d+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 Tse(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,i=null;for(let s=0,o;s<t.length;s++)(o=t[s])&&o.from>n&&o.to<r&&((i||(i=[])).push(o),t[s]=null);return i}function Ase(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function LC(t,e,n,r){let i=[],s=!1;e.forEach((l,c)=>{let d=Tse(t,l,c+n);if(d){s=!0;let u=LC(d,l,n+c+1,r);u!=Ts&&i.push(c,c+l.nodeSize,u)}});let o=Pse(s?Ase(t):t,-n).sort(Hf);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||i.length?new Aa(o,i):Ts}function Hf(t,e){return t.from-e.from||t.to-e.to}function Pz(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let i=n+1;i<e.length;i++){let s=e[i];if(s.from==r.from){s.to!=r.to&&(e==t&&(e=t.slice()),e[i]=s.copy(s.from,r.to),nX(e,i+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),nX(e,i,r.copy(s.from,r.to)));break}}}return e}function nX(t,e,n){for(;e<t.length&&Hf(n,t[e])>0;)e++;t.splice(e,0,n)}function $D(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Ts&&e.push(r)}),t.cursorWrapper&&e.push(Aa.create(t.state.doc,[t.cursorWrapper.deco])),Nh.from(e)}const KWe={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},XWe=Eo&&ep<=11;class YWe{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 QWe{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new YWe,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;i<r.length;i++)this.queue.push(r[i]);Eo&&ep<=11&&r.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Rs&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),XWe&&(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,KWe)),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(KK(this.view)){if(this.suppressingSelectionUpdates)return tm(this.view);if(Eo&&ep<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&fg(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=Yx(s))n.add(s);for(let s=e.anchorNode;s;s=Yx(s))if(n.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.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(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&KK(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let u=0;u<n.length;u++){let m=this.registerMutation(n[u],c);m&&(s=s<0?m.from:Math.min(m.from,s),o=o<0?m.to:Math.max(m.to,o),m.typeOver&&(l=!0))}if(c.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let m=u.nextSibling;m&&m.nodeType==1&&m.contentEditable=="false"&&u.parentNode.removeChild(u)}}else if(tc&&c.length){let u=c.filter(m=>m.nodeName=="BR");if(u.length==2){let[m,p]=u;m.parentNode&&m.parentNode.parentNode==p.parentNode?p.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let p of u){let f=p.parentNode;f&&f.nodeName=="LI"&&(!m||eKe(e,m)!=f)&&p.remove()}}}let d=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&$T(r)&&(d=vz(e))&&d.eq(ir.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,tm(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||i)&&(s>-1&&(e.docView.markDirty(s,o),ZWe(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,tKe(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||tm(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 u=0;u<e.addedNodes.length;u++){let m=e.addedNodes[u];n.push(m),m.nodeType==3&&(this.lastChangedTextNode=m)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let i=e.previousSibling,s=e.nextSibling;if(Eo&&ep<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:m,nextSibling:p}=e.addedNodes[u];(!m||Array.prototype.indexOf.call(e.addedNodes,m)<0)&&(i=m),(!p||Array.prototype.indexOf.call(e.addedNodes,p)<0)&&(s=p)}let o=i&&i.parentNode==e.target?ms(i)+1:0,l=r.localPosFromDOM(e.target,o,-1),c=s&&s.parentNode==e.target?ms(s):e.target.childNodes.length,d=r.localPosFromDOM(e.target,c,1);return{from:l,to:d}}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 rX=new WeakMap,aX=!1;function ZWe(t){if(!rX.has(t)&&(rX.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=tc,aX)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."),aX=!0}}function iX(t,e){let n=e.startContainer,r=e.startOffset,i=e.endContainer,s=e.endOffset,o=t.domAtPos(t.state.selection.anchor);return fg(o.node,o.offset,i,s)&&([n,r,i,s]=[i,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:s}}function JWe(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return iX(t,i)}let n;function r(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?iX(t,n):null}function eKe(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 tKe(t,e){var n;let{focusNode:r,focusOffset:i}=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,i)}else s.parentNode.removeChild(s)}}function nKe(t,e,n){let{node:r,fromOffset:i,toOffset:s,from:o,to:l}=t.docView.parseRange(e,n),c=t.domSelectionRange(),d,u=c.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(d=[{node:u,offset:c.anchorOffset}],$T(c)||d.push({node:c.focusNode,offset:c.focusOffset})),bs&&t.input.lastKeyCode===8)for(let g=s;g>i;g--){let b=r.childNodes[g-1],_=b.pmViewDesc;if(b.nodeName=="BR"&&!_){s=g;break}if(!_||_.size)break}let m=t.state.doc,p=t.someProp("domParser")||w0.fromSchema(t.state.schema),f=m.resolve(o),x=null,v=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:i,to:s,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:rKe,context:f});if(d&&d[0].pos!=null){let g=d[0].pos,b=d[1]&&d[1].pos;b==null&&(b=g),x={anchor:g+o,head:b+o}}return{doc:v,sel:x,from:o,to:l}}function rKe(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Rs&&/^(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||Rs&&/^(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 aKe=/^(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 iKe(t,e,n,r,i){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,F=vz(t,T);if(F&&!t.state.selection.eq(F)){if(bs&&Gu&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",D=>D(t,bf(13,"Enter"))))return;let k=t.state.tr.setSelection(F);T=="pointer"?k.setMeta("pointer",!0):T=="key"&&k.scrollIntoView(),s&&k.setMeta("composition",s),t.dispatch(k)}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,d=nKe(t,e,n),u=t.state.doc,m=u.slice(d.from,d.to),p,f;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(p=t.state.selection.to,f="end"):(p=t.state.selection.from,f="start"),t.input.lastKeyCode=null;let x=lKe(m.content,d.doc.content,d.from,p,f);if(x&&t.input.domChangeCount++,(Qx&&t.input.lastIOSEnter>Date.now()-225||Gu)&&i.some(T=>T.nodeType==1&&!aKe.test(T.nodeName))&&(!x||x.endA>=x.endB)&&t.someProp("handleKeyDown",T=>T(t,bf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!x)if(r&&c instanceof $n&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))x={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let T=sX(t,t.state.doc,d.sel);if(T&&!T.eq(t.state.selection)){let F=t.state.tr.setSelection(T);s&&F.setMeta("composition",s),t.dispatch(F)}}return}t.state.selection.from<t.state.selection.to&&x.start==x.endB&&t.state.selection instanceof $n&&(x.start>t.state.selection.from&&x.start<=t.state.selection.from+2&&t.state.selection.from>=d.from?x.start=t.state.selection.from:x.endA<t.state.selection.to&&x.endA>=t.state.selection.to-2&&t.state.selection.to<=d.to&&(x.endB+=t.state.selection.to-x.endA,x.endA=t.state.selection.to)),Eo&&ep<=11&&x.endB==x.start+1&&x.endA==x.start&&x.start>d.from&&d.doc.textBetween(x.start-d.from-1,x.start-d.from+1)==" "&&(x.start--,x.endA--,x.endB--);let v=d.doc.resolveNoCache(x.start-d.from),g=d.doc.resolveNoCache(x.endB-d.from),b=u.resolve(x.start),_=v.sameParent(g)&&v.parent.inlineContent&&b.end()>=x.endA;if((Qx&&t.input.lastIOSEnter>Date.now()-225&&(!_||i.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!_&&v.pos<d.doc.content.size&&(!v.sameParent(g)||!v.parent.inlineContent)&&v.pos<g.pos&&!/\S/.test(d.doc.textBetween(v.pos,g.pos,"","")))&&t.someProp("handleKeyDown",T=>T(t,bf(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>x.start&&oKe(u,x.start,x.endA,v,g)&&t.someProp("handleKeyDown",T=>T(t,bf(8,"Backspace")))){Gu&&bs&&t.domObserver.suppressSelectionUpdates();return}bs&&x.endB==x.start&&(t.input.lastChromeDelete=Date.now()),Gu&&!_&&v.start()!=g.start()&&g.parentOffset==0&&v.depth==g.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==x.endA&&(x.endB-=2,g=d.doc.resolveNoCache(x.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,bf(13,"Enter"))})},20));let C=x.start,P=x.endA,N=T=>{let F=T||t.state.tr.replace(C,P,d.doc.slice(x.start-d.from,x.endB-d.from));if(d.sel){let k=sX(t,F.doc,d.sel);k&&!(bs&&t.composing&&k.empty&&(x.start!=x.endB||t.input.lastChromeDelete<Date.now()-100)&&(k.head==C||k.head==F.mapping.map(P)-1)||Eo&&k.empty&&k.head==C)&&F.setSelection(k)}return s&&F.setMeta("composition",s),F.scrollIntoView()},A;if(_)if(v.pos==g.pos){Eo&&ep<=11&&v.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>tm(t),20));let T=N(t.state.tr.delete(C,P)),F=u.resolve(x.start).marksAcross(u.resolve(x.endA));F&&T.ensureMarks(F),t.dispatch(T)}else if(x.endA==x.endB&&(A=sKe(v.parent.content.cut(v.parentOffset,g.parentOffset),b.parent.content.cut(b.parentOffset,x.endA-b.start())))){let T=N(t.state.tr);A.type=="add"?T.addMark(C,P,A.mark):T.removeMark(C,P,A.mark),t.dispatch(T)}else if(v.parent.child(v.index()).isText&&v.index()==g.index()-(g.textOffset?0:1)){let T=v.parent.textBetween(v.parentOffset,g.parentOffset),F=()=>N(t.state.tr.insertText(T,C,P));t.someProp("handleTextInput",k=>k(t,C,P,T,F))||t.dispatch(F())}else t.dispatch(N());else t.dispatch(N())}function sX(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:wz(t,e.resolve(n.anchor),e.resolve(n.head))}function sKe(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,i=n,s=r,o,l,c;for(let u=0;u<r.length;u++)i=r[u].removeFromSet(i);for(let u=0;u<n.length;u++)s=n[u].removeFromSet(s);if(i.length==1&&s.length==0)l=i[0],o="add",c=u=>u.mark(l.addToSet(u.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",c=u=>u.mark(l.removeFromSet(u.marks));else return null;let d=[];for(let u=0;u<e.childCount;u++)d.push(c(e.child(u)));if(Vt.from(d).eq(t))return{mark:l,type:o}}function oKe(t,e,n,r,i){if(n-e<=i.pos-r.pos||VD(r,!0,!1)<i.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(VD(s,!0,!0));return!o.parent.isTextblock||o.pos>n||VD(o,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(o.parent.content)}function VD(t,e,n){let r=t.depth,i=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,i++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function lKe(t,e,n,r,i){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(i=="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&&oX(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&&oX(t.textBetween(s-1,s+1))&&(s+=c?1:-1),o=s+(o-l),l=s}return{start:s,endA:o,endB:l}}function oX(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 jse{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 kWe,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(mX),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=dX(this),cX(this),this.nodeViews=uX(this),this.docView=HK(this.state.doc,lX(this),$D(this),this.dom,this),this.domObserver=new QWe(this,(r,i,s,o)=>iKe(this,r,i,s,o)),this.domObserver.start(),NWe(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&&CL(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(mX),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 i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(_se(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=uX(this);dKe(f,this.nodeViews)&&(this.nodeViews=f,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&CL(this),this.editable=dX(this),cX(this);let c=$D(this),d=lX(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",m=s||!this.docView.matchesNode(e.doc,d,c);(m||!e.selection.eq(i.selection))&&(o=!0);let p=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&z9e(this);if(o){this.domObserver.stop();let f=m&&(Eo||bs)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&cKe(i.selection,e.selection);if(m){let x=bs?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=zWe(this)),(s||!this.docView.update(e.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=HK(e.doc,d,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&cWe(this))?tm(this,f):(use(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():p&&U9e(p)}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 Mn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&LK(this,n.getBoundingClientRect(),e)}else LK(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,i=-1;if(this.state.doc.nodeAt(r.from)==r.node)i=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&&(i=s)}this.dragging=new Nse(e.slice,e.move,i<0?void 0:Mn.create(this.state.doc,i))}someProp(e,n){let r=this._props&&this._props[e],i;if(r!=null&&(i=n?n(r):r))return i;for(let o=0;o<this.directPlugins.length;o++){let l=this.directPlugins[o].props[e];if(l!=null&&(i=n?n(l):l))return i}let s=this.state.plugins;if(s)for(let o=0;o<s.length;o++){let l=s[o].props[e];if(l!=null&&(i=n?n(l):l))return i}}hasFocus(){if(Eo){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&&B9e(this.dom),tm(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 G9e(this,e)}coordsAtPos(e,n=1){return rse(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 i=this.docView.posFromDOM(e,n,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return Q9e(this,n||this.state,e)}pasteHTML(e,n){return ww(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return ww(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return Sz(this,e)}destroy(){this.docView&&(CWe(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],$D(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,A9e())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return TWe(this,e)}domSelectionRange(){let e=this.domSelection();return e?Rs&&this.root.nodeType===11&&F9e(this.dom.ownerDocument)==this.dom&&JWe(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}jse.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function lX(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"),[Ys.node(0,t.state.doc.content.size,e)]}function cX(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:Ys.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function dX(t){return!t.someProp("editable",e=>e(t.state)===!1)}function cKe(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 uX(t){let e=Object.create(null);function n(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function dKe(t,e){let n=0,r=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)r++;return n!=r}function mX(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 mp={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:"'"},OC={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uKe=typeof navigator<"u"&&/Mac/.test(navigator.platform),mKe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var hs=0;hs<10;hs++)mp[48+hs]=mp[96+hs]=String(hs);for(var hs=1;hs<=24;hs++)mp[hs+111]="F"+hs;for(var hs=65;hs<=90;hs++)mp[hs]=String.fromCharCode(hs+32),OC[hs]=String.fromCharCode(hs);for(var GD in mp)OC.hasOwnProperty(GD)||(OC[GD]=mp[GD]);function hKe(t){var e=uKe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||mKe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?OC:mp)[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 pKe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),fKe=typeof navigator<"u"&&/Win/.test(navigator.platform);function gKe(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,i,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))i=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))pKe?o=!0:i=!0;else throw new Error("Unrecognized modifier name: "+c)}return r&&(n="Alt-"+n),i&&(n="Ctrl-"+n),o&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function bKe(t){let e=Object.create(null);for(let n in t)e[gKe(n)]=t[n];return e}function WD(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 xKe(t){return new Ra({props:{handleKeyDown:Mse(t)}})}function Mse(t){let e=bKe(t);return function(n,r){let i=hKe(r),s,o=e[WD(i,r)];if(o&&o(n.state,n.dispatch,n))return!0;if(i.length==1&&i!=" "){if(r.shiftKey){let l=e[WD(i,r,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(fKe&&r.ctrlKey&&r.altKey)&&(s=mp[r.keyCode])&&s!=i){let l=e[WD(s,r)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var yKe=Object.defineProperty,Tz=(t,e)=>{for(var n in e)yKe(t,n,{get:e[n],enumerable:!0})};function WT(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:i}=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 i},get tr(){return r=n.selection,i=n.doc,s=n.storedMarks,n}}}var KT=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:i}=n,s=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...d)=>{const u=l(...d)(s);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(i),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o=[],l=!!t,c=t||i.tr,d=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(m=>m===!0)),u={...Object.fromEntries(Object.entries(n).map(([m,p])=>[m,(...x)=>{const v=this.buildProps(c,e),g=p(...x)(v);return o.push(g),u}])),run:d};return u}createCan(t){const{rawCommands:e,state:n}=this,r=!1,i=t||n.tr,s=this.buildProps(i,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...d)=>c(...d)({...s,dispatch:void 0})])),chain:()=>this.createChain(i,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:i}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:WT({state:i,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,(...d)=>c(...d)(o)]))}};return o}},Ese={};Tz(Ese,{blur:()=>vKe,clearContent:()=>wKe,clearNodes:()=>SKe,command:()=>_Ke,createParagraphNear:()=>kKe,cut:()=>NKe,deleteCurrentNode:()=>CKe,deleteNode:()=>PKe,deleteRange:()=>TKe,deleteSelection:()=>AKe,enter:()=>jKe,exitCode:()=>MKe,extendMarkRange:()=>EKe,first:()=>DKe,focus:()=>RKe,forEach:()=>LKe,insertContent:()=>OKe,insertContentAt:()=>UKe,joinBackward:()=>qKe,joinDown:()=>HKe,joinForward:()=>$Ke,joinItemBackward:()=>VKe,joinItemForward:()=>GKe,joinTextblockBackward:()=>WKe,joinTextblockForward:()=>KKe,joinUp:()=>BKe,keyboardShortcut:()=>YKe,lift:()=>QKe,liftEmptyBlock:()=>ZKe,liftListItem:()=>JKe,newlineInCode:()=>eXe,resetAttributes:()=>tXe,scrollIntoView:()=>nXe,selectAll:()=>rXe,selectNodeBackward:()=>aXe,selectNodeForward:()=>iXe,selectParentNode:()=>sXe,selectTextblockEnd:()=>oXe,selectTextblockStart:()=>lXe,setContent:()=>cXe,setMark:()=>AXe,setMeta:()=>jXe,setNode:()=>MXe,setNodeSelection:()=>EXe,setTextDirection:()=>DXe,setTextSelection:()=>FXe,sinkListItem:()=>RXe,splitBlock:()=>LXe,splitListItem:()=>OXe,toggleList:()=>IXe,toggleMark:()=>zXe,toggleNode:()=>UXe,toggleWrap:()=>BXe,undoInputRule:()=>HXe,unsetAllMarks:()=>qXe,unsetMark:()=>$Xe,unsetTextDirection:()=>VXe,updateAttributes:()=>GXe,wrapIn:()=>WXe,wrapInList:()=>KXe});var vKe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),wKe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),SKe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:i}=r;return n&&i.forEach(({$from:s,$to:o})=>{t.doc.nodesBetween(s.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:d,mapping:u}=e,m=d.resolve(u.map(c)),p=d.resolve(u.map(c+l.nodeSize)),f=m.blockRange(p);if(!f)return;const x=Ny(f);if(l.type.isTextblock){const{defaultType:v}=m.parent.contentMatchAt(m.index());e.setNodeMarkup(f.start,v)}(x||x===0)&&e.lift(f,x)})}),!0},_Ke=t=>e=>t(e),kKe=()=>({state:t,dispatch:e})=>Gie(t,e),NKe=(t,e)=>({editor:n,tr:r})=>{const{state:i}=n,s=i.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 $n(r.doc.resolve(Math.max(o-1,0)))),!0},CKe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const i=t.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const l=i.before(s),c=i.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function bi(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 PKe=t=>({tr:e,state:n,dispatch:r})=>{const i=bi(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const c=s.before(o),d=s.after(o);e.delete(c,d).scrollIntoView()}return!0}return!1},TKe=t=>({tr:e,dispatch:n})=>{const{from:r,to:i}=t;return n&&e.delete(r,i),!0},AKe=()=>({state:t,dispatch:e})=>pz(t,e),jKe=()=>({commands:t})=>t.keyboardShortcut("Enter"),MKe=()=>({state:t,dispatch:e})=>p9e(t,e);function Az(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function IC(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>n.strict?e[i]===t[i]:Az(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function Dse(t,e,n={}){return t.find(r=>r.type===e&&IC(Object.fromEntries(Object.keys(n).map(i=>[i,r.attrs[i]])),n))}function hX(t,e,n={}){return!!Dse(t,e,n)}function jz(t,e,n){var r;if(!t||!e)return;let i=t.parent.childAfter(t.parentOffset);if((!i.node||!i.node.marks.some(u=>u.type===e))&&(i=t.parent.childBefore(t.parentOffset)),!i.node||!i.node.marks.some(u=>u.type===e)||(n=n||((r=i.node.marks[0])==null?void 0:r.attrs),!Dse([...i.node.marks],e,n)))return;let o=i.index,l=t.start()+i.offset,c=o+1,d=l+i.node.nodeSize;for(;o>0&&hX([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c<t.parent.childCount&&hX([...t.parent.child(c).marks],e,n);)d+=t.parent.child(c).nodeSize,c+=1;return{from:l,to:d}}function Sm(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 EKe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const s=Sm(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:d,to:u}=l;if(i){const m=jz(c,s,e);if(m&&m.from<=d&&m.to>=u){const p=$n.create(o,m.from,m.to);n.setSelection(p)}}return!0},DKe=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 Fse(t){return t instanceof $n}function jf(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function Rse(t,e=null){if(!e)return null;const n=ir.atStart(t),r=ir.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const i=n.from,s=r.to;return e==="all"?$n.create(t,jf(0,i,s),jf(t.content.size,i,s)):$n.create(t,jf(e,i,s),jf(e,i,s))}function pX(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function zC(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function FKe(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var RKe=(t=null,e={})=>({editor:n,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(zC()||pX())&&r.dom.focus(),FKe()&&!zC()&&!pX()&&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&&!Fse(n.state.selection))return o(),!0;const l=Rse(i.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||i.setSelection(l),c&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},LKe=(t,e)=>n=>t.every((r,i)=>e(r,{...n,index:i})),OKe=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Lse=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&&Lse(r)}return t};function ik(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 Lse(n)}function _w(t,e,n){if(t instanceof zc||t instanceof Vt)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,i=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return Vt.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),_w("",e,n)}if(i){if(n.errorOnInvalidContent){let o=!1,l="";const c=new yie({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:d=>(o=!0,l=typeof d=="string"?d:d.outerHTML,null)}]}})});if(n.slice?w0.fromSchema(c).parseSlice(ik(t),n.parseOptions):w0.fromSchema(c).parse(ik(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=w0.fromSchema(e);return n.slice?s.parseSlice(ik(t),n.parseOptions).content:s.parse(ik(t),n.parseOptions)}return _w("",e,n)}function IKe(t,e,n){const r=t.steps.length-1;if(r<e)return;const i=t.steps[r];if(!(i instanceof Ui||i instanceof Hi))return;const s=t.mapping.maps[r];let o=0;s.forEach((l,c,d,u)=>{o===0&&(o=u)}),t.setSelection(ir.near(t.doc.resolve(o),n))}var zKe=t=>!("type"in t),UKe=(t,e,n)=>({tr:r,dispatch:i,editor:s})=>{var o;if(i){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)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{_w(e,s.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(g){c(g)}try{l=_w(e,s.schema,{parseOptions:d,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(g){return c(g),!1}let{from:u,to:m}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,f=!0;if((zKe(l)?l:[l]).forEach(g=>{g.check(),p=p?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===m&&f){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,m+=1)}let v;if(p){if(Array.isArray(e))v=e.map(g=>g.text||"").join("");else if(e instanceof Vt){let g="";e.forEach(b=>{b.text&&(g+=b.text)}),v=g}else typeof e=="object"&&e&&e.text?v=e.text:v=e;r.insertText(v,u,m)}else{v=l;const g=r.doc.resolve(u),b=g.node(),_=g.parentOffset===0,C=b.isText||b.isTextblock,P=b.content.size>0;_&&C&&P&&(u=Math.max(0,u-1)),r.replaceWith(u,m,v)}n.updateSelection&&IKe(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:v}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:v})}return!0},BKe=()=>({state:t,dispatch:e})=>u9e(t,e),HKe=()=>({state:t,dispatch:e})=>m9e(t,e),qKe=()=>({state:t,dispatch:e})=>zie(t,e),$Ke=()=>({state:t,dispatch:e})=>qie(t,e),VKe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=BT(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},GKe=()=>({state:t,dispatch:e,tr:n})=>{try{const r=BT(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},WKe=()=>({state:t,dispatch:e})=>c9e(t,e),KKe=()=>({state:t,dispatch:e})=>d9e(t,e);function Ose(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function XKe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,i,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))i=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))zC()||Ose()?o=!0:i=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),i&&(n=`Ctrl-${n}`),o&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var YKe=t=>({editor:e,view:n,tr:r,dispatch:i})=>{const s=XKe(t).split(/-(?!$)/),o=s.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),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",d=>d(n,l))});return c?.steps.forEach(d=>{const u=d.map(r.mapping);u&&i&&r.maybeStep(u)}),!0};function hp(t,e,n={}){const{from:r,to:i,empty:s}=t.selection,o=e?bi(e,t.schema):null,l=[];t.doc.nodesBetween(r,i,(m,p)=>{if(m.isText)return;const f=Math.max(r,p),x=Math.min(i,p+m.nodeSize);l.push({node:m,from:f,to:x})});const c=i-r,d=l.filter(m=>o?o.name===m.node.type.name:!0).filter(m=>IC(m.node.attrs,n,{strict:!1}));return s?!!d.length:d.reduce((m,p)=>m+p.to-p.from,0)>=c}var QKe=(t,e={})=>({state:n,dispatch:r})=>{const i=bi(t,n.schema);return hp(n,i,e)?h9e(n,r):!1},ZKe=()=>({state:t,dispatch:e})=>Wie(t,e),JKe=t=>({state:e,dispatch:n})=>{const r=bi(t,e.schema);return N9e(r)(e,n)},eXe=()=>({state:t,dispatch:e})=>Vie(t,e);function XT(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function fX(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,i)=>(n.includes(i)||(r[i]=t[i]),r),{})}var tXe=(t,e)=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=XT(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=bi(t,r.schema)),l==="mark"&&(o=Sm(t,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{r.doc.nodesBetween(d.$from.pos,d.$to.pos,(u,m)=>{s&&s===u.type&&(c=!0,i&&n.setNodeMarkup(m,void 0,fX(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(p=>{o===p.type&&(c=!0,i&&n.addMark(m,m+u.nodeSize,o.create(fX(p.attrs,e))))})})}),c},nXe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),rXe=()=>({tr:t,dispatch:e})=>{if(e){const n=new cl(t.doc);t.setSelection(n)}return!0},aXe=()=>({state:t,dispatch:e})=>Bie(t,e),iXe=()=>({state:t,dispatch:e})=>$ie(t,e),sXe=()=>({state:t,dispatch:e})=>b9e(t,e),oXe=()=>({state:t,dispatch:e})=>v9e(t,e),lXe=()=>({state:t,dispatch:e})=>y9e(t,e);function PL(t,e,n={},r={}){return _w(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var cXe=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const d=PL(t,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});return o&&s.replaceWith(0,c.content.size,d).setMeta("preventUpdate",!n),!0}return o&&s.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},t,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Ise(t,e){const n=Sm(e,t.schema),{from:r,to:i,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,i,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function zse(t,e){const n=new Rie(t);return e.forEach(r=>{r.steps.forEach(i=>{n.step(i)})}),n}function dXe(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 uXe(t,e,n){const r=[];return t.nodesBetween(e.from,e.to,(i,s)=>{n(i)&&r.push({node:i,pos:s})}),r}function mXe(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 YT(t){return e=>mXe(e.$from,t)}function An(t,e,n){return t.config[e]===void 0&&t.parent?An(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?An(t.parent,e,n):null}):t.config[e]}function Mz(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=An(e,"addExtensions",n);return r?[e,...Mz(r())]:e}).flat(10)}function Ez(t,e){const n=Cg.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(n),i.innerHTML}function Use(t){return typeof t=="function"}function Ir(t,e=void 0,...n){return Use(t)?e?t.bind(e)(...n):t(...n):t}function hXe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Zx(t){const e=t.filter(i=>i.type==="extension"),n=t.filter(i=>i.type==="node"),r=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function Bse(t){const e=[],{nodeExtensions:n,markExtensions:r}=Zx(t),i=[...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:i},c=An(o,"addGlobalAttributes",l);if(!c)return;c().forEach(u=>{u.types.forEach(m=>{Object.entries(u.attributes).forEach(([p,f])=>{e.push({type:m,name:p,attribute:{...s,...f}})})})})}),i.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=An(o,"addAttributes",l);if(!c)return;const d=c();Object.entries(d).forEach(([u,m])=>{const p={...s,...m};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:o.name,name:u,attribute:p})})}),e}function Xa(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([i,s])=>{if(!r[i]){r[i]=s;return}if(i==="class"){const l=s?String(s).split(" "):[],c=r[i]?r[i].split(" "):[],d=l.filter(u=>!c.includes(u));r[i]=[...c,...d].join(" ")}else if(i==="style"){const l=s?s.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[i]?r[i].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[m,p]=u.split(":").map(f=>f.trim());d.set(m,p)}),l.forEach(u=>{const[m,p]=u.split(":").map(f=>f.trim());d.set(m,p)}),r[i]=Array.from(d.entries()).map(([u,m])=>`${u}: ${m}`).join("; ")}else r[i]=s}),r},{})}function kw(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)=>Xa(n,r),{})}function pXe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function gX(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 i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):pXe(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function bX(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&hXe(n)?!1:n!=null))}function xX(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 fXe(t,e){var n;const r=Bse(t),{nodeExtensions:i,markExtensions:s}=Zx(t),o=(n=i.find(d=>An(d,"topNode")))==null?void 0:n.name,l=Object.fromEntries(i.map(d=>{const u=r.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((b,_)=>{const C=An(_,"extendNodeSchema",m);return{...b,...C?C(d):{}}},{}),f=bX({...p,content:Ir(An(d,"content",m)),marks:Ir(An(d,"marks",m)),group:Ir(An(d,"group",m)),inline:Ir(An(d,"inline",m)),atom:Ir(An(d,"atom",m)),selectable:Ir(An(d,"selectable",m)),draggable:Ir(An(d,"draggable",m)),code:Ir(An(d,"code",m)),whitespace:Ir(An(d,"whitespace",m)),linebreakReplacement:Ir(An(d,"linebreakReplacement",m)),defining:Ir(An(d,"defining",m)),isolating:Ir(An(d,"isolating",m)),attrs:Object.fromEntries(u.map(xX))}),x=Ir(An(d,"parseHTML",m));x&&(f.parseDOM=x.map(b=>gX(b,u)));const v=An(d,"renderHTML",m);v&&(f.toDOM=b=>v({node:b,HTMLAttributes:kw(b,u)}));const g=An(d,"renderText",m);return g&&(f.toText=g),[d.name,f]})),c=Object.fromEntries(s.map(d=>{const u=r.filter(g=>g.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((g,b)=>{const _=An(b,"extendMarkSchema",m);return{...g,..._?_(d):{}}},{}),f=bX({...p,inclusive:Ir(An(d,"inclusive",m)),excludes:Ir(An(d,"excludes",m)),group:Ir(An(d,"group",m)),spanning:Ir(An(d,"spanning",m)),code:Ir(An(d,"code",m)),attrs:Object.fromEntries(u.map(xX))}),x=Ir(An(d,"parseHTML",m));x&&(f.parseDOM=x.map(g=>gX(g,u)));const v=An(d,"renderHTML",m);return v&&(f.toDOM=g=>v({mark:g,HTMLAttributes:kw(g,u)})),[d.name,f]}));return new yie({topNode:o,nodes:l,marks:c})}function gXe(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function UC(t){return t.sort((n,r)=>{const i=An(n,"priority")||100,s=An(r,"priority")||100;return i>s?-1:i<s?1:0})}function Hse(t){const e=UC(Mz(t)),n=gXe(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 qse(t,e,n){const{from:r,to:i}=e,{blockSeparator:s=`
- `,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,i,(c,d,u,m)=>{var p;c.isBlock&&d>r&&(l+=s);const f=o?.[c.type.name];if(f)return u&&(l+=f({node:c,pos:d,parent:u,index:m,range:e})),!1;c.isText&&(l+=(p=c?.text)==null?void 0:p.slice(Math.max(r,d)-d,i-d))}),l}function bXe(t,e){const n={from:0,to:t.content.size};return qse(t,n,e)}function $se(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function xXe(t,e){const n=bi(e,t.schema),{from:r,to:i}=t.selection,s=[];t.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function Vse(t,e){const n=XT(typeof e=="string"?e:e.name,t.schema);return n==="node"?xXe(t,e):n==="mark"?Ise(t,e):{}}function yXe(t,e=JSON.stringify){const n={};return t.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function vXe(t){const e=yXe(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 Gse(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.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 d=e.slice(s).map(l,-1),u=e.slice(s).map(c),m=e.invert().map(d,-1),p=e.invert().map(u);r.push({oldRange:{from:m,to:p},newRange:{from:d,to:u}})})}),vXe(r)}function Dz(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(i=>{const s=n.resolve(t),o=jz(s,i.type);o&&r.push({mark:i,...o})}):n.nodesBetween(t,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}var wXe=(t,e,n,r=20)=>{const i=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function sk(t,e){return e.nodes[t]||e.marks[t]||null}function Vk(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const i=t.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}var SXe=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var c,d;const u=((d=(c=i.type.spec).toText)==null?void 0:d.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";n+=i.isAtom&&!i.isText?u:u.slice(0,Math.max(0,r-s))}),n};function TL(t,e,n={}){const{empty:r,ranges:i}=t.selection,s=e?Sm(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(m=>s?s.name===m.type.name:!0).find(m=>IC(m.attrs,n,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:m,$to:p})=>{const f=m.pos,x=p.pos;t.doc.nodesBetween(f,x,(v,g)=>{if(!v.isText&&!v.marks.length)return;const b=Math.max(f,g),_=Math.min(x,g+v.nodeSize),C=_-b;o+=C,l.push(...v.marks.map(P=>({mark:P,from:b,to:_})))})}),o===0)return!1;const c=l.filter(m=>s?s.name===m.mark.type.name:!0).filter(m=>IC(m.mark.attrs,n,{strict:!1})).reduce((m,p)=>m+p.to-p.from,0),d=l.filter(m=>s?m.mark.type!==s&&m.mark.type.excludes(s):!0).reduce((m,p)=>m+p.to-p.from,0);return(c>0?c+d:c)>=o}function _Xe(t,e,n={}){if(!e)return hp(t,null,n)||TL(t,null,n);const r=XT(e,t.schema);return r==="node"?hp(t,e,n):r==="mark"?TL(t,e,n):!1}var kXe=(t,e)=>{const{$from:n,$to:r,$anchor:i}=t.selection;if(e){const s=YT(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},NXe=t=>{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function yX(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function vX(t,e){const{nodeExtensions:n}=Zx(e),r=n.find(o=>o.name===t);if(!r)return!1;const i={name:r.name,options:r.options,storage:r.storage},s=Ir(An(r,"group",i));return typeof s!="string"?!1:s.split(" ").includes("list")}function QT(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 i=!0;return t.content.forEach(s=>{i!==!1&&(QT(s,{ignoreWhitespace:n,checkChildren:e})||(i=!1))}),i}return!1}function Wse(t){return t instanceof Mn}var Kse=class Xse{constructor(e){this.position=e}static fromJSON(e){return new Xse(e.position)}toJSON(){return{position:this.position}}};function CXe(t,e){const n=e.mapping.mapResult(t.position);return{position:new Kse(n.pos),mapResult:n}}function PXe(t){return new Kse(t)}function TXe(t,e,n){var r;const{selection:i}=e;let s=null;if(Fse(i)&&(s=i.$cursor),s){const l=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(d=>d.type.excludes(n)))}const{ranges:o}=i;return o.some(({$from:l,$to:c})=>{let d=l.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(l.pos,c.pos,(u,m,p)=>{if(d)return!1;if(u.isInline){const f=!p||p.type.allowsMarkType(n),x=!!n.isInSet(u.marks)||!u.marks.some(v=>v.type.excludes(n));d=f&&x}return!d}),d})}var AXe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=Sm(t,r.schema);if(i)if(o){const d=Ise(r,c);n.addStoredMark(c.create({...d,...e}))}else l.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;r.doc.nodesBetween(u,m,(p,f)=>{const x=Math.max(f,u),v=Math.min(f+p.nodeSize,m);p.marks.find(b=>b.type===c)?p.marks.forEach(b=>{c===b.type&&n.addMark(x,v,c.create({...b.attrs,...e}))}):n.addMark(x,v,c.create(e))})});return TXe(r,n,c)},jXe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),MXe=(t,e={})=>({state:n,dispatch:r,chain:i})=>{const s=bi(t,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>DK(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>DK(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},EXe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,i=jf(t,0,r.content.size),s=Mn.create(r,i);e.setSelection(s)}return!0},DXe=(t,e)=>({tr:n,state:r,dispatch:i})=>{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),i&&n.doc.nodesBetween(o,l,(c,d)=>{c.isText||n.setNodeMarkup(d,void 0,{...c.attrs,dir:t})}),!0},FXe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:i,to:s}=typeof t=="number"?{from:t,to:t}:t,o=$n.atStart(r).from,l=$n.atEnd(r).to,c=jf(i,o,l),d=jf(s,o,l),u=$n.create(r,c,d);e.setSelection(u)}return!0},RXe=t=>({state:e,dispatch:n})=>{const r=bi(t,e.schema);return T9e(r)(e,n)};function wX(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(i=>e?.includes(i.type.name));t.tr.ensureMarks(r)}}var LXe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,d=i.extensionManager.attributes,u=Vk(d,l.node().type.name,l.node().attrs);if(s instanceof Mn&&s.node.isBlock)return!l.parentOffset||!em(o,l.pos)?!1:(r&&(t&&wX(n,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,p=l.depth===0?void 0:dXe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let f=m&&p?[{type:p,attrs:u}]:void 0,x=em(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!x&&em(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(x=!0,f=p?[{type:p,attrs:u}]:void 0),r){if(x&&(s instanceof $n&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),p&&!m&&!l.parentOffset&&l.parent.type!==p)){const v=e.mapping.map(l.before()),g=e.doc.resolve(v);l.node(-1).canReplaceWith(g.index(),g.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&wX(n,i.extensionManager.splittableMarks),e.scrollIntoView()}return x},OXe=(t,e={})=>({tr:n,state:r,dispatch:i,editor:s})=>{var o;const l=bi(t,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==l)return!1;const p=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(i){let b=Vt.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let F=c.depth-_;F>=c.depth-3;F-=1)b=Vt.from(c.node(F).copy(b));const C=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,P={...Vk(p,c.node().type.name,c.node().attrs),...e},N=((o=l.contentMatch.defaultType)==null?void 0:o.createAndFill(P))||void 0;b=b.append(Vt.from(l.createAndFill(null,N)||void 0));const A=c.before(c.depth-(_-1));n.replace(A,c.after(-C),new cn(b,4-_,0));let T=-1;n.doc.nodesBetween(A,n.doc.content.size,(F,k)=>{if(T>-1)return!1;F.isTextblock&&F.content.size===0&&(T=k+1)}),T>-1&&n.setSelection($n.near(n.doc.resolve(T))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,x={...Vk(p,m.type.name,m.attrs),...e},v={...Vk(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,d.pos);const g=f?[{type:l,attrs:x},{type:f,attrs:v}]:[{type:l,attrs:x}];if(!em(n.doc,c.pos,2))return!1;if(i){const{selection:b,storedMarks:_}=r,{splittableMarks:C}=s.extensionManager,P=_||b.$to.parentOffset&&b.$from.marks();if(n.split(c.pos,2,g).scrollIntoView(),!P||!i)return!0;const N=P.filter(A=>C.includes(A.type.name));n.ensureMarks(N)}return!0},KD=(t,e)=>{const n=YT(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 i=t.doc.nodeAt(r);return n.node.type===i?.type&&Sp(t.doc,n.pos)&&t.join(n.pos),!0},XD=(t,e)=>{const n=YT(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 i=t.doc.nodeAt(r);return n.node.type===i?.type&&Sp(t.doc,r)&&t.join(r),!0},IXe=(t,e,n,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:c,commands:d,can:u})=>{const{extensions:m,splittableMarks:p}=i.extensionManager,f=bi(t,o.schema),x=bi(e,o.schema),{selection:v,storedMarks:g}=o,{$from:b,$to:_}=v,C=b.blockRange(_),P=g||v.$to.parentOffset&&v.$from.marks();if(!C)return!1;const N=YT(A=>vX(A.type.name,m))(v);if(C.depth>=1&&N&&C.depth-N.depth<=1){if(N.node.type===f)return d.liftListItem(x);if(vX(N.node.type.name,m)&&f.validContent(N.node.content)&&l)return c().command(()=>(s.setNodeMarkup(N.pos,f),!0)).command(()=>KD(s,f)).command(()=>XD(s,f)).run()}return!n||!P||!l?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>KD(s,f)).command(()=>XD(s,f)).run():c().command(()=>{const A=u().wrapInList(f,r),T=P.filter(F=>p.includes(F.type.name));return s.ensureMarks(T),A?!0:d.clearNodes()}).wrapInList(f,r).command(()=>KD(s,f)).command(()=>XD(s,f)).run()},zXe=(t,e={},n={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=n,o=Sm(t,r.schema);return TL(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},UXe=(t,e,n={})=>({state:r,commands:i})=>{const s=bi(t,r.schema),o=bi(e,r.schema),l=hp(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?i.setNode(o,c):i.setNode(s,{...c,...n})},BXe=(t,e={})=>({state:n,commands:r})=>{const i=bi(t,n.schema);return hp(n,i,e)?r.lift(i):r.wrapIn(i,e)},HXe=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const i=n[r];let s;if(i.spec.isInputRules&&(s=i.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},qXe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:i}=n;return r||e&&i.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},$Xe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=Sm(t,r.schema),{$from:d,empty:u,ranges:m}=l;if(!i)return!0;if(u&&o){let{from:p,to:f}=l;const x=(s=d.marks().find(g=>g.type===c))==null?void 0:s.attrs,v=jz(d,c,x);v&&(p=v.from,f=v.to),n.removeMark(p,f,c)}else m.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},VXe=t=>({tr:e,state:n,dispatch:r})=>{const{selection:i}=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=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,c)=>{if(l.isText)return;const d={...l.attrs};delete d.dir,e.setNodeMarkup(c,void 0,d)}),!0},GXe=(t,e={})=>({tr:n,state:r,dispatch:i})=>{let s=null,o=null;const l=XT(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=bi(t,r.schema)),l==="mark"&&(o=Sm(t,r.schema));let c=!1;return n.selection.ranges.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;let p,f,x,v;n.selection.empty?r.doc.nodesBetween(u,m,(g,b)=>{s&&s===g.type&&(c=!0,x=Math.max(b,u),v=Math.min(b+g.nodeSize,m),p=b,f=g)}):r.doc.nodesBetween(u,m,(g,b)=>{b<u&&s&&s===g.type&&(c=!0,x=Math.max(b,u),v=Math.min(b+g.nodeSize,m),p=b,f=g),b>=u&&b<=m&&(s&&s===g.type&&(c=!0,i&&n.setNodeMarkup(b,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(_=>{if(o===_.type&&(c=!0,i)){const C=Math.max(b,u),P=Math.min(b+g.nodeSize,m);n.addMark(C,P,o.create({..._.attrs,...e}))}}))}),f&&(p!==void 0&&i&&n.setNodeMarkup(p,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(g=>{o===g.type&&i&&n.addMark(x,v,o.create({...g.attrs,...e}))}))}),c},WXe=(t,e={})=>({state:n,dispatch:r})=>{const i=bi(t,n.schema);return w9e(i,e)(n,r)},KXe=(t,e={})=>({state:n,dispatch:r})=>{const i=bi(t,n.schema);return S9e(i,e)(n,r)},XXe=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={}}},ZT=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},YXe=(t,e)=>{if(Az(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 ok(t){var e;const{editor:n,from:r,to:i,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||(e=d.nodeBefore||d.nodeAfter)!=null&&e.marks.find(p=>p.type.spec.code))return!1;let u=!1;const m=SXe(d)+s;return o.forEach(p=>{if(u)return;const f=YXe(m,p.find);if(!f)return;const x=c.state.tr,v=WT({state:c.state,transaction:x}),g={from:r-(f[0].length-s.length),to:i},{commands:b,chain:_,can:C}=new KT({editor:n,state:v});p.handler({state:v,range:g,match:f,commands:b,chain:_,can:C})===null||!x.steps.length||(p.undoable&&x.setMeta(l,{transform:x,from:r,to:i,text:s}),c.dispatch(x),u=!0)}),u}function QXe(t){const{editor:e,rules:n}=t,r=new Ra({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const c=i.getMeta("applyInputRules");return c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=Ez(Vt.from(u),o.schema);const{from:m}=c,p=m+u.length;ok({editor:e,from:m,to:p,text:u,rules:n,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return ok({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&ok({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?ok({editor:e,from:o.pos,to:o.pos,text:`
- `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function ZXe(t){return Object.prototype.toString.call(t).slice(8,-1)}function lk(t){return ZXe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function Yse(t,e){const n={...t};return lk(t)&&lk(e)&&Object.keys(e).forEach(r=>{lk(e[r])&&lk(t[r])?n[r]=Yse(t[r],e[r]):n[r]=e[r]}),n}var Fz=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{...Ir(An(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Ir(An(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>Yse(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}},kp=class Qse extends Fz{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new Qse(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!!!o.find(d=>d?.type.name===n.name))return!1;const c=o.find(d=>d?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",i.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 JXe(t){return typeof t=="number"}var eYe=class{constructor(t){this.find=t.find,this.handler=t.handler}},tYe=(t,e,n)=>{if(Az(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=t,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function nYe(t){const{editor:e,state:n,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:d,can:u}=new KT({editor:e,state:n}),m=[];return n.doc.nodesBetween(r,i,(f,x)=>{var v,g,b,_,C;if((g=(v=f.type)==null?void 0:v.spec)!=null&&g.code||!(f.isText||f.isTextblock||f.isInline))return;const P=(C=(_=(b=f.content)==null?void 0:b.size)!=null?_:f.nodeSize)!=null?C:0,N=Math.max(r,x),A=Math.min(i,x+P);if(N>=A)return;const T=f.isText?f.text||"":f.textBetween(N-x,A-x,void 0,"");tYe(T,s.find,o).forEach(k=>{if(k.index===void 0)return;const D=N+k.index+1,H=D+k[0].length,z={from:n.tr.mapping.map(D),to:n.tr.mapping.map(H)},X=s.handler({state:n,range:z,match:k,commands:c,chain:d,can:u,pasteEvent:o,dropEvent:l});m.push(X)})}),m.every(f=>f!==null)}var ck=null,rYe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function aYe(t){const{editor:e,rules:n}=t;let r=null,i=!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:u,from:m,to:p,rule:f,pasteEvt:x})=>{const v=u.tr,g=WT({state:u,transaction:v});if(!(!nYe({editor:e,state:g,from:Math.max(m-1,0),to:p.b-1,rule:f,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(u=>new Ra({view(m){const p=x=>{var v;r=(v=m.dom.parentElement)!=null&&v.contains(x.target)?m.dom.parentElement:null,r&&(ck=e)},f=()=>{ck&&(ck=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(m,p)=>{if(s=r===m.dom.parentElement,l=p,!s){const f=ck;f?.isEditable&&setTimeout(()=>{const x=f.state.selection;x&&f.commands.deleteRange({from:x.from,to:x.to})},10)}return!1},paste:(m,p)=>{var f;const x=(f=p.clipboardData)==null?void 0:f.getData("text/html");return o=p,i=!!x?.includes("data-pm-slice"),!1}}},appendTransaction:(m,p,f)=>{const x=m[0],v=x.getMeta("uiEvent")==="paste"&&!i,g=x.getMeta("uiEvent")==="drop"&&!s,b=x.getMeta("applyPasteRules"),_=!!b;if(!v&&!g&&!_)return;if(_){let{text:N}=b;typeof N=="string"?N=N:N=Ez(Vt.from(N),f.schema);const{from:A}=b,T=A+N.length,F=rYe(N);return c({rule:u,state:f,from:A,to:{b:T},pasteEvt:F})}const C=p.doc.content.findDiffStart(f.doc.content),P=p.doc.content.findDiffEnd(f.doc.content);if(!(!JXe(C)||!P||C===P.b))return c({rule:u,state:f,from:C,to:P,pasteEvt:o})}}))}var JT=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Hse(t),this.schema=fXe(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:sk(e.name,this.schema)},r=An(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return UC([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:sk(r.name,this.schema)},s=[],o=An(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&An(r,"exitable",i)&&(l.ArrowRight=()=>kp.handleExit({editor:t,mark:r})),o){const p=Object.fromEntries(Object.entries(o()).map(([f,x])=>[f,()=>x({editor:t})]));l={...l,...p}}const c=xKe(l);s.push(c);const d=An(r,"addInputRules",i);if(yX(r,t.options.enableInputRules)&&d){const p=d();if(p&&p.length){const f=QXe({editor:t,rules:p}),x=Array.isArray(f)?f:[f];s.push(...x)}}const u=An(r,"addPasteRules",i);if(yX(r,t.options.enablePasteRules)&&u){const p=u();if(p&&p.length){const f=aYe({editor:t,rules:p});s.push(...f)}}const m=An(r,"addProseMirrorPlugins",i);if(m){const p=m();s.push(...p)}return s})}get attributes(){return Bse(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Zx(this.extensions);return Object.fromEntries(e.filter(n=>!!An(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:bi(n.name,this.schema)},s=An(n,"addNodeView",i);if(!s)return[];const o=s();if(!o)return[];const l=(c,d,u,m,p)=>{const f=kw(c,r);return o({node:c,view:d,getPos:u,decorations:m,innerDecorations:p,editor:t,extension:n,HTMLAttributes:f})};return[n.name,l]}))}dispatchTransaction(t){const{editor:e}=this;return UC([...this.extensions].reverse()).reduceRight((r,i)=>{const s={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:sk(i.name,this.schema)},o=An(i,"dispatchTransaction",s);return o?l=>{o.call(s,{transaction:l,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Zx(this.extensions);return Object.fromEntries(e.filter(n=>!!An(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Sm(n.name,this.schema)},s=An(n,"addMarkView",i);if(!s)return[];const o=(l,c,d)=>{const u=kw(l,r);return s()({mark:l,view:c,inline:d,editor:t,extension:n,HTMLAttributes:u,updateAttributes:m=>{yYe(l,t,m)}})};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:sk(e.name,this.schema)};e.type==="mark"&&((n=Ir(An(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const i=An(e,"onBeforeCreate",r),s=An(e,"onCreate",r),o=An(e,"onUpdate",r),l=An(e,"onSelectionUpdate",r),c=An(e,"onTransaction",r),d=An(e,"onFocus",r),u=An(e,"onBlur",r),m=An(e,"onDestroy",r);i&&this.editor.on("beforeCreate",i),s&&this.editor.on("create",s),o&&this.editor.on("update",o),l&&this.editor.on("selectionUpdate",l),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),m&&this.editor.on("destroy",m)})}};JT.resolve=Hse;JT.sort=UC;JT.flatten=Mz;var iYe={};Tz(iYe,{ClipboardTextSerializer:()=>Jse,Commands:()=>eoe,Delete:()=>toe,Drop:()=>noe,Editable:()=>roe,FocusEvents:()=>ioe,Keymap:()=>soe,Paste:()=>ooe,Tabindex:()=>loe,TextDirection:()=>coe,focusEventsPluginKey:()=>aoe});var Qr=class Zse extends Fz{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Zse(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},Jse=Qr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Ra({key:new Ei("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:i}=e,{ranges:s}=i,o=Math.min(...s.map(u=>u.$from.pos)),l=Math.max(...s.map(u=>u.$to.pos)),c=$se(n);return qse(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),eoe=Qr.create({name:"commands",addCommands(){return{...Ese}}}),toe=Qr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,i;const s=()=>{var o,l,c,d;if((d=(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?d:t.getMeta("y-sync$"))return;const u=zse(t.before,[t,...e]);Gse(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(x,v)=>{const g=v+x.nodeSize-2,b=f.oldRange.from<=v&&g<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:x,from:v,to:g,newFrom:u.mapping.map(v),newTo:u.mapping.map(g),deletedRange:f.oldRange,newRange:f.newRange,partial:!b,editor:this.editor,transaction:t,combinedTransform:u})})});const p=u.mapping;u.steps.forEach((f,x)=>{var v,g;if(f instanceof Oc){const b=p.slice(x).map(f.from,-1),_=p.slice(x).map(f.to),C=p.invert().map(b,-1),P=p.invert().map(_),N=(v=u.doc.nodeAt(b-1))==null?void 0:v.marks.some(T=>T.eq(f.mark)),A=(g=u.doc.nodeAt(_))==null?void 0:g.marks.some(T=>T.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:C,to:P},newRange:{from:b,to:_},partial:!!(A||N),editor:this.editor,transaction:t,combinedTransform:u})}})};(i=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||i?setTimeout(s,0):s()}}),noe=Qr.create({name:"drop",addProseMirrorPlugins(){return[new Ra({key:new Ei("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),roe=Qr.create({name:"editable",addProseMirrorPlugins(){return[new Ra({key:new Ei("editable"),props:{editable:()=>this.editor.options.editable}})]}}),aoe=new Ei("focusEvents"),ioe=Qr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new Ra({key:aoe,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}}}})]}}),soe=Qr.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:c,doc:d}=l,{empty:u,$anchor:m}=c,{pos:p,parent:f}=m,x=m.parent.isTextblock&&p>0?l.doc.resolve(p-1):m,v=x.parent.type.spec.isolating,g=m.pos-m.parentOffset,b=v&&x.parent.childCount===1?g===m.pos:ir.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!b||b&&m.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()},i={...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 zC()||Ose()?s:i},addProseMirrorPlugins(){return[new Ra({key:new Ei("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),i=t.some(v=>v.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,c=ir.atStart(e.doc).from,d=ir.atEnd(e.doc).to;if(s||!(o===c&&l===d)||!QT(n.doc))return;const p=n.tr,f=WT({state:n,transaction:p}),{commands:x}=new KT({editor:this.editor,state:f});if(x.clearNodes(),!!p.steps.length)return p}})]}}),ooe=Qr.create({name:"paste",addProseMirrorPlugins(){return[new Ra({key:new Ei("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),loe=Qr.create({name:"tabindex",addProseMirrorPlugins(){return[new Ra({key:new Ei("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),coe=Qr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Zx(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 Ra({key:new Ei("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),sYe=class i0{constructor(e,n,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=i}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 i0(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 i0(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 i0(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const i=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(!i&&!o&&c.depth<=this.depth)return;const d=new i0(c,this.editor,i,i||o?n:null);i&&(d.actualDepth=this.depth+1),e.push(d)}),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,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(n).length>0){const s=i.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=i;i=i.parent}return r}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},r=!1){let i=[];if(!this.children||this.children.length===0)return i;const s=Object.keys(n);return this.children.forEach(o=>{r&&i.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,n,r))))}),i}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},oYe=`.ProseMirror {
- position: relative;
- }
- .ProseMirror {
- word-wrap: break-word;
- white-space: pre-wrap;
- white-space: break-spaces;
- -webkit-font-variant-ligatures: none;
- font-variant-ligatures: none;
- font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
- }
- .ProseMirror [contenteditable="false"] {
- white-space: normal;
- }
- .ProseMirror [contenteditable="false"] [contenteditable="true"] {
- white-space: pre-wrap;
- }
- .ProseMirror pre {
- white-space: pre-wrap;
- }
- img.ProseMirror-separator {
- display: inline !important;
- border: none !important;
- margin: 0 !important;
- width: 0 !important;
- height: 0 !important;
- }
- .ProseMirror-gapcursor {
- display: none;
- pointer-events: none;
- position: absolute;
- margin: 0;
- }
- .ProseMirror-gapcursor:after {
- content: "";
- display: block;
- position: absolute;
- top: -2px;
- width: 20px;
- border-top: 1px solid black;
- animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
- }
- @keyframes ProseMirror-cursor-blink {
- to {
- visibility: hidden;
- }
- }
- .ProseMirror-hideselection *::selection {
- background: transparent;
- }
- .ProseMirror-hideselection *::-moz-selection {
- background: transparent;
- }
- .ProseMirror-hideselection * {
- caret-color: transparent;
- }
- .ProseMirror-focused .ProseMirror-gapcursor {
- display: block;
- }`;function lYe(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(i),i}var cYe=class extends XXe{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:CXe,createMappablePosition:PXe},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:i,moved:s})=>this.options.onDrop(r,i,s)),this.on("paste",({event:r,slice:i})=>this.options.onPaste(r,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=Rse(e,this.options.autofocus);this.editorState=cx.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=lYe(oYe,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=Use(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(i=>{const s=typeof i=="string"?`${i}$`:i.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?[roe,Jse.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),eoe,ioe,soe,loe,noe,ooe,toe,coe.configure({direction:this.options.textDirection})].filter(i=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[i.name]!==!1:!0):[],...this.options.extensions].filter(i=>["extension","node","mark"].includes(i?.type));this.extensionManager=new JT(r,this)}createCommandManager(){this.commandManager=new KT({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=PL(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=PL(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),i=n?this.extensionManager.dispatchTransaction(r):r;this.editorView=new jse(t,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:i,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(d=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(d)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),i=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!i)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(d=>d.getMeta("focus")||d.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(d=>d.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return Vse(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return _Xe(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Ez(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=`
- `,textSerializers:n={}}=t||{};return bXe(this.state.doc,{blockSeparator:e,textSerializers:{...$se(this.schema),...n}})}get isEmpty(){return QT(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 sYe(e,this)}get $doc(){return this.$pos(0)}};function Jx(t){return new ZT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=Ir(t.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),d=n.from+l.indexOf(o),u=d+o.length;if(Dz(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(v=>v===t.type&&v!==f.mark.type)).filter(f=>f.to>d).length)return null;u<n.to&&s.delete(u,n.to),d>n.from&&s.delete(n.from+c,d);const p=n.from+c+o.length;s.addMark(n.from+c,p,t.type.create(i||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function doe(t){return new ZT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=Ir(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(i);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=o+d;u>l?u=l:l=u+r[1].length;const m=r[0][r[0].length-1];s.insertText(m,o+r[0].length-1),s.replaceWith(u,l,c)}else if(r[0]){const d=t.type.isInline?o:o-1;s.insert(d,t.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function AL(t){return new ZT({find:t.find,handler:({state:e,range:n,match:r})=>{const i=e.doc.resolve(n.from),s=Ir(t.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.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 ey(t){return new ZT({find:t.find,handler:({state:e,range:n,match:r,chain:i})=>{const s=Ir(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),d=c&&mz(c,t.type,s);if(!d)return null;if(o.wrap(c,d),t.keepMarks&&t.editor){const{selection:m,storedMarks:p}=e,{splittableMarks:f}=t.editor.extensionManager,x=p||m.$to.parentOffset&&m.$from.marks();if(x){const v=x.filter(g=>f.includes(g.type.name));o.ensureMarks(v)}}if(t.keepAttributes){const m=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(m,s).run()}const u=o.doc.resolve(n.from-1).nodeBefore;u&&u.type===t.type&&Sp(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,u))&&o.join(n.from-1)},undoable:t.undoable})}var dYe=t=>"touches"in t,uYe=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,d=l.clientY-this.startY;this.handleResize(c,d)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const d=c.clientX-this.startX,u=c.clientY-this.startY;this.handleResize(d,u)},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,i,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),(i=t.options)!=null&&i.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"),i=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),i&&(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,dYe(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:i}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,i,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,i=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?i=this.startHeight+n:c&&(i=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(i=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,i,t):{width:r,height:i}}applyConstraints(t,e,n){var r,i,s,o;if(!n){let d=Math.max(this.minSize.width,t),u=Math.max(this.minSize.height,e);return(r=this.maxSize)!=null&&r.width&&(d=Math.min(this.maxSize.width,d)),(i=this.maxSize)!=null&&i.height&&(u=Math.min(this.maxSize.height,u)),{width:d,height:u}}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",i=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function mYe(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof Mn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var hYe={};Tz(hYe,{createAtomBlockMarkdownSpec:()=>pYe,createBlockMarkdownSpec:()=>fYe,createInlineMarkdownSpec:()=>xYe,parseAttributes:()=>Rz,parseIndentedBlocks:()=>jL,renderNestedMarkdownContent:()=>Oz,serializeAttributes:()=>Lz});function Rz(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,d=>(n.push(d),`__QUOTED_${n.length-1}__`)),i=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const d=i.map(u=>u.trim().slice(1));e.class=d.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(([,d,u])=>{var m;const p=parseInt(((m=u.match(/__QUOTED_(\d+)__/))==null?void 0:m[1])||"0",10),f=n[p];f&&(e[d]=f.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(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function Lz(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 pYe(t){const{nodeName:e,name:n,parseAttributes:r=Rz,serializeAttributes:i=Lz,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,d=u=>{if(!l)return u;const m={};return l.forEach(p=>{p in u&&(m[p]=u[p])}),m};return{parseMarkdown:(u,m)=>{const p={...s,...u.attributes};return m.createNode(e,p,[])},markdownTokenizer:{name:e,level:"block",start(u){var m;const p=new RegExp(`^:::${c}(?:\\s|$)`,"m"),f=(m=u.match(p))==null?void 0:m.index;return f!==void 0?f:-1},tokenize(u,m,p){const f=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),x=u.match(f);if(!x)return;const v=x[1]||"",g=r(v);if(!o.find(_=>!(_ in g)))return{type:e,raw:x[0],attributes:g}}},renderMarkdown:u=>{const m=d(u.attrs||{}),p=i(m),f=p?` {${p}}`:"";return`:::${c}${f} :::`}}}function fYe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=Rz,serializeAttributes:s=Lz,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,d=n||e,u=m=>{if(!c)return m;const p={};return c.forEach(f=>{f in m&&(p[f]=m[f])}),p};return{parseMarkdown:(m,p)=>{let f;if(r){const v=r(m);f=typeof v=="string"?[{type:"text",text:v}]:v}else l==="block"?f=p.parseChildren(m.tokens||[]):f=p.parseInline(m.tokens||[]);const x={...o,...m.attributes};return p.createNode(e,x,f)},markdownTokenizer:{name:e,level:"block",start(m){var p;const f=new RegExp(`^:::${d}`,"m"),x=(p=m.match(f))==null?void 0:p.index;return x!==void 0?x:-1},tokenize(m,p,f){var x;const v=new RegExp(`^:::${d}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),g=m.match(v);if(!g)return;const[b,_=""]=g,C=i(_);let P=1;const N=b.length;let A="";const T=/^:::([\w-]*)(\s.*)?/gm,F=m.slice(N);for(T.lastIndex=0;;){const k=T.exec(F);if(k===null)break;const D=k.index,H=k[1];if(!((x=k[2])!=null&&x.endsWith(":::"))){if(H)P+=1;else if(P-=1,P===0){const z=F.slice(0,D);A=z.trim();const X=m.slice(0,N+D+k[0].length);let L=[];if(A)if(l==="block")for(L=f.blockTokens(z),L.forEach(ne=>{ne.text&&(!ne.tokens||ne.tokens.length===0)&&(ne.tokens=f.inlineTokens(ne.text))});L.length>0;){const ne=L[L.length-1];if(ne.type==="paragraph"&&(!ne.text||ne.text.trim()===""))L.pop();else break}else L=f.inlineTokens(A);return{type:e,raw:X,attributes:C,content:A,tokens:L}}}}}},renderMarkdown:(m,p)=>{const f=u(m.attrs||{}),x=s(f),v=x?` {${x}}`:"",g=p.renderChildren(m.content||[],`
- `);return`:::${d}${v}
- ${g}
- :::`}}}function gYe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,i,s,o]=r;e[i]=s||o,r=n.exec(t)}return e}function bYe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function xYe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:i=gYe,serializeAttributes:s=bYe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,d=n||e,u=p=>{if(!c)return p;const f={};return c.forEach(x=>{const v=typeof x=="string"?x:x.name,g=typeof x=="string"?void 0:x.skipIfDefault;if(v in p){const b=p[v];if(g!==void 0&&b===g)return;f[v]=b}}),f},m=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,f)=>{const x={...o,...p.attributes};if(l)return f.createNode(e,x);const v=r?r(p):p.content||"";return v?f.createNode(e,x,[f.createTextNode(v)]):f.createNode(e,x,[])},markdownTokenizer:{name:e,level:"inline",start(p){const f=l?new RegExp(`\\[${m}\\s*[^\\]]*\\]`):new RegExp(`\\[${m}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${m}\\]`),x=p.match(f),v=x?.index;return v!==void 0?v:-1},tokenize(p,f,x){const v=l?new RegExp(`^\\[${m}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${m}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${m}\\]`),g=p.match(v);if(!g)return;let b="",_="";if(l){const[,P]=g;_=P}else{const[,P,N]=g;_=P,b=N||""}const C=i(_.trim());return{type:e,raw:g[0],content:b.trim(),attributes:C}}},renderMarkdown:p=>{let f="";r?f=r(p):p.content&&p.content.length>0&&(f=p.content.filter(b=>b.type==="text").map(b=>b.text).join(""));const x=u(p.attrs||{}),v=s(x),g=v?` ${v}`:"";return l?`[${d}${g}]`:`[${d}${g}]${f}[/${d}]`}}}function jL(t,e,n){var r,i,s,o;const l=t.split(`
- `),c=[];let d="",u=0;const m=e.baseIndentSize||2;for(;u<l.length;){const p=l[u],f=p.match(e.itemPattern);if(!f){if(c.length>0)break;if(p.trim()===""){u+=1,d=`${d}${p}
- `;continue}else return}const x=e.extractItemData(f),{indentLevel:v,mainContent:g}=x;d=`${d}${p}
- `;const b=[g];for(u+=1;u<l.length;){const N=l[u];if(N.trim()===""){const T=l.slice(u+1).findIndex(D=>D.trim()!=="");if(T===-1)break;if((((i=(r=l[u+1+T].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:i.length)||0)>v){b.push(N),d=`${d}${N}
- `,u+=1;continue}else break}if((((o=(s=N.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:o.length)||0)>v)b.push(N),d=`${d}${N}
- `,u+=1;else break}let _;const C=b.slice(1);if(C.length>0){const N=C.map(A=>A.slice(v+m)).join(`
- `);N.trim()&&(e.customNestedParser?_=e.customNestedParser(N):_=n.blockTokens(N))}const P=e.createToken(x,_);c.push(P)}if(c.length!==0)return{items:c,raw:d}}function Oz(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const i=typeof n=="function"?n(r):n,[s,...o]=t.content,l=e.renderChildren([s]),c=[`${i}${l}`];return o&&o.length>0&&o.forEach(d=>{const u=e.renderChildren([d]);if(u){const m=u.split(`
- `).map(p=>p?e.indent(p):"").join(`
- `);c.push(m)}}),c.join(`
- `)}function yYe(t,e,n={}){const{state:r}=e,{doc:i,tr:s}=r,o=t;i.descendants((l,c)=>{const d=s.mapping.map(c),u=s.mapping.map(c)+l.nodeSize;let m=null;if(l.marks.forEach(f=>{if(f!==o)return!1;m=f}),!m)return;let p=!1;if(Object.keys(n).forEach(f=>{n[f]!==m.attrs[f]&&(p=!0)}),p){const f=t.type.create({...t.attrs,...n});s.removeMark(d,u,t.type),s.addMark(d,u,f)}}),s.docChanged&&e.view.dispatch(s)}var Ro=class uoe extends Fz{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new uoe(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function bg(t){return new eYe({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:i})=>{const s=Ir(t.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],c=r[0];let d=n.to;if(l){const u=c.search(/\S/),m=n.from+c.indexOf(l),p=m+l.length;if(Dz(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>m).length)return null;p<n.to&&o.delete(p,n.to),m>n.from&&o.delete(n.from+u,m),d=n.from+u+l.length,o.addMark(n.from+u,d,t.type.create(s||{})),o.removeStoredMark(t.type)}}})}const{getOwnPropertyNames:vYe,getOwnPropertySymbols:wYe}=Object,{hasOwnProperty:SYe}=Object.prototype;function YD(t,e){return function(r,i,s){return t(r,i,s)&&e(r,i,s)}}function dk(t){return function(n,r,i){if(!n||!r||typeof n!="object"||typeof r!="object")return t(n,r,i);const{cache:s}=i,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,i);return s.delete(n),s.delete(r),c}}function _Ye(t){return t?.[Symbol.toStringTag]}function SX(t){return vYe(t).concat(wYe(t))}const kYe=Object.hasOwn||((t,e)=>SYe.call(t,e));function Pg(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const NYe="__v",CYe="__o",PYe="_owner",{getOwnPropertyDescriptor:_X,keys:kX}=Object;function TYe(t,e){return t.byteLength===e.byteLength&&BC(new Uint8Array(t),new Uint8Array(e))}function AYe(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 jYe(t,e){return t.byteLength===e.byteLength&&BC(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function MYe(t,e){return Pg(t.getTime(),e.getTime())}function EYe(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function DYe(t,e){return t===e}function NX(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const i=new Array(r),s=t.entries();let o,l,c=0;for(;(o=s.next())&&!o.done;){const d=e.entries();let u=!1,m=0;for(;(l=d.next())&&!l.done;){if(i[m]){m++;continue}const p=o.value,f=l.value;if(n.equals(p[0],f[0],c,m,t,e,n)&&n.equals(p[1],f[1],p[0],f[0],t,e,n)){u=i[m]=!0;break}m++}if(!u)return!1;c++}return!0}const FYe=Pg;function RYe(t,e,n){const r=kX(t);let i=r.length;if(kX(e).length!==i)return!1;for(;i-- >0;)if(!moe(t,e,n,r[i]))return!1;return!0}function $v(t,e,n){const r=SX(t);let i=r.length;if(SX(e).length!==i)return!1;let s,o,l;for(;i-- >0;)if(s=r[i],!moe(t,e,n,s)||(o=_X(t,s),l=_X(e,s),(o||l)&&(!o||!l||o.configurable!==l.configurable||o.enumerable!==l.enumerable||o.writable!==l.writable)))return!1;return!0}function LYe(t,e){return Pg(t.valueOf(),e.valueOf())}function OYe(t,e){return t.source===e.source&&t.flags===e.flags}function CX(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const i=new Array(r),s=t.values();let o,l;for(;(o=s.next())&&!o.done;){const c=e.values();let d=!1,u=0;for(;(l=c.next())&&!l.done;){if(!i[u]&&n.equals(o.value,l.value,o.value,l.value,t,e,n)){d=i[u]=!0;break}u++}if(!d)return!1}return!0}function BC(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 IYe(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 moe(t,e,n,r){return(r===PYe||r===CYe||r===NYe)&&(t.$$typeof||e.$$typeof)?!0:kYe(e,r)&&n.equals(t[r],e[r],r,r,t,e,n)}const zYe="[object ArrayBuffer]",UYe="[object Arguments]",BYe="[object Boolean]",HYe="[object DataView]",qYe="[object Date]",$Ye="[object Error]",VYe="[object Map]",GYe="[object Number]",WYe="[object Object]",KYe="[object RegExp]",XYe="[object Set]",YYe="[object String]",QYe={"[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},ZYe="[object URL]",JYe=Object.prototype.toString;function eQe({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:i,areFunctionsEqual:s,areMapsEqual:o,areNumbersEqual:l,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:m,areTypedArraysEqual:p,areUrlsEqual:f,unknownTagComparators:x}){return function(g,b,_){if(g===b)return!0;if(g==null||b==null)return!1;const C=typeof g;if(C!==typeof b)return!1;if(C!=="object")return C==="number"?l(g,b,_):C==="function"?s(g,b,_):!1;const P=g.constructor;if(P!==b.constructor)return!1;if(P===Object)return c(g,b,_);if(Array.isArray(g))return e(g,b,_);if(P===Date)return r(g,b,_);if(P===RegExp)return u(g,b,_);if(P===Map)return o(g,b,_);if(P===Set)return m(g,b,_);const N=JYe.call(g);if(N===qYe)return r(g,b,_);if(N===KYe)return u(g,b,_);if(N===VYe)return o(g,b,_);if(N===XYe)return m(g,b,_);if(N===WYe)return typeof g.then!="function"&&typeof b.then!="function"&&c(g,b,_);if(N===ZYe)return f(g,b,_);if(N===$Ye)return i(g,b,_);if(N===UYe)return c(g,b,_);if(QYe[N])return p(g,b,_);if(N===zYe)return t(g,b,_);if(N===HYe)return n(g,b,_);if(N===BYe||N===GYe||N===YYe)return d(g,b,_);if(x){let A=x[N];if(!A){const T=_Ye(g);T&&(A=x[T])}if(A)return A(g,b,_)}return!1}}function tQe({circular:t,createCustomConfig:e,strict:n}){let r={areArrayBuffersEqual:TYe,areArraysEqual:n?$v:AYe,areDataViewsEqual:jYe,areDatesEqual:MYe,areErrorsEqual:EYe,areFunctionsEqual:DYe,areMapsEqual:n?YD(NX,$v):NX,areNumbersEqual:FYe,areObjectsEqual:n?$v:RYe,arePrimitiveWrappersEqual:LYe,areRegExpsEqual:OYe,areSetsEqual:n?YD(CX,$v):CX,areTypedArraysEqual:n?YD(BC,$v):BC,areUrlsEqual:IYe,unknownTagComparators:void 0};if(e&&(r=Object.assign({},r,e(r))),t){const i=dk(r.areArraysEqual),s=dk(r.areMapsEqual),o=dk(r.areObjectsEqual),l=dk(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:i,areMapsEqual:s,areObjectsEqual:o,areSetsEqual:l})}return r}function nQe(t){return function(e,n,r,i,s,o,l){return t(e,n,l)}}function rQe({circular:t,comparator:e,createState:n,equals:r,strict:i}){if(n)return function(l,c){const{cache:d=t?new WeakMap:void 0,meta:u}=n();return e(l,c,{cache:d,equals:r,meta:u,strict:i})};if(t)return function(l,c){return e(l,c,{cache:new WeakMap,equals:r,meta:void 0,strict:i})};const s={cache:void 0,equals:r,meta:void 0,strict:i};return function(l,c){return e(l,c,s)}}const aQe=Np();Np({strict:!0});Np({circular:!0});Np({circular:!0,strict:!0});Np({createInternalComparator:()=>Pg});Np({strict:!0,createInternalComparator:()=>Pg});Np({circular:!0,createInternalComparator:()=>Pg});Np({circular:!0,createInternalComparator:()=>Pg,strict:!0});function Np(t={}){const{circular:e=!1,createInternalComparator:n,createState:r,strict:i=!1}=t,s=tQe(t),o=eQe(s),l=n?n(o):nQe(o);return rQe({circular:e,comparator:o,createState:r,equals:l,strict:i})}var iQe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},sQe=({contentComponent:t})=>{const e=eO.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return a.jsx(a.Fragment,{children:Object.values(e)})};function oQe(){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]:khe.createPortal(r.reactElement,r.element,n)},t.forEach(i=>i())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(i=>i())}}}var lQe=class extends ea.Component{constructor(t){var e;super(t),this.editorContentRef=ea.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=oQe(),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 a.jsxs(a.Fragment,{children:[a.jsx("div",{ref:iQe(e,this.editorContentRef),...n}),t?.contentComponent&&a.jsx(sQe,{contentComponent:t.contentComponent})]})}},cQe=w.forwardRef((t,e)=>{const n=ea.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return ea.createElement(lQe,{key:n,innerRef:e,...t})}),hoe=ea.memo(cQe),dQe=typeof window<"u"?w.useLayoutEffect:w.useEffect,uQe=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 mQe(t){var e;const[n]=w.useState(()=>new uQe(t.editor)),r=aee.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:aQe);return dQe(()=>n.watch(t.editor),[t.editor,n]),w.useDebugValue(r),r}var hQe=!1,ML=typeof window>"u",pQe=ML||!!(typeof window<"u"&&window.next),fQe=class poe{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?ML||pQe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...r)},onBlur:(...r)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...r)},onCreate:(...r)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...r)},onDestroy:(...r)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...r)},onFocus:(...r)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...r)},onSelectionUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...r)},onTransaction:(...r)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...r)},onUpdate:(...r)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...r)},onContentError:(...r)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...r)},onDrop:(...r)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...r)},onPaste:(...r)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...r)},onDelete:(...r)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...r)}};return new cYe(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((i,s)=>{var o;return i===((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?poe.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,i)=>r===e[i]))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 gQe(t={},e=[]){const n=w.useRef(t);n.current=t;const[r]=w.useState(()=>new fQe(n)),i=eO.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return w.useDebugValue(i),w.useEffect(r.onRender(e)),mQe({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var foe=w.createContext({editor:null});foe.Consumer;var bQe=w.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),xQe=()=>w.useContext(bQe);ea.forwardRef((t,e)=>{const{onDragStart:n}=xQe(),r=t.as||"div";return a.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});ea.createContext({markViewContentRef:()=>{}});var Iz=w.createContext({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}});Iz.displayName="TiptapContext";var yQe=()=>w.useContext(Iz);function goe({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 i=w.useMemo(()=>({editor:r}),[r]),s=w.useMemo(()=>({editor:r}),[r]);return a.jsx(foe.Provider,{value:s,children:a.jsx(Iz.Provider,{value:i,children:n})})}goe.displayName="Tiptap";function boe({...t}){const{editor:e}=yQe();return a.jsx(hoe,{editor:e,...t})}boe.displayName="Tiptap.Content";Object.assign(goe,{Content:boe});var HC=(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]},vQe=/^\s*>\s$/,wQe=Ro.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return HC("blockquote",{...Xa(this.options.HTMLAttributes,t),children:HC("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(i=>{const l=e.renderChildren([i]).split(`
- `).map(c=>c.trim()===""?n:`${n} ${c}`);r.push(l.join(`
- `))}),r.join(`
- ${n}
- `)},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[ey({find:vQe,type:this.type})]}}),SQe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,_Qe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,kQe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,NQe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,CQe=kp.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 HC("strong",{...Xa(this.options.HTMLAttributes,t),children:HC("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[Jx({find:SQe,type:this.type}),Jx({find:kQe,type:this.type})]},addPasteRules(){return[bg({find:_Qe,type:this.type}),bg({find:NQe,type:this.type})]}}),PQe=/(^|[^`])`([^`]+)`(?!`)$/,TQe=/(^|[^`])`([^`]+)`(?!`)/g,AQe=kp.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",Xa(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[Jx({find:PQe,type:this.type})]},addPasteRules(){return[bg({find:TQe,type:this.type})]}}),QD=4,jQe=/^```([a-z]+)?[\s\n]$/,MQe=/^~~~([a-z]+)?[\s\n]$/,EQe=Ro.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:QD,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",Xa(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 i=((n=t.attrs)==null?void 0:n.language)||"";return t.content?r=[`\`\`\`${i}`,e.renderChildren(t.content),"```"].join(`
- `):r=`\`\`\`${i}
- \`\`\``,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:QD,{state:r}=t,{selection:i}=r,{$from:s,empty:o}=i;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:d,to:u}=i,f=r.doc.textBetween(d,u,`
- `,`
- `).split(`
- `).map(x=>l+x).join(`
- `);return c.replaceWith(d,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:QD,{state:r}=t,{selection:i}=r,{$from:s,empty:o}=i;return s.parent.type!==this.type?!1:o?t.commands.command(({tr:l})=>{var c;const{pos:d}=s,u=s.start(),m=s.end(),f=r.doc.textBetween(u,m,`
- `,`
- `).split(`
- `);let x=0,v=0;const g=d-u;for(let A=0;A<f.length;A+=1){if(v+f[A].length>=g){x=A;break}v+=f[A].length+1}const _=((c=f[x].match(/^ */))==null?void 0:c[0])||"",C=Math.min(_.length,n);if(C===0)return!0;let P=u;for(let A=0;A<x;A+=1)P+=f[A].length+1;return l.delete(P,P+C),d-P<=C&&l.setSelection($n.create(l.doc,P)),!0}):t.commands.command(({tr:l})=>{const{from:c,to:d}=i,p=r.doc.textBetween(c,d,`
- `,`
- `).split(`
- `).map(f=>{var x;const v=((x=f.match(/^ */))==null?void 0:x[0])||"",g=Math.min(v.length,n);return f.slice(g)}).join(`
- `);return l.replaceWith(c,d,r.schema.text(p)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;const s=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
- `);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:i,empty:s}=n;if(!s||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const l=i.after();return l===void 0?!1:r.nodeAt(l)?t.commands.command(({tr:d})=>(d.setSelection(ir.near(r.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[AL({find:jQe,type:this.type,getAttributes:t=>({language:t[1]})}),AL({find:MQe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new Ra({key:new Ei("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"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!n||!s)return!1;const{tr:o,schema:l}=t.state,c=l.text(n.replace(/\r\n?/g,`
- `));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection($n.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),DQe=Ro.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
- `):""}),FQe=Ro.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",Xa(this.options.HTMLAttributes,t)]},renderText(){return`
- `},renderMarkdown:()=>`
- `,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:i,storedMarks:s}=n;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&o){const m=c.filter(p=>l.includes(p.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),RQe=Ro.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]}`,Xa(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,i="#".repeat(r);return t.content?`${i} ${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=>AL({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),LQe=Ro.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Xa(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!mYe(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,i=t();return Wse(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,d=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection($n.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(Mn.create(o.doc,c.pos)):o.setSelection($n.create(o.doc,c.pos));else{const u=s.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,m=u?.create();m&&(o.insert(d,m),o.setSelection($n.create(o.doc,d+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[doe({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),OQe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,IQe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,zQe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,UQe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,BQe=kp.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",Xa(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[Jx({find:OQe,type:this.type}),Jx({find:zQe,type:this.type})]},addPasteRules(){return[bg({find:IQe,type:this.type}),bg({find:UQe,type:this.type})]}});const HQe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",qQe="ελ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",EL="numeric",DL="ascii",FL="alpha",N0="asciinumeric",s0="alphanumeric",RL="domain",xoe="emoji",$Qe="scheme",VQe="slashscheme",ZD="whitespace";function GQe(t,e){return t in e||(e[t]=[]),e[t]}function Mf(t,e,n){e[EL]&&(e[N0]=!0,e[s0]=!0),e[DL]&&(e[N0]=!0,e[FL]=!0),e[N0]&&(e[s0]=!0),e[FL]&&(e[s0]=!0),e[s0]&&(e[RL]=!0),e[xoe]&&(e[RL]=!0);for(const r in e){const i=GQe(r,n);i.indexOf(t)<0&&i.push(t)}}function WQe(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function No(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}No.groups={};No.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 i=e.jr[r][0],s=e.jr[r][1];if(s&&i.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 i=0;i<t.length;i++)this.tt(t[i],e,n,r)},tr(t,e,n,r){r=r||No.groups;let i;return e&&e.j?i=e:(i=new No(e),n&&r&&Mf(e,n,r)),this.jr.push([t,i]),i},ts(t,e,n,r){let i=this;const s=t.length;if(!s)return i;for(let o=0;o<s-1;o++)i=i.tt(t[o]);return i.tt(t[s-1],e,n,r)},tt(t,e,n,r){r=r||No.groups;const i=this;if(e&&e.j)return i.j[t]=e,e;const s=e;let o,l=i.go(t);if(l?(o=new No,Object.assign(o.j,l.j),o.jr.push.apply(o.jr,l.jr),o.jd=l.jd,o.t=l.t):o=new No,s){if(r)if(o.t&&typeof o.t=="string"){const c=Object.assign(WQe(o.t,r),n);Mf(s,c,r)}else n&&Mf(s,n,r);o.t=s}return i.j[t]=o,o}};const tr=(t,e,n,r,i)=>t.ta(e,n,r,i),Ia=(t,e,n,r,i)=>t.tr(e,n,r,i),PX=(t,e,n,r,i)=>t.ts(e,n,r,i),Kt=(t,e,n,r,i)=>t.tt(e,n,r,i),Tu="WORD",LL="UWORD",yoe="ASCIINUMERICAL",voe="ALPHANUMERICAL",Nw="LOCALHOST",OL="TLD",IL="UTLD",Gk="SCHEME",tx="SLASH_SCHEME",zz="NUM",zL="WS",Uz="NL",C0="OPENBRACE",P0="CLOSEBRACE",qC="OPENBRACKET",$C="CLOSEBRACKET",VC="OPENPAREN",GC="CLOSEPAREN",WC="OPENANGLEBRACKET",KC="CLOSEANGLEBRACKET",XC="FULLWIDTHLEFTPAREN",YC="FULLWIDTHRIGHTPAREN",QC="LEFTCORNERBRACKET",ZC="RIGHTCORNERBRACKET",JC="LEFTWHITECORNERBRACKET",eP="RIGHTWHITECORNERBRACKET",tP="FULLWIDTHLESSTHAN",nP="FULLWIDTHGREATERTHAN",rP="AMPERSAND",aP="APOSTROPHE",iP="ASTERISK",vh="AT",sP="BACKSLASH",oP="BACKTICK",lP="CARET",Ch="COLON",Bz="COMMA",cP="DOLLAR",ud="DOT",dP="EQUALS",Hz="EXCLAMATION",zl="HYPHEN",T0="PERCENT",uP="PIPE",mP="PLUS",hP="POUND",A0="QUERY",qz="QUOTE",woe="FULLWIDTHMIDDLEDOT",$z="SEMI",md="SLASH",j0="TILDE",pP="UNDERSCORE",Soe="EMOJI",fP="SYM";var _oe=Object.freeze({__proto__:null,ALPHANUMERICAL:voe,AMPERSAND:rP,APOSTROPHE:aP,ASCIINUMERICAL:yoe,ASTERISK:iP,AT:vh,BACKSLASH:sP,BACKTICK:oP,CARET:lP,CLOSEANGLEBRACKET:KC,CLOSEBRACE:P0,CLOSEBRACKET:$C,CLOSEPAREN:GC,COLON:Ch,COMMA:Bz,DOLLAR:cP,DOT:ud,EMOJI:Soe,EQUALS:dP,EXCLAMATION:Hz,FULLWIDTHGREATERTHAN:nP,FULLWIDTHLEFTPAREN:XC,FULLWIDTHLESSTHAN:tP,FULLWIDTHMIDDLEDOT:woe,FULLWIDTHRIGHTPAREN:YC,HYPHEN:zl,LEFTCORNERBRACKET:QC,LEFTWHITECORNERBRACKET:JC,LOCALHOST:Nw,NL:Uz,NUM:zz,OPENANGLEBRACKET:WC,OPENBRACE:C0,OPENBRACKET:qC,OPENPAREN:VC,PERCENT:T0,PIPE:uP,PLUS:mP,POUND:hP,QUERY:A0,QUOTE:qz,RIGHTCORNERBRACKET:ZC,RIGHTWHITECORNERBRACKET:eP,SCHEME:Gk,SEMI:$z,SLASH:md,SLASH_SCHEME:tx,SYM:fP,TILDE:j0,TLD:OL,UNDERSCORE:pP,UTLD:IL,UWORD:LL,WORD:Tu,WS:zL});const _u=/[a-z]/,Vv=new RegExp("\\p{L}","u"),JD=new RegExp("\\p{Emoji}","u"),ku=/\d/,e3=/\s/,TX="\r",t3=`
- `,KQe="️",XQe="",n3="";let uk=null,mk=null;function YQe(t=[]){const e={};No.groups=e;const n=new No;uk==null&&(uk=AX(HQe)),mk==null&&(mk=AX(qQe)),Kt(n,"'",aP),Kt(n,"{",C0),Kt(n,"}",P0),Kt(n,"[",qC),Kt(n,"]",$C),Kt(n,"(",VC),Kt(n,")",GC),Kt(n,"<",WC),Kt(n,">",KC),Kt(n,"(",XC),Kt(n,")",YC),Kt(n,"「",QC),Kt(n,"」",ZC),Kt(n,"『",JC),Kt(n,"』",eP),Kt(n,"<",tP),Kt(n,">",nP),Kt(n,"&",rP),Kt(n,"*",iP),Kt(n,"@",vh),Kt(n,"`",oP),Kt(n,"^",lP),Kt(n,":",Ch),Kt(n,",",Bz),Kt(n,"$",cP),Kt(n,".",ud),Kt(n,"=",dP),Kt(n,"!",Hz),Kt(n,"-",zl),Kt(n,"%",T0),Kt(n,"|",uP),Kt(n,"+",mP),Kt(n,"#",hP),Kt(n,"?",A0),Kt(n,'"',qz),Kt(n,"/",md),Kt(n,";",$z),Kt(n,"~",j0),Kt(n,"_",pP),Kt(n,"\\",sP),Kt(n,"・",woe);const r=Ia(n,ku,zz,{[EL]:!0});Ia(r,ku,r);const i=Ia(r,_u,yoe,{[N0]:!0}),s=Ia(r,Vv,voe,{[s0]:!0}),o=Ia(n,_u,Tu,{[DL]:!0});Ia(o,ku,i),Ia(o,_u,o),Ia(i,ku,i),Ia(i,_u,i);const l=Ia(n,Vv,LL,{[FL]:!0});Ia(l,_u),Ia(l,ku,s),Ia(l,Vv,l),Ia(s,ku,s),Ia(s,_u),Ia(s,Vv,s);const c=Kt(n,t3,Uz,{[ZD]:!0}),d=Kt(n,TX,zL,{[ZD]:!0}),u=Ia(n,e3,zL,{[ZD]:!0});Kt(n,n3,u),Kt(d,t3,c),Kt(d,n3,u),Ia(d,e3,u),Kt(u,TX),Kt(u,t3),Ia(u,e3,u),Kt(u,n3,u);const m=Ia(n,JD,Soe,{[xoe]:!0});Kt(m,"#"),Ia(m,JD,m),Kt(m,KQe,m);const p=Kt(m,XQe);Kt(p,"#"),Ia(p,JD,m);const f=[[_u,o],[ku,i]],x=[[_u,null],[Vv,l],[ku,s]];for(let v=0;v<uk.length;v++)dh(n,uk[v],OL,Tu,f);for(let v=0;v<mk.length;v++)dh(n,mk[v],IL,LL,x);Mf(OL,{tld:!0,ascii:!0},e),Mf(IL,{utld:!0,alpha:!0},e),dh(n,"file",Gk,Tu,f),dh(n,"mailto",Gk,Tu,f),dh(n,"http",tx,Tu,f),dh(n,"https",tx,Tu,f),dh(n,"ftp",tx,Tu,f),dh(n,"ftps",tx,Tu,f),Mf(Gk,{scheme:!0,ascii:!0},e),Mf(tx,{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]?{[$Qe]:!0}:{[VQe]:!0};g.indexOf("-")>=0?_[RL]=!0:_u.test(g)?ku.test(g)?_[N0]=!0:_[DL]=!0:_[EL]=!0,PX(n,g,g,_)}return PX(n,"localhost",Nw,{ascii:!0}),n.jd=new No(fP),{start:n,tokens:Object.assign({groups:e},_oe)}}function koe(t,e){const n=QQe(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,i=[];let s=0,o=0;for(;o<r;){let l=t,c=null,d=0,u=null,m=-1,p=-1;for(;o<r&&(c=l.go(n[o]));)l=c,l.accepts()?(m=0,p=0,u=l):m>=0&&(m+=n[o].length,p++),d+=n[o].length,s+=n[o].length,o++;s-=m,o-=p,d-=m,i.push({t:u.t,v:e.slice(s-d,s),s:s-d,e:s})}return i}function QQe(t){const e=[],n=t.length;let r=0;for(;r<n;){let i=t.charCodeAt(r),s,o=i<55296||i>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 dh(t,e,n,r,i){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 No(r),s.jr=i.slice(),t.j[c]=s),t=s}return s=new No(n),s.jr=i.slice(),t.j[e[o-1]]=s,s}function AX(t){const e=[],n=[];let r=0,i="0123456789";for(;r<t.length;){let s=0;for(;i.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 Cw={defaultProtocol:"http",events:null,format:jX,formatHref:jX,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Vz(t,e=null){let n=Object.assign({},Cw);t&&(n=Object.assign(n,t instanceof Vz?t.o:t));const r=n.ignoreTags,i=[];for(let s=0;s<r.length;s++)i.push(r[s].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=i}Vz.prototype={o:Cw,ignoreTags:[],defaultRender(t){return t},check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const r=e!=null;let i=this.o[t];return i&&(typeof i=="object"?(i=n.t in i?i[n.t]:Cw[t],typeof i=="function"&&r&&(i=i(e,n))):typeof i=="function"&&r&&(i=i(e,n.t,n)),i)},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 jX(t){return t}function Noe(t,e){this.t="token",this.v=t,this.tk=e}Noe.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=Cw.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),i=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),c=t.get("target",n,e),d=t.get("rel",n,e),u=t.getObj("attributes",n,e),m=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),c&&(o.target=c),d&&(o.rel=d),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:m}}};function eA(t,e){class n extends Noe{constructor(i,s){super(i,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const MX=eA("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),EX=eA("text"),ZQe=eA("nl"),hk=eA("url",{isLink:!0,toHref(t=Cw.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==Nw&&t[1].t===Ch}}),Ll=t=>new No(t);function JQe({groups:t}){const e=t.domain.concat([rP,iP,vh,sP,oP,lP,cP,dP,zl,zz,T0,uP,mP,hP,md,fP,j0,pP]),n=[aP,Ch,Bz,ud,Hz,T0,A0,qz,$z,WC,KC,C0,P0,$C,qC,VC,GC,XC,YC,QC,ZC,JC,eP,tP,nP],r=[rP,aP,iP,sP,oP,lP,cP,dP,zl,C0,P0,T0,uP,mP,hP,A0,md,fP,j0,pP],i=Ll(),s=Kt(i,j0);tr(s,r,s),tr(s,t.domain,s);const o=Ll(),l=Ll(),c=Ll();tr(i,t.domain,o),tr(i,t.scheme,l),tr(i,t.slashscheme,c),tr(o,r,s),tr(o,t.domain,o);const d=Kt(o,vh);Kt(s,vh,d),Kt(l,vh,d),Kt(c,vh,d);const u=Kt(s,ud);tr(u,r,s),tr(u,t.domain,s);const m=Ll();tr(d,t.domain,m),tr(m,t.domain,m);const p=Kt(m,ud);tr(p,t.domain,m);const f=Ll(MX);tr(p,t.tld,f),tr(p,t.utld,f),Kt(d,Nw,f);const x=Kt(m,zl);Kt(x,zl,x),tr(x,t.domain,m),tr(f,t.domain,m),Kt(f,ud,p),Kt(f,zl,x);const v=Kt(f,Ch);tr(v,t.numeric,MX);const g=Kt(o,zl),b=Kt(o,ud);Kt(g,zl,g),tr(g,t.domain,o),tr(b,r,s),tr(b,t.domain,o);const _=Ll(hk);tr(b,t.tld,_),tr(b,t.utld,_),tr(_,t.domain,o),tr(_,r,s),Kt(_,ud,b),Kt(_,zl,g),Kt(_,vh,d);const C=Kt(_,Ch),P=Ll(hk);tr(C,t.numeric,P);const N=Ll(hk),A=Ll();tr(N,e,N),tr(N,n,A),tr(A,e,N),tr(A,n,A),Kt(_,md,N),Kt(P,md,N);const T=Kt(l,Ch),F=Kt(c,Ch),k=Kt(F,md),D=Kt(k,md);tr(l,t.domain,o),Kt(l,ud,b),Kt(l,zl,g),tr(c,t.domain,o),Kt(c,ud,b),Kt(c,zl,g),tr(T,t.domain,N),Kt(T,md,N),Kt(T,A0,N),tr(D,t.domain,N),tr(D,e,N),Kt(D,md,N);const H=[[C0,P0],[qC,$C],[VC,GC],[WC,KC],[XC,YC],[QC,ZC],[JC,eP],[tP,nP]];for(let z=0;z<H.length;z++){const[X,L]=H[z],ne=Kt(N,X);Kt(A,X,ne),Kt(ne,L,N);const ie=Ll(hk);tr(ne,e,ie);const ee=Ll();tr(ne,n),tr(ie,e,ie),tr(ie,n,ee),tr(ee,e,ie),tr(ee,n,ee),Kt(ie,L,N),Kt(ee,L,N)}return Kt(i,Nw,_),Kt(i,Uz,ZQe),{start:i,tokens:_oe}}function eZe(t,e,n){let r=n.length,i=0,s=[],o=[];for(;i<r;){let l=t,c=null,d=null,u=0,m=null,p=-1;for(;i<r&&!(c=l.go(n[i].t));)o.push(n[i++]);for(;i<r&&(d=c||l.go(n[i].t));)c=null,l=d,l.accepts()?(p=0,m=l):p>=0&&p++,i++,u++;if(p<0)i-=u,i<r&&(o.push(n[i]),i++);else{o.length>0&&(s.push(r3(EX,e,o)),o=[]),i-=p,u-=p;const f=m.t,x=n.slice(i-u,i);s.push(r3(f,e,x))}}return o.length>0&&s.push(r3(EX,e,o)),s}function r3(t,e,n){const r=n[0].s,i=n[n.length-1].e,s=e.slice(r,i);return new t(s,n)}const tZe=typeof console<"u"&&console&&console.warn||(()=>{}),nZe="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",ba={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function rZe(){return No.groups={},ba.scanner=null,ba.parser=null,ba.tokenQueue=[],ba.pluginQueue=[],ba.customSchemes=[],ba.initialized=!1,ba}function DX(t,e=!1){if(ba.initialized&&tZe(`linkifyjs: already initialized - will not register custom scheme "${t}" ${nZe}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format.
- 1. Must only contain digits, lowercase ASCII letters or "-"
- 2. Cannot start or end with "-"
- 3. "-" cannot repeat`);ba.customSchemes.push([t,e])}function aZe(){ba.scanner=YQe(ba.customSchemes);for(let t=0;t<ba.tokenQueue.length;t++)ba.tokenQueue[t][1]({scanner:ba.scanner});ba.parser=JQe(ba.scanner.tokens);for(let t=0;t<ba.pluginQueue.length;t++)ba.pluginQueue[t][1]({scanner:ba.scanner,parser:ba.parser});return ba.initialized=!0,ba}function Gz(t){return ba.initialized||aZe(),eZe(ba.parser.start,t,koe(ba.scanner.start,t))}Gz.scan=koe;function Coe(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 Vz(n),i=Gz(t),s=[];for(let o=0;o<i.length;o++){const l=i[o];l.isLink&&(!e||l.t===e)&&r.check(l)&&s.push(l.toFormattedObject(r))}return s}var Wz="[\0- -\u2029 ]",iZe=new RegExp(Wz),sZe=new RegExp(`${Wz}$`),oZe=new RegExp(Wz,"g");function lZe(t){return t.length===1?t[0].isLink:t.length===3&&t[1].isLink?["()","[]"].includes(t[0].value+t[2].value):!1}function cZe(t){return new Ra({key:new Ei("autolink"),appendTransaction:(e,n,r)=>{const i=e.some(d=>d.docChanged)&&!n.doc.eq(r.doc),s=e.some(d=>d.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=zse(n.doc,[...e]);if(Gse(l).forEach(({newRange:d})=>{const u=uXe(r.doc,d,f=>f.isTextblock);let m,p;if(u.length>1)m=u[0],p=r.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!sZe.test(f))return;m=u[0],p=r.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&p){const f=p.split(iZe).filter(Boolean);if(f.length<=0)return!1;const x=f[f.length-1],v=m.pos+p.lastIndexOf(x);if(!x)return!1;const g=Gz(x).map(b=>b.toObject(t.defaultProtocol));if(!lZe(g))return!1;g.filter(b=>b.isLink).map(b=>({...b,from:v+b.start+1,to:v+b.end+1})).filter(b=>r.schema.marks.code?!r.doc.rangeHasMark(b.from,b.to,r.schema.marks.code):!0).filter(b=>t.validate(b.value)).filter(b=>t.shouldAutoLink(b.value)).forEach(b=>{Dz(b.from,b.to,r.doc).some(_=>_.mark.type===t.type)||o.addMark(b.from,b.to,t.type.create({href:b.href}))})}}),!!o.steps.length)return o}})}function dZe(t){return new Ra({key:new Ei("handleClickLink"),props:{handleClick:(e,n,r)=>{var i,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 d=t.editor.view.dom;o=c.closest("a"),o&&!d.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=Vse(e.state,t.type.name),d=(i=o.href)!=null?i:c.href,u=(s=o.target)!=null?s:c.target;d&&(window.open(d,u),l=!0)}return l}}})}function uZe(t){return new Ra({key:new Ei("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(u=>{c+=u.textContent});const d=Coe(c,{defaultProtocol:t.defaultProtocol}).find(u=>u.isLink&&u.value===c);return!c||!d||i!==void 0&&!i(d.value)?!1:t.editor.commands.setMark(t.type,{href:d.href})}}})}function rf(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&n.push(i)}),!t||t.replace(oZe,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var Poe=kp.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"){DX(t);return}DX(t.scheme,t.optionalSlashes)})},onDestroy(){rZe()},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)=>!!rf(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 i=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(i)||!/\./.test(i))}}},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=>!!rf(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=>!!rf(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Xa(this.options.HTMLAttributes,t),0]:["a",Xa(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,i,s;const o=(r=(n=t.attrs)==null?void 0:n.href)!=null?r:"",l=(s=(i=t.attrs)==null?void 0:i.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=>!!rf(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=>!!rf(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[bg({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,i=Coe(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!rf(o,n),protocols:n,defaultProtocol:r}));i.length&&i.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(cZe({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!rf(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(dZe({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(uZe({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),mZe=Poe,hZe=Object.defineProperty,pZe=(t,e)=>{for(var n in e)hZe(t,n,{get:e[n],enumerable:!0})},fZe="listItem",FX="textStyle",RX=/^\s*([-+*])\s$/,Toe=Ro.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",Xa(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,`
- `):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(fZe,this.editor.getAttributes(FX)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=ey({find:RX,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=ey({find:RX,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(FX),editor:this.editor})),[t]}}),Aoe=Ro.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",Xa(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(i=>i.type==="paragraph"))n=e.parseChildren(t.tokens);else{const i=t.tokens[0];if(i&&i.type==="text"&&i.tokens&&i.tokens.length>0){if(n=[{type:"paragraph",content:e.parseInline(i.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)=>Oz(t,e,r=>{var i,s;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((s=(i=r.meta)==null?void 0:i.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)}}}),gZe={};pZe(gZe,{findListItemPos:()=>SS,getNextListDepth:()=>Kz,handleBackspace:()=>UL,handleDelete:()=>BL,hasListBefore:()=>joe,hasListItemAfter:()=>bZe,hasListItemBefore:()=>Moe,listItemHasSubList:()=>Eoe,nextListIsDeeper:()=>Doe,nextListIsHigher:()=>Foe});var SS=(t,e)=>{const{$from:n}=e.selection,r=bi(t,e.schema);let i=null,s=n.depth,o=n.pos,l=null;for(;s>0&&l===null;)i=n.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},Kz=(t,e)=>{const n=SS(t,e);if(!n)return!1;const[,r]=wXe(e,t,n.$pos.pos+4);return r},joe=(t,e,n)=>{const{$anchor:r}=t.selection,i=Math.max(0,r.pos-2),s=t.doc.resolve(i).node();return!(!s||!n.includes(s.type.name))},Moe=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-2);return!(i.index()===0||((n=i.nodeBefore)==null?void 0:n.type.name)!==t)},Eoe=(t,e,n)=>{if(!n)return!1;const r=bi(t,e.schema);let i=!1;return n.descendants(s=>{s.type===r&&(i=!0)}),i},UL=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!hp(t.state,e)&&joe(t.state,e,n)){const{$anchor:l}=t.state.selection,c=t.state.doc.resolve(l.before()-1),d=[];c.node().descendants((p,f)=>{p.type.name===e&&d.push({node:p,pos:f})});const u=d.at(-1);if(!u)return!1;const m=t.state.doc.resolve(c.start()+u.pos+1);return t.chain().cut({from:l.start()-1,to:l.end()+1},m.end()).joinForward().run()}if(!hp(t.state,e)||!NXe(t.state))return!1;const r=SS(e,t.state);if(!r)return!1;const s=t.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=Eoe(e,t.state,s);return Moe(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},Doe=(t,e)=>{const n=Kz(t,e),r=SS(t,e);return!r||!n?!1:n>r.depth},Foe=(t,e)=>{const n=Kz(t,e),r=SS(t,e);return!r||!n?!1:n<r.depth},BL=(t,e)=>{if(!hp(t.state,e)||!kXe(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:i}=n;return!n.empty&&r.sameParent(i)?!1:Doe(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():Foe(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},bZe=(t,e)=>{var n;const{$anchor:r}=e.selection,i=e.doc.resolve(r.pos-r.parentOffset-2);return!(i.index()===i.parent.childCount-1||((n=i.nodeAfter)==null?void 0:n.type.name)!==t)},Roe=Qr.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&&BL(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&&BL(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&&UL(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&&UL(t,n,r)&&(e=!0)}),e}}}}),LX=/^(\s*)(\d+)\.\s+(.*)$/,xZe=/^\s/;function yZe(t){const e=[];let n=0,r=0;for(;n<t.length;){const i=t[n],s=i.match(LX);if(!s)break;const[,o,l,c]=s,d=o.length;let u=c,m=n+1;const p=[i];for(;m<t.length;){const f=t[m];if(f.match(LX))break;if(f.trim()==="")p.push(f),u+=`
- `,m+=1;else if(f.match(xZe))p.push(f),u+=`
- ${f.slice(d+2)}`,m+=1;else break}e.push({indent:d,number:parseInt(l,10),content:u.trim(),raw:p.join(`
- `)}),r=m,n=m}return[e,r]}function Loe(t,e,n){var r;const i=[];let s=0;for(;s<t.length;){const o=t[s];if(o.indent===e){const l=o.content.split(`
- `),c=((r=l[0])==null?void 0:r.trim())||"",d=[];c&&d.push({type:"paragraph",raw:c,tokens:n.inlineTokens(c)});const u=l.slice(1).join(`
- `).trim();if(u){const f=n.blockTokens(u);d.push(...f)}let m=s+1;const p=[];for(;m<t.length&&t[m].indent>e;)p.push(t[m]),m+=1;if(p.length>0){const f=Math.min(...p.map(v=>v.indent)),x=Loe(p,f,n);d.push({type:"list",ordered:!0,start:p[0].number,items:x,raw:p.map(v=>v.raw).join(`
- `)})}i.push({type:"list_item",raw:o.raw,tokens:d}),s=m}else s+=1}return i}function vZe(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(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}var wZe="listItem",OX="textStyle",IX=/^(\d+)\.\s$/,Ooe=Ro.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",Xa(this.options.HTMLAttributes,n),0]:["ol",Xa(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?vZe(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,`
- `):"",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 i=t.split(`
- `),[s,o]=yZe(i);if(s.length===0)return;const l=Loe(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:i.slice(0,o).join(`
- `)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(wZe,this.editor.getAttributes(OX)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=ey({find:IX,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=ey({find:IX,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(OX)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),SZe=/^\s*(\[([( |x])?\])\s$/,_Ze=Ro.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",Xa(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 i=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return Oz(t,e,i)},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 i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),d=m=>{var p,f;l.ariaLabel=((f=(p=this.options.a11y)==null?void 0:p.checkboxLabel)==null?void 0:f.call(p,m,l.checked))||`Task item checkbox for ${m.textContent||"empty task item"}`};d(t),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",m=>m.preventDefault()),l.addEventListener("change",m=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:p}=m.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const x=n();if(typeof x!="number")return!1;const v=f.doc.nodeAt(x);return f.setNodeMarkup(x,void 0,{...v?.attrs,checked:p}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,p)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([m,p])=>{i.setAttribute(m,p)}),i.dataset.checked=t.attrs.checked,l.checked=t.attrs.checked,s.append(l,o),i.append(s,c),Object.entries(e).forEach(([m,p])=>{i.setAttribute(m,p)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:c,update:m=>{if(m.type!==this.type)return!1;i.dataset.checked=m.attrs.checked,l.checked=m.attrs.checked,d(m);const p=r.extensionManager.attributes,f=kw(m,p),x=new Set(Object.keys(f)),v=this.options.HTMLAttributes;return u.forEach(g=>{x.has(g)||(g in v?i.setAttribute(g,v[g]):i.removeAttribute(g))}),Object.entries(f).forEach(([g,b])=>{b==null?g in v?i.setAttribute(g,v[g]):i.removeAttribute(g):i.setAttribute(g,b)}),u=x,!0}}}},addInputRules(){return[ey({find:SZe,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),kZe=Ro.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",Xa(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,`
- `):"",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=jL(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)},i=jL(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(i)return{type:"taskList",raw:i.raw,items:i.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()}}});Qr.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(Toe.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(Aoe.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(Roe.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(Ooe.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(_Ze.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(kZe.configure(this.options.taskList)),t}});var zX=" ",NZe=" ",CZe=Ro.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Xa(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===zX||r[0].text===NZe)?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?zX:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),PZe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,TZe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,AZe=kp.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",Xa(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[Jx({find:PZe,type:this.type})]},addPasteRules(){return[bg({find:TZe,type:this.type})]}}),jZe=Ro.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),Ioe=kp.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",Xa(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 i=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!i)return;const s=i[2].trim();return{type:"underline",raw:i[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()}}}),MZe=Ioe;function EZe(t={}){return new Ra({view(e){return new DZe(e,t)}})}class DZe{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(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,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,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(n){let m=e.nodeBefore,p=e.nodeAfter;if(m||p){let f=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(f){let x=f.getBoundingClientRect(),v=m?x.bottom:x.top;m&&p&&(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 m=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*o;r={left:m.left-p,right:m.left+p,top:m.top,bottom:m.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 d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let m=c.getBoundingClientRect(),p=m.width/c.offsetWidth,f=m.height/c.offsetHeight;d=m.left-c.scrollLeft*p,u=m.top-c.scrollTop*f}this.element.style.left=(r.left-d)/o+"px",this.element.style.top=(r.top-u)/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),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,n,e):i;if(n&&!s){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=jie(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 qa extends ir{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return qa.valid(r)?new qa(r):ir.near(r)}content(){return cn.empty}eq(e){return e instanceof qa&&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 qa(e.resolve(n.pos))}getBookmark(){return new Xz(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!FZe(e)||!RZe(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let i=n.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&qa.valid(e))return e;let i=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;i+=n;let c=e.doc.resolve(i);if(qa.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!Mn.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*n),r=!1;continue e}break}s=o,i+=n;let l=e.doc.resolve(i);if(qa.valid(l))return l}return null}}}qa.prototype.visible=!1;qa.findFrom=qa.findGapCursorFrom;ir.jsonID("gapcursor",qa);class Xz{constructor(e){this.pos=e}map(e){return new Xz(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return qa.valid(n)?new qa(n):ir.near(n)}}function zoe(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function FZe(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 i=r.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||zoe(i.type))return!0;if(i.inlineContent)return!1}}return!0}function RZe(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 i=r.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||zoe(i.type))return!0;if(i.inlineContent)return!1}}return!0}function LZe(){return new Ra({props:{decorations:UZe,createSelectionBetween(t,e,n){return e.pos==n.pos&&qa.valid(n)?new qa(n):null},handleClick:IZe,handleKeyDown:OZe,handleDOMEvents:{beforeinput:zZe}}})}const OZe=Mse({ArrowLeft:pk("horiz",-1),ArrowRight:pk("horiz",1),ArrowUp:pk("vert",-1),ArrowDown:pk("vert",1)});function pk(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof $n){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let d=qa.findGapCursorFrom(l,e,c);return d?(i&&i(r.tr.setSelection(new qa(d))),!0):!1}}function IZe(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!qa.valid(r))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});return i&&i.inside>-1&&Mn.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new qa(r))),!0)}function zZe(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof qa))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 i=Vt.empty;for(let o=r.length-1;o>=0;o--)i=Vt.from(r[o].createAndFill(null,i));let s=t.state.tr.replace(n.pos,n.pos,new cn(i,0,0));return s.setSelection($n.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function UZe(t){if(!(t.selection instanceof qa))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Aa.create(t.doc,[Ys.widget(t.selection.head,e,{key:"gapcursor"})])}var gP=200,qi=function(){};qi.prototype.append=function(e){return e.length?(e=qi.from(e),!this.length&&e||e.length<gP&&this.leafAppend(e)||this.length<gP&&e.leafPrepend(this)||this.appendInner(e)):this};qi.prototype.prepend=function(e){return e.length?qi.from(e).append(this):this};qi.prototype.appendInner=function(e){return new BZe(this,e)};qi.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?qi.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};qi.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};qi.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)};qi.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},n,r),i};qi.from=function(e){return e instanceof qi?e:e&&e.length?new Uoe(e):qi.empty};var Uoe=(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(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var c=s;c<o;c++)if(i(this.values[c],l+c)===!1)return!1},e.prototype.forEachInvertedInner=function(i,s,o,l){for(var c=s-1;c>=o;c--)if(i(this.values[c],l+c)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=gP)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=gP)return new e(i.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(qi);qi.empty=new Uoe([]);var BZe=(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,i,s,o){var l=this.left.length;if(i<l&&this.left.forEachInner(r,i,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(r,Math.min(i,l),s,o)===!1)return!1},e.prototype.sliceInner=function(r,i){if(r==0&&i==this.length)return this;var s=this.left.length;return i<=s?this.left.slice(r,i):r>=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,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})(qi);const HZe=500;class Fc{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 i,s;n&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,c,d=[],u=[];return this.items.forEach((m,p)=>{if(!m.step){i||(i=this.remapping(r,p+1),s=i.maps.length),s--,u.push(m);return}if(i){u.push(new hd(m.map));let f=m.step.map(i.slice(s)),x;f&&o.maybeStep(f).doc&&(x=o.mapping.maps[o.mapping.maps.length-1],d.push(new hd(x,void 0,void 0,d.length+u.length))),s--,x&&i.appendMap(x,s)}else o.maybeStep(m.step);if(m.selection)return l=i?m.selection.map(i.slice(s)):m.selection,c=new Fc(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,r,i){let s=[],o=this.eventCount,l=this.items,c=!i&&l.length?l.get(l.length-1):null;for(let u=0;u<e.steps.length;u++){let m=e.steps[u].invert(e.docs[u]),p=new hd(e.mapping.maps[u],m,n),f;(f=c&&c.merge(p))&&(p=f,u?s.pop():l=l.slice(0,l.length-1)),s.push(p),n&&(o++,n=void 0),i||(c=p)}let d=o-r.depth;return d>$Ze&&(l=qZe(l,d),o-=d),new Fc(l.append(s),o)}remapping(e,n){let r=new xw;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,n),r}addMaps(e){return this.eventCount==0?this:new Fc(this.items.append(e.map(n=>new hd(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],i=Math.max(0,this.items.length-n),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(p=>{p.selection&&l--},i);let c=n;this.items.forEach(p=>{let f=s.getMirror(--c);if(f==null)return;o=Math.min(o,f);let x=s.maps[f];if(p.step){let v=e.steps[f].invert(e.docs[f]),g=p.selection&&p.selection.map(s.slice(c+1,f));g&&l++,r.push(new hd(x,v,g))}else r.push(new hd(x))},i);let d=[];for(let p=n;p<o;p++)d.push(new hd(s.maps[p]));let u=this.items.slice(0,i).append(d).append(r),m=new Fc(u,l);return m.emptyItemCount()>HZe&&(m=m.compress(this.items.length-r.length)),m}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,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let c=o.step.map(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=o.selection&&o.selection.map(n.slice(r));u&&s++;let m=new hd(d.invert(),c,u),p,f=i.length-1;(p=i.length&&i[f].merge(m))?i[f]=p:i.push(m)}}else o.map&&r--},this.items.length,0),new Fc(qi.from(i.reverse()),s)}}Fc.empty=new Fc(qi.empty,0);function qZe(t,e){let n;return t.forEach((r,i)=>{if(r.selection&&e--==0)return n=i,!1}),t.slice(n)}class hd{constructor(e,n,r,i){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new hd(n.getMap().invert(),n,this.selection)}}}class wh{constructor(e,n,r,i,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const $Ze=20;function VZe(t,e,n,r){let i=n.getMeta(qf),s;if(i)return i.historyState;n.getMeta(KZe)&&(t=new wh(t.done,t.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(o&&o.getMeta(qf))return o.getMeta(qf).redo?new wh(t.done.addTransform(n,void 0,r,Wk(e)),t.undone,UX(n.mapping.maps),t.prevTime,t.prevComposition):new wh(t.done,t.undone.addTransform(n,void 0,r,Wk(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||!GZe(n,t.prevRanges)),d=o?a3(t.prevRanges,n.mapping):UX(n.mapping.maps);return new wh(t.done.addTransform(n,c?e.selection.getBookmark():void 0,r,Wk(e)),Fc.empty,d,n.time,l??t.prevComposition)}else return(s=n.getMeta("rebased"))?new wh(t.done.rebased(n,s),t.undone.rebased(n,s),a3(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new wh(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),a3(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function GZe(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,i)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&i>=e[s]&&(n=!0)}),n}function UX(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,i,s,o)=>e.push(s,o));return e}function a3(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let i=e.map(t[r],1),s=e.map(t[r+1],-1);i<=s&&n.push(i,s)}return n}function WZe(t,e,n){let r=Wk(e),i=qf.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(),i,r),c=new wh(n?l:s.remaining,n?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(qf,{redo:n,historyState:c})}let i3=!1,BX=null;function Wk(t){let e=t.plugins;if(BX!=e){i3=!1,BX=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){i3=!0;break}}return i3}const qf=new Ei("history"),KZe=new Ei("closeHistory");function XZe(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new Ra({key:qf,state:{init(){return new wh(Fc.empty,Fc.empty,null,0,-1)},apply(e,n,r){return VZe(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,i=r=="historyUndo"?Hoe:r=="historyRedo"?qoe:null;return!i||!e.editable?!1:(n.preventDefault(),i(e.state,e.dispatch))}}}})}function Boe(t,e){return(n,r)=>{let i=qf.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(r){let s=WZe(i,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const Hoe=Boe(!1,!0),qoe=Boe(!0,!0);Qr.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 Ra({key:new Ei("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const i=this.options.limit;if(i==null||i===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>i){const o=s-i,l=0,c=o;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const d=r.tr.deleteRange(l,c);return t=!0,d}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-r,d=l-c,u=l;return e.deleteRange(d,u),!(this.storage.characters({node:e.doc})>r)}})]}});var YZe=Qr.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[EZe(this.options)]}});Qr.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Ra({key:new Ei("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!n||!r)return Aa.create(t,[]);let o=0;this.options.mode==="deepest"&&t.descendants((c,d)=>{if(c.isText)return;if(!(i>=d&&i<=d+c.nodeSize-1))return!1;o+=1});let l=0;return t.descendants((c,d)=>{if(c.isText||!(i>=d&&i<=d+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(Ys.node(d,d+c.nodeSize,{class:this.options.className}))}),Aa.create(t,s)}}})]}});var QZe=Qr.create({name:"gapCursor",addProseMirrorPlugins(){return[LZe()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Ir(An(t,"allowGapCursor",n)))!=null?e:null}}}),HX="placeholder";function ZZe(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}Qr.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:HX,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${ZZe(this.options.dataAttribute)}`:`data-${HX}`;return[new Ra({key:new Ei("placeholder"),props:{decorations:({doc:e,selection:n})=>{const r=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:i}=n,s=[];if(!r)return null;const o=this.editor.isEmpty;return e.descendants((l,c)=>{const d=i>=c&&i<=c+l.nodeSize,u=!l.isLeaf&&QT(l);if((d||!this.options.showOnlyCurrent)&&u){const m=[this.options.emptyNodeClass];o&&m.push(this.options.emptyEditorClass);const p=Ys.node(c,c+l.nodeSize,{class:m.join(" "),[t]:typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:l,pos:c,hasAnchor:d}):this.options.placeholder});s.push(p)}return this.options.includeChildren}),Aa.create(e,s)}}})]}});Qr.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new Ra({key:new Ei("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||Wse(n.selection)||t.view.dragging?null:Aa.create(n.doc,[Ys.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function qX({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var JZe=Qr.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Ei(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(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(n).includes(i.name));return[new Ra({key:e,appendTransaction:(i,s,o)=>{const{doc:l,tr:c,schema:d}=o,u=e.getState(o),m=l.content.size,p=d.nodes[n];if(u)return c.insert(m,p.create())},state:{init:(i,s)=>{const o=s.tr.doc.lastChild;return!qX({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!qX({node:o,types:r})}}})]}}),eJe=Qr.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>Hoe(t,e),redo:()=>({state:t,dispatch:e})=>qoe(t,e)}},addProseMirrorPlugins(){return[XZe(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()}}}),tJe=Qr.create({name:"starterKit",addExtensions(){var t,e,n,r;const i=[];return this.options.bold!==!1&&i.push(CQe.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(wQe.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(Toe.configure(this.options.bulletList)),this.options.code!==!1&&i.push(AQe.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(EQe.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(DQe.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(YZe.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(QZe.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(FQe.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(RQe.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(eJe.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(LQe.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(BQe.configure(this.options.italic)),this.options.listItem!==!1&&i.push(Aoe.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(Roe.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&i.push(Poe.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(Ooe.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(CZe.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(AZe.configure(this.options.strike)),this.options.text!==!1&&i.push(jZe.configure(this.options.text)),this.options.underline!==!1&&i.push(Ioe.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&i.push(JZe.configure((r=this.options)==null?void 0:r.trailingNode)),i}}),nJe=tJe,rJe=Qr.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")}}}),aJe=rJe,iJe=20,$oe=(t,e=0)=>{const n=[];return!t.children.length||e>iJe||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...$oe(r,e+1))}),n},sJe=t=>{if(!t.children.length)return;const e=$oe(t);e&&e.forEach(n=>{var r,i;const s=n.getAttribute("style"),o=(i=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:i.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},Voe=kp.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&sJe(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Xa(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(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),oJe=Qr.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(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].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()}}}),Goe=Qr.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(i=>i.trim()).filter(Boolean);for(let i=r.length-1;i>=0;i-=1){const s=r[i].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()}}}),lJe=Qr.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()}}}),cJe=Qr.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()}}}),dJe=Qr.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()}}});Qr.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(oJe.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(Goe.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(lJe.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(cJe.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(dJe.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(Voe.configure(this.options.textStyle)),t}});var uJe=Goe,mJe=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,hJe=Ro.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",Xa(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,i,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(i=(r=t.attrs)==null?void 0:r.alt)!=null?i:"",d=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return d?``:``},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:i,getPos:s,HTMLAttributes:o,editor:l})=>{const c=document.createElement("img");Object.entries(o).forEach(([m,p])=>{if(p!=null)switch(m){case"width":case"height":break;default:c.setAttribute(m,p);break}}),c.src=o.src;const d=new uYe({element:c,editor:l,node:i,getPos:s,onResize:(m,p)=>{c.style.width=`${m}px`,c.style.height=`${p}px`},onCommit:(m,p)=>{const f=s();f!==void 0&&this.editor.chain().setNodeSelection(f).updateAttributes(this.name,{width:m,height:p}).run()},onUpdate:(m,p,f)=>m.type===i.type,options:{directions:t,min:{width:e,height:n},preserveAspectRatio:r===!0}}),u=d.dom;return u.style.visibility="hidden",u.style.pointerEvents="none",c.onload=()=>{u.style.visibility="",u.style.pointerEvents=""},d}},addCommands(){return{setImage:t=>({commands:e})=>e.insertContent({type:this.name,attrs:t})}},addInputRules(){return[doe({find:mJe,type:this.type,getAttributes:t=>{const[,,e,n,r]=t;return{src:n,alt:e,title:r}}})]}}),pJe=hJe;function HL({content:t,onChange:e,placeholder:n}){const{t:r}=Rt(),i=gQe({extensions:[nJe.configure({heading:!1,codeBlock:!1,code:!1}),MZe,mZe.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),aJe.configure({types:["paragraph"]}),Voe,uJe,pJe.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(!i)return null;const s=({onClick:l,isActive:c=!1,children:d,title:u})=>a.jsx("button",{type:"button",onClick:l,title:u,className:`p-1.5 rounded hover:bg-bambu-dark-tertiary transition-colors ${c?"bg-bambu-dark-tertiary text-bambu-green":"text-bambu-gray"}`,children:d}),o=()=>{const l=window.prompt("Enter URL:");l&&i.chain().focus().setLink({href:l}).run()};return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[a.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[a.jsx(s,{onClick:()=>i.chain().focus().toggleBold().run(),isActive:i.isActive("bold"),title:r("richTextEditor.bold"),children:a.jsx(kpe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleItalic().run(),isActive:i.isActive("italic"),title:r("richTextEditor.italic"),children:a.jsx(Bge,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleUnderline().run(),isActive:i.isActive("underline"),title:r("richTextEditor.underline"),children:a.jsx(Bxe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().toggleBulletList().run(),isActive:i.isActive("bulletList"),title:r("richTextEditor.bulletList"),children:a.jsx(Ow,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().toggleOrderedList().run(),isActive:i.isActive("orderedList"),title:r("richTextEditor.numberedList"),children:a.jsx(lN,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("left").run(),isActive:i.isActive({textAlign:"left"}),title:r("richTextEditor.alignLeft"),children:a.jsx(Dxe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("center").run(),isActive:i.isActive({textAlign:"center"}),title:r("richTextEditor.alignCenter"),children:a.jsx(Axe,{className:"w-4 h-4"})}),a.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("right").run(),isActive:i.isActive({textAlign:"right"}),title:r("richTextEditor.alignRight"),children:a.jsx(Mxe,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),a.jsx(s,{onClick:o,isActive:i.isActive("link"),title:r("richTextEditor.addLink"),children:a.jsx(ly,{className:"w-4 h-4"})}),i.isActive("link")&&a.jsx(s,{onClick:()=>i.chain().focus().unsetLink().run(),title:r("richTextEditor.removeLink"),children:a.jsx(ap,{className:"w-4 h-4"})})]}),a.jsx(hoe,{editor:i})]})}function Woe({archiveId:t,archiveName:e,onClose:n}){const r=sn(),[i,s]=w.useState(!1),[o,l]=w.useState(null),[c,d]=w.useState({}),{data:u,isLoading:m,error:p}=Qe({queryKey:["archive-project-page",t],queryFn:()=>me.getArchiveProjectPage(t)}),f=it({mutationFn:N=>me.updateArchiveProjectPage(t,N),onSuccess:()=>{r.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),d({})}});w.useEffect(()=>{const N=A=>{A.key==="Escape"&&(o!==null?l(null):i?b():n())};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[o,i,n]);const x=[...u?.model_pictures||[],...u?.profile_pictures||[]],v=()=>{d({title:u?.title||"",description:u?.description||"",designer:u?.designer||"",license:u?.license||"",profile_title:u?.profile_title||"",profile_description:u?.profile_description||""}),s(!0)},g=()=>{f.mutate(c)},b=()=>{s(!1),d({})},_=N=>rie.sanitize(N,{ALLOWED_TAGS:["p","br","b","strong","i","em","u","a","ul","ol","li","figure","img"],ALLOWED_ATTR:["href","src","target","rel","style"],ADD_ATTR:["target"]}),C=u&&(u.title||u.description||u.designer||u.profile_title||x.length>0),P=N=>{N.target===N.currentTarget&&n()};return a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:P,children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&a.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[!i&&C&&a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:v,children:[a.jsx(Kf,{className:"w-4 h-4 mr-1"}),"Edit"]}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:b,children:"Cancel"}),a.jsxs(Fe,{variant:"primary",size:"sm",onClick:g,disabled:f.isPending,children:[a.jsx(gs,{className:"w-4 h-4 mr-1"}),"Save"]})]}),a.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[m&&a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),p&&a.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),u&&!C&&a.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[a.jsx(Ms,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"No project page data found in this 3MF file."}),a.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),u&&C&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-4",children:[i?a.jsx("input",{type:"text",value:c.title||"",onChange:N=>d({...c,title:N.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"}):u.title&&a.jsx("h3",{className:"text-xl font-semibold text-white",children:u.title}),a.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sm,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.designer||"",onChange:N=>d({...c,designer:N.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.designer&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(sm,{className:"w-4 h-4"}),a.jsx("span",{children:u.designer}),u.designer_user_id&&a.jsx("a",{href:`https://makerworld.com/en/@${u.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:a.jsx(na,{className:"w-3 h-3"})})]}),u.creation_date&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(Yr,{className:"w-4 h-4"}),a.jsx("span",{children:u.creation_date})]}),i?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ms,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c.license||"",onChange:N=>d({...c,license:N.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.license&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(Ms,{className:"w-4 h-4"}),a.jsx("span",{children:u.license})]}),u.origin&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:u.origin})]})]}),(u.description||i)&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),i?a.jsx(HL,{content:c.description||"",onChange:N=>d({...c,description:N}),placeholder:"Enter description..."}):a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(u.description||"")}})]}),(u.profile_title||u.profile_description||i)&&a.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),i?a.jsxs("div",{className:"space-y-2",children:[a.jsx("input",{type:"text",value:c.profile_title||"",onChange:N=>d({...c,profile_title:N.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),a.jsx(HL,{content:c.profile_description||"",onChange:N=>d({...c,profile_description:N}),placeholder:"Profile description..."})]}):a.jsxs(a.Fragment,{children:[u.profile_title&&a.jsx("p",{className:"text-white font-medium",children:u.profile_title}),u.profile_description&&a.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(u.profile_description)}}),u.profile_user_name&&a.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",u.profile_user_name]})]})]}),x.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[a.jsx(rm,{className:"w-4 h-4"}),"Images (",x.length,")"]}),a.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:x.map((N,A)=>a.jsx("button",{onClick:()=>l(A),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:a.jsx("img",{src:N.url,alt:N.name,className:"w-full h-full object-cover"})},N.path))})]}),u.design_model_id&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("a",{href:`https://makerworld.com/en/models/${u.design_model_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-bambu-green hover:underline",children:[a.jsx(na,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&x[o]&&a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[a.jsx("button",{onClick:N=>{N.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:a.jsx(dl,{className:"w-6 h-6 text-white"})}),a.jsx("img",{src:x[o].url,alt:x[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:N=>N.stopPropagation()}),a.jsx("button",{onClick:N=>{N.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:a.jsx(Ka,{className:"w-6 h-6 text-white"})}),a.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:a.jsx(Bt,{className:"w-6 h-6 text-white"})}),a.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",x.length]})]})]})}const fJe=[.25,.5,.75,1,1.5,2,3,4];function gJe({archiveId:t,timelapseSrc:e,onClose:n,onSave:r}){const{showToast:i}=bn(),s=w.useRef(null),o=w.useRef(null),[l,c]=w.useState(!1),[d,u]=w.useState(0),[m,p]=w.useState(0),[f,x]=w.useState(0),[v,g]=w.useState(0),[b,_]=w.useState(1),[C,P]=w.useState(null),[N,A]=w.useState(null),[T,F]=w.useState(.8),[k,D]=w.useState(!1),{data:H,isLoading:z}=Qe({queryKey:["timelapse-info",t],queryFn:()=>me.getTimelapseInfo(t)}),{data:X}=Qe({queryKey:["timelapse-thumbnails",t],queryFn:()=>me.getTimelapseThumbnails(t,15)}),L=it({mutationFn:()=>me.processTimelapse(t,{trimStart:f,trimEnd:v,speed:b,saveMode:"replace"},C||void 0),onSuccess:W=>{i(W.message,"success"),r?.(),n()},onError:W=>{i(W.message||"Processing failed","error")}});w.useEffect(()=>{H?.duration&&v===0&&g(H.duration)},[H?.duration,v]),w.useEffect(()=>{const W=re=>{re.key==="Escape"&&n()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[n]),w.useEffect(()=>{const W=s.current;if(!W)return;const re=()=>{const $=W.currentTime;u($),$>=v&&(W.currentTime=f)},ce=()=>{p(W.duration),v===0&&g(W.duration)},xe=()=>c(!0),Ne=()=>c(!1);return W.addEventListener("timeupdate",re),W.addEventListener("durationchange",ce),W.addEventListener("play",xe),W.addEventListener("pause",Ne),()=>{W.removeEventListener("timeupdate",re),W.removeEventListener("durationchange",ce),W.removeEventListener("play",xe),W.removeEventListener("pause",Ne)}},[f,v]),w.useEffect(()=>{const W=o.current,re=s.current;!W||!re||!N||(W.currentTime=re.currentTime,W.playbackRate=re.playbackRate,l&&!k?W.play().catch(()=>{}):W.pause())},[l,N,k]),w.useEffect(()=>{o.current&&(o.current.volume=k?0:T)},[T,k]),w.useEffect(()=>{s.current&&(s.current.playbackRate=b),o.current&&(o.current.playbackRate=b)},[b]);const ne=w.useCallback(()=>{const W=s.current;W&&(l?W.pause():(W.currentTime<f&&(W.currentTime=f),W.play()))},[l,f]),ie=W=>{const re=s.current;re&&(re.currentTime=Math.max(f,Math.min(v,W)))},ee=W=>{const re=W.target.files?.[0];re&&(N&&URL.revokeObjectURL(N),P(re),A(URL.createObjectURL(re)))},ue=()=>{N&&URL.revokeObjectURL(N),P(null),A(null)};w.useEffect(()=>()=>{N&&URL.revokeObjectURL(N)},[N]);const le=v-f,oe=le/b;return z?a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.jsxs("div",{className:"flex items-center gap-3 text-white",children:[a.jsx(dt,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(qh,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fe,{variant:"primary",size:"sm",onClick:()=>L.mutate(),disabled:L.isPending,children:L.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(gs,{className:"w-4 h-4"}),"Save"]})}),a.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[a.jsxs("div",{className:"relative",children:[a.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:ne,muted:!!N}),!l&&a.jsx("button",{onClick:ne,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:a.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:a.jsx($i,{className:"w-8 h-8 text-white"})})}),N&&a.jsx("audio",{ref:o,src:N,loop:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Kbe,{className:"w-4 h-4"}),a.jsx("span",{children:"Trim"}),a.jsxs("span",{className:"ml-auto",children:[ph(f)," - ",ph(v)," (",ph(le),")"]})]}),a.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsx("div",{className:"absolute inset-0 flex",children:X?.thumbnails.map((W,re)=>a.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${W})`}},re))}),a.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${f/m*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(m-v)/m*100}%`}}),a.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${f/m*100}%`,right:`${(m-v)/m*100}%`}}),a.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${d/m*100}%`}}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:f,onChange:W=>{const re=parseFloat(W.target.value);re<v-1&&(x(re),s.current&&s.current.currentTime<re&&(s.current.currentTime=re))},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 50% 0 0)"}}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:v,onChange:W=>{const re=parseFloat(W.target.value);re>f+1&&g(re)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),a.jsx("input",{type:"range",min:0,max:m,step:.1,value:d,onChange:W=>ie(parseFloat(W.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
- [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
- [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
- [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("div",{className:"flex items-center justify-center gap-2",children:a.jsx("button",{onClick:ne,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(zw,{className:"w-5 h-5 text-white"}):a.jsx($i,{className:"w-5 h-5 text-white"})})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Fw,{className:"w-4 h-4"}),a.jsx("span",{children:"Speed"}),a.jsxs("span",{className:"ml-auto",children:[b,"x (output: ",ph(oe),")"]})]}),a.jsx("div",{className:"flex gap-1",children:fJe.map(W=>a.jsxs("button",{onClick:()=>_(W),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${b===W?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[W,"x"]},W))})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(X3,{className:"w-4 h-4"}),a.jsx("span",{children:"Music Overlay"})]}),C?a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(X3,{className:"w-5 h-5 text-bambu-green"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:C.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[(C.size/1024/1024).toFixed(1)," MB"]})]}),a.jsx("button",{onClick:()=>D(!k),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:k?a.jsx(Yxe,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Kxe,{className:"w-4 h-4 text-bambu-green"})}),a.jsx("input",{type:"range",min:0,max:1,step:.1,value:T,onChange:W=>F(parseFloat(W.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
- [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
- [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),a.jsx("button",{onClick:ue,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:a.jsx(rn,{className:"w-4 h-4 text-red-400"})})]}):a.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:[a.jsx(Ma,{className:"w-8 h-8 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),a.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),a.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:ee,className:"hidden"})]})]}),a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Original:"})," ",ph(m)," @ ",H?.width,"x",H?.height]}),a.jsxs("p",{className:"text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:"Output:"})," ",ph(oe)," @ ",b,"x speed",C&&" + music overlay"]})]})]}),L.isPending&&a.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[a.jsx(dt,{className:"w-12 h-12 text-bambu-green animate-spin"}),a.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),a.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const bJe=[.25,.5,.75,1,1.5,2,3,4];function Koe({src:t,title:e,downloadFilename:n,archiveId:r,onClose:i,onEdit:s}){const o=w.useRef(null),[l,c]=w.useState(!0),[d,u]=w.useState(1),[m,p]=w.useState(0),[f,x]=w.useState(0),[v,g]=w.useState(!1);w.useEffect(()=>{const A=o.current;A&&(A.playbackRate=d)},[d]),w.useEffect(()=>{const A=T=>{T.key==="Escape"&&i()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[i]),w.useEffect(()=>{const A=o.current;if(!A)return;const T=()=>p(A.currentTime),F=()=>x(A.duration),k=()=>c(!0),D=()=>c(!1);return A.addEventListener("timeupdate",T),A.addEventListener("durationchange",F),A.addEventListener("play",k),A.addEventListener("pause",D),()=>{A.removeEventListener("timeupdate",T),A.removeEventListener("durationchange",F),A.removeEventListener("play",k),A.removeEventListener("pause",D)}},[]);const b=()=>{const A=o.current;A&&(l?A.pause():A.play())},_=A=>{const T=o.current;T&&(T.currentTime=parseFloat(A.target.value))},C=()=>{const A=o.current;A&&(A.currentTime=Math.max(0,A.currentTime-5))},P=()=>{const A=o.current;A&&(A.currentTime=Math.min(f,A.currentTime+5))},N=()=>{const A=document.createElement("a");A.href=t,A.download=n,A.click()};return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[a.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(qh,{className:"w-5 h-5 text-bambu-green"}),e]}),a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>g(!0),children:[a.jsx(ai,{className:"w-4 h-4"}),"Edit"]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:N,children:[a.jsx(ca,{className:"w-4 h-4"}),"Download"]}),a.jsx("button",{onClick:i,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),a.jsxs("div",{className:"p-4",children:[a.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:b}),a.jsxs("div",{className:"mt-4 space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:ph(m)}),a.jsx("input",{type:"range",min:0,max:f||100,value:m,onChange:_,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
- [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
- [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
- [&::-webkit-slider-thumb]:cursor-pointer`}),a.jsx("span",{className:"text-xs text-bambu-gray w-12",children:ph(f)})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:C,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:a.jsx(lxe,{className:"w-5 h-5 text-bambu-gray"})}),a.jsx("button",{onClick:b,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?a.jsx(zw,{className:"w-5 h-5 text-white"}):a.jsx($i,{className:"w-5 h-5 text-white"})}),a.jsx("button",{onClick:P,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:a.jsx(EP,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),a.jsx("div",{className:"flex gap-1",children:bJe.map(A=>a.jsxs("button",{onClick:()=>u(A),className:`px-2 py-1 text-xs rounded transition-colors ${d===A?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[A,"x"]},A))})]})]})]})]})]}),v&&r&&a.jsx(gJe,{archiveId:r,timelapseSrc:t,onClose:()=>g(!1),onSave:s})]})}function xJe({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:i}=Qe({queryKey:["archive-comparison",t],queryFn:()=>me.compareArchives(t)});return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i?a.jsxs("div",{className:"text-center py-12 text-red-400",children:[a.jsx(Rn,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),a.jsx("p",{children:"Failed to load comparison"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:i instanceof Error?i.message:"Unknown error"})]}):n?a.jsx(yJe,{comparison:n}):null}),a.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:a.jsx(Fe,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function yJe({comparison:t}){return a.jsxs("div",{className:"space-y-6",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.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=>a.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[a.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),a.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))]})}),a.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>a.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[a.jsx("td",{className:"py-2 pr-4 text-sm",children:a.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&a.jsx(Rn,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),a.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>a.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??a.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&a.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&a.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[a.jsx(Rn,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),a.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>a.jsxs("li",{children:[a.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&a.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[a.jsx(Rr,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[a.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),a.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?a.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>a.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[a.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",a.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):a.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:a.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function vJe(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4);if(i<1)return"Just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function wJe({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:i,isDiscarding:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(t.tags||""),[u,m]=w.useState(t.notes||""),[p,f]=w.useState(t.project_id),[x,v]=w.useState(!1);return a.jsx(At,{children:a.jsxs(Mt,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Hh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx("span",{children:Co(t.file_size)}),a.jsx("span",{children:"·"}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),vJe(t.uploaded_at)]}),t.source_ip&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"·"}),a.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?a.jsx(ac,{className:"w-5 h-5"}):a.jsx(Un,{className:"w-5 h-5"})}),a.jsx(Fe,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:u,project_id:p||void 0}),disabled:i,children:i?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(Qs,{className:"w-4 h-4"}),"Archive"]})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>v(!0),disabled:s,children:s?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4 text-red-400"})})]})]}),x&&a.jsx(_n,{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&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),a.jsx("input",{type:"text",value:c,onChange:g=>d(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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),a.jsx("textarea",{value:u,onChange:g=>m(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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),a.jsxs("select",{value:p||"",onChange:g=>f(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:[a.jsx("option",{value:"",children:"No project"}),e.map(g=>a.jsx("option",{value:g.id,children:g.name},g.id))]})]})]})]})})}function SJe(){const t=sn(),{showToast:e}=bn(),[n,r]=w.useState(!1),[i,s]=w.useState(!1),[o,l]=w.useState(new Set),[c,d]=w.useState(new Set),{data:u,isLoading:m}=Qe({queryKey:["pending-uploads"],queryFn:Xb.list,refetchInterval:1e4}),{data:p}=Qe({queryKey:["projects"],queryFn:()=>me.getProjects()}),f=it({mutationFn:({id:b,data:_})=>Xb.archive(b,_),onMutate:({id:b})=>{l(_=>new Set(_).add(b))},onSettled:(b,_,{id:C})=>{l(P=>{const N=new Set(P);return N.delete(C),N})},onSuccess:b=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${b.print_name}`)},onError:b=>{e(b.message||"Failed to archive","error")}}),x=it({mutationFn:b=>Xb.discard(b),onMutate:b=>{d(_=>new Set(_).add(b))},onSettled:(b,_,C)=>{d(P=>{const N=new Set(P);return N.delete(C),N})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:b=>{e(b.message||"Failed to discard","error")}}),v=it({mutationFn:Xb.archiveAll,onSuccess:b=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${b.archived} files${b.failed>0?`, ${b.failed} failed`:""}`)},onError:b=>{e(b.message||"Failed to archive all","error")}}),g=it({mutationFn:Xb.discardAll,onSuccess:b=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${b.discarded} files`)},onError:b=>{e(b.message||"Failed to discard all","error")}});return m?a.jsx(At,{children:a.jsx(Mt,{className:"py-8 flex justify-center",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!u||u.length===0?null:a.jsxs("div",{className:"mb-6",children:[a.jsxs(At,{className:"border-l-4 border-l-yellow-500",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ma,{className:"w-5 h-5 text-yellow-500"}),a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",u.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fe,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:v.isPending,children:v.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(Qs,{className:"w-4 h-4"}),"Archive All"]})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:g.isPending,children:g.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsxs(a.Fragment,{children:[a.jsx(rn,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),a.jsxs(Mt,{children:[a.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."}),a.jsx("div",{className:"space-y-3",children:u.map(b=>a.jsx(wJe,{upload:b,projects:p||[],onArchive:(_,C)=>f.mutate({id:_,data:C}),onDiscard:_=>x.mutate(_),isArchiving:o.has(b.id),isDiscarding:c.has(b.id)},b.id))})]})]}),n&&a.jsx(_n,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${u.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{v.mutate(),r(!1)},onCancel:()=>r(!1)}),i&&a.jsx(_n,{title:"Discard All Uploads",message:`Are you sure you want to discard all ${u.length} pending uploads? This cannot be undone.`,confirmText:"Discard All",variant:"danger",onConfirm:()=>{g.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function _Je({onClose:t}){const e=sn(),{showToast:n}=bn(),[r,i]=w.useState(""),[s,o]=w.useState(null),[l,c]=w.useState(""),[d,u]=w.useState(null),[m,p]=w.useState("count");w.useEffect(()=>{const k=D=>{D.key==="Escape"&&(s?o(null):d?u(null):t())};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,s,d]);const{data:f,isLoading:x}=Qe({queryKey:["tags"],queryFn:me.getTags}),v=it({mutationFn:({oldName:k,newName:D})=>me.renameTag(k,D),onSuccess:(k,{oldName:D,newName:H})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${D}" to "${H}" in ${k.affected} archive${k.affected!==1?"s":""}`),o(null)},onError:k=>{n(k.message||"Failed to rename tag","error")}}),g=it({mutationFn:k=>me.deleteTag(k),onSuccess:(k,D)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${D}" from ${k.affected} archive${k.affected!==1?"s":""}`),u(null)},onError:k=>{n(k.message||"Failed to delete tag","error")}}),b=k=>{o(k.name),c(k.name),u(null)},_=()=>{o(null),c("")},C=()=>{if(!s||!l.trim())return;const k=l.trim();if(k===s){_();return}v.mutate({oldName:s,newName:k})},P=k=>{k.key==="Enter"?(k.preventDefault(),C()):k.key==="Escape"&&(k.preventDefault(),_())},N=k=>{u(k),o(null)},A=()=>{d&&g.mutate(d)},T=f?.filter(k=>k.name.toLowerCase().includes(r.toLowerCase())).sort((k,D)=>m==="count"&&D.count-k.count||k.name.localeCompare(D.name)),F=f?.reduce((k,D)=>k+D.count,0)||0;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(im,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.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:k=>i(k.target.value)})]}),a.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:m,onChange:k=>p(k.target.value),children:[a.jsx("option",{value:"count",children:"Sort by Count"}),a.jsx("option",{value:"name",children:"Sort by Name"})]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[f.length," tag",f.length!==1?"s":""," across ",F," usage",F!==1?"s":""]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:x?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):T?.length?a.jsx("div",{className:"space-y-2",children:T.map(k=>a.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===k.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.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:D=>c(D.target.value),onKeyDown:P,autoFocus:!0}),a.jsx(Fe,{size:"sm",variant:"primary",onClick:C,disabled:!l.trim()||v.isPending,className:"p-1.5",children:v.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Rr,{className:"w-4 h-4"})}),a.jsx(Fe,{size:"sm",variant:"ghost",onClick:_,className:"p-1.5",children:a.jsx(Bt,{className:"w-4 h-4"})})]}):d===k.name?a.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',k.name,'" from ',k.count," archive",k.count!==1?"s":"","?"]}),a.jsx(Fe,{size:"sm",variant:"danger",onClick:A,disabled:g.isPending,className:"p-1.5",children:g.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"})}),a.jsx(Fe,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"p-1.5",children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.jsxs(a.Fragment,{children:[a.jsx(im,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-white flex-1 truncate",children:k.name}),a.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:k.count}),a.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:()=>b(k),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>N(k.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:a.jsx(rn,{className:"w-4 h-4"})})]})]})},k.name))}):a.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsx(Fe,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function Ph(t){const e=t.filename;if(e){const n=e.toLowerCase();if(n.endsWith(".gcode")||n.includes(".gcode."))return!0}return!!(t.total_layers||t.print_time_seconds)}function Xoe(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 Th(t,e,n,r){try{if(n==="source"){const{token:i}=await me.createSourceSlicerToken(t),s=me.getSourceSlicerDownloadUrl(t,i,e);Pf(`${window.location.origin}${s}`,r)}else{const{token:i}=await me.createArchiveSlicerToken(t),s=me.getArchiveSlicerDownloadUrl(t,i,e);Pf(`${window.location.origin}${s}`,r)}}catch{const i=n==="source"?me.getSource3mfForSlicer(t,e):me.getArchiveForSlicer(t,e);Pf(`${window.location.origin}${i}`,r)}}function kJe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",currency:d,t:u,onNavigateToArchive:m}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const p=sn(),{showToast:f}=bn(),{hasPermission:x,canModify:v}=wr(),g=Kae(),[b,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(!1),[k,D]=w.useState(!1),[H,z]=w.useState(!1),[X,L]=w.useState([]),[ne,ie]=w.useState(!1),[ee,ue]=w.useState(!1),[le,oe]=w.useState(!1),[W,re]=w.useState(!1),[ce,xe]=w.useState(!1),[Ne,$]=w.useState(!1),[Y,E]=w.useState(!1),[j,O]=w.useState(null),[K,B]=w.useState(null),[he,I]=w.useState(!1),V=w.useRef(null),Q=w.useRef(null),G=w.useRef(null),{data:J}=Qe({queryKey:["archive-plates",t.id],queryFn:()=>me.getArchivePlates(t.id),enabled:he,staleTime:300*1e3}),se=t.duplicate_sequence??0,fe=t.original_archive_id??null,pe=J?.plates??[],de=J?.is_multi_plate??!1,U=K??0,R=it({mutationFn:()=>me.deleteArchiveTimelapse(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseRemoved"))},onError:te=>{f(te.message||u("archives.toast.failedRemoveTimelapse"),"error")}}),ae=it({mutationFn:te=>me.uploadArchiveTimelapse(t.id,te),onSuccess:te=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseUploaded",{filename:te.filename}))},onError:te=>{f(te.message||u("archives.toast.failedUploadTimelapse"),"error")}}),_e=it({mutationFn:te=>me.uploadSource3mf(t.id,te),onSuccess:te=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.source3mfAttached",{filename:te.filename}))},onError:te=>{f(te.message||u("archives.toast.failedUploadSource3mf"),"error")}}),Se=it({mutationFn:()=>me.deleteSource3mf(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.source3mfRemoved"))},onError:te=>{f(te.message||u("archives.toast.failedRemoveSource3mf"),"error")}}),ye=it({mutationFn:te=>me.uploadF3d(t.id,te),onSuccess:te=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.f3dAttached",{filename:te.filename}))},onError:te=>{f(te.message||u("archives.toast.failedUploadF3d"),"error")}}),Ae=it({mutationFn:()=>me.deleteF3d(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.f3dRemoved"))},onError:te=>{f(te.message||u("archives.toast.failedRemoveF3d"),"error")}}),ve=it({mutationFn:()=>me.scanArchiveTimelapse(t.id),onSuccess:te=>{te.status==="attached"?(p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseAttached",{filename:te.filename}))):te.status==="exists"?f(u("archives.toast.timelapseAlreadyAttached")):te.status==="not_found"&&te.available_files&&te.available_files.length>0?(L(te.available_files),z(!0)):f(te.message||u("archives.toast.noMatchingTimelapse"),"warning")},onError:te=>{f(te.message||u("archives.toast.failedScanTimelapse"),"error")}}),je=it({mutationFn:te=>me.selectArchiveTimelapse(t.id,te),onSuccess:te=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.timelapseAttached",{filename:te.filename})),z(!1),L([])},onError:te=>{f(te.message||u("archives.toast.failedAttachTimelapse"),"error")}}),Re=it({mutationFn:()=>me.deleteArchive(t.id),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.archiveDeleted"))},onError:()=>{f(u("archives.toast.failedDeleteArchive"),"error")}}),Ee=it({mutationFn:()=>me.toggleFavorite(t.id),onSuccess:te=>{p.invalidateQueries({queryKey:["archives"]}),f(te.is_favorite?u("archives.toast.addedToFavorites"):u("archives.toast.removedFromFavorites"))}}),{data:Te}=Qe({queryKey:["archive-folders",t.id],queryFn:()=>me.getLibraryFoldersByArchive(t.id)}),Me=it({mutationFn:te=>me.updateArchive(t.id,{project_id:te}),onSuccess:()=>{p.invalidateQueries({queryKey:["archives"]}),p.invalidateQueries({queryKey:["projects"]}),f(u("archives.toast.projectUpdated"))},onError:()=>{f(u("archives.toast.failedUpdateProject"),"error")}}),Be=te=>{te.preventDefault(),O({x:te.clientX,y:te.clientY})},tt=[...Ph(t)?[{label:u("archives.menu.print"),icon:a.jsx(Ar,{className:"w-4 h-4"}),onClick:()=>P(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:u("archives.permission.noReprint"):u("archives.card.noFileForReprint")},{label:u("archives.menu.schedule"),icon:a.jsx(Yr,{className:"w-4 h-4"}),onClick:()=>re(!0),disabled:!t.file_path||!x("queue:create"),title:t.file_path?x("queue:create")?void 0:u("archives.permission.noAddToQueue"):u("archives.card.noFileForReprint")},{label:u("archives.menu.openInBambuStudio"),icon:a.jsx(na,{className:"w-4 h-4"}),onClick:()=>{const te=t.print_name||t.filename||"model";Th(t.id,te,"file",c)},disabled:!t.file_path,title:t.file_path?void 0:u("archives.card.noFileForReprint")}]:[{label:u("archives.menu.slice"),icon:a.jsx(na,{className:"w-4 h-4"}),onClick:()=>{const te=t.print_name||t.filename||"model";Th(t.id,te,"file",c)}}],{label:t.external_url?u("archives.menu.externalLink"):u("archives.menu.viewOnMakerWorld"),icon:a.jsx(rl,{className:"w-4 h-4"}),onClick:()=>{const te=t.external_url||t.makerworld_url;te&&window.open(te,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.preview3d"),icon:a.jsx(mi,{className:"w-4 h-4"}),onClick:()=>_(!0)},{label:u("archives.menu.viewTimelapse"),icon:a.jsx(qh,{className:"w-4 h-4"}),onClick:()=>D(!0),disabled:!t.timelapse_path},{label:u("archives.menu.scanForTimelapse"),icon:a.jsx(uN,{className:"w-4 h-4"}),onClick:()=>ve.mutate(),disabled:!t.printer_id||!!t.timelapse_path||ve.isPending||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.uploadTimelapse"),icon:a.jsx(Ma,{className:"w-4 h-4"}),onClick:()=>G.current?.click(),disabled:!!t.timelapse_path||!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:u("archives.menu.removeTimelapse"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>E(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?u("archives.menu.downloadSource3mf"):u("archives.menu.uploadSource3mf"),icon:a.jsx(iN,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?me.downloadSource3mf(t.id).catch(te=>{console.error("Source 3MF download failed:",te)}):V.current?.click()},disabled:!t.source_3mf_path&&!v("archives","update",t.created_by_id),title:!t.source_3mf_path&&!v("archives","update",t.created_by_id)?u("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:u("archives.menu.replaceSource3mf"),icon:a.jsx(Ma,{className:"w-4 h-4"}),onClick:()=>V.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.removeSource3mf"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>xe(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?u("archives.menu.replaceF3d"):u("archives.menu.uploadF3d"),icon:a.jsx(mi,{className:"w-4 h-4"}),onClick:()=>Q.current?.click(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:u("archives.menu.downloadF3d"),icon:a.jsx(ca,{className:"w-4 h-4"}),onClick:()=>{me.downloadF3d(t.id).catch(te=>{console.error("F3D download failed:",te)})}},{label:u("archives.menu.removeF3d"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>$(!0),danger:!0,disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.download"),icon:a.jsx(ca,{className:"w-4 h-4"}),onClick:()=>{me.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(te=>{console.error("Archive download failed:",te)})},disabled:!x("archives:read"),title:x("archives:read")?void 0:u("archives.permission.noDownload")},{label:u("archives.menu.copyDownloadLink"),icon:a.jsx(Fs,{className:"w-4 h-4"}),onClick:()=>{const te=`${window.location.origin}${me.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(te).then(()=>{f(u("archives.toast.linkCopied"))}).catch(()=>{f(u("archives.toast.failedCopyLink"),"error")})},disabled:!x("archives:read"),title:x("archives:read")?void 0:u("archives.permission.noCopyLink")},{label:u("archives.menu.qrCode"),icon:a.jsx(MQ,{className:"w-4 h-4"}),onClick:()=>ie(!0)},{label:t.photos?.length?u("archives.menu.viewPhotosCount",{count:t.photos.length}):u("archives.menu.viewPhotos"),icon:a.jsx(Tx,{className:"w-4 h-4"}),onClick:()=>ue(!0),disabled:!t.photos?.length},{label:u("archives.menu.projectPage"),icon:a.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>oe(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?u("archives.menu.removeFromFavorites"):u("archives.menu.addToFavorites"),icon:a.jsx(Xf,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Ee.mutate(),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},{label:u("archives.menu.edit"),icon:a.jsx(ai,{className:"w-4 h-4"}),onClick:()=>F(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:u("archives.menu.goToProject",{name:t.project_name}),icon:a.jsx(Es,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:u("archives.menu.addToProject"),icon:a.jsx(Es,{className:"w-4 h-4"}),onClick:()=>{},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?void 0:u("archives.permission.noUpdateArchives"),submenu:(()=>{const te=[];if(t.project_id&&te.push({label:u("archives.menu.removeFromProject"),icon:a.jsx(Bt,{className:"w-4 h-4"}),onClick:()=>Me.mutate(null),disabled:!v("archives","update",t.created_by_id)}),!s)te.push({label:u("archives.menu.loading"),icon:a.jsx(dt,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const Ie=s.filter(be=>be.status==="active");Ie.length===0?te.push({label:u("archives.menu.noProjectsAvailable"),icon:a.jsx(Es,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):Ie.forEach(be=>{te.push({label:be.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:be.color||"#888"}}),onClick:()=>Me.mutate(be.id),disabled:t.project_id===be.id||!v("archives","update",t.created_by_id)})})}return te})()},{label:u(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(xs,{className:"w-4 h-4"}):a.jsx(to,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:u("archives.menu.delete"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>A(!0),danger:!0,disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?void 0:u("archives.permission.noDelete")}];return a.jsxs(At,{"data-archive-id":t.id,className:`relative flex flex-col group ${n?"ring-2 ring-bambu-green":""} ${i?"cursor-pointer":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,onContextMenu:Be,onClick:i?()=>r(t.id):void 0,children:[i&&a.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:te=>{te.stopPropagation(),r(t.id)},children:n?a.jsx(xs,{className:"w-5 h-5 text-bambu-green"}):a.jsx(to,{className:"w-5 h-5 text-white"})}),a.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),children:[t.thumbnail_path?a.jsx("img",{src:K!==null&&pe.length>0?me.getArchivePlateThumbnail(t.id,pe[U]?.index??0):me.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(rm,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),de&&pe.length>1&&a.jsxs(a.Fragment,{children:[a.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 ${g?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:te=>{te.stopPropagation(),B(Ie=>{const be=Ie??0;return be>0?be-1:pe.length-1})},title:u("archives.card.previousPlate"),children:a.jsx(dl,{className:"w-4 h-4 text-white"})}),a.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 ${g?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:te=>{te.stopPropagation(),B(Ie=>{const be=Ie??0;return be<pe.length-1?be+1:0})},title:u("archives.card.nextPlate"),children:a.jsx(Ka,{className:"w-4 h-4 text-white"})}),a.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 ${g?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:pe.map((te,Ie)=>a.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${Ie===U?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:be=>{be.stopPropagation(),B(Ie)},title:te.name||u("archives.card.plateNumber",{index:te.index})},te.index))})]}),a.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${g?"opacity-100":"opacity-0 group-hover:opacity-100"} ${i?"left-10":""}`,onClick:te=>{te.stopPropagation();const Ie=te.currentTarget.getBoundingClientRect();O({x:Ie.left,y:Ie.bottom+4})},title:u("archives.card.moreOptions"),children:a.jsx(Bh,{className:"w-5 h-5 text-white"})}),a.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${v("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:te=>{te.stopPropagation(),v("archives","update",t.created_by_id)&&Ee.mutate()},disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?t.is_favorite?u("archives.card.removeFromFavorites"):u("archives.card.addToFavorites"):u("archives.permission.noUpdateArchives"),children:a.jsx(Xf,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${v("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&a.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"?u("archives.card.cancelled"):u("archives.card.failed")}),t.duplicate_count>0&&se>0&&fe&&a.jsxs("button",{onClick:te=>{te.stopPropagation(),m?.(fe)},className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 hover:bg-purple-600/90 text-white flex items-center gap-1 transition-colors cursor-pointer",title:u("archives.viewOriginalPrint",{id:fe}),children:[a.jsx(Fs,{className:"w-3 h-3"}),"#",se]}),t.duplicate_count>0&&se===0&&a.jsxs("span",{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:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[a.jsx(TQ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.source_3mf_path&&a.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:te=>{te.stopPropagation();const Ie=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source";Th(t.id,Ie,"source",c)},title:u("archives.card.openSource3mf"),children:a.jsx(iN,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&a.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:te=>{te.stopPropagation(),me.downloadF3d(t.id).catch(Ie=>{console.error("F3D download failed:",Ie)})},title:u("archives.card.downloadF3d"),children:a.jsx(mi,{className:"w-4 h-4 text-cyan-400"})}),a.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:te=>{te.stopPropagation(),_(!0)},title:u("archives.card.preview3d"),children:a.jsx(aa,{className:"w-4 h-4 text-white"})}),t.timelapse_path&&a.jsx("button",{className:"absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:te=>{te.stopPropagation(),D(!0)},title:u("archives.card.viewTimelapse"),children:a.jsx(qh,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&a.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:te=>{te.stopPropagation(),ue(!0)},title:t.photos.length===1?u("archives.card.viewPhoto"):u("archives.card.viewPhotos",{count:t.photos.length}),children:[a.jsx(Tx,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&a.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})]}),Te&&Te.length>0&&a.jsx(_o,{to:`/files?folder=${Te[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:te=>te.stopPropagation(),title:u("archives.card.openFolder",{name:Te[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:a.jsx(Uc,{className:"w-4 h-4 text-yellow-400"})})]}),a.jsxs(Mt,{className:"p-4 flex-1 flex flex-col",children:[a.jsxs("p",{className:"text-[10px] text-bambu-gray/70 mb-1",children:["#",t.id]}),a.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[a.jsx("h3",{className:"min-w-0 font-medium text-white truncate",children:t.print_name||t.filename}),a.jsx(Fe,{variant:"ghost",size:"sm",className:"p-1 sm:p-1.5 shrink-0",onClick:()=>F(!0),disabled:!v("archives","update",t.created_by_id),title:v("archives","update",t.created_by_id)?u("archives.card.edit"):u("archives.card.noPermissionEdit"),children:a.jsx(ai,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:e}),a.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${Ph(t)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:Ph(t)?u("archives.card.slicedFile"):u("archives.card.sourceFile"),children:Ph(t)?u("archives.card.gcode"):u("archives.card.source")}),t.content_hash&&a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono bg-bambu-dark-tertiary/50 text-bambu-gray-light opacity-0 transition-opacity duration-150 group-hover:opacity-100",title:`SHA256: ${t.content_hash}`,children:t.content_hash.slice(0,8).toUpperCase()}),t.project_name&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(te=>te.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(te=>te.id===t.project_id)?.color||"#6b7280"},title:u("archives.card.project",{name:t.project_name}),children:t.project_name})]}),a.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)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${ps(t.print_time_seconds||0)}
- Actual: ${ps(t.actual_time_seconds||0)}
- Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ps(t.actual_time_seconds)}`:`Estimated: ${ps(t.print_time_seconds||0)}`,children:[a.jsx(Qn,{className:"w-3 h-3"}),ps(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&a.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&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(ja,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.cost!=null||t.energy_cost!=null)&&a.jsxs("div",{className:"flex items-center gap-3 text-bambu-gray",children:[t.cost!=null&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(vfe,{className:"w-3 h-3"}),d,t.cost.toFixed(2)]}),t.energy_cost!=null&&a.jsxs("div",{className:"flex items-center gap-1.5",title:`${u("stats.energyUsed")}: ${t.energy_kwh?.toFixed(3)||"N/A"} kWh`,children:[a.jsx(ic,{className:"w-3 h-3"}),d,t.energy_cost.toFixed(2)]})]}),(t.layer_height||t.total_layers)&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(aa,{className:"w-3 h-3"}),t.total_layers&&a.jsx("span",{children:t.total_layers===1?u("archives.card.layer",{count:t.total_layers}):u("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&a.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count}),children:[a.jsx(mi,{className:"w-3 h-3"}),t.object_count===1?u("archives.card.object",{count:t.object_count}):u("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:u("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(Ar,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&a.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[a.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((te,Ie)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:te},title:te},Ie))})]})]}),(t.tags||t.notes)&&a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&a.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:a.jsx(LQ,{className:"w-3 h-3"})}),t.tags?.split(",").map((te,Ie)=>a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:te.trim()},Ie))]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("span",{children:Zf(t.created_at,l)}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1",title:u("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx(sm,{className:"w-3 h-3"}),t.created_by_username]}),a.jsx("span",{children:Co(t.file_size)})]})]}),a.jsxs("div",{className:"flex gap-1 mt-3",children:[Ph(t)?a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>P(!0),disabled:!t.file_path||!v("archives","reprint",t.created_by_id),title:t.file_path?v("archives","reprint",t.created_by_id)?void 0:u("archives.card.noPermissionReprint"):u("archives.card.noFileForReprint"),children:[a.jsx(Ar,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.reprint")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>re(!0),disabled:!t.file_path||!x("queue:create"),title:t.file_path?x("queue:create")?u("archives.card.schedulePrint"):u("archives.permission.noAddToQueue"):u("archives.card.noFileForReprint"),children:[a.jsx(Yr,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.schedule")})]}),a.jsx(Fe,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const te=t.print_name||t.filename||"model";Th(t.id,te,"file",c)},title:u("archives.card.openInBambuStudio"),children:a.jsx(na,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):a.jsxs(Fe,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>{const te=t.print_name||t.filename||"model";Th(t.id,te,"file",c)},title:u("archives.card.openInBambuStudioToSlice"),children:[a.jsx(na,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"hidden sm:inline truncate",children:u("archives.card.slice")})]}),a.jsx(Fe,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const te=t.external_url||t.makerworld_url;te&&window.open(te,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?u("archives.card.externalLink"):t.makerworld_url?u("archives.card.makerWorld",{designer:t.designer||u("archives.card.viewProject")}):u("archives.card.noExternalLink"),children:a.jsx(rl,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),a.jsx(Fe,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{me.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(te=>{console.error("Archive download failed:",te)})},title:u("archives.card.download"),children:a.jsx(ca,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>A(!0),disabled:!v("archives","delete",t.created_by_id),title:v("archives","delete",t.created_by_id)?u("archives.card.delete"):u("archives.card.noPermissionDelete"),children:a.jsx(rn,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),T&&a.jsx(Xae,{archive:t,onClose:()=>F(!1)}),b&&a.jsx(cz,{archiveId:t.id,title:t.print_name||t.filename,fileType:Xoe(t.filename),onClose:()=>_(!1)}),C&&a.jsx(ec,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>P(!1)}),N&&a.jsx(_n,{title:u("archives.modal.deleteArchive"),message:u("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Re.mutate(),A(!1)},onCancel:()=>A(!1)}),ce&&a.jsx(_n,{title:u("archives.modal.removeSource3mf"),message:u("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Se.mutate(),xe(!1)},onCancel:()=>xe(!1)}),Ne&&a.jsx(_n,{title:u("archives.modal.removeF3d"),message:u("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Ae.mutate(),$(!1)},onCancel:()=>$(!1)}),Y&&a.jsx(_n,{title:u("archives.modal.removeTimelapse"),message:u("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:u("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{R.mutate(),E(!1)},onCancel:()=>E(!1)}),j&&a.jsx(Yae,{x:j.x,y:j.y,items:tt,onClose:()=>O(null)}),k&&t.timelapse_path&&a.jsx(Koe,{src:me.getArchiveTimelapse(t.id),title:u("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>D(!1),onEdit:()=>{p.invalidateQueries({queryKey:["archives"]}),D(!1)}}),H&&X.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:u("archives.modal.selectTimelapse")}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:u("archives.modal.selectTimelapseDesc")})]}),a.jsx("button",{onClick:()=>{z(!1),L([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:X.map(te=>a.jsxs("button",{onClick:()=>je.mutate(te.name),disabled:je.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:[a.jsx(qh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:te.name}),a.jsxs("p",{className:"text-sm text-gray-400",children:[Co(te.size),te.mtime&&` • ${Zf(te.mtime,l)}`]})]})]},te.name))}),a.jsx("div",{className:"p-4 border-t border-gray-700",children:a.jsx(Fe,{variant:"secondary",onClick:()=>{z(!1),L([])},className:"w-full",children:"Cancel"})})]})}),ne&&a.jsx(Qae,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ie(!1)}),ee&&t.photos&&t.photos.length>0&&a.jsx(Zae,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>ue(!1),onDelete:async te=>{try{await me.deleteArchivePhoto(t.id,te),p.invalidateQueries({queryKey:["archives"]}),f(u("archives.toast.photoDeleted"))}catch{f(u("archives.toast.failedDeletePhoto"),"error")}}}),le&&a.jsx(Woe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>oe(!1)}),W&&a.jsx(ec,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>re(!1)}),a.jsx("input",{ref:V,type:"file",accept:".3mf",className:"hidden",onChange:te=>{const Ie=te.target.files?.[0];Ie&&_e.mutate(Ie),te.target.value=""}}),a.jsx("input",{ref:Q,type:"file",accept:".f3d",className:"hidden",onChange:te=>{const Ie=te.target.files?.[0];Ie&&ye.mutate(Ie),te.target.value=""}}),a.jsx("input",{ref:G,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:te=>{const Ie=te.target.files?.[0];Ie&&ae.mutate(Ie),te.target.value=""}})]})}function NJe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:i,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c,onNavigateToArchive:d}){const u=sn(),{showToast:m}=bn(),{hasPermission:p,canModify:f}=wr(),[x,v]=w.useState(!1),[g,b]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(!1),[A,T]=w.useState(!1),[F,k]=w.useState(!1),[D,H]=w.useState(!1),[z,X]=w.useState([]),[L,ne]=w.useState(!1),[ie,ee]=w.useState(!1),[ue,le]=w.useState(!1),[oe,W]=w.useState(!1),[re,ce]=w.useState(!1),[xe,Ne]=w.useState(!1),[$,Y]=w.useState(null),E=w.useRef(null),j=w.useRef(null),O=w.useRef(null),K=t.duplicate_sequence??0,B=t.original_archive_id??null,he=it({mutationFn:()=>me.deleteArchiveTimelapse(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveTimelapse"),"error")}}),I=it({mutationFn:ye=>me.uploadArchiveTimelapse(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseUploaded",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadTimelapse"),"error")}}),V=it({mutationFn:ye=>me.uploadSource3mf(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfAttached",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadSource3mf"),"error")}}),Q=it({mutationFn:()=>me.deleteSource3mf(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.source3mfRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),G=it({mutationFn:ye=>me.uploadF3d(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dAttached",{filename:ye.filename}))},onError:ye=>{m(ye.message||c("archives.toast.failedUploadF3d"),"error")}}),J=it({mutationFn:()=>me.deleteF3d(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.f3dRemoved"))},onError:ye=>{m(ye.message||c("archives.toast.failedRemoveF3d"),"error")}}),se=it({mutationFn:()=>me.scanArchiveTimelapse(t.id),onSuccess:ye=>{ye.status==="attached"?(u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:ye.filename}))):ye.status==="exists"?m(c("archives.toast.timelapseAlreadyAttached")):ye.status==="not_found"&&ye.available_files&&ye.available_files.length>0?(X(ye.available_files),H(!0)):m(ye.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:ye=>{m(ye.message||c("archives.toast.failedScanTimelapse"),"error")}}),fe=it({mutationFn:ye=>me.selectArchiveTimelapse(t.id,ye),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.timelapseAttached",{filename:ye.filename})),H(!1),X([])},onError:ye=>{m(ye.message||c("archives.toast.failedAttachTimelapse"),"error")}}),pe=it({mutationFn:()=>me.deleteArchive(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.archiveDeleted"))},onError:()=>{m(c("archives.toast.failedDeleteArchive"),"error")}}),de=it({mutationFn:()=>me.toggleFavorite(t.id),onSuccess:ye=>{u.invalidateQueries({queryKey:["archives"]}),m(ye.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:U}=Qe({queryKey:["archive-folders",t.id],queryFn:()=>me.getLibraryFoldersByArchive(t.id)}),R=it({mutationFn:ye=>me.updateArchive(t.id,{project_id:ye}),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),u.invalidateQueries({queryKey:["projects"]}),m(c("archives.toast.projectUpdated"))},onError:()=>{m(c("archives.toast.failedUpdateProject"),"error")}}),ae=ye=>{ye.preventDefault(),Y({x:ye.clientX,y:ye.clientY})},Se=[...Ph(t)?[{label:c("archives.menu.print"),icon:a.jsx(Ar,{className:"w-4 h-4"}),onClick:()=>C(!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:a.jsx(Yr,{className:"w-4 h-4"}),onClick:()=>N(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?void 0:c("archives.permission.noAddToQueue"):c("archives.card.noFileForReprint")},{label:c("archives.menu.openInBambuStudio"),icon:a.jsx(na,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";Th(t.id,ye,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:c("archives.card.noFileForReprint")}]:[{label:c("archives.menu.slice"),icon:a.jsx(na,{className:"w-4 h-4"}),onClick:()=>{const ye=t.print_name||t.filename||"model";Th(t.id,ye,"file",l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:a.jsx(rl,{className:"w-4 h-4"}),onClick:()=>{const ye=t.external_url||t.makerworld_url;ye&&window.open(ye,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:a.jsx(mi,{className:"w-4 h-4"}),onClick:()=>T(!0)},{label:c("archives.menu.viewTimelapse"),icon:a.jsx(qh,{className:"w-4 h-4"}),onClick:()=>k(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:a.jsx(uN,{className:"w-4 h-4"}),onClick:()=>se.mutate(),disabled:!t.printer_id||!!t.timelapse_path||se.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:a.jsx(Ma,{className:"w-4 h-4"}),onClick:()=>O.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:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>Ne(!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:a.jsx(iN,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?me.downloadSource3mf(t.id).catch(ye=>{console.error("Source 3MF download failed:",ye)}):E.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:a.jsx(Ma,{className:"w-4 h-4"}),onClick:()=>E.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:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>W(!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:a.jsx(mi,{className:"w-4 h-4"}),onClick:()=>j.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:a.jsx(ca,{className:"w-4 h-4"}),onClick:()=>{me.downloadF3d(t.id).catch(ye=>{console.error("F3D download failed:",ye)})}},{label:c("archives.menu.removeF3d"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>ce(!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:a.jsx(ca,{className:"w-4 h-4"}),onClick:()=>{me.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:a.jsx(Fs,{className:"w-4 h-4"}),onClick:()=>{const ye=`${window.location.origin}${me.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ye).then(()=>{m(c("archives.toast.linkCopied"))}).catch(()=>{m(c("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:a.jsx(MQ,{className:"w-4 h-4"}),onClick:()=>ne(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:a.jsx(Tx,{className:"w-4 h-4"}),onClick:()=>ee(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:a.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>le(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:a.jsx(Xf,{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:a.jsx(ai,{className:"w-4 h-4"}),onClick:()=>v(!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:a.jsx(Es,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:a.jsx(Es,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const ye=[];if(t.project_id&&ye.push({label:c("archives.menu.removeFromProject"),icon:a.jsx(Bt,{className:"w-4 h-4"}),onClick:()=>R.mutate(null)}),!s)ye.push({label:c("archives.menu.loading"),icon:a.jsx(dt,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const Ae=s.filter(ve=>ve.status==="active");Ae.length===0?ye.push({label:c("archives.menu.noProjectsAvailable"),icon:a.jsx(Es,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):Ae.forEach(ve=>{ye.push({label:ve.name,icon:a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:ve.color||"#888"}}),onClick:()=>R.mutate(ve.id),disabled:t.project_id===ve.id})})}return ye})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?a.jsx(xs,{className:"w-4 h-4"}):a.jsx(to,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:a.jsx(rn,{className:"w-4 h-4"}),onClick:()=>b(!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 a.jsxs(a.Fragment,{children:[a.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:ae,children:[a.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[i&&a.jsx("button",{onClick:()=>r(t.id),children:n?a.jsx(xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(to,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?a.jsx("img",{src:me.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):a.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:a.jsx(rm,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),a.jsxs("div",{className:"col-span-4",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&a.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.duplicate_count>0&&K>0&&B&&a.jsxs("button",{onClick:ye=>{ye.stopPropagation(),d?.(B)},className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 hover:bg-purple-600/90 text-white flex-shrink-0 transition-colors flex items-center gap-1",title:c("archives.viewOriginalPrint",{id:B}),children:[a.jsx(Fs,{className:"w-3 h-3"}),"#",K]}),t.duplicate_count>0&&K===0&&a.jsxs("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 text-white flex-shrink-0 flex items-center gap-1",title:`${t.duplicate_count} reprint${t.duplicate_count===1?"":"s"}`,children:[a.jsx(TQ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.timelapse_path&&a.jsx("span",{title:c("archives.list.hasTimelapse"),children:a.jsx(qh,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),U&&U.length>0&&a.jsx(_o,{to:`/files?folder=${U[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:U[0].name}),onClick:ye=>ye.stopPropagation(),children:a.jsx(Uc,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&a.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[a.jsx(Ar,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&a.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&a.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ye,Ae)=>a.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-black/20",style:{backgroundColor:ye},title:ye},Ae))})]})]}),a.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),a.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[a.jsx("div",{children:Qf(t.created_at)}),t.created_by_username&&a.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[a.jsx(sm,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:Co(t.file_size)}),a.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[Ph(t)&&a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>C(!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:a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{const ye=t.print_name||t.filename||"model";Th(t.id,ye,"file",l)},title:c("archives.card.openInBambuStudio"),children:a.jsx(na,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:a.jsx(rl,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{me.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ye=>{console.error("Archive download failed:",ye)})},title:c("archives.card.download"),children:a.jsx(ca,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>v(!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:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>b(!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:a.jsx(rn,{className:"w-4 h-4 text-red-400"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:ye=>{const Ae=ye.currentTarget.getBoundingClientRect();Y({x:Ae.left,y:Ae.bottom+4})},title:c("archives.card.moreOptions"),children:a.jsx(Bh,{className:"w-4 h-4"})})]})]}),x&&a.jsx(Xae,{archive:t,onClose:()=>v(!1)}),A&&a.jsx(cz,{archiveId:t.id,title:t.print_name||t.filename,fileType:Xoe(t.filename),onClose:()=>T(!1)}),_&&a.jsx(ec,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>C(!1)}),g&&a.jsx(_n,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{pe.mutate(),b(!1)},onCancel:()=>b(!1)}),oe&&a.jsx(_n,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Q.mutate(),W(!1)},onCancel:()=>W(!1)}),re&&a.jsx(_n,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{J.mutate(),ce(!1)},onCancel:()=>ce(!1)}),xe&&a.jsx(_n,{title:c("archives.modal.removeTimelapse"),message:c("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{he.mutate(),Ne(!1)},onCancel:()=>Ne(!1)}),$&&a.jsx(Yae,{x:$.x,y:$.y,items:Se,onClose:()=>Y(null)}),F&&t.timelapse_path&&a.jsx(Koe,{src:me.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:()=>k(!1),onEdit:()=>{u.invalidateQueries({queryKey:["archives"]}),k(!1)}}),D&&z.length>0&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:c("archives.modal.selectTimelapse")}),a.jsx("p",{className:"text-sm text-gray-400 mt-1",children:c("archives.modal.selectTimelapseDesc")})]}),a.jsx("button",{onClick:()=>{H(!1),X([])},className:"text-gray-400 hover:text-white p-1",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:z.map(ye=>a.jsxs("button",{onClick:()=>fe.mutate(ye.name),disabled:fe.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[a.jsx("div",{className:"font-medium text-white",children:ye.name}),a.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[a.jsx("span",{children:Co(ye.size)}),ye.mtime&&a.jsx("span",{children:Qf(ye.mtime)})]})]},ye.name))})]})}),L&&a.jsx(Qae,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>ne(!1)}),ie&&t.photos&&a.jsx(Zae,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>ee(!1),onDelete:async ye=>{try{await me.deleteArchivePhoto(t.id,ye),u.invalidateQueries({queryKey:["archives"]}),m(c("archives.toast.photoDeleted"))}catch{m(c("archives.toast.failedDeletePhoto"),"error")}}}),ue&&a.jsx(Woe,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>le(!1)}),P&&a.jsx(ec,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>N(!1)}),a.jsx("input",{ref:E,type:"file",accept:".3mf",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&V.mutate(Ae),ye.target.value=""}}),a.jsx("input",{ref:j,type:"file",accept:".f3d",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&G.mutate(Ae),ye.target.value=""}}),a.jsx("input",{ref:O,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ye=>{const Ae=ye.target.files?.[0];Ae&&I.mutate(Ae),ye.target.value=""}})]})}const CJe=[{id:"all",label:"All Archives",icon:a.jsx(Uc,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:a.jsx(Qn,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:a.jsx(Yr,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:a.jsx(Yr,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:a.jsx(Xf,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:a.jsx(Wa,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:a.jsx(Fs,{className:"w-4 h-4"})}];function PJe(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:i}=wr(),s=w.useRef(null),[o,l]=w.useState(""),[c,d]=w.useState(()=>{const Ve=localStorage.getItem("archiveFilterPrinter");return Ve?Number(Ve):null}),[u,m]=w.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,f]=w.useState(()=>{const Ve=localStorage.getItem("archiveFilterColors");return Ve?new Set(JSON.parse(Ve)):new Set}),[x,v]=w.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[g,b]=w.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[_,C]=w.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[P,N]=w.useState(()=>localStorage.getItem("archiveHideDuplicates")==="true"),[A,T]=w.useState(()=>localStorage.getItem("archiveFilterTag")),[F,k]=w.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[D,H]=w.useState(!1),[z,X]=w.useState([]),[L,ne]=w.useState(!1),[ie,ee]=w.useState(new Set),[ue,le]=w.useState(!1),[oe,W]=w.useState(!1),[re,ce]=w.useState(!1),[xe,Ne]=w.useState(!1),[$,Y]=w.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[E,j]=w.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[O,K]=w.useState(()=>localStorage.getItem("archiveCollection")||"all"),[B,he]=w.useState(0),[I,V]=w.useState(()=>{try{const Ve=localStorage.getItem("archivePageSize");return Ve?Number(Ve):50}catch{return 50}}),[Q,G]=w.useState(!1),[J,se]=w.useState(!1),[fe,pe]=w.useState(!1),[de,U]=w.useState(!1),[R,ae]=w.useState(null),[_e,Se]=w.useState(null),[ye,Ae]=w.useState(()=>localStorage.getItem("logFilterUser")||null),[ve,je]=w.useState(()=>localStorage.getItem("logFilterStatus")),[Re,Ee]=w.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[Te,Me]=w.useState(()=>localStorage.getItem("logFilterDateTo")||""),[Be,Ke]=w.useState(()=>{const Ve=localStorage.getItem("logOffset");return Ve?Number(Ve):0}),[tt,te]=w.useState(!1),[Ie,be]=w.useState(()=>{const Ve=localStorage.getItem("logPageSize");return Ve?Number(Ve):25}),$e=w.useCallback(Ve=>{Se(Ve),ae(Ve)},[]);w.useEffect(()=>{if(R){const Ve=setTimeout(()=>{const Et=document.querySelector(`[data-archive-id="${R}"]`);Et?Et.scrollIntoView({behavior:"smooth",block:"center"}):_e===R&&n(t("archives.originalPrintNotVisible"),"warning"),_e===R&&Se(null)},100),gt=setTimeout(()=>ae(null),5e3);return()=>{clearTimeout(Ve),clearTimeout(gt)}}},[R,_e,n,t]);const{data:He,isLoading:ge}=Qe({queryKey:["archives",c],queryFn:()=>me.getArchives(c||void 0)}),{data:Pe}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:qe}=Qe({queryKey:["projects"],queryFn:()=>me.getProjects()}),{data:Ze}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:ut}=Qe({queryKey:["users"],queryFn:me.getUsers,enabled:$==="log"}),{data:vt,isLoading:wt}=Qe({queryKey:["print-log",c,ye,ve,Re,Te,o,Be,Ie],queryFn:()=>me.getPrintLog({search:o||void 0,printerId:c||void 0,username:ye||void 0,status:ve||void 0,dateFrom:Re||void 0,dateTo:Te||void 0,limit:Ie,offset:Be}),enabled:$==="log"}),$t=Ze?.time_format||"system",Qt=Ze?.preferred_slicer||"bambu_studio",en=So(Ze?.currency||"USD"),Xt=it({mutationFn:async Ve=>(await Promise.all(Ve.map(gt=>me.deleteArchive(gt))),Ve.length),onSuccess:Ve=>{e.invalidateQueries({queryKey:["archives"]}),ee(new Set),n(`${Ve} archive${Ve!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),tn=it({mutationFn:()=>me.clearPrintLog(),onSuccess:Ve=>{e.invalidateQueries({queryKey:["print-log"]}),Ke(0),n(t("archives.log.cleared",{count:Ve.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});w.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),w.useEffect(()=>{u?localStorage.setItem("archiveFilterMaterial",u):localStorage.removeItem("archiveFilterMaterial")},[u]),w.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),w.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",x)},[x]),w.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",g.toString())},[g]),w.useEffect(()=>{localStorage.setItem("archiveHideFailed",_.toString())},[_]),w.useEffect(()=>{localStorage.setItem("archiveHideDuplicates",P.toString())},[P]),w.useEffect(()=>{A?localStorage.setItem("archiveFilterTag",A):localStorage.removeItem("archiveFilterTag")},[A]),w.useEffect(()=>{localStorage.setItem("archiveFilterFileType",F)},[F]),w.useEffect(()=>{he(0)},[o,c,u,p,x,g,_,P,A,F,E,O]),w.useEffect(()=>{try{localStorage.setItem("archivePageSize",String(I))}catch{}},[I]),w.useEffect(()=>{localStorage.setItem("archiveViewMode",$)},[$]),w.useEffect(()=>{localStorage.setItem("archiveSortBy",E)},[E]),w.useEffect(()=>{localStorage.setItem("archiveCollection",O)},[O]),w.useEffect(()=>{ye?localStorage.setItem("logFilterUser",ye):localStorage.removeItem("logFilterUser")},[ye]),w.useEffect(()=>{ve?localStorage.setItem("logFilterStatus",ve):localStorage.removeItem("logFilterStatus")},[ve]),w.useEffect(()=>{Re?localStorage.setItem("logFilterDateFrom",Re):localStorage.removeItem("logFilterDateFrom")},[Re]),w.useEffect(()=>{Te?localStorage.setItem("logFilterDateTo",Te):localStorage.removeItem("logFilterDateTo")},[Te]),w.useEffect(()=>{localStorage.setItem("logOffset",Be.toString())},[Be]),w.useEffect(()=>{localStorage.setItem("logPageSize",Ie.toString())},[Ie]);const Ge=new Map(Pe?.map(Ve=>[Ve.id,Ve.name])||[]),Ft=[...new Set(He?.flatMap(Ve=>Ve.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),Yt=[...new Set(He?.flatMap(Ve=>Ve.filament_color?.split(",")||[]).filter(Boolean)||[])],Pt=[...new Set(He?.flatMap(Ve=>Ve.tags?.split(",").map(gt=>gt.trim())||[]).filter(Boolean)||[])].sort(),pt=He?.filter(Ve=>{const gt=new Date,Et=er(Ve.created_at)||new Date(0);let Gt=!0;switch(O){case"recent":Gt=gt.getTime()-Et.getTime()<1440*60*1e3;break;case"this-week":Gt=gt.getTime()-Et.getTime()<10080*60*1e3;break;case"this-month":Gt=Et.getMonth()===gt.getMonth()&&Et.getFullYear()===gt.getFullYear();break;case"favorites":Gt=Ve.is_favorite===!0;break;case"failed":Gt=Ve.status==="failed"||Ve.status==="aborted";break;case"duplicates":Gt=Ve.duplicate_count>0;break}const on=(Ve.print_name||Ve.filename).toLowerCase().includes(o.toLowerCase()),fn=!u||Ve.filament_type?.split(", ").includes(u),Ln=Ve.filament_color?.split(",")||[],yn=p.size===0||(x==="or"?Ln.some(On=>p.has(On)):[...p].every(On=>Ln.includes(On))),hn=O==="favorites"||!g||Ve.is_favorite,xn=O==="failed"||!_||Ve.status!=="failed"&&Ve.status!=="aborted",Nn=O==="duplicates"||!P||Ve.duplicate_count===0||Ve.duplicate_sequence===0,Pn=Ve.tags?.split(",").map(On=>On.trim())||[],Nr=!A||Pn.includes(A),Sn=Ph(Ve);return Gt&&on&&fn&&yn&&hn&&xn&&Nn&&Nr&&(F==="all"||F==="gcode"&&Sn||F==="source"&&!Sn)}).sort((Ve,gt)=>{switch(E){case"date-desc":return(er(gt.created_at)?.getTime()||0)-(er(Ve.created_at)?.getTime()||0);case"date-asc":return(er(Ve.created_at)?.getTime()||0)-(er(gt.created_at)?.getTime()||0);case"name-asc":return(Ve.print_name||Ve.filename).localeCompare(gt.print_name||gt.filename);case"name-desc":return(gt.print_name||gt.filename).localeCompare(Ve.print_name||Ve.filename);case"size-desc":return gt.file_size-Ve.file_size;case"size-asc":return Ve.file_size-gt.file_size;default:return 0}}),Wt=pt?.length||0,Ut=I===-1,ze=Ut?Wt||1:I,st=Math.max(1,Math.ceil(Wt/ze)),ht=Ut?pt:pt?.slice(B*ze,(B+1)*ze);w.useEffect(()=>{if(R&&pt&&!Ut){const Ve=pt.findIndex(gt=>gt.id===R);if(Ve>=0){const gt=Math.floor(Ve/ze);gt!==B&&he(gt)}}},[R]);const rt=ue||ie.size>0,Le=Ve=>{ee(gt=>{const Et=new Set(gt);return Et.has(Ve)?Et.delete(Ve):Et.add(Ve),Et})},Oe=()=>{pt&&ee(new Set(pt.map(Ve=>Ve.id)))},Ce=()=>{ee(new Set),le(!1)},We=Ve=>{f(gt=>{const Et=new Set(gt);return Et.has(Ve)?Et.delete(Ve):Et.add(Ve),Et})},Je=()=>{f(new Set)},Xe=()=>{l(""),d(null),m(null),b(!1),C(!1),N(!1),T(null),k("all")},Ye=o||c||u||g||_||P||A||F!=="all",St=w.useCallback(Ve=>{Ve.preventDefault(),Ve.dataTransfer.types.includes("Files")&&ne(!0)},[]),et=w.useCallback(Ve=>{Ve.preventDefault(),Ve.currentTarget===Ve.target&&ne(!1)},[]),jt=w.useCallback(Ve=>{Ve.preventDefault(),ne(!1);const gt=Array.from(Ve.dataTransfer.files).filter(Et=>Et.name.endsWith(".3mf"));gt.length>0?(X(gt),H(!0)):Ve.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),bt=w.useCallback(Ve=>{const gt=Ve.target;if(gt.tagName==="INPUT"||gt.tagName==="TEXTAREA"||gt.isContentEditable){Ve.key==="Escape"&>.blur();return}switch(Ve.key){case"/":Ve.preventDefault(),s.current?.focus();break;case"u":case"U":!Ve.metaKey&&!Ve.ctrlKey&&(Ve.preventDefault(),H(!0));break;case"Escape":rt&&Ce();break}},[rt]);return w.useEffect(()=>(document.addEventListener("keydown",bt),()=>document.removeEventListener("keydown",bt)),[bt]),a.jsxs("div",{className:"p-4 md:p-8 relative",onDragOver:St,onDragLeave:et,onDrop:jt,children:[L&&a.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:a.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[a.jsx(Ma,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),a.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),a.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),rt&&a.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:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Ce,children:[a.jsx(Bt,{className:"w-4 h-4"}),"Close"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("span",{className:"text-white font-medium",children:[ie.size," selected"]}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:Oe,children:"Select All"}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>ce(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(im,{className:"w-4 h-4"}),"Tags"]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>Ne(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[a.jsx(Es,{className:"w-4 h-4"}),"Project"]}),a.jsxs(Fe,{variant:"secondary",size:"sm",disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const Ve=Array.from(ie);Promise.all(Ve.map(gt=>me.toggleFavorite(gt))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${Ve.length} archive${Ve.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[a.jsx(Xf,{className:"w-4 h-4"}),"Favorite"]}),a.jsxs(Fe,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>W(!0),disabled:!i("archives:delete_own","archives:delete_all"),title:i("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[a.jsx(rn,{className:"w-4 h-4"}),"Delete"]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),a.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:O,onChange:Ve=>K(Ve.target.value),children:CJe.map(Ve=>a.jsx("option",{value:Ve.id,children:Ve.label},Ve.id))})]}),a.jsxs("p",{className:"text-bambu-gray",children:[pt?.length||0," of ",He?.length||0," prints"]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>G(!Q),disabled:J,children:[J?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(sN,{className:"w-4 h-4"}),"Export"]}),Q&&a.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:[a.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()=>{G(!1),se(!0);try{const{blob:Ve,filename:gt}=await me.exportArchives({format:"csv",printerId:c||void 0,status:O==="failed"?"failed":void 0,search:o||void 0}),Et=URL.createObjectURL(Ve),Gt=document.createElement("a");Gt.href=Et,Gt.download=gt,Gt.click(),URL.revokeObjectURL(Et),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{se(!1)}},children:[a.jsx(Ms,{className:"w-4 h-4"}),"Export as CSV"]}),a.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()=>{G(!1),se(!0);try{const{blob:Ve,filename:gt}=await me.exportArchives({format:"xlsx",printerId:c||void 0,status:O==="failed"?"failed":void 0,search:o||void 0}),Et=URL.createObjectURL(Ve),Gt=document.createElement("a");Gt.href=Et,Gt.download=gt,Gt.click(),URL.revokeObjectURL(Et),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{se(!1)}},children:[a.jsx(sN,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),ie.size>=2&&ie.size<=5&&a.jsxs(Fe,{variant:"secondary",onClick:()=>pe(!0),children:[a.jsx(dx,{className:"w-4 h-4"}),"Compare (",ie.size,")"]}),!rt&&a.jsxs(Fe,{variant:"secondary",onClick:()=>le(!0),children:[a.jsx(xs,{className:"w-4 h-4"}),"Select"]}),a.jsxs(Fe,{onClick:()=>H(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[a.jsx(Ma,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),a.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[a.jsx("button",{className:`p-2 ${$==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("grid"),title:t("archives.gridView"),children:a.jsx(Lw,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${$==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("list"),title:t("archives.listView"),children:a.jsx(Ow,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${$==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("calendar"),title:t("archives.calendarView"),children:a.jsx(Lpe,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 ${$==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>Y("log"),title:t("archives.logView"),children:a.jsx(cfe,{className:"w-4 h-4"})})]}),$!=="log"&&a.jsx(At,{className:"mb-6",children:a.jsxs(Mt,{className:"py-4",children:[a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.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:Ve=>l(Ve.target.value)})]}),a.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:[a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(jP,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.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:Ve=>d(Ve.target.value?Number(Ve.target.value):null),children:[a.jsx("option",{value:"",children:"All Printers"}),Pe?.map(Ve=>a.jsx("option",{value:Ve.id,children:Ve.name},Ve.id))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(ja,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.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:u||"",onChange:Ve=>m(Ve.target.value||null),children:[a.jsx("option",{value:"",children:"All Materials"}),Ft.map(Ve=>a.jsx("option",{value:Ve,children:Ve},Ve))]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(iN,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.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:F,onChange:Ve=>k(Ve.target.value),children:[a.jsx("option",{value:"all",children:"All Files"}),a.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),a.jsx("option",{value:"source",children:"Source Only"})]})]}),a.jsxs("button",{onClick:()=>b(!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:[a.jsx(Xf,{className:`w-4 h-4 ${g?"fill-yellow-400":""}`}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),a.jsxs("button",{onClick:()=>C(!_),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:[a.jsx(Wa,{className:"w-4 h-4 "}),a.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),a.jsxs("button",{onClick:()=>N(!P),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${P?"bg-purple-500/20 border-purple-500 text-purple-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("archives.hideDuplicates"),children:[a.jsx(Fs,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm hidden md:inline",children:t("archives.hideDuplicates")})]}),Pt.length>0&&a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(im,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.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:A||"",onChange:Ve=>T(Ve.target.value||null),children:[a.jsx("option",{value:"",children:"All Tags"}),Pt.map(Ve=>a.jsx("option",{value:Ve,children:Ve},Ve))]}),a.jsx("button",{onClick:()=>U(!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:a.jsx(Hw,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx(fO,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),a.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:E,onChange:Ve=>j(Ve.target.value),children:[a.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),a.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),a.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),a.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),a.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),a.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),Ye&&a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:Xe,className:"text-bambu-gray hover:text-white",children:[a.jsx(Bt,{className:"w-4 h-4"}),"Reset"]})]}),Yt.length>0&&a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&a.jsx("button",{onClick:()=>v(Ve=>Ve==="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()}),a.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:Yt.map(Ve=>a.jsx("button",{onClick:()=>We(Ve),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(Ve)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:Ve},title:Ve},Ve))}),p.size>0&&a.jsxs("button",{onClick:Je,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[a.jsx(Bt,{className:"w-3 h-3"}),"Clear"]})]})]})}),a.jsx(SJe,{}),ge?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):pt?.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):$==="calendar"?a.jsx(At,{className:"p-6",children:a.jsx(G7e,{archives:pt||[],onArchiveClick:Ve=>{l(""),Y("grid"),ae(Ve.id)},highlightedArchiveId:R})}):$==="grid"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:ht?.map(Ve=>a.jsx(kJe,{archive:Ve,printerName:Ve.printer_id?Ge.get(Ve.printer_id)||"Unknown":Ve.sliced_for_model?`Sliced for ${Ve.sliced_for_model}`:"No Printer",isSelected:ie.has(Ve.id),onSelect:Le,selectionMode:rt,projects:qe,isHighlighted:Ve.id===R,timeFormat:$t,preferredSlicer:Qt,currency:en,t,onNavigateToArchive:$e},Ve.id))}),a.jsx($X,{pageIndex:B,pageSize:I,totalRows:Wt,totalPages:st,onPageChange:he,onPageSizeChange:Ve=>{V(Ve),he(0)},t})]}):$==="list"?a.jsxs(a.Fragment,{children:[a.jsx(At,{children:a.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[a.jsx("div",{className:"col-span-1"}),a.jsx("div",{className:"col-span-4",children:"Name"}),a.jsx("div",{className:"col-span-2",children:"Printer"}),a.jsx("div",{className:"col-span-2",children:"Date"}),a.jsx("div",{className:"col-span-1",children:"Size"}),a.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),ht?.map(Ve=>a.jsx(NJe,{archive:Ve,printerName:Ve.printer_id?Ge.get(Ve.printer_id)||"Unknown":Ve.sliced_for_model?`Sliced for ${Ve.sliced_for_model}`:"No Printer",isSelected:ie.has(Ve.id),onSelect:Le,selectionMode:rt,projects:qe,isHighlighted:Ve.id===R,preferredSlicer:Qt,t,onNavigateToArchive:$e},Ve.id))]})}),a.jsx($X,{pageIndex:B,pageSize:I,totalRows:Wt,totalPages:st,onPageChange:he,onPageSizeChange:Ve=>{V(Ve),he(0)},t})]}):$==="log"?a.jsxs("div",{className:"space-y-4",children:[a.jsx(At,{children:a.jsx(Mt,{className:"py-3",children:a.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[a.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.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:Ve=>{l(Ve.target.value),Ke(0)}})]}),a.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:Ve=>{d(Ve.target.value?Number(Ve.target.value):null),Ke(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allPrinters")}),Pe?.map(Ve=>a.jsx("option",{value:Ve.id,children:Ve.name},Ve.id))]}),a.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:ye||"",onChange:Ve=>{Ae(Ve.target.value||null),Ke(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allUsers")}),ut?.map(Ve=>a.jsx("option",{value:Ve.username,children:Ve.username},Ve.id))]}),a.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:ve||"",onChange:Ve=>{je(Ve.target.value||null),Ke(0)},children:[a.jsx("option",{value:"",children:t("archives.log.allStatuses")}),a.jsx("option",{value:"completed",children:t("archives.status.completed")}),a.jsx("option",{value:"failed",children:t("archives.status.failed")}),a.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),a.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),a.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),a.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:Re,onChange:Ve=>{Ee(Ve.target.value),Ke(0)}})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),a.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:Te,onChange:Ve=>{Me(Ve.target.value),Ke(0)}})]}),a.jsx("div",{className:"ml-auto",children:a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>te(!0),disabled:!r("archives:delete_all")||tn.isPending,children:[a.jsx(rn,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),a.jsx(At,{children:wt?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):vt?.items.length?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),a.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),a.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:vt.items.map(Ve=>a.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[a.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Zf(Ve.started_at||Ve.created_at,$t)}),a.jsx("td",{className:"px-4 py-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[Ve.thumbnail_path&&a.jsx("img",{src:me.getPrintLogThumbnail(Ve.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:gt=>{gt.target.style.display="none"}}),a.jsx("span",{className:"text-white truncate max-w-[200px]",children:Ve.print_name||"—"})]})}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Ve.printer_name||"—"}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Ve.created_by_username||"—"}),a.jsx("td",{className:"px-4 py-3",children:a.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Ve.status==="completed"?"bg-green-500/20 text-green-400":Ve.status==="failed"?"bg-red-500/20 text-red-400":Ve.status==="stopped"?"bg-yellow-500/20 text-yellow-400":Ve.status==="cancelled"?"bg-orange-500/20 text-orange-400":Ve.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:Ve.status})}),a.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:Ve.duration_seconds?ps(Ve.duration_seconds):"—"}),a.jsx("td",{className:"px-4 py-3",children:a.jsxs("div",{className:"flex items-center gap-1.5",children:[Ve.filament_color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:Ve.filament_color.startsWith("#")?Ve.filament_color:void 0}}),a.jsx("span",{className:"text-bambu-gray-light text-xs",children:Ve.filament_type||"—"})]})})]},Ve.id))})]})}),a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(Be+Ie,vt.total),total:vt.total})}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),a.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:Ie,onChange:Ve=>{be(Number(Ve.target.value)),Ke(0)},children:[a.jsx("option",{value:10,children:"10"}),a.jsx("option",{value:25,children:"25"}),a.jsx("option",{value:50,children:"50"}),a.jsx("option",{value:100,children:"100"})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(Be/Ie)+1," / ",Math.max(1,Math.ceil(vt.total/Ie))]}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>Ke(Math.max(0,Be-Ie)),disabled:Be===0,children:a.jsx(dl,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>Ke(Be+Ie),disabled:Be+Ie>=vt.total,children:a.jsx(Ka,{className:"w-4 h-4"})})]})]})]}):a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,D&&a.jsx(O7e,{onClose:()=>{H(!1),X([])},initialFiles:z}),oe&&a.jsx(_n,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:ie.size}),confirmText:t("archives.modal.deleteCount",{count:ie.size}),variant:"danger",onConfirm:()=>{Xt.mutate(Array.from(ie)),W(!1)},onCancel:()=>W(!1)}),re&&a.jsx(U7e,{selectedIds:Array.from(ie),existingTags:Pt,onClose:()=>ce(!1)}),xe&&a.jsx(B7e,{selectedIds:Array.from(ie),onClose:()=>Ne(!1)}),fe&&ie.size>=2&&ie.size<=5&&a.jsx(xJe,{archiveIds:Array.from(ie),onClose:()=>{pe(!1),ee(new Set),le(!1)}}),de&&a.jsx(_Je,{onClose:()=>U(!1)}),tt&&a.jsx(_n,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{tn.mutate(),te(!1)},onCancel:()=>te(!1)})]})}function $X({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o("archives.prints")}`:a.jsxs(a.Fragment,{children:[o("archives.pagination.showing")," ",t*c+1," ",o("archives.pagination.to")," ",Math.min((t+1)*c,n)," ",o("archives.pagination.of")," ",n," ",o("archives.prints")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("archives.pagination.show")}),a.jsxs("select",{value:e,onChange:d=>s(Number(d.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:[[25,50,100,200].map(d=>a.jsx("option",{value:d,children:d},d)),a.jsx("option",{value:-1,children:o("archives.pagination.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(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:a.jsx(bO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(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:a.jsx(dl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("archives.pagination.page")," ",t+1," ",o("archives.pagination.of")," ",r]}),a.jsx("button",{onClick:()=>i(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:a.jsx(Ka,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(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:a.jsx(xO,{className:"w-4 h-4"})})]})]})]})}function TJe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return w.useMemo(()=>r=>{e.forEach(i=>i(r))},e)}const tA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Cy(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function Yz(t){return"nodeType"in t}function Lo(t){var e,n;return t?Cy(t)?t:Yz(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Qz(t){const{Document:e}=Lo(t);return t instanceof e}function _S(t){return Cy(t)?!1:t instanceof Lo(t).HTMLElement}function Yoe(t){return t instanceof Lo(t).SVGElement}function Py(t){return t?Cy(t)?t.document:Yz(t)?Qz(t)?t:_S(t)||Yoe(t)?t.ownerDocument:document:document:document}const zd=tA?w.useLayoutEffect:w.useEffect;function Zz(t){const e=w.useRef(t);return zd(()=>{e.current=t}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return e.current==null?void 0:e.current(...r)},[])}function AJe(){const t=w.useRef(null),e=w.useCallback((r,i)=>{t.current=setInterval(r,i)},[]),n=w.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function Pw(t,e){e===void 0&&(e=[t]);const n=w.useRef(t);return zd(()=>{n.current!==t&&(n.current=t)},e),n}function kS(t,e){const n=w.useRef();return w.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function bP(t){const e=Zz(t),n=w.useRef(null),r=w.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function qL(t){const e=w.useRef();return w.useEffect(()=>{e.current=t},[t]),e.current}let s3={};function NS(t,e){return w.useMemo(()=>{if(e)return e;const n=s3[t]==null?0:s3[t]+1;return s3[t]=n,t+"-"+n},[t,e])}function Qoe(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const l=Object.entries(o);for(const[c,d]of l){const u=s[c];u!=null&&(s[c]=u+t*d)}return s},{...e})}}const kx=Qoe(1),Tw=Qoe(-1);function jJe(t){return"clientX"in t&&"clientY"in t}function Jz(t){if(!t)return!1;const{KeyboardEvent:e}=Lo(t.target);return e&&t instanceof e}function MJe(t){if(!t)return!1;const{TouchEvent:e}=Lo(t.target);return e&&t instanceof e}function $L(t){if(MJe(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 jJe(t)?{x:t.clientX,y:t.clientY}:null}const ty=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[ty.Translate.toString(t),ty.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),VX="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function EJe(t){return t.matches(VX)?t:t.querySelector(VX)}const DJe={display:"none"};function FJe(t){let{id:e,value:n}=t;return ea.createElement("div",{id:e,style:DJe},n)}function RJe(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const i={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 ea.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function LJe(){const[t,e]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const Zoe=w.createContext(null);function OJe(t){const e=w.useContext(Zoe);w.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function IJe(){const[t]=w.useState(()=>new Set),e=w.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[w.useCallback(r=>{let{type:i,event:s}=r;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const zJe={draggable:`
- To pick up a draggable item, press the space bar.
- While dragging, use the arrow keys to move the item.
- Press space again to drop the item in its new position, or press escape to cancel.
- `},UJe={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 BJe(t){let{announcements:e=UJe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=zJe}=t;const{announce:s,announcement:o}=LJe(),l=NS("DndLiveRegion"),[c,d]=w.useState(!1);if(w.useEffect(()=>{d(!0)},[]),OJe(w.useMemo(()=>({onDragStart(m){let{active:p}=m;s(e.onDragStart({active:p}))},onDragMove(m){let{active:p,over:f}=m;e.onDragMove&&s(e.onDragMove({active:p,over:f}))},onDragOver(m){let{active:p,over:f}=m;s(e.onDragOver({active:p,over:f}))},onDragEnd(m){let{active:p,over:f}=m;s(e.onDragEnd({active:p,over:f}))},onDragCancel(m){let{active:p,over:f}=m;s(e.onDragCancel({active:p,over:f}))}}),[s,e])),!c)return null;const u=ea.createElement(ea.Fragment,null,ea.createElement(FJe,{id:r,value:i.draggable}),ea.createElement(RJe,{id:l,announcement:o}));return n?Ou.createPortal(u,n):u}var _i;(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"})(_i||(_i={}));function xP(){}function yP(t,e){return w.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function Joe(){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 qc=Object.freeze({x:0,y:0});function ele(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function tle(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function HJe(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function GX(t){let{left:e,top:n,height:r,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function nle(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function WX(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 rle=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=WX(e,e.left,e.top),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const d=ele(WX(c),i);s.push({id:l,data:{droppableContainer:o,value:d}})}}return s.sort(tle)},qJe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=GX(e),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const d=GX(c),u=i.reduce((p,f,x)=>p+ele(d[x],f),0),m=Number((u/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:m}})}}return s.sort(tle)};function $Je(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),i=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=i-r,l=s-n;if(r<i&&n<s){const c=e.width*e.height,d=t.width*t.height,u=o*l,m=u/(c+d-u);return Number(m.toFixed(4))}return 0}const VJe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const i=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const c=$Je(l,e);c>0&&i.push({id:o,data:{droppableContainer:s,value:c}})}}return i.sort(HJe)};function GJe(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function ale(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:qc}function WJe(t){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];return i.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 KJe=WJe(1);function XJe(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 YJe(t,e,n){const r=XJe(e);if(!r)return t;const{scaleX:i,scaleY:s,x:o,y:l}=r,c=t.left-o-(1-i)*parseFloat(n),d=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),u=i?t.width/i:t.width,m=s?t.height/s:t.height;return{width:u,height:m,top:d,right:c+u,bottom:d+m,left:c}}const QJe={ignoreTransform:!1};function Ty(t,e){e===void 0&&(e=QJe);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:d,transformOrigin:u}=Lo(t).getComputedStyle(t);d&&(n=YJe(n,d,u))}const{top:r,left:i,width:s,height:o,bottom:l,right:c}=n;return{top:r,left:i,width:s,height:o,bottom:l,right:c}}function KX(t){return Ty(t,{ignoreTransform:!0})}function ZJe(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function JJe(t,e){return e===void 0&&(e=Lo(t).getComputedStyle(t)),e.position==="fixed"}function eet(t,e){e===void 0&&(e=Lo(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const s=e[i];return typeof s=="string"?n.test(s):!1})}function nA(t,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Qz(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!_S(i)||Yoe(i)||n.includes(i))return n;const s=Lo(t).getComputedStyle(i);return i!==t&&eet(i,s)&&n.push(i),JJe(i,s)?n:r(i.parentNode)}return t?r(t):n}function ile(t){const[e]=nA(t,1);return e??null}function o3(t){return!tA||!t?null:Cy(t)?t:Yz(t)?Qz(t)||t===Py(t).scrollingElement?window:_S(t)?t:null:null}function sle(t){return Cy(t)?t.scrollX:t.scrollLeft}function ole(t){return Cy(t)?t.scrollY:t.scrollTop}function VL(t){return{x:sle(t),y:ole(t)}}var zi;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(zi||(zi={}));function lle(t){return!tA||!t?!1:t===document.scrollingElement}function cle(t){const e={x:0,y:0},n=lle(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const tet={x:.2,y:.2};function net(t,e,n,r,i){let{top:s,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=tet);const{isTop:d,isBottom:u,isLeft:m,isRight:p}=cle(t),f={x:0,y:0},x={x:0,y:0},v={height:e.height*i.y,width:e.width*i.x};return!d&&s<=e.top+v.height?(f.y=zi.Backward,x.y=r*Math.abs((e.top+v.height-s)/v.height)):!u&&c>=e.bottom-v.height&&(f.y=zi.Forward,x.y=r*Math.abs((e.bottom-v.height-c)/v.height)),!p&&l>=e.right-v.width?(f.x=zi.Forward,x.x=r*Math.abs((e.right-v.width-l)/v.width)):!m&&o<=e.left+v.width&&(f.x=zi.Backward,x.x=r*Math.abs((e.left+v.width-o)/v.width)),{direction:f,speed:x}}function ret(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:i}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:t.clientWidth,height:t.clientHeight}}function dle(t){return t.reduce((e,n)=>kx(e,VL(n)),qc)}function aet(t){return t.reduce((e,n)=>e+sle(n),0)}function iet(t){return t.reduce((e,n)=>e+ole(n),0)}function set(t,e){if(e===void 0&&(e=Ty),!t)return;const{top:n,left:r,bottom:i,right:s}=e(t);ile(t)&&(i<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const oet=[["x",["left","right"],aet],["y",["top","bottom"],iet]];class e5{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),i=dle(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of oet)for(const c of o)Object.defineProperty(this,c,{get:()=>{const d=l(r),u=i[s]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class M0{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 i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function cet(t){const{EventTarget:e}=Lo(t);return t instanceof e?t:Py(t)}function l3(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 Hl;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(Hl||(Hl={}));function XX(t){t.preventDefault()}function det(t){t.stopPropagation()}var vr;(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"})(vr||(vr={}));const ule={start:[vr.Space,vr.Enter],cancel:[vr.Esc],end:[vr.Space,vr.Enter,vr.Tab]},uet=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case vr.Right:return{...n,x:n.x+25};case vr.Left:return{...n,x:n.x-25};case vr.Down:return{...n,y:n.y+25};case vr.Up:return{...n,y:n.y-25}}};class rA{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 M0(Py(n)),this.windowListeners=new M0(Lo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Hl.Resize,this.handleCancel),this.windowListeners.add(Hl.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Hl.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&set(r),n(qc)}handleKeyDown(e){if(Jz(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:s=ule,coordinateGetter:o=uet,scrollBehavior:l="smooth"}=i,{code:c}=e;if(s.end.includes(c)){this.handleEnd(e);return}if(s.cancel.includes(c)){this.handleCancel(e);return}const{collisionRect:d}=r.current,u=d?{x:d.left,y:d.top}:qc;this.referenceCoordinates||(this.referenceCoordinates=u);const m=o(e,{active:n,context:r.current,currentCoordinates:u});if(m){const p=Tw(m,u),f={x:0,y:0},{scrollableAncestors:x}=r.current;for(const v of x){const g=e.code,{isTop:b,isRight:_,isLeft:C,isBottom:P,maxScroll:N,minScroll:A}=cle(v),T=ret(v),F={x:Math.min(g===vr.Right?T.right-T.width/2:T.right,Math.max(g===vr.Right?T.left:T.left+T.width/2,m.x)),y:Math.min(g===vr.Down?T.bottom-T.height/2:T.bottom,Math.max(g===vr.Down?T.top:T.top+T.height/2,m.y))},k=g===vr.Right&&!_||g===vr.Left&&!C,D=g===vr.Down&&!P||g===vr.Up&&!b;if(k&&F.x!==m.x){const H=v.scrollLeft+p.x,z=g===vr.Right&&H<=N.x||g===vr.Left&&H>=A.x;if(z&&!p.y){v.scrollTo({left:H,behavior:l});return}z?f.x=v.scrollLeft-H:f.x=g===vr.Right?v.scrollLeft-N.x:v.scrollLeft-A.x,f.x&&v.scrollBy({left:-f.x,behavior:l});break}else if(D&&F.y!==m.y){const H=v.scrollTop+p.y,z=g===vr.Down&&H<=N.y||g===vr.Up&&H>=A.y;if(z&&!p.x){v.scrollTo({top:H,behavior:l});return}z?f.y=v.scrollTop-H:f.y=g===vr.Down?v.scrollTop-N.y:v.scrollTop-A.y,f.y&&v.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(e,kx(Tw(m,this.referenceCoordinates),f))}}}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()}}rA.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=ule,onActivation:i}=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(),i?.({event:t.nativeEvent}),!0)}return!1}}];function YX(t){return!!(t&&"distance"in t)}function QX(t){return!!(t&&"delay"in t)}class t5{constructor(e,n,r){var i;r===void 0&&(r=cet(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=Py(o),this.documentListeners=new M0(this.document),this.listeners=new M0(r),this.windowListeners=new M0(Lo(o)),this.initialCoordinates=(i=$L(s))!=null?i:qc,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(Hl.Resize,this.handleCancel),this.windowListeners.add(Hl.DragStart,XX),this.windowListeners.add(Hl.VisibilityChange,this.handleCancel),this.windowListeners.add(Hl.ContextMenu,XX),this.documentListeners.add(Hl.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(QX(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(YX(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:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(Hl.Click,det,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Hl.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const c=(n=$L(e))!=null?n:qc,d=Tw(i,c);if(!r&&l){if(YX(l)){if(l.tolerance!=null&&l3(d,l.tolerance))return this.handleCancel();if(l3(d,l.distance))return this.handleStart()}if(QX(l)&&l3(d,l.tolerance))return this.handleCancel();this.handlePending(l,d);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===vr.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const met={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class aA extends t5{constructor(e){const{event:n}=e,r=Py(n.target);super(e,met,r)}}aA.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 het={move:{name:"mousemove"},end:{name:"mouseup"}};var GL;(function(t){t[t.RightClick=2]="RightClick"})(GL||(GL={}));class pet extends t5{constructor(e){super(e,het,Py(e.event.target))}}pet.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===GL.RightClick?!1:(r?.({event:n}),!0)}}];const c3={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class fet extends t5{constructor(e){super(e,c3)}static setup(){return window.addEventListener(c3.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(c3.move.name,e)};function e(){}}}fet.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var E0;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(E0||(E0={}));var vP;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(vP||(vP={}));function get(t){let{acceleration:e,activator:n=E0.Pointer,canScroll:r,draggingRect:i,enabled:s,interval:o=5,order:l=vP.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:m,threshold:p}=t;const f=xet({delta:m,disabled:!s}),[x,v]=AJe(),g=w.useRef({x:0,y:0}),b=w.useRef({x:0,y:0}),_=w.useMemo(()=>{switch(n){case E0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case E0.DraggableRect:return i}},[n,i,c]),C=w.useRef(null),P=w.useCallback(()=>{const A=C.current;if(!A)return;const T=g.current.x*b.current.x,F=g.current.y*b.current.y;A.scrollBy(T,F)},[]),N=w.useMemo(()=>l===vP.TreeOrder?[...d].reverse():d,[l,d]);w.useEffect(()=>{if(!s||!d.length||!_){v();return}for(const A of N){if(r?.(A)===!1)continue;const T=d.indexOf(A),F=u[T];if(!F)continue;const{direction:k,speed:D}=net(A,F,_,e,p);for(const H of["x","y"])f[H][k[H]]||(D[H]=0,k[H]=0);if(D.x>0||D.y>0){v(),C.current=A,x(P,o),g.current=D,b.current=k;return}}g.current={x:0,y:0},b.current={x:0,y:0},v()},[e,P,r,v,s,o,JSON.stringify(_),JSON.stringify(f),x,d,N,u,JSON.stringify(p)])}const bet={x:{[zi.Backward]:!1,[zi.Forward]:!1},y:{[zi.Backward]:!1,[zi.Forward]:!1}};function xet(t){let{delta:e,disabled:n}=t;const r=qL(e);return kS(i=>{if(n||!r||!i)return bet;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[zi.Backward]:i.x[zi.Backward]||s.x===-1,[zi.Forward]:i.x[zi.Forward]||s.x===1},y:{[zi.Backward]:i.y[zi.Backward]||s.y===-1,[zi.Forward]:i.y[zi.Forward]||s.y===1}}},[n,e,r])}function yet(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return kS(i=>{var s;return e==null?null:(s=r??i)!=null?s:null},[r,e])}function vet(t,e){return w.useMemo(()=>t.reduce((n,r)=>{const{sensor:i}=r,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var Aw;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Aw||(Aw={}));var WL;(function(t){t.Optimized="optimized"})(WL||(WL={}));const ZX=new Map;function wet(t,e){let{dragging:n,dependencies:r,config:i}=e;const[s,o]=w.useState(null),{frequency:l,measure:c,strategy:d}=i,u=w.useRef(t),m=g(),p=Pw(m),f=w.useCallback(function(b){b===void 0&&(b=[]),!p.current&&o(_=>_===null?b:_.concat(b.filter(C=>!_.includes(C))))},[p]),x=w.useRef(null),v=kS(b=>{if(m&&!n)return ZX;if(!b||b===ZX||u.current!==t||s!=null){const _=new Map;for(let C of t){if(!C)continue;if(s&&s.length>0&&!s.includes(C.id)&&C.rect.current){_.set(C.id,C.rect.current);continue}const P=C.node.current,N=P?new e5(c(P),P):null;C.rect.current=N,N&&_.set(C.id,N)}return _}return b},[t,s,n,m,c]);return w.useEffect(()=>{u.current=t},[t]),w.useEffect(()=>{m||f()},[n,m]),w.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),w.useEffect(()=>{m||typeof l!="number"||x.current!==null||(x.current=setTimeout(()=>{f(),x.current=null},l))},[l,m,f,...r]),{droppableRects:v,measureDroppableContainers:f,measuringScheduled:s!=null};function g(){switch(d){case Aw.Always:return!1;case Aw.BeforeDragging:return n;default:return!n}}}function mle(t,e){return kS(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function _et(t,e){return mle(t,e)}function ket(t){let{callback:e,disabled:n}=t;const r=Zz(e),i=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(()=>()=>i?.disconnect(),[i]),i}function iA(t){let{callback:e,disabled:n}=t;const r=Zz(e),i=w.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return w.useEffect(()=>()=>i?.disconnect(),[i]),i}function Net(t){return new e5(Ty(t),t)}function JX(t,e,n){e===void 0&&(e=Net);const[r,i]=w.useState(null);function s(){i(c=>{if(!t)return null;if(t.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=e(t);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const o=ket({callback(c){if(t)for(const d of c){const{type:u,target:m}=d;if(u==="childList"&&m instanceof HTMLElement&&m.contains(t)){s();break}}}}),l=iA({callback:s});return zd(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),r}function Cet(t){const e=mle(t);return ale(t,e)}const eY=[];function Pet(t){const e=w.useRef(t),n=kS(r=>t?r&&r!==eY&&t&&e.current&&t.parentNode===e.current.parentNode?r:nA(t):eY,[t]);return w.useEffect(()=>{e.current=t},[t]),n}function Tet(t){const[e,n]=w.useState(null),r=w.useRef(t),i=w.useCallback(s=>{const o=o3(s.target);o&&n(l=>l?(l.set(o,VL(o)),new Map(l)):null)},[]);return w.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(c=>{const d=o3(c);return d?(d.addEventListener("scroll",i,{passive:!0}),[d,VL(d)]):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 d=o3(c);d?.removeEventListener("scroll",i)})}},[i,t]),w.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>kx(s,o),qc):dle(t):qc,[t,e])}function tY(t,e){e===void 0&&(e=[]);const n=w.useRef(null);return w.useEffect(()=>{n.current=null},e),w.useEffect(()=>{const r=t!==qc;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?Tw(t,n.current):qc}function Aet(t){w.useEffect(()=>{if(!tA)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 jet(t,e){return w.useMemo(()=>t.reduce((n,r)=>{let{eventName:i,handler:s}=r;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function hle(t){return w.useMemo(()=>t?ZJe(t):null,[t])}const nY=[];function Met(t,e){e===void 0&&(e=Ty);const[n]=t,r=hle(n?Lo(n):null),[i,s]=w.useState(nY);function o(){s(()=>t.length?t.map(c=>lle(c)?r:new e5(e(c),c)):nY)}const l=iA({callback:o});return zd(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),i}function Eet(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return _S(e)?e:t}function Det(t){let{measure:e}=t;const[n,r]=w.useState(null),i=w.useCallback(d=>{for(const{target:u}of d)if(_S(u)){r(m=>{const p=e(u);return m?{...m,width:p.width,height:p.height}:p});break}},[e]),s=iA({callback:i}),o=w.useCallback(d=>{const u=Eet(d);s?.disconnect(),u&&s?.observe(u),r(u?e(u):null)},[e,s]),[l,c]=bP(o);return w.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const Fet=[{sensor:aA,options:{}},{sensor:rA,options:{}}],Ret={current:{}},Kk={draggable:{measure:KX},droppable:{measure:KX,strategy:Aw.WhileDragging,frequency:WL.Optimized},dragOverlay:{measure:Ty}};class D0 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 Let={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new D0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:xP},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Kk,measureDroppableContainers:xP,windowRect:null,measuringScheduled:!1},Oet={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:xP,draggableNodes:new Map,over:null,measureDroppableContainers:xP},sA=w.createContext(Oet),ple=w.createContext(Let);function Iet(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new D0}}}function zet(t,e){switch(e.type){case _i.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case _i.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 _i.DragEnd:case _i.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case _i.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new D0(t.droppable.containers);return i.set(r,n),{...t,droppable:{...t.droppable,containers:i}}}case _i.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new D0(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case _i.UnregisterDroppable:{const{id:n,key:r}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;const s=new D0(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function Uet(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:i}=w.useContext(sA),s=qL(r),o=qL(n?.id);return w.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!Jz(s)||document.activeElement===s.target)return;const l=i.get(o);if(!l)return;const{activatorNode:c,node:d}=l;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const m=EJe(u);if(m){m.focus();break}}})}},[r,e,i,o,s]),null}function Bet(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...r}),n):n}function Het(t){return w.useMemo(()=>({draggable:{...Kk.draggable,...t?.draggable},droppable:{...Kk.droppable,...t?.droppable},dragOverlay:{...Kk.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function qet(t){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=t;const s=w.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;zd(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const d=e?.node.current;if(!d||d.isConnected===!1)return;const u=n(d),m=ale(u,r);if(o||(m.x=0),l||(m.y=0),s.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const p=ile(d);p&&p.scrollBy({top:m.y,left:m.x})}},[e,o,l,r,n])}const fle=w.createContext({...qc,scaleX:1,scaleY:1});var Sh;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(Sh||(Sh={}));const gle=w.memo(function(e){var n,r,i,s;let{id:o,accessibility:l,autoScroll:c=!0,children:d,sensors:u=Fet,collisionDetection:m=VJe,measuring:p,modifiers:f,...x}=e;const v=w.useReducer(zet,void 0,Iet),[g,b]=v,[_,C]=IJe(),[P,N]=w.useState(Sh.Uninitialized),A=P===Sh.Initialized,{draggable:{active:T,nodes:F,translate:k},droppable:{containers:D}}=g,H=T!=null?F.get(T):null,z=w.useRef({initial:null,translated:null}),X=w.useMemo(()=>{var $e;return T!=null?{id:T,data:($e=H?.data)!=null?$e:Ret,rect:z}:null},[T,H]),L=w.useRef(null),[ne,ie]=w.useState(null),[ee,ue]=w.useState(null),le=Pw(x,Object.values(x)),oe=NS("DndDescribedBy",o),W=w.useMemo(()=>D.getEnabled(),[D]),re=Het(p),{droppableRects:ce,measureDroppableContainers:xe,measuringScheduled:Ne}=wet(W,{dragging:A,dependencies:[k.x,k.y],config:re.droppable}),$=yet(F,T),Y=w.useMemo(()=>ee?$L(ee):null,[ee]),E=be(),j=_et($,re.draggable.measure);qet({activeNode:T!=null?F.get(T):null,config:E.layoutShiftCompensation,initialRect:j,measure:re.draggable.measure});const O=JX($,re.draggable.measure,j),K=JX($?$.parentElement:null),B=w.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:F,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),he=D.getNodeFor((n=B.current.over)==null?void 0:n.id),I=Det({measure:re.dragOverlay.measure}),V=(r=I.nodeRef.current)!=null?r:$,Q=A?(i=I.rect)!=null?i:O:null,G=!!(I.nodeRef.current&&I.rect),J=Cet(G?null:O),se=hle(V?Lo(V):null),fe=Pet(A?he??$:null),pe=Met(fe),de=Bet(f,{transform:{x:k.x-J.x,y:k.y-J.y,scaleX:1,scaleY:1},activatorEvent:ee,active:X,activeNodeRect:O,containerNodeRect:K,draggingNodeRect:Q,over:B.current.over,overlayNodeRect:I.rect,scrollableAncestors:fe,scrollableAncestorRects:pe,windowRect:se}),U=Y?kx(Y,k):null,R=Tet(fe),ae=tY(R),_e=tY(R,[O]),Se=kx(de,ae),ye=Q?KJe(Q,de):null,Ae=X&&ye?m({active:X,collisionRect:ye,droppableRects:ce,droppableContainers:W,pointerCoordinates:U}):null,ve=nle(Ae,"id"),[je,Re]=w.useState(null),Ee=G?de:kx(de,_e),Te=GJe(Ee,(s=je?.rect)!=null?s:null,O),Me=w.useRef(null),Be=w.useCallback(($e,He)=>{let{sensor:ge,options:Pe}=He;if(L.current==null)return;const qe=F.get(L.current);if(!qe)return;const Ze=$e.nativeEvent,ut=new ge({active:L.current,activeNode:qe,event:Ze,options:Pe,context:B,onAbort(wt){if(!F.get(wt))return;const{onDragAbort:Qt}=le.current,en={id:wt};Qt?.(en),_({type:"onDragAbort",event:en})},onPending(wt,$t,Qt,en){if(!F.get(wt))return;const{onDragPending:tn}=le.current,Ge={id:wt,constraint:$t,initialCoordinates:Qt,offset:en};tn?.(Ge),_({type:"onDragPending",event:Ge})},onStart(wt){const $t=L.current;if($t==null)return;const Qt=F.get($t);if(!Qt)return;const{onDragStart:en}=le.current,Xt={activatorEvent:Ze,active:{id:$t,data:Qt.data,rect:z}};Ou.unstable_batchedUpdates(()=>{en?.(Xt),N(Sh.Initializing),b({type:_i.DragStart,initialCoordinates:wt,active:$t}),_({type:"onDragStart",event:Xt}),ie(Me.current),ue(Ze)})},onMove(wt){b({type:_i.DragMove,coordinates:wt})},onEnd:vt(_i.DragEnd),onCancel:vt(_i.DragCancel)});Me.current=ut;function vt(wt){return async function(){const{active:Qt,collisions:en,over:Xt,scrollAdjustedTranslate:tn}=B.current;let Ge=null;if(Qt&&tn){const{cancelDrop:Ft}=le.current;Ge={activatorEvent:Ze,active:Qt,collisions:en,delta:tn,over:Xt},wt===_i.DragEnd&&typeof Ft=="function"&&await Promise.resolve(Ft(Ge))&&(wt=_i.DragCancel)}L.current=null,Ou.unstable_batchedUpdates(()=>{b({type:wt}),N(Sh.Uninitialized),Re(null),ie(null),ue(null),Me.current=null;const Ft=wt===_i.DragEnd?"onDragEnd":"onDragCancel";if(Ge){const Yt=le.current[Ft];Yt?.(Ge),_({type:Ft,event:Ge})}})}}},[F]),Ke=w.useCallback(($e,He)=>(ge,Pe)=>{const qe=ge.nativeEvent,Ze=F.get(Pe);if(L.current!==null||!Ze||qe.dndKit||qe.defaultPrevented)return;const ut={active:Ze};$e(ge,He.options,ut)===!0&&(qe.dndKit={capturedBy:He.sensor},L.current=Pe,Be(ge,He))},[F,Be]),tt=vet(u,Ke);Aet(u),zd(()=>{O&&P===Sh.Initializing&&N(Sh.Initialized)},[O,P]),w.useEffect(()=>{const{onDragMove:$e}=le.current,{active:He,activatorEvent:ge,collisions:Pe,over:qe}=B.current;if(!He||!ge)return;const Ze={active:He,activatorEvent:ge,collisions:Pe,delta:{x:Se.x,y:Se.y},over:qe};Ou.unstable_batchedUpdates(()=>{$e?.(Ze),_({type:"onDragMove",event:Ze})})},[Se.x,Se.y]),w.useEffect(()=>{const{active:$e,activatorEvent:He,collisions:ge,droppableContainers:Pe,scrollAdjustedTranslate:qe}=B.current;if(!$e||L.current==null||!He||!qe)return;const{onDragOver:Ze}=le.current,ut=Pe.get(ve),vt=ut&&ut.rect.current?{id:ut.id,rect:ut.rect.current,data:ut.data,disabled:ut.disabled}:null,wt={active:$e,activatorEvent:He,collisions:ge,delta:{x:qe.x,y:qe.y},over:vt};Ou.unstable_batchedUpdates(()=>{Re(vt),Ze?.(wt),_({type:"onDragOver",event:wt})})},[ve]),zd(()=>{B.current={activatorEvent:ee,active:X,activeNode:$,collisionRect:ye,collisions:Ae,droppableRects:ce,draggableNodes:F,draggingNode:V,draggingNodeRect:Q,droppableContainers:D,over:je,scrollableAncestors:fe,scrollAdjustedTranslate:Se},z.current={initial:Q,translated:ye}},[X,$,Ae,ye,F,V,Q,ce,D,je,fe,Se]),get({...E,delta:k,draggingRect:ye,pointerCoordinates:U,scrollableAncestors:fe,scrollableAncestorRects:pe});const te=w.useMemo(()=>({active:X,activeNode:$,activeNodeRect:O,activatorEvent:ee,collisions:Ae,containerNodeRect:K,dragOverlay:I,draggableNodes:F,droppableContainers:D,droppableRects:ce,over:je,measureDroppableContainers:xe,scrollableAncestors:fe,scrollableAncestorRects:pe,measuringConfiguration:re,measuringScheduled:Ne,windowRect:se}),[X,$,O,ee,Ae,K,I,F,D,ce,je,xe,fe,pe,re,Ne,se]),Ie=w.useMemo(()=>({activatorEvent:ee,activators:tt,active:X,activeNodeRect:O,ariaDescribedById:{draggable:oe},dispatch:b,draggableNodes:F,over:je,measureDroppableContainers:xe}),[ee,tt,X,O,b,oe,F,je,xe]);return ea.createElement(Zoe.Provider,{value:C},ea.createElement(sA.Provider,{value:Ie},ea.createElement(ple.Provider,{value:te},ea.createElement(fle.Provider,{value:Te},d)),ea.createElement(Uet,{disabled:l?.restoreFocus===!1})),ea.createElement(BJe,{...l,hiddenTextDescribedById:oe}));function be(){const $e=ne?.autoScrollEnabled===!1,He=typeof c=="object"?c.enabled===!1:c===!1,ge=A&&!$e&&!He;return typeof c=="object"?{...c,enabled:ge}:{enabled:ge}}}),$et=w.createContext(null),rY="button",Vet="Draggable";function Get(t){let{id:e,data:n,disabled:r=!1,attributes:i}=t;const s=NS(Vet),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:m,over:p}=w.useContext(sA),{role:f=rY,roleDescription:x="draggable",tabIndex:v=0}=i??{},g=c?.id===e,b=w.useContext(g?fle:$et),[_,C]=bP(),[P,N]=bP(),A=jet(o,e),T=Pw(n);zd(()=>(m.set(e,{id:e,key:s,node:_,activatorNode:P,data:T}),()=>{const k=m.get(e);k&&k.key===s&&m.delete(e)}),[m,e]);const F=w.useMemo(()=>({role:f,tabIndex:v,"aria-disabled":r,"aria-pressed":g&&f===rY?!0:void 0,"aria-roledescription":x,"aria-describedby":u.draggable}),[r,f,v,g,x,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:F,isDragging:g,listeners:r?void 0:A,node:_,over:p,setNodeRef:C,setActivatorNodeRef:N,transform:b}}function Wet(){return w.useContext(ple)}const Ket="Droppable",Xet={timeout:25};function Yet(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=t;const s=NS(Ket),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=w.useContext(sA),u=w.useRef({disabled:n}),m=w.useRef(!1),p=w.useRef(null),f=w.useRef(null),{disabled:x,updateMeasurementsFor:v,timeout:g}={...Xet,...i},b=Pw(v??r),_=w.useCallback(()=>{if(!m.current){m.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(b.current)?b.current:[b.current]),f.current=null},g)},[g]),C=iA({callback:_,disabled:x||!o}),P=w.useCallback((F,k)=>{C&&(k&&(C.unobserve(k),m.current=!1),F&&C.observe(F))},[C]),[N,A]=bP(P),T=Pw(e);return w.useEffect(()=>{!C||!N.current||(C.disconnect(),m.current=!1,C.observe(N.current))},[N,C]),w.useEffect(()=>(l({type:_i.RegisterDroppable,element:{id:r,key:s,disabled:n,node:N,rect:p,data:T}}),()=>l({type:_i.UnregisterDroppable,key:s,id:r})),[r]),w.useEffect(()=>{n!==u.current.disabled&&(l({type:_i.SetDroppableDisabled,id:r,key:s,disabled:n}),u.current.disabled=n)},[r,s,n,l]),{active:o,rect:p,isOver:c?.id===r,node:N,over:c,setNodeRef:A}}function oA(t,e,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function Qet(t,e){return t.reduce((n,r,i)=>{const s=e.get(r);return s&&(n[i]=s),n},Array(t.length))}function fk(t){return t!==null&&t>=0}function Zet(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 Jet(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const n5=t=>{let{rects:e,activeIndex:n,overIndex:r,index:i}=t;const s=oA(e,r,n),o=e[i],l=s[i];return!l||!o?null:{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}},gk={scaleX:1,scaleY:1},ett=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:r;if(!l)return null;if(i===n){const d=s[o];return d?{x:0,y:n<o?d.top+d.height-(l.top+l.height):d.top-l.top,...gk}:null}const c=ttt(s,i,n);return i>n&&i<=o?{x:0,y:-l.height-c,...gk}:i<n&&i>=o?{x:0,y:l.height+c,...gk}:{x:0,y:0,...gk}};function ttt(t,e,n){const r=t[e],i=t[e-1],s=t[e+1];return r?n<e?i?r.top-(i.top+i.height):s?s.top-(r.top+r.height):0:s?s.top-(r.top+r.height):i?r.top-(i.top+i.height):0:0}const ble="Sortable",xle=ea.createContext({activeIndex:-1,containerId:ble,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:n5,disabled:{draggable:!1,droppable:!1}});function yle(t){let{children:e,id:n,items:r,strategy:i=n5,disabled:s=!1}=t;const{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=Wet(),m=NS(ble,n),p=l.rect!==null,f=w.useMemo(()=>r.map(A=>typeof A=="object"&&"id"in A?A.id:A),[r]),x=o!=null,v=o?f.indexOf(o.id):-1,g=d?f.indexOf(d.id):-1,b=w.useRef(f),_=!Zet(f,b.current),C=g!==-1&&v===-1||_,P=Jet(s);zd(()=>{_&&x&&u(f)},[_,f,x,u]),w.useEffect(()=>{b.current=f},[f]);const N=w.useMemo(()=>({activeIndex:v,containerId:m,disabled:P,disableTransforms:C,items:f,overIndex:g,useDragOverlay:p,sortedRects:Qet(f,c),strategy:i}),[v,m,P.draggable,P.droppable,C,f,g,c,p,i]);return ea.createElement(xle.Provider,{value:N},e)}const ntt=t=>{let{id:e,items:n,activeIndex:r,overIndex:i}=t;return oA(n,r,i).indexOf(e)},rtt=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=t;return!d||!r||l!==s&&i===o?!1:n?!0:o!==i&&e===c},att={duration:200,easing:"ease"},vle="transform",itt=ty.Transition.toString({property:vle,duration:0,easing:"linear"}),stt={roleDescription:"sortable"};function ott(t){let{disabled:e,index:n,node:r,rect:i}=t;const[s,o]=w.useState(null),l=w.useRef(n);return zd(()=>{if(!e&&n!==l.current&&r.current){const c=i.current;if(c){const d=Ty(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&o(u)}}n!==l.current&&(l.current=n)},[e,n,r,i]),w.useEffect(()=>{s&&o(null)},[s]),s}function wle(t){let{animateLayoutChanges:e=rtt,attributes:n,disabled:r,data:i,getNewIndex:s=ntt,id:o,strategy:l,resizeObserverConfig:c,transition:d=att}=t;const{items:u,containerId:m,activeIndex:p,disabled:f,disableTransforms:x,sortedRects:v,overIndex:g,useDragOverlay:b,strategy:_}=w.useContext(xle),C=ltt(r,f),P=u.indexOf(o),N=w.useMemo(()=>({sortable:{containerId:m,index:P,items:u},...i}),[m,i,P,u]),A=w.useMemo(()=>u.slice(u.indexOf(o)),[u,o]),{rect:T,node:F,isOver:k,setNodeRef:D}=Yet({id:o,data:N,disabled:C.droppable,resizeObserverConfig:{updateMeasurementsFor:A,...c}}),{active:H,activatorEvent:z,activeNodeRect:X,attributes:L,setNodeRef:ne,listeners:ie,isDragging:ee,over:ue,setActivatorNodeRef:le,transform:oe}=Get({id:o,data:N,attributes:{...stt,...n},disabled:C.draggable}),W=TJe(D,ne),re=!!H,ce=re&&!x&&fk(p)&&fk(g),xe=!b&&ee,Ne=xe&&ce?oe:null,Y=ce?Ne??(l??_)({rects:v,activeNodeRect:X,activeIndex:p,overIndex:g,index:P}):null,E=fk(p)&&fk(g)?s({id:o,items:u,activeIndex:p,overIndex:g}):P,j=H?.id,O=w.useRef({activeId:j,items:u,newIndex:E,containerId:m}),K=u!==O.current.items,B=e({active:H,containerId:m,isDragging:ee,isSorting:re,id:o,index:P,items:u,newIndex:O.current.newIndex,previousItems:O.current.items,previousContainerId:O.current.containerId,transition:d,wasDragging:O.current.activeId!=null}),he=ott({disabled:!B,index:P,node:F,rect:T});return w.useEffect(()=>{re&&O.current.newIndex!==E&&(O.current.newIndex=E),m!==O.current.containerId&&(O.current.containerId=m),u!==O.current.items&&(O.current.items=u)},[re,E,m,u]),w.useEffect(()=>{if(j===O.current.activeId)return;if(j!=null&&O.current.activeId==null){O.current.activeId=j;return}const V=setTimeout(()=>{O.current.activeId=j},50);return()=>clearTimeout(V)},[j]),{active:H,activeIndex:p,attributes:L,data:N,rect:T,index:P,newIndex:E,items:u,isOver:k,isSorting:re,isDragging:ee,listeners:ie,node:F,overIndex:g,over:ue,setNodeRef:W,setActivatorNodeRef:le,setDroppableNodeRef:D,setDraggableNodeRef:ne,transform:he??Y,transition:I()};function I(){if(he||K&&O.current.newIndex===P)return itt;if(!(xe&&!Jz(z)||!d)&&(re||B))return ty.Transition.toString({...d,property:vle})}}function ltt(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 wP(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 ctt=[vr.Down,vr.Right,vr.Up,vr.Left],Sle=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(ctt.includes(t.code)){if(t.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const p=i.get(m.id);if(p)switch(t.code){case vr.Down:r.top<p.top&&c.push(m);break;case vr.Up:r.top>p.top&&c.push(m);break;case vr.Left:r.left>p.left&&c.push(m);break;case vr.Right:r.left<p.left&&c.push(m);break}});const d=qJe({collisionRect:r,droppableRects:i,droppableContainers:c});let u=nle(d,"id");if(u===o?.id&&d.length>1&&(u=d[1].id),u!=null){const m=s.get(n.id),p=s.get(u),f=p?i.get(p.id):null,x=p?.node.current;if(x&&f&&m&&p){const g=nA(x).some((A,T)=>l[T]!==A),b=_le(m,p),_=dtt(m,p),C=g||!b?{x:0,y:0}:{x:_?r.width-f.width:0,y:_?r.height-f.height:0},P={x:f.left,y:f.top};return C.x&&C.y?P:Tw(P,C)}}}};function _le(t,e){return!wP(t)||!wP(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function dtt(t,e){return!wP(t)||!wP(e)||!_le(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}function utt(t){return t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function mtt({activeCount:t,pendingCount:e,totalTime:n,totalWeight:r,historyCount:i,t:s}){const o=[{icon:$i,value:t,label:s("queue.summary.printing"),color:"text-blue-400"},{icon:Qn,value:e,label:s("queue.summary.queued"),color:"text-yellow-400"},{icon:vd,value:ps(n),label:s("queue.summary.totalTime"),color:"text-bambu-green"},{icon:UQ,value:utt(r),label:s("queue.summary.totalWeight"),color:"text-purple-400"},{icon:xr,value:i,label:s("queue.summary.history"),color:"text-bambu-gray"}];return a.jsx("div",{className:"flex items-center gap-3 sm:gap-5 flex-wrap px-4 py-3 bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary mb-6",children:o.map((l,c)=>a.jsxs("div",{className:"flex items-center gap-3",children:[c>0&&a.jsx("span",{className:"hidden sm:block text-bambu-dark-tertiary",children:"|"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(l.icon,{className:`w-4 h-4 ${l.color}`}),a.jsx("span",{className:"text-sm font-semibold text-white",children:l.value}),a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:l.label})]})]},c))})}const aY={completed:{icon:xr,color:"text-emerald-400",border:"border-l-emerald-500"},failed:{icon:Na,color:"text-red-400",border:"border-l-red-500"},skipped:{icon:EP,color:"text-orange-400",border:"border-l-gray-500"},cancelled:{icon:Bt,color:"text-gray-400",border:"border-l-gray-500"}};function htt({item:t,onRequeue:e,onRemove:n,timeFormat:r="system",hasPermission:i,canModify:s,t:o}){const l=aY[t.status]||aY.cancelled,c=l.icon,d=t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,u=t.archive_thumbnail?me.getArchiveThumbnail(t.archive_id):t.library_file_thumbnail?me.getLibraryFileThumbnailUrl(t.library_file_id):null,m=t.completed_at||t.created_at;return a.jsxs("div",{className:`flex items-center gap-2 sm:gap-3 px-3 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary border-l-[3px] ${l.border}`,children:[a.jsx(c,{className:`w-4 h-4 shrink-0 ${l.color}`}),a.jsx("div",{className:"w-8 h-8 shrink-0 bg-bambu-dark rounded overflow-hidden",children:u?a.jsx("img",{src:u,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(aa,{className:"w-4 h-4"})})}),a.jsx("span",{className:"text-sm text-white font-medium truncate min-w-0 flex-1",children:d}),t.printer_name&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[a.jsx(Ar,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate max-w-[100px]",children:t.printer_name})]}),t.print_time_seconds&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[a.jsx(vd,{className:"w-3 h-3"}),ps(t.print_time_seconds)]}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:Gh(m,r,o)}),a.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:e,disabled:!i("queue:create"),title:i("queue:create")?o("queue.actions.requeue"):o("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5",children:a.jsx(cr,{className:"w-3.5 h-3.5"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:n,disabled:!s("queue","delete",t.created_by_id),title:s("queue","delete",t.created_by_id)?o("common.remove"):o("queue.permissions.noRemove"),className:"p-1.5",children:a.jsx(rn,{className:"w-3.5 h-3.5"})})]})]})}function Gv(t){const e=new Date(t);return e.setHours(0,0,0,0),e}function ptt(t){return t.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}function ftt(t){return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function gtt(t,e){if(t<=0)return e("queue.timeline.time.anyMoment");const n=Math.round(t/6e4);if(n<60)return e("queue.timeline.time.minutesLeft",{minutes:n});const r=Math.floor(n/60),i=n%60;return i===0?e("queue.timeline.time.hoursLeft",{hours:r}):e("queue.timeline.time.hoursMinutesLeft",{hours:r,minutes:i})}function btt(t){const e=new Date;return e.setHours(t,0,0,0),e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function xtt({event:t,now:e,onItemClick:n,t:r}){const i=t.item,s=i.archive_name||i.library_file_name||r("common.unknown"),o=i.printer_name||(i.target_model?`${r("queue.filter.any")} ${i.target_model}`:r("queue.timeline.unassigned")),l=t.type==="printing",c=t.estimatedEnd.getTime()-e.getTime(),d=i.archive_thumbnail?me.getArchiveThumbnail(i.archive_id):i.library_file_thumbnail?me.getLibraryFileThumbnailUrl(i.library_file_id):null;return a.jsxs("div",{className:`flex items-center gap-3 px-3 sm:px-4 py-3 bg-bambu-dark-secondary rounded-xl border cursor-pointer transition-all hover:border-bambu-green/40
- ${l?"border-blue-500/30":"border-bambu-dark-tertiary"}`,onClick:()=>n(i),children:[a.jsx("div",{className:`w-1 self-stretch rounded-full shrink-0 ${l?"bg-blue-500":"bg-bambu-green/40"}`}),a.jsx("div",{className:"w-10 h-10 shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:d?a.jsx("img",{src:d,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(aa,{className:"w-5 h-5"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:s}),a.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[a.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",children:[a.jsx(Ar,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:o})]}),i.print_time_seconds&&a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray",children:ps(i.print_time_seconds)})]}),l&&t.progress!=null&&a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:a.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all",style:{width:`${t.progress}%`}})}),a.jsxs("span",{className:"text-xs text-blue-400 shrink-0",children:[Math.round(t.progress),"%"]})]})]}),a.jsxs("div",{className:"text-right shrink-0",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:ftt(t.estimatedEnd)}),a.jsx("p",{className:`text-xs mt-0.5 ${l?"text-blue-400":"text-bambu-gray"}`,children:gtt(c,r)})]})]})}function ytt({queueItems:t,printerStatuses:e,onItemClick:n,t:r}){const[i,s]=w.useState(()=>Gv(new Date)),[o,l]=w.useState(()=>new Date),[c,d]=w.useState("all");w.useEffect(()=>{const F=setInterval(()=>l(new Date),6e4);return()=>clearInterval(F)},[]);const u=o.getTime(),m=Gv(new Date).getTime()===Gv(i).getTime(),p=w.useMemo(()=>{const F=[],k=new Map;for(const D of t)if(D.status==="printing"){const H=D.printer_id!=null?e[D.printer_id]:void 0,z=er(D.started_at)||new Date;let X;if(H?.remaining_time!=null&&H.remaining_time>0)X=new Date(u+H.remaining_time*60*1e3);else if(D.print_time_seconds){const L=H?.progress||0,ne=Math.max(0,1-L/100);X=new Date(u+D.print_time_seconds*ne*1e3)}else X=new Date(u+36e5);F.push({item:D,estimatedStart:z,estimatedEnd:X,progress:H?.progress??void 0,type:"printing"})}else if(D.status==="pending"){const H=D.printer_id;k.has(H)||k.set(H,[]),k.get(H).push(D)}for(const[D,H]of k){H.sort((X,L)=>X.position-L.position);let z=u;for(const X of F)X.item.printer_id===D&&X.type==="printing"&&(z=Math.max(z,X.estimatedEnd.getTime()));for(const X of H){const L=er(X.scheduled_time);if(L){const ue=Date.now()+15552e6;L.getTime()<=ue&&(z=Math.max(z,L.getTime()))}const ne=(X.print_time_seconds||3600)*1e3,ie=new Date(z),ee=new Date(z+ne);F.push({item:X,estimatedStart:ie,estimatedEnd:ee,type:"queued"}),z=ee.getTime()}}return F.sort((D,H)=>D.estimatedEnd.getTime()-H.estimatedEnd.getTime()),F},[t,e,u]),f=Gv(i).getTime(),x=f+1440*60*1e3-1,v=w.useMemo(()=>p.filter(F=>{const k=F.estimatedEnd.getTime();return k<f||k>x?!1:c==="printing"?F.type==="printing":c==="queued"?F.type==="queued":!0}),[p,f,x,c]),g=w.useMemo(()=>{const F=new Map;for(const k of v){const D=k.estimatedEnd.getHours();F.has(D)||F.set(D,[]),F.get(D).push(k)}return Array.from(F.entries()).sort(([k],[D])=>k-D)},[v]),b=p.filter(F=>F.type==="printing"&&F.estimatedEnd.getTime()>=f&&F.estimatedEnd.getTime()<=x).length,_=p.filter(F=>F.type==="queued"&&F.estimatedEnd.getTime()>=f&&F.estimatedEnd.getTime()<=x).length,C=w.useMemo(()=>{let F=0;for(const k of p)F=Math.max(F,k.estimatedEnd.getTime());return F>0?new Date(F):null},[p]),P=()=>s(Gv(new Date)),N=()=>{const F=new Date(i);F.setDate(F.getDate()-1),s(F)},A=()=>{const F=new Date(i);F.setDate(F.getDate()+1),s(F)},T=[{key:"all",label:r("queue.timeline.filterAll"),count:b+_},{key:"printing",label:r("queue.timeline.filterPrinting"),count:b},{key:"queued",label:r("queue.timeline.filterQueued"),count:_}];return a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:N,className:"p-1.5",children:a.jsx(dl,{className:"w-4 h-4"})}),a.jsx("span",{className:"text-sm font-medium text-white min-w-[140px] text-center",children:ptt(i)}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:A,className:"p-1.5",children:a.jsx(Ka,{className:"w-4 h-4"})}),!m&&a.jsx(Fe,{variant:"ghost",size:"sm",onClick:P,className:"text-xs text-bambu-green",children:r("queue.timeline.day.today")})]}),C&&a.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1.5",children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),r("queue.timeline.allDoneBy",{time:C.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]})]}),a.jsx("div",{className:"flex gap-2 mb-5",children:T.map(F=>a.jsxs("button",{onClick:()=>d(F.key),className:`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${c===F.key?"bg-bambu-green text-white":"bg-bambu-dark-secondary border border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[F.label,F.count>0&&a.jsx("span",{className:`ml-1.5 text-xs ${c===F.key?"text-white/70":"text-bambu-gray"}`,children:F.count})]},F.key))}),g.length>0?a.jsx("div",{className:"space-y-6",children:g.map(([F,k])=>a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[a.jsx("span",{className:"text-xs font-medium text-bambu-gray w-14 shrink-0",children:btt(F)}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a.jsx("div",{className:"space-y-2 sm:ml-[68px]",children:k.map(D=>a.jsx(xtt,{event:D,now:o,onItemClick:n,t:r},D.item.id))})]},F))}):a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[a.jsx(aa,{className:"w-12 h-12 mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:r("queue.timeline.noData")})]})]})}function vtt(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function wtt({status:t,waitingReason:e,printerState:n,t:r}){if(t==="pending"&&e)return a.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:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),r("queue.status.waiting")]});if(t==="printing"&&n==="PAUSE")return a.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:[a.jsx(zw,{className:"w-3.5 h-3.5"}),r("queue.status.paused")]});const i={pending:{icon:Qn,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:r("queue.status.pending")},printing:{icon:$i,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:r("queue.status.printing")},completed:{icon:xr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:r("queue.status.completed")},failed:{icon:Na,color:"text-status-error bg-status-error/10 border-status-error/20",label:r("queue.status.failed")},skipped:{icon:EP,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:r("queue.status.skipped")},cancelled:{icon:Bt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:r("queue.status.cancelled")}},{icon:s,color:o,label:l}=i[t];return a.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[a.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function Stt({selectedCount:t,printers:e,onSave:n,onClose:r,isSaving:i,canControlPrinter:s,t:o}){const[l,c]=w.useState("unchanged"),[d,u]=w.useState("unchanged"),[m,p]=w.useState("unchanged"),[f,x]=w.useState("unchanged"),[v,g]=w.useState("unchanged"),[b,_]=w.useState("unchanged"),[C,P]=w.useState("unchanged"),[N,A]=w.useState("unchanged"),[T,F]=w.useState("unchanged"),[k,D]=w.useState("unchanged"),H=()=>{const X={};l!=="unchanged"&&(X.printer_id=l),d!=="unchanged"&&(X.manual_start=d),m!=="unchanged"&&(X.auto_off_after=m),f!=="unchanged"&&(X.require_previous_success=f),v!=="unchanged"&&(X.bed_levelling=v),b!=="unchanged"&&(X.flow_cali=b),C!=="unchanged"&&(X.vibration_cali=C),N!=="unchanged"&&(X.layer_inspect=N),T!=="unchanged"&&(X.timelapse=T),k!=="unchanged"&&(X.use_ams=k),n(X)},z=l!=="unchanged"||d!=="unchanged"||m!=="unchanged"||f!=="unchanged"||v!=="unchanged"||b!=="unchanged"||C!=="unchanged"||N!=="unchanged"||T!=="unchanged"||k!=="unchanged";return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("queue.bulkEdit.title",{count:t})}),a.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:o("queue.bulkEdit.description")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printer")}),a.jsxs("select",{value:l===null?"null":l==="unchanged"?"unchanged":String(l),onChange:X=>{const L=X.target.value;c(L==="unchanged"?"unchanged":L==="null"?null:Number(L))},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:[a.jsx("option",{value:"unchanged",children:o("queue.bulkEdit.noChange")}),a.jsx("option",{value:"null",children:o("queue.filter.unassigned")}),e.map(X=>a.jsx("option",{value:X.id,children:X.name},X.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.queueOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Nu,{label:o("queue.bulkEdit.staged"),value:d,onChange:u,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.autoPowerOff"),value:m,onChange:p,disabled:!s,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.requirePrevious"),value:f,onChange:x,t:o})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printOptions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Nu,{label:o("queue.bulkEdit.bedLevelling"),value:v,onChange:g,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.flowCalibration"),value:b,onChange:_,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.vibrationCalibration"),value:C,onChange:P,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.layerInspection"),value:N,onChange:A,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.timelapse"),value:T,onChange:F,t:o}),a.jsx(Nu,{label:o("queue.bulkEdit.useAms"),value:k,onChange:D,t:o})]})]})]}),a.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Fe,{variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Fe,{onClick:H,disabled:!z||i,children:o(i?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function Nu({label:t,value:e,onChange:n,disabled:r,t:i}){return a.jsxs("div",{className:`flex items-center justify-between py-1 ${r?"opacity-50":""}`,children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[a.jsx("button",{onClick:()=>n("unchanged"),disabled:r,className:`px-2 py-1 text-xs rounded ${e==="unchanged"?"bg-bambu-dark-tertiary text-white":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:"—"}),a.jsx("button",{onClick:()=>n(!1),disabled:r,className:`px-2 py-1 text-xs rounded ${e===!1?"bg-red-500/20 text-red-400":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:i("common.off")}),a.jsx("button",{onClick:()=>n(!0),disabled:r,className:`px-2 py-1 text-xs rounded ${e===!0?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white"} disabled:cursor-not-allowed`,children:i("common.on")})]})]})}function iY({item:t,position:e,onEdit:n,onCancel:r,onRemove:i,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:d=!1,onToggleSelect:u,hasPermission:m,canModify:p,printerState:f,t:x}){const{data:v}=Qe({queryKey:["printerStatus",t.printer_id],queryFn:()=>me.getPrinterStatus(t.printer_id),refetchInterval:3e4,enabled:t.printer_id!=null&&f==="printing"}),g=!!t.library_file_id&&!t.archive_id,{data:b}=Qe({queryKey:["archive-plates",t.archive_id],queryFn:()=>me.getArchivePlates(t.archive_id),enabled:!!t.archive_id&&!g}),{data:_}=Qe({queryKey:["library-file-plates",t.library_file_id],queryFn:()=>me.getLibraryFilePlates(t.library_file_id),enabled:g&&!!t.library_file_id}),C=g?_:b,P=C?.plates??[],N=m("queue:reorder"),{attributes:A,listeners:T,setNodeRef:F,transform:k,transition:D,isDragging:H}=wle({id:t.id,disabled:t.status!=="pending"||!N}),z={transform:ty.Transform.toString(k),transition:D},X=t.status==="printing",L=t.status==="pending",ne=["completed","failed","skipped","cancelled"].includes(t.status),ie=L&&u;return a.jsxs("div",{ref:F,style:z,className:`
- group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
- border-l-[3px] ${X?"border-l-blue-500":L?"border-l-yellow-500":t.status==="completed"?"border-l-emerald-500":t.status==="failed"?"border-l-red-500":"border-l-gray-500"}
- ${H?"opacity-50 scale-[1.02] shadow-xl z-50":""}
- ${X?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""}
- ${d&&ie?"sm:border-bambu-dark-tertiary border-bambu-green/40":""}
- ${!d&&!X?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""}
- ${ie?"sm:cursor-default":""}
- `,onClick:ie?()=>{window.innerWidth<640&&u()}:void 0,children:[ie&&d&&a.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),a.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[L&&u&&a.jsx("button",{onClick:ee=>{ee.stopPropagation(),u()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${d?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:d&&a.jsx(Rr,{className:"w-4 h-4"})}),L?a.jsx("div",{...A,...T,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:a.jsx($h,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?a.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]}):a.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),a.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?a.jsx("img",{src:t.plate_id!=null?me.getArchivePlateThumbnail(t.archive_id,t.plate_id):me.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?me.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):me.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(aa,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.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}`,(C?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(ee=>ee.index===t.plate_id)?.name||x("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(_o,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:a.jsx(na,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(_o,{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:a.jsx(na,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&a.jsx("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30",children:t.batch_name})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[a.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&&!t.printer_id?"text-blue-400":""}`,children:[a.jsx(Ar,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${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&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(vd,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ps(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(UQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),vtt(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(sm,{className:"w-3.5 h-3.5"}),t.created_by_username]}),L&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),t.scheduled_time?(er(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?x?.("queue.time.overdue")??"Overdue":Gh(t.scheduled_time,c,x):x?.("queue.time.asap")??"ASAP"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&a.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:[a.jsx(AQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.staged")]}),t.require_previous_success&&a.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&&a.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:[a.jsx(Ud,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.autoPowerOff")]}),t.gcode_injection&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1",children:[a.jsx(oy,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.gcodeInjection")]})]}),X&&v&&a.jsxs("div",{className:"mt-2 sm:mt-3",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),a.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&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),ps(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:x("printers.estimatedCompletion"),children:["ETA ",jO(v.remaining_time,c,x)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(aa,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[a.jsx(Wa,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),t.error_message]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:ee=>ee.stopPropagation(),children:[a.jsx(wtt,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:x}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[X&&a.jsx(Fe,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("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:a.jsx(ife,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Fe,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("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:a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("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:a.jsx(Bt,{className:"w-4 h-4"})})]}),ne&&a.jsxs(a.Fragment,{children:[a.jsx(Fe,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("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:a.jsx(cr,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(rn,{className:"w-4 h-4"})})]})]})]})]})]})}function _tt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=wr(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(null),[g,b]=w.useState(null),[_,C]=w.useState(null),[P,N]=w.useState([]),[A,T]=w.useState(!1),[F,k]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[D,H]=w.useState(()=>{const Ae=localStorage.getItem("queue.historySortAsc");return Ae!==null?Ae==="true":!1}),[z,X]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,ne]=w.useState(()=>{const Ae=localStorage.getItem("queue.pendingSortAsc");return Ae!==null?Ae==="true":!0}),[ie,ee]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[ue,le]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",F)},[F]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(D))},[D]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",z)},[z]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ie))},[ie]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",ue)},[ue]);const oe=Joe(yP(aA,{activationConstraint:{distance:8}}),yP(rA,{coordinateGetter:Sle})),{data:W}=Qe({queryKey:["settings"],queryFn:me.getSettings}),re=W?.time_format||"system",{data:ce,isLoading:xe}=Qe({queryKey:["queue",o,c],queryFn:()=>me.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:Ne}=Qe({queryKey:["printers"],queryFn:()=>me.getPrinters()}),$=it({mutationFn:Ae=>me.updateSettings({queue_shortest_first:Ae}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Y=it({mutationFn:Ae=>me.cancelQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),E=it({mutationFn:Ae=>me.removeFromQueue(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=it({mutationFn:Ae=>me.stopQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),O=it({mutationFn:Ae=>me.startQueueItem(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),K=it({mutationFn:Ae=>me.reorderQueue(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),B=it({mutationFn:async()=>{const Ae=ce?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];for(const ve of Ae)await me.removeFromQueue(ve.id);return Ae.length},onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Ae}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),he=it({mutationFn:Ae=>me.bulkUpdateQueue(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),N([]),T(!1),n(Ae.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),I=it({mutationFn:async Ae=>{for(const ve of Ae)await me.cancelQueueItem(ve);return Ae.length},onSuccess:Ae=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:Ae}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),V=Ae=>{N(ve=>ve.includes(Ae)?ve.filter(je=>je!==Ae):[...ve,Ae])},Q=w.useMemo(()=>{const Ae=new Set;return Ne?.forEach(ve=>{ve.location&&Ae.add(ve.location)}),ce?.forEach(ve=>{ve.target_location&&Ae.add(ve.target_location)}),Array.from(Ae).sort()},[Ne,ce]),G=w.useCallback(Ae=>u?Ae.target_location?Ae.target_location===u:Ae.printer_id?Ne?.find(je=>je.id===Ae.printer_id)?.location===u:!1:!0,[u,Ne]),J=w.useMemo(()=>{let Ae=ce?.filter(je=>je.status==="pending")||[];u&&(Ae=Ae.filter(G));const ve=je=>{if(!je.scheduled_time)return 0;const Re=er(je.scheduled_time)?.getTime()??0,Ee=Date.now()+4320*60*60*1e3;return Re>Ee?0:Re};return W?.queue_shortest_first?[...Ae].sort((je,Re)=>{const Ee=je.printer_id??-(je.target_model?.charCodeAt(0)??0),Te=Re.printer_id??-(Re.target_model?.charCodeAt(0)??0);if(Ee!==Te)return Ee-Te;const Me=je.been_jumped?1:0,Be=Re.been_jumped?1:0;if(Me!==Be)return Be-Me;const Ke=je.print_time_seconds??1/0,tt=Re.print_time_seconds??1/0;return Ke!==tt?Ke-tt:je.position-Re.position}):[...Ae].sort((je,Re)=>{let Ee;if(z==="name"){const Te=je.archive_name||je.library_file_name||"",Me=Re.archive_name||Re.library_file_name||"";Ee=Te.localeCompare(Me)}else z==="printer"?Ee=(je.printer_name||"").localeCompare(Re.printer_name||""):z==="time"?Ee=ve(je)-ve(Re):Ee=je.position-Re.position;return L?Ee:-Ee})},[ce,z,L,G,u,W?.queue_shortest_first]),se=()=>{const Ae=J.map(ve=>ve.id);P.length===Ae.length?N([]):N(Ae)},fe=w.useMemo(()=>{let Ae=ce?.filter(ve=>ve.status==="printing")||[];return u&&(Ae=Ae.filter(G)),Ae},[ce,u,G]),pe=w.useMemo(()=>{const Ae=new Set;return fe.forEach(ve=>{ve.printer_id&&Ae.add(ve.printer_id)}),Array.from(Ae)},[fe]),de=fp({queries:pe.map(Ae=>({queryKey:["printerStatus",Ae],queryFn:()=>me.getPrinterStatus(Ae),refetchInterval:5e3}))}),U=w.useMemo(()=>{const Ae={};return pe.forEach((ve,je)=>{const Re=de[je];Re?.data?.state&&(Ae[ve]=Re.data.state)}),Ae},[pe,de]),R=w.useMemo(()=>{const Ae={};return pe.forEach((ve,je)=>{const Re=de[je];Re?.data&&(Ae[ve]={progress:Re.data.progress??void 0,remaining_time:Re.data.remaining_time??void 0,state:Re.data.state??void 0})}),Ae},[pe,de]),ae=w.useMemo(()=>{let Ae=ce?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];return u&&(Ae=Ae.filter(G)),[...Ae].sort((ve,je)=>{let Re;if(F==="name"){const Ee=ve.archive_name||ve.library_file_name||"",Te=je.archive_name||je.library_file_name||"";Re=Ee.localeCompare(Te)}else F==="printer"?Re=(ve.printer_name||"").localeCompare(je.printer_name||""):Re=(er(je.completed_at||je.created_at)?.getTime()??0)-(er(ve.completed_at||ve.created_at)?.getTime()??0);return D?-Re:Re})},[ce,F,D,G,u]),_e=w.useMemo(()=>J.reduce((Ae,ve)=>Ae+(ve.print_time_seconds||0),0),[J]),Se=w.useMemo(()=>J.reduce((Ae,ve)=>Ae+(ve.filament_used_grams||0),0),[J]),ye=Ae=>{const{active:ve,over:je}=Ae;if(!je||ve.id===je.id)return;const Re=J.findIndex(Te=>Te.id===ve.id),Ee=J.findIndex(Te=>Te.id===je.id);if(Re!==-1&&Ee!==-1){const Me=oA(J,Re,Ee).map((Be,Ke)=>({id:Be.id,position:Ke+1}));K.mutate(Me)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(lN,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsx(mtt,{activeCount:fe.length,pendingCount:J.length,totalTime:_e,totalWeight:Se,historyCount:ae.length,t}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[a.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:Ae=>{const ve=Ae.target.value;l(ve==="unassigned"?-1:ve===""?null:Number(ve))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),Ne?.map(Ae=>a.jsx("option",{value:Ae.id,children:Ae.name},Ae.id))]}),a.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:Ae=>d(Ae.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Q.length>0&&a.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:u,onChange:Ae=>m(Ae.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Q.map(Ae=>a.jsx("option",{value:Ae,children:Ae},Ae))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),ae.length>0&&a.jsxs(Fe,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(rn,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsxs("div",{className:"hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{className:`p-2 transition-colors ${ue==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("list"),title:t("queue.timeline.listView"),children:a.jsx(Ow,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${ue==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx($pe,{className:"w-4 h-4"})})]}),a.jsxs("button",{onClick:()=>{const Ae=!(W?.queue_shortest_first??!1);$.mutate(Ae)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${W?.queue_shortest_first?"bg-bambu-green/20 border-bambu-green text-bambu-green":"bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,title:t("queue.sjf.tooltip","Shortest Job First — scheduler prioritizes shorter prints"),children:[a.jsx(hxe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]})]}),xe?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):ce?.length===0?a.jsxs(At,{className:"p-12 text-center border-dashed",children:[a.jsx(Yr,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):ue==="timeline"?a.jsx(ytt,{queueItems:ce||[],printerStatuses:R,onItemClick:Ae=>{["completed","failed","skipped","cancelled"].includes(Ae.status)?b(Ae):Ae.status==="pending"?v(Ae):Ae.status==="printing"&&C({type:"stop",item:Ae})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[fe.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-2 sm:space-y-3",children:fe.map(Ae=>a.jsx(iY,{item:Ae,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>C({type:"stop",item:Ae}),onRequeue:()=>{},onStart:()=>{},timeFormat:re,hasPermission:r,canModify:s,printerState:Ae.printer_id?U[Ae.printer_id]:null,t},Ae.id))})]}),J.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Qn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:J.length}),")"]}),a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.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:z,onChange:Ae=>X(Ae.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>ne(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(Wf,{className:"w-4 h-4"}):a.jsx(Cx,{className:"w-4 h-4"})})]})]}),a.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:[a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:se,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===J.length&&J.length>0?a.jsx(xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(to,{className:"w-4 h-4"}),P.length===J.length&&J.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:P.length})}),a.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:()=>T(!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:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[a.jsx(ai,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:()=>I.mutate(P),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:I.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[a.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),a.jsx(gle,{sensors:oe,collisionDetection:rle,onDragEnd:ye,children:a.jsx(yle,{items:J.map(Ae=>Ae.id),strategy:ett,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:J.map((Ae,ve)=>a.jsx(iY,{item:Ae,position:ve+1,onEdit:()=>v(Ae),onCancel:()=>C({type:"cancel",item:Ae}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>O.mutate(Ae.id),timeFormat:re,isSelected:P.includes(Ae.id),onToggleSelect:()=>V(Ae.id),hasPermission:r,canModify:s,t},Ae.id))})})})]}),ae.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("button",{onClick:()=>ee(!ie),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ie?a.jsx(Ka,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(Un,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ae.length}),")"]})]}),!ie&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.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:F,onChange:Ae=>k(Ae.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>H(!D),title:t(D?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:D?a.jsx(Wf,{className:"w-4 h-4"}):a.jsx(Cx,{className:"w-4 h-4"})})]})]}),!ie&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:ae.slice(0,50).map(Ae=>a.jsx(htt,{item:Ae,onRemove:()=>C({type:"remove",item:Ae}),onRequeue:()=>b(Ae),timeFormat:re,hasPermission:r,canModify:s,t},Ae.id))})]})]}),x&&a.jsx(ec,{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&&a.jsx(ec,{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:()=>b(null)}),_&&a.jsx(_n,{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"?Y.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):E.mutate(_.item.id),C(null)},onCancel:()=>C(null)}),p&&a.jsx(_n,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:ae.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{B.mutate(),f(!1)},onCancel:()=>f(!1)}),A&&a.jsx(Stt,{selectedCount:P.length,printers:Ne?.map(Ae=>({id:Ae.id,name:Ae.name}))||[],onSave:Ae=>{Object.keys(Ae).length>0&&he.mutate({item_ids:P,...Ae})},onClose:()=>T(!1),isSaving:he.isPending,canControlPrinter:r("printers:control"),t})]})}function ktt({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const C=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return C.observe(_),()=>C.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach(H=>{const z=H.split("T")[0];_[z]=(_[z]||0)+1});const C=new Date,P=new Date(C);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],A=[];let T=[],F=-1;const k=new Date(P);let D=0;for(;k<=C;)k.getDay()===0&&T.length>0&&(N.push(T),T=[],D++),k.getMonth()!==F&&(A.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:D}),F=k.getMonth()),T.push(new Date(k)),k.setDate(k.getDate()+1);return T.length>0&&N.push(T),{weeks:N,monthLabels:A,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const C=_/c;return C<=.25?"bg-bambu-green/30":C<=.5?"bg-bambu-green/50":C<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,x=r-p-16,v=m>0?Math.floor((x-(m-1)*f)/m):12,g=Math.max(8,Math.min(20,v)),b=g<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:_,weekIndex:C},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:b,marginLeft:P===0?0:`${(C-(o[P-1]?.weekIndex||0))*(g+f)-24}px`},children:_},P))}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((_,C)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:g,fontSize:b,visibility:C%2===1?"visible":"hidden"},children:_},_))}),s.map((_,C)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(k=>k.getDay()===P);if(!N)return a.jsx("div",{style:{width:g,height:g}},P);const A=N.toISOString().split("T")[0],T=l[A]||0,F=A===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(T)} ${F?"ring-1 ring-white":""}`,style:{width:g,height:g},title:`${N.toLocaleDateString()}: ${T} print${T!==1?"s":""}`},P)})},C))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:b},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:g,height:g}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:g,height:g}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:g,height:g}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:g,height:g}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:g,height:g}})]}),a.jsx("span",{children:"More"})]})]})})}const sY=["weight","prints","time"];function SP({value:t,onChange:e,exclude:n}){const{t:r}=Rt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?sY.filter(o=>!n.includes(o)):sY;return a.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>a.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function Ah(t){if(t>=1e6){const e=t/1e6;return`${e%1===0?e.toFixed(0):e.toFixed(1)}t`}if(t>=1e3){const e=t/1e3;return`${e%1===0?e.toFixed(0):e.toFixed(1)}kg`}return`${Math.round(t)}g`}const bk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Ntt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],oY=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"];function Ctt({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Rt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const D=er(k.completed_at||k.created_at)||new Date,H=`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,z=F.get(H)||{date:H,filament:0,cost:0,prints:0};z.filament+=k.filament_used_grams||0,z.cost+=k.cost||0,z.prints+=k.quantity||1,F.set(H,z)}),Array.from(F.values()).sort((k,D)=>k.date.localeCompare(D.date)).map(k=>({...k,dateLabel:new Date(k.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=w.useMemo(()=>{if(n&&r)return Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1;if(n)return Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1;if(t.length<2)return 0;const F=t.map(k=>new Date(k.completed_at||k.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const F=new Map,k=u>1;return t.forEach(D=>{const H=er(D.completed_at||D.created_at)||new Date,z=H.getHours(),X=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}T${String(z).padStart(2,"0")}`,L=F.get(X)||{date:X,filament:0,cost:0,prints:0};L.filament+=D.filament_used_grams||0,L.cost+=D.cost||0,L.prints+=D.quantity||1,F.set(X,L)}),Array.from(F.values()).sort((D,H)=>D.date.localeCompare(H.date)).map(D=>{const[H,z]=D.date.split("T"),X=new Date(H),L=parseInt(z,10),ne=k?`${Ntt[X.getDay()]} ${oY[L]}`:oY[L];return{...D,dateLabel:ne}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(k=>{const D=new Date(k.date),H=new Date(D);H.setDate(D.getDate()-D.getDay());const z=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}`,X=F.get(z)||{week:z,filament:0,cost:0,prints:0};X.filament+=k.filament,X.cost+=k.cost,X.prints+=k.prints,F.set(z,X)}),Array.from(F.values()).sort((k,D)=>k.week.localeCompare(D.week)).map(k=>({date:k.week,dateLabel:`Week of ${new Date(k.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...k}))},[d]),f=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", ");H.forEach(z=>{const X=(k.filament_used_grams||0)/H.length;F.set(z,(F.get(z)||0)+X)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D)})).sort((k,D)=>D.value-k.value)},[t]),x=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{(k.filament_type||"Unknown").split(", ").forEach(z=>{F.set(z,(F.get(z)||0)+1)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:D})).sort((k,D)=>D.value-k.value)},[t]),v=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", "),z=(k.actual_time_seconds||k.print_time_seconds||0)/H.length;H.forEach(X=>{F.set(X,(F.get(X)||0)+z)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D/3600*10)/10})).sort((k,D)=>D.value-k.value)},[t]),g=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(k.status!=="completed"&&k.status!=="failed")return;(k.filament_type||"Unknown").split(", ").forEach(H=>{const z=F.get(H)||{completed:0,failed:0};k.status==="completed"?z.completed++:z.failed++,F.set(H,z)})}),Array.from(F.entries()).filter(([,k])=>k.completed+k.failed>=2).map(([k,D])=>{const H=D.completed+D.failed,z=Math.round(D.completed/H*100);return{name:k,rate:z,total:H}}).sort((k,D)=>D.rate-k.rate)},[t]),b=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(!k.filament_color)return;const D=k.filament_color.split(",").map(z=>z.trim()),H=(k.filament_used_grams||0)/D.length;D.forEach(z=>{const X=F.get(z)||{count:0,weight:0};X.count++,X.weight+=H,F.set(z,X)})}),Array.from(F.entries()).map(([k,D])=>({hex:k,value:l==="prints"?D.count:Math.round(D.weight)})).sort((k,D)=>D.value-k.value)},[t,l]),_=s==="weight"?f:s==="prints"?x:v,C=u<=7&&m.length>0?m:p,P=t.reduce((F,k)=>F+(k.filament_used_grams||0),0),N=t.reduce((F,k)=>F+(k.cost||0),0),A=t.reduce((F,k)=>F+(k.quantity||1),0),T=new Set(t.map(F=>F.printer_id).filter(Boolean)).size;return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),a.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:Ah(P)})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("nav.printers").toLowerCase()]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,N.toFixed(2)]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[A," ",i("common.prints")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[A>0?(P/A).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,A>0?(N/A).toFixed(2):"0.00"," avg"]})]})]}),C.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),a.jsx(Fh,{width:"100%",height:250,children:a.jsxs(YVe,{data:C,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(kf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Nf,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(Cf,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),a.jsx(Rh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),a.jsx(gae,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),a.jsx(SP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Fh,{width:160,height:160,children:a.jsxs(zW,{children:[a.jsx(QR,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((F,k)=>a.jsx(Gx,{fill:bk[k%bk.length]},`cell-${k}`))}),a.jsx(Rh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?Ah(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((F,k)=>{const D=_.reduce((z,X)=>z+X.value,0),H=D>0?(F.value/D*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:bk[k%bk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:F.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?Ah(F.value):s==="time"?`${F.value}h`:F.value," · ",H,"%"]})]},F.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),g.length>0?a.jsx("div",{className:"space-y-1.5",children:g.map(F=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:F.name}),a.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:a.jsx("div",{className:`h-full rounded-full transition-all ${F.rate>=90?"bg-status-ok":F.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${F.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${F.rate>=90?"text-status-ok":F.rate>=70?"text-status-warning":"text-status-error"}`,children:[F.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.name))}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),a.jsx(SP,{value:l,onChange:c,exclude:["time"]})]}),b.length>0?(()=>{const F=b.reduce((k,D)=>k+D.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(Fh,{width:"100%",height:"100%",children:a.jsxs(zW,{children:[a.jsx(QR,{data:b,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:b.map((k,D)=>a.jsx(Gx,{fill:k.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${D}`))}),a.jsx(Rh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:k=>[l==="weight"?Ah(Number(k??0)):`${k??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?Ah(F):F}),a.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[b.length," ",b.length===1?"color":"colors"]})]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:b.slice(0,8).map(k=>{const D=F>0?(k.value/F*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[a.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:k.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[D,"%"]})]},k.hex)})}),b.length>8&&a.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",b.length-8," more"]})]})})():a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function Ptt({id:t,title:e,component:n,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=wle({id:t}),x={transform:ty.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...x,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx($h,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(vO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(MP,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(vg,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function Ttt({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(k=>{F[k.id]=k.defaultSize||4}),F},[c,d]=w.useState(()=>{const F=localStorage.getItem(e);if(F)try{const k=JSON.parse(F);if(!k.sizes)k.sizes=l();else{const D=l();for(const H in D)H in k.sizes||(k.sizes[H]=D[H])}return k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const F=window.matchMedia(`(max-width: ${r}px)`),k=H=>{f(H.matches)};k(F);const D=H=>k(H);return F.addEventListener?F.addEventListener("change",D):F.addListener(D),()=>{F.removeEventListener?F.removeEventListener("change",D):F.removeListener(D)}},[r]);const x=r&&p?1:n;w.useEffect(()=>{const F=()=>m(k=>!k);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const k=t.map(D=>D.id).filter(D=>!c.order.includes(D));k.length>0&&d(D=>({...D,order:[...D.order,...k]}))},[t,c.order]);const v=Joe(yP(aA,{activationConstraint:{distance:8}}),yP(rA,{coordinateGetter:Sle})),g=F=>{const{active:k,over:D}=F;D&&k.id!==D.id&&d(H=>{const z=H.order.indexOf(k.id),X=H.order.indexOf(D.id);return{...H,order:oA(H.order,z,X)}})},b=F=>{d(k=>({...k,hidden:k.hidden.includes(F)?k.hidden.filter(D=>D!==F):[...k.hidden,F]}))},_=F=>{d(k=>{const D=k.sizes[F]||4,H=D===1?2:D===2?4:1;return{...k,sizes:{...k.sizes,[F]:H}}})},C=()=>{const F={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()};d(F),s?.()},P=c.order.map(F=>t.find(k=>k.id===F)).filter(Boolean),N=P.filter(F=>!c.hidden.includes(F.id)),A=P.filter(F=>c.hidden.includes(F.id)),T=o?.({hiddenCount:A.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:C});return a.jsxs("div",{className:"space-y-4",children:[T,!i&&!o&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:C,children:[a.jsx(eo,{className:"w-4 h-4"}),"Reset Layout"]}),A.length>0&&a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(ul,{className:"w-4 h-4"}),A.length," Hidden"]})]}),u&&A.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(F=>a.jsxs("button",{onClick:()=>b(F.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:[a.jsx(ul,{className:"w-3 h-3"}),F.title]},F.id))})]}),a.jsx(gle,{sensors:v,collisionDetection:rle,onDragEnd:g,children:a.jsx(yle,{items:N.map(F=>F.id),strategy:n5,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${x}, minmax(0, 1fr))`},children:N.map(F=>{const k=c.sizes[F.id]||2,D=Math.min(k,x);return a.jsx(Ptt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:k,columnSpan:D,onToggleVisibility:()=>b(F.id),onToggleSize:()=>_(F.id)},F.id)})})})}),N.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Fe,{className:"mt-4",onClick:C,children:"Reset Layout"})]})]})}function Att(t){const e=new Date,n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(n,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(n,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(n,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(n,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(n,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(n,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const jtt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],Mtt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],KL=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],d3=[{key:"<30m",max:1800},{key:"30m-1h",max:3600},{key:"1-2h",max:7200},{key:"2-4h",max:14400},{key:"4-8h",max:28800},{key:"8-12h",max:43200},{key:"12-24h",max:86400},{key:"24h+",max:1/0}],xk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function Ett({stats:t,currency:e}){const{t:n}=Rt(),r=t?.energy_data_warming_up===!0,i=r?n("stats.energyWarmingUpTooltip"):void 0,s=[{icon:ja,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Qn,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:ja,color:"text-orange-400",label:n("stats.filamentUsed"),value:Ah(t?.total_filament_grams||0)},{icon:aN,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:ic,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:r,tooltip:i},{icon:aN,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:r,tooltip:i}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>a.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:a.jsx(o.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&a.jsx(Rn,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),a.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function Dtt({stats:t,printerMap:e,size:n=1}){const{t:r}=Rt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round(t.successful_prints/i*100):0,o=n===1?112:n===2?128:144,l=o/2-8,c=l*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Na,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.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&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.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(([d,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function Ftt({stats:t,printerMap:e,size:n=1}){const{t:r}=Rt(),i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),d=i-100,u=n===1?112:n===2?128:144,m=u/2-8,p=m*2*Math.PI,f=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(OQ,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&a.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])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.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 Rtt({printDates:t,dateFrom:e,dateTo:n}){const{days:r,hourlyCounts:i,maxCount:s}=w.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(n+"T00:00:00"),p=[],f=b=>`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,x=new Date(u);for(;x<=m;)p.push({key:f(x),label:x.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),x.setDate(x.getDate()+1);const v={};let g=0;return t.forEach(b=>{const _=er(b);if(!_)return;const P=`${`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}-${_.getHours()}`;v[P]=(v[P]||0)+1,v[P]>g&&(g=v[P])}),{days:p,hourlyCounts:v,maxCount:Math.max(1,g)}},[t,e,n]),o=u=>{if(u===0)return"bg-bambu-dark";const m=u/s;return m<=.25?"bg-bambu-green/30":m<=.5?"bg-bambu-green/50":m<=.75?"bg-bambu-green/75":"bg-bambu-green"},l=20,c=2,d=80;return a.jsxs("div",{className:"w-full overflow-x-auto",children:[a.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[a.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:KL.map((u,m)=>a.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>a.jsxs("div",{className:"flex items-center",style:{gap:c},children:[a.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return a.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${KL[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:c},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),a.jsx("span",{children:"More"})]})]})}function Ltt({printDates:t,size:e=2,dateFrom:n,dateTo:r}){const i=w.useMemo(()=>n&&r?Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1:n?Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1:1/0,[n,r]);if(i<=7&&n&&r)return a.jsx(Rtt,{printDates:t,dateFrom:n,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return a.jsx(ktt,{printDates:t,months:o})}function Ott({stats:t,archives:e,printerMap:n}){const{t:r}=Rt(),[i,s]=w.useState("weight"),[o,l]=w.useState("weight"),c=w.useMemo(()=>{const b=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([_,C])=>{const P=b.get(_)||{prints:0,weight:0,time:0};P.prints=C,b.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const C=String(_.printer_id),P=b.get(C)||{prints:0,weight:0,time:0};P.weight+=_.filament_used_grams||0,P.time+=_.actual_time_seconds||_.print_time_seconds||0,t?.prints_by_printer||P.prints++,b.set(C,P)}),Array.from(b.entries()).map(([_,C])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?C.prints:i==="weight"?Math.round(C.weight):Math.round(C.time/3600*10)/10})).sort((_,C)=>C.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const b=Array.from({length:24},(_,C)=>({hour:C,label:KL[C],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const C=er(_.started_at);if(!C)return;const P=C.getHours();b[P].total++,_.status==="failed"&&b[P].failures++}),b},[e]),u=w.useMemo(()=>{const b=d3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const C=_.actual_time_seconds||_.print_time_seconds;if(!(!C||C<=0)){for(let P=0;P<d3.length;P++)if(C<=d3[P].max){b[P].count++;break}}}),b},[e]),m=w.useMemo(()=>{const b=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=er(P.created_at)||new Date(P.created_at);let A=N.getDay()-1;A<0&&(A=6),o==="prints"?b[A]++:o==="weight"?b[A]+=P.filament_used_grams||0:b[A]+=(P.actual_time_seconds||P.print_time_seconds||0)/3600;const T=new Date(N);T.setDate(N.getDate()-(N.getDay()+6)%7),_.add(`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`)});const C=Math.max(_.size,1);return Mtt.map((P,N)=>({name:P,avg:Math.round(b[N]/C*10)/10}))},[e,o]),p=b=>({unit:b==="weight"?"g":b==="time"?"h":"",color:b==="weight"?"#00ae42":b==="time"?"#3b82f6":"#f59e0b"}),f=p(i),x=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),v=p(o),g=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),a.jsx(SP,{value:i,onChange:s})]}),c.length>0?a.jsx(Fh,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(Z1,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(kf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Nf,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(Cf,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(Rh,{contentStyle:xk,formatter:b=>[i==="weight"?Ah(Number(b??0)):`${b??0}${f.unit}`,x]}),a.jsx(Zb,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?a.jsx(Fh,{width:"100%",height:160,children:a.jsxs(Z1,{data:u,children:[a.jsx(kf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Nf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(Cf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Rh,{contentStyle:xk}),a.jsx(Zb,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),a.jsx(SP,{value:o,onChange:l})]}),e.length>0?a.jsx(Fh,{width:"100%",height:160,children:a.jsxs(Z1,{data:m,children:[a.jsx(kf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Nf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(Cf,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(Rh,{contentStyle:xk,formatter:b=>[`${b??0}${v.unit}`,g]}),a.jsx(Zb,{dataKey:"avg",fill:v.color,radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?a.jsx(Fh,{width:"100%",height:160,children:a.jsxs(Z1,{data:d,children:[a.jsx(kf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Nf,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(Cf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Rh,{contentStyle:xk}),a.jsx(Zb,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(Zb,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function Itt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Rt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ctt,{archives:t,currency:e,dateFrom:n,dateTo:r})}function ztt({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Rt(),s=!!(e||n),{data:o,isLoading:l}=Qe({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>me.getFailureAnalysis({...s?{dateFrom:e,dateTo:n}:{days:30},createdById:r})});if(l)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Rn,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(_O,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate<o.trend[o.trend.length-2].failure_rate?"text-status-ok":"text-status-error"}`}),a.jsx("span",{className:"text-bambu-gray",children:i("stats.lastWeekRate",{rate:o.trend[o.trend.length-1].failure_rate.toFixed(1)})})]})})]}),u.length>0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function Utt({archives:t,currency:e}){const{t:n}=Rt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=x=>{let v=null,g=0;return t.forEach(b=>{const _=x(b);_&&_>g&&(g=_,v=b)}),{archive:v,value:g}},o=s(x=>x.actual_time_seconds);o.archive&&i.push({icon:Qn,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ps(o.value),detail:o.archive.print_name||null});const l=s(x=>x.filament_used_grams);l.archive&&i.push({icon:ja,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:Ah(l.value),detail:l.archive.print_name||null});const c=s(x=>x.cost);c.archive&&i.push({icon:aN,iconColor:"text-green-400",label:n("stats.mostExpensivePrint"),value:`${e}${c.value.toFixed(2)}`,detail:c.archive.print_name||null});const d=new Map;t.forEach(x=>{const v=er(x.created_at)||new Date(x.created_at),g=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`;d.set(g,(d.get(g)||0)+1)});let u="",m=0;d.forEach((x,v)=>{x>m&&(m=x,u=v)}),m>1&&i.push({icon:Yr,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[x,v,g]=u.split("-").map(Number);return new Date(x,v-1,g).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(x=>x.status==="completed"||x.status==="failed").sort((x,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(x.completed_at||x.created_at).getTime());let f=0;for(const x of p)if(x.status==="completed")f++;else break;return f>0&&i.push({icon:ic,iconColor:"text-yellow-400",label:n("stats.successStreak"),value:`${f}`,detail:f===1?n("stats.streakPrint"):n("stats.streakPrints",{count:f})}),i},[t,e,n]);return r.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noArchiveData")}):a.jsx("div",{className:"space-y-3",children:r.map((i,s)=>a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:a.jsx(i.icon,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function Btt(){const{t}=Rt(),{showToast:e}=bn(),{hasPermission:n,authEnabled:r}=wr(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(0),[u,m]=w.useState(0),[p,f]=w.useState(!1),[x,v]=w.useState(null),[g,b]=w.useState(!1),_=r&&n("stats:filter_by_user"),[C,P]=w.useState(()=>{try{const Y=localStorage.getItem("bambusy-stats-timeframe");if(Y){const E=JSON.parse(Y);if(E.preset)return E}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,A]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(C))},[C]);const T=w.useMemo(()=>C.preset==="custom"?{dateFrom:C.dateFrom,dateTo:C.dateTo}:Att(C.preset),[C]);w.useEffect(()=>{const Y=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const O=JSON.parse(j);m(O.hidden?.length||0)}}catch{m(0)}};Y(),window.addEventListener("storage",Y);const E=setInterval(Y,2e3);return()=>{window.removeEventListener("storage",Y),clearInterval(E)}},[c]);const F=x!==null?x:void 0,{data:k,isLoading:D,isFetching:H,refetch:z}=Qe({queryKey:["archiveStats",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>me.getArchiveStats({dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F})}),{data:X}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:L,isFetching:ne,refetch:ie}=Qe({queryKey:["archivesSlim",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>me.getArchivesSlim(T.dateFrom,T.dateTo,F)}),{data:ee}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:ue}=Qe({queryKey:["users"],queryFn:me.getUsers,enabled:_}),le=w.useMemo(()=>x===null?t("stats.allUsers","All Users"):x===-1?t("stats.noUser","No User (System)"):ue?.find(Y=>Y.id===x)?.username??"?",[x,ue,t]),oe=async Y=>{l(!1),s(!0);try{const{blob:E,filename:j}=await me.exportStats({format:Y,days:90,createdById:F}),O=URL.createObjectURL(E),K=document.createElement("a");K.href=O,K.download=j,K.click(),URL.revokeObjectURL(O),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},W=async()=>{f(!0);try{const Y=await me.recalculateCosts();await Promise.all([z(),ie()]),e(t("stats.recalculatedCosts",{count:Y.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},re=(H||ne)&&!D,ce=So(ee?.currency||"USD"),xe=new Map(X?.map(Y=>[String(Y.id),Y.name])||[]),Ne=w.useMemo(()=>L?.map(Y=>Y.created_at)||[],[L]);if(D)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const $=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(Ett,{stats:k,currency:ce}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Y=>a.jsx(Dtt,{stats:k,printerMap:xe,size:Y}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Y=>a.jsx(Ftt,{stats:k,printerMap:xe,size:Y}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Y=>a.jsx(ztt,{size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Y=>a.jsx(Ltt,{printDates:Ne,size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(Utt,{archives:L||[],currency:ce}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(Ott,{stats:k,archives:L||[],printerMap:xe}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(Itt,{archives:L||[],currency:ce,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),re&&a.jsx(dt,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Fe,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(ul,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Y=>Y+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(eo,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Fe,{variant:"secondary",onClick:W,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Fpe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(sN,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&a.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:[a.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:()=>oe("csv"),children:[a.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.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:()=>oe("xlsx"),children:[a.jsx(sN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&ue&&ue.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>b(!g),children:[a.jsx(Fu,{className:"w-4 h-4"}),le,a.jsx(Un,{className:"w-3 h-3"})]}),g&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>b(!1)}),a.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 p-2 max-h-64 overflow-y-auto",children:[a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${x===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(null),b(!1)},children:t("stats.allUsers","All Users")}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${x===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(-1),b(!1)},children:t("stats.noUser","No User (System)")}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),ue.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${x===Y.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Y.id),b(!1)},children:Y.username},Y.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>A(!N),children:[a.jsx(Yr,{className:"w-4 h-4"}),t(`stats.timeframe.${C.preset}`),a.jsx(Un,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>A(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[jtt.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${C.preset===Y?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Y,dateFrom:void 0,dateTo:void 0}),A(!1)},children:t(`stats.timeframe.${Y}`)},Y)),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${C.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Y=>({...Y,preset:"custom"})),children:t("stats.timeframe.custom")}),C.preset==="custom"&&a.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),a.jsx("input",{type:"date",value:C.dateFrom||"",max:C.dateTo||new Date().toISOString().split("T")[0],onChange:Y=>P(E=>({...E,dateFrom:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),a.jsx("input",{type:"date",value:C.dateTo||"",min:C.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Y=>P(E=>({...E,dateTo:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsx(Fe,{variant:"primary",onClick:()=>A(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Ttt,{widgets:$,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function kle({summary:t,children:e,defaultOpen:n=!1,className:r="",summaryClassName:i=""}){const[s,o]=w.useState(n);return a.jsxs("div",{className:r,children:[a.jsxs("button",{type:"button",onClick:()=>o(l=>!l),className:`w-full flex items-center justify-between gap-2 text-left ${i}`,"aria-expanded":s,children:[a.jsx("div",{className:"flex-1 min-w-0",children:t}),a.jsx(Un,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsx("div",{className:"mt-3",children:e})]})}function Htt({plug:t,onEdit:e}){const{t:n}=Rt(),r=sn(),{showToast:i}=bn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:x}=Qe({queryKey:["smart-plug-status",t.id],queryFn:()=>me.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),g=v?.find(D=>D.id===t.printer_id),b=it({mutationFn:D=>me.controlSmartPlug(t.id,D),onMutate:async D=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const H=r.getQueryData(["smart-plug-status",t.id]),z=D==="on"?"ON":D==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],X=>({...X,state:z})),{previousStatus:H}},onError:(D,H,z)=>{z?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],z.previousStatus),i(n("smartPlugs.failedToTurn",{action:H,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=it({mutationFn:D=>me.updateSmartPlug(t.id,D),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),C=it({mutationFn:()=>me.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),P=f?.state==="ON",N=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,A=(f?.reachable??!1)||N,T=b.isPending,k=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const D=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${D}/`:`http://${D}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(At,{className:"relative",children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?A?"bg-teal-500/20":"bg-red-500/20":A?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(SO,{className:`w-5 h-5 ${A?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Rw,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(rl,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(Ql,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.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.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[x?a.jsx(dt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.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"}),A&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?f?.state||"?":n("smartPlugs.offline")})]}):t.plug_type==="rest"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),a.jsx("span",{className:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?f?.state||"?":n("smartPlugs.offline")})]}):A?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(Vh,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:P?"text-status-ok":"text-bambu-gray",children:f?.state||n("smartPlugs.unknown")})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Md,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),k&&a.jsxs("a",{href:k,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:[a.jsx(na,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),g&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("smartPlugs.linkedTo")," "]}),a.jsx("span",{className:"text-sm text-white",children:g.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.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:[a.jsx(ul,{className:"w-3 h-3"}),n("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&a.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:[a.jsx(Uh,{className:"w-3 h-3"}),n("smartPlugs.alerts")]}),t.schedule_enabled&&a.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:[a.jsx(Yr,{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?n("smartPlugs.scheduleOn",{time:t.schedule_on_time}):n("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Fe,{size:"sm",variant:P?"primary":"secondary",disabled:!A||T,onClick:()=>c(!0),className:"flex-1",children:[T?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Ud,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(Fe,{size:"sm",variant:P?"secondary":"primary",disabled:!A||T,onClick:()=>u(!0),className:"flex-1",children:[T?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Uw,{className:"w-4 h-4"}),n("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.kwhToday")})]})]}),a.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(jd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?n("smartPlugs.settings"):n("smartPlugs.automationSettings")]}),a.jsx("span",{children:m?"-":"+"})]}),m&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Lw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:D=>_.mutate({show_in_switchbar:D.target.checked}),className:"sr-only peer"}),a.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"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.enableAutomation")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:D=>_.mutate({enabled:D.target.checked}),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOn")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOnDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:D=>_.mutate({auto_on:D.target.checked}),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOff")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:D=>_.mutate({auto_off:D.target.checked}),className:"sr-only peer"}),a.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&&a.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffPersistent")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffPersistentDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:D=>_.mutate({auto_off_persistent:D.target.checked}),className:"sr-only peer"}),a.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&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:n("smartPlugs.turnOffDelayMode")}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(Qn,{className:"w-4 h-4"}),n("smartPlugs.time")]}),a.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:[a.jsx(qw,{className:"w-4 h-4"}),n("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayMinutes")}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:D=>_.mutate({off_delay_minutes:parseInt(D.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"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.tempThreshold")}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:D=>_.mutate({off_temp_threshold:parseInt(D.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.tempThresholdDescription")})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Iu,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(_n,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{C.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(_n,{title:n("smartPlugs.turnOnSmartPlug"),message:n("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{b.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&a.jsx(_n,{title:n("smartPlugs.turnOffSmartPlug"),message:n("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{b.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function qtt({plug:t,onClose:e}){const{t:n}=Rt(),r=sn(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[d,u]=w.useState(t?.ip_address||""),[m,p]=w.useState(t?.username||""),[f,x]=w.useState(t?.password||""),[v,g]=w.useState(t?.ha_entity_id||""),[b,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[C,P]=w.useState(t?.mqtt_power_path||""),[N,A]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[T,F]=w.useState(t?.mqtt_energy_topic||""),[k,D]=w.useState(t?.mqtt_energy_path||""),[H,z]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[X,L]=w.useState(t?.mqtt_state_topic||""),[ne,ie]=w.useState(t?.mqtt_state_path||""),[ee,ue]=w.useState(t?.mqtt_state_on_value||""),[le,oe]=w.useState(t?.rest_on_url||""),[W,re]=w.useState(t?.rest_on_body||""),[ce,xe]=w.useState(t?.rest_off_url||""),[Ne,$]=w.useState(t?.rest_off_body||""),[Y,E]=w.useState(t?.rest_method||"POST"),[j,O]=w.useState(t?.rest_headers||""),[K,B]=w.useState(t?.rest_status_url||""),[he,I]=w.useState(t?.rest_status_path||""),[V,Q]=w.useState(t?.rest_status_on_value||""),[G,J]=w.useState(t?.rest_power_url||""),[se,fe]=w.useState(t?.rest_power_path||""),[pe,de]=w.useState((t?.rest_power_multiplier??1).toString()),[U,R]=w.useState(t?.rest_energy_url||""),[ae,_e]=w.useState(t?.rest_energy_path||""),[Se,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[Ae,ve]=w.useState(t?.ha_power_entity||""),[je,Re]=w.useState(t?.ha_energy_today_entity||""),[Ee,Te]=w.useState(t?.ha_energy_total_entity||""),[Me,Be]=w.useState(""),[Ke,tt]=w.useState(""),[te,Ie]=w.useState(!1),be=w.useRef(null),[$e,He]=w.useState(""),[ge,Pe]=w.useState(!1),qe=w.useRef(null),[Ze,ut]=w.useState(""),[vt,wt]=w.useState(!1),$t=w.useRef(null),[Qt,en]=w.useState(""),[Xt,tn]=w.useState(!1),Ge=w.useRef(null),[Ft,Yt]=w.useState(t?.printer_id||null),[Pt,pt]=w.useState(null),[Wt,Ut]=w.useState(null),[ze,st]=w.useState(t?.power_alert_enabled||!1),[ht,rt]=w.useState(t?.power_alert_high?.toString()||""),[Le,Oe]=w.useState(t?.power_alert_low?.toString()||""),[Ce,We]=w.useState(t?.schedule_enabled||!1),[Je,Xe]=w.useState(t?.schedule_on_time||""),[Ye,St]=w.useState(t?.schedule_off_time||""),[et,jt]=w.useState(t?.show_in_switchbar||!1),[bt,Ve]=w.useState(t?.show_on_printer_card??!0),[gt,Et]=w.useState(!1),[Gt,on]=w.useState({scanned:0,total:0}),[fn,Ln]=w.useState([]),yn=w.useRef(null),{data:hn}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:xn}=Qe({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),{data:Nn}=Qe({queryKey:["settings"],queryFn:me.getSettings}),Pn=!!(Nn?.ha_enabled&&Nn?.ha_url&&Nn?.ha_token);w.useEffect(()=>{const xt=setTimeout(()=>{tt(Me)},300);return()=>clearTimeout(xt)},[Me]),w.useEffect(()=>{const xt=Kn=>{be.current&&!be.current.contains(Kn.target)&&Ie(!1),qe.current&&!qe.current.contains(Kn.target)&&Pe(!1),$t.current&&!$t.current.contains(Kn.target)&&wt(!1),Ge.current&&!Ge.current.contains(Kn.target)&&tn(!1)};return document.addEventListener("mousedown",xt),()=>document.removeEventListener("mousedown",xt)},[]);const{data:Nr,isLoading:Sn,error:Pa}=Qe({queryKey:["ha-entities",Ke],queryFn:()=>me.getHAEntities(Ke||void 0),enabled:s==="homeassistant"&&Pn,retry:!1,staleTime:0}),{data:On}=Qe({queryKey:["ha-sensor-entities"],queryFn:me.getHASensorEntities,enabled:s==="homeassistant"&&Pn,retry:!1,staleTime:0});w.useEffect(()=>{const xt=Kn=>{Kn.key==="Escape"&&e()};return window.addEventListener("keydown",xt),()=>{window.removeEventListener("keydown",xt),yn.current&&clearInterval(yn.current)}},[e]);const ya=async()=>{Et(!0),Ln([]),on({scanned:0,total:0}),Ut(null);try{await me.startTasmotaScan();const xt=async()=>{try{const Kn=await me.getTasmotaScanStatus();on({scanned:Kn.scanned,total:Kn.total});const Zn=await me.getDiscoveredTasmotaDevices();Ln(Zn),Kn.running||(Et(!1),yn.current&&(clearInterval(yn.current),yn.current=null))}catch(Kn){console.error("Polling error:",Kn)}};await xt(),yn.current=setInterval(xt,500)}catch(xt){Et(!1);const Kn=xt instanceof Error?xt.message:typeof xt=="string"?xt:JSON.stringify(xt);Ut(Kn||n("smartPlugs.failedToStartScan"))}},ua=async()=>{try{await me.stopTasmotaScan()}catch{}Et(!1),yn.current&&(clearInterval(yn.current),yn.current=null)},Zr=xt=>{u(xt.ip_address),c(xt.name),pt(null)},sa=it({mutationFn:()=>me.testSmartPlugConnection(d,m||null,f||null),onSuccess:xt=>{pt(xt),Ut(null),!l&&xt.device_name&&c(xt.device_name)},onError:xt=>{pt(null),Ut(xt.message)}}),Ta=it({mutationFn:xt=>me.createSmartPlug(xt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xt=>{Ut(xt.message)}}),Wi=it({mutationFn:xt=>me.updateSmartPlug(t.id,xt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xt=>{Ut(xt.message)}}),_m=hn?.filter(xt=>s==="tasmota"?!xn?.some(Zn=>Zn.printer_id===xt.id&&Zn.id!==t?.id&&Zn.plug_type==="tasmota"):!0),Vd=xt=>{if(xt.preventDefault(),Ut(null),!l.trim()){Ut(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Ut("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Ut(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const Zn=b.trim(),qt=T.trim(),Kc=X.trim();if(!Zn&&!qt&&!Kc){Ut(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!le.trim()&&!ce.trim()){Ut(n("smartPlugs.restUrlRequired"));return}const Kn={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&Ae||null,ha_energy_today_entity:s==="homeassistant"&&je||null,ha_energy_total_entity:s==="homeassistant"&&Ee||null,mqtt_power_topic:s==="mqtt"&&b.trim()||null,mqtt_power_path:s==="mqtt"&&C.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&T.trim()||null,mqtt_energy_path:s==="mqtt"&&k.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(H)||1,mqtt_state_topic:s==="mqtt"&&X.trim()||null,mqtt_state_path:s==="mqtt"&&ne.trim()||null,mqtt_state_on_value:s==="mqtt"&&ee.trim()||null,rest_on_url:s==="rest"&&le.trim()||null,rest_on_body:s==="rest"&&W.trim()||null,rest_off_url:s==="rest"&&ce.trim()||null,rest_off_body:s==="rest"&&Ne.trim()||null,rest_method:s==="rest"?Y:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&K.trim()||null,rest_status_path:s==="rest"&&he.trim()||null,rest_status_on_value:s==="rest"&&V.trim()||null,rest_power_url:s==="rest"&&G.trim()||null,rest_power_path:s==="rest"&&se.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(pe)||1,rest_energy_url:s==="rest"&&U.trim()||null,rest_energy_path:s==="rest"&&ae.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(Se)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Ft,power_alert_enabled:ze,power_alert_high:ht?parseFloat(ht):null,power_alert_low:Le?parseFloat(Le):null,schedule_enabled:Ce,schedule_on_time:Je||null,schedule_off_time:Ye||null,show_in_switchbar:et,show_on_printer_card:bt};i?Wi.mutate(Kn):Ta.mutate(Kn)},fl=Ta.isPending||Wi.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.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:xt=>xt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Vd,className:"p-6 space-y-4 overflow-y-auto",children:[Wt&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Wt}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),pt(null),Ut(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:[a.jsx(Ql,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),pt(null),Ut(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:[a.jsx(Rw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),pt(null),Ut(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:[a.jsx(SO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),pt(null),Ut(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(rl,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[gt?a.jsxs(Fe,{type:"button",variant:"secondary",onClick:ua,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(Fe,{type:"button",variant:"primary",onClick:ya,className:"w-full",children:[a.jsx(kr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),gt&&Gt.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Gt.scanned," / ",Gt.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Gt.scanned/Gt.total*100}%`}})})]}),fn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:fn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:fn.map(xt=>a.jsxs("button",{type:"button",onClick:()=>Zr(xt),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:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ql,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:xt.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:xt.ip_address})]})]}),xt.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${xt.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(Ud,{className:"w-3 h-3"}),xt.state]})]},xt.ip_address))})]}),!gt&&fn.length===0&&Gt.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:n("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Pn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.haNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.haSettingsPath")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:n("smartPlugs.selectEntity")}),a.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:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Pn&&a.jsxs(a.Fragment,{children:[Sn&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(dt,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),Pa&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:n("smartPlugs.failedToLoadEntities",{error:Pa.message})}),(()=>{const xt=xn?.filter(qt=>qt.ha_entity_id&&qt.id!==t?.id).map(qt=>qt.ha_entity_id)||[],Kn=(Nr||[]).filter(qt=>!xt.includes(qt.entity_id)),Zn=Nr?.find(qt=>qt.entity_id===v);return a.jsxs("div",{ref:be,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.selectEntity")}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:te?Me:Zn?`${Zn.friendly_name} (${Zn.entity_id})`:"",onChange:qt=>{Be(qt.target.value),te||Ie(!0)},onFocus:()=>{Ie(!0),Be("")},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&&!te&&a.jsx("button",{type:"button",onClick:()=>{g(""),Be("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Sn&&a.jsx(dt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),te&&a.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:[Sn&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!Sn&&Kn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Ke?n("smartPlugs.noEntitiesMatching",{search:Ke}):n("smartPlugs.noEntitiesAvailable")}),!Sn&&Kn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{g(qt.entity_id),Ie(!1),Be(""),l||c(qt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${qt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:qt.entity_id}),a.jsx("span",{className:qt.state==="on"?"text-bambu-green":"",children:qt.state})]})]},qt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Ke?n("smartPlugs.searchingEntities",{count:Kn.length}):n("smartPlugs.showingEntities",{count:Kn.length})})]})})(),v&&On&&On.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:n("smartPlugs.energyMonitoringOptional")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:n("smartPlugs.energyMonitoringHint")})]}),(()=>{const xt=On.filter(qt=>qt.unit_of_measurement==="W"||qt.unit_of_measurement==="kW"||qt.unit_of_measurement==="mW"),Kn=$e?xt.filter(qt=>qt.entity_id.toLowerCase().includes($e.toLowerCase())||qt.friendly_name.toLowerCase().includes($e.toLowerCase())):xt,Zn=On.find(qt=>qt.entity_id===Ae);return a.jsxs("div",{ref:qe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.powerSensorW")}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:ge?$e:Zn?`${Zn.friendly_name} (${Zn.state} ${Zn.unit_of_measurement})`:"",onChange:qt=>{He(qt.target.value),ge||Pe(!0)},onFocus:()=>{Pe(!0),He("")},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"}),Ae&&!ge&&a.jsx("button",{type:"button",onClick:()=>{ve(""),He("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),ge&&a.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:[a.jsx("button",{type:"button",onClick:()=>{ve(""),Pe(!1),He("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Kn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{ve(qt.entity_id),Pe(!1),He("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Kn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const xt=On.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Kn=Ze?xt.filter(qt=>qt.entity_id.toLowerCase().includes(Ze.toLowerCase())||qt.friendly_name.toLowerCase().includes(Ze.toLowerCase())):xt,Zn=On.find(qt=>qt.entity_id===je);return a.jsxs("div",{ref:$t,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.energyTodayKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:vt?Ze:Zn?`${Zn.friendly_name} (${Zn.state} ${Zn.unit_of_measurement})`:"",onChange:qt=>{ut(qt.target.value),vt||wt(!0)},onFocus:()=>{wt(!0),ut("")},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"}),je&&!vt&&a.jsx("button",{type:"button",onClick:()=>{Re(""),ut("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),vt&&a.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:[a.jsx("button",{type:"button",onClick:()=>{Re(""),wt(!1),ut("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Kn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Re(qt.entity_id),wt(!1),ut("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===je?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Kn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const xt=On.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Kn=Qt?xt.filter(qt=>qt.entity_id.toLowerCase().includes(Qt.toLowerCase())||qt.friendly_name.toLowerCase().includes(Qt.toLowerCase())):xt,Zn=On.find(qt=>qt.entity_id===Ee);return a.jsxs("div",{ref:Ge,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.totalEnergyKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Xt?Qt:Zn?`${Zn.friendly_name} (${Zn.state} ${Zn.unit_of_measurement})`:"",onChange:qt=>{en(qt.target.value),Xt||tn(!0)},onFocus:()=>{tn(!0),en("")},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"}),Ee&&!Xt&&a.jsx("button",{type:"button",onClick:()=>{Te(""),en("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Xt&&a.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:[a.jsx("button",{type:"button",onClick:()=>{Te(""),tn(!1),en("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Kn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Te(qt.entity_id),tn(!1),en("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Ee?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Kn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!Nn?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.mqttNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.mqttSettingsPath")})," ",n("smartPlugs.mqttNotConfiguredSuffix")]}),Nn?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:n("smartPlugs.monitorOnly")}),a.jsx("p",{className:"text-xs opacity-80",children:n("smartPlugs.mqttMonitorOnlyDescription")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.powerMonitoring")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:b,onChange:xt=>_(xt.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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:C,onChange:xt=>P(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:N,onChange:xt=>A(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttPowerHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:T,onChange:xt=>F(xt.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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:k,onChange:xt=>D(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:H,onChange:xt=>z(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttEnergyHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:X,onChange:xt=>L(xt.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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:ne,onChange:xt=>ie(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.onValue")}),a.jsx("input",{type:"text",value:ee,onChange:xt=>ue(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.restControl")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restMethod")}),a.jsxs("select",{value:Y,onChange:xt=>E(xt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"GET",children:"GET"}),a.jsx("option",{value:"POST",children:"POST"}),a.jsx("option",{value:"PUT",children:"PUT"}),a.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOnUrl")}),a.jsx("input",{type:"text",value:le,onChange:xt=>{oe(xt.target.value),pt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOnBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:W,onChange:xt=>re(xt.target.value),placeholder:n("smartPlugs.restBodyHint"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOffUrl")}),a.jsx("input",{type:"text",value:ce,onChange:xt=>{xe(xt.target.value),pt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOffBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:Ne,onChange:xt=>$(xt.target.value),placeholder:n("smartPlugs.restBodyHint"),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"})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.restHeaders")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("div",{children:a.jsx("textarea",{value:j,onChange:xt=>O(xt.target.value),placeholder:n("smartPlugs.restHeadersHint"),rows:2,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 font-mono text-sm"})})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusUrl")}),a.jsx("input",{type:"text",value:K,onChange:xt=>B(xt.target.value),placeholder:n("smartPlugs.restStatusHint"),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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusPath")}),a.jsx("input",{type:"text",value:he,onChange:xt=>I(xt.target.value),placeholder:n("smartPlugs.restPathHint"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusOnValue")}),a.jsx("input",{type:"text",value:V,onChange:xt=>Q(xt.target.value),placeholder:"ON",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"})]})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restPowerUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:G,onChange:xt=>J(xt.target.value),placeholder:n("smartPlugs.restPowerUrlHint"),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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerPath")}),a.jsx("input",{type:"text",value:se,onChange:xt=>fe(xt.target.value),placeholder:n("smartPlugs.restPathHint"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerMultiplier")}),a.jsx("input",{type:"text",value:pe,onChange:xt=>de(xt.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"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restEnergyUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:U,onChange:xt=>R(xt.target.value),placeholder:n("smartPlugs.restEnergyUrlHint"),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"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyPath")}),a.jsx("input",{type:"text",value:ae,onChange:xt=>_e(xt.target.value),placeholder:n("smartPlugs.restPathHint"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyMultiplier")}),a.jsx("input",{type:"text",value:Se,onChange:xt=>ye(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.restEnergyHint")})]}),(le.trim()||ce.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(Fe,{type:"button",variant:"secondary",onClick:async()=>{pt(null);try{const xt=le.trim()||ce.trim(),Kn=await me.testRESTConnection(xt,Y,j.trim()||null);pt({success:Kn.success}),Kn.success||Ut(Kn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{pt({success:!1}),Ut(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(Vh,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),Pt&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${Pt.success?"text-green-400":"text-red-400"}`,children:[Pt.success?a.jsx(xr,{className:"w-4 h-4"}):a.jsx(Md,{className:"w-4 h-4"}),Pt.success?n("smartPlugs.connectionSuccess"):n("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.ipAddress")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:xt=>{u(xt.target.value),pt(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"}),a.jsxs(Fe,{type:"button",variant:"secondary",onClick:()=>sa.mutate(),disabled:!d.trim()||sa.isPending,children:[sa.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Vh,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&Pt&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${Pt.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:Pt.success?a.jsxs(a.Fragment,{children:[a.jsx(xr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:n("smartPlugs.connectedResult")}),a.jsxs("p",{className:"text-sm opacity-80",children:[Pt.device_name&&n("smartPlugs.deviceLabel",{name:Pt.device_name}),n("smartPlugs.stateLabel",{state:Pt.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Md,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.nameLabel")}),a.jsx("input",{type:"text",value:l,onChange:xt=>c(xt.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"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.username")}),a.jsx("input",{type:"text",value:m,onChange:xt=>p(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.password")}),a.jsx("input",{type:"password",value:f,onChange:xt=>x(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:n("smartPlugs.authHint")})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.linkToPrinter")}),a.jsxs("select",{value:Ft??"",onChange:xt=>Yt(xt.target.value?Number(xt.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:[a.jsx("option",{value:"",children:n("smartPlugs.noPrinter")}),_m?.map(xt=>a.jsx("option",{value:xt.id,children:xt.name},xt.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.linkingDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Uh,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.powerAlerts")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ze,onChange:xt=>st(xt.target.checked),className:"sr-only peer"}),a.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"})]})]}),ze&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertAbove")}),a.jsx("input",{type:"number",value:ht,onChange:xt=>rt(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertBelow")}),a.jsx("input",{type:"number",value:Le,onChange:xt=>Oe(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Qn,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.dailySchedule")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ce,onChange:xt=>We(xt.target.checked),className:"sr-only peer"}),a.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"})]})]}),Ce&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOnAt")}),a.jsx("input",{type:"time",value:Je,onChange:xt=>Xe(xt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOffAt")}),a.jsx("input",{type:"time",value:Ye,onChange:xt=>St(xt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.scheduleDescription")})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Lw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:et,onChange:xt=>jt(xt.target.checked),className:"sr-only peer"}),a.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"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ul,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showOnPrinterCard")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.displayOnPrinterCard")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:bt,onChange:xt=>Ve(xt.target.checked),className:"sr-only peer"}),a.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"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(Fe,{type:"submit",disabled:fl,className:"flex-1",children:[fl?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(gs,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function zn({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.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:a.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"}`})})}function $tt({provider:t,onEdit:e}){const{t:n}=Rt(),r=sn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),m=u?.find(g=>g.id===t.printer_id),p=it({mutationFn:g=>me.updateNotificationProvider(t.id,g),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=it({mutationFn:()=>me.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),x=it({mutationFn:()=>me.testNotificationProvider(t.id),onSuccess:g=>{d(g),r.invalidateQueries({queryKey:["notification-providers"]})},onError:g=>{d({success:!1,message:g.message})}}),v=g=>g||"";return a.jsxs(a.Fragment,{children:[a.jsx(At,{className:"relative",children:a.jsxs(Mt,{className:"p-3",children:[a.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Uh,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:n("notifications.lastSuccess",{date:Qf(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(er(t.last_error_at)?.getTime()||0)>(er(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(zn,{checked:t.enabled,onChange:g=>p.mutate({enabled:g})})]})]}),t.enabled&&a.jsxs(a.Fragment,{children:[m&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("notifications.printer")," "]}),a.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.allPrinters")})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:n("notifications.start")}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:n("notifications.plateCheck")}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:n("notifications.complete")}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:n("notifications.failed")}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:n("notifications.stopped")}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:n("notifications.progress")}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:n("notifications.offline")}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:n("notifications.error")}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:n("notifications.lowFilament")}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:n("notifications.maintenance")}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:n("notifications.amsHumidity")}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:n("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:n("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:n("notifications.amsHtTemp")}),t.on_bed_cooled&&a.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:n("notifications.bedCooled")}),t.on_first_layer_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:n("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:n("notifications.missingSpoolAssignmentLabel")}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(dN,{className:"w-3 h-3"}),n("notifications.quiet")]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(Yr,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Fe,{size:"sm",variant:"secondary",disabled:x.isPending,onClick:()=>{d(null),x.mutate()},className:"w-full",children:[x.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Bw,{className:"w-4 h-4"}),n("notifications.sendTestNotification")]})}),c&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?a.jsx(xr,{className:"w-4 h-4"}):a.jsx(Na,{className:"w-4 h-4"}),a.jsx("span",{children:c.message})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(jd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(ac,{className:"w-4 h-4"}):a.jsx(Un,{className:"w-4 h-4"})]}),o&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.sendFromProvider")})]}),a.jsx(zn,{checked:t.enabled,onChange:g=>p.mutate({enabled:g})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printEvents")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStarted")}),a.jsx(zn,{checked:t.on_print_start,onChange:g=>p.mutate({on_print_start:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.plateNotEmpty")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.plateNotEmptyDescription")})]}),a.jsx(zn,{checked:t.on_plate_not_empty??!0,onChange:g=>p.mutate({on_plate_not_empty:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printCompleted")}),a.jsx(zn,{checked:t.on_print_complete,onChange:g=>p.mutate({on_print_complete:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.bedCooledLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.bedCooledDescription")})]}),a.jsx(zn,{checked:t.on_bed_cooled??!1,onChange:g=>p.mutate({on_bed_cooled:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(zn,{checked:t.on_first_layer_complete??!1,onChange:g=>p.mutate({on_first_layer_complete:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.missingSpoolAssignmentLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.missingSpoolAssignmentDescription")})]}),a.jsx(zn,{checked:t.on_print_missing_spool_assignment??!1,onChange:g=>p.mutate({on_print_missing_spool_assignment:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printFailed")}),a.jsx(zn,{checked:t.on_print_failed,onChange:g=>p.mutate({on_print_failed:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStopped")}),a.jsx(zn,{checked:t.on_print_stopped,onChange:g=>p.mutate({on_print_stopped:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.progressMilestones")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.progressMilestonesDescription")})]}),a.jsx(zn,{checked:t.on_print_progress,onChange:g=>p.mutate({on_print_progress:g})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerOffline")}),a.jsx(zn,{checked:t.on_printer_offline,onChange:g=>p.mutate({on_printer_offline:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerError")}),a.jsx(zn,{checked:t.on_printer_error,onChange:g=>p.mutate({on_printer_error:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.lowFilamentLabel")}),a.jsx(zn,{checked:t.on_filament_low,onChange:g=>p.mutate({on_filament_low:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.maintenanceDue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.maintenanceDueDescription")})]}),a.jsx(zn,{checked:t.on_maintenance_due??!1,onChange:g=>p.mutate({on_maintenance_due:g})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHumidityHighDescription")})]}),a.jsx(zn,{checked:t.on_ams_humidity_high??!1,onChange:g=>p.mutate({on_ams_humidity_high:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsTemperatureHighDescription")})]}),a.jsx(zn,{checked:t.on_ams_temperature_high??!1,onChange:g=>p.mutate({on_ams_temperature_high:g})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsHtAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtHumidityHighDescription")})]}),a.jsx(zn,{checked:t.on_ams_ht_humidity_high??!1,onChange:g=>p.mutate({on_ams_ht_humidity_high:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtTemperatureHighDescription")})]}),a.jsx(zn,{checked:t.on_ams_ht_temperature_high??!1,onChange:g=>p.mutate({on_ams_ht_temperature_high:g})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printQueue")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAdded")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAddedDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_added??!1,onChange:g=>p.mutate({on_queue_job_added:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAssigned")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAssignedDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_assigned??!1,onChange:g=>p.mutate({on_queue_job_assigned:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobStarted")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobStartedDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_started??!1,onChange:g=>p.mutate({on_queue_job_started:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobWaiting")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobWaitingDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_waiting??!0,onChange:g=>p.mutate({on_queue_job_waiting:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobSkipped")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobSkippedDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_skipped??!0,onChange:g=>p.mutate({on_queue_job_skipped:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobFailed")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobFailedDescription")})]}),a.jsx(zn,{checked:t.on_queue_job_failed??!0,onChange:g=>p.mutate({on_queue_job_failed:g})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.queueComplete")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.queueCompleteDescription")})]}),a.jsx(zn,{checked:t.on_queue_completed??!1,onChange:g=>p.mutate({on_queue_completed:g})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(zn,{checked:t.quiet_hours_enabled,onChange:g=>p.mutate({quiet_hours_enabled:g})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.noNotificationsDuring")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Qn,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[v(t.quiet_hours_start)||"22:00"," - ",v(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeQuietHours")})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Yr,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(zn,{checked:t.daily_digest_enabled,onChange:g=>p.mutate({daily_digest_enabled:g})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Qn,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:n("notifications.sendAt",{time:v(t.daily_digest_time)||"08:00"})})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeDigestTime")})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Iu,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(_n,{title:n("notifications.deleteProvider"),message:n("notifications.deleteConfirm",{name:t.name}),confirmText:n("notifications.delete"),variant:"danger",onConfirm:()=>{f.mutate(),s(!1)},onCancel:()=>s(!1)})]})}const Vtt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function Gtt({provider:t,onClose:e}){const{t:n}=Rt(),r=sn(),i=!!t,[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.provider_type||"email"),[d,u]=w.useState(t?.printer_id||null),[m,p]=w.useState(t?.quiet_hours_enabled||!1),[f,x]=w.useState(t?.quiet_hours_start||"22:00"),[v,g]=w.useState(t?.quiet_hours_end||"07:00"),[b,_]=w.useState(t?.daily_digest_enabled||!1),[C,P]=w.useState(t?.daily_digest_time||"08:00"),[N,A]=w.useState(t?.on_print_start??!1),[T,F]=w.useState(t?.on_print_complete??!0),[k,D]=w.useState(t?.on_print_failed??!0),[H,z]=w.useState(t?.on_print_stopped??!0),[X,L]=w.useState(t?.on_print_progress??!1),[ne,ie]=w.useState(t?.on_printer_offline??!1),[ee,ue]=w.useState(t?.on_printer_error??!1),[le,oe]=w.useState(t?.on_filament_low??!1),[W,re]=w.useState(t?.on_maintenance_due??!1),[ce,xe]=w.useState(t?.on_bed_cooled??!1),[Ne,$]=w.useState(t?.on_first_layer_complete??!1),[Y,E]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([de,U])=>[de,String(U)])):{}),[j,O]=w.useState(null),[K,B]=w.useState(null),{data:he}=Qe({queryKey:["printers"],queryFn:me.getPrinters});w.useEffect(()=>{const de=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[e]);const I=it({mutationFn:()=>me.testNotificationConfig({provider_type:l,config:Y}),onSuccess:de=>{O(de),B(null)},onError:de=>{O({success:!1,message:de.message})}}),V=it({mutationFn:de=>me.createNotificationProvider(de),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:de=>{B(de.message)}}),Q=it({mutationFn:de=>me.updateNotificationProvider(t.id,de),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:de=>{B(de.message)}}),G=de=>{if(de.preventDefault(),B(null),!s.trim()){B(n("notifications.nameRequired"));return}const U=fe(l);for(const ae of U)if(!Y[ae.key]?.trim()){B(n("notifications.fieldRequired",{field:ae.label}));return}const R={name:s.trim(),provider_type:l,config:Y,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?v:null,daily_digest_enabled:b,daily_digest_time:b?C:null,on_print_start:N,on_print_complete:T,on_print_failed:k,on_print_stopped:H,on_print_progress:X,on_printer_offline:ne,on_printer_error:ee,on_filament_low:le,on_maintenance_due:W,on_bed_cooled:ce,on_first_layer_complete:Ne};i?Q.mutate(R):V.mutate(R)},J=V.isPending||Q.isPending,se=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:U=>U.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},fe=de=>se(de).filter(U=>U.required),pe=se(l);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.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:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"notifications.editTitle":"notifications.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:G,className:"p-6 space-y-4",children:[K&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:K}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.nameLabel")}),a.jsx("input",{type:"text",value:s,onChange:de=>o(de.target.value),placeholder:n("notifications.namePlaceholder"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.providerTypeLabel")}),a.jsx("select",{value:l,onChange:de=>{c(de.target.value),E({}),O(null)},disabled:i,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:Vtt.map(de=>a.jsx("option",{value:de,children:n(`notifications.providerTypes.${de}`,de)},de))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n(`notifications.providerDescriptions.${l}`,"")})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.configuration")}),pe.filter(de=>!("showIf"in de)||de.showIf?.(Y)!==!1).map(de=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[de.label," ",de.required&&"*"]}),de.type==="select"&&"options"in de&&de.options?a.jsx("select",{value:Y[de.key]||de.options[0]?.value||"",onChange:U=>{E({...Y,[de.key]:U.target.value}),O(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(U=>a.jsx("option",{value:U.value,children:U.label},U.value))}):a.jsx("input",{type:de.type,value:Y[de.key]||"",onChange:U=>{E({...Y,[de.key]:U.target.value}),O(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))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Fe,{type:"button",variant:"secondary",onClick:()=>{O(null),I.mutate()},disabled:I.isPending||fe(l).length>0&&!Y[fe(l)[0]?.key],className:"flex-1",children:[I.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Bw,{className:"w-4 h-4"}),n("notifications.testConfiguration")]})}),j&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${j.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:j.success?a.jsxs(a.Fragment,{children:[a.jsx(xr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.printerFilter")}),a.jsxs("select",{value:d??"",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:[a.jsx("option",{value:"",children:n("notifications.allPrinters")}),he?.map(de=>a.jsx("option",{value:de.id,children:de.name},de.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.onlyFromPrinter")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.quietHoursDnd")}),a.jsx(zn,{checked:m,onChange:p})]}),m&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietStart")}),a.jsx("input",{type:"time",value:f,onChange:de=>x(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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietEnd")}),a.jsx("input",{type:"time",value:v,onChange:de=>g(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"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.dailyDigestLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")})]}),a.jsx(zn,{checked:b,onChange:_})]}),b&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.sendDigestAt")}),a.jsx("input",{type:"time",value:C,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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.digestCollected")})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.notificationEvents")}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printEvents")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.start")}),a.jsx(zn,{checked:N,onChange:A})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(zn,{checked:T,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(zn,{checked:k,onChange:D})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(zn,{checked:H,onChange:z})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.progress")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.progressPercent")})]}),a.jsx(zn,{checked:X,onChange:L})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.bedCooled")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.bedCooledAfterPrint")})]}),a.jsx(zn,{checked:ce,onChange:xe})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(zn,{checked:Ne,onChange:$})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.offline")}),a.jsx(zn,{checked:ne,onChange:ie})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.error")}),a.jsx(zn,{checked:ee,onChange:ue})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(zn,{checked:le,onChange:oe})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(zn,{checked:W,onChange:re})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(Fe,{type:"submit",disabled:J,className:"flex-1",children:[J?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(gs,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function Wtt({template:t,onClose:e}){const{t:n}=Rt(),r=sn(),i=w.useRef(null),[s,o]=w.useState(t.title_template),[l,c]=w.useState(t.body_template),[d,u]=w.useState(null),[m,p]=w.useState(!0),{data:f}=Qe({queryKey:["template-variables"],queryFn:me.getTemplateVariables}),x=f?.find(A=>A.event_type===t.event_type),{data:v,isLoading:g}=Qe({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>me.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const A=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e]);const b=it({mutationFn:A=>me.updateNotificationTemplate(t.id,A),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:A=>{u(A.message)}}),_=it({mutationFn:()=>me.resetNotificationTemplate(t.id),onSuccess:A=>{o(A.title_template),c(A.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:A=>{u(A.message)}}),C=A=>{if(A.preventDefault(),u(null),!s.trim()){u(n("notifications.titleRequired"));return}if(!l.trim()){u(n("notifications.bodyRequired"));return}b.mutate({title_template:s,body_template:l})},P=A=>{const T=i.current;if(!T)return;const F=T.selectionStart,k=T.selectionEnd,D=l,H=D.substring(0,F),z=D.substring(k),X=H+`{${A}}`+z;c(X),setTimeout(()=>{T.focus();const L=F+A.length+2;T.setSelectionRange(L,L)},0)},N=s!==t.title_template||l!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("notifications.editTemplate",{name:t.name})}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:C,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.titleLabel")}),a.jsx("input",{type:"text",value:s,onChange:A=>o(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:n("notifications.titlePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.bodyLabel")}),a.jsx("textarea",{ref:i,value:l,onChange:A=>c(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:n("notifications.bodyPlaceholder")})]}),x&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:n("notifications.availableVariables")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:x.variables.map(A=>a.jsxs("button",{type:"button",onClick:()=>P(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:[a.jsx(or,{className:"w-3 h-3"}),A]},A))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:n("notifications.clickToInsert")})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(ul,{className:"w-4 h-4"}),n("notifications.livePreview")]}),a.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:n(m?"notifications.hide":"notifications.show")})]}),m&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:g?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),n("notifications.loadingPreview")]}):v?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.titlePreview")}),a.jsx("div",{className:"text-white font-medium",children:v.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.bodyPreview")}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:v.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:n("notifications.enterTemplateContent")})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Fe,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(eo,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(Fe,{onClick:C,disabled:b.isPending||!N,children:[b.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(gs,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const Ktt={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 Xtt({onClose:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=bn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=Qe({queryKey:["settings"],queryFn:me.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:x,isRefetching:v}=Qe({queryKey:["notification-logs",i,c],queryFn:()=>me.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:g}=Qe({queryKey:["notification-log-stats",i],queryFn:()=>me.getNotificationLogStats(i)}),b=it({mutationFn:()=>me.clearNotificationLogs(30),onSuccess:C=>{r(C.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:C=>{r(`Failed to clear logs: ${C.message}`,"error")}}),_=C=>{const P=er(C);if(!P)return"";const A=new Date().getTime()-P.getTime();return A<6e4?e("notifications.justNow"):A<36e5?`${Math.floor(A/6e4)}m ago`:A<864e5?`${Math.floor(A/36e5)}h ago`:P.toLocaleDateString()+" "+YQ(P,m)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.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:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(B0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),g&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",a.jsx("span",{className:"text-white font-medium",children:g.total})," ",e("notifications.statsNotifications")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(xr,{className:"w-4 h-4"}),e("notifications.statsSent",{count:g.success_count})]}),g.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Na,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:g.failure_count})]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:i,onChange:C=>s(Number(C.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:[a.jsx("option",{value:1,children:e("notifications.last24Hours")}),a.jsx("option",{value:7,children:e("notifications.last7Days")}),a.jsx("option",{value:30,children:e("notifications.last30Days")}),a.jsx("option",{value:90,children:e("notifications.last90Days")})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:C=>d(C.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>x(),disabled:v,children:[v?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>b.mutate(),disabled:b.isPending,className:"text-red-400 hover:text-red-300",children:[b.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(C=>a.jsx(Ytt,{log:C,isExpanded:o===C.id,onToggle:()=>l(o===C.id?null:C.id),formatDate:_,formatFullDate:P=>Zf(P,m)},C.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(B0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function Ytt({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Rt();return a.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:[a.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?a.jsx(xr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(Na,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${Ktt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(ac,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Un,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),a.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}function Qtt({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Rt();w.useEffect(()=>{const d=u=>{u.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const c=d=>{e({...t,group_ids:t.group_ids.includes(d)?t.group_ids.filter(u=>u!==d):[...t.group_ids,d]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(At,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Mt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:d=>e({...t,username:d.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})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:d=>e({...t,email:d.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})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.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."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.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(d=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(d.id),onChange:()=>c(d.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:d.name}),d.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},d.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Fe,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(or,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function Ztt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[d,u]=w.useState(!1),[m,p]=w.useState(!0),[f,x]=w.useState("all"),[v,g]=w.useState(!1),[b,_]=w.useState(!1),[C,P]=w.useState(!1),{data:N,isLoading:A}=Qe({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings}),{data:T,isLoading:F,refetch:k}=Qe({queryKey:["spoolman-status"],queryFn:me.getSpoolmanStatus,refetchInterval:3e4}),{data:D}=Qe({queryKey:["printers"],queryFn:me.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),u(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),g(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==d||N.spoolman_report_partial_usage!=="false"!==m){const re=setTimeout(()=>{H.mutate()},500);return()=>clearTimeout(re)}},[r,s,l,d,m,v]);const H=it({mutationFn:()=>me.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),n(t("settings.toast.settingsSaved"))}}),z=it({mutationFn:me.connectSpoolman,onSuccess:()=>{k()}}),X=it({mutationFn:me.disconnectSpoolman,onSuccess:()=>{k()}}),L=it({mutationFn:me.syncAllPrintersAms,onSuccess:W=>{W.success}}),ne=it({mutationFn:W=>me.syncPrinterAms(W),onSuccess:W=>{W.success}}),ie=()=>{f==="all"?L.mutate():ne.mutate(f)},ee=it({mutationFn:me.syncWeightsFromAms,onSuccess:W=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:W.synced,skipped:W.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),ue=L.isPending||ne.isPending,le=f==="all"?L.data:ne.data,oe=f==="all"?L.isSuccess:ne.isSuccess;return A?a.jsxs(At,{id:"card-spoolman",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Kl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Mt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(At,{id:"card-spoolman",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Kl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),H.isPending&&a.jsx(dt,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!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:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(ja,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!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:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(na,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(fs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:ee.isPending,children:[ee.isPending?a.jsx(dt,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(cr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(fs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:W=>o(W.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:W=>c(W.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:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:W=>u(W.target.checked),className:"sr-only peer"}),a.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"})]})]}),d&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:m,onChange:W=>p(W.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),F?a.jsx(dt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):T?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Rr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Bt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:T?.connected?a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[X.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Wge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Fe,{size:"sm",onClick:()=>z.mutate(),disabled:z.isPending||!s,children:[z.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Ku,{className:"w-4 h-4"}),t("settings.connect")]})})]}),z.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:z.error.message}),T?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:f,onChange:W=>x(W.target.value==="all"?"all":Number(W.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:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),D?.map(W=>a.jsx("option",{value:W.id,children:W.name},W.id))]}),a.jsx(Un,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:ie,disabled:ue,children:[ue?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),oe&&le&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${le.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:le.success?`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} successfully`:`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} with ${le.errors.length} error${le.errors.length!==1?"s":""}`}),le.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[le.skipped_count," spool",le.skipped_count!==1?"s":""," skipped"]})]}),le.skipped_count>5&&a.jsx("button",{onClick:()=>_(!b),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:b?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(b?le.skipped:le.skipped.slice(0,5)).map((W,re)=>a.jsxs("li",{className:"flex items-center gap-2",children:[W.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${W.color}`}}),a.jsx("span",{children:W.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",W.reason]})]},re)),!b&&le.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",le.skipped_count-5," more"]})]})]}),le.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:le.errors.map((W,re)=>a.jsx("li",{children:W},re))})]})]})]})]})]}),C&&a.jsx(_n,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:ee.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>ee.mutate(),onCancel:()=>P(!1)})]})}function Jtt(){const{t}=Rt(),{showToast:e}=bn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,x]=w.useState(""),[v,g]=w.useState(""),[b,_]=w.useState(!1),[C,P]=w.useState(new Set),[N,A]=w.useState(!1),[T,F]=w.useState(null),[k,D]=w.useState(!1),H=w.useCallback(async()=>{try{const xe=await me.getSpoolCatalog();r(xe)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{H()},[H]);const z=n.filter(xe=>xe.name.toLowerCase().includes(o.toLowerCase())),X=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const xe=await me.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(Ne=>[...Ne,xe].sort(($,Y)=>$.name.localeCompare(Y.name))),u(!1),x(""),g(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=xe=>{p(xe.id),x(xe.name),g(xe.weight.toString())},ne=()=>{p(null),x(""),g("")},ie=async xe=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const Ne=await me.updateCatalogEntry(xe,{name:f.trim(),weight:parseInt(v)});r($=>$.map(Y=>Y.id===xe?Ne:Y).sort((Y,E)=>Y.name.localeCompare(E.name))),p(null),x(""),g(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},ee=async()=>{if(T)try{await me.deleteCatalogEntry(T.id),r(xe=>xe.filter(Ne=>Ne.id!==T.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},ue=async()=>{D(!1),s(!0);try{await me.resetSpoolCatalog(),await H(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},le=xe=>{P(Ne=>{const $=new Set(Ne);return $.has(xe)?$.delete(xe):$.add(xe),$})},oe=()=>{C.size===z.length?P(new Set):P(new Set(z.map(xe=>xe.id)))},W=async()=>{if(A(!1),C.size!==0)try{const xe=await me.bulkDeleteCatalogEntries([...C]);r(Ne=>Ne.filter($=>!C.has($.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:xe.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},re=()=>{const xe=n.map(({name:E,weight:j})=>({name:E,weight:j})),Ne=new Blob([JSON.stringify(xe,null,2)],{type:"application/json"}),$=URL.createObjectURL(Ne),Y=document.createElement("a");Y.href=$,Y.download="spool-catalog.json",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL($),e(t("settings.catalog.exported",{count:n.length}),"success")},ce=async xe=>{const Ne=xe.target.files?.[0];if(Ne){try{const $=await Ne.text(),Y=JSON.parse($);if(!Array.isArray(Y))throw new Error("Invalid format");let E=0,j=0;for(const O of Y){if(!O.name||typeof O.weight!="number"){j++;continue}if(n.some(B=>B.name.toLowerCase()===O.name.toLowerCase())){j++;continue}try{const B=await me.addCatalogEntry({name:O.name,weight:O.weight});r(he=>[...he,B].sort((I,V)=>I.name.localeCompare(V.name))),E++}catch{j++}}e(t("settings.catalog.imported",{added:E,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(At,{id:"card-spool-catalog",children:[a.jsxs(wn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Kl,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:re,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:[a.jsx(ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.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:[a.jsx(Ma,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:ce}),a.jsxs("button",{onClick:()=>D(!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:[a.jsx(eo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>u(!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:[a.jsx(or,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),C.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:C.size})}),a.jsxs("button",{onClick:()=>A(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(rn,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),a.jsx("button",{onClick:()=>P(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.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:xe=>l(xe.target.value)})]}),d&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.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:f,onChange:xe=>x(xe.target.value)})}),a.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:xe=>g(xe.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:X,disabled:b,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:[b?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Rr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),x(""),g("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(dt,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:z.length>0&&C.size===z.length,onChange:oe,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:z.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):z.map(xe=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${C.has(xe.id)?"bg-bambu-dark":""}`,children:m===xe.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(xe.id),onChange:()=>le(xe.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2",children:a.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:f,onChange:Ne=>x(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.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:Ne=>g(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>ie(xe.id),disabled:b,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:b?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Rr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:ne,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(xe.id),onChange:()=>le(xe.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2 text-white",children:xe.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[xe.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:xe.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(xe),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>F(xe),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(rn,{className:"w-4 h-4"})})]})})]})},xe.id))})]})})]}),T&&a.jsx(_n,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:T.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:ee,onCancel:()=>F(null)}),N&&a.jsx(_n,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:C.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:W,onCancel:()=>A(!1)}),k&&a.jsx(_n,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:ue,onCancel:()=>D(!1)})]})}function ent(){const{t}=Rt(),{showToast:e}=bn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,d]=w.useState("Bambu Lab"),u=w.useRef(null),[m,p]=w.useState(!1),[f,x]=w.useState(null),[v,g]=w.useState(""),[b,_]=w.useState(""),[C,P]=w.useState("#FFFFFF"),[N,A]=w.useState(""),[T,F]=w.useState(!1),[k,D]=w.useState(new Set),[H,z]=w.useState(!1),[X,L]=w.useState(!1),[ne,ie]=w.useState(null),[ee,ue]=w.useState(null),[le,oe]=w.useState(!1),W=w.useCallback(async()=>{try{const G=await me.getColorCatalog();r(G)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{W()},[W]);const re=[...new Set(n.map(G=>G.manufacturer))].sort(),ce=n.filter(G=>{const J=o===""||G.manufacturer.toLowerCase().includes(o.toLowerCase())||G.color_name.toLowerCase().includes(o.toLowerCase())||(G.material?.toLowerCase().includes(o.toLowerCase())??!1),se=c===""||G.manufacturer===c;return J&&se}),xe=()=>{g(""),_(""),P("#FFFFFF"),A("")},Ne=async()=>{if(!v.trim()||!b.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const G=await me.addColorEntry({manufacturer:v.trim(),color_name:b.trim(),hex_color:C,material:N.trim()||null});r(J=>[...J,G].sort((se,fe)=>se.manufacturer.localeCompare(fe.manufacturer)||(se.material||"").localeCompare(fe.material||"")||se.color_name.localeCompare(fe.color_name))),p(!1),xe(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{F(!1)}},$=G=>{x(G.id),g(G.manufacturer),_(G.color_name),P(G.hex_color),A(G.material||"")},Y=()=>{x(null),xe()},E=async G=>{if(!v.trim()||!b.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const J=await me.updateColorEntry(G,{manufacturer:v.trim(),color_name:b.trim(),hex_color:C,material:N.trim()||null});r(se=>se.map(fe=>fe.id===G?J:fe).sort((fe,pe)=>fe.manufacturer.localeCompare(pe.manufacturer)||(fe.material||"").localeCompare(pe.material||"")||fe.color_name.localeCompare(pe.color_name))),x(null),xe(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{F(!1)}},j=async()=>{if(ee)try{await me.deleteColorEntry(ee.id),r(G=>G.filter(J=>J.id!==ee.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{ue(null)}},O=async()=>{oe(!1),s(!0);try{await me.resetColorCatalog(),await W(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},K=async()=>{L(!0),ie(null);try{const G={},J=om();J&&(G.Authorization=`Bearer ${J}`);const se=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:G});if(!se.ok)throw new Error("Failed to start sync");const fe=se.body?.getReader();if(!fe)throw new Error("No response body");const pe=new TextDecoder;let de="";for(;;){const{done:U,value:R}=await fe.read();if(U)break;de+=pe.decode(R,{stream:!0});const ae=de.split(`
- `);de=ae.pop()||"";for(const _e of ae)if(_e.startsWith("data: "))try{const Se=JSON.parse(_e.slice(6));Se.type==="progress"?ie({fetched:Se.total_fetched,total:Se.total_available}):Se.type==="complete"?Se.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Se.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Se.added,skipped:Se.skipped}),"success"):Se.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Se.error}`,"error")}catch{}}await W()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{L(!1),ie(null)}},B=G=>{D(J=>{const se=new Set(J);return se.has(G)?se.delete(G):se.add(G),se})},he=()=>{k.size===ce.length?D(new Set):D(new Set(ce.map(G=>G.id)))},I=async()=>{if(z(!1),k.size!==0)try{const G=await me.bulkDeleteColorEntries([...k]);r(J=>J.filter(se=>!k.has(se.id))),D(new Set),e(t("settings.colorCatalog.bulkDeleted",{count:G.deleted}),"success")}catch{e(t("settings.colorCatalog.bulkDeleteFailed"),"error")}},V=()=>{const G=n.map(({manufacturer:pe,color_name:de,hex_color:U,material:R})=>({manufacturer:pe,color_name:de,hex_color:U,material:R})),J=new Blob([JSON.stringify(G,null,2)],{type:"application/json"}),se=URL.createObjectURL(J),fe=document.createElement("a");fe.href=se,fe.download="color-catalog.json",document.body.appendChild(fe),fe.click(),document.body.removeChild(fe),URL.revokeObjectURL(se),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},Q=async G=>{const J=G.target.files?.[0];if(J){try{const se=await J.text(),fe=JSON.parse(se);if(!Array.isArray(fe))throw new Error("Invalid format");let pe=0,de=0;for(const U of fe){if(!U.manufacturer||!U.color_name||!U.hex_color){de++;continue}if(n.some(ae=>ae.manufacturer.toLowerCase()===U.manufacturer.toLowerCase()&&ae.color_name.toLowerCase()===U.color_name.toLowerCase()&&(ae.material||"").toLowerCase()===(U.material||"").toLowerCase())){de++;continue}try{const ae=await me.addColorEntry({manufacturer:U.manufacturer,color_name:U.color_name,hex_color:U.hex_color,material:U.material||null});r(_e=>[..._e,ae].sort((Se,ye)=>Se.manufacturer.localeCompare(ye.manufacturer)||(Se.material||"").localeCompare(ye.material||"")||Se.color_name.localeCompare(ye.color_name))),pe++}catch{de++}}e(t("settings.colorCatalog.imported",{added:pe,skipped:de}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return a.jsxs(At,{id:"card-color-catalog",children:[a.jsxs(wn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Iw,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:V,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:[a.jsx(ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>u.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:[a.jsx(Ma,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:u,type:"file",accept:".json",className:"hidden",onChange:Q}),a.jsxs("button",{onClick:K,disabled:X,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:[X?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(sy,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:X?ne?`${Math.min(ne.fetched,ne.total)} / ${ne.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),a.jsxs("button",{onClick:()=>oe(!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:[a.jsx(eo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>p(!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:[a.jsx(or,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),k.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.colorCatalog.selectedCount",{count:k.size})}),a.jsxs("button",{onClick:()=>z(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(rn,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),a.jsx("button",{onClick:()=>D(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),a.jsxs("div",{className:"flex gap-2 flex-wrap",children:[a.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.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:G=>l(G.target.value)})]}),a.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:G=>d(G.target.value),children:[a.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),re.map(G=>a.jsx("option",{value:G,children:G},G))]})]}),m&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[a.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:G=>g(G.target.value)}),a.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:b,onChange:G=>_(G.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:C,onChange:G=>P(G.target.value)}),a.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:C,onChange:G=>P(G.target.value)})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.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:N,onChange:G=>A(G.target.value)}),a.jsxs("button",{onClick:Ne,disabled:T,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:[T?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Rr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{p(!1),xe()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]})]}),(o||c)&&a.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:ce.length,total:n.length})}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(dt,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:ce.length>0&&k.size===ce.length,onChange:he,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),a.jsx("th",{className:"px-3 py-2 w-16"})]})}),a.jsx("tbody",{children:ce.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):ce.map(G=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.has(G.id)?"bg-bambu-dark":""}`,children:f===G.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(G.id),onChange:()=>B(G.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:C,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.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:J=>g(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.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:J=>A(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.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:b,onChange:J=>_(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.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:C,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>E(G.id),disabled:T,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:T?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Rr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:Y,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(G.id),onChange:()=>B(G.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:G.hex_color},title:G.hex_color})}),a.jsx("td",{className:"px-3 py-2 text-white",children:G.manufacturer}),a.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:G.material||"-"}),a.jsx("td",{className:"px-3 py-2 text-white",children:G.color_name}),a.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:G.hex_color}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>$(G),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>ue(G),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(rn,{className:"w-4 h-4"})})]})})]})},G.id))})]})})]}),ee&&a.jsx(_n,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${ee.manufacturer} - ${ee.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:j,onCancel:()=>ue(null)}),H&&a.jsx(_n,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:I,onCancel:()=>z(!1)}),le&&a.jsx(_n,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:O,onCancel:()=>oe(!1)})]})}function tnt({link:t,onClose:e}){const{t:n}=Rt(),r=sn(),i=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.url||""),[u,m]=w.useState(t?.icon||"link"),[p,f]=w.useState(t?.open_in_new_tab||!1),[x,v]=w.useState(!!t?.custom_icon),[g,b]=w.useState(t?.custom_icon?me.getExternalLinkIconUrl(t.id):null),[_,C]=w.useState(null),[P,N]=w.useState(null);w.useEffect(()=>{const X=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[e]);const A=it({mutationFn:async X=>{const L=await me.createExternalLink(X);return _?await me.uploadExternalLinkIcon(L.id,_):L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:X=>{N(X.message)}}),T=it({mutationFn:async X=>{let L=await me.updateExternalLink(t.id,X);return _?L=await me.uploadExternalLinkIcon(t.id,_):!x&&t?.custom_icon&&(L=await me.deleteExternalLinkIcon(t.id)),L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:X=>{N(X.message)}}),F=X=>{const L=X.target.files?.[0];if(L){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(L.type)){N("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(L.size>1024*1024){N("Image file must be less than 1MB");return}C(L),v(!0);const ie=new FileReader;ie.onload=ee=>{b(ee.target?.result)},ie.readAsDataURL(L)}},k=()=>{C(null),b(null),v(!1),s.current&&(s.current.value="")},D=X=>{if(X.preventDefault(),N(null),!o.trim()){N("Name is required");return}if(!c.trim()){N("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){N("URL must start with http:// or https://");return}const L={name:o.trim(),url:c.trim(),icon:u,open_in_new_tab:p};i?T.mutate(L):A.mutate(L)},H=A.isPending||T.isPending,z=DP(u);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:X=>X.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:x&&g?a.jsx("img",{src:g,alt:"",className:"w-5 h-5 rounded"}):a.jsx(z,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[P&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:P}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:o,onChange:X=>l(X.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:c,onChange:X=>d(X.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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),a.jsx("button",{type:"button",onClick:()=>f(!p),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:F}),x&&g?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:g,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:k,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(rn,{className:"w-4 h-4"})})]}):a.jsxs(Fe,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[a.jsx(Ma,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!x&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(pye,{value:u,onChange:m})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Fe,{type:"submit",disabled:H,className:"flex-1",children:[H?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(gs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function nnt(){const{t}=Rt(),e=sn(),[n,r]=w.useState(!1),[i,s]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),{data:u,isLoading:m}=Qe({queryKey:["external-links"],queryFn:me.getExternalLinks}),p=it({mutationFn:C=>me.deleteExternalLink(C),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=it({mutationFn:C=>me.reorderExternalLinks(C),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(C,P)=>{d(P),C.dataTransfer.effectAllowed="move"},v=C=>{C.preventDefault(),C.dataTransfer.dropEffect="move"},g=(C,P)=>{if(C.preventDefault(),c===null||c===P||!u)return;const N=u.map(k=>k.id),A=N.indexOf(c),T=N.indexOf(P);if(A===-1||T===-1)return;const F=[...N];F.splice(A,1),F.splice(T,0,c),f.mutate(F),d(null)},b=C=>{l(C)},_=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(At,{id:"card-sidebar-links",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ku,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Fe,{size:"sm",onClick:()=>r(!0),children:[a.jsx(or,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Mt,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),m?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"space-y-2",children:u.map(C=>{const P=DP(C.icon);return a.jsxs("div",{draggable:!0,onDragStart:N=>x(N,C.id),onDragOver:v,onDrop:N=>g(N,C.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===C.id?"opacity-50":""}`,children:[a.jsx($h,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(P,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white font-medium truncate",children:C.name}),a.jsx(na,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:C.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(C),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>b(C),disabled:p.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:a.jsx(rn,{className:"w-4 h-4"})})]})]},C.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Ku,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(tnt,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(_n,{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 u3={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function rnt({printer:t,models:e}){const{t:n}=Rt(),r=sn(),{showToast:i}=bn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[d,u]=w.useState(t.name),[m,p]=w.useState(""),[f,x]=w.useState(t.mode==="queue"?"review":t.mode),[v,g]=w.useState(t.target_printer_id),[b,_]=w.useState(t.bind_ip||""),[C,P]=w.useState(t.remote_interface_ip||""),[N,A]=w.useState(t.model||""),[T,F]=w.useState(t.auto_dispatch??!0),[k,D]=w.useState(!1),[H,z]=w.useState(null),[X,L]=w.useState(!1);w.useEffect(()=>{H||(c(t.enabled),x(t.mode==="queue"?"review":t.mode),u(t.name),g(t.target_printer_id),_(t.bind_ip||""),P(t.remote_interface_ip||""),A(t.model||""),F(t.auto_dispatch??!0))},[t,H]);const{data:ne}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:ie}=Qe({queryKey:["network-interfaces"],queryFn:()=>me.getNetworkInterfaces().then(j=>j.interfaces)}),ee=it({mutationFn:j=>hN.update(t.id,j),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.updated")),z(null)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),x(t.mode==="queue"?"review":t.mode),g(t.target_printer_id),_(t.bind_ip||""),z(null)}}),ue=it({mutationFn:()=>hN.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.deleted")),L(!1)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToDelete"),"error"),L(!1)}}),le=j=>{j.stopPropagation();const O=!l;if(O){if(!b){i(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(f==="proxy"){if(!v){i(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!m&&!t.access_code_set){i(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(O),z("toggle"),ee.mutate({enabled:O})},oe=()=>{d.trim()&&(z("name"),ee.mutate({name:d.trim()}))},W=()=>{if(!m){i(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(m.length!==8){i(n("virtualPrinter.toast.accessCodeLength"),"error");return}z("accessCode"),ee.mutate({access_code:m}),p("")},re=j=>{x(j),z("mode"),ee.mutate({mode:j})},ce=j=>{A(j),z("model"),ee.mutate({model:j})},xe=j=>{g(j),z("targetPrinter"),ee.mutate({target_printer_id:j})},Ne=j=>{P(j),z("remoteInterface"),ee.mutate({remote_interface_ip:j})},$=t.status?.running||!1,Y=n(`virtualPrinter.mode.${u3[f]||"archive"}`),E=ne?.find(j=>j.id===v)?.name;return a.jsxs(a.Fragment,{children:[a.jsxs(At,{children:[a.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[a.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?a.jsx(Un,{className:"w-4 h-4"}):a.jsx(Ka,{className:"w-4 h-4"})}),a.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${$?"bg-green-400 animate-pulse":"bg-gray-500"}`}),a.jsx("span",{className:"text-white font-medium truncate",children:t.name}),a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:Y}),t.model_name&&a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),E&&a.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&a.jsx(q3,{className:"w-3 h-3 inline mr-1"}),E]}),b&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:b}),C&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:C}),a.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:j=>j.stopPropagation(),children:a.jsx("button",{onClick:le,disabled:H==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${H==="toggle"?"opacity-50":""}`,children:a.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&&a.jsxs(Mt,{className:"pt-0 space-y-4",children:[a.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:j=>u(j.target.value),onBlur:oe,onKeyDown:j=>j.key==="Enter"&&oe(),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"}),a.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),a.jsx("button",{onClick:()=>L(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:a.jsx(rn,{className:"w-4 h-4"})})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(j=>a.jsxs("button",{onClick:()=>re(j),disabled:H==="mode",className:`p-2 rounded-lg border text-left transition-colors ${f===j?j==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[j==="proxy"&&a.jsx(q3,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${u3[j]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${u3[j]}Desc`)})]},j))})]}),f==="print_queue"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.autoDispatch.title")}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.autoDispatch.description")})]}),a.jsx("button",{onClick:()=>{const j=!T;F(j),z("autoDispatch"),ee.mutate({auto_dispatch:j})},disabled:H==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${T?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${H==="autoDispatch"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${T?"translate-x-5":""}`})})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:N,onChange:j=>ce(j.target.value),disabled:H==="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(([j,O])=>a.jsxs("option",{value:j,children:[O," (",j,")"]},j))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),f==="proxy"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[a.jsx(fs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[a.jsx(Rr,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[a.jsx(Rn,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:k?"text":"password",value:m,onChange:j=>p(j.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"}),a.jsx("button",{onClick:()=>D(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:k?a.jsx(vg,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"})})]}),a.jsx(Fe,{onClick:W,disabled:!m||H==="accessCode",variant:"primary",children:H==="accessCode"?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a.jsx("span",{className:m.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:m.length})})})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:v??"",onChange:j=>{const O=parseInt(j.target.value,10);isNaN(O)||xe(O)},disabled:H==="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:[a.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),ne?.map(j=>a.jsxs("option",{value:j.id,children:[j.name," (",j.ip_address,")"]},j.id))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:b,onChange:j=>{_(j.target.value),z("bindIp"),ee.mutate({bind_ip:j.target.value})},disabled:H==="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:[a.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),ie?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,")",j.is_alias?" [alias]":""," - ",j.subnet]},j.ip))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),C?a.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:a.jsx(Rr,{className:"w-3 h-3"})}):a.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:a.jsx(fs,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C,onChange:j=>Ne(j.target.value),disabled:H==="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:[a.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),ie?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,") - ",j.subnet]},j.ip))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),X&&a.jsx(_n,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:ue.isPending,onConfirm:()=>ue.mutate(),onCancel:()=>L(!1)})]})}const lY={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function ant({onClose:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=bn(),[i,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,d]=w.useState(null),{data:u}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),m=it({mutationFn:()=>hN.create({name:i.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:p=>{r(p.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:a.jsx(At,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:a.jsxs(Mt,{className:"p-6 space-y-4",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),a.jsx("input",{type:"text",value:i,onChange:p=>s(p.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(p=>a.jsxs("button",{onClick:()=>l(p),className:`p-2 rounded-lg border text-left transition-colors ${o===p?p==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[p==="proxy"&&a.jsx(q3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${lY[p]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${lY[p]}Desc`)})]},p))})]}),o==="proxy"&&a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:c??"",onChange:p=>{const f=parseInt(p.target.value,10);d(isNaN(f)?null:f)},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:[a.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),u?.map(p=>a.jsxs("option",{value:p.id,children:[p.name," (",p.ip_address,")"]},p.id))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),a.jsx(Fe,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function int(){const{t}=Rt(),[e,n]=w.useState(!1),{data:r,isLoading:i}=Qe({queryKey:["virtual-printers"],queryFn:hN.list,refetchInterval:1e4});if(i)return a.jsx(At,{children:a.jsx(Mt,{className:"py-8 flex justify-center",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[a.jsx(At,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Mt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs",children:[a.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),a.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:[a.jsx(na,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(At,{className:"lg:col-span-3",children:a.jsx(Mt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(fs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),a.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ar,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),a.jsxs(Fe,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(or,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"py-8 text-center",children:[a.jsx(Ar,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),a.jsxs(Fe,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(or,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>a.jsx(rnt,{printer:l,models:o},l.id))}),e&&a.jsx(ant,{onClose:()=>n(!1)})]})}function cY(t){if(t<60)return`${t}s`;const e=Math.floor(t/60);if(e<60)return`${e}m`;const n=Math.floor(e/60),r=e%60;if(n<24)return r?`${n}h ${r}m`:`${n}h`;const i=Math.floor(n/24),s=n%24;return s?`${i}d ${s}h`:`${i}d`}function dY(t){return t==null?"—":t>=1024?`${(t/1024).toFixed(1)} GB`:`${Math.round(t)} MB`}function snt({device:t,onUnregister:e,isDeleting:n}){const{t:r}=Rt(),{showToast:i}=bn(),s=t.system_stats,o=s?.memory,l=s?.disk,c=t.online,[d,u]=w.useState(null),[m,p]=w.useState(null),f=async b=>{p(b);try{b==="update"?await Ur.triggerUpdate(t.device_id):await Ur.systemCommand(t.device_id,b),i(r("settings.spoolbuddy.commandQueued"),"success")}catch(_){const C=_ instanceof Error?_.message:r("settings.spoolbuddy.commandError");i(C,"error")}finally{p(null),u(null)}},x=[{key:"update",label:r("settings.spoolbuddy.update"),icon:ca},{key:"restart_browser",label:r("settings.spoolbuddy.restartBrowser"),icon:wO},{key:"restart_daemon",label:r("settings.spoolbuddy.restartDaemon"),icon:cr},{key:"reboot",label:r("settings.spoolbuddy.reboot"),icon:H0},{key:"shutdown",label:r("settings.spoolbuddy.shutdown"),icon:Ud,variant:"danger"}],v={update:r("settings.spoolbuddy.updateConfirmTitle"),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmTitle"),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmTitle"),reboot:r("settings.spoolbuddy.rebootConfirmTitle"),shutdown:r("settings.spoolbuddy.shutdownConfirmTitle")},g={update:r("settings.spoolbuddy.updateConfirmBody",{hostname:t.hostname}),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmBody",{hostname:t.hostname}),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmBody",{hostname:t.hostname}),reboot:r("settings.spoolbuddy.rebootConfirmBody",{hostname:t.hostname}),shutdown:r("settings.spoolbuddy.shutdownConfirmBody",{hostname:t.hostname})};return a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"text-base font-semibold text-white truncate",children:t.hostname}),a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${c?"bg-green-500/15 text-green-400 border border-green-500/40":"bg-gray-500/15 text-gray-400 border border-gray-500/40"}`,children:[c?a.jsx(Vh,{className:"w-3 h-3"}):a.jsx(Md,{className:"w-3 h-3"}),r(c?"settings.spoolbuddy.online":"settings.spoolbuddy.offline")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray font-mono mt-1 truncate",children:t.device_id})]}),a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>e(t),disabled:n,"aria-label":r("settings.spoolbuddy.unregister"),children:[a.jsx(rn,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:r("settings.spoolbuddy.unregister")})]})]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.ipAddress")}),a.jsx("div",{className:"text-white font-mono",children:t.ip_address})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.firmware")}),a.jsx("div",{className:"text-white",children:t.firmware_version??"—"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"text-bambu-gray flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),r("settings.spoolbuddy.lastSeen")]}),a.jsx("div",{className:"text-white",children:t.last_seen?Gh(t.last_seen):r("settings.spoolbuddy.never")})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.daemonUptime")}),a.jsx("div",{className:"text-white",children:cY(t.uptime_s)})]})]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:x.map(({key:b,label:_,icon:C,variant:P})=>a.jsxs(Fe,{variant:P??"secondary",size:"sm",onClick:()=>u(b),disabled:!c||m!==null,"aria-label":_,children:[m===b?a.jsx(dt,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(C,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:_})]},b))}),a.jsxs("div",{className:"flex items-center gap-3 text-xs flex-wrap",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.nfc_ok?a.jsx(nl,{className:"w-3.5 h-3.5 text-green-400"}):a.jsx(Na,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.nfc"),t.nfc_reader_type&&a.jsxs("span",{className:"text-bambu-gray/70",children:["(",t.nfc_reader_type,")"]})]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.scale_ok?a.jsx(nl,{className:"w-3.5 h-3.5 text-green-400"}):a.jsx(Na,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.scale")]})]}),s&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-xs",children:[s.cpu_temp_c!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(qw,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.cpuTemp")}),a.jsxs("div",{className:"text-white",children:[s.cpu_temp_c.toFixed(1),"°C"]})]})]}),o&&o.percent!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Kv,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.memory")}),a.jsxs("div",{className:"text-white",children:[o.percent.toFixed(0),"% (",dY(o.used_mb)," / ",dY(o.total_mb),")"]})]})]}),l&&l.percent!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rp,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.disk")}),a.jsxs("div",{className:"text-white",children:[l.percent.toFixed(0),"% (",l.used_gb?.toFixed(1)," / ",l.total_gb?.toFixed(1)," GB)"]})]})]}),s.system_uptime_s!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Qn,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.systemUptime")}),a.jsx("div",{className:"text-white",children:cY(s.system_uptime_s)})]})]})]}),s.os&&a.jsx("div",{className:"mt-3 text-xs text-bambu-gray font-mono truncate",children:[s.os.os,s.os.kernel,s.os.arch,s.os.python&&`Python ${s.os.python}`].filter(Boolean).join(" · ")})]})]}),d&&a.jsx(_n,{variant:d==="shutdown"||d==="reboot"?"danger":"default",title:v[d],message:g[d],confirmText:r("settings.spoolbuddy.commandConfirm"),isLoading:m!==null,onConfirm:()=>f(d),onCancel:()=>u(null)})]})}function ont(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),[r,i]=w.useState(null),{data:s=[],isLoading:o}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:15e3}),l=it({mutationFn:d=>Ur.deleteDevice(d),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolbuddy-devices"]}),n(t("settings.spoolbuddy.unregisterSuccess"),"success"),i(null)},onError:d=>{n(d.message||t("settings.spoolbuddy.unregisterError"),"error")}});if(o)return a.jsx(At,{children:a.jsx(Mt,{className:"py-8 flex justify-center",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const c=s.length>1;return a.jsxs("div",{className:"space-y-4",children:[a.jsx(At,{children:a.jsx(Mt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[a.jsx(fs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.infoTitle")}),a.jsx("p",{children:t("settings.spoolbuddy.infoBody")})]})]})})}),c&&a.jsx(At,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Mt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.duplicatesTitle",{count:s.length})}),a.jsx("p",{children:t("settings.spoolbuddy.duplicatesBody")})]})]})})}),s.length===0?a.jsx(At,{children:a.jsx(Mt,{className:"py-8 text-center text-bambu-gray text-sm",children:t("settings.spoolbuddy.empty")})}):a.jsx("div",{className:"space-y-3",children:s.map(d=>a.jsx(snt,{device:d,onUnregister:i,isDeleting:l.isPending&&l.variables===d.device_id},d.id))}),r&&a.jsx(_n,{variant:"danger",title:t("settings.spoolbuddy.confirmTitle"),message:t("settings.spoolbuddy.confirmBody",{hostname:r.hostname,deviceId:r.device_id}),confirmText:t("settings.spoolbuddy.unregister"),isLoading:l.isPending,onConfirm:()=>l.mutate(r.device_id),onCancel:()=>i(null)})]})}function m3(t){if(!t)return"-";const e=er(t);return e?e.toLocaleString():"-"}function h3({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:a.jsx(xr,{className:"w-3 h-3"}),failed:a.jsx(Na,{className:"w-3 h-3"}),skipped:a.jsx(EP,{className:"w-3 h-3"}),running:a.jsx(dt,{className:"w-3 h-3 animate-spin"})};return a.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 lnt(){const t=sn(),{showToast:e}=bn(),{t:n}=Rt(),[r,i]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[d,u]=w.useState(!1),[m,p]=w.useState("daily"),[f,x]=w.useState(!0),[v,g]=w.useState(!0),[b,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(!0),[k,D]=w.useState(!1),[H,z]=w.useState(!1),[X,L]=w.useState(""),[ne,ie]=w.useState(!1),[ee,ue]=w.useState(null),[le,oe]=w.useState(null),W=w.useRef(null),[re,ce]=w.useState(null),[xe,Ne]=w.useState(null),[$,Y]=w.useState(""),{data:E,refetch:j}=Qe({queryKey:["local-backup-status"],queryFn:me.getLocalBackupStatus,refetchInterval:te=>te.state.data?.is_running?1e3:1e4}),{data:O,refetch:K}=Qe({queryKey:["local-backup-files"],queryFn:me.getLocalBackups,refetchInterval:3e4});w.useEffect(()=>{E?.path!==void 0&&Y(E.path)},[E?.path]);const B=it({mutationFn:me.triggerLocalBackup,onSuccess:te=>{te.success?e(n("backup.scheduledBackupComplete")):e(te.message,"error"),j(),K()},onError:()=>e(n("backup.scheduledBackupFailed"),"error")}),he=it({mutationFn:te=>me.deleteLocalBackup(te),onSuccess:()=>{K(),ce(null)}}),I=it({mutationFn:async te=>(Ne(null),z(!0),oe(null),L(n("backup.restoring")),me.restoreLocalBackup(te)),onSuccess:te=>{z(!1),L(""),te.success?(oe({success:!0,message:te.message}),e(n("backup.backupRestoredRestart"),"success")):(oe({success:!1,message:te.message}),e(te.message,"error"))},onError:te=>{z(!1),L("");const Ie=te instanceof Error?te.message:n("backup.failedToRestore");oe({success:!1,message:Ie}),e(Ie,"error")}});w.useEffect(()=>{if(k||H){const Ie=be=>(be.preventDefault(),be.returnValue="A backup operation is in progress. Are you sure you want to leave?",be.returnValue);return window.addEventListener("beforeunload",Ie),()=>window.removeEventListener("beforeunload",Ie)}},[k,H]);const[V,Q]=w.useState(!1),[G,J]=w.useState(null),se=w.useRef(null),fe=w.useRef(!1),{data:pe,isLoading:de}=Qe({queryKey:["github-backup-config"],queryFn:me.getGitHubBackupConfig}),{data:U}=Qe({queryKey:["github-backup-status"],queryFn:me.getGitHubBackupStatus,refetchInterval:te=>te.state.data?.is_running?500:1e4}),{data:R}=Qe({queryKey:["github-backup-logs"],queryFn:()=>me.getGitHubBackupLogs(20)}),{data:ae}=Qe({queryKey:["cloud-status"],queryFn:me.getCloudStatus}),{data:_e}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),Se=fp({queries:(_e??[]).map(te=>({queryKey:["printerStatus",te.id],queryFn:()=>me.getPrinterStatus(te.id),staleTime:1e4,refetchInterval:3e4}))}),ye=(_e??[]).map((te,Ie)=>({printer:te,connected:Se[Ie]?.data?.connected??!1})),Ae=ye.length,ve=ye.filter(te=>te.connected).length,je=Ae>0&&ve===0,Re=ve>0&&ve<Ae;w.useEffect(()=>{pe&&(i(pe.repository_url),c(pe.branch),u(pe.schedule_enabled),p(pe.schedule_type),x(pe.backup_kprofiles),g(pe.backup_cloud_profiles),_(pe.backup_settings),P(pe.backup_spools),A(pe.backup_archives),F(pe.enabled),o(""),setTimeout(()=>{fe.current=!0},100))},[pe]);const Ee=w.useCallback(async(te=!1)=>{if(pe?.has_token)try{te&&s?(await me.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:b,backup_spools:C,backup_archives:N,enabled:T}),o(""),e(n("backup.tokenUpdated"))):(await me.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:b,backup_spools:C,backup_archives:N,enabled:T}),e(n("backup.settingsSaved"))),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Ie){e(n("backup.failedToSave",{message:Ie.message}),"error")}},[pe?.has_token,r,s,l,d,m,f,v,b,C,N,T,t,e,n]);w.useEffect(()=>{if(!(!fe.current||!pe?.has_token))return se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{Ee(!1)},500),()=>{se.current&&clearTimeout(se.current)}},[r,l,d,m,f,v,b,C,N,T,Ee,pe?.has_token]),w.useEffect(()=>{if(!(!fe.current||!pe?.has_token||!s))return se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{Ee(!0)},1e3),()=>{se.current&&clearTimeout(se.current)}},[s,Ee,pe?.has_token]);const Te=it({mutationFn:te=>me.saveGitHubBackupConfig(te),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(n("backup.githubBackupEnabled")),o(""),fe.current=!0},onError:te=>{e(n("backup.failedToSave",{message:te.message}),"error")}}),Me=it({mutationFn:me.triggerGitHubBackup,onSuccess:te=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),te.success?te.files_changed>0?e(n("backup.backupCompleteFiles",{count:te.files_changed})):e(n("backup.backupSkippedNoChanges")):e(n("backup.backupFailed2",{message:te.message}),"error")},onError:te=>{e(n("backup.backupFailed2",{message:te.message}),"error")}}),Be=it({mutationFn:()=>me.clearGitHubBackupLogs(0),onSuccess:te=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(n("backup.clearedLogs",{count:te.deleted}))},onError:te=>{e(n("backup.failedToClearLogs",{message:te.message}),"error")}}),Ke=async()=>{Q(!0),J(null);try{let te;if(s){if(!r){e(n("backup.enterRepoUrl"),"error"),Q(!1);return}te=await me.testGitHubConnection(r,s)}else if(pe?.has_token)te=await me.testGitHubStoredConnection();else{e(n("backup.enterRepoAndToken"),"error"),Q(!1);return}J({success:te.success,message:te.message})}catch(te){J({success:!1,message:te.message})}finally{Q(!1)}},tt=()=>{if(!r){e(n("backup.repoRequired"),"error");return}if(!s){e(n("backup.tokenRequired"),"error");return}Te.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:b,backup_spools:C,backup_archives:N,enabled:T})};return de?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(At,{id:"card-backup-github",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(V3,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.githubBackup")})]}),pe&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.enabled")}),a.jsx(zn,{checked:T,onChange:F})]})]})}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.githubDescription")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.repositoryUrl")}),a.jsx("input",{type:"text",value:r,onChange:te=>{i(te.target.value),J(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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("backup.personalAccessToken")," ",pe?.has_token&&a.jsx("span",{className:"text-green-400",children:n("backup.tokenSaved")})]}),a.jsx("input",{type:"password",value:s,onChange:te=>{o(te.target.value),J(null)},placeholder:pe?.has_token?n("backup.enterNewToken"):"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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("backup.tokenHint")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.branch")}),a.jsx("input",{type:"text",value:l,onChange:te=>c(te.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.autoBackup")}),a.jsxs("select",{value:d?m:"disabled",onChange:te=>{te.target.value==="disabled"?u(!1):(u(!0),p(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",children:[a.jsx("option",{value:"disabled",children:n("backup.manualOnly")}),a.jsx("option",{value:"hourly",children:n("backup.hourly")}),a.jsx("option",{value:"daily",children:n("backup.daily")}),a.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:n("backup.includeInBackup")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${je?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:f,onChange:te=>x(te.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}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${je?"text-bambu-gray":"text-white"}`,children:n("backup.kProfiles")}),je&&a.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:[a.jsx(Rn,{className:"w-3 h-3"}),n("backup.noPrintersConnected")]}),Re&&a.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:[a.jsx(Rn,{className:"w-3 h-3"}),n("backup.printersConnected",{connected:ve,total:Ae})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.kProfilesDescription")})]})]}),a.jsxs("label",{className:`flex items-start gap-2 ${ae?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:te=>g(te.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:!ae?.is_authenticated}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${ae?.is_authenticated?"text-white":"text-bambu-gray"}`,children:n("backup.cloudProfiles")}),!ae?.is_authenticated&&a.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:[a.jsx(Rn,{className:"w-3 h-3"}),n("backup.cloudLoginRequiredShort")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.cloudProfilesDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:b,onChange:te=>_(te.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"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.appSettings")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.appSettingsDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C,onChange:te=>P(te.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"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.spoolInventory")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.spoolInventoryDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:N,onChange:te=>A(te.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"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.printArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.printArchivesDescription")})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[U?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:U.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[n("backup.lastBackupAt")," ",Gh(U.last_backup_at,"system",n)]}),a.jsx(h3,{status:U.last_backup_status})]}):a.jsx("span",{children:n("backup.noBackupsYet")})}),U.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(Qn,{className:"w-3 h-3 inline mr-1"}),n("backup.next")," ",Gh(U.next_scheduled_run,"system",n)]})]}),G&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${G.success?"text-green-400":"text-red-400"}`,children:[G.success?a.jsx(xr,{className:"w-4 h-4"}):a.jsx(Na,{className:"w-4 h-4"}),G.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:U?.configured?a.jsx(a.Fragment,{children:Me.isPending||U.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:U.progress||n("backup.startingBackup")})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"primary",size:"sm",onClick:()=>Me.mutate(),disabled:!pe?.enabled,children:[a.jsx($i,{className:"w-4 h-4"}),n("backup.backupNow")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Ke,disabled:V,children:[V?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),n("backup.test")]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"primary",size:"sm",onClick:tt,disabled:Te.isPending||!r||!s,children:[Te.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(xr,{className:"w-4 h-4"}),n("backup.enableBackup")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Ke,disabled:V||!r||!s,children:[V?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),n("backup.testConnection")]})]})})]})]})]}),R&&R.length>0&&a.jsxs(At,{id:"card-backup-history",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(B0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.history")})]}),a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:()=>Be.mutate(),disabled:Be.isPending,children:[a.jsx(rn,{className:"w-4 h-4"}),n("backup.clear")]})]})}),a.jsx(Mt,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.date")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.status")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.commit")})]})}),a.jsx("tbody",{children:R.slice(0,10).map(te=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:m3(te.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(h3,{status:te.status})}),a.jsx("td",{className:"py-2 px-2",children:te.commit_sha?a.jsxs("a",{href:`${pe?.repository_url}/commit/${te.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[te.commit_sha.substring(0,7),a.jsx(na,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},te.id))})]})})})]})]}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs(At,{id:"card-backup-local",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Kl,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.localBackup")})]})}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.localBackupDescription")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.downloadBackupLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.completeBackupZip")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",disabled:k||H,onClick:async()=>{D(!0),L(n("backup.preparingBackup"));try{L(n("backup.creatingArchive"));const{blob:te,filename:Ie}=await me.exportBackup();L(n("backup.downloadingFile"));const be=URL.createObjectURL(te),$e=document.createElement("a");$e.href=be,$e.download=Ie,$e.click(),URL.revokeObjectURL(be),e(n("backup.backupDownloaded"))}catch(te){e(n("backup.failedToCreateBackup",{message:te instanceof Error?te.message:"Unknown error"}),"error")}finally{D(!1),L("")}},children:[a.jsx(ca,{className:"w-4 h-4"}),n("backup.download")]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:W,type:"file",accept:".zip",className:"hidden",onChange:te=>{const Ie=te.target.files?.[0];Ie&&(ue(Ie),ie(!0)),te.target.value=""}}),a.jsxs(Fe,{variant:"secondary",size:"sm",disabled:H||k,onClick:()=>W.current?.click(),children:[a.jsx(Ma,{className:"w-4 h-4"}),n("backup.restore")]})]}),le&&a.jsx("div",{className:`p-3 rounded-lg ${le.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[le.success?a.jsx(xr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx(Na,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:le.success?"text-green-200":"text-red-200",children:[le.message,le.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Fe,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(eo,{className:"w-3 h-3"}),n("backup.reloadNow")]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:n("backup.restoreReplacesAll")})," ",a.jsx("span",{className:"text-yellow-200/70",children:n("backup.restoreReplacesAllDetail")})]})]})})]})]}),a.jsxs(At,{id:"card-backup-scheduled",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sge,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.scheduledBackup")})]}),a.jsx(zn,{checked:E?.enabled??!1,onChange:async te=>{try{await me.updateSettings({local_backup_enabled:te}),e(n("backup.settingsSaved"))}catch(Ie){e(n("backup.failedToSave",{message:Ie instanceof Error?Ie.message:"Unknown error"}),"error")}j()}})]})}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.scheduledBackupDescription")}),E?.enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.frequency")}),a.jsxs("select",{value:E?.schedule??"daily",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",onChange:async te=>{try{await me.updateSettings({local_backup_schedule:te.target.value}),e(n("backup.settingsSaved"))}catch(Ie){e(n("backup.failedToSave",{message:Ie instanceof Error?Ie.message:"Unknown error"}),"error")}j()},children:[a.jsx("option",{value:"hourly",children:n("backup.hourly")}),a.jsx("option",{value:"daily",children:n("backup.daily")}),a.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]}),(E?.schedule??"daily")!=="hourly"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.backupTime")}),a.jsx("input",{type:"time",value:E?.time??"03:00",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 [color-scheme:dark]",onChange:async te=>{try{await me.updateSettings({local_backup_time:te.target.value}),e(n("backup.settingsSaved"))}catch(Ie){e(n("backup.failedToSave",{message:Ie instanceof Error?Ie.message:"Unknown error"}),"error")}j()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.utc")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.retention")}),a.jsx("input",{type:"number",min:1,max:100,value:E?.retention??5,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",onChange:async te=>{const Ie=Math.max(1,Math.min(100,parseInt(te.target.value)||5));try{await me.updateSettings({local_backup_retention:Ie}),e(n("backup.settingsSaved"))}catch(be){e(n("backup.failedToSave",{message:be instanceof Error?be.message:"Unknown error"}),"error")}j()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.retentionDescription")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.outputPath")}),a.jsx("input",{type:"text",value:$,onChange:te=>Y(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",onBlur:async()=>{try{await me.updateSettings({local_backup_path:$}),e(n("backup.settingsSaved"))}catch(te){e(n("backup.failedToSave",{message:te instanceof Error?te.message:"Unknown error"}),"error")}j(),K()},onKeyDown:te=>{te.key==="Enter"&&te.target.blur()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:$?n("backup.outputPathDescription"):a.jsxs(a.Fragment,{children:[n("backup.defaultPathLabel")," ",a.jsx("code",{className:"text-bambu-gray",children:E?.default_path||"..."})]})})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"text-sm",children:[E?.last_backup_at&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsxs("span",{children:[n("backup.lastBackup"),":"]}),a.jsx(h3,{status:E.last_status}),a.jsx("span",{children:Gh(E.last_backup_at)})]}),E?.next_run&&a.jsxs("div",{className:"text-bambu-gray mt-1",children:[a.jsxs("span",{children:[n("backup.nextBackup"),": "]}),a.jsx("span",{children:m3(E.next_run)})]})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",disabled:E?.is_running||B.isPending,onClick:()=>B.mutate(),children:[E?.is_running||B.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx($i,{className:"w-4 h-4"}),E?.is_running?n("backup.backupRunning"):n("backup.runNow")]})]}),O&&O.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:n("backup.backupFiles")}),a.jsx("div",{className:"space-y-1",children:O.map(te=>a.jsxs("div",{className:"flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-white truncate block",children:te.filename}),a.jsxs("span",{className:"text-bambu-gray text-xs",children:[(te.size/1024/1024).toFixed(1)," MB · ",m3(te.created_at)]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{className:"text-bambu-gray hover:text-bambu-green p-1",title:n("backup.download"),onClick:async()=>{try{const{blob:Ie,filename:be}=await me.downloadLocalBackup(te.filename),$e=URL.createObjectURL(Ie),He=document.createElement("a");He.href=$e,He.download=be,He.click(),URL.revokeObjectURL($e)}catch{e(n("backup.scheduledBackupFailed"),"error")}},children:a.jsx(ca,{className:"w-3.5 h-3.5"})}),a.jsx("button",{className:"text-bambu-gray hover:text-yellow-400 p-1",title:n("backup.restore"),onClick:()=>Ne(te.filename),children:a.jsx(eo,{className:"w-3.5 h-3.5"})}),a.jsx("button",{className:"text-bambu-gray hover:text-red-400 p-1",onClick:()=>ce(te.filename),title:n("backup.deleteBackup"),children:a.jsx(rn,{className:"w-3.5 h-3.5"})})]})]},te.filename))})]}),O&&O.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary",children:n("backup.noScheduledBackups")})]})]})]})]}),re&&a.jsx(_n,{title:n("backup.deleteBackup"),message:n("backup.deleteBackupConfirm"),confirmText:n("backup.deleteBackup"),variant:"danger",onConfirm:()=>he.mutate(re),onCancel:()=>ce(null)}),xe&&a.jsx(_n,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:xe}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:()=>I.mutate(xe),onCancel:()=>Ne(null)}),ne&&ee&&a.jsx(_n,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:ee.name}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{ie(!1),z(!0),oe(null);try{L(n("backup.uploadingFile"));const te=await me.importBackup(ee);oe(te),te.success?e(n("backup.backupRestoredRestart"),"success"):e(te.message,"error")}catch(te){const Ie=te instanceof Error?te.message:n("backup.failedToRestore");oe({success:!1,message:Ie}),e(Ie,"error")}finally{z(!1),L(""),ue(null)}},onCancel:()=>{ie(!1),ue(null)}}),(k||H)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.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:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:n(k?"backup.creatingBackup":"backup.restoringBackup")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:X||n(k?"backup.preparing":"backup.processing")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:n("backup.doNotClosePage")})]})})]})})]})}function cnt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("medium"),[d,u]=w.useState("notify"),[m,p]=w.useState(10),[f,x]=w.useState(null),[v,g]=w.useState(null),[b,_]=w.useState(!1),{data:C}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:P,refetch:N}=Qe({queryKey:["obico-status"],queryFn:me.getObicoStatus,refetchInterval:1e4}),{data:A}=Qe({queryKey:["printers"],queryFn:me.getPrinters});w.useEffect(()=>{if(C){i(C.obico_enabled??!1),o(C.obico_ml_url??""),c(C.obico_sensitivity??"medium"),u(C.obico_action??"notify"),p(C.obico_poll_interval??10);try{const D=C.obico_enabled_printers?JSON.parse(C.obico_enabled_printers):null;x(Array.isArray(D)?D:null)}catch{x(null)}_(!0)}},[C]);const T=it({mutationFn:()=>me.updateSettings({obico_enabled:r,obico_ml_url:s,obico_sensitivity:l,obico_action:d,obico_poll_interval:m,obico_enabled_printers:f===null?"":JSON.stringify(f)}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),e.invalidateQueries({queryKey:["obico-status"]}),n(t("settings.toast.settingsSaved"))}});w.useEffect(()=>{if(!b||!C||!(C.obico_enabled!==r||C.obico_ml_url!==s||C.obico_sensitivity!==l||C.obico_action!==d||C.obico_poll_interval!==m||C.obico_enabled_printers!==(f===null?"":JSON.stringify(f))))return;const H=setTimeout(()=>T.mutate(),500);return()=>clearTimeout(H)},[r,s,l,d,m,f,b]);const F=async()=>{g(null);try{const D=await me.testObicoConnection(s);D.ok?g({ok:!0,message:t("failureDetection.testSuccess")}):g({ok:!1,message:D.error||`HTTP ${D.status_code??"?"} — ${D.body??t("failureDetection.testFailed")}`})}catch(D){g({ok:!1,message:D instanceof Error?D.message:String(D)})}},k=(D,H)=>{if(f===null){const z=A?.map(L=>L.id)??[],X=H?z:z.filter(L=>L!==D);x(X);return}x(H?[...f,D]:f.filter(z=>z!==D))};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(At,{id:"card-fd-ml",children:[a.jsxs(wn,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(DQ,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.title")})]}),a.jsx(zn,{checked:r,onChange:i})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:t("failureDetection.description")})]}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.mlUrl")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:s,onChange:D=>o(D.target.value),placeholder:"http://192.168.1.10:3333",className:"flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",disabled:!r}),a.jsx(Fe,{onClick:F,disabled:!s||T.isPending,variant:"secondary",children:t("failureDetection.test")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.mlUrlHint")}),v&&a.jsxs("div",{className:`flex items-start gap-2 mt-2 text-sm ${v.ok?"text-green-400":"text-red-400"}`,children:[v.ok?a.jsx(Rr,{className:"w-4 h-4 mt-0.5"}):a.jsx(Bt,{className:"w-4 h-4 mt-0.5"}),a.jsx("span",{children:v.message})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.sensitivity")}),a.jsxs("select",{value:l,onChange:D=>c(D.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"low",children:t("failureDetection.sensitivityLow")}),a.jsx("option",{value:"medium",children:t("failureDetection.sensitivityMedium")}),a.jsx("option",{value:"high",children:t("failureDetection.sensitivityHigh")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.sensitivityHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.action")}),a.jsxs("select",{value:d,onChange:D=>u(D.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"notify",children:t("failureDetection.actionNotify")}),a.jsx("option",{value:"pause",children:t("failureDetection.actionPause")}),a.jsx("option",{value:"pause_and_off",children:t("failureDetection.actionPauseOff")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.pollInterval")}),a.jsx("input",{type:"number",value:m,onChange:D=>p(Math.max(5,Math.min(120,Number(D.target.value)||10))),min:5,max:120,disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.pollIntervalHint")})]}),P&&!P.external_url_configured&&r&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-900/30 border border-amber-700 rounded text-sm text-amber-200",children:[a.jsx(Rn,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:t("failureDetection.externalUrlMissing")}),a.jsx("div",{className:"text-xs mt-1",children:t("failureDetection.externalUrlHint")})]})]})]})]}),a.jsxs(At,{id:"card-fd-perprinter",children:[a.jsxs(wn,{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.perPrinterTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("failureDetection.perPrinterHint")})]}),a.jsxs(Mt,{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[a.jsx("input",{type:"checkbox",checked:f===null,onChange:D=>x(D.target.checked?null:A?.map(H=>H.id)??[]),disabled:!r}),a.jsx("span",{className:"text-white",children:t("failureDetection.monitorAll")})]}),f!==null&&A&&a.jsx("div",{className:"pl-5 space-y-1 border-l border-gray-700",children:A.map(D=>a.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[a.jsx("input",{type:"checkbox",checked:f.includes(D.id),onChange:H=>k(D.id,H.target.checked),disabled:!r}),a.jsx("span",{className:"text-white",children:D.name})]},D.id))})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(At,{id:"card-fd-status",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.statusTitle")})}),a.jsx(Mt,{children:P?a.jsxs("div",{className:"space-y-3 text-sm",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.serviceRunning")}),a.jsx("span",{className:P.is_running?"text-green-400":"text-red-400",children:P.is_running?t("common.yes"):t("common.no")})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.thresholds")}),a.jsxs("span",{className:"text-white font-mono",children:[P.thresholds.low.toFixed(2)," / ",P.thresholds.high.toFixed(2)]})]}),P.last_error&&a.jsxs("div",{className:"flex items-start gap-2 text-red-400",children:[a.jsx(Bt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),a.jsx("span",{className:"break-words",children:P.last_error})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray mb-1",children:t("failureDetection.activePrinters")}),Object.keys(P.per_printer).length===0?a.jsx("div",{className:"text-bambu-gray italic text-xs",children:t("failureDetection.noActivePrints")}):a.jsx("div",{className:"space-y-1",children:Object.entries(P.per_printer).map(([D,H])=>{const z=A?.find(L=>String(L.id)===D),X=H.class==="failure"?"text-red-400":H.class==="warning"?"text-amber-400":"text-green-400";return a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-white",children:z?.name??`Printer ${D}`}),a.jsxs("span",{className:`font-mono ${X}`,children:[H.class," (",H.score.toFixed(3),", ",H.frame_count,"f)"]})]},D)})})]})]}):a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:t("common.loading")})]})})]}),a.jsxs(At,{id:"card-fd-history",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.historyTitle")}),a.jsx("button",{onClick:()=>N(),className:"text-xs text-bambu-gray hover:text-white",children:t("common.refresh")})]})}),a.jsx(Mt,{children:!P||P.history.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(fs,{className:"w-4 h-4"}),a.jsx("span",{children:t("failureDetection.noHistory")})]}):a.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto text-xs font-mono",children:P.history.map((D,H)=>{const z=A?.find(L=>L.id===D.printer_id),X=D.class==="failure"?"text-red-400":D.class==="warning"?"text-amber-400":"text-bambu-gray";return a.jsxs("div",{className:"flex justify-between gap-2 py-1 border-b border-gray-800",children:[a.jsx("span",{className:"text-bambu-gray",children:new Date(D.timestamp).toLocaleTimeString()}),a.jsx("span",{className:"text-white truncate",children:z?.name??`#${D.printer_id}`}),a.jsxs("span",{className:X,children:[D.class," ",D.score.toFixed(3)]})]},H)})})})]})]})]})}const dnt={starttls:587,ssl:465,none:25},unt={587:"starttls",465:"ssl",25:"none"};function mnt(){const{t}=Rt(),{showToast:e}=bn(),n=sn(),[r,i]=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}=Qe({queryKey:["smtpSettings"],queryFn:()=>me.getSMTPSettings()}),{authEnabled:d}=wr(),{data:u}=Qe({queryKey:["advancedAuthStatus"],queryFn:()=>me.getAdvancedAuthStatus()});w.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=T=>{i({...r,smtp_security:T,smtp_port:dnt[T]})},p=T=>{const F=unt[T];i({...r,smtp_port:T,...F?{smtp_security:F}:{}})},f=T=>{i({...r,smtp_auth_enabled:T,...T?{}:{smtp_username:"",smtp_password:""}})},x=it({mutationFn:T=>me.saveSMTPSettings(T),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:T=>{e(T.message,"error")}}),v=it({mutationFn:T=>me.testSMTP(T),onSuccess:T=>{e(T.message,T.success?"success":"error")},onError:T=>{e(T.message,"error")}}),g=it({mutationFn:T=>T?me.enableAdvancedAuth():me.disableAdvancedAuth(),onSuccess:T=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(T.message,"success")},onError:T=>{e(T.message,"error")}}),b=()=>{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}x.mutate(r)},_=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}v.mutate({test_recipient:s})},C=()=>{if(!d){e(t("settings.email.errors.enableAuthFirst"),"error");return}if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}g.mutate(!u?.advanced_auth_enabled)};if(c)return a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})});const P=u?.advanced_auth_enabled??!1,N="w-full px-3 py-2 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-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return a.jsxs("div",{className:"space-y-3",children:[a.jsxs(At,{id:"card-email-advanced-auth",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(am,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Fe,{onClick:C,disabled:g.isPending,variant:P?"danger":"primary",children:P?a.jsxs(a.Fragment,{children:[a.jsx(u0,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(pd,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Mt,{children:a.jsx("div",{className:"space-y-3",children:P?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(xr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Rn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsx("div",{className:"lg:col-span-2",children:a.jsxs(At,{id:"card-smtp-config",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Mt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:T=>f(T.target.value==="true"),className:N,children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),a.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:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:T=>i({...r,smtp_username:T.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:A})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:T=>i({...r,smtp_password:T.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:A})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:T=>i({...r,smtp_host:T.target.value}),placeholder:"smtp.gmail.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:T=>p(parseInt(T.target.value)||587),placeholder:"587",className:N})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:T=>m(T.target.value),className:N,children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:T=>i({...r,smtp_from_email:T.target.value}),placeholder:"your@email.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:T=>i({...r,smtp_from_name:T.target.value}),placeholder:"BamBuddy",className:N})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Fe,{onClick:b,disabled:x.isPending,className:"flex-1",children:x.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),a.jsx("div",{children:a.jsxs(At,{id:"card-email-test",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Mt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:T=>o(T.target.value),placeholder:"test@example.com",className:N})]}),a.jsx(Fe,{onClick:_,disabled:v.isPending,variant:"secondary",children:v.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Bw,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const hnt={starttls:"389",ldaps:"636"};function pnt(){const{t}=Rt(),{showToast:e}=bn(),n=sn(),{authEnabled:r}=wr(),[i,s]=w.useState({ldap_server_url:"",ldap_bind_dn:"",ldap_bind_password:"",ldap_search_base:"",ldap_user_filter:"(sAMAccountName={username})",ldap_security:"starttls",ldap_group_mapping:"",ldap_auto_provision:!1,ldap_default_group:""}),{data:o,isLoading:l}=Qe({queryKey:["settings"],queryFn:()=>me.getSettings()}),{data:c}=Qe({queryKey:["ldapStatus"],queryFn:()=>me.getLDAPStatus()}),{data:d=[]}=Qe({queryKey:["groups"],queryFn:()=>me.getGroups()});w.useEffect(()=>{o&&s({ldap_server_url:o.ldap_server_url||"",ldap_bind_dn:o.ldap_bind_dn||"",ldap_bind_password:"",ldap_search_base:o.ldap_search_base||"",ldap_user_filter:o.ldap_user_filter||"(sAMAccountName={username})",ldap_security:o.ldap_security||"starttls",ldap_group_mapping:o.ldap_group_mapping||"",ldap_auto_provision:o.ldap_auto_provision??!1,ldap_default_group:o.ldap_default_group||""})},[o]);const u=it({mutationFn:b=>me.updateSettings(b),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(t("settings.ldap.settingsSaved")||"LDAP settings saved","success")},onError:b=>{e(b.message,"error")}}),m=it({mutationFn:b=>me.updateSettings({ldap_enabled:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(c?.ldap_enabled?t("settings.ldap.disabled")||"LDAP authentication disabled":t("settings.ldap.enabled")||"LDAP authentication enabled","success")},onError:b=>{e(b.message,"error")}}),p=it({mutationFn:()=>me.testLDAP(),onSuccess:b=>{e(b.message,b.success?"success":"error")},onError:b=>{e(b.message,"error")}}),f=()=>{if(!i.ldap_server_url){e(t("settings.ldap.errors.serverRequired")||"LDAP server URL is required","error");return}if(!i.ldap_search_base){e(t("settings.ldap.errors.searchBaseRequired")||"Search base DN is required","error");return}const b={ldap_server_url:i.ldap_server_url,ldap_bind_dn:i.ldap_bind_dn,ldap_search_base:i.ldap_search_base,ldap_user_filter:i.ldap_user_filter,ldap_security:i.ldap_security,ldap_group_mapping:i.ldap_group_mapping,ldap_auto_provision:i.ldap_auto_provision,ldap_default_group:i.ldap_default_group};i.ldap_bind_password&&(b.ldap_bind_password=i.ldap_bind_password),u.mutate(b)},x=()=>{if(!r){e(t("settings.ldap.errors.enableAuthFirst")||"Enable authentication first","error");return}if(!c?.ldap_enabled&&!c?.ldap_configured){e(t("settings.ldap.errors.configureLdapFirst")||"Save LDAP settings first","error");return}m.mutate(!c?.ldap_enabled)};if(l)return a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})});const v=c?.ldap_enabled??!1,g="w-full px-3 py-2 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";return a.jsxs("div",{className:"space-y-3",children:[a.jsxs(At,{id:"card-ldap-toggle",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Du,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.title")||"LDAP Authentication"})]}),a.jsx(Fe,{onClick:x,disabled:m.isPending,variant:v?"danger":"primary",children:v?a.jsxs(a.Fragment,{children:[a.jsx(u0,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(pd,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),a.jsx(Mt,{children:v?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(xr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.enabledDesc")||"LDAP authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.ldap.feature1")||"Users can login with LDAP credentials"}),a.jsx("li",{children:t("settings.ldap.feature2")||"Local admin account remains as fallback"}),a.jsx("li",{children:t("settings.ldap.feature3")||"LDAP groups are mapped to BamBuddy groups on login"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Rn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.disabledDesc")||"LDAP authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300 mt-1",children:t("settings.ldap.disabledHint")||"Configure and save LDAP settings below, then enable."})]})]})})})]}),a.jsxs(At,{id:"card-ldap-server",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),a.jsx(Mt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[a.jsxs("div",{className:"md:col-span-2",children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.serverUrl")||"Server URL"}),a.jsx("input",{type:"text",className:g,placeholder:"ldaps://ldap.example.com:636",value:i.ldap_server_url,onChange:b=>s({...i,ldap_server_url:b.target.value})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.serverUrlHint")||"Use ldaps:// for SSL or ldap:// with StartTLS"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.security")||"Security"}),a.jsx("div",{className:"flex gap-2",children:["starttls","ldaps"].map(b=>a.jsx("button",{onClick:()=>s({...i,ldap_security:b}),className:`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${i.ldap_security===b?"bg-bambu-green text-black":"bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:b==="starttls"?"StartTLS":"LDAPS"},b))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.securityHint")||`Default port: ${hnt[i.ldap_security]}`})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindDn")||"Bind DN (Service Account)"}),a.jsx("input",{type:"text",className:g,placeholder:"cn=service-account,ou=service,dc=example,dc=com",value:i.ldap_bind_dn,onChange:b=>s({...i,ldap_bind_dn:b.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindPassword")||"Bind Password"}),a.jsx("input",{type:"password",className:g,placeholder:o?.ldap_bind_dn?"••••••••":"",value:i.ldap_bind_password,onChange:b=>s({...i,ldap_bind_password:b.target.value})})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.searchBase")||"Search Base DN"}),a.jsx("input",{type:"text",className:g,placeholder:"ou=users,dc=example,dc=com",value:i.ldap_search_base,onChange:b=>s({...i,ldap_search_base:b.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.userFilter")||"User Search Filter"}),a.jsx("input",{type:"text",className:g,placeholder:"(sAMAccountName={username})",value:i.ldap_user_filter,onChange:b=>s({...i,ldap_user_filter:b.target.value})})]})]}),a.jsx(kle,{summary:a.jsx("span",{className:"text-sm font-medium text-bambu-gray",children:t("settings.ldap.advanced")||"Advanced"}),className:"border-t border-bambu-dark-tertiary pt-3",summaryClassName:"py-1",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white",children:t("settings.ldap.autoProvision")||"Auto-provision users"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:t("settings.ldap.autoProvisionHint")||"Automatically create a BamBuddy account on first LDAP login"})]}),a.jsx("button",{onClick:()=>s({...i,ldap_auto_provision:!i.ldap_auto_provision}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${i.ldap_auto_provision?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.ldap_auto_provision?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.defaultGroup")||"Default group"}),a.jsxs("select",{className:g,value:i.ldap_default_group,onChange:b=>s({...i,ldap_default_group:b.target.value}),children:[a.jsx("option",{value:"",children:t("settings.ldap.defaultGroupNone")||"— None (reject login) —"}),d.map(b=>a.jsx("option",{value:b.name,children:b.name},b.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.defaultGroupHint")||"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped group. Leave empty to leave unmapped users without permissions."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.groupMapping")||"Group Mapping (JSON)"}),a.jsx("textarea",{className:`${g} font-mono text-sm`,rows:4,placeholder:`{
- "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",
- "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"
- }`,value:i.ldap_group_mapping,onChange:b=>s({...i,ldap_group_mapping:b.target.value})}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[t("settings.ldap.groupMappingHint")||"Map LDAP group DNs to BamBuddy groups. Available groups: ",d.map(b=>b.name).join(", ")]})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsxs(Fe,{onClick:f,disabled:u.isPending,children:[u.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(xr,{className:"w-4 h-4"}),t("common.save")||"Save"]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Bw,{className:"w-4 h-4"}),t("settings.ldap.testConnection")||"Test Connection"]})]})]})})]})]})}function Xk({value:t,onChange:e,placeholder:n,maxLength:r=6}){return a.jsx("input",{type:"text",value:t,onChange:i=>e(i.target.value.toUpperCase().replace(/\s/g,"")),maxLength:r,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 font-mono tracking-widest text-center",placeholder:n,autoComplete:"one-time-code"})}function Nle({codes:t,onDone:e}){const{t:n}=Rt(),[r,i]=w.useState(!1),s=()=>{navigator.clipboard.writeText(t.join(`
- `)),i(!0),setTimeout(()=>i(!1),2e3)};return a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-4",children:a.jsx("p",{className:"text-amber-400 text-sm font-medium",children:n("settings.twoFa.backupCodesWarning")})}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map((o,l)=>a.jsx("code",{className:"bg-bambu-dark-secondary rounded px-3 py-2 text-center font-mono text-sm text-white tracking-widest",children:o},l))}),a.jsxs("div",{className:"flex gap-3",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:s,className:"flex items-center gap-2",children:[a.jsx(Fs,{className:"w-4 h-4"}),n(r?"common.copied":"common.copy")]}),a.jsx(Fe,{variant:"primary",size:"sm",onClick:e,className:"flex-1",children:n("settings.twoFa.savedCodes")})]})]})}function fnt({onDone:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=bn(),[i,s]=w.useState("qr"),[o,l]=w.useState(""),[c,d]=w.useState([]),[u,m]=w.useState(!1),{data:p,isLoading:f}=Qe({queryKey:["totp-setup"],queryFn:()=>me.setupTOTP(),staleTime:1/0}),x=it({mutationFn:v=>me.enableTOTP(v),onSuccess:v=>{d(v.backup_codes),s("backup"),n.invalidateQueries({queryKey:["2fa-status"]})},onError:()=>r(e("settings.twoFa.invalidCode"),"error")});return f||!p?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(cr,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i==="qr"?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:e("settings.twoFa.setupInstructions")}),a.jsx("div",{className:"flex justify-center",children:a.jsx("img",{src:`data:image/png;base64,${p.qr_code_b64}`,alt:"TOTP QR Code",className:"w-48 h-48 rounded-lg"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:e("settings.twoFa.manualEntry")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark-secondary rounded-lg px-3 py-2",children:[a.jsx("code",{className:"text-white text-xs font-mono flex-1 break-all",children:u?p.secret:"••••••••••••••••"}),a.jsx("button",{onClick:()=>m(!u),className:"text-bambu-gray hover:text-white",children:u?a.jsx(vg,{className:"w-4 h-4"}):a.jsx(ul,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{navigator.clipboard.writeText(p.secret)},className:"text-bambu-gray hover:text-white",children:a.jsx(Fs,{className:"w-4 h-4"})})]})]}),a.jsx(Fe,{variant:"primary",className:"w-full",onClick:()=>s("confirm"),children:e("settings.twoFa.scannedContinue")})]}):i==="confirm"?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:e("settings.twoFa.enterCodeToConfirm")}),a.jsx(Xk,{value:o,onChange:l,placeholder:"000000"}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>s("qr"),className:"flex-1",children:e("common.back")}),a.jsx(Fe,{variant:"primary",className:"flex-1",disabled:o.length!==6||x.isPending,onClick:()=>x.mutate(o),children:x.isPending?e("common.saving"):e("settings.twoFa.activate")})]})]}):a.jsxs("div",{className:"space-y-4",children:[a.jsx("h3",{className:"text-white font-medium",children:e("settings.twoFa.backupCodesTitle")}),a.jsx(Nle,{codes:c,onDone:t})]})}function gnt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{user:r}=wr(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(""),[x,v]=w.useState(null),[g,b]=w.useState(null),[_,C]=w.useState(""),[P,N]=w.useState(!1),[A,T]=w.useState(""),[F,k]=w.useState(!1),{data:D,isLoading:H}=Qe({queryKey:["2fa-status"],queryFn:()=>me.get2FAStatus()}),{data:z}=Qe({queryKey:["oidc-links"],queryFn:()=>me.getOIDCLinks()}),X=it({mutationFn:()=>me.enableEmailOTP(),onSuccess:oe=>{b(oe.setup_token),n(oe.message,"success")},onError:oe=>{const W=oe.message??"";W.toLowerCase().includes("smtp")?n(t("settings.twoFa.smtpRequired"),"error"):n(W,"error")}}),L=it({mutationFn:()=>me.confirmEnableEmailOTP(g,_),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),b(null),C(""),n(t("settings.twoFa.emailOtpEnabled"),"success")},onError:oe=>n(oe.message,"error")}),ne=it({mutationFn:oe=>me.disableEmailOTP(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),N(!1),T(""),n(t("settings.twoFa.emailOtpDisabled"),"success")},onError:oe=>n(oe.message,"error")}),ie=it({mutationFn:oe=>me.disableTOTP(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),l(!1),m(""),n(t("settings.twoFa.totpDisabled"),"success")},onError:()=>n(t("settings.twoFa.invalidCode"),"error")}),ee=it({mutationFn:oe=>me.regenerateBackupCodes(oe),onSuccess:oe=>{e.invalidateQueries({queryKey:["2fa-status"]}),d(!1),f(""),v(oe.backup_codes)},onError:()=>n(t("settings.twoFa.invalidCode"),"error")}),ue=it({mutationFn:oe=>me.deleteOIDCLink(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-links"]}),n(t("settings.twoFa.oidcUnlinked"),"success")},onError:oe=>n(oe.message,"error")});if(H)return a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(cr,{className:"w-6 h-6 animate-spin text-bambu-green"})});const le=!!r?.email;return a.jsxs("div",{className:"space-y-6",children:[a.jsxs(At,{id:"card-2fa-totp",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${D?.totp_enabled?"bg-green-500/20":"bg-gray-500/20"}`,children:a.jsx(Y3,{className:`w-5 h-5 ${D?.totp_enabled?"text-green-400":"text-gray-400"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.totpTitle")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.twoFa.totpDesc")})]}),a.jsx("div",{className:"ml-auto",children:D?.totp_enabled?a.jsxs("span",{className:"flex items-center gap-1 text-green-400 text-sm font-medium",children:[a.jsx(yH,{className:"w-4 h-4"})," ",t("common.enabled")]}):a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray text-sm",children:[a.jsx(vH,{className:"w-4 h-4"})," ",t("common.disabled")]})})]})}),a.jsx(Mt,{children:i?a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("h4",{className:"text-white font-medium",children:t("settings.twoFa.setupAuthApp")}),a.jsx("button",{onClick:()=>{s(!1),e.removeQueries({queryKey:["totp-setup"]})},className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx(fnt,{onDone:()=>{s(!1),e.removeQueries({queryKey:["totp-setup"]})}})]}):o?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.disableConfirmHint")}),a.jsx(Xk,{value:u,onChange:m,placeholder:"000000 or XXXXXXXX",maxLength:8}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{l(!1),m("")},className:"flex-1",children:t("common.cancel")}),a.jsx(Fe,{variant:"danger",className:"flex-1",disabled:u.length<6||ie.isPending,onClick:()=>ie.mutate(u),children:ie.isPending?t("common.saving"):t("settings.twoFa.disableTotp")})]})]}):c?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.regenBackupHint")}),a.jsx(Xk,{value:p,onChange:f,placeholder:"000000 or XXXXXXXX",maxLength:8}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{d(!1),f("")},className:"flex-1",children:t("common.cancel")}),a.jsx(Fe,{variant:"primary",className:"flex-1",disabled:p.length<6||ee.isPending,onClick:()=>ee.mutate(p),children:ee.isPending?t("common.saving"):t("settings.twoFa.regenBackup")})]})]}):x?a.jsxs("div",{className:"space-y-4",children:[a.jsx("h4",{className:"text-white font-medium",children:t("settings.twoFa.newBackupCodes")}),a.jsx(Nle,{codes:x,onDone:()=>v(null)})]}):a.jsx("div",{className:"space-y-3",children:D?.totp_enabled?a.jsxs("div",{className:"flex flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray-light",children:[a.jsx(Ws,{className:"w-4 h-4"}),t("settings.twoFa.backupCodesRemaining",{count:D.backup_codes_remaining})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>d(!0),className:"flex items-center gap-2",children:[a.jsx(cr,{className:"w-4 h-4"}),t("settings.twoFa.regenBackup")]}),a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>l(!0),className:"flex items-center gap-2",children:[a.jsx(rn,{className:"w-4 h-4"}),t("settings.twoFa.disableTotp")]})]}):a.jsxs(Fe,{variant:"primary",onClick:()=>s(!0),className:"flex items-center gap-2",children:[a.jsx(Y3,{className:"w-4 h-4"}),t("settings.twoFa.setupTotp")]})})})]}),a.jsxs(At,{id:"card-2fa-emailotp",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${D?.email_otp_enabled?"bg-green-500/20":"bg-gray-500/20"}`,children:a.jsx(am,{className:`w-5 h-5 ${D?.email_otp_enabled?"text-green-400":"text-gray-400"}`})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.emailOtpTitle")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:le?t("settings.twoFa.emailOtpDesc",{email:r?.email}):t("settings.twoFa.emailOtpNoEmail")})]}),a.jsx("div",{className:"ml-auto",children:D?.email_otp_enabled?a.jsxs("span",{className:"flex items-center gap-1 text-green-400 text-sm font-medium",children:[a.jsx(yH,{className:"w-4 h-4"})," ",t("common.enabled")]}):a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray text-sm",children:[a.jsx(vH,{className:"w-4 h-4"})," ",t("common.disabled")]})})]})}),a.jsx(Mt,{children:le?g?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.emailSetupEnterCode")}),a.jsx(Xk,{value:_,onChange:C,placeholder:"000000"}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{b(null),C("")},className:"flex-1",children:t("common.cancel")}),a.jsx(Fe,{variant:"primary",className:"flex-1",disabled:_.length!==6||L.isPending,onClick:()=>L.mutate(),children:L.isPending?t("common.saving"):t("settings.twoFa.verifyAndEnable")})]})]}):P?a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.emailDisablePasswordHint")}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:F?"text":"password",value:A,onChange:oe=>T(oe.target.value),placeholder:t("settings.twoFa.passwordPlaceholder"),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"}),a.jsx("button",{type:"button",onClick:()=>k(!F),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:F?a.jsx(vg,{className:"w-5 h-5"}):a.jsx(ul,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{N(!1),T("")},className:"flex-1",children:t("common.cancel")}),a.jsx(Fe,{variant:"danger",className:"flex-1",disabled:!A||ne.isPending,onClick:()=>ne.mutate(A),children:ne.isPending?t("common.saving"):t("settings.twoFa.disableEmailOtp")})]})]}):a.jsx("div",{className:"flex gap-3",children:D?.email_otp_enabled?a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>N(!0),className:"flex items-center gap-2",children:[a.jsx(rn,{className:"w-4 h-4"}),t("settings.twoFa.disableEmailOtp")]}):a.jsxs(Fe,{variant:"primary",disabled:!le||X.isPending,onClick:()=>X.mutate(),className:"flex items-center gap-2",children:[a.jsx(am,{className:"w-4 h-4"}),X.isPending?t("common.saving"):t("settings.twoFa.enableEmailOtp")]})}):a.jsx("p",{className:"text-amber-400 text-sm",children:t("settings.twoFa.addEmailFirst")})})]}),z&&z.length>0&&a.jsxs(At,{id:"card-2fa-linked",children:[a.jsxs(wn,{children:[a.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.linkedAccounts")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.twoFa.linkedAccountsDesc")})]}),a.jsx(Mt,{children:a.jsx("div",{className:"space-y-3",children:z.map(oe=>a.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-bambu-dark-tertiary last:border-0",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:oe.provider_name}),oe.provider_email&&a.jsx("p",{className:"text-bambu-gray text-xs",children:oe.provider_email})]}),a.jsx(Fe,{variant:"danger",size:"sm",onClick:()=>ue.mutate(oe.provider_id),disabled:ue.isPending,children:a.jsx(rn,{className:"w-4 h-4"})})]},oe.id))})})]})]})}const bnt={name:"",issuer_url:"",client_id:"",client_secret:"",scopes:"openid email profile",is_enabled:!0,auto_create_users:!1,auto_link_existing_accounts:!1,icon_url:void 0};function uY({initial:t,isEdit:e=!1,onSave:n,onCancel:r,isPending:i}){const{t:s}=Rt(),[o,l]=w.useState(t),[c,d]=w.useState(!1),u=(x,v)=>l(g=>({...g,[x]:v})),m="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 text-sm",p="block text-sm font-medium text-white mb-1",f=()=>{const x={...o};e&&!c&&delete x.client_secret,n(x)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:p,children:[s("settings.oidc.form.name")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{className:m,value:o.name,onChange:x=>u("name",x.target.value),placeholder:"Google"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:p,children:[s("settings.oidc.form.issuerUrl")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{className:m,value:o.issuer_url,onChange:x=>u("issuer_url",x.target.value),placeholder:"https://accounts.google.com"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:p,children:[s("settings.oidc.form.clientId")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{className:m,value:o.client_id,onChange:x=>u("client_id",x.target.value),placeholder:"your-client-id"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:p,children:[s("settings.oidc.form.clientSecret"),!e&&a.jsx("span",{className:"text-red-400",children:" *"}),e&&a.jsxs("span",{className:"text-bambu-gray text-xs ml-1",children:["(",s("settings.oidc.form.secretHint"),")"]})]}),a.jsx("input",{className:m,type:"password",value:c?o.client_secret:"",placeholder:e&&!c?"••••••••":s("settings.oidc.form.secretPlaceholder"),onChange:x=>{d(!0),u("client_secret",x.target.value)}})]}),a.jsxs("div",{children:[a.jsx("label",{className:p,children:s("settings.oidc.form.scopes")}),a.jsx("input",{className:m,value:o.scopes,onChange:x=>u("scopes",x.target.value),placeholder:"openid email profile"})]}),a.jsxs("div",{children:[a.jsx("label",{className:p,children:s("settings.oidc.form.iconUrl")}),a.jsx("input",{className:m,value:o.icon_url??"",onChange:x=>u("icon_url",x.target.value||void 0),placeholder:"https://..."})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-6 pt-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx(zn,{checked:o.is_enabled??!0,onChange:x=>u("is_enabled",x)}),a.jsx("span",{className:"text-white text-sm",children:s("settings.oidc.form.enabled")})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx(zn,{checked:o.auto_create_users??!1,onChange:x=>u("auto_create_users",x)}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm",children:s("settings.oidc.form.autoCreate")}),a.jsx("p",{className:"text-bambu-gray text-xs",children:s("settings.oidc.form.autoCreateDesc")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx(zn,{checked:o.auto_link_existing_accounts??!1,onChange:x=>u("auto_link_existing_accounts",x)}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm",children:s("settings.oidc.form.autoLink")}),a.jsx("p",{className:"text-bambu-gray text-xs",children:s("settings.oidc.form.autoLinkDesc")})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Fe,{variant:"secondary",onClick:r,className:"flex-1",children:s("common.cancel")}),a.jsx(Fe,{variant:"primary",className:"flex-1",disabled:!o.name||!o.issuer_url||!o.client_id||!e&&!o.client_secret||e&&c&&!o.client_secret||i,onClick:f,children:s(i?"common.saving":"common.save")})]})]})}function xnt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),[r,i]=w.useState(!1),[s,o]=w.useState(null),[l,c]=w.useState(null),{data:d,isLoading:u}=Qe({queryKey:["oidc-providers-all"],queryFn:()=>me.getOIDCProvidersAll()}),m=it({mutationFn:v=>me.createOIDCProvider(v),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),i(!1),n(t("settings.oidc.created"),"success")},onError:v=>n(v.message,"error")}),p=it({mutationFn:({id:v,data:g})=>me.updateOIDCProvider(v,g),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),o(null),n(t("settings.oidc.updated"),"success")},onError:v=>n(v.message,"error")}),f=it({mutationFn:v=>me.deleteOIDCProvider(v),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),c(null),n(t("settings.oidc.deleted"),"success")},onError:v=>n(v.message,"error")}),x=v=>p.mutate({id:v.id,data:{is_enabled:!v.is_enabled}});return u?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(cr,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"space-y-6",children:[a.jsxs(At,{id:"card-oidc",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-semibold",children:t("settings.oidc.title")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.oidc.desc")})]}),!r&&a.jsxs(Fe,{variant:"primary",size:"sm",onClick:()=>i(!0),className:"flex items-center gap-2",children:[a.jsx(or,{className:"w-4 h-4"}),t("settings.oidc.addProvider")]})]})}),r&&a.jsx(Mt,{children:a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsx("h4",{className:"text-white font-medium mb-4",children:t("settings.oidc.newProvider")}),a.jsx(uY,{initial:bnt,onSave:v=>m.mutate(v),onCancel:()=>i(!1),isPending:m.isPending})]})})]}),d&&d.length===0&&!r&&a.jsx(At,{id:"card-oidc-empty",children:a.jsx(Mt,{children:a.jsxs("div",{className:"text-center py-8 space-y-3",children:[a.jsx(rl,{className:"w-12 h-12 text-bambu-gray mx-auto"}),a.jsx("p",{className:"text-bambu-gray",children:t("settings.oidc.empty")}),a.jsxs(Fe,{variant:"primary",size:"sm",onClick:()=>i(!0),className:"inline-flex items-center gap-2",children:[a.jsx(or,{className:"w-4 h-4"}),t("settings.oidc.addProvider")]})]})})}),d?.map(v=>a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-3",children:[v.icon_url?a.jsx("img",{src:v.icon_url,alt:v.name,className:"w-8 h-8 rounded object-contain",onError:g=>{g.target.style.display="none"}}):a.jsx("div",{className:"w-8 h-8 rounded-full bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(rl,{className:"w-4 h-4 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h4",{className:"text-white font-medium",children:v.name}),v.is_enabled?a.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400 bg-green-400/10 px-2 py-0.5 rounded-full",children:[a.jsx(Rr,{className:"w-3 h-3"})," ",t("common.enabled")]}):a.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-0.5 rounded-full",children:[a.jsx(Bt,{className:"w-3 h-3"})," ",t("common.disabled")]})]}),a.jsxs("div",{className:"flex items-center gap-1 text-bambu-gray text-xs mt-0.5",children:[a.jsx(na,{className:"w-3 h-3"}),a.jsx("span",{children:v.issuer_url})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(zn,{checked:v.is_enabled,onChange:()=>x(v),disabled:p.isPending}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>o(s===v.id?null:v.id),children:a.jsx(Iu,{className:"w-4 h-4"})}),a.jsx(Fe,{variant:"danger",size:"sm",onClick:()=>c(v),children:a.jsx(rn,{className:"w-4 h-4"})})]})]})}),s===v.id&&a.jsx(Mt,{children:a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsx(uY,{isEdit:!0,initial:{name:v.name,issuer_url:v.issuer_url,client_id:v.client_id,client_secret:"",scopes:v.scopes,is_enabled:v.is_enabled,auto_create_users:v.auto_create_users,auto_link_existing_accounts:v.auto_link_existing_accounts,icon_url:v.icon_url??void 0},onSave:g=>p.mutate({id:v.id,data:g}),onCancel:()=>o(null),isPending:p.isPending})})}),s!==v.id&&a.jsx(Mt,{children:a.jsxs("dl",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-2 text-sm",children:[a.jsxs("div",{children:[a.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.clientId")}),a.jsx("dd",{className:"text-white font-mono truncate",children:v.client_id})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.scopes")}),a.jsx("dd",{className:"text-white",children:v.scopes})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.autoCreate")}),a.jsx("dd",{className:v.auto_create_users?"text-green-400":"text-bambu-gray",children:v.auto_create_users?t("common.yes"):t("common.no")})]}),a.jsxs("div",{children:[a.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.autoLink")}),a.jsx("dd",{className:v.auto_link_existing_accounts?"text-green-400":"text-bambu-gray",children:v.auto_link_existing_accounts?t("common.yes"):t("common.no")})]})]})})]},v.id)),l&&a.jsx(_n,{title:t("settings.oidc.deleteTitle"),message:t("settings.oidc.deleteMessage",{name:l.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:()=>f.mutate(l.id),onCancel:()=>c(null)})]})}const ynt={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 vnt(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function o0(t,e,n=0){if(n>5)return"...";if(e.$ref)return o0(t,vnt(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const s=o0(t,i,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?[o0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,s]of Object.entries(e.properties))r[i]=o0(t,s,n+1);return r}return{};default:return null}}function wnt({path:t,method:e,spec:n,schema:r,apiKey:i}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[d,u]=w.useState(""),[m,p]=w.useState(null),[f,x]=w.useState(!1),[v,g]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const F={};for(const k of n.parameters)k.schema?.default!==void 0&&(F[k.name]=String(k.schema.default));c(k=>({...F,...k}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!d){const F=n.requestBody.content["application/json"].schema,k=o0(r,F);u(JSON.stringify(k,null,2))}},[s,n.requestBody,r,d]);const _=(()=>{const F=[];for(const k of n.parameters||[])if(k.in==="path"||k.required){const D=l[k.name];(D===void 0||D==="")&&F.push(k.name)}return F})(),C=async()=>{if(_.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${_.join(", ")}`,duration:0});return}x(!0),p(null);try{let F=t;const k=new URLSearchParams;for(const oe of n.parameters||[]){const W=l[oe.name];W!==void 0&&W!==""&&(oe.in==="path"?F=F.replace(`{${oe.name}}`,encodeURIComponent(W)):oe.in==="query"&&k.append(oe.name,W))}const D=k.toString(),H=`${F}${D?`?${D}`:""}`,z={"Content-Type":"application/json"};i&&(z["X-API-Key"]=i);const X={method:e.toUpperCase(),headers:z};["post","put","patch"].includes(e)&&d&&(X.body=d);const L=performance.now(),ne=await fetch(H,X),ie=Math.round(performance.now()-L),ee={};ne.headers.forEach((oe,W)=>{ee[W]=oe});let ue;ne.headers.get("content-type")?.includes("application/json")?ue=await ne.json():ue=await ne.text(),p({status:ne.status,statusText:ne.statusText,headers:ee,body:ue,duration:ie})}catch(F){p({status:0,statusText:"Network Error",headers:{},body:F instanceof Error?F.message:"Unknown error",duration:0})}finally{x(!1)}},P=async()=>{if(m){const F=typeof m.body=="string"?m.body:JSON.stringify(m.body,null,2);try{await navigator.clipboard.writeText(F),g(!0),setTimeout(()=>g(!1),2e3)}catch{const k=document.createElement("textarea");k.value=F,k.style.position="fixed",k.style.left="-999999px",document.body.appendChild(k),k.select(),document.execCommand("copy"),document.body.removeChild(k),g(!0),setTimeout(()=>g(!1),2e3)}}},N=(n.parameters||[]).filter(F=>F.in==="path"),A=(n.parameters||[]).filter(F=>F.in==="query"),T=["post","put","patch"].includes(e)&&n.requestBody;return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.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?a.jsx(Un,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${ynt[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),a.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&a.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),N.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),a.jsx("div",{className:"space-y-2",children:N.map(F=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[F.name,F.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),a.jsx("input",{type:"text",value:l[F.name]||"",onChange:k=>c(D=>({...D,[F.name]:k.target.value})),placeholder:F.description||F.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"})]},F.name))})]}),A.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),a.jsx("div",{className:"space-y-2",children:A.map(F=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[F.name,F.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),F.schema?.enum?a.jsxs("select",{value:l[F.name]||"",onChange:k=>c(D=>({...D,[F.name]:k.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:[a.jsx("option",{value:"",children:"-- Select --"}),F.schema.enum.map(k=>a.jsx("option",{value:k,children:k},k))]}):a.jsx("input",{type:"text",value:l[F.name]||"",onChange:k=>c(D=>({...D,[F.name]:k.target.value})),placeholder:F.description||F.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"})]},F.name))})]}),T&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),a.jsx("textarea",{value:d,onChange:F=>u(F.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..."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Fe,{onClick:C,disabled:f,children:[f?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx($i,{className:"w-4 h-4"}),"Execute"]}),_.length>0&&a.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Fill in: ",_.join(", ")]})]}),m&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",a.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${m.status>=200&&m.status<300?"bg-green-500/20 text-green-400":m.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[m.status," ",m.statusText]}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[m.duration,"ms"]})]}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:P,children:v?a.jsx(xr,{className:"w-3 h-3 text-green-400"}):a.jsx(Fs,{className:"w-3 h-3"})})]}),a.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 m.body=="string"?m.body:JSON.stringify(m.body,null,2)})]})]})]})}function Snt({apiKey:t=""}){const[e,n]=w.useState(null),[r,i]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[d,u]=w.useState("");if(w.useEffect(()=>{async function g(){try{const b=await fetch("/openapi.json");if(!b.ok)throw new Error("Failed to fetch OpenAPI schema");const _=await b.json();n(_)}catch(b){o(b instanceof Error?b.message:"Unknown error")}finally{i(!1)}}g()},[]),r)return a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return a.jsx(At,{children:a.jsx(Mt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-red-400",children:[a.jsx(Wa,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{children:"Failed to load API schema"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const m={};for(const[g,b]of Object.entries(e.paths))for(const[_,C]of Object.entries(b)){if(_==="parameters")continue;const P=C.tags||["Other"];for(const N of P)m[N]||(m[N]=[]),m[N].push({path:g,method:_,spec:C})}const p=Object.entries(m).map(([g,b])=>{if(!d)return{tag:g,endpoints:b};const _=b.filter(({path:C,method:P,spec:N})=>{const A=d.toLowerCase();return C.toLowerCase().includes(A)||P.toLowerCase().includes(A)||(N.summary?.toLowerCase()||"").includes(A)||(N.description?.toLowerCase()||"").includes(A)});return{tag:g,endpoints:_}}).filter(({endpoints:g})=>g.length>0).sort((g,b)=>g.tag.localeCompare(b.tag)),f=g=>{c(b=>{const _=new Set(b);return _.has(g)?_.delete(g):_.add(g),_})},x=()=>{c(new Set(p.map(g=>g.tag)))},v=()=>{c(new Set)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("div",{className:"flex-1",children:a.jsx("input",{type:"text",value:d,onChange:g=>u(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"})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),a.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[a.jsx(na,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((g,b)=>g+b.endpoints.length,0)," endpoints in ",p.length," categories"]}),a.jsx("div",{className:"space-y-3",children:p.map(({tag:g,endpoints:b})=>a.jsxs(At,{children:[a.jsx("button",{onClick:()=>f(g),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:a.jsxs("div",{className:"flex items-center gap-2",children:[l.has(g)?a.jsx(Un,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(Ka,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:g.replace(/-/g," ")}),a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:b.length})]})}),l.has(g)&&a.jsx(Mt,{className:"pt-0 space-y-2",children:b.map(({path:_,method:C,spec:P})=>a.jsx(wnt,{path:_,method:C,spec:P,schema:e,apiKey:t},`${C}-${_}`))})]},g))})]})}const Cle=new Map;function En(t){Cle.set(t.anchor,t)}function _nt(){return Array.from(Cle.values())}const knt=["general","plugs","notifications","queue","filament","network","apikeys","virtual-printer","spoolbuddy","failure-detection","users","backup"];En({labelKey:"settings.general",tab:"general",keywords:"language date time format printer model printers cards",anchor:"card-general"});En({labelKey:"settings.appearance",tab:"general",keywords:"theme dark light mode colors",anchor:"card-appearance"});En({labelKey:"settings.archiveSettings",tab:"general",keywords:"archive auto save thumbnails captures",anchor:"card-archive"});En({labelKey:"settings.camera",tab:"general",keywords:"camera external video stream",anchor:"card-camera"});En({labelKey:"settings.costTracking",tab:"general",keywords:"currency filament cost energy kwh price",anchor:"card-cost"});En({labelKey:"settings.fileManager",tab:"general",keywords:"file manager archive mode disk warning storage",anchor:"card-filemanager"});En({labelKey:"settings.updates",tab:"general",keywords:"updates version firmware beta check",anchor:"card-updates"});En({labelKey:"settings.dataManagement",tab:"general",keywords:"data reset clear logs notifications preferences",anchor:"card-data"});En({labelKey:"settings.smartPlugs",tab:"plugs",keywords:"smart plug energy power automation tapo kasa tplink shelly",anchor:"card-plugs"});En({labelKey:"settings.providers",tab:"notifications",keywords:"telegram discord email notification providers webhook",anchor:"card-providers"});En({labelKey:"settings.messageTemplates",tab:"notifications",keywords:"message templates notification text edit",anchor:"card-templates"});En({labelKey:"settings.defaultPrintOptions",labelFallback:"Default Print Options",tab:"queue",keywords:"print bed leveling flow calibration vibration first layer timelapse",anchor:"card-print-options"});En({labelKey:"settings.staggeredStart",labelFallback:"Staggered Start",tab:"queue",keywords:"staggered batch delay start queue group",anchor:"card-staggered"});En({labelKey:"settings.plateClear",labelFallback:"Plate-Clear Confirmation",tab:"queue",keywords:"plate clear confirm auto queue",anchor:"card-plate"});En({labelKey:"settings.gcodeInjection",labelFallback:"G-code Injection",tab:"queue",keywords:"gcode injection start end autoprint farmloop swapmod autoclear printflow",anchor:"card-gcode"});En({labelKey:"settings.queueDrying",tab:"queue",keywords:"drying presets temperature time humidity ams",anchor:"card-drying"});En({labelKey:"settings.filamentChecks",tab:"filament",keywords:"filament check warning runout remaining",anchor:"card-filamentchecks"});En({labelKey:"settings.printModal",tab:"filament",keywords:"print modal custom mapping",anchor:"card-printmodal"});En({labelKey:"settings.amsDisplayThresholds",tab:"filament",keywords:"ams humidity temperature threshold history retention",anchor:"card-amsthresholds"});En({labelKey:"settings.externalUrl",tab:"network",keywords:"external url reverse proxy public notification link",anchor:"card-externalurl"});En({labelKey:"settings.ftpRetry",tab:"network",keywords:"ftp retry upload retries backoff",anchor:"card-ftpretry"});En({labelKey:"settings.homeAssistant",tab:"network",keywords:"home assistant ha hass mqtt integration",anchor:"card-ha"});En({labelKey:"settings.mqttPublishing",tab:"network",keywords:"mqtt publish broker topic",anchor:"card-mqtt"});En({labelKey:"settings.prometheusMetrics",tab:"network",keywords:"prometheus metrics grafana monitoring bearer token",anchor:"card-prometheus"});En({labelKey:"settings.createNewApiKey",tab:"apikeys",keywords:"api key create permission scope",anchor:"card-createapi"});En({labelKey:"settings.webhookEndpoints",tab:"apikeys",keywords:"webhook endpoint post http",anchor:"card-webhooks"});En({labelKey:"settings.apiBrowser",tab:"apikeys",keywords:"api browser endpoint documentation test",anchor:"card-apibrowser"});En({labelKey:"settings.tabs.virtualPrinter",tab:"virtual-printer",keywords:"virtual printer proxy archive slicer bambustudio orcaslicer ip bind",anchor:"card-vp"});En({labelKey:"settings.tabs.spoolbuddy",tab:"spoolbuddy",keywords:"spoolbuddy device scale nfc rfid kiosk unregister",anchor:"card-spoolbuddy"});En({labelKey:"settings.currentUser",tab:"users",subTab:"users",keywords:"current user profile password change",anchor:"card-currentuser"});En({labelKey:"settings.users",tab:"users",subTab:"users",keywords:"users accounts list",anchor:"card-users"});En({labelKey:"settings.groups",tab:"users",subTab:"users",keywords:"groups roles permissions administrators operators viewers",anchor:"card-groups"});En({labelKey:"settings.email.smtpSettings",labelFallback:"SMTP Configuration",tab:"users",subTab:"email",keywords:"smtp email send server port password auth starttls ssl",anchor:"card-smtp"});En({labelKey:"settings.ldap.title",labelFallback:"LDAP Authentication",tab:"users",subTab:"ldap",keywords:"ldap active directory ad authentication bind dn search base group mapping",anchor:"card-ldap"});En({labelKey:"settings.tabs.backup",tab:"backup",keywords:"backup github restore download cloud sync profiles archives",anchor:"card-backup"});En({labelKey:"externalLinks.title",labelFallback:"Sidebar Links",tab:"general",keywords:"sidebar links external custom navigation url add",anchor:"card-sidebar-links"});En({labelKey:"settings.filamentTracking",tab:"filament",keywords:"spoolman filament tracking inventory sync remote integration",anchor:"card-spoolman"});En({labelKey:"settings.catalog.spoolCatalog",labelFallback:"Spool Catalog",tab:"filament",keywords:"spool catalog entries brand material reset import export",anchor:"card-spool-catalog"});En({labelKey:"settings.colorCatalog.title",labelFallback:"Color Catalog",tab:"filament",keywords:"color catalog hex swatch palette sync reset",anchor:"card-color-catalog"});En({labelKey:"settings.tabs.failureDetection",labelFallback:"Failure Detection",tab:"failure-detection",keywords:"failure detection ai ml obico spaghetti detect monitoring",anchor:"card-fd-ml"});En({labelKey:"failureDetection.perPrinterTitle",labelFallback:"Per-Printer Settings",tab:"failure-detection",keywords:"failure detection per printer enable per-printer sensitivity",anchor:"card-fd-perprinter"});En({labelKey:"failureDetection.statusTitle",labelFallback:"Detection Status",tab:"failure-detection",keywords:"failure detection status running connection",anchor:"card-fd-status"});En({labelKey:"failureDetection.historyTitle",labelFallback:"Detection History",tab:"failure-detection",keywords:"failure detection history log events",anchor:"card-fd-history"});En({labelKey:"settings.email.advancedAuth",labelFallback:"Advanced Email Authentication",tab:"users",subTab:"email",keywords:"email authentication advanced password reset self-service forgot",anchor:"card-email-advanced-auth"});En({labelKey:"settings.email.testConnection",labelFallback:"Test SMTP Connection",tab:"users",subTab:"email",keywords:"email smtp test connection send check",anchor:"card-email-test"});En({labelKey:"settings.twoFa.totpTitle",labelFallback:"Authenticator App (TOTP)",tab:"users",subTab:"twofa",keywords:"two factor 2fa totp authenticator app google authy otp",anchor:"card-2fa-totp"});En({labelKey:"settings.twoFa.emailOtpTitle",labelFallback:"Email One-Time Codes",tab:"users",subTab:"twofa",keywords:"two factor 2fa email otp one time code",anchor:"card-2fa-emailotp"});En({labelKey:"settings.twoFa.linkedAccounts",labelFallback:"Linked Accounts",tab:"users",subTab:"twofa",keywords:"two factor 2fa linked accounts sso oidc provider google github",anchor:"card-2fa-linked"});En({labelKey:"settings.oidc.title",labelFallback:"Single Sign-On (OIDC)",tab:"users",subTab:"oidc",keywords:"sso oidc openid single sign-on pocketid authentik keycloak google okta azure provider",anchor:"card-oidc"});En({labelKey:"settings.ldap.serverConfig",labelFallback:"LDAP Server Configuration",tab:"users",subTab:"ldap",keywords:"ldap server url bind dn user search base group filter tls",anchor:"card-ldap-server"});En({labelKey:"backup.githubBackup",labelFallback:"GitHub Backup",tab:"backup",keywords:"github backup cloud remote sync profiles token",anchor:"card-backup-github"});En({labelKey:"backup.history",labelFallback:"Backup History",tab:"backup",keywords:"backup history log runs github commits",anchor:"card-backup-history"});En({labelKey:"backup.localBackup",labelFallback:"Local Backup",tab:"backup",keywords:"local backup download zip manual export",anchor:"card-backup-local"});En({labelKey:"backup.scheduledBackup",labelFallback:"Scheduled Backups",tab:"backup",keywords:"scheduled backup automatic hourly daily weekly retention local path",anchor:"card-backup-scheduled"});const Nnt={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"},mY=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],hY=(t,e)=>Nnt[t]||mY[e%mY.length];function Cnt(){const t=sn(),e=Do(),[n,r]=PP(),{t:i,i18n:s}=Rt(),{showToast:o}=bn(),{authEnabled:l,user:c,isAdmin:d,refreshAuth:u,hasPermission:m}=wr(),{mode:p,darkStyle:f,darkBackground:x,darkAccent:v,lightStyle:g,lightBackground:b,lightAccent:_,setDarkStyle:C,setDarkBackground:P,setDarkAccent:N,setLightStyle:A,setLightBackground:T,setLightAccent:F}=wg(),[k,D]=w.useState(null),[H,z]=w.useState(!1),[X,L]=w.useState(null),[ne,ie]=w.useState(!1),[ee,ue]=w.useState(null),[le,oe]=w.useState(null),[W,re]=w.useState(""),[ce,xe]=w.useState(""),[Ne,$]=w.useState(!1),[Y,E]=w.useState(QQ()),j=n.get("tab"),O=j==="email",K=O?"users":j&&knt.includes(j)?j:"general",[B,he]=w.useState(K),[I,V]=w.useState(O?"email":"users"),Q=we=>{he(we),we==="users"&&V("users"),we==="general"?n.delete("tab"):n.set("tab",we),r(n,{replace:!0})},[G,J]=w.useState(!1),[se,fe]=w.useState(""),[pe,de]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[U,R]=w.useState(null),[ae,_e]=w.useState(null),[Se,ye]=w.useState(""),[Ae,ve]=w.useState(!1),[je,Re]=w.useState(!1),[Ee,Te]=w.useState(null),[Me,Be]=w.useState(!1),[Ke,tt]=w.useState(!1),[te,Ie]=w.useState(!1),[be,$e]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[He,ge]=w.useState(!1),[Pe,qe]=w.useState(!1),[Ze,ut]=w.useState(!1),[vt,wt]=w.useState(!1),[$t,Qt]=w.useState(null),[en,Xt]=w.useState(null),[tn,Ge]=w.useState(null),[Ft,Yt]=w.useState(!1),[Pt,pt]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Wt,Ut]=w.useState(null),[ze,st]=w.useState(null),[ht,rt]=w.useState(!1),[Le,Oe]=w.useState({}),[Ce,We]=w.useState({}),Je=we=>{E(we),Dye(we),o(i("settings.toast.settingsSaved"),"success")},Xe=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},Ye=!!k?.default_sidebar_order,St=async we=>{try{if(we){let _t;const ln=localStorage.getItem("sidebarOrder");try{_t=ln?JSON.parse(ln):zu.map(zt=>zt.id)}catch{_t=zu.map(zt=>zt.id)}(!Array.isArray(_t)||_t.length===0)&&(_t=zu.map(zt=>zt.id));const mn=JSON.stringify({order:_t});await me.updateSettings({default_sidebar_order:mn}),D(zt=>zt&&{...zt,default_sidebar_order:mn}),o(i("settings.sidebarDefaultSet"),"success")}else await me.updateSettings({default_sidebar_order:""}),D(_t=>_t&&{..._t,default_sidebar_order:""}),o(i("settings.sidebarDefaultCleared"),"success");t.invalidateQueries({queryKey:["settings"]}),t.invalidateQueries({queryKey:["default-sidebar-order"]})}catch{o(i("settings.sidebarDefaultFailed"),"error")}},{data:et,isLoading:jt}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:bt,isLoading:Ve,isFetching:gt}=Qe({queryKey:["storage-usage"],queryFn:()=>me.getStorageUsage(),enabled:B==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),Et=async()=>{qe(!0);try{const we=await me.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],we)}catch(we){const _t=we instanceof Error?we.message:"Failed to refresh storage usage";o(_t,"error")}finally{qe(!1)}},{data:Gt,isLoading:on}=Qe({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),{data:fn,isLoading:Ln}=Qe({queryKey:["smart-plugs-energy",Gt?.map(we=>we.id)],queryFn:async()=>{if(!Gt||Gt.length===0)return null;const we=await Promise.all(Gt.filter(mr=>mr.enabled).map(async mr=>{try{const Vn=await me.getSmartPlugStatus(mr.id);return{plug:mr,status:Vn}}catch{return{plug:mr,status:null}}}));let _t=0,ln=0,mn=0,zt=0,dn=0;for(const{plug:mr,status:Vn}of we){const yi=mr.plug_type==="mqtt"&&Vn?.energy?.power!=null;(Vn?.reachable||yi)&&Vn?.energy&&(dn++,Vn.energy?.power!=null&&(_t+=Vn.energy.power),Vn.energy?.today!=null&&(ln+=Vn.energy.today),Vn.energy?.yesterday!=null&&(mn+=Vn.energy.yesterday),Vn.energy?.total!=null&&(zt+=Vn.energy.total))}return{totalPower:_t,totalToday:ln,totalYesterday:mn,totalLifetime:zt,reachableCount:dn,totalPlugs:Gt.filter(mr=>mr.enabled).length}},enabled:B==="plugs"&&!!Gt&&Gt.length>0,refetchInterval:B==="plugs"?1e4:!1}),{data:yn,isLoading:hn}=Qe({queryKey:["notification-providers"],queryFn:me.getNotificationProviders}),{data:xn,isLoading:Nn}=Qe({queryKey:["api-keys"],queryFn:me.getAPIKeys}),Pn=it({mutationFn:we=>me.createAPIKey(we),onSuccess:we=>{R(we.key||null),J(!1),fe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:we=>{o(`Failed to create API key: ${we.message}`,"error")}}),Nr=it({mutationFn:we=>me.deleteAPIKey(we),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyDeleted"))},onError:we=>{o(`Failed to delete API key: ${we.message}`,"error")}}),{data:Sn}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:Pa,isLoading:On}=Qe({queryKey:["notification-templates"],queryFn:me.getNotificationTemplates}),{data:ya}=Qe({queryKey:["virtual-printer-settings"],queryFn:lye.getSettings,refetchInterval:1e4}),ua=ya?.status?.running??!1,{data:Zr}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:15e3}),sa=Zr?.length??0,Ta=Zr?.some(we=>we.online)??!1,{data:Wi}=Qe({queryKey:["obico-status"],queryFn:me.getObicoStatus,refetchInterval:15e3}),_m=!!(Wi?.is_running&&Wi?.enabled),{data:Vd}=Qe({queryKey:["ffmpeg-status"],queryFn:me.checkFfmpeg}),{data:fl}=Qe({queryKey:["version"],queryFn:me.getVersion}),{data:xt,refetch:Kn,isRefetching:Zn}=Qe({queryKey:["updateCheck"],queryFn:me.checkForUpdates,enabled:et?.check_updates!==!1,staleTime:300*1e3}),{data:qt,refetch:Kc}=Qe({queryKey:["updateStatus"],queryFn:me.getUpdateStatus,refetchInterval:we=>{const _t=we.state.data;return _t?.status==="downloading"||_t?.status==="installing"?1e3:!1}}),{data:Ki}=Qe({queryKey:["mqtt-status"],queryFn:me.getMQTTStatus,refetchInterval:B==="network"?5e3:!1}),{data:gl}=Qe({queryKey:["github-backup-status"],queryFn:me.getGitHubBackupStatus}),{data:fc}=Qe({queryKey:["cloud-status"],queryFn:me.getCloudStatus}),{data:Qa={advanced_auth_enabled:!1,smtp_configured:!1}}=Qe({queryKey:["advancedAuthStatus"],queryFn:()=>me.getAdvancedAuthStatus()}),{data:km}=Qe({queryKey:["ldapStatus"],queryFn:()=>me.getLDAPStatus()}),{data:Cp}=Qe({queryKey:["twoFAStatus"],queryFn:()=>me.get2FAStatus()}),{data:Gd=[]}=Qe({queryKey:["oidcProvidersAll"],queryFn:()=>me.getOIDCProvidersAll(),enabled:d}),{data:Xi=[],isLoading:Nm}=Qe({queryKey:["users"],queryFn:()=>me.getUsers(),enabled:l&&m("users:read")}),{data:vs=[],isLoading:Yi}=Qe({queryKey:["groups"],queryFn:()=>me.getGroups(),enabled:l&&m("groups:read")}),zs=it({mutationFn:we=>me.createUser(we),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),ut(!1),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:we=>{o(we.message,"error")}}),bl=it({mutationFn:({id:we,data:_t})=>me.updateUser(we,_t),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),wt(!1),Qt(null),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:we=>{o(we.message,"error")}}),Za=it({mutationFn:({id:we,deleteItems:_t})=>me.deleteUser(we,_t),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),Xt(null),Ge(null)},onError:we=>{o(we.message,"error")}}),xl=it({mutationFn:we=>me.resetUserPassword({user_id:we}),onSuccess:we=>{o(we.message,"success")},onError:we=>{o(we.message,"error")}}),Wd=async we=>{Xt(we),Yt(!0);try{const _t=await me.getUserItemsCount(we);Ge(_t)}catch{Ge({archives:0,queue_items:0,library_files:0})}finally{Yt(!1)}},yl=it({mutationFn:we=>me.deleteGroup(we),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:we=>{o(we.message,"error")}}),xi=()=>{const we=Qa?.advanced_auth_enabled||!1;if(!Pt.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(we&&!Pt.email){o("Email is required when advanced authentication is enabled","error");return}if(!we){if(!Pt.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(Pt.password!==Pt.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Pt.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}zs.mutate({username:Pt.username,password:we?void 0:Pt.password,email:Pt.email||void 0,role:Pt.role,group_ids:Pt.group_ids.length>0?Pt.group_ids:void 0})},Us=we=>{if(Pt.password){if(Pt.password!==Pt.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Pt.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const _t={username:Pt.username||void 0,password:Pt.password||void 0,email:Pt.email||void 0,role:Pt.role,group_ids:Pt.group_ids};_t.password||delete _t.password,bl.mutate({id:we,data:_t})},gc=we=>{Qt(we.id),pt({username:we.username,password:"",email:we.email||"",confirmPassword:"",role:we.role,group_ids:we.groups?.map(_t=>_t.id)||[]}),wt(!0)},Oo=we=>{pt(_t=>({..._t,group_ids:_t.group_ids.includes(we)?_t.group_ids.filter(ln=>ln!==we):[..._t.group_ids,we]}))},Pp=it({mutationFn:me.applyUpdate,onSuccess:we=>{we.is_docker?o(we.message,"error"):Kc()}}),[vl,co]=w.useState(null),wl=it({mutationFn:me.testAllNotificationProviders,onSuccess:we=>{co(we),t.invalidateQueries({queryKey:["notification-providers"]}),we.failed===0?o(`All ${we.tested} providers tested successfully!`,"success"):o(`${we.success}/${we.tested} providers succeeded`,we.failed>0?"error":"success")},onError:we=>{o(`Failed to test providers: ${we.message}`,"error")}}),Io=it({mutationFn:async we=>{if(!Gt)return{success:0,failed:0};const _t=Gt.filter(mn=>mn.enabled),ln=await Promise.all(_t.map(async mn=>{try{return await me.controlSmartPlug(mn.id,we),{success:!0}}catch{return{success:!1}}}));return{success:ln.filter(mn=>mn.success).length,failed:ln.filter(mn=>!mn.success).length}},onSuccess:(we,_t)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),we.failed===0?o(`All ${we.success} plugs turned ${_t}`,"success"):o(`${we.success} plugs turned ${_t}, ${we.failed} failed`,"error")},onError:we=>{o(`Failed: ${we.message}`,"error")}}),Xc=w.useRef(null),Cm=w.useRef(null),uo=w.useRef(!1),mo=w.useRef(!0);w.useEffect(()=>{if(et&&!k){const we={...et,external_url:et.external_url||window.location.origin};D(we),setTimeout(()=>{mo.current=!1},100)}},[et,k]);const zo=it({mutationFn:me.updateSettings,onSuccess:we=>{t.setQueryData(["settings"],we),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:we=>{o(`Failed to save: ${we.message}`,"error")},onSettled:()=>{uo.current=!1}}),Tg=it({mutationFn:({id:we,data:_t})=>me.updatePrinter(we,_t),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:we=>{o(`Failed to update printer: ${we.message}`,"error")}});w.useEffect(()=>{if(!(mo.current||!k||!et||!(et.auto_archive!==k.auto_archive||et.save_thumbnails!==k.save_thumbnails||et.capture_finish_photo!==k.capture_finish_photo||et.default_filament_cost!==k.default_filament_cost||et.currency!==k.currency||et.energy_cost_per_kwh!==k.energy_cost_per_kwh||et.energy_tracking_mode!==k.energy_tracking_mode||et.check_updates!==k.check_updates||(et.check_printer_firmware??!0)!==(k.check_printer_firmware??!0)||(et.include_beta_updates??!1)!==(k.include_beta_updates??!1)||et.notification_language!==k.notification_language||(et.bed_cooled_threshold??35)!==(k.bed_cooled_threshold??35)||et.ams_humidity_good!==k.ams_humidity_good||et.ams_humidity_fair!==k.ams_humidity_fair||et.ams_temp_good!==k.ams_temp_good||et.ams_temp_fair!==k.ams_temp_fair||et.ams_history_retention_days!==k.ams_history_retention_days||et.disable_filament_warnings!==k.disable_filament_warnings||et.prefer_lowest_filament!==k.prefer_lowest_filament||(et.queue_drying_enabled??!1)!==(k.queue_drying_enabled??!1)||(et.queue_drying_block??!1)!==(k.queue_drying_block??!1)||(et.ambient_drying_enabled??!1)!==(k.ambient_drying_enabled??!1)||(et.drying_presets??"")!==(k.drying_presets??"")||et.per_printer_mapping_expanded!==k.per_printer_mapping_expanded||et.date_format!==k.date_format||et.time_format!==k.time_format||et.default_printer_id!==k.default_printer_id||et.ftp_retry_enabled!==k.ftp_retry_enabled||et.ftp_retry_count!==k.ftp_retry_count||et.ftp_retry_delay!==k.ftp_retry_delay||et.ftp_timeout!==k.ftp_timeout||et.mqtt_enabled!==k.mqtt_enabled||et.mqtt_broker!==k.mqtt_broker||et.mqtt_port!==k.mqtt_port||et.mqtt_username!==k.mqtt_username||et.mqtt_password!==k.mqtt_password||et.mqtt_topic_prefix!==k.mqtt_topic_prefix||et.mqtt_use_tls!==k.mqtt_use_tls||et.external_url!==k.external_url||et.ha_enabled!==k.ha_enabled||et.ha_url!==k.ha_url||et.ha_token!==k.ha_token||(et.library_archive_mode??"ask")!==(k.library_archive_mode??"ask")||Number(et.library_disk_warning_gb??5)!==Number(k.library_disk_warning_gb??5)||(et.camera_view_mode??"window")!==(k.camera_view_mode??"window")||(et.preferred_slicer??"bambu_studio")!==(k.preferred_slicer??"bambu_studio")||et.prometheus_enabled!==k.prometheus_enabled||et.prometheus_token!==k.prometheus_token||(et.user_notifications_enabled??!0)!==(k.user_notifications_enabled??!0)||(et.default_bed_levelling??!0)!==(k.default_bed_levelling??!0)||(et.default_flow_cali??!1)!==(k.default_flow_cali??!1)||(et.default_vibration_cali??!0)!==(k.default_vibration_cali??!0)||(et.default_layer_inspect??!1)!==(k.default_layer_inspect??!1)||(et.default_timelapse??!1)!==(k.default_timelapse??!1)||(et.stagger_group_size??2)!==(k.stagger_group_size??2)||(et.stagger_interval_minutes??5)!==(k.stagger_interval_minutes??5)||(et.require_plate_clear??!1)!==(k.require_plate_clear??!1)))&&!uo.current)return Xc.current&&clearTimeout(Xc.current),Xc.current=setTimeout(()=>{if(uo.current)return;uo.current=!0;const _t={auto_archive:k.auto_archive,save_thumbnails:k.save_thumbnails,capture_finish_photo:k.capture_finish_photo,default_filament_cost:k.default_filament_cost,currency:k.currency,energy_cost_per_kwh:k.energy_cost_per_kwh,energy_tracking_mode:k.energy_tracking_mode,check_updates:k.check_updates,check_printer_firmware:k.check_printer_firmware,include_beta_updates:k.include_beta_updates,notification_language:k.notification_language,bed_cooled_threshold:k.bed_cooled_threshold,ams_humidity_good:k.ams_humidity_good,ams_humidity_fair:k.ams_humidity_fair,ams_temp_good:k.ams_temp_good,ams_temp_fair:k.ams_temp_fair,ams_history_retention_days:k.ams_history_retention_days,disable_filament_warnings:k.disable_filament_warnings,prefer_lowest_filament:k.prefer_lowest_filament,queue_drying_enabled:k.queue_drying_enabled,queue_drying_block:k.queue_drying_block,ambient_drying_enabled:k.ambient_drying_enabled,drying_presets:k.drying_presets,per_printer_mapping_expanded:k.per_printer_mapping_expanded,date_format:k.date_format,time_format:k.time_format,default_printer_id:k.default_printer_id,ftp_retry_enabled:k.ftp_retry_enabled,ftp_retry_count:k.ftp_retry_count,ftp_retry_delay:k.ftp_retry_delay,ftp_timeout:k.ftp_timeout,mqtt_enabled:k.mqtt_enabled,mqtt_broker:k.mqtt_broker,mqtt_port:k.mqtt_port,mqtt_username:k.mqtt_username,mqtt_password:k.mqtt_password,mqtt_topic_prefix:k.mqtt_topic_prefix,mqtt_use_tls:k.mqtt_use_tls,external_url:k.external_url,ha_enabled:k.ha_enabled,ha_url:k.ha_url,ha_token:k.ha_token,library_archive_mode:k.library_archive_mode,library_disk_warning_gb:k.library_disk_warning_gb,camera_view_mode:k.camera_view_mode,preferred_slicer:k.preferred_slicer,prometheus_enabled:k.prometheus_enabled,prometheus_token:k.prometheus_token,user_notifications_enabled:k.user_notifications_enabled,default_bed_levelling:k.default_bed_levelling,default_flow_cali:k.default_flow_cali,default_vibration_cali:k.default_vibration_cali,default_layer_inspect:k.default_layer_inspect,default_timelapse:k.default_timelapse,stagger_group_size:k.stagger_group_size,stagger_interval_minutes:k.stagger_interval_minutes,require_plate_clear:k.require_plate_clear};zo.mutate(_t)},500),()=>{Xc.current&&clearTimeout(Xc.current)}},[k,et,zo]);const kn=w.useCallback((we,_t)=>{D(ln=>ln?{...ln,[we]:_t}:null)},[]),Ay=async(we,_t,ln)=>{if(!_t){o(i("settings.toast.enterCameraUrl"),"error");return}We(mn=>({...mn,[we]:!0})),Oe(mn=>({...mn,[we]:null}));try{const mn=await me.testExternalCamera(we,_t,ln);Oe(zt=>({...zt,[we]:mn})),mn.success?o(i("settings.toast.cameraConnected",{resolution:mn.resolution||""}),"success"):o(mn.error||i("settings.toast.connectionFailed"),"error")}catch(mn){const zt=mn instanceof Error?mn.message:i("settings.toast.testFailed");Oe(dn=>({...dn,[we]:{success:!1,error:zt}})),o(zt,"error")}finally{We(mn=>({...mn,[we]:!1}))}},[Yc,Ag]=w.useState({}),Pm=w.useRef({}),jg=w.useRef(new Set);w.useEffect(()=>{if(Sn){const we={};Sn.forEach(_t=>{_t.external_camera_url&&!jg.current.has(_t.id)&&(we[_t.id]=_t.external_camera_url,jg.current.add(_t.id))}),Object.keys(we).length>0&&Ag(_t=>({..._t,...we}))}},[Sn]);const jy=(we,_t)=>{Ag(ln=>({...ln,[we]:_t})),Pm.current[we]&&clearTimeout(Pm.current[we]),Pm.current[we]=setTimeout(()=>{Tg.mutate({id:we,data:{external_camera_url:_t||null}})},800)},mt=(we,_t)=>{const ln={};_t.type!==void 0&&(ln.external_camera_type=_t.type||null),_t.enabled!==void 0&&(ln.external_camera_enabled=_t.enabled),_t.rotation!==void 0&&(ln.camera_rotation=_t.rotation),Tg.mutate({id:we,data:ln})};if(jt||!k)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const Ht=_nt().map(we=>({...we,label:i(we.labelKey,we.labelFallback??we.labelKey)})),Jt=ce.trim().toLowerCase(),ot=Jt?Ht.filter(we=>we.label.toLowerCase().includes(Jt)||we.keywords.toLowerCase().includes(Jt)).slice(0,8):[],Bn=we=>{Q(we.tab),we.subTab&&V(we.subTab),xe(""),setTimeout(()=>{const _t=document.getElementById(we.anchor);_t&&(_t.scrollIntoView({behavior:"smooth",block:"start"}),_t.classList.add("ring-2","ring-bambu-green"),setTimeout(()=>_t.classList.remove("ring-2","ring-bambu-green"),1500))},50)};return a.jsx(dye,{density:"dense",children:a.jsxs("div",{className:"p-4 md:p-6",children:[a.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"flex items-baseline gap-3",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),a.jsx("p",{className:"text-sm text-bambu-gray hidden md:block",children:i("settings.configureBambuddy")})]}),a.jsxs("div",{className:"relative sm:w-72",children:[a.jsx(kr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),a.jsx("input",{type:"text",value:ce,onChange:we=>xe(we.target.value),placeholder:i("settings.searchPlaceholder","Search settings…"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),ce&&a.jsx("button",{onClick:()=>xe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear",children:a.jsx(Bt,{className:"w-3.5 h-3.5"})}),ot.length>0&&a.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-30 overflow-hidden",children:ot.map(we=>a.jsxs("button",{onClick:()=>Bn(we),className:"w-full px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors border-b border-bambu-dark-tertiary last:border-b-0",children:[a.jsx("p",{className:"text-sm text-white",children:we.label}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i(`settings.tabs.${we.tab==="virtual-printer"?"virtualPrinter":we.tab==="failure-detection"?"failureDetection":we.tab}`),we.subTab?` › ${i(`settings.tabs.${we.subTab}`,we.subTab)}`:""]})]},we.anchor))}),Jt&&ot.length===0&&a.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-30 p-3",children:a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noSearchResults","No matching settings.")})})]})]}),a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("nav",{className:"flex flex-wrap gap-1 border-b border-bambu-dark-tertiary lg:flex-col lg:flex-nowrap lg:gap-0 lg:border-b-0 lg:border-r lg:w-48 lg:flex-shrink-0 lg:self-start lg:sticky lg:top-4",children:[a.jsxs("button",{onClick:()=>Q("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Hw,{className:"w-4 h-4"}),i("settings.tabs.general")]}),a.jsxs("button",{onClick:()=>Q("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ql,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Gt&&Gt.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Gt.length})]}),a.jsxs("button",{onClick:()=>Q("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Uh,{className:"w-4 h-4"}),i("settings.tabs.notifications"),yn&&yn.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:yn.length})]}),a.jsxs("button",{onClick:()=>Q("queue"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="queue"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(lN,{className:"w-4 h-4"}),i("settings.tabs.queue","Workflow")]}),a.jsxs("button",{onClick:()=>Q("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(jfe,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),a.jsxs("button",{onClick:()=>Q("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Vh,{className:"w-4 h-4"}),i("settings.tabs.network"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Ki?.enabled?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>Q("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ws,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),xn&&xn.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:xn.length})]}),a.jsxs("button",{onClick:()=>Q("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ar,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),a.jsx("span",{className:`w-2 h-2 rounded-full ${ua?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>Q("spoolbuddy"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="spoolbuddy"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(EQ,{className:"w-4 h-4"}),i("settings.tabs.spoolbuddy"),sa>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:sa}),a.jsx("span",{className:`w-2 h-2 rounded-full ${Ta?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>Q("failure-detection"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="failure-detection"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(DQ,{className:"w-4 h-4"}),i("settings.tabs.failureDetection"),a.jsx("span",{className:`w-2 h-2 rounded-full ${_m?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>Q("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Fu,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>Q("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${B==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Kl,{className:"w-4 h-4"}),i("settings.tabs.backup"),a.jsx("span",{className:`w-2 h-2 rounded-full ${fc?.is_authenticated&&gl?.configured&&gl?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[B==="general"&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(At,{id:"card-general",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(rl,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:s.language,onChange:we=>{s.changeLanguage(we.target.value),me.updateSettings({language:we.target.value}),o(i("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:J8.map(we=>a.jsxs("option",{value:we.code,children:[we.nativeName," (",we.name,")"]},we.code))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:Y,onChange:we=>Je(we.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:zu.map(we=>a.jsx("option",{value:we.to,children:i(we.labelKey)},we.id))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.dateFormat")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.date_format||"system",onChange:we=>kn("date_format",we.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:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"us",children:i("settings.dateFormatUs")}),a.jsx("option",{value:"eu",children:i("settings.dateFormatEu")}),a.jsx("option",{value:"iso",children:i("settings.dateFormatIso")})]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.timeFormat")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.time_format||"system",onChange:we=>kn("time_format",we.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:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"12h",children:i("settings.timeFormat12")}),a.jsx("option",{value:"24h",children:i("settings.timeFormat24")})]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultPrinter")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.default_printer_id??"",onChange:we=>kn("default_printer_id",we.target.value?Number(we.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:[a.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Sn?.map(we=>a.jsx("option",{value:we.id,children:we.name},we.id))]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultPrinterDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k.preferred_slicer??"bambu_studio",onChange:we=>kn("preferred_slicer",we.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:[a.jsx("option",{value:"bambu_studio",children:i("settings.slicerBambuStudio")}),a.jsx("option",{value:"orcaslicer",children:i("settings.slicerOrcaSlicer")})]}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[i("settings.sidebarOrderDescription"),l&&m("settings:update")&&` ${i("settings.sidebarOrderSetDefaultHint")}`]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Xe,children:[a.jsx(eo,{className:"w-4 h-4"}),i("settings.reset")]}),l&&m("settings:update")&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:i("settings.setDefault")}),a.jsx(zn,{checked:Ye,onChange:St,disabled:jt})]})]})]})]})]}),a.jsxs(At,{id:"card-appearance",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Iw,{className:"w-5 h-5"}),i("settings.appearance")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${p==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.darkMode"),p==="dark"&&a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),a.jsxs("select",{value:x,onChange:we=>{P(we.target.value),o(i("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:[a.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),a.jsx("option",{value:"warm",children:i("settings.bgWarm")}),a.jsx("option",{value:"cool",children:i("settings.bgCool")}),a.jsx("option",{value:"oled",children:i("settings.bgOled")}),a.jsx("option",{value:"slate",children:i("settings.bgSlate")}),a.jsx("option",{value:"forest",children:i("settings.bgForest")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),a.jsxs("select",{value:v,onChange:we=>{N(we.target.value),o(i("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:[a.jsx("option",{value:"green",children:i("settings.accentGreen")}),a.jsx("option",{value:"teal",children:i("settings.accentTeal")}),a.jsx("option",{value:"blue",children:i("settings.accentBlue")}),a.jsx("option",{value:"orange",children:i("settings.accentOrange")}),a.jsx("option",{value:"purple",children:i("settings.accentPurple")}),a.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),a.jsxs("select",{value:f,onChange:we=>{C(we.target.value),o(i("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:[a.jsx("option",{value:"classic",children:i("settings.styleClassic")}),a.jsx("option",{value:"glow",children:i("settings.styleGlow")}),a.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${p==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.lightMode"),p==="light"&&a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),a.jsxs("select",{value:b,onChange:we=>{T(we.target.value),o(i("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:[a.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),a.jsx("option",{value:"warm",children:i("settings.bgWarm")}),a.jsx("option",{value:"cool",children:i("settings.bgCool")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),a.jsxs("select",{value:_,onChange:we=>{F(we.target.value),o(i("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:[a.jsx("option",{value:"green",children:i("settings.accentGreen")}),a.jsx("option",{value:"teal",children:i("settings.accentTeal")}),a.jsx("option",{value:"blue",children:i("settings.accentBlue")}),a.jsx("option",{value:"orange",children:i("settings.accentOrange")}),a.jsx("option",{value:"purple",children:i("settings.accentPurple")}),a.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),a.jsxs("select",{value:g,onChange:we=>{A(we.target.value),o(i("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:[a.jsx("option",{value:"classic",children:i("settings.styleClassic")}),a.jsx("option",{value:"glow",children:i("settings.styleGlow")}),a.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.themeToggleHint")})]})]}),a.jsxs(At,{id:"card-archive",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.autoArchivePrints")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoArchiveDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.auto_archive,onChange:we=>kn("auto_archive",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.saveThumbnailsDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.save_thumbnails,onChange:we=>kn("save_thumbnails",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.captureFinishPhotoDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.capture_finish_photo,onChange:we=>kn("capture_finish_photo",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),k.capture_finish_photo&&Vd&&!Vd.installed&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(Rn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-yellow-500 font-medium",children:i("settings.ffmpegNotInstalled")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:i("settings.ffmpegRequired")})]})]})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-md",children:[a.jsxs(At,{id:"card-camera",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(kO,{className:"w-5 h-5 text-bambu-green"}),i("settings.camera")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.cameraViewMode")}),a.jsxs("select",{value:k.camera_view_mode??"window",onChange:we=>kn("camera_view_mode",we.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:[a.jsx("option",{value:"window",children:i("settings.newWindow")}),a.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.camera_view_mode==="embedded"?i("settings.cameraOverlayDescription"):i("settings.cameraWindowDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:i("settings.externalCamerasDescription")}),Sn&&Sn.length>0?a.jsx("div",{className:"space-y-3",children:Sn.map(we=>a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-white font-medium text-sm",children:we.name}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:we.external_camera_enabled,onChange:_t=>mt(we.id,{enabled:_t.target.checked}),className:"sr-only peer"}),a.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"})]})]}),we.external_camera_enabled&&a.jsxs("div",{className:"space-y-2 mt-2",children:[a.jsx("input",{type:"text",placeholder:we.external_camera_type==="usb"?i("settings.cameraPlaceholderUsb"):i("settings.cameraPlaceholderUrl"),value:Yc[we.id]??we.external_camera_url??"",onChange:_t=>jy(we.id,_t.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"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:we.external_camera_type||"mjpeg",onChange:_t=>mt(we.id,{type:_t.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:[a.jsx("option",{value:"mjpeg",children:i("settings.cameraTypeMjpeg")}),a.jsx("option",{value:"rtsp",children:i("settings.cameraTypeRtsp")}),a.jsx("option",{value:"snapshot",children:i("settings.cameraTypeSnapshot")}),a.jsx("option",{value:"usb",children:i("settings.cameraTypeUsb")})]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>Ay(we.id,Yc[we.id]??we.external_camera_url??"",we.external_camera_type||"mjpeg"),disabled:Ce[we.id]||!(Yc[we.id]??we.external_camera_url),children:Ce[we.id]?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):i("settings.test")})]}),Le[we.id]&&a.jsx("div",{className:`text-xs flex items-center gap-1 ${Le[we.id]?.success?"text-green-500":"text-red-500"}`,children:Le[we.id]?.success?a.jsxs(a.Fragment,{children:[a.jsx(xr,{className:"w-3 h-3"}),i("settings.connected"),Le[we.id]?.resolution&&` (${Le[we.id]?.resolution})`]}):a.jsxs(a.Fragment,{children:[a.jsx(Na,{className:"w-3 h-3"}),Le[we.id]?.error||i("settings.toast.connectionFailed")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:i("settings.cameraRotation")}),a.jsxs("select",{value:we.camera_rotation||0,onChange:_t=>mt(we.id,{rotation:parseInt(_t.target.value)}),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:0,children:"0°"}),a.jsx("option",{value:90,children:"90°"}),a.jsx("option",{value:180,children:"180°"}),a.jsx("option",{value:270,children:"270°"})]})]})]})]},we.id))}):a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),a.jsxs(At,{id:"card-cost",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.currency")}),a.jsx("select",{value:k.currency,onChange:we=>kn("currency",we.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:l7e.map(we=>a.jsx("option",{value:we.code,children:we.label},we.code))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultFilamentCost")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:So(k.currency)}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:k.default_filament_cost,onChange:we=>kn("default_filament_cost",parseFloat(we.target.value)||0),style:{paddingLeft:`${Math.max(2,So(k.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"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.electricityCost")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:So(k.currency)}),a.jsx("input",{type:"number",step:"0.001",min:"0",value:k.energy_cost_per_kwh,onChange:we=>kn("energy_cost_per_kwh",parseFloat(we.target.value)||0),style:{paddingLeft:`${Math.max(2,So(k.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"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.energyDisplayMode")}),a.jsxs("select",{value:k.energy_tracking_mode||"total",onChange:we=>kn("energy_tracking_mode",we.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:[a.jsx("option",{value:"print",children:i("settings.printsOnly")}),a.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:k.energy_tracking_mode==="print"?i("settings.energyModePrintDescription"):i("settings.energyModeTotalDescription")})]})]})]}),a.jsxs(At,{id:"card-filemanager",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),i("settings.fileManager")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.createArchiveEntry")}),a.jsxs("select",{value:k.library_archive_mode??"ask",onChange:we=>kn("library_archive_mode",we.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:[a.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),a.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),a.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.createArchiveEntryDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.lowDiskSpaceWarning")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:k.library_disk_warning_gb??5,onChange:we=>kn("library_disk_warning_gb",parseFloat(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.lowDiskSpaceDescription")})]})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-sm",children:[a.jsx(nnt,{}),a.jsxs(At,{id:"card-updates",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.updates")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider",children:i("settings.printerFirmware")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.checkFirmwareDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_printer_firmware??!0,onChange:we=>kn("check_printer_firmware",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider mb-4",children:i("settings.bambuddySoftware")})}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoCheckDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.check_updates,onChange:we=>kn("check_updates",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:`flex items-center justify-between ${k.check_updates?"":"opacity-50"}`,children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.includeBetaUpdates")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.includeBetaUpdatesDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.include_beta_updates??!1,onChange:we=>kn("include_beta_updates",we.target.checked),disabled:!k.check_updates,className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",fl?.version||"..."]})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>Kn(),disabled:Zn,children:[Zn?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),i("settings.checkNow")]})]}),xt?.update_available?a.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",xt.latest_version]}),xt.release_name&&xt.release_name!==xt.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:xt.release_name})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[xt.release_notes&&a.jsx("button",{onClick:()=>Be(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:i("settings.releaseNotes")}),xt.release_url&&a.jsx("a",{href:xt.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:a.jsx(na,{className:"w-4 h-4"})})]})]}),qt?.status==="downloading"||qt?.status==="installing"?a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:qt.message})]}),a.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${qt.progress}%`}})})]}):qt?.status==="complete"?a.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:qt.message}):qt?.status==="error"?a.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:qt.error||qt.message}):xt?.is_docker?a.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.updateViaDocker")}),a.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"})]}):a.jsxs(Fe,{className:"mt-3",onClick:()=>Pp.mutate(),disabled:Pp.isPending,children:[Pp.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(ca,{className:"w-4 h-4"}),i("settings.installUpdate")]})]}):xt?.error?a.jsx("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:i("settings.failedToCheckUpdates",{error:xt.error})}):xt&&!xt.update_available?a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:i("settings.latestVersionRunning")}):null]})]})]}),a.jsxs(At,{id:"card-data",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>ve(!0),children:[a.jsx(rn,{className:"w-4 h-4"}),i("common.clear")]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>Re(!0),children:[a.jsx(rn,{className:"w-4 h-4"}),i("settings.reset")]})]}),a.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.storageUsage","Storage Usage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageDescription","Breakdown of data usage by category")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Et,disabled:gt||Pe,children:[a.jsx(cr,{className:`w-4 h-4 ${gt||Pe?"animate-spin":""}`}),i("common.refresh","Refresh")]})]}),a.jsx("div",{className:"mt-3",children:Ve?a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("common.loading","Loading")]}):bt?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:bt.categories.filter(we=>we.bytes>0).map((we,_t)=>a.jsx("div",{className:`${hY(we.key,_t)} h-full`,style:{width:`${we.percent_of_total}%`},title:`${we.label}: ${we.formatted}`},we.key))}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:bt.categories.filter(we=>we.bytes>0).map((we,_t)=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:`w-3 h-3 rounded-full ${hY(we.key,_t)}`}),a.jsx("span",{className:"text-bambu-gray",children:we.label}),a.jsx("span",{className:"text-white",children:we.formatted}),a.jsxs("span",{className:"text-bambu-gray",children:["(",we.percent_of_total.toFixed(1),"%)"]})]},we.key))}),a.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[i("settings.storageUsageTotal","Total"),": ",a.jsx("span",{className:"text-white",children:bt.total_formatted}),bt.scan_errors>0&&a.jsxs("span",{className:"ml-2 text-amber-400",children:[i("settings.storageUsageErrors","Scan errors"),": ",bt.scan_errors]})]}),bt.other_breakdown?.length>0&&a.jsxs("div",{className:"mt-4",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("settings.storageUsageOtherBreakdown","Other breakdown")}),a.jsx("div",{className:"space-y-2",children:bt.other_breakdown.map(we=>a.jsxs("div",{className:"flex items-center justify-between text-xs",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white",children:we.label}),a.jsx("span",{className:`px-2 py-0.5 rounded-full border ${we.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:we.kind==="system"?i("settings.storageUsageSystem","System"):i("settings.storageUsageData","Data")})]}),a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx("span",{className:"text-white",children:we.formatted}),a.jsxs("span",{children:["(",we.percent_of_total.toFixed(1),"%)"]})]})]},`${we.bucket}-${we.kind}`))})]})]}):a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.backupRestore")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.backupRestoreDescription")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>Q("backup"),children:[a.jsx(Kl,{className:"w-4 h-4"}),i("settings.goToBackup")]})]})]})]})]})]}),B==="network"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[a.jsxs(At,{id:"card-externalurl",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(rl,{className:"w-5 h-5 text-blue-400"}),i("settings.externalUrl")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.externalUrlDescription")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bambuddyUrl")}),a.jsx("input",{type:"text",value:k.external_url??"",onChange:we=>kn("external_url",we.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.externalUrlHint")})]})]})]}),a.jsxs(At,{id:"card-ftpretry",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(cr,{className:"w-5 h-5 text-blue-400"}),i("settings.ftpRetry")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.ftpRetryDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoRetryDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ftp_retry_enabled??!0,onChange:we=>kn("ftp_retry_enabled",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),k.ftp_retry_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryAttempts")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_count??3,onChange:we=>kn("ftp_retry_count",parseInt(we.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(we=>a.jsx("option",{value:we,children:i("settings.time",{count:we})},we))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryDelay")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_retry_delay??2,onChange:we=>kn("ftp_retry_delay",parseInt(we.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(we=>a.jsx("option",{value:we,children:i("settings.second",{count:we})},we))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.connectionTimeout")}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:k.ftp_timeout??30,onChange:we=>kn("ftp_timeout",parseInt(we.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,180,300].map(we=>a.jsx("option",{value:we,children:i("settings.nSeconds",{count:we})},we))}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.increaseForWeakWifi")})]})]})]})]})]}),a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[a.jsxs(At,{id:"card-ha",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Rw,{className:"w-5 h-5 text-bambu-green"}),i("settings.homeAssistant")]}),k.ha_enabled&&ze&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${ze.success?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${ze.success?"text-green-400":"text-red-400"}`,children:ze.success?i("settings.connected"):i("settings.disconnected")})]})]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.homeAssistantFullDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),k.ha_env_managed&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx(pd,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ha_enabled??!1,onChange:we=>kn("ha_enabled",we.target.checked),disabled:k.ha_env_managed,className:"sr-only peer"}),a.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 ${k.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),k.ha_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.homeAssistantUrl"),k.ha_url_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:k.ha_url??"",onChange:we=>kn("ha_url",we.target.value),placeholder:"http://192.168.1.100:8123",disabled:k.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 ${k.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_url_from_env&&a.jsx(pd,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_url_from_env&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.longLivedAccessToken"),k.ha_token_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"password",value:k.ha_token??"",onChange:we=>kn("ha_token",we.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:k.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 ${k.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),k.ha_token_from_env&&a.jsx(pd,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),k.ha_token_from_env?a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.haTokenHint")})]}),k.ha_url&&k.ha_token&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs(Fe,{variant:"secondary",size:"sm",disabled:ht,onClick:async()=>{rt(!0),st(null);try{const we=await me.testHAConnection(k.ha_url,k.ha_token);st(we)}catch(we){st({success:!1,message:null,error:we instanceof Error?we.message:i("common.unknownError")})}finally{rt(!1)}},children:[ht?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Vh,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),a.jsxs(At,{id:"card-mqtt",children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Vh,{className:"w-5 h-5 text-blue-400"}),i("settings.mqttPublishing")]}),Ki?.enabled&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Ki.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${Ki.connected?"text-green-400":"text-red-400"}`,children:Ki.connected?i("settings.connected"):i("settings.disconnected")})]})]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttEnableDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_enabled??!1,onChange:we=>kn("mqtt_enabled",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),k.mqtt_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.brokerHostname")}),a.jsx("input",{type:"text",value:k.mqtt_broker??"",onChange:we=>kn("mqtt_broker",we.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"})]}),a.jsxs("div",{className:"flex items-end gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.port")}),a.jsx("input",{type:"number",min:"1",max:"65535",value:k.mqtt_port??1883,onChange:we=>kn("mqtt_port",Math.min(65535,Math.max(1,parseInt(we.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"})]}),a.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.mqtt_use_tls??!1,onChange:we=>{const _t=we.target.checked;kn("mqtt_use_tls",_t);const ln=k.mqtt_port??1883;_t&&ln===1883?kn("mqtt_port",8883):!_t&&ln===8883&&kn("mqtt_port",1883)},className:"sr-only peer"}),a.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"})]}),a.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.usernameOptional")}),a.jsx("input",{type:"text",value:k.mqtt_username??"",onChange:we=>kn("mqtt_username",we.target.value),placeholder:i("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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.passwordOptional")}),a.jsx("input",{type:"password",value:k.mqtt_password??"",onChange:we=>kn("mqtt_password",we.target.value),placeholder:i("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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.topicPrefix")}),a.jsx("input",{type:"text",value:k.mqtt_topic_prefix??"bambuddy",onChange:we=>kn("mqtt_topic_prefix",we.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.topicPrefixHint",{prefix:k.mqtt_topic_prefix||"bambuddy"})})]}),Ki&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${Ki.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:"text-bambu-gray",children:Ki.connected?a.jsxs(a.Fragment,{children:[i("settings.mqttConnectedTo")," ",a.jsxs("span",{className:"text-white",children:[Ki.broker,":",Ki.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),a.jsx("div",{className:"flex-1 lg:max-w-md space-y-3",children:a.jsxs(At,{id:"card-prometheus",children:[a.jsx(wn,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Q3,{className:"w-5 h-5 text-orange-400"}),i("settings.prometheusMetrics")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.prometheusEndpointDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.prometheus_enabled??!1,onChange:we=>kn("prometheus_enabled",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),k.prometheus_enabled&&a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bearerTokenOptional")}),a.jsx("input",{type:"password",value:k.prometheus_token??"",onChange:we=>kn("prometheus_token",we.target.value),placeholder:i("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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.bearerTokenHint")})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),a.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - ",i("settings.metricsConnectionStatus")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - ",i("settings.metricsPrinterState")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - ",i("settings.metricsPrintProgress")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - ",i("settings.metricsBedTemp")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - ",i("settings.metricsNozzleTemp")]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - ",i("settings.metricsPrintsTotal")]}),a.jsx("p",{className:"text-bambu-gray/70 italic",children:i("settings.metricsMore")})]})]})]})]})]})})]}),ze&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[ze.success?a.jsx(xr,{className:"w-8 h-8 text-green-400"}):a.jsx(Na,{className:"w-8 h-8 text-red-400"}),a.jsx("h3",{className:"text-lg font-medium text-white",children:ze.success?i("settings.connectionSuccessful"):i("settings.connectionFailed")})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:ze.success?ze.message||i("settings.haConnectionSuccess"):ze.error||i("settings.haConnectionFailed")}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Fe,{variant:"primary",onClick:()=>st(null),children:i("settings.ok")})})]})}),B==="plugs"&&a.jsxs("div",{id:"card-plugs",children:[a.jsxs("div",{className:"flex items-start justify-between mb-6",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ql,{className:"w-5 h-5 text-bambu-green"}),i("settings.smartPlugs")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.smartPlugsDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Gt&&Gt.filter(we=>we.enabled).length>1&&a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Te("on"),disabled:Io.isPending,title:i("settings.turnAllPlugsOn"),children:[Io.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Ud,{className:"w-4 h-4 text-bambu-green"}),i("settings.allOn")]}),a.jsxs(Fe,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Te("off"),disabled:Io.isPending,title:i("settings.turnAllPlugsOff"),children:[Io.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Uw,{className:"w-4 h-4 text-red-400"}),i("settings.allOff")]})]}),a.jsxs(Fe,{className:"whitespace-nowrap",onClick:()=>{L(null),z(!0)},children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addSmartPlug")]})]})]}),Gt&&Gt.length>0&&a.jsxs(At,{className:"mb-6",children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(ic,{className:"w-4 h-4 text-yellow-400"}),i("settings.energySummary"),Ln&&a.jsx(dt,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),a.jsx(Mt,{children:fn?a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(ic,{className:"w-3 h-3"}),i("settings.currentPower")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[fn.totalPower.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:i("settings.plugsOnline",{reachable:fn.reachableCount,total:fn.totalPlugs})})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Yr,{className:"w-3 h-3"}),i("settings.today")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[fn.totalToday.toFixed(3),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(fn.totalToday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",So(k?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(Q3,{className:"w-3 h-3"}),i("settings.yesterday")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[fn.totalYesterday.toFixed(3),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(fn.totalYesterday*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",So(k?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(aN,{className:"w-3 h-3"}),i("settings.total")]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[fn.totalLifetime.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(k?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(fn.totalLifetime*(k?.energy_cost_per_kwh??0)).toFixed(2)," ",So(k?.currency||"USD")]})]})]}):Ln?null:a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.enablePlugsForSummary")})})]}),on?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Gt&&Gt.length>0?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Gt.map(we=>a.jsx(Htt,{plug:we,onEdit:_t=>{L(_t),z(!0)}},we.id))}):a.jsx(At,{children:a.jsx(Mt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ql,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),a.jsxs(Fe,{onClick:()=>{L(null),z(!0)},children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),B==="notifications"&&a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-providers",children:[a.jsx(Uh,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>$(!0),children:[a.jsx(B0,{className:"w-4 h-4"}),i("settings.log")]}),yn&&yn.length>0&&a.jsxs(Fe,{size:"sm",variant:"secondary",onClick:()=>{co(null),wl.mutate()},disabled:wl.isPending,children:[wl.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Bw,{className:"w-4 h-4"}),i("settings.testAll")]}),a.jsxs(Fe,{size:"sm",onClick:()=>{ue(null),ie(!0)},children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addNotificationProvider")]})]})]}),a.jsx(At,{className:"mb-4",children:a.jsx(Mt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),a.jsx("select",{value:k.notification_language||"en",onChange:we=>kn("notification_language",we.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:J8.map(we=>a.jsx("option",{value:we.code,children:we.nativeName},we.code))})]})})}),a.jsx(At,{className:"mb-4",children:a.jsx(Mt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.bedCooledThreshold")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.bedCooledThresholdDescription")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:20,max:80,step:1,value:k.bed_cooled_threshold??35,onChange:we=>kn("bed_cooled_threshold",Number(we.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"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),a.jsx(At,{className:"mb-4",children:a.jsx(Mt,{className:"py-3",children:a.jsxs("div",{className:`flex items-center justify-between ${Qa?.advanced_auth_enabled?"":"opacity-50"}`,children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.userNotificationsEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Qa?.advanced_auth_enabled?i("settings.userNotificationsEnabledDescription"):i("settings.userNotificationsDisabledHint")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",className:"sr-only peer",checked:k.user_notifications_enabled??!0,disabled:!Qa?.advanced_auth_enabled,onChange:we=>kn("user_notifications_enabled",we.target.checked)}),a.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 peer-disabled:cursor-not-allowed"})]})]})})}),vl&&a.jsx(At,{className:"mb-4",children:a.jsxs(Mt,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),a.jsx("button",{onClick:()=>co(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(xr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:vl.success})]}),vl.failed>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(Na,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:vl.failed})]})]}),vl.results.filter(we=>!we.success).length>0&&a.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:vl.results.filter(we=>!we.success).map(we=>a.jsxs("div",{className:"text-xs text-red-400",children:[a.jsxs("span",{className:"font-medium",children:[we.provider_name,":"]})," ",we.message]},we.provider_id))})]})}),hn?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):yn&&yn.length>0?a.jsx("div",{className:"space-y-3",children:yn.map(we=>a.jsx($tt,{provider:we,onEdit:_t=>{ue(_t),ie(!0)}},we.id))}):a.jsx(At,{children:a.jsx(Mt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Uh,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),a.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),a.jsxs(Fe,{size:"sm",onClick:()=>{ue(null),ie(!0)},children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-2",id:"card-templates",children:[a.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:i("settings.messageTemplatesDescription")}),a.jsxs("div",{className:"relative mb-3",children:[a.jsx(kr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),a.jsx("input",{type:"text",value:W,onChange:we=>re(we.target.value),placeholder:i("settings.filterTemplates","Filter templates…"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),W&&a.jsx("button",{onClick:()=>re(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear filter",children:a.jsx(Bt,{className:"w-3.5 h-3.5"})})]}),On?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Pa&&Pa.length>0?(()=>{const we=W.trim().toLowerCase(),_t=[...Pa].sort((ln,mn)=>ln.name.localeCompare(mn.name)).filter(ln=>!we||ln.name.toLowerCase().includes(we)||(ln.title_template||"").toLowerCase().includes(we));return _t.length===0?a.jsx("p",{className:"text-sm text-bambu-gray italic text-center py-6",children:i("settings.noTemplatesMatch","No templates match your filter.")}):a.jsx("div",{className:"space-y-2",children:_t.map(ln=>a.jsx(At,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>oe(ln),children:a.jsx(Mt,{className:"py-2.5 px-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium text-sm truncate",children:ln.name}),a.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ln.title_template})]}),a.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:mn=>{mn.stopPropagation(),oe(ln)},children:a.jsx(Iu,{className:"w-4 h-4 text-bambu-gray"})})]})})},ln.id))})})():a.jsx(At,{children:a.jsx(Mt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ms,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),B==="apikeys"&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-createapi",children:[a.jsx(Ws,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),a.jsxs(Fe,{size:"sm",onClick:()=>J(!0),className:"flex-shrink-0",children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.createKey")]})]}),U&&a.jsx(At,{className:"mb-6 border-bambu-green",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(xr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[a.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:U}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(U);else{const we=document.createElement("textarea");we.value=U,we.style.position="fixed",we.style.left="-999999px",document.body.appendChild(we),we.select(),document.execCommand("copy"),document.body.removeChild(we)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:a.jsx(Fs,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-2 mt-3",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>{ye(U),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>R(null),children:i("common.dismiss")})]})]})]})})}),G&&a.jsxs(At,{className:"mb-6",children:[a.jsx(wn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),a.jsx("input",{type:"text",value:se,onChange:we=>fe(we.target.value),placeholder:i("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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:pe.can_read_status,onChange:we=>de(_t=>({..._t,can_read_status:we.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.readStatus")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:pe.can_queue,onChange:we=>de(_t=>({..._t,can_queue:we.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:pe.can_control_printer,onChange:we=>de(_t=>({..._t,can_control_printer:we.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[a.jsxs(Fe,{onClick:()=>Pn.mutate({name:se||i("settings.unnamedKey"),...pe}),disabled:Pn.isPending,children:[Pn.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(or,{className:"w-4 h-4"}),i("settings.createKey")]}),a.jsx(Fe,{variant:"secondary",onClick:()=>J(!1),children:i("common.cancel")})]})]})]}),Nn?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):xn&&xn.length>0?a.jsx("div",{className:"space-y-3",children:xn.map(we=>a.jsx(At,{children:a.jsx(Mt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Ws,{className:`w-5 h-5 ${we.enabled?"text-bambu-green":"text-bambu-gray"}`}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:we.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[we.key_prefix,"••••••••",we.last_used&&` · ${i("settings.lastUsed")}: ${Qf(we.last_used)}`]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex gap-1 text-xs",children:[we.can_read_status&&a.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),we.can_queue&&a.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),we.can_control_printer&&a.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>_e(we.id),children:a.jsx(rn,{className:"w-4 h-4 text-red-400"})})]})]})})},we.id))}):a.jsx(At,{children:a.jsx(Mt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ws,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),a.jsxs(Fe,{onClick:()=>J(!0),children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),a.jsxs(At,{className:"mt-6",children:[a.jsx(wn,{children:a.jsx("h3",{className:"text-base font-semibold text-white",id:"card-webhooks",children:i("settings.webhookEndpoints")})}),a.jsxs(Mt,{className:"space-y-3 text-sm",children:[a.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),a.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-green-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-red-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-apibrowser",children:[a.jsx(rl,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),a.jsx(At,{className:"mb-4",children:a.jsxs(Mt,{className:"py-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),a.jsx("input",{type:"text",value:Se,onChange:we=>ye(we.target.value),placeholder:i("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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),a.jsx(Snt,{apiKey:Se})]})]}),B==="virtual-printer"&&a.jsx("div",{id:"card-vp",children:a.jsx(int,{})}),B==="spoolbuddy"&&a.jsx("div",{id:"card-spoolbuddy",children:a.jsx(ont,{})}),B==="queue"&&k&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"lg:w-1/2 space-y-3",children:[a.jsxs(At,{id:"card-print-options",children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(lN,{className:"w-4 h-4 text-bambu-green"}),i("settings.defaultPrintOptions","Default Print Options")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.defaultPrintOptionsDescription","Set default values for print options when starting new prints. These can be overridden per print in the print dialog.")}),[{key:"default_bed_levelling",label:i("settings.defaultBedLevelling","Bed Levelling"),desc:i("settings.defaultBedLevellingDesc","Auto-level bed before print"),fallback:!0},{key:"default_flow_cali",label:i("settings.defaultFlowCali","Flow Calibration"),desc:i("settings.defaultFlowCaliDesc","Calibrate extrusion flow"),fallback:!1},{key:"default_vibration_cali",label:i("settings.defaultVibrationCali","Vibration Calibration"),desc:i("settings.defaultVibrationCaliDesc","Reduce ringing artifacts"),fallback:!0},{key:"default_layer_inspect",label:i("settings.defaultLayerInspect","First Layer Inspection"),desc:i("settings.defaultLayerInspectDesc","AI inspection of first layer"),fallback:!1},{key:"default_timelapse",label:i("settings.defaultTimelapse","Timelapse"),desc:i("settings.defaultTimelapseDesc","Record timelapse video"),fallback:!1}].map(({key:we,label:_t,desc:ln,fallback:mn})=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 mr-4",children:[a.jsx("p",{className:"text-sm text-white",children:_t}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:ln})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k[we]??mn,onChange:zt=>kn(we,zt.target.checked),className:"sr-only peer"}),a.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"})]})]},we))]})]}),a.jsxs(At,{id:"card-staggered",children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(aa,{className:"w-4 h-4 text-bambu-green"}),i("settings.staggeredStart","Staggered Start")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.staggeredStartDescription","Default group size and interval when staggering multi-printer batch starts. Can be overridden per batch in the print modal.")}),a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerGroupSize","Group size")}),a.jsx("input",{type:"number",min:1,max:50,value:k.stagger_group_size??2,onChange:we=>kn("stagger_group_size",Math.max(1,Math.min(50,parseInt(we.target.value)||1))),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerGroupSizeHelp","Printers to start simultaneously per group")})]}),a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerInterval","Interval (minutes)")}),a.jsx("input",{type:"number",min:1,max:60,value:k.stagger_interval_minutes??5,onChange:we=>kn("stagger_interval_minutes",Math.max(1,Math.min(60,parseInt(we.target.value)||1))),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerIntervalHelp","Delay between each group starting")})]})]})]})]}),a.jsxs(At,{id:"card-plate",children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(Du,{className:"w-4 h-4 text-bambu-green"}),i("settings.plateClear","Plate-Clear Confirmation")]})}),a.jsx(Mt,{className:"space-y-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 mr-4",children:[a.jsx("p",{className:"text-sm text-white",children:i("settings.requirePlateClear","Require plate-clear confirmation")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.requirePlateClearDescription","When enabled, the scheduler waits for per-printer plate-clear confirmation before starting queued prints on printers with finished jobs. Disable for farm workflows where plates are verified physically.")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.require_plate_clear??!1,onChange:we=>kn("require_plate_clear",we.target.checked),className:"sr-only peer"}),a.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"})]})]})})]}),a.jsxs(At,{id:"card-gcode",children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(oy,{className:"w-4 h-4 text-bambu-green"}),i("settings.gcodeInjection","G-code Injection")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.gcodeInjectionDescription",'Configure custom G-code to inject at the start and/or end of prints for auto-print systems like Farmloop, SwapMod, AutoClear, and Printflow 3D. Snippets are configured per printer model and applied when "Inject G-code" is enabled on a queue item.')}),(()=>{const we=(()=>{try{return k.gcode_snippets?JSON.parse(k.gcode_snippets):{}}catch{return{}}})(),_t=[...new Set((Sn||[]).filter(zt=>zt.model).map(zt=>zt.model))].sort(),ln=(zt,dn,mr)=>{const Vn={...we};Vn[zt]||(Vn[zt]={start_gcode:"",end_gcode:""}),Vn[zt][dn]=mr,!Vn[zt].start_gcode&&!Vn[zt].end_gcode&&delete Vn[zt];const yi=Object.keys(Vn).length>0?JSON.stringify(Vn):"";D(Bs=>Bs?{...Bs,gcode_snippets:yi}:null),Cm.current=yi},mn=()=>{Cm.current!==null&&(zo.mutate({gcode_snippets:Cm.current}),Cm.current=null)};return _t.length===0?a.jsx("p",{className:"text-sm text-bambu-gray italic",children:i("settings.gcodeInjectionNoPrinters","No printers found. Add printers to configure G-code snippets.")}):_t.map(zt=>{const dn=we[zt]||{start_gcode:"",end_gcode:""},mr=!!(dn.start_gcode||dn.end_gcode);return a.jsx(kle,{defaultOpen:mr,className:"border border-bambu-dark-tertiary rounded-lg px-3 py-2",summary:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:zt}),mr&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:i("settings.gcodeConfigured","Configured")})]}),children:a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeStartLabel","Start G-code")}),a.jsx("textarea",{value:dn.start_gcode,onChange:Vn=>ln(zt,"start_gcode",Vn.target.value),onBlur:mn,placeholder:i("settings.gcodeStartPlaceholder","G-code prepended before the print starts..."),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono focus:outline-none focus:border-bambu-green resize-y"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeEndLabel","End G-code")}),a.jsx("textarea",{value:dn.end_gcode,onChange:Vn=>ln(zt,"end_gcode",Vn.target.value),onBlur:mn,placeholder:i("settings.gcodeEndPlaceholder","G-code appended after the print ends..."),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono focus:outline-none focus:border-bambu-green resize-y"})]})]})},zt)})})()]})]})]}),a.jsx("div",{className:"lg:w-1/2 space-y-3",children:a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",id:"card-drying",children:[a.jsx(Au,{className:"w-4 h-4 text-amber-400"}),i("settings.queueDrying")]})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.queueDryingDescription")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingEnabledDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.queue_drying_enabled??!1,onChange:we=>kn("queue_drying_enabled",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),k.queue_drying_enabled&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingBlock")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingBlockDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.queue_drying_block??!1,onChange:we=>kn("queue_drying_block",we.target.checked),className:"sr-only peer"}),a.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-amber-500"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.ambientDryingEnabled")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.ambientDryingEnabledDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.ambient_drying_enabled??!1,onChange:we=>kn("ambient_drying_enabled",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:i("settings.dryingPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.dryingPresetsDescription")}),a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-1.5",children:i("settings.dryingFilament")}),a.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS 2 Pro"}),a.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS-HT"})]})}),a.jsx("tbody",{children:(()=>{const we={PLA:{n3f:45,n3s:45,n3f_hours:12,n3s_hours:12},PETG:{n3f:65,n3s:65,n3f_hours:12,n3s_hours:12},TPU:{n3f:65,n3s:75,n3f_hours:12,n3s_hours:18},ABS:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},ASA:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},PA:{n3f:65,n3s:85,n3f_hours:12,n3s_hours:12},PC:{n3f:65,n3s:80,n3f_hours:12,n3s_hours:8},PVA:{n3f:65,n3s:85,n3f_hours:12,n3s_hours:18}};let _t={...we};try{if(k.drying_presets){const mn=JSON.parse(k.drying_presets);typeof mn=="object"&&mn!==null&&(_t={...we,...mn})}}catch{}const ln=(mn,zt,dn)=>{const mr={..._t,[mn]:{..._t[mn],[zt]:dn}};kn("drying_presets",JSON.stringify(mr))};return Object.entries(_t).map(([mn,zt])=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50",children:[a.jsx("td",{className:"py-1.5 pr-2 text-white font-medium",children:mn}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a.jsx("input",{type:"number",min:30,max:65,value:zt.n3f,onChange:dn=>ln(mn,"n3f",Math.max(1,parseInt(dn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:zt.n3f_hours,onChange:dn=>ln(mn,"n3f_hours",Math.max(1,parseInt(dn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"h"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a.jsx("input",{type:"number",min:30,max:85,value:zt.n3s,onChange:dn=>ln(mn,"n3s",Math.max(1,parseInt(dn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),a.jsx("td",{className:"py-1 px-1",children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:zt.n3s_hours,onChange:dn=>ln(mn,"n3s_hours",Math.max(1,parseInt(dn.target.value)||0)),className:"w-14 px-1.5 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center text-xs focus:border-amber-500/50 focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-bambu-gray",children:"h"})]})})]},mn))})()})]})})]})]})]})})]}),B==="filament"&&k&&a.jsx(a.Fragment,{children:a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"lg:w-1/3 space-y-3",children:[a.jsx(Ztt,{}),a.jsxs(At,{id:"card-filamentchecks",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.filamentChecks")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.disableFilamentWarnings")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.disableFilamentWarningsDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.disable_filament_warnings,onChange:we=>kn("disable_filament_warnings",we.target.checked),className:"sr-only peer"}),a.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"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.preferLowestFilament")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.preferLowestFilamentDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.prefer_lowest_filament,onChange:we=>kn("prefer_lowest_filament",we.target.checked),className:"sr-only peer"}),a.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"})]})]})]})]}),a.jsxs(At,{id:"card-printmodal",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.printModal")})}),a.jsx(Mt,{className:"space-y-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.expandCustomMapping")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.expandCustomMappingDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k.per_printer_mapping_expanded??!1,onChange:we=>kn("per_printer_mapping_expanded",we.target.checked),className:"sr-only peer"}),a.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"})]})]})})]}),a.jsxs(At,{id:"card-amsthresholds",children:[a.jsx(wn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),a.jsxs(Mt,{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(yO,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_good??40,onChange:we=>kn("ams_humidity_good",parseInt(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:k.ams_humidity_fair??60,onChange:we=>kn("ams_humidity_fair",parseInt(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")}),a.jsx("p",{className:"text-xs text-amber-400/70",children:i("settings.fairAlsoDryingThreshold")})]}),a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(qw,{className:"w-4 h-4 text-orange-400"}),a.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_good??28,onChange:we=>kn("ams_temp_good",parseFloat(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:k.ams_temp_fair??35,onChange:we=>kn("ams_temp_fair",parseFloat(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Kl,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"1",max:"365",value:k.ams_history_retention_days??30,onChange:we=>kn("ams_history_retention_days",parseInt(we.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"}),a.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]})]})]})]}),a.jsxs("div",{className:"lg:w-2/3 space-y-3",children:[a.jsx(Jtt,{}),a.jsx(ent,{})]})]})}),ae!==null&&a.jsx(_n,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{Nr.mutate(ae),_e(null)},onCancel:()=>_e(null)}),H&&a.jsx(qtt,{plug:X,onClose:()=>{z(!1),L(null)}}),ne&&a.jsx(Gtt,{provider:ee,onClose:()=>{ie(!1),ue(null)}}),le&&a.jsx(Wtt,{template:le,onClose:()=>oe(null)}),Ne&&a.jsx(Xtt,{onClose:()=>$(!1)}),Ae&&a.jsx(_n,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{ve(!1);try{const we=await me.clearNotificationLogs(30);o(we.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>ve(!1)}),je&&a.jsx(_n,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{Re(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>Re(!1)}),Ee&&a.jsx(_n,{title:`Turn All Plugs ${Ee==="on"?"On":"Off"}`,message:`This will turn ${Ee==="on"?"ON":"OFF"} all ${Gt?.filter(we=>we.enabled).length||0} enabled smart plugs. ${Ee==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${Ee==="on"?"On":"Off"}`,variant:Ee==="off"?"danger":"warning",onConfirm:()=>{const we=Ee;Te(null),Io.mutate(we)},onCancel:()=>Te(null)}),Me&&xt?.release_notes&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Be(!1),children:a.jsxs(At,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:we=>we.stopPropagation(),children:[a.jsxs(wn,{className:"flex flex-row items-center justify-between shrink-0",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",xt.latest_version]}),xt.release_name&&xt.release_name!==xt.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray",children:xt.release_name})]}),a.jsx("button",{onClick:()=>Be(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx(Mt,{className:"overflow-y-auto flex-1",children:a.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:xt.release_notes})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[xt.release_url&&a.jsx("a",{href:xt.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:a.jsxs(Fe,{variant:"secondary",className:"w-full",children:[a.jsx(na,{className:"w-4 h-4"}),"View on GitHub"]})}),a.jsx(Fe,{onClick:()=>Be(!1),className:"flex-1",children:"Close"})]})]})}),B==="users"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>V("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${I==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Fu,{className:"w-4 h-4"}),i("settings.tabs.users")]}),a.jsxs("button",{onClick:()=>V("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${I==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(am,{className:"w-4 h-4"}),i("settings.tabs.emailAuth")||"Email Authentication",Qa?.advanced_auth_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>V("ldap"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px lg:border-b-0 lg:border-l-2 lg:-ml-px lg:mb-0 lg:justify-start flex items-center gap-2 ${I==="ldap"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Du,{className:"w-4 h-4"}),i("settings.tabs.ldap")||"LDAP",km?.ldap_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>V("twofa"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${I==="twofa"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Du,{className:"w-4 h-4"}),i("settings.tabs.twoFa"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Cp?.totp_enabled||Cp?.email_otp_enabled?"bg-green-400":"bg-bambu-gray/40"}`})]}),d&&a.jsxs("button",{onClick:()=>V("oidc"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${I==="oidc"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(rl,{className:"w-4 h-4"}),i("settings.tabs.oidc"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Gd.some(we=>we.is_enabled)?"bg-green-400":"bg-bambu-gray/40"}`})]})]}),I==="users"&&a.jsxs(a.Fragment,{children:[a.jsx(At,{children:a.jsx(Mt,{className:"py-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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?a.jsx(pd,{className:"w-5 h-5 text-green-400"}):a.jsx(u0,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&a.jsxs(Fe,{variant:"secondary",onClick:()=>tt(!0),children:[a.jsx(u0,{className:"w-4 h-4"}),i("common.disable")]}):a.jsxs(Fe,{onClick:()=>e("/setup"),children:[a.jsx(pd,{className:"w-4 h-4"}),i("common.enable")]})]})})}),Qa?.advanced_auth_enabled&&a.jsx(At,{className:"border-blue-500/30 bg-blue-500/5",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(am,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-3",children:[c&&a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-currentuser",children:[a.jsx(Fu,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),c.auth_source!=="ldap"&&a.jsxs(Fe,{size:"sm",variant:"ghost",onClick:()=>Ie(!0),children:[a.jsx(Ws,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),a.jsx(Mt,{children:a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),c.groups?.map(we=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${we.name==="Administrators"?"bg-purple-500/20 text-purple-300":we.name==="Operators"?"bg-blue-500/20 text-blue-300":we.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:we.name},we.id))]})]})})})]}),a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-users",children:[a.jsx(Fu,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),m("users:create")&&a.jsxs(Fe,{size:"sm",onClick:()=>{ut(!0),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),a.jsx(Mt,{children:Nm?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Xi.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Xi.map(we=>a.jsxs("div",{className:"py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:we.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[we.auth_source==="ldap"&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-cyan-500/20 text-cyan-300",children:"LDAP"}),we.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),we.groups?.map(_t=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${_t.name==="Administrators"?"bg-purple-500/20 text-purple-300":_t.name==="Operators"?"bg-blue-500/20 text-blue-300":_t.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:_t.name},_t.id))]})]}),a.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[m("users:update")&&a.jsx(Fe,{size:"sm",variant:"ghost",onClick:()=>gc(we),children:a.jsx(Iu,{className:"w-4 h-4"})}),m("users:delete")&&we.id!==c?.id&&a.jsx(Fe,{size:"sm",variant:"ghost",onClick:()=>Wd(we.id),children:a.jsx(rn,{className:"w-4 h-4"})})]})]},we.id))})})]})]}),a.jsx("div",{children:a.jsxs(At,{children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-groups",children:[a.jsx(Du,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),m("groups:create")&&a.jsxs(Fe,{size:"sm",onClick:()=>e("/groups/new"),children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),a.jsx(Mt,{children:Yi?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):vs.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:vs.map(we=>a.jsxs("div",{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Du,{className:`w-4 h-4 ${we.name==="Administrators"?"text-purple-400":we.name==="Operators"?"text-blue-400":we.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),a.jsx("span",{className:"text-white font-medium",children:we.name}),we.is_system&&a.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[m("groups:update")&&a.jsx(Fe,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${we.id}/edit`),children:a.jsx(Iu,{className:"w-4 h-4"})}),m("groups:delete")&&!we.is_system&&a.jsx(Fe,{size:"sm",variant:"ghost",onClick:()=>Ut(we.id),children:a.jsx(rn,{className:"w-4 h-4"})})]})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:we.description||i("settings.noDescription")}),a.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[a.jsx("span",{children:i("settings.userCount",{count:we.user_count})}),a.jsx("span",{children:i("settings.permissionCount",{count:we.permissions.length})})]})]},we.id))})})]})})]}),!l&&a.jsx(At,{children:a.jsx(Mt,{className:"py-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx(u0,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),a.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature1")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature2")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),a.jsxs(Fe,{onClick:()=>e("/setup"),children:[a.jsx(pd,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),I==="email"&&a.jsx("div",{className:"max-w-5xl",id:"card-smtp",children:a.jsx(mnt,{})}),I==="ldap"&&a.jsx("div",{className:"max-w-5xl",id:"card-ldap",children:a.jsx(pnt,{})}),I==="twofa"&&a.jsx("div",{className:"max-w-2xl",children:a.jsx(gnt,{})}),I==="oidc"&&d&&a.jsx("div",{className:"max-w-3xl",children:a.jsx(xnt,{})})]}),Ze&&!Qa?.advanced_auth_enabled&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{ut(!1),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(At,{className:"w-full max-w-md",onClick:we=>we.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{ut(!1),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Mt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),a.jsx("input",{type:"text",value:Pt.username,onChange:we=>pt({...Pt,username:we.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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),a.jsx("input",{type:"password",value:Pt.password,onChange:we=>pt({...Pt,password:we.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:i("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Pt.confirmPassword,onChange:we=>pt({...Pt,confirmPassword:we.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 ${Pt.confirmPassword&&Pt.password!==Pt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),Pt.confirmPassword&&Pt.password!==Pt.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groups")}),a.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:[vs.map(we=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pt.group_ids.includes(we.id),onChange:()=>Oo(we.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:we.name}),we.is_system&&a.jsx("span",{className:"text-xs text-yellow-400",children:i("settings.systemBadge")})]},we.id)),vs.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{ut(!1),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("common.cancel")}),a.jsx(Fe,{onClick:xi,disabled:zs.isPending||!Pt.username||!Pt.password||Pt.password!==Pt.confirmPassword||Pt.password.length<6,children:zs.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("settings.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(or,{className:"w-4 h-4"}),i("settings.createUser")]})})]})]})]})}),Ze&&Qa?.advanced_auth_enabled&&a.jsx(Qtt,{formData:Pt,setFormData:pt,groups:vs,onClose:()=>{ut(!1),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:xi,isCreating:zs.isPending,isCreateButtonDisabled:zs.isPending||!Pt.username||!Pt.email}),vt&&$t!==null&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{wt(!1),Qt(null),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(At,{className:"w-full max-w-md",onClick:we=>we.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Iu,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{wt(!1),Qt(null),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Mt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",Qa?.advanced_auth_enabled&&a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:Pt.username,onChange:we=>pt({...Pt,username:we.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:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",Qa?.advanced_auth_enabled?a.jsx("span",{className:"text-red-400",children:"*"}):a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),a.jsx("input",{type:"email",value:Pt.email,onChange:we=>pt({...Pt,email:we.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:i("users.form.emailPlaceholder")||"user@example.com",required:Qa?.advanced_auth_enabled})]}),!Qa?.advanced_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),a.jsx("input",{type:"password",value:Pt.password,onChange:we=>pt({...Pt,password:we.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:i("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),Pt.password&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Pt.confirmPassword,onChange:we=>pt({...Pt,confirmPassword:we.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 ${Pt.confirmPassword&&Pt.password!==Pt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Pt.confirmPassword&&Pt.password!==Pt.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),Qa?.advanced_auth_enabled&&a.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>$t&&xl.mutate($t),disabled:xl.isPending||!Pt.email,className:"w-full",children:xl.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):a.jsxs(a.Fragment,{children:[a.jsx(eo,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),a.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:vs.map(we=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pt.group_ids.includes(we.id),onChange:()=>Oo(we.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:we.name}),we.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},we.id))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{wt(!1),Qt(null),pt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),a.jsx(Fe,{onClick:()=>Us($t),disabled:bl.isPending||!Pt.username||Qa?.advanced_auth_enabled&&!Pt.email||!!(!Qa?.advanced_auth_enabled&&Pt.password&&(Pt.password!==Pt.confirmPassword||Pt.password.length<6)),children:bl.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):a.jsxs(a.Fragment,{children:[a.jsx(gs,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),en!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Xt(null),Ge(null)},children:a.jsxs(At,{className:"w-full max-w-md",onClick:we=>we.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[a.jsx(rn,{className:"w-5 h-5"}),a.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),a.jsx(Mt,{className:"space-y-3",children:Ft?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):tn&&tn.archives+tn.queue_items+tn.library_files>0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),a.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[tn.archives>0&&a.jsxs("li",{children:[tn.archives," archive",tn.archives!==1?"s":""]}),tn.queue_items>0&&a.jsxs("li",{children:[tn.queue_items," queue item",tn.queue_items!==1?"s":""]}),tn.library_files>0&&a.jsxs("li",{children:[tn.library_files," library file",tn.library_files!==1?"s":""]})]}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(Fe,{variant:"danger",onClick:()=>Za.mutate({id:en,deleteItems:!0}),disabled:Za.isPending,className:"justify-center",children:i("settings.deleteUserAndItems")}),a.jsx(Fe,{variant:"secondary",onClick:()=>Za.mutate({id:en,deleteItems:!1}),disabled:Za.isPending,className:"justify-center",children:i("settings.deleteUserKeepItems")}),a.jsx(Fe,{variant:"ghost",onClick:()=>{Xt(null),Ge(null)},disabled:Za.isPending,className:"justify-center",children:i("common.cancel")})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Fe,{variant:"ghost",onClick:()=>{Xt(null),Ge(null)},disabled:Za.isPending,children:i("common.cancel")}),a.jsx(Fe,{variant:"danger",onClick:()=>Za.mutate({id:en,deleteItems:!1}),disabled:Za.isPending,children:i("settings.deleteUserTitle")})]})]})})]})}),Wt!==null&&a.jsx(_n,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{yl.mutate(Wt),Ut(null)},onCancel:()=>Ut(null)}),B==="failure-detection"&&a.jsx("div",{id:"card-failure-detection",children:a.jsx(cnt,{})}),B==="backup"&&a.jsx("div",{id:"card-backup",children:a.jsx(lnt,{})}),Ke&&a.jsx(_n,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await me.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),tt(!1),window.location.href="/"}catch(we){const _t=we instanceof Error?we.message:i("settings.toast.authDisableFailed");o(_t,"error")}},onCancel:()=>tt(!1)}),te&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{Ie(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(At,{className:"w-full max-w-md",onClick:we=>we.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ws,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{Ie(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Mt,{children:[a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),a.jsx("input",{type:"password",value:be.currentPassword,onChange:we=>$e({...be,currentPassword:we.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:i("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),a.jsx("input",{type:"password",value:be.newPassword,onChange:we=>$e({...be,newPassword:we.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:i("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),a.jsx("input",{type:"password",value:be.confirmPassword,onChange:we=>$e({...be,confirmPassword:we.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 ${be.confirmPassword&&be.newPassword!==be.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),be.confirmPassword&&be.newPassword!==be.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>{Ie(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),a.jsx(Fe,{onClick:async()=>{if(be.newPassword!==be.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(be.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}ge(!0);try{await me.changePassword(be.currentPassword,be.newPassword),o(i("settings.toast.passwordChanged"),"success"),Ie(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})}catch(we){const _t=we instanceof Error?we.message:"Failed to change password";o(_t,"error")}finally{ge(!1)}},disabled:He||!be.currentPassword||!be.newPassword||be.newPassword!==be.confirmPassword||be.newPassword.length<6,children:He?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),i("settings.changing")]}):a.jsxs(a.Fragment,{children:[a.jsx(Ws,{className:"w-4 h-4"}),i("settings.changePassword")]})})]})]})]})})]})]})]})})}const Ple=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},Pnt=t=>t.startsWith("HH")?"HF":"S",Tnt=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Tle=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 p3({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:s,note:o}){const l=Pnt(t.nozzle_id),c=t.nozzle_diameter,d=()=>{r&&s?s():e()};return a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?a.jsx(xs,{className:"w-4 h-4 text-bambu-green"}):a.jsx(to,{className:"w-4 h-4"})}),a.jsxs("button",{onClick:d,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${i?"ring-1 ring-bambu-green":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Ple(t.k_value)}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&a.jsx("span",{title:"Has note",children:a.jsx(LQ,{className:"w-3 h-3 text-yellow-500"})}),a.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&a.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&&a.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:a.jsx(Fs,{className:"w-4 h-4"})})]})}function f3({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:i=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:d,onSaveNote:u,hasPermission:m}){const{t:p}=Rt(),{showToast:f}=bn(),[x,v]=w.useState(t?.name||""),[g,b]=w.useState(t?.k_value?Ple(t.k_value):"0.020"),[_,C]=w.useState(t?.filament_id||""),[P,N]=w.useState(t?.nozzle_id?Tnt(t.nozzle_id):"HH00"),[A,T]=w.useState(t?.nozzle_diameter||n),[F,k]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[D,H]=w.useState(!1),[z,X]=w.useState({current:0,total:0}),[L,ne]=w.useState(o),ie=ea.useMemo(()=>{const ce=new Map;for(const Ne of i)ce.set(Ne.filament_id,Ne.name);const xe=new Map;for(const Ne of r)if(Ne.filament_id&&!xe.has(Ne.filament_id)){const Y=ce.get(Ne.filament_id)||Tle(Ne.name||"");xe.set(Ne.filament_id,{id:Ne.filament_id,name:Y||Ne.filament_id})}return Array.from(xe.values()).sort((Ne,$)=>Ne.name.localeCompare($.name))},[r,i]),ee=it({mutationFn:ce=>(console.log("[KProfile] Calling API..."),me.setKProfile(e,ce)),onSuccess:ce=>{if(console.log("[KProfile] Save success:",ce),f(p("kProfiles.toast.profileSaved")),u&&L!==o){let xe;L===""&&l?xe=l:t&&t.slot_id>0?xe=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:xe=`name_${x}_${_}`,u(xe,L)}H(!0),setTimeout(()=>{H(!1),d()},2500)},onError:ce=>{console.error("[KProfile] Save error:",ce),f(ce.message,"error"),H(!1)}}),ue=it({mutationFn:ce=>(console.log("[KProfile] Deleting profile..."),me.deleteKProfile(e,ce)),onSuccess:ce=>{console.log("[KProfile] Delete success:",ce),f(p("kProfiles.toast.profileDeleted")),H(!0),setTimeout(()=>{H(!1),c()},4e3)},onError:ce=>{console.error("[KProfile] Delete error:",ce),f(ce.message,"error"),H(!1)}}),[le,oe]=w.useState(!1),W=()=>{t&&ue.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})},re=async ce=>{if(ce.preventDefault(),s&&!t&&F.length===0){f(p("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const xe=parseFloat(g).toFixed(6),Ne=`${P}-${A}`;if(t||F.length===1){const Y={name:x,k_value:xe,filament_id:_,nozzle_id:Ne,nozzle_diameter:A,extruder_id:t?t.extruder_id:F[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",Y),ee.mutate(Y);return}H(!0),X({current:1,total:F.length});const $=F.map(Y=>({name:x,k_value:xe,filament_id:_,nozzle_id:Ne,nozzle_diameter:A,extruder_id:Y,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${$.length} profiles in batch:`,$);try{if(await me.setKProfilesBatch(e,$),f(p("kProfiles.toast.profilesSaved",{count:F.length})),u&&L){const Y=`name_${x}_${_}`;u(Y,L)}}catch(Y){console.error("[KProfile] Failed to save batch:",Y),f(p("kProfiles.toast.failedToSaveBatch"),"error"),H(!1),X({current:0,total:0});return}X({current:F.length,total:F.length}),setTimeout(()=>{H(!1),X({current:0,total:0}),d()},3e3)};return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[a.jsxs(At,{className:"w-full max-w-md relative",children:[D&&a.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:z.total>1?p("kProfiles.modal.savingExtruder",{current:z.current,total:z.total}):p("kProfiles.modal.syncing")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:p("kProfiles.modal.pleaseWait")})]}),a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:p(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),a.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:D,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:re,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.profileName")}),a.jsx("input",{type:"text",value:x,onChange:ce=>v(ce.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:p("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.kValue")}),a.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:ce=>{const xe=ce.target.value;(xe===""||/^\d*\.?\d*$/.test(xe))&&b(xe)},onBlur:ce=>{const xe=parseFloat(ce.target.value);isNaN(xe)||b((Math.trunc(xe*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:p("kProfiles.modal.kValuePlaceholder"),required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.kValueHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.filament")}),a.jsxs("select",{value:_,onChange:ce=>{const xe=ce.target.value;if(C(xe),!t&&xe&&!x){const Ne=ie.find($=>$.id===xe);Ne&&v(`${P==="HH00"?"HF":"S"} ${Ne.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:[a.jsx("option",{value:"",children:p("kProfiles.modal.selectFilament")}),t?.filament_id&&a.jsx("option",{value:t.filament_id,children:ie.find(ce=>ce.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&ie.map(ce=>a.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),!t&&ie.length===0&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.noFilamentsHelp")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.flowType")}),a.jsxs("select",{value:P,onChange:ce=>{const xe=ce.target.value;if(N(xe),!t&&_&&!x){const Ne=ie.find($=>$.id===_);Ne&&v(`${xe==="HS00"?"HF":"S"} ${Ne.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:[a.jsx("option",{value:"HH00",children:p("kProfiles.modal.highFlow")}),a.jsx("option",{value:"HS00",children:p("kProfiles.modal.standard")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.nozzleSize")}),a.jsxs("select",{value:A,onChange:ce=>T(ce.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:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?a.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?p("kProfiles.modal.left"):p("kProfiles.modal.right")}):a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:F.includes(1),onChange:ce=>{ce.target.checked?k([...F,1]):k(F.filter(xe=>xe!==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"}),a.jsx("span",{className:"text-white",children:p("kProfiles.modal.left")})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:F.includes(0),onChange:ce=>{ce.target.checked?k([...F,0]):k(F.filter(xe=>xe!==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"}),a.jsx("span",{className:"text-white",children:p("kProfiles.modal.right")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.notes")}),a.jsx("textarea",{value:L,onChange:ce=>ne(ce.target.value),placeholder:p("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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.notesHelp")})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&a.jsx(Fe,{type:"button",variant:"secondary",onClick:()=>oe(!0),disabled:ue.isPending||D||!m("kprofiles:delete"),title:m("kprofiles:delete")?void 0:p("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:ue.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"})}),a.jsx(Fe,{type:"button",variant:"secondary",onClick:c,disabled:D,className:"flex-1",children:p("common.cancel")}),a.jsxs(Fe,{type:"submit",disabled:ee.isPending||D||!m(t?"kprofiles:update":"kprofiles:create"),title:m(t?"kprofiles:update":"kprofiles:create")?void 0:p(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[ee.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(Fw,{className:"w-4 h-4"}),p("common.save")]})]})]})]})]}),le&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:a.jsx(At,{className:"w-full max-w-sm",children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(rn,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:p("kProfiles.deleteConfirm.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:p("kProfiles.deleteConfirm.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:p("kProfiles.deleteConfirm.message",{name:t?.name})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>oe(!1),className:"flex-1",children:p("common.cancel")}),a.jsxs(Fe,{onClick:()=>{oe(!1),W()},disabled:ue.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[ue.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),p("common.delete")]})]})]})})})]})}const yk={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function Ant(){const{t}=Rt(),{showToast:e}=bn(),{hasPermission:n}=wr(),[r,i]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(yk.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,x]=w.useState(""),[v,g]=w.useState("all"),[b,_]=w.useState("all"),[C,P]=w.useState(()=>localStorage.getItem(yk.SORT_OPTION)||"name"),[N,A]=w.useState(!1),[T,F]=w.useState(new Set),[k,D]=w.useState(!1),[H,z]=w.useState(!1),X=w.useCallback(R=>`${R.slot_id}_${R.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(yk.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(yk.SORT_OPTION,C)},[C]);const{data:L,isLoading:ne}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:ie,isLoading:ee,isFetching:ue,error:le,refetch:oe}=Qe({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const R=await me.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:W}=Qe({queryKey:["kprofiles",r,"0.4"],queryFn:()=>me.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:re}=Qe({queryKey:["builtinFilaments"],queryFn:()=>me.getBuiltinFilaments(),staleTime:3e5}),{data:ce}=Qe({queryKey:["filamentIdMap"],queryFn:()=>me.getFilamentIdMap(),staleTime:3e5}),{data:xe,refetch:Ne}=Qe({queryKey:["kprofile-notes",r],queryFn:()=>me.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),$=le?.message?.includes("not connected");w.useEffect(()=>{if(!r&&L&&L.length>0){const R=L.find(ae=>ae.is_active);R&&i(R.id)}},[r,L]),w.useEffect(()=>{if(r){const R=setTimeout(()=>{oe()},150);return()=>clearTimeout(R)}},[r,s]);const Y=L?.filter(R=>R.is_active)||[],E=ea.useMemo(()=>{const R=new Map;if(re)for(const ae of re)R.set(ae.filament_id,ae.name);if(ce)for(const[ae,_e]of Object.entries(ce))R.has(ae)||R.set(ae,_e);return R},[re,ce]),j=ea.useMemo(()=>Array.from(E.entries()).map(([R,ae])=>({filament_id:R,name:ae})),[E]),O=ea.useCallback(R=>E.get(R.filament_id)||Tle(R.name),[E]),K=ea.useMemo(()=>ie?.profiles?ie.profiles.filter(ae=>{const _e=f.toLowerCase(),Se=!_e||ae.name.toLowerCase().includes(_e)||ae.filament_id.toLowerCase().includes(_e),ye=v==="all"||v==="left"&&ae.extruder_id===1||v==="right"&&ae.extruder_id===0,Ae=b==="all"||b==="hf"&&ae.nozzle_id.startsWith("HH")||b==="s"&&ae.nozzle_id.startsWith("HS");return Se&&ye&&Ae}).sort((ae,_e)=>{switch(C){case"k_value":return parseFloat(ae.k_value)-parseFloat(_e.k_value);case"filament":return O(ae).localeCompare(O(_e));default:return ae.name.localeCompare(_e.name)}}):[],[ie?.profiles,f,v,b,C,O]),B=L?.find(R=>R.id===r),he=B?.nozzle_count===2;w.useEffect(()=>{const R=ae=>{ae.target instanceof HTMLInputElement||ae.target instanceof HTMLTextAreaElement||ae.target instanceof HTMLSelectElement||l||d||m||(ae.key==="r"||ae.key==="R"?(ae.preventDefault(),oe()):ae.key==="n"||ae.key==="N"?(ae.preventDefault(),u(!0)):ae.key==="Escape"&&N&&(ae.preventDefault(),A(!1),F(new Set)))};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[l,d,m,N,oe]);const I=w.useCallback(()=>{if(!ie?.profiles||ie.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const R={version:1,exported_at:new Date().toISOString(),printer:B?.name||"Unknown",nozzle_diameter:s,profiles:ie.profiles.map(ye=>({name:ye.name,k_value:ye.k_value,filament_id:ye.filament_id,nozzle_id:ye.nozzle_id,nozzle_diameter:ye.nozzle_diameter,extruder_id:ye.extruder_id}))},ae=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),_e=URL.createObjectURL(ae),Se=document.createElement("a");Se.href=_e,Se.download=`kprofiles_${B?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se),URL.revokeObjectURL(_e),e(t("kProfiles.toast.exportedProfiles",{count:ie.profiles.length}))},[ie?.profiles,B,s,e,t]),V=w.useCallback(()=>{const R=document.createElement("input");R.type="file",R.accept=".json",R.onchange=async ae=>{const _e=ae.target.files?.[0];if(_e)try{const Se=await _e.text(),ye=JSON.parse(Se);if(!ye.profiles||!Array.isArray(ye.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let Ae=0;for(const ve of ye.profiles)if(!(!ve.name||!ve.k_value||!ve.filament_id))try{await me.setKProfile(r,{name:ve.name,k_value:parseFloat(ve.k_value).toFixed(6),filament_id:ve.filament_id,nozzle_id:ve.nozzle_id||`HH00-${s}`,nozzle_diameter:ve.nozzle_diameter||s,extruder_id:ve.extruder_id??0,slot_id:0}),Ae++,await new Promise(je=>setTimeout(je,500))}catch(je){console.error("Failed to import profile:",ve.name,je)}e(t("kProfiles.toast.importedProfiles",{count:Ae,total:ye.profiles.length})),oe()}catch(Se){console.error("Import error:",Se),e(t("kProfiles.toast.failedToParseImport"),"error")}},R.click()},[r,s,e,oe,t]),Q=w.useCallback(R=>{F(ae=>{const _e=new Set(ae);return _e.has(R)?_e.delete(R):_e.add(R),_e})},[]),G=w.useCallback(()=>{F(new Set(K.map(R=>X(R))))},[K,X]),J=w.useCallback(()=>{T.size!==0&&D(!0)},[T.size]),se=w.useCallback(async()=>{const R=K.filter(_e=>T.has(X(_e)));z(!0);let ae=0;for(const _e of R)try{await me.deleteKProfile(r,{slot_id:_e.slot_id,extruder_id:_e.extruder_id,nozzle_id:_e.nozzle_id,nozzle_diameter:_e.nozzle_diameter,filament_id:_e.filament_id,setting_id:_e.setting_id}),ae++,await new Promise(Se=>setTimeout(Se,300))}catch(Se){console.error("Failed to delete profile:",_e.name,Se)}e(t("kProfiles.toast.profilesDeleted",{count:ae})),z(!1),D(!1),A(!1),F(new Set),oe()},[r,T,K,e,oe,X,t]),fe=w.useCallback(R=>{const ae=[];return R.setting_id&&ae.push(R.setting_id),ae.push(`slot_${R.slot_id}_${R.filament_id}_${R.extruder_id}`),ae.push(`name_${R.name}_${R.filament_id}`),ae},[]),pe=w.useCallback(async(R,ae)=>{if(r)try{await me.setKProfileNote(r,R,ae),Ne()}catch(_e){console.error("Failed to save note:",_e),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,Ne,e,t]),de=w.useCallback(R=>{if(!xe?.notes)return{note:"",key:null};const ae=fe(R);for(const _e of ae)if(xe.notes[_e])return{note:xe.notes[_e],key:_e};return{note:"",key:null}},[xe,fe]),U=w.useCallback(R=>de(R).note,[de]);return ne?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!L||L.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"py-12 text-center",children:[a.jsx(Wa,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):Y.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"py-12 text-center",children:[a.jsx(Ar,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):a.jsxs(a.Fragment,{children:[ue&&!ee&&a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[a.jsx(dt,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1 min-w-48",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),a.jsx("select",{value:r||"",onChange:R=>i(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:Y.map(R=>a.jsx("option",{value:R.id,children:R.name},R.id))})]}),a.jsxs("div",{className:"w-32",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),a.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:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>oe(),disabled:ue||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[a.jsx(cr,{className:`w-4 h-4 ${ue?"animate-spin":""}`}),t("kProfiles.refresh")]}),a.jsxs(Fe,{onClick:()=>u(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[a.jsx(or,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[a.jsxs("div",{className:"flex-1 min-w-48 relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:f,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"})]}),he&&a.jsx("div",{className:"w-36",children:a.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:[a.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),a.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),a.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:b,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:[a.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),a.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),a.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:C,onChange:R=>P(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:[a.jsx("option",{value:"name",children:t("kProfiles.sortName")}),a.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),a.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[a.jsxs(Fe,{variant:"secondary",onClick:I,disabled:!ie?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[a.jsx(ca,{className:"w-4 h-4"}),t("kProfiles.export")]}),a.jsxs(Fe,{variant:"secondary",onClick:V,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[a.jsx(Ma,{className:"w-4 h-4"}),t("kProfiles.import")]}),a.jsx("div",{className:"flex-1"}),N?a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"secondary",onClick:G,children:[a.jsx(xs,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),a.jsxs(Fe,{variant:"secondary",onClick:J,disabled:T.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:[a.jsx(rn,{className:"w-4 h-4"}),t("kProfiles.delete")," (",T.size,")"]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>{A(!1),F(new Set)},children:[a.jsx(Bt,{className:"w-4 h-4"}),t("common.cancel")]})]}):a.jsxs(Fe,{variant:"secondary",onClick:()=>A(!0),disabled:!K.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(xs,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),ee?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):$?a.jsx(At,{children:a.jsxs(Mt,{className:"py-12 text-center",children:[a.jsx(Md,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),a.jsxs(Fe,{variant:"secondary",onClick:()=>oe(),children:[a.jsx(cr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):K.length>0?he?a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),a.jsx("div",{className:"space-y-1",children:K.filter(R=>R.extruder_id===1).map(R=>a.jsx(p3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:T.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),a.jsx("div",{className:"space-y-1",children:K.filter(R=>R.extruder_id===0).map(R=>a.jsx(p3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:T.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))})]})]}):a.jsx("div",{className:"space-y-1",children:K.map(R=>a.jsx(p3,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:N,isSelected:T.has(X(R)),onToggleSelect:()=>Q(X(R)),note:U(R)},X(R)))}):f||v!=="all"||b!=="all"?a.jsx(At,{children:a.jsxs(Mt,{className:"py-12 text-center",children:[a.jsx(kr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):a.jsx(At,{children:a.jsxs(Mt,{className:"py-12 text-center",children:[a.jsx(Fw,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),a.jsxs(Fe,{onClick:()=>u(!0),children:[a.jsx(or,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:R,key:ae}=de(l);return a.jsx(f3,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:W?.profiles||ie?.profiles,builtinFilaments:j,isDualNozzle:he,initialNote:R,initialNoteKey:ae,onSaveNote:pe,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),oe()},onSave:()=>{c(null),oe()}})})(),d&&r&&a.jsx(f3,{printerId:r,nozzleDiameter:s,existingProfiles:W?.profiles||ie?.profiles,builtinFilaments:j,isDualNozzle:he,onSaveNote:pe,hasPermission:n,onClose:()=>{u(!1),oe()},onSave:()=>{u(!1),oe()}}),m&&r&&a.jsx(f3,{printerId:r,nozzleDiameter:s,existingProfiles:W?.profiles||ie?.profiles,builtinFilaments:j,isDualNozzle:he,onSaveNote:pe,hasPermission:n,profile:{...m,slot_id:0,name:`${m.name} (Copy)`},onClose:()=>{p(null),oe()},onSave:()=>{p(null),oe()}}),k&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-sm",children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(rn,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:T.size})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>D(!1),disabled:H,className:"flex-1",children:t("common.cancel")}),a.jsxs(Fe,{onClick:se,disabled:H,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[H?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Ale=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],jnt={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 Mnt(t){const e=t.toUpperCase();for(const n of Ale)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function Ent(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of Ale){const i=n.indexOf(r);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function g3({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:i}=Rt(),{hasPermission:s}=wr(),o=t.filament_type||Mnt(t.name),l=t.filament_vendor||Ent(t.name);let c=null,d=!1;if(t.default_filament_colour)try{const u=JSON.parse(t.default_filament_colour),m=Array.isArray(u)?u[0]:u;typeof m=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(m.replace("#",""))&&(c=m.replace("#","").slice(0,6),d=!0)}catch{const u=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(u.replace("#",""))&&(c=u.replace("#","").slice(0,6),d=!0)}return!c&&o&&(c=jnt[o.toUpperCase()]||null),a.jsx(At,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:a.jsxs(Mt,{className:"p-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&a.jsx("div",{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0 ${!d&&!c?"opacity-25":d?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),a.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&a.jsx("span",{className:"text-xs text-bambu-gray",children:l}),a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&a.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:a.jsx(rn,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?a.jsx(ac,{className:"w-3.5 h-3.5"}):a.jsx(Un,{className:"w-3.5 h-3.5"})})]})]}),r&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),a.jsx("span",{className:"text-white",children:o})]}),l&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),a.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),a.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),a.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),a.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),a.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),a.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&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),a.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),a.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function Dnt(){const{t}=Rt(),{hasPermission:e}=wr(),n=sn(),{showToast:r}=bn(),[i,s]=w.useState(""),[o,l]=w.useState(null),[c,d]=w.useState(!1),[u,m]=w.useState(null),{data:p,isLoading:f}=Qe({queryKey:["localPresets"],queryFn:()=>me.getLocalPresets()}),x=it({mutationFn:async T=>{const F=[];for(const k of Array.from(T)){const D=new FormData;D.append("file",k),F.push(await me.importLocalPresets(D))}return F},onSuccess:T=>{n.invalidateQueries({queryKey:["localPresets"]});let F=0,k=0,D=0;for(const H of T)F+=H.imported,k+=H.skipped,D+=H.errors.length;F>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:F})),k>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:k}),"warning"),D>0&&r(t("profiles.localProfiles.toast.importError",{count:D}),"error")},onError:T=>{r(T.message,"error")}}),v=it({mutationFn:T=>me.deleteLocalPreset(T),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),m(null),r(t("profiles.localProfiles.toast.deleted"))}}),g=w.useCallback(T=>{!T||T.length===0||x.mutate(T)},[x]),b=w.useCallback(T=>{T.preventDefault(),d(!1),g(T.dataTransfer.files)},[g]),_=w.useCallback(T=>{if(!i)return T;const F=i.toLowerCase();return T.filter(k=>k.name.toLowerCase().includes(F)||k.filament_type?.toLowerCase().includes(F)||k.filament_vendor?.toLowerCase().includes(F))},[i]),C=w.useMemo(()=>_(p?.filament||[]),[p?.filament,_]),P=w.useMemo(()=>_(p?.printer||[]),[p?.printer,_]),N=w.useMemo(()=>_(p?.process||[]),[p?.process,_]),A=C.length+P.length+N.length;return f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&a.jsxs("div",{onDragOver:T=>{T.preventDefault(),d(!0)},onDragLeave:()=>d(!1),onDrop:b,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:[a.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:T=>g(T.target.files)}),x.isPending?a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx(dt,{className:"w-5 h-5 text-bambu-green animate-spin"}),a.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ma,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),A>0&&a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:i,onChange:T=>s(T.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"})]}),A===0&&!f&&a.jsxs("div",{className:"text-center py-12",children:[a.jsx(rp,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),A>0&&a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[C.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(TP,{className:"w-4 h-4 text-bambu-green"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",C.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:C.map(T=>a.jsx(g3,{preset:T,onDelete:F=>m(F),onExpand:l,isExpanded:o===T.id},T.id))})]}),N.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(aa,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:N.map(T=>a.jsx(g3,{preset:T,onDelete:F=>m(F),onExpand:l,isExpanded:o===T.id},T.id))})]}),P.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(jd,{className:"w-4 h-4 text-orange-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",P.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:P.map(T=>a.jsx(g3,{preset:T,onDelete:F=>m(F),onExpand:l,isExpanded:o===T.id},T.id))})]})]}),u!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Wa,{className:"w-5 h-5 text-red-400"}),a.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Fe,{variant:"secondary",size:"sm",onClick:()=>m(null),children:t("profiles.localProfiles.cancel")}),a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>v.mutate(u),disabled:v.isPending,children:[v.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function r5(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),i=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,d=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),u=d?d[1].toUpperCase():null;return{printer:i,nozzle:o,layerHeight:c,filamentType:u}}function jw(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function Fnt({onSuccess:t,t:e}){const{showToast:n}=bn(),[r,i]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(""),[m,p]=w.useState(""),[f,x]=w.useState("global"),[v,g]=w.useState(null),[b,_]=w.useState(null),C=it({mutationFn:()=>me.cloudLogin(s,l,f),onSuccess:F=>{F.success?(n(e("profiles.login.toast.loggedIn")),t()):F.needs_verification?(g(F.verification_type||"email"),_(F.tfa_key||null),F.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(F.message,"error")},onError:F=>n(F.message,"error")}),P=it({mutationFn:()=>me.cloudVerify(s,d,b||void 0),onSuccess:F=>{F.success?(n(e("profiles.login.toast.loggedIn")),t()):n(F.message,"error")},onError:F=>n(F.message,"error")}),N=it({mutationFn:()=>me.cloudSetToken(m),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:F=>n(F.message,"error")}),A=F=>{F.preventDefault(),r==="email"?C.mutate():r==="code"?P.mutate():r==="token"&&N.mutate()},T=C.isPending||P.isPending||N.isPending;return a.jsx(At,{className:"max-w-md mx-auto",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:a.jsx(sy,{className:"w-6 h-6 text-bambu-green"})}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),a.jsxs("form",{onSubmit:A,className:"space-y-4",children:[r==="email"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),a.jsx("input",{type:"email",value:s,onChange:F=>o(F.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),a.jsx("input",{type:"password",value:l,onChange:F=>c(F.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),a.jsxs("select",{value:f,onChange:F=>x(F.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:[a.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),a.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),a.jsx("input",{type:"text",value:d,onChange:F=>u(F.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"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),a.jsx("textarea",{value:m,onChange:F=>p(F.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})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r==="code"&&a.jsx(Fe,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),a.jsxs(Fe,{type:"submit",disabled:T,className:"flex-1",children:[T?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(xH,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(Ws,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(xH,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Wb({label:t,value:e,options:n,onChange:r}){const[i,s]=w.useState(!1),o=n.find(l=>l.value===e);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>s(!i),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:[a.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),a.jsx("span",{children:o?.label||"All"}),a.jsx(Un,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),a.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=>a.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:[a.jsx("span",{children:l.label}),l.count!==void 0&&a.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function Rnt(){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?a.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:a.jsx(Wf,{className:"w-5 h-5"})}):null}function b3({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=r5(t.name),d=jw(t.setting_id);return a.jsxs("div",{className:"flex items-center gap-2 group",children:[a.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${i?"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:a.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&a.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}),!i&&d&&a.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),a.jsx("button",{onClick:u=>{u.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:a.jsx(Fs,{className:"w-4 h-4"})})]})}function XL(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(`
- `)){const i=t.replace(/\\n/g,`
- `).replace(/\\"/g,'"').replace(/\\t/g," ").split(`
- `);if(i.length>1)return`"""
- `+i.map(s=>n+" "+s).join(`
- `)+`
- `+n+'"""'}return JSON.stringify(t)}if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":`[
- `+t.map(i=>n+" "+XL(i,e+1)).join(`,
- `)+`
- `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{
- `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+XL(o,e+1)).join(`,
- `)+`
- `+n+"}"}return String(t)}function Lnt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=bn(),c=sn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=Qe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>me.getCloudSettingDetail(t.setting_id)}),f=it({mutationFn:()=>me.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),x=jw(t.setting_id),v=r5(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&a.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")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.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:XL(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Rn,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Fe,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(rn,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Fe,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Fs,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&a.jsxs(a.Fragment,{children:[a.jsxs(Fe,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(ai,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Fe,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(rn,{className:"w-4 h-4"})})]})]})})]})})})}function jle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Mle(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Ont({onClose:t,onApply:e,t:n}){const{showToast:r}=bn(),[i,s]=w.useState(jle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[x,v]=w.useState("{}"),[g,b]=w.useState(null),[_,C]=w.useState(null),P=o==="all"?i:i.filter(X=>X.type===o),N=X=>{s(X),Mle(X)},A=X=>{const L=i.filter(ne=>ne.id!==X);N(L),C(null),r(n("profiles.templates.toast.deleted"))},T=X=>{d(X.id),m(X.name),f(X.description),v(JSON.stringify(X.settings,null,2)),b(null)},F=()=>{if(!(!c||!u.trim()))try{const X=JSON.parse(x),L=i.map(ne=>ne.id===c?{...ne,name:u.trim(),description:p.trim(),settings:X}:ne);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(X){b(X.message)}},k=()=>{d(null),m(""),f(""),v("{}"),b(null)},D=X=>{const L=i.map(ne=>ne.id===X?{...ne,showInModal:!ne.showInModal}:ne);N(L)},H={filament:{label:n("profiles.presets.types.filament"),icon:TP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:jd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Ar,color:"text-purple-400"}},z=_?i.find(X=>X.id===_):null;return w.useEffect(()=>{const X=L=>{L.key==="Escape"&&(_?C(null):c?k():t())};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(At,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Rn,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:()=>C(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Fe,{onClick:()=>A(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(rn,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(At,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ax,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(X=>a.jsx("button",{onClick:()=>l(X),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:X==="all"?n("common.all"):H[X].label},X))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(Ax,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(X=>{const L=H[X.type],ne=L.icon;return c===X.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ie=>m(ie.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}),a.jsx("input",{type:"text",value:p,onChange:ie=>f(ie.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"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:x,onChange:ie=>{v(ie.target.value),b(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Fe,{size:"sm",onClick:F,disabled:!u.trim(),children:[a.jsx(gs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:k,children:"Cancel"})]})]},X.id):a.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:[a.jsx(ne,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:X.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:X.description})]}),a.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(X.settings).length})}),a.jsx("button",{onClick:()=>D(X.id),className:`p-1 transition-colors ${X.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:X.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:X.showInModal?a.jsx(ul,{className:"w-4 h-4"}):a.jsx(vg,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(X),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")}),a.jsx("button",{onClick:()=>T(X),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>C(X.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(rn,{className:"w-4 h-4"})})]},X.id)})})})]})})]})}function Ele({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=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 b=e[g],_=n[g],C=g in e,P=g in n;let N;!C&&P?N="added":C&&!P?N="removed":JSON.stringify(b)!==JSON.stringify(_)?N="changed":N="same",v.push({key:g,left:b,right:_,status:N})}return v.sort((g,b)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[b.status]?_[g.status]-_[b.status]:g.key.localeCompare(b.key)})},[e,n]),m=w.useMemo(()=>{let x=[...u];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},[u,o,c]),p=w.useMemo(()=>({added:u.filter(x=>x.status==="added").length,removed:u.filter(x=>x.status==="removed").length,changed:u.filter(x=>x.status==="changed").length,same:u.filter(x=>x.status==="same").length}),[u]),f=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]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(dx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(or,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(cN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx($3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(bM,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:x=>d(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"})]}),p.same>0&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.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")}),a.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")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(bM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],g={added:a.jsx(or,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(cN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx($3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(bM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[g,a.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(x.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(x.right)})})]},x.key)})})]})})]})})})}function Int({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=bn(),s=sn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,x]=w.useState(e?.base_id||""),[v,g]=w.useState(""),[b,_]=w.useState(e?.setting||{inherits:""}),[C,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,A]=w.useState(null),[T,F]=w.useState(""),[k,D]=w.useState(!1),[H,z]=w.useState(""),[X,L]=w.useState(!1),[ne,ie]=w.useState(jle),[ee,ue]=w.useState(!1),[le,oe]=w.useState(""),[W,re]=w.useState(""),[ce,xe]=w.useState(!0),[Ne,$]=w.useState(null),[Y,E]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),O=w.useMemo(()=>j.filter(Me=>jw(Me.setting_id)),[j]),{data:K}=Qe({queryKey:["cloudFields",d],queryFn:()=>me.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:B}=Qe({queryKey:["allPresetDetails",d,O.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let Ke=0;Ke<O.length;Ke+=5){const tt=O.slice(Ke,Ke+5);(await Promise.all(tt.map(async Ie=>{try{const be=await me.getCloudSettingDetail(Ie.setting_id);return{id:Ie.setting_id,detail:be}}catch{return null}}))).forEach(Ie=>{Ie&&(Me[Ie.id]=Ie.detail)})}return Me},enabled:O.length>0,staleTime:1e3*60*10}),{data:he,isLoading:I}=Qe({queryKey:["cloudSettingDetail",f],queryFn:()=>me.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(b,null,2))},[b,l]);const V=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(Be=>!jw(Be.setting_id)).sort((Be,Ke)=>Be.name.localeCompare(Ke.name)),[n,d]);w.useEffect(()=>{if(!f)return;const Me=V.find(Be=>Be.setting_id===f);Me&&(g(Me.name),o||(_({inherits:Me.name}),P(JSON.stringify({inherits:Me.name},null,2))))},[f,V,o]);const Q=w.useMemo(()=>{const Me=K?.fields||[],Be=new Set(Me.map(Ie=>Ie.key)),Ke=new Set,tt=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);B&&Object.values(B).forEach(Ie=>{Ie?.setting&&Object.keys(Ie.setting).forEach(be=>{!Be.has(be)&&!tt.has(be)&&Ke.add(be)})}),Object.keys(b).forEach(Ie=>{!Be.has(Ie)&&!tt.has(Ie)&&Ke.add(Ie)});const te=Array.from(Ke).sort().map(Ie=>({key:Ie,label:Ie.replace(/_/g," ").replace(/\b\w/g,be=>be.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...te]},[K,B,b,r]),G=Q.filter(Me=>Me.label.toLowerCase().includes(T.toLowerCase())||Me.key.toLowerCase().includes(T.toLowerCase())),J=()=>{if(H.trim()){const Me=H.trim().toLowerCase().replace(/\s+/g,"_");se(Me,""),z(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:Me}))}},se=(Me,Be)=>{_(Ke=>{const tt={...Ke};return Be===""||Be===void 0?delete tt[Me]:tt[Me]=Be,tt})},fe=Me=>{_(Be=>({...Be,...Me.settings})),$(Me.name),i(r("profiles.templates.toast.applied"))},pe=()=>{if(!le.trim())return;const Me={...b};if(delete Me.inherits,Object.keys(Me).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:le.trim(),description:W.trim()||r("profiles.presets.customTemplate"),type:d,settings:Me,showInModal:ce},Ke=[...ne,Be];ie(Ke),Mle(Ke),ue(!1),oe(""),re(""),xe(!0),i(r("profiles.templates.toast.created"))},de=w.useMemo(()=>ne.filter(Me=>Me.type===d&&Me.showInModal),[d,ne]),U=Me=>{P(Me);try{const Be=JSON.parse(Me);_(Be),A(null)}catch(Be){A(Be.message)}},R=Me=>{Me.preventDefault(),D(!1);const Be=Me.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Ke=new FileReader;Ke.onload=tt=>{try{const te=tt.target?.result,Ie=JSON.parse(te),be=Ie.setting||Ie;_($e=>({...$e,...be})),P(JSON.stringify({...b,...be},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Ke.readAsText(Be)}},ae=it({mutationFn:()=>{const Me={...b},Be=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Me[Be]=`"${m}"`;const Ke={type:d,name:m,base_id:f,setting:Me};return me.createCloudSetting(Ke)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),_e=it({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return me.updateCloudSetting(e.setting_id,{name:m,setting:b})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>i(Me.message,"error")}),Se=o?_e:ae,ye=he?.setting?.inherits,Ae=ye?V.find(Me=>Me.name===ye):void 0,{data:ve}=Qe({queryKey:["cloudSettingDetail",Ae?.setting_id],queryFn:()=>me.getCloudSettingDetail(Ae.setting_id),enabled:!!Ae?.setting_id}),je=w.useMemo(()=>{const Me=ve?.setting||{},Be=he?.setting||{},Ke=f&&B?.[f]?.setting?B[f].setting:{};return{...Me,...Be,...Ke}},[f,he,ve,B]),Re=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const Be=[...new Set(Me.map(Ke=>String(Ke)))];return Be.length===1?Be[0]:Me.join(", ")}return String(Me)},Ee=Me=>{const Be=b[Me.key],Ke=je[Me.key],tt=Re(Ke),te=I?r("common.loading"):tt||"",Ie="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(Me.type==="boolean"){const be=Be==="1"||Be===void 0&&Ke==="1";return a.jsx("button",{type:"button",onClick:()=>se(Me.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${be?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${be?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?a.jsxs("select",{value:Be||"",onChange:be=>se(Me.key,be.target.value),className:Ie,children:[a.jsx("option",{value:"",children:te}),Me.options?.map(be=>a.jsx("option",{value:be.value,children:be.label},be.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:Me.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:be=>se(Me.key,be.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:te,className:Ie}),Me.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},Te=w.useMemo(()=>he?.setting?he.setting:{},[he]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:R,children:[Y&&f&&a.jsx(Ele,{onClose:()=>E(!1),leftPreset:Te,rightPreset:b,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(At,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>E(!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:[a.jsx(dx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),k&&a.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:a.jsxs("div",{className:"text-center",children:[a.jsx(Ma,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:Me=>{u(Me.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:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:Me=>x(Me.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:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),V.map(Me=>a.jsx("option",{value:Me.setting_id,children:Me.name},Me.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:m,onChange:Me=>p(Me.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&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Rr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),I&&a.jsx(dt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.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:[a.jsx(wH,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.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:[a.jsx(Ow,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.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:[a.jsx(oy,{className:"w-4 h-4"}),"JSON",N&&a.jsx(Wa,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const Me={name:m,type:d,base_id:f,setting:b},Be=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),Ke=URL.createObjectURL(Be),tt=document.createElement("a");tt.href=Ke,tt.download=`${m||"preset"}.json`,document.body.appendChild(tt),tt.click(),document.body.removeChild(tt),URL.revokeObjectURL(Ke),i(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:[a.jsx(ca,{className:"w-4 h-4"}),r("common.download")]}),a.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:[a.jsx(Ma,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const Be=Me.target.files?.[0];if(Be){const Ke=new FileReader;Ke.onload=tt=>{try{const te=JSON.parse(tt.target?.result),Ie=te.setting||te;_(be=>({...be,...Ie})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Ke.readAsText(Be)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(Ax,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(b).filter(Me=>Me!=="inherits").length>0&&a.jsxs("button",{onClick:()=>ue(!ee),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(gs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),ee&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:le,onChange:Me=>oe(Me.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}),a.jsx("input",{type:"text",value:W,onChange:Me=>re(Me.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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Fe,{size:"sm",onClick:pe,disabled:!le.trim(),children:[a.jsx(gs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>xe(!ce),className:`flex items-center gap-1.5 text-xs transition-colors ${ce?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ce?a.jsx(ul,{className:"w-3.5 h-3.5"}):a.jsx(vg,{className:"w-3.5 h-3.5"}),r(ce?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Ne&&a.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:[a.jsx(Rr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Ne})]}),a.jsx("button",{onClick:()=>$(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[de.map(Me=>a.jsxs("button",{onClick:()=>fe(Me),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Me.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.id)),de.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:Q.slice(0,10).map(Me=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ee(Me)})]},Me.key))})]}),Object.keys(b).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(b).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Me,": ",String(Be).slice(0,20),a.jsx("button",{onClick:()=>se(Me,void 0),className:"hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},Me))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:B?r("profiles.templates.fieldsCount",{count:Q.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:T,onChange:Me=>F(Me.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"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[G.filter(Me=>!(Me.key in b)).map(Me=>{const Be=je[Me.key],Ke=Re(Be);return a.jsxs("div",{onClick:()=>{_(tt=>({...tt,[Me.key]:Ke||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Me.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ke&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ke,children:[Ke.slice(0,20),Ke.length>20?"...":""]}),a.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:a.jsx(or,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),G.filter(Me=>!(Me.key in b)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:X?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:H,onChange:Me=>z(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&J(),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}),a.jsx(Fe,{size:"sm",onClick:J,disabled:!H.trim(),children:a.jsx(or,{className:"w-4 h-4"})}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>{L(!1),z("")},children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.jsxs("button",{onClick:()=>L(!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:[a.jsx(or,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(b).filter(Me=>Me!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(b).filter(([Me])=>Me!=="inherits").map(([Me,Be])=>{const Ke=Q.find(tt=>tt.key===Me);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Ke?.label||Me}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),a.jsx("button",{onClick:()=>se(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),Ke?Ee(Ke):a.jsx("input",{type:"text",value:String(Be),onChange:tt=>se(Me,tt.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"})]},Me)}),Object.keys(b).filter(Me=>Me!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(wH,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(b).filter(Me=>Me!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{ue(!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:[a.jsx(gs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Wa,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:C,onChange:Me=>U(Me.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 ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Fe,{onClick:()=>Se.mutate(),disabled:Se.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[Se.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):o?a.jsx(gs,{className:"w-4 h-4"}):a.jsx(or,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function znt({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,x]=w.useState("all"),[v,g]=w.useState("all"),[b,_]=w.useState("all"),[C,P]=w.useState("all"),[N,A]=w.useState(null),[T,F]=w.useState(!1),[k,D]=w.useState(!1),[H,z]=w.useState(null),[X,L]=w.useState(null),[ne,ie]=w.useState(null),[ee,ue]=w.useState(!1),[le,oe]=w.useState([null,null]),[W,re]=w.useState(!1),[ce,xe]=w.useState(null),Ne=sn(),$=w.useMemo(()=>[...t.filament.map(J=>({...J,type:"filament"})),...t.printer.map(J=>({...J,type:"printer"})),...t.process.map(J=>({...J,type:"process"}))].map(J=>({...J,meta:r5(J.name)})),[t]),Y=w.useMemo(()=>{const G=new Set,J=new Set,se=new Set;return $.forEach(fe=>{fe.meta.nozzle&&G.add(fe.meta.nozzle),fe.meta.filamentType&&J.add(fe.meta.filamentType),fe.meta.layerHeight&&se.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(G).sort((fe,pe)=>parseFloat(fe)-parseFloat(pe)),filaments:Array.from(J).sort(),layerHeights:Array.from(se).sort((fe,pe)=>parseFloat(fe)-parseFloat(pe))}},[$,i]),E=w.useMemo(()=>f==="all"?null:i.find(J=>J.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>$.filter(G=>d==="all"||G.type===d).filter(G=>{if(m==="all")return!0;const J=jw(G.setting_id);return m==="custom"?J:!J}).filter(G=>{if(f==="all"||!E)return!0;const J=G.meta.printer?.toLowerCase()||"",se=E.toLowerCase();return J.includes(se)||se.includes(J)}).filter(G=>v==="all"||G.meta.nozzle===v).filter(G=>b==="all"||G.meta.filamentType===b).filter(G=>C==="all"||G.meta.layerHeight===C).filter(G=>l===""||G.name.toLowerCase().includes(l.toLowerCase())).sort((G,J)=>G.name.localeCompare(J.name)),[$,d,m,f,E,v,b,C,l]),O=G=>{if(ee){const J=le[0]?.setting_id===G.setting_id,se=le[1]?.setting_id===G.setting_id;if(J)oe([le[1],null]);else if(se)oe([le[0],null]);else if(!le[0])oe([G,null]);else if(le[1]){if(le[0].type!==G.type)return;oe([le[0],G])}else{if(le[0].type!==G.type)return;oe([le[0],G])}}else A(G)},K=G=>{if(le[0]?.setting_id===G.setting_id)return 0;if(le[1]?.setting_id===G.setting_id)return 1},B=async G=>{try{const J=await me.getCloudSettingDetail(G.setting_id),se=G.type==="process"?"print":G.type;z({type:se,name:G.name,base_id:J.base_id||"GFSA00",setting:J.setting||{}}),A(null)}catch(J){console.error("Failed to fetch preset details for duplication:",J)}},he=async G=>{try{Ne.removeQueries({queryKey:["cloudSettingDetail",G.setting_id]});const J=await me.getCloudSettingDetail(G.setting_id),se=G.type==="process"?"print":G.type;L({type:se,name:G.name,base_id:J.base_id||"GFSA00",setting:J.setting||{},setting_id:G.setting_id}),A(null)}catch(J){console.error("Failed to fetch preset details for editing:",J)}},I=()=>{u("all"),p("all"),x("all"),g("all"),_("all"),P("all"),c("")},V=d!=="all"||m!=="all"||f!=="all"||v!=="all"||b!=="all"||C!=="all"||l!=="",Q=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:G=>c(G.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"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Fe,{variant:ee?"primary":"secondary",onClick:()=>{ee?(ue(!1),oe([null,null])):ue(!0)},children:[a.jsx(dx,{className:"w-4 h-4"}),o(ee?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(Ax,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Fe,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(cr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Fe,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(or,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(jP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(Wb,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:Q},{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:G=>u(G)}),a.jsx(Wb,{label:o("profiles.cloudView.filters.owner"),value:m,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:G=>p(G)}),Y.printers.length>0&&a.jsx(Wb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(G=>({value:G.id,label:G.name}))],onChange:x}),Y.nozzles.length>0&&a.jsx(Wb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(G=>({value:G,label:G}))],onChange:g}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(Wb,{label:o("profiles.cloudView.filters.filament"),value:b,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(G=>({value:G,label:G}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(Wb,{label:o("profiles.cloudView.filters.layer"),value:C,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(G=>({value:G,label:G}))],onChange:P}),V&&a.jsx("button",{onClick:I,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),ee&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(dx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:le[0]?o("profiles.cloudView.selectAnotherPreset",{type:le[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[0]?le[0].name:o("profiles.cloudView.selectFirst")}),a.jsx($3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[1]?le[1].name:o("profiles.cloudView.selectSecond")})]}),le[0]&&le[1]&&a.jsxs(Fe,{size:"sm",onClick:async()=>{try{const[G,J]=await Promise.all([me.getCloudSettingDetail(le[0].setting_id),me.getCloudSettingDetail(le[1].setting_id)]);xe([G.setting||{},J.setting||{}]),re(!0)}catch{}},children:[a.jsx(dx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Gh(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:Q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(aa,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),V&&a.jsx("button",{onClick:I,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(TP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(G=>G.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(G=>G.type==="filament").map(G=>a.jsx(b3,{setting:G,onClick:()=>O(G),onDuplicate:()=>B(G),compareMode:ee,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:ee&&!!le[0]&&le[0].type!==G.type,t:o},G.setting_id)),j.filter(G=>G.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(jd,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(G=>G.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(G=>G.type==="process").map(G=>a.jsx(b3,{setting:G,onClick:()=>O(G),onDuplicate:()=>B(G),compareMode:ee,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:ee&&!!le[0]&&le[0].type!==G.type,t:o},G.setting_id)),j.filter(G=>G.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Ar,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(G=>G.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(G=>G.type==="printer").map(G=>a.jsx(b3,{setting:G,onClick:()=>O(G),onDuplicate:()=>B(G),compareMode:ee,isCompareSelected:K(G)!==void 0,compareIndex:K(G),compareDisabled:ee&&!!le[0]&&le[0].type!==G.type,t:o},G.setting_id)),j.filter(G=>G.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx(Lnt,{setting:N,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>B(N),onEdit:()=>he(N),hasPermission:s,t:o}),(T||H||X||ne)&&a.jsx(Int,{onClose:()=>{F(!1),z(null),L(null),ie(null)},initialData:X||H||(ne?{type:ne.type,name:"",base_id:"",setting:ne.setting}:void 0),allPresets:t,t:o}),k&&a.jsx(Ont,{onClose:()=>D(!1),onApply:G=>{ie({type:G.type,setting:G.settings}),D(!1)},t:o}),W&&ce&&le[0]&&le[1]&&a.jsx(Ele,{onClose:()=>{re(!1),xe(null)},leftPreset:ce[0],rightPreset:ce[1],leftLabel:le[0].name,rightLabel:le[1].name,t:o})]})}function Unt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=wr(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=Qe({queryKey:["cloudStatus"],queryFn:me.getCloudStatus}),{data:u=[]}=Qe({queryKey:["printers"],queryFn:me.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:x}=Qe({queryKey:["cloudSettings"],queryFn:()=>me.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=it({mutationFn:me.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.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 ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(sy,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.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 ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(rp,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.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 ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[a.jsx(Fw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(K3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(znt,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Fe,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Fnt,{onSuccess:g,t})]}),i==="local"&&a.jsx(Dnt,{}),i==="kprofiles"&&a.jsx(Ant,{}),a.jsx(Rnt,{})]})}const l0={Droplet:TP,Flame:Au,Ruler:Hbe,Sparkles:Ax,Square:to,Cable:gO,Wrench:Yf,Calendar:Yr,Timer:vd,Cog:Sfe,Fan:CQ,Zap:ic,Wind:BQ,Thermometer:qw,Layers:aa,Box:mi,Target:OQ,RefreshCw:cr,Settings:Hw,Filter:jP,CircleDot:rfe};function F0(t){return t&&l0[t]||Yf}function Kb(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 i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} 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 i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function x3(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 Bnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":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":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":m?"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":i?"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":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||i?"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":u?"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||i?"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":d?"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 u?"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 u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function Hnt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=F0(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>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",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Kb(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Kb(f,"days",i)}):i("maintenance.timeLeft",{duration:Kb(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Kb(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Kb(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Kb(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.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:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.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`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Bnt(t.maintenance_type_name,t.printer_model);return f?a.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:a.jsx(na,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Rn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(Qn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Rr,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(zn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(Fe,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(eo,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function qnt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...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),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(At,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.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:[a.jsx(Rn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.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:[a.jsx(Qn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.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:[a.jsx(Rr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.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?a.jsx(ac,{className:"w-4 h-4"}):a.jsx(Un,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(vd,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&d(!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}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Fe,{size:"sm",onClick:x,children:s("common.save")}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[a.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),a.jsx(Kf,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=F0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&a.jsx(Mt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(Hnt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function $nt({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[x,v]=w.useState(""),[g,b]=w.useState("hours"),[_,C]=w.useState(!1),[P,N]=w.useState(""),[A,T]=w.useState("100"),[F,k]=w.useState("hours"),[D,H]=w.useState("Wrench"),[z,X]=w.useState(""),[L,ne]=w.useState(new Set),[ie,ee]=w.useState(null),[ue,le]=w.useState(null),oe=w.useMemo(()=>t?t.map(U=>({id:U.printer_id,name:U.printer_name})):[],[t]),W=U=>t?t.filter(R=>R.maintenance_items.some(ae=>ae.maintenance_type_id===U)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ae=>ae.maintenance_type_id===U)?.id})):[],re=U=>{if(!t)return[];const R=new Set(W(U).map(ae=>ae.printerId));return oe.filter(ae=>!R.has(ae.id))},[ce,xe]=w.useState(null),[Ne,$]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState("hours"),[K,B]=w.useState("Wrench"),[he,I]=w.useState(""),V=U=>{xe(U),$(U.name),E(U.default_interval_hours.toString()),O(U.interval_type||"hours"),B(U.icon||"Wrench"),I(U.wiki_url||"")},Q=()=>{ce&&Ne.trim()&&parseFloat(Y)>0&&(i(ce.id,{name:Ne.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:K,wiki_url:he.trim()||null}),xe(null))},G=(U,R,ae)=>{const _e=parseFloat(x);if(!isNaN(_e)&&_e>0){const Se=Math.abs(_e-R)<.01?null:_e;n(U,{custom_interval_hours:Se,custom_interval_type:g!==ae?g:null})}f(null)},J=U=>{U.preventDefault(),P.trim()&&parseFloat(A)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(A),interval_type:F,icon:D,wiki_url:z.trim()||null},Array.from(L)),N(""),T("100"),k("hours"),X(""),ne(new Set),C(!1))},se=U=>{ne(R=>{const ae=new Set(R);return ae.has(U)?ae.delete(U):ae.add(U),ae})},fe=t?.map(U=>({printerId:U.printer_id,printerName:U.printer_name,items:U.maintenance_items.sort((R,ae)=>R.maintenance_type_id-ae.maintenance_type_id)})).sort((U,R)=>U.printerName.localeCompare(R.printerName))||[],pe=e.filter(U=>U.is_system),de=e.filter(U=>!U.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fe,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(Fe,{onClick:()=>C(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(or,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(At,{className:"mb-6",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("form",{onSubmit:J,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:U=>N(U.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:m("maintenance.exampleName"),autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:F,onChange:U=>{k(U.target.value),U.target.value==="days"?T("30"):T("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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:F==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),a.jsx("input",{type:"number",value:A,onChange:U=>T(U.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"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(l0).map(U=>{const R=l0[U];return a.jsx("button",{type:"button",onClick:()=>H(U),className:`p-2 rounded-lg transition-colors ${D===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},U)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:z,onChange:U=>X(U.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/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:oe.map(U=>a.jsx("button",{type:"button",onClick:()=>se(U.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(U.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:U.name},U.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:()=>{C(!1),ne(new Set)},children:m("common.cancel")}),a.jsx(Fe,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(U=>{const R=F0(U.icon),ae=U.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(Yr,{className:"w-3 h-3"}):a.jsx(vd,{className:"w-3 h-3"}),x3(U.default_interval_hours,ae,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&le(U)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(rn,{className:"w-4 h-4"})})]})},U.id)}),de.map(U=>{const R=F0(U.icon),ae=U.interval_type||"hours";if(ce?.id===U.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Ne,onChange:ve=>$(ve.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:m("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:ve=>O(ve.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:ve=>E(ve.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"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(l0).map(ve=>{const je=l0[ve];return a.jsx("button",{type:"button",onClick:()=>B(ve),className:`p-1.5 rounded transition-colors ${K===ve?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(je,{className:"w-3.5 h-3.5"})},ve)})}),a.jsx("input",{type:"url",value:he,onChange:ve=>I(ve.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:m("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{size:"sm",onClick:Q,disabled:!Ne.trim(),children:m("common.save")}),a.jsx(Fe,{size:"sm",variant:"secondary",onClick:()=>xe(null),children:m("common.cancel")})]})]})},U.id);const Se=W(U.id),ye=re(U.id),Ae=ie===U.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(Yr,{className:"w-3 h-3"}):a.jsx(vd,{className:"w-3 h-3"}),x3(U.default_interval_hours,ae,m)]})]}),a.jsxs("button",{onClick:()=>ee(Ae?null:U.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${Se.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:m("maintenance.printersAssignedClick",{count:Se.length}),children:[a.jsx(Ar,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:Se.length}),a.jsx(Un,{className:`w-3 h-3 transition-transform ${Ae?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>V(U),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(Kf,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:U.name}))&&s(U.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:a.jsx(rn,{className:"w-4 h-4"})})]}),Ae&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),Se.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:Se.map(ve=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ve.printerName,a.jsx("button",{onClick:()=>ve.itemId&&d(ve.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},ve.printerId))}),ye.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ye.map(ve=>a.jsxs("button",{onClick:()=>c(ve.id,U.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",ve.name]},ve.id))]})]})]},U.id)})]})]}),fe.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:fe.map(U=>a.jsx(At,{children:a.jsxs(Mt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:U.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:U.items.map(R=>{const ae=F0(R.maintenance_type_icon),_e=e.find(je=>je.id===R.maintenance_type_id),Se=_e?.default_interval_hours||R.interval_hours,ye=_e?.interval_type||"hours",Ae=R.interval_type||"hours",ve=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(ae,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),ve?a.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?a.jsx(Yr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(vd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:g,onChange:je=>b(je.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:x,onChange:je=>v(je.target.value),onKeyDown:je=>{je.key==="Enter"&&G(R.id,Se,ye),je.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),a.jsx(Fe,{size:"sm",onClick:()=>G(R.id,Se,ye),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),b(Ae))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("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 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[Ae==="days"?a.jsx(Yr,{className:"w-3 h-3"}):a.jsx(vd,{className:"w-3 h-3"}),x3(R.interval_hours,Ae,m),a.jsx(Kf,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},U.printerId))})]}),fe.length===0&&a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx(Qn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&a.jsx(_n,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ue.id),le(null)},onCancel:()=>le(null)})]})}function Vnt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=wr(),[i,s]=w.useState("status"),{data:o,isLoading:l}=Qe({queryKey:["maintenanceOverview"],queryFn:me.getMaintenanceOverview}),{data:c}=Qe({queryKey:["maintenanceTypes"],queryFn:me.getMaintenanceTypes}),d=it({mutationFn:({id:A,notes:T})=>me.performMaintenance(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:A=>{n(A.message,"error")}}),u=it({mutationFn:({id:A,data:T})=>me.updateMaintenanceItem(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:A=>{n(A.message,"error")}}),m=it({mutationFn:({id:A,data:T})=>me.updateMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:A=>{n(A.message,"error")}}),p=it({mutationFn:me.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:A=>{n(A.message,"error")}}),f=it({mutationFn:me.restoreDefaultMaintenanceTypes,onSuccess:A=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:A.restored}))},onError:A=>{n(A.message,"error")}}),x=it({mutationFn:({printerId:A,hours:T})=>me.setPrinterHours(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:A=>{n(A.message,"error")}}),v=it({mutationFn:({printerId:A,typeId:T})=>me.assignMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:A=>{n(A.message,"error")}}),g=it({mutationFn:me.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:A=>{n(A.message,"error")}}),b=A=>{d.mutate({id:A})},_=(A,T)=>{u.mutate({id:A,data:{enabled:T}})},C=(A,T)=>{x.mutate({printerId:A,hours:T})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((A,T)=>A+T.due_count,0)||0,N=o?.reduce((A,T)=>A+T.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),a.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((A,T)=>{const F=A.due_count*10+A.warning_count,k=T.due_count*10+T.warning_count;return F!==k?k-F:A.printer_name.localeCompare(T.printer_name)}).map(A=>a.jsx(qnt,{overview:A,onPerform:b,onToggle:_,onSetHours:C,hasPermission:r,t},A.printer_id)):a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-16",children:[a.jsx(Yf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx($nt,{overview:o,types:c||[],onUpdateInterval:(A,T)=>u.mutate({id:A,data:T}),onAddType:async(A,T)=>{const F=await me.createMaintenanceType(A);for(const k of T)await me.assignMaintenanceType(k,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(A,T)=>m.mutate({id:A,data:T}),onDeleteType:A=>p.mutate(A),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(A,T)=>v.mutate({printerId:A,typeId:T}),onRemoveItem:A=>g.mutate(A),hasPermission:r,t})]})}const pY=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Dle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||pY[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[x,v]=w.useState(t?.target_parts_count?.toString()||""),[g,b]=w.useState(t?.status||"active"),[_,C]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[A,T]=w.useState(t?.priority||"normal"),[F,k]=w.useState(t?.budget?.toString()||""),D=H=>{H.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:x?parseInt(x,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:A,budget:F.trim()?parseFloat(F):null,...t&&{status:g}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:D,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:H=>l(H.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:s("projects.namePlaceholder"),required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:H=>d(H.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:s("projects.descriptionPlaceholder"),rows:2})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:pY.map(H=>a.jsx("button",{type:"button",onClick:()=>m(H),className:`w-8 h-8 rounded-full transition-transform ${u===H?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:H}},H))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:H=>f(H.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:s("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:x,onChange:H=>v(H.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:s("projects.targetPartsPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:H=>C(H.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:s("projects.tagsPlaceholder")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:H=>N(H.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:A,onChange:H=>T(H.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:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:H=>k(H.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:g,onChange:H=>b(H.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:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(Fe,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function Gnt({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:i,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",d=t.status==="archived",[u,m]=w.useState(!1),f=c?{icon:nl,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:Qs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Qn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:Es,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.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:[a.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`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.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?a.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?a.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&&a.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")}),d&&a.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&&a.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(C=>C.trim())).filter(Boolean),v=[...new Set(x)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(C=>C.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),b=[...new Set(g)];return v.length===0&&b.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),b.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[b.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),b.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",b.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[a.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:()=>m(!u),children:a.jsx(Bh,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Kf,{className:"w-4 h-4"}),s("common.edit")]}),a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(rn,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>a.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?a.jsx("img",{src:me.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(ja,{className:"w-6 h-6"})}),x.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Rn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(aa,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(ja,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(W3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function Wnt(){const{t}=Rt(),e=Do(),n=sn(),{showToast:r}=bn(),{hasPermission:i}=wr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=Qe({queryKey:["settings"],queryFn:me.getSettings}),x=So(f?.currency||"USD"),{data:v,isLoading:g}=Qe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>me.getProjects(d==="all"?void 0:d)}),b=it({mutationFn:ne=>me.createProject(ne),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:ne=>{r(ne.message,"error")}}),_=it({mutationFn:({id:ne,data:ie})=>me.updateProject(ne,ie),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:ne=>{r(ne.message,"error")}}),C=it({mutationFn:ne=>me.deleteProject(ne),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:ne=>{p(null),r(ne.message,"error")}}),P=it({mutationFn:ne=>me.importProject(ne),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:ne=>{r(ne.message,"error")}}),N=w.useRef(null),A=async()=>{try{const ne=await me.getProjects(),ie=await Promise.all(ne.map(async oe=>await me.exportProjectJson(oe.id))),ee=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),ue=URL.createObjectURL(ee),le=document.createElement("a");le.href=ue,le.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,le.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(ne){r(ne.message,"error")}},T=()=>{N.current?.click()},F=async ne=>{const ie=ne.target.files?.[0];if(ie){try{if(ie.name.toLowerCase().endsWith(".zip"))await me.importProjectFile(ie),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ie.text(),le=JSON.parse(ue),oe=Array.isArray(le)?le:[le];for(const W of oe)await P.mutateAsync(W);oe.length>1&&r(t("projects.toast.multipleImported",{count:oe.length}),"success")}}catch(ee){r(`${t("projects.toast.importFailed")}: ${ee.message}`,"error")}ne.target.value=""}},k=ne=>{l?_.mutate({id:l.id,data:ne}):b.mutate(ne)},D=ne=>{c(ne),o(!0)},H=ne=>{e(`/projects/${ne.id}`)},z=ne=>{p(ne)},X=()=>{m!==null&&C.mutate(m)},L=v?.reduce((ne,ie)=>(ne[ie.status]=(ne[ie.status]||0)+1,ne.all=(ne.all||0)+1,ne),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Es,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Fe,{variant:"secondary",onClick:T,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Ma,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Fe,{variant:"secondary",onClick:A,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(ca,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Fe,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Qn},{key:"completed",label:t("projects.statusCompleted"),icon:nl},{key:"archived",label:t("projects.statusArchived"),icon:Qs},{key:"all",label:t("common.all"),icon:Es}].map(({key:ne,label:ie,icon:ee})=>a.jsxs("button",{onClick:()=>u(ne),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===ne?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(ee,{className:"w-4 h-4"}),a.jsx("span",{children:ie}),L[ne]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===ne?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[ne]})]},ne))}),g?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Es,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&a.jsxs(Fe,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(ne=>a.jsx(Gnt,{project:ne,onClick:()=>H(ne),onEdit:()=>D(ne),onDelete:()=>z(ne.id),hasPermission:i,t},ne.id))}),m!==null&&a.jsx(_n,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:X,onCancel:()=>p(null)}),s&&a.jsx(Dle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:b.isPending||_.isPending,currencySymbol:x,t})]})}function Knt(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Xnt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Ynt({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,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function fY({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(At,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function Qnt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(ja,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.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=>a.jsxs(_o,{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?a.jsx("img",{src:me.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ja,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx(Na,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(xr,{className:"w-4 h-4 text-bambu-green"})}),a.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:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function Znt({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:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Rn,{className:"w-3 h-3"}),i]})}function y3(t,e){if(!t)return null;const n=er(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function Jnt(){const{id:t}=Ew(),e=Do(),{t:n}=Rt(),r=sn(),{showToast:i}=bn(),{hasPermission:s}=wr(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(null),[x,v]=w.useState(null),g=parseInt(t||"0",10),{data:b,isLoading:_,error:C}=Qe({queryKey:["project",g],queryFn:()=>me.getProject(g),enabled:g>0}),{data:P,isLoading:N}=Qe({queryKey:["project-archives",g],queryFn:()=>me.getProjectArchives(g),enabled:g>0}),{data:A,isLoading:T}=Qe({queryKey:["project-bom",g],queryFn:()=>me.getProjectBOM(g),enabled:g>0}),{data:F,isLoading:k}=Qe({queryKey:["project-timeline",g],queryFn:()=>me.getProjectTimeline(g,20),enabled:g>0}),{data:D}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:H}=Qe({queryKey:["project-folders",g],queryFn:()=>me.getLibraryFoldersByProject(g),enabled:g>0}),{data:z,isLoading:X}=Qe({queryKey:["project-files",g],queryFn:()=>me.getLibraryFiles(null,!1,g),enabled:g>0}),L=w.useMemo(()=>{const ge=new Map;for(const Pe of z??[])if(Pe.folder_id!=null){const qe=ge.get(Pe.folder_id)??[];qe.push(Pe),ge.set(Pe.folder_id,qe)}return ge},[z]),ne=So(D?.currency||"USD"),ie=D?.time_format||"system",ee=it({mutationFn:ge=>me.updateProject(g,ge),onSuccess:()=>{r.invalidateQueries({queryKey:["project",g]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:ge=>{i(ge.message,"error")}}),ue=()=>{m(b?.notes||""),d(!0)},le=()=>{ee.mutate({notes:u})},oe=()=>{d(!1),m("")},[W,re]=w.useState(""),[ce,xe]=w.useState(1),[Ne,$]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState(""),[K,B]=w.useState(!1),[he,I]=w.useState(!1),[V,Q]=w.useState(null),[G,J]=w.useState(""),[se,fe]=w.useState(1),[pe,de]=w.useState(""),[U,R]=w.useState(""),[ae,_e]=w.useState(""),[Se,ye]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Ae=it({mutationFn:ge=>me.createBOMItem(g,ge),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",g]}),r.invalidateQueries({queryKey:["project",g]}),re(""),xe(1),$(""),E(""),O(""),B(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:ge=>i(ge.message,"error")}),ve=it({mutationFn:({itemId:ge,data:Pe})=>me.updateBOMItem(g,ge,Pe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",g]}),r.invalidateQueries({queryKey:["project",g]}),Q(null)},onError:ge=>i(ge.message,"error")}),je=it({mutationFn:ge=>me.deleteBOMItem(g,ge),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",g]}),r.invalidateQueries({queryKey:["project",g]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:ge=>i(ge.message,"error")}),Re=ge=>{ge.preventDefault(),W.trim()&&Ae.mutate({name:W.trim(),quantity_needed:ce,unit_price:Ne?parseFloat(Ne):void 0,sourcing_url:Y.trim()||void 0,remarks:j.trim()||void 0})},Ee=ge=>{const Pe=ge.is_complete?0:ge.quantity_needed;ve.mutate({itemId:ge.id,data:{quantity_acquired:Pe}})},Te=(ge,Pe)=>{ye({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Pe}),onConfirm:()=>{ye(qe=>({...qe,isOpen:!1})),je.mutate(ge)}})},Me=ge=>{Q(ge),J(ge.name),fe(ge.quantity_needed),de(ge.unit_price?.toString()||""),R(ge.sourcing_url||""),_e(ge.remarks||"")},Be=ge=>{ge.preventDefault(),!(!V||!G.trim())&&ve.mutate({itemId:V.id,data:{name:G.trim(),quantity_needed:se,unit_price:pe?parseFloat(pe):void 0,sourcing_url:U.trim()||void 0,remarks:ae.trim()||void 0}})},Ke=()=>{Q(null)},tt=async()=>{try{const{blob:ge,filename:Pe}=await me.exportProjectZip(Number(g)),qe=URL.createObjectURL(ge),Ze=document.createElement("a");Ze.href=qe,Ze.download=Pe||`${b?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Ze.click(),URL.revokeObjectURL(qe),i(n("projectDetail.toast.projectExported"),"success")}catch(ge){i(ge.message,"error")}},te=it({mutationFn:()=>me.createTemplateFromProject(g),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:ge=>i(ge.message,"error")}),Ie=ge=>Zf(ge,ie,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(_)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(C||!b)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:C?`${n("common.error")}: ${C.message}`:n("projectDetail.notFound")}),a.jsx(Fe,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const be=b.stats,$e=be?.progress_percent??0,He=be?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(_o,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),a.jsx(Ka,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:b.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(kQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:b.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:b.name}),b.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:b.description})]})]}),a.jsx(Ynt,{status:b.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Fe,{variant:"secondary",onClick:tt,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(ca,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Fe,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Kf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(b.target_count||b.target_parts_count)&&a.jsx(At,{children:a.jsxs(Mt,{className:"p-4 space-y-4",children:[b.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[be?.total_archives||0," / ",b.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min($e,100)}%`,backgroundColor:$e>=100?"#22c55e":b.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:$e.toFixed(0)})}),be?.remaining_prints!=null&&be.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_prints})})]})]}),b.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[be?.completed_prints||0," / ",b.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(He,100)}%`,backgroundColor:He>=100?"#22c55e":b.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:He.toFixed(0)})}),be?.remaining_parts!=null&&be.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:be.remaining_parts})})]})]})]})}),be&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(At,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(ja,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[be.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),be.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:be.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:be.completed_prints})})]})]})})}),a.jsx(fY,{icon:Qn,label:n("projectDetail.stats.printTime"),value:Cye(be.total_print_time_hours),color:"text-yellow-400"}),a.jsx(fY,{icon:Ar,label:n("projectDetail.stats.filamentUsed"),value:Xnt(be.total_filament_grams),color:"text-purple-400"})]}),be&&(()=>{const ge=be.estimated_cost+be.total_energy_cost+be.bom_cost;return be.estimated_cost>0||ge>0||b.budget!==null})()&&a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[ne,be.estimated_cost.toFixed(2)]})]}),be.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[be.total_energy_kwh.toFixed(3)," kWh",be.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",ne,be.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const ge=be.estimated_cost+be.total_energy_cost+be.bom_cost;return ge<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[ne,ge.toFixed(2)]}),be.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),b.budget!==null&&(()=>{const ge=be.estimated_cost+be.total_energy_cost+be.bom_cost,Pe=b.budget-ge;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[ne,b.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${Pe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[ne,Pe.toFixed(2)]})]})]})})()]})]})}),b.children&&b.children.length>0&&a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(hge,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:b.children.length})]}),a.jsx("div",{className:"space-y-2",children:b.children.map(ge=>a.jsxs(_o,{to:`/projects/${ge.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ge.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:ge.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ge.status==="completed"?"bg-status-ok/20 text-status-ok":ge.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ge.status})]}),ge.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[ge.progress_percent.toFixed(0),"%"]})]},ge.id))})]})}),b.parent_id&&b.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(aa,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(_o,{to:`/projects/${b.parent_id}`,className:"text-bambu-green hover:underline",children:b.parent_name})]}),(b.tags||b.due_date||b.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[b.priority&&b.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(Znt,{priority:b.priority,t:n})]}),b.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Yr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:Qf(b.due_date,{year:"numeric",month:"short",day:"numeric"})}),y3(b.due_date,n)&&a.jsxs("span",{className:`text-xs ${y3(b.due_date,n).color}`,children:["(",y3(b.due_date,n).label,")"]})]}),b.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(im,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:b.tags.split(",").map((ge,Pe)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ge.trim()},Pe))})]})]}),a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:oe,disabled:ee.isPending,children:[a.jsx(Bt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Fe,{size:"sm",onClick:le,disabled:ee.isPending,children:[ee.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(gs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:ue,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Kf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(HL,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):b.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:rie.sanitize(b.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Uc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(_o,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),H&&H.length>0?a.jsx("div",{className:"space-y-4",children:H.map(ge=>{const Pe=L.get(ge.id)??[],qe=X;return a.jsxs("div",{children:[a.jsxs(_o,{to:`/files?folder=${ge.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Uc,{className:"w-5 h-5 text-bambu-green shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ge.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ge.file_count})})]})]}),a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),qe?a.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:a.jsx(dt,{className:"w-4 h-4 animate-spin"})}):Pe.length===0?a.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):a.jsx("div",{className:"space-y-1 pl-3",children:Pe.map(Ze=>{const ut=Knt(Ze.filename);return a.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Ze.thumbnail_path?a.jsx("img",{src:me.getLibraryFileThumbnailUrl(Ze.id),alt:Ze.print_name||Ze.filename,className:"w-full h-full object-cover"}):a.jsx(Hh,{className:"w-5 h-5 text-bambu-gray/40"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",title:Ze.print_name||Ze.filename,children:Ze.print_name||Ze.filename}),a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ze.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ze.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ze.file_type.toUpperCase()})]}),ut&&a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("button",{onClick:()=>f(Ze),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>v(Ze),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:a.jsx(Ipe,{className:"w-4 h-4"})})]})]},Ze.id)})})]},ge.id)})}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(FQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),be&&be.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:be.bom_completed_items,total:be.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[A&&A.some(ge=>ge.is_complete)&&a.jsx("button",{onClick:()=>I(!he),className:`text-xs px-2 py-1 rounded transition-colors ${he?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(he?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!K&&a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>B(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(or,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),K&&a.jsxs("form",{onSubmit:Re,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:W,onChange:ge=>re(ge.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ce,onChange:ge=>xe(parseInt(ge.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")}),a.jsx("input",{type:"number",step:"0.01",value:Ne,onChange:ge=>$(ge.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:ne})})]})]}),a.jsx("input",{type:"url",value:Y,onChange:ge=>E(ge.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")}),a.jsx("input",{type:"text",value:j,onChange:ge=>O(ge.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")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",size:"sm",onClick:()=>B(!1),children:n("common.cancel")}),a.jsx(Fe,{type:"submit",size:"sm",disabled:!W.trim()||Ae.isPending,children:Ae.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),T?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):A&&A.length>0?a.jsxs("div",{className:"space-y-2",children:[A.filter(ge=>!he||!ge.is_complete).map(ge=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${ge.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:V?.id===ge.id?a.jsxs("form",{onSubmit:Be,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:G,onChange:Pe=>J(Pe.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:se,onChange:Pe=>fe(parseInt(Pe.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")}),a.jsx("input",{type:"number",step:"0.01",value:pe,onChange:Pe=>de(Pe.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:ne})})]})]}),a.jsx("input",{type:"url",value:U,onChange:Pe=>R(Pe.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")}),a.jsx("input",{type:"text",value:ae,onChange:Pe=>_e(Pe.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")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",size:"sm",onClick:Ke,children:n("common.cancel")}),a.jsx(Fe,{type:"submit",size:"sm",disabled:!G.trim()||ve.isPending,children:ve.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Ee(ge),disabled:ve.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 shrink-0 ${ge.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:ge.is_complete&&a.jsx(xr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${ge.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ge.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ge.quantity_needed]})]}),ge.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[ne,(ge.unit_price*ge.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Me(ge),disabled:!s("projects:update"),className:`p-1 rounded transition-colors 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:a.jsx(ai,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Te(ge.id,ge.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors 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:a.jsx(rn,{className:"w-4 h-4"})})]})]}),ge.sourcing_url&&a.jsxs("a",{href:ge.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:Pe=>Pe.stopPropagation(),children:[a.jsx(na,{className:"w-3 h-3 shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ge.sourcing_url).hostname.replace("www.","")}catch{return ge.sourcing_url}})()})]}),ge.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ge.remarks})]})]})},ge.id)),be&&be.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[ne,be.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(B0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?a.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((ge,Pe)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${ge.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ge.event_type==="print_failed"?"bg-status-error/20 text-status-error":ge.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ge.event_type==="print_completed"&&a.jsx(xr,{className:"w-4 h-4"}),ge.event_type==="print_failed"&&a.jsx(Na,{className:"w-4 h-4"}),ge.event_type==="print_started"&&a.jsx(Ar,{className:"w-4 h-4"}),ge.event_type==="queued"&&a.jsx(W3,{className:"w-4 h-4"}),ge.event_type==="project_created"&&a.jsx(or,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:ge.title}),ge.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ge.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ie(ge.timestamp)})]})]},Pe))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!b.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>te.mutate(),disabled:te.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[te.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Fs,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),be&&(be.queued_prints>0||be.in_progress_prints>0)&&a.jsx(At,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(W3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(_o,{to:`/queue?project=${g}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[be.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:be.in_progress_prints})}),be.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:be.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ja,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:P?.length||0})]})}),N?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(dt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(Qnt,{archives:P||[],t:n})]}),o&&a.jsx(Dle,{t:n,currencySymbol:ne,project:{...b,archive_count:be?.total_archives||0,total_items:be?.total_items||0,completed_count:be?.completed_prints||0,failed_count:be?.failed_prints||0,queue_count:be?.queued_prints||0,progress_percent:be?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ge=>ee.mutate(ge),isLoading:ee.isPending}),Se.isOpen&&a.jsx(_n,{title:Se.title,message:Se.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Se.onConfirm,onCancel:()=>ye(ge=>({...ge,isOpen:!1}))}),p&&a.jsx(ec,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:g,onClose:()=>f(null),onSuccess:()=>{f(null),r.invalidateQueries({queryKey:["archives"]})}}),x&&a.jsx(ec,{mode:"add-to-queue",libraryFileId:x.id,archiveName:x.print_name||x.filename,projectId:g,onClose:()=>v(null),onSuccess:()=>{v(null),r.invalidateQueries({queryKey:["queue"]})}})]})}function ert({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.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:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Fe,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function trt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(oN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.jsx("input",{type:"text",value:i,onChange:f=>s(f.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:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.jsx("input",{type:"text",value:o,onChange:f=>l(f.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 font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(Fe,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function nrt({type:t,currentName:e,onClose:n,onSave:r,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.jsx("input",{type:"text",value:c,onChange:m=>d(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Fe,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function rrt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const x of m)f.push({id:x.id,name:x.name,depth:p}),x.children.length>0&&f.push(...d(x.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Uc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Fe,{onClick:()=>i(l),disabled:s,children:s?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function art({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){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:d}=Qe({queryKey:["projects"],queryFn:()=>me.getProjects()}),{data:u}=Qe({queryKey:["archives-for-link"],queryFn:()=>me.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ku,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(NQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.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:[a.jsx(Qs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(x=>a.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:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:x.name})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(x=>a.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:[a.jsx(Hh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(Fe,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(ap,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(Fe,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Fe,{onClick:m,disabled:!l||r,children:r?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function Fle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:d}){const[u,m]=w.useState(!0),[p,f]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id,g=t.is_external;return a.jsxs("div",{children:[a.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?a.jsx("button",{onClick:b=>{b.stopPropagation(),m(!u)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Ka,{className:`w-3.5 h-3.5 transition-transform ${u?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),g?a.jsx(oN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Uc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:b=>{b.stopPropagation(),i(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:[a.jsx(Ku,{className:"w-3 h-3"}),t.project_name?a.jsx(NQ,{className:"w-3 h-3"}):a.jsx(Qs,{className:"w-3 h-3"})]}),g&&t.external_readonly&&a.jsx("span",{title:d("fileManager.readOnly"),children:a.jsx(pd,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&!g&&a.jsx("button",{onClick:b=>{b.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:d("fileManager.linkToProjectOrArchive"),children:a.jsx(Ku,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:b=>b.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Bh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),a.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:[a.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),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionRenameFolder"),children:[a.jsx(ai,{className:"w-3.5 h-3.5"}),d("common.rename")]}),a.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")&&(i(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionLinkFolder"),children:[a.jsx(Ku,{className:"w-3.5 h-3.5"}),d(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.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),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:d("fileManager.noPermissionDeleteFolder"),children:[a.jsx(rn,{className:"w-3.5 h-3.5"}),d("common.delete")]})]})]})]})})]}),x&&u&&a.jsx("div",{children:t.children.map(b=>a.jsx(Fle,{folder:b,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:d},b.id))})]})}function YL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function irt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:x,t:v}){const[g,b]=w.useState(!1);return a.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:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${me.getLibraryFileThumbnailUrl(t.id)}${m?(me.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(Hh,{className:"w-12 h-12 text-bambu-gray/30"}),a.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()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:Co(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),ps(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Ar,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(sm,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>b(!g),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Bh,{className:"w-4 h-4 text-bambu-gray"})}),g&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>b(!1)}),a.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&&YL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),b(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Ar,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&YL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),b(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),b(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(mi,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),b(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(ca,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),b(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(ai,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),b(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(rm,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),b(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(rn,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.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&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function srt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=wr(),[l]=PP(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[x,v]=w.useState(!1),[g,b]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(!1),[A,T]=w.useState(null),[F,k]=w.useState(null),[D,H]=w.useState(null),[z,X]=w.useState(null),[L,ne]=w.useState(null),[ie,ee]=w.useState(null),[ue,le]=w.useState({}),[oe,W]=w.useState(null),[re,ce]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[xe,Ne]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[$,Y]=w.useState(()=>{const Ge=localStorage.getItem("library-sidebar-width");return Ge?parseInt(Ge,10):256}),[E,j]=w.useState(!1),O=w.useRef(null);w.useEffect(()=>{if(!E)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ge=Yt=>{if(!O.current)return;const Pt=O.current.parentElement?.getBoundingClientRect();if(!Pt)return;const pt=Yt.clientX-Pt.left,Wt=Math.min(500,Math.max(200,pt));Y(Wt)},Ft=()=>{j(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String($))};return document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",Ft),()=>{document.removeEventListener("mousemove",Ge),document.removeEventListener("mouseup",Ft),document.body.style.userSelect="",document.body.style.cursor=""}},[E,$]);const[K,B]=w.useState(""),[he,I]=w.useState("all"),[V,Q]=w.useState(""),[G,J]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[se,fe]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),pe=Kae();w.useEffect(()=>{const Ge=l.get("folder");if(Ge){const Ft=parseInt(Ge,10);m(Ft)}},[l]);const{data:de}=Qe({queryKey:["settings"],queryFn:()=>me.getSettings()}),{data:U,isLoading:R}=Qe({queryKey:["library-folders"],queryFn:()=>me.getLibraryFolders()}),{data:ae,isLoading:_e}=Qe({queryKey:["library-files",u],queryFn:()=>me.getLibraryFiles(u,u===null)}),{data:Se}=Qe({queryKey:["library-stats"],queryFn:()=>me.getLibraryStats()}),{data:ye}=Qe({queryKey:["users"],queryFn:()=>me.getUsers()}),Ae=w.useMemo(()=>{if(!ae)return[];const Ge=new Set(ae.map(Ft=>Ft.file_type));return Array.from(Ge).sort()},[ae]),ve=w.useMemo(()=>{if(!ae)return[];let Ge=[...ae];if(K.trim()){const Ft=K.toLowerCase();Ge=Ge.filter(Yt=>Yt.filename.toLowerCase().includes(Ft)||Yt.print_name&&Yt.print_name.toLowerCase().includes(Ft))}if(he!=="all"&&(Ge=Ge.filter(Ft=>Ft.file_type===he)),V.trim()){const Ft=V.toLowerCase();Ge=Ge.filter(Yt=>Yt.created_by_username&&Yt.created_by_username.toLowerCase().includes(Ft))}return Ge.sort((Ft,Yt)=>{let Pt=0;switch(G){case"name":Pt=(Ft.print_name||Ft.filename).localeCompare(Yt.print_name||Yt.filename);break;case"date":Pt=(er(Ft.created_at)?.getTime()??0)-(er(Yt.created_at)?.getTime()??0);break;case"size":Pt=Ft.file_size-Yt.file_size;break;case"type":Pt=Ft.file_type.localeCompare(Yt.file_type);break;case"prints":Pt=Ft.print_count-Yt.print_count;break}return se==="asc"?Pt:-Pt}),Ge},[ae,K,he,V,G,se]),je=w.useMemo(()=>{if(!Se||!de)return!1;const Ge=(de.library_disk_warning_gb||5)*1024*1024*1024;return Se.disk_free_bytes<Ge},[Se,de]),Re=it({mutationFn:Ge=>me.createLibraryFolder(Ge),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ge=>n(Ge.message,"error")}),Ee=it({mutationFn:async Ge=>{const Ft=await me.createExternalFolder(Ge);return await me.scanExternalFolder(Ft.id),Ft},onSuccess:Ge=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),b(!1),m(Ge.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ge=>n(Ge.message,"error")}),Te=it({mutationFn:Ge=>me.scanExternalFolder(Ge),onSuccess:Ge=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:Ge.added,removed:Ge.removed}),"success")},onError:Ge=>n(Ge.message,"error")}),Me=it({mutationFn:Ge=>me.deleteLibraryFolder(Ge),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===F?.id&&m(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ge=>{k(null),n(Ge.message,"error")}}),Be=it({mutationFn:Ge=>me.deleteLibraryFile(Ge),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(Ge=>Ge.filter(Ft=>Ft!==F?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ge=>{k(null),n(Ge.message,"error")}}),Ke=it({mutationFn:Ge=>me.bulkDeleteLibrary(Ge,[]),onSuccess:(Ge,Ft)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Ft.length}),"success"),f([]),k(null)},onError:Ge=>{k(null),n(Ge.message,"error")}}),tt=it({mutationFn:({fileIds:Ge,folderId:Ft})=>me.moveLibraryFiles(Ge,Ft),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ge=>n(Ge.message,"error")}),te=it({mutationFn:({id:Ge,data:Ft})=>me.updateLibraryFolder(Ge,Ft),onSuccess:(Ge,Ft)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),T(null);const Yt=Ft.data.project_id===0&&Ft.data.archive_id===0;n(t(Yt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ge=>n(Ge.message,"error")}),Ie=it({mutationFn:({id:Ge,filename:Ft})=>me.updateLibraryFile(Ge,{filename:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ge=>{ee(null),n(Ge.message,"error")}}),be=it({mutationFn:({id:Ge,name:Ft})=>me.updateLibraryFolder(Ge,{name:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ge=>{ee(null),n(Ge.message,"error")}}),$e=it({mutationFn:()=>me.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ge=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ge.succeeded>0){const Ft=Date.now(),Yt={};Ge.results.forEach(Pt=>{Pt.success&&(Yt[Pt.file_id]=Ft)}),le(Pt=>({...Pt,...Yt}))}Ge.succeeded>0&&Ge.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ge.succeeded}),"success"):Ge.succeeded>0&&Ge.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ge.succeeded,failed:Ge.failed}),"success"):Ge.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ge.results[0]?.error||"Unknown error"}),"error")},onError:Ge=>n(Ge.message,"error")}),He=it({mutationFn:Ge=>me.batchGenerateStlThumbnails({file_ids:[Ge]}),onSuccess:Ge=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ge.succeeded>0){const Ft=Ge.results[0]?.file_id;Ft&&le(Yt=>({...Yt,[Ft]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ge.results[0]?.error||"Unknown error"}),"error")},onError:Ge=>n(Ge.message,"error")}),ge=w.useCallback(Ge=>{const Ft=Ge.toLowerCase();return Ft.endsWith(".gcode")||Ft.includes(".gcode.")},[]),Pe=w.useMemo(()=>ae?ae.filter(Ge=>p.includes(Ge.id)&&ge(Ge.filename)):[],[ae,p,ge]),qe=w.useCallback(Ge=>{f(Ft=>Ft.includes(Ge)?Ft.filter(Yt=>Yt!==Ge):[...Ft,Ge])},[]),Ze=w.useCallback(()=>{ve.length>0&&f(ve.map(Ge=>Ge.id))},[ve]),ut=w.useCallback(()=>{f([])},[]),vt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},wt=Ge=>{me.downloadLibraryFile(Ge).catch(Ft=>{console.error("Library file download failed:",Ft)})},$t=()=>{F&&(F.type==="file"?Be.mutate(F.id):F.type==="folder"?Me.mutate(F.id):F.type==="bulk"&&Ke.mutate(p))},Qt=Me.isPending||Be.isPending||Ke.isPending,en=Ge=>{ce(Ge),localStorage.setItem("library-view-mode",Ge)},Xt=R||_e,tn=w.useMemo(()=>{if(!u||!U)return null;const Ge=Ft=>{for(const Yt of Ft){if(Yt.id===u)return Yt;const Pt=Ge(Yt.children);if(Pt)return Pt}return null};return Ge(U)},[u,U]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Uc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>en("grid"),className:`p-1.5 rounded transition-colors ${re==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(Lw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>en("list"),className:`p-1.5 rounded transition-colors ${re==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(Ow,{className:"w-4 h-4"})})]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>$e.mutate(),disabled:$e.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[$e.isPending?a.jsx(dt,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(rm,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>b(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(oN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(dge,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Fe,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Ma,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),je&&Se&&de&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Rn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:Co(Se.disk_free_bytes),total:Co(Se.disk_total_bytes),threshold:de.library_disk_warning_gb})})]})]}),Se&&a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(AP,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Uc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(rp,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Co(Se.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${je?"text-amber-500":"text-white"}`,children:Co(Se.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:Ge=>m(Ge.target.value?parseInt(Ge.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:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),U&&(()=>{const Ge=(Ft,Yt=0)=>{const Pt=[];for(const pt of Ft)Pt.push({id:pt.id,name:pt.name,fileCount:pt.file_count,depth:Yt}),pt.children.length>0&&Pt.push(...Ge(pt.children,Yt+1));return Pt};return Ge(U).map(Ft=>a.jsxs("option",{value:Ft.id,children:["│ ".repeat(Ft.depth),"📂 ",Ft.name," ",Ft.fileCount>0?`(${Ft.fileCount})`:""]},Ft.id))})()]})}),a.jsxs("div",{ref:O,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:`${$}px`},children:[a.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 ${E?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ge=>{Ge.preventDefault(),j(!0)},onDoubleClick:()=>{Y(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${E?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const Ge=!xe;Ne(Ge),localStorage.setItem("library-wrap-folders",String(Ge))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${xe?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(xe?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(Hh,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),U?.map(Ge=>a.jsx(Fle,{folder:Ge,selectedFolderId:u,onSelect:m,onDelete:Ft=>k({type:"folder",id:Ft}),onLink:T,onRename:Ft=>ee({type:"folder",id:Ft.id,name:Ft.name}),wrapNames:xe,hasPermission:r,t},Ge.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[tn?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(oN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),tn.external_readonly&&a.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[a.jsx(pd,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:tn.external_path||"",children:tn.external_path})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>u&&Te.mutate(u),disabled:Te.isPending,title:t("fileManager.scanFolder"),children:[Te.isPending?a.jsx(dt,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),ae&&ae.length>0&&a.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:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:K,onChange:Ge=>B(Ge.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"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:he,onChange:Ge=>I(Ge.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:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Ae.map(Ge=>a.jsx("option",{value:Ge,children:Ge.toUpperCase()},Ge))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:V,onChange:Ge=>Q(Ge.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 ${V?"pr-7":""}`,style:V?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),V&&a.jsx("button",{onClick:()=>Q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Bt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(Ge=>a.jsx("option",{value:Ge.username},Ge.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:G,onChange:Ge=>{const Ft=Ge.target.value;J(Ft),localStorage.setItem("library-sort-field",Ft)},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:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>fe(Ge=>{const Ft=Ge==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ft),Ft}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(se==="asc"?"fileManager.ascending":"fileManager.descending"),children:se==="asc"?a.jsx(gpe,{className:"w-4 h-4 text-white"}):a.jsx(cpe,{className:"w-4 h-4 text-white"})})]}),(K||he!=="all"||V)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:ve.length,total:ae.length})})]}),ve.length>0&&a.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:[p.length===ve.length&&p.length>0?a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(to,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:Ze,children:[a.jsx(xs,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Pe.length===1&&a.jsxs(Fe,{variant:"primary",size:"sm",onClick:()=>X(Pe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx($i,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Pe.length===1&&a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>ne(Pe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(Qn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(vbe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Fe,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(rn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Fe,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(Bt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Xt?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):ae?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Hh,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Fe,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(or,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):ve.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(kr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Fe,{variant:"secondary",onClick:()=>{B(""),I("all")},children:t("fileManager.clearFilters")})]}):re==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.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:ve.map(Ge=>a.jsx(irt,{file:Ge,isSelected:p.includes(Ge.id),isMobile:pe,t,onSelect:qe,onDelete:Ft=>k({type:"file",id:Ft}),onDownload:wt,onAddToQueue:Ft=>{const Yt=ae?.find(Pt=>Pt.id===Ft);Yt&&ne(Yt)},onPrint:H,onPreview3d:W,onRename:Ft=>ee({type:"file",id:Ft.id,name:Ft.filename}),onGenerateThumbnail:Ft=>He.mutate(Ft.id),thumbnailVersion:ue[Ge.id],hasPermission:r,canModify:s,authEnabled:o},Ge.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.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:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),ve.map(Ge=>a.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 ${p.includes(Ge.id)?"bg-bambu-green/10":""}`,onClick:()=>qe(Ge.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ge.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ge.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ge.thumbnail_path?a.jsx("img",{src:`${me.getLibraryFileThumbnailUrl(Ge.id)}${ue[Ge.id]?(me.getLibraryFileThumbnailUrl(Ge.id).includes("?")?"&":"?")+`v=${ue[Ge.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(Hh,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ge.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${me.getLibraryFileThumbnailUrl(Ge.id)}${ue[Ge.id]?(me.getLibraryFileThumbnailUrl(Ge.id).includes("?")?"&":"?")+`v=${ue[Ge.id]}`:""}`,alt:Ge.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Ge.print_name||Ge.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ge.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(sm,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ge.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ge.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ge.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ge.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ge.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Co(Ge.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ge.print_count>0?`${Ge.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:Ft=>Ft.stopPropagation(),children:[YL(Ge.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&H(Ge),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:a.jsx(Ar,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&ne(Ge)},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:a.jsx(Qn,{className:"w-4 h-4"})})]}),(Ge.file_type==="3mf"||Ge.file_type==="gcode"||Ge.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&W(Ge),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:a.jsx(mi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&wt(Ge.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:a.jsx(ca,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ge.created_by_id)&&ee({type:"file",id:Ge.id,name:Ge.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ge.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ge.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ge.created_by_id),children:a.jsx(ai,{className:"w-4 h-4"})}),Ge.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ge.created_by_id)&&He.mutate(Ge.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ge.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",Ge.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:He.isPending||!s("library","update",Ge.created_by_id),children:a.jsx(rm,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ge.created_by_id)&&k({type:"file",id:Ge.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ge.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",Ge.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ge.created_by_id),children:a.jsx(rn,{className:"w-4 h-4"})})]})]},Ge.id))]})})]})]}),x&&a.jsx(ert,{parentId:u,onClose:()=>v(!1),onSave:Ge=>Re.mutate(Ge),isLoading:Re.isPending,t}),g&&a.jsx(trt,{onClose:()=>b(!1),onSave:Ge=>Ee.mutate(Ge),isLoading:Ee.isPending,t}),_&&U&&a.jsx(rrt,{folders:U,selectedFiles:p,currentFolderId:u,onClose:()=>C(!1),onMove:Ge=>tt.mutate({fileIds:p,folderId:Ge}),isLoading:tt.isPending,t}),P&&a.jsx(Uae,{folderId:u,onClose:()=>N(!1),onUploadComplete:vt}),A&&a.jsx(art,{folder:A,onClose:()=>T(null),onLink:Ge=>te.mutate({id:A.id,data:Ge}),isLoading:te.isPending,t}),F&&a.jsx(_n,{title:F.type==="folder"?t("fileManager.deleteFolder"):F.type==="bulk"?t("fileManager.deleteFilesCount",{count:F.count}):t("fileManager.deleteFile"),message:F.type==="folder"?t("fileManager.deleteFolderConfirm"):F.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:F.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Qt,loadingText:t("fileManager.deleting"),onConfirm:$t,onCancel:()=>k(null)}),D&&a.jsx(ec,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>H(null),onSuccess:()=>{H(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&a.jsx(ec,{mode:"reprint",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>X(null),onSuccess:()=>{X(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(ec,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>ne(null),onSuccess:()=>{ne(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),oe&&a.jsx(cz,{libraryFileId:oe.id,title:oe.print_name||oe.filename,fileType:oe.file_type,onClose:()=>W(null)}),ie&&a.jsx(nrt,{type:ie.type,currentName:ie.name,onClose:()=>ee(null),onSave:Ge=>{ie.type==="file"?Ie.mutate({id:ie.id,filename:Ge}):be.mutate({id:ie.id,name:Ge})},isLoading:Ie.isPending||be.isPending,t})]})}const vk=5,ort=2e3,lrt=3e4,crt=5e3;function drt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),{hasPermission:r}=wr(),{printerId:i}=Ew(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(!0),[x,v]=w.useState(Date.now()),[g,b]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(0),[A,T]=w.useState(!1),[F,k]=w.useState(0),[D,H]=w.useState(1),[z,X]=w.useState({x:0,y:0}),[L,ne]=w.useState(!1),[ie,ee]=w.useState({x:0,y:0}),[ue,le]=w.useState(null),[oe,W]=w.useState(null),re=w.useRef(null),ce=w.useRef(null),xe=w.useRef(null),Ne=w.useRef(null),$=w.useRef(null),{data:Y}=Qe({queryKey:["printer",s],queryFn:()=>me.getPrinter(s),enabled:s>0}),{data:E}=Qe({queryKey:["printerStatus",s],queryFn:()=>me.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),j=it({mutationFn:Te=>me.setChamberLight(s,Te),onMutate:async Te=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:Te})),{previousStatus:Me}},onSuccess:(Te,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(Te,Me,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(Te.message||t("printers.toast.failedToControlChamberLight"),"error")}}),O=(E?.state==="RUNNING"||E?.state==="PAUSE")&&(E?.printable_objects_count??0)>=2;w.useEffect(()=>(Y&&(document.title=`${Y.name} - Camera`),()=>{document.title="Bambuddy"}),[Y]);const K=w.useRef(!1);w.useEffect(()=>{const Te=`/api/v1/printers/${s}/camera/stop`;K.current=!1;const Me=()=>{if(s>0&&!K.current){K.current=!0;const tt={},te=om();te&&(tt.Authorization=`Bearer ${te}`),fetch(Te,{method:"POST",keepalive:!0,headers:tt}).catch(()=>{})}},Be=()=>{Me()};window.addEventListener("beforeunload",Be);const Ke=re.current;return()=>{window.removeEventListener("beforeunload",Be),Ke&&(Ke.src=""),Me()}},[s]),w.useEffect(()=>{if(p&&!g){const Me=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,p,x,g]),w.useEffect(()=>{const Te=()=>{const Me=!!document.fullscreenElement;C(Me),H(1),X({x:0,y:0}),o==="stream"&&!g&&(re.current&&(re.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Te),()=>document.removeEventListener("fullscreenchange",Te)},[o,g]),w.useEffect(()=>{let Te;const Me=()=>{clearTimeout(Te),Te=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(Te),window.removeEventListener("resize",Me)}},[]),w.useEffect(()=>()=>{xe.current&&clearTimeout(xe.current),Ne.current&&clearInterval(Ne.current),$.current&&clearInterval($.current)},[]);const B=w.useCallback(()=>{if(P>=vk){T(!1),m(!0);return}const Te=Math.min(ort*Math.pow(2,P),lrt);T(!0),k(Math.ceil(Te/1e3)),Ne.current=setInterval(()=>{k(Me=>Me<=1?(Ne.current&&clearInterval(Ne.current),0):Me-1)},1e3),xe.current=setTimeout(()=>{N(Me=>Me+1),T(!1),f(!0),m(!1),re.current&&(re.current.src=""),v(Date.now())},Te)},[P]);w.useEffect(()=>{if(o!=="stream"||p||A||g){$.current&&(clearInterval($.current),$.current=null);return}return $.current=setInterval(async()=>{try{const Te=await me.getCameraStatus(s);(Te.stalled||!Te.active&&!u)&&(console.log(`Stream issue detected: stalled=${Te.stalled}, active=${Te.active}, reconnecting...`),$.current&&(clearInterval($.current),$.current=null),f(!1),B())}catch{}},crt),()=>{$.current&&(clearInterval($.current),$.current=null)}},[o,p,u,A,g,s,B]);const he=()=>{f(!1),o==="stream"&&P<vk?B():m(!0)},I=()=>{if(f(!1),m(!1),N(0),T(!1),xe.current&&clearTimeout(xe.current),Ne.current&&clearInterval(Ne.current),re.current&&!localStorage.getItem("cameraWindowState")){const Te=re.current,Me=Te.naturalWidth,Be=Te.naturalHeight;if(Me>0&&Be>0){const te=window.outerWidth-window.innerWidth,Ie=window.outerHeight-window.innerHeight,be=Me+16+te,$e=Be+45+16+Ie;try{window.resizeTo(be,$e)}catch{}}}},V=()=>{if(s>0){const Te={},Me=om();Me&&(Te.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Te}).catch(()=>{})}},Q=Te=>{o===Te||g||(b(!0),f(!0),m(!1),N(0),T(!1),H(1),X({x:0,y:0}),xe.current&&clearTimeout(xe.current),Ne.current&&clearInterval(Ne.current),re.current&&(re.current.src=""),o==="stream"&&V(),setTimeout(()=>{l(Te),v(Date.now()),b(!1)},100))},G=()=>{g||(b(!0),f(!0),m(!1),N(0),T(!1),xe.current&&clearTimeout(xe.current),Ne.current&&clearInterval(Ne.current),re.current&&(re.current.src=""),o==="stream"&&V(),setTimeout(()=>{v(Date.now()),b(!1)},100))},J=()=>{ce.current&&(document.fullscreenElement?document.exitFullscreen():ce.current.requestFullscreen())},se=()=>{H(Te=>Math.min(Te+.5,4))},fe=()=>{H(Te=>{const Me=Math.max(Te-.5,1);return Me===1&&X({x:0,y:0}),Me})},pe=Te=>{Te.preventDefault(),Te.deltaY<0?se():fe()},de=Te=>{D>1&&(Te.preventDefault(),ne(!0),ee({x:Te.clientX-z.x,y:Te.clientY-z.y}))},U=w.useCallback(()=>{if(!ce.current)return{x:300,y:200};const Te=ce.current.getBoundingClientRect(),Me=Te.width*(D-1)/2,Be=Te.height*(D-1)/2;return{x:Math.max(50,Me),y:Math.max(50,Be)}},[D]),R=Te=>{if(L&&D>1){const Me=Te.clientX-ie.x,Be=Te.clientY-ie.y,Ke=U();X({x:Math.max(-Ke.x,Math.min(Ke.x,Me)),y:Math.max(-Ke.y,Math.min(Ke.y,Be))})}},ae=()=>{ne(!1)},_e=Te=>{if(Te.length<2)return 0;const Me=Te[0].clientX-Te[1].clientX,Be=Te[0].clientY-Te[1].clientY;return Math.sqrt(Me*Me+Be*Be)},Se=Te=>Te.length<2?{x:Te[0].clientX,y:Te[0].clientY}:{x:(Te[0].clientX+Te[1].clientX)/2,y:(Te[0].clientY+Te[1].clientY)/2},ye=Te=>{Te.touches.length===2?(Te.preventDefault(),le(_e(Te.touches)),W(Se(Te.touches))):Te.touches.length===1&&D>1&&(Te.preventDefault(),ne(!0),ee({x:Te.touches[0].clientX-z.x,y:Te.touches[0].clientY-z.y}))},Ae=Te=>{if(Te.touches.length===2&&ue!==null){Te.preventDefault();const Me=_e(Te.touches),Be=Me/ue;H(tt=>{const te=Math.max(1,Math.min(4,tt*Be));return te===1&&X({x:0,y:0}),te}),le(Me);const Ke=Se(Te.touches);if(oe){const tt=U();X(te=>({x:Math.max(-tt.x,Math.min(tt.x,te.x+(Ke.x-oe.x))),y:Math.max(-tt.y,Math.min(tt.y,te.y+(Ke.y-oe.y)))}))}W(Ke)}else if(Te.touches.length===1&&L&&D>1){Te.preventDefault();const Me=Te.touches[0].clientX-ie.x,Be=Te.touches[0].clientY-ie.y,Ke=U();X({x:Math.max(-Ke.x,Math.min(Ke.x,Me)),y:Math.max(-Ke.y,Math.min(Ke.y,Be))})}},ve=Te=>{Te.touches.length<2&&(le(null),W(null)),Te.touches.length===0&&ne(!1)},je=()=>{H(1),X({x:0,y:0})},Re=g?"":za(o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`),Ee=p||g||A;return s?a.jsxs("div",{ref:ce,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(Tx,{className:"w-4 h-4"}),Y?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>Q("stream"),disabled:Ee,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")}),a.jsx("button",{onClick:()=>Q("snapshot"),disabled:Ee,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")})]}),a.jsx("button",{onClick:()=>j.mutate(!E?.chamber_light),disabled:!E?.connected||j.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${E?.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:a.jsx(iI,{on:E?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>d(!0),disabled:!O||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${O&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(O?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(VP,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:G,disabled:Ee,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(cr,{className:`w-4 h-4 text-bambu-gray ${Ee?"animate-spin":""}`})}),a.jsx("button",{onClick:J,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?a.jsx(jQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(cbe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:R,onMouseUp:ae,onMouseLeave:ae,onTouchStart:ye,onTouchMove:Ae,onTouchEnd:ve,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||g)&&!A&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(cr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),A&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Md,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:F,attempt:Math.min(P+1,vk),max:vk})}),a.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),u&&!A&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Rn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:G,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:re,src:Re,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${D}) translate(${z.x/D}px, ${z.y/D}px) rotate(${Y?.camera_rotation||0}deg)`,...Y?.camera_rotation===90||Y?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:D>1?L?"grabbing":"grab":"default"},onError:Re?he:void 0,onLoad:Re?I:void 0,onMouseDown:de,draggable:!1},x),a.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:[a.jsx("button",{onClick:fe,disabled:D<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(CO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:je,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(D*100),"%"]}),a.jsx("button",{onClick:se,disabled:D>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(NO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(sI,{printerId:s,isOpen:c,onClose:()=>d(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function urt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function mrt(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),i=t.get("camera"),s=i!=="false"&&i!=="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 hrt(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 prt(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 frt(){const{printerId:t}=Ew(),[e]=PP(),{t:n}=Rt(),r=sn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>mrt(e),[e]),c=prt(l.size),{data:d}=Qe({queryKey:["printer",i],queryFn:()=>me.getPrinter(i),enabled:i>0}),{data:u}=Qe({queryKey:["printerStatus",i],queryFn:()=>me.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Qe({queryKey:["settings"],queryFn:me.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,C=new WebSocket(_);return C.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},C.onerror=()=>{},()=>{C.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const x=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,g=za(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.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:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Ar,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:urt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:hrt(u,n)}),l.showProgress&&x&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),x&&(l.showLayers||l.showEta)&&a.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(aa,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(vd,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ps(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Qn,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",jO(u.remaining_time,p,n)]})]})]})]}),!x&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function grt(){const{t}=Rt(),{id:e}=Ew(),{mode:n}=wg(),{data:r,isLoading:i,error:s}=Qe({queryKey:["external-link",e],queryFn:()=>me.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Rn,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.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 gY(){const{id:t}=Ew(),e=Do(),n=sn(),{t:r}=Rt(),{showToast:i}=bn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[x,v]=w.useState(!1),{data:g,isLoading:b}=Qe({queryKey:["group",t],queryFn:()=>me.getGroup(Number(t)),enabled:s}),{data:_,isLoading:C}=Qe({queryKey:["permissions"],queryFn:()=>me.getPermissions()});s&&g&&!x&&(l(g.name),d(g.description||""),m(g.permissions),v(!0));const P=it({mutationFn:ee=>me.createGroup(ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),N=it({mutationFn:ee=>me.updateGroup(Number(t),ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),A=P.isPending||N.isPending,T=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==g?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},F=ee=>{m(ue=>ue.includes(ee)?ue.filter(le=>le!==ee):[...ue,ee])},k=(ee,ue)=>{const le=ee.permissions.map(oe=>oe.value);m(oe=>{const W=oe.filter(re=>!le.includes(re));return ue?[...W,...le]:W})},D=ee=>ee.permissions.every(ue=>u.includes(ue.value)),H=ee=>{const ue=ee.permissions.filter(le=>u.includes(le.value)).length;return ue>0&&ue<ee.permissions.length},z=()=>{_&&m(_.all_permissions)},X=()=>{m([])},L=p.toLowerCase(),ne=w.useMemo(()=>_?L?_.categories.map(ee=>({...ee,permissions:ee.permissions.filter(ue=>ue.label.toLowerCase().includes(L))})).filter(ee=>ee.permissions.length>0):_.categories:[],[_,L]),ie=_?.all_permissions.length??0;return b||C?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(kQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&a.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:[a.jsx(Rn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:ee=>l(ee.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")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:ee=>d(ee.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")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ie]}),a.jsx(Fe,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),a.jsx(Fe,{size:"sm",variant:"ghost",onClick:X,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:ee=>f(ee.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"})]})]}),ne.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:ne.map(ee=>{const ue=_.categories.find(ce=>ce.name===ee.name),le=ue.permissions.filter(ce=>u.includes(ce.value)).length,oe=ue.permissions.length,W=D(ue),re=H(ue);return a.jsxs(At,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>k(ue,!W),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${W?"bg-bambu-green border-bambu-green":re?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[W&&a.jsx(Rr,{className:"w-3 h-3 text-white"}),re&&!W&&a.jsx(cN,{className:"w-3 h-3 text-white"})]}),a.jsx(Du,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:ee.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[le,"/",oe]})]}),a.jsx("div",{className:"p-3 space-y-1",children:ee.permissions.map(ce=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(ce.value),onChange:()=>F(ce.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"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:ce.label})]},ce.value))})]},ee.name)})}),a.jsx("div",{className:"h-16"}),a.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:[a.jsx(Fe,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(Fe,{onClick:T,disabled:A||!o.trim(),children:A?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(gs,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const QL={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 Rle(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 Lle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],brt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],R0=["Basic","Matte","Silk","Silk+","Tough","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"],Ole=[{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"}],xrt=[{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"}],bY=[...Ole,...xrt],Ile="bambuddy-recent-colors",yrt=8,vrt=[{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 pp(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="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of R0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of R0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function zle(t,e){const n=new Set(brt);for(const r of t){const{brand:i}=pp(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=pp(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function wrt(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 i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Ule(t,e,n){if(t.length>0){const r=[],i=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=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=wrt(n);if(r.length>0)return r}return vrt}function Ble(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(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function Hle(){try{const t=localStorage.getItem(Ile);if(t)return JSON.parse(t)}catch{}return[]}function qle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,yrt);try{localStorage.setItem(Ile,JSON.stringify(r))}catch{}return r}function v3(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(),i=pp(r);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function $le({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:x}=Rt(),[v,g]=w.useState(!1),[b,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(""),[k,D]=w.useState(""),[H,z]=w.useState(""),[X,L]=w.useState(String(t.label_weight)),[ne,ie]=w.useState(!1),ee=w.useRef(null),ue=w.useRef(null),le=w.useRef(null),oe=w.useRef(null);w.useEffect(()=>{const $=Y=>{ee.current&&!ee.current.contains(Y.target)&&g(!1),oe.current&&!oe.current.contains(Y.target)&&A(!1),ue.current&&!ue.current.contains(Y.target)&&_(!1),le.current&&!le.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const W=w.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes($)||Y.code.toLowerCase().includes($))},[l,i]),re=w.useMemo(()=>{if(!T)return c;const $=T.toLowerCase();return c.filter(E=>E.toLowerCase().includes($)).sort((E,j)=>{const O=E.toLowerCase()===$,K=j.toLowerCase()===$;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[c,T]),ce=w.useMemo(()=>{if(!k)return R0;const $=k.toLowerCase();return R0.filter(Y=>Y.toLowerCase().includes($))},[k]),xe=w.useMemo(()=>{if(!H)return d;const $=H.toLowerCase();return d.filter(E=>E.toLowerCase().includes($)).sort((E,j)=>{const O=E.toLowerCase()===$,K=j.toLowerCase()===$;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[H,d]);w.useEffect(()=>{ne||L(String(t.label_weight))},[t.label_weight,ne]);const Ne=$=>{e("slicer_filament",$.code),s($.displayName),g(!1);const Y=pp($.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-3 h-3 animate-spin"})," ",x("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(sy,{className:"w-3 h-3 text-bambu-green"})," ",x("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(mfe,{className:"w-3 h-3"})," ",x("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:ee,children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:i,onChange:$=>{s($.target.value),g(!0)},onFocus:()=>{g(!0),s("")}}),v&&a.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:W.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noPresetsFound")}):W.map($=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===$.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Ne($),children:$.displayName},$.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[x("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:oe,children:[a.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:N?H:t.material,onChange:$=>{z($.target.value),A(!0)},onFocus:()=>{A(!0),z("")}}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.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:[xe.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):xe.map($=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",$),A(!1),z("")},children:$},$)),H&&!xe.includes(H)&&a.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",H),A(!1),z("")},children:x("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:ue,children:[a.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:b?T:t.brand,onChange:$=>{F($.target.value),_(!0)},onFocus:()=>{_(!0),F("")}}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),b&&a.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:[re.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):re.map($=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",$),_(!1),F("")},children:$},$)),T&&!re.includes(T)&&a.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",T),_(!1),F("")},children:x("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:le,children:[a.jsx("input",{type:"text",value:C?k:t.subtype,onChange:$=>{D($.target.value),P(!0)},onFocus:()=>{P(!0),D("")},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"}),a.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&a.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:[ce.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):ce.map($=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",$),P(!1),D("")},children:$},$)),k&&!R0.some($=>$.toLowerCase()===k.toLowerCase().trim())&&a.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",k),P(!1),D("")},children:x("inventory.useCustomBrand",{brand:k})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.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:X,min:0,onFocus:()=>ie(!0),onChange:$=>L($.target.value),onBlur:()=>{ie(!1);const $=X.trim(),Y=Number($);if(!$||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const E=Math.round(Y);e("label_weight",E),L(String(E))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("inventory.quantity")}),a.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:m,min:1,max:100,onChange:$=>{const Y=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(Y)}})]})]})}function Vle({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=b=>u.toUpperCase()===b.toUpperCase(),p=(b,_)=>{e("rgba",b.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:b})},f=w.useMemo(()=>{if(i.length===0)return[];const b=t.brand?.trim(),_=t.material?.toLowerCase().trim(),C=t.subtype?.toLowerCase().trim();if(!b&&!_)return[];const P=b?b.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],N=T=>{if(P.length===0)return!0;const F=T.toLowerCase();return P.some(k=>F.includes(k))};if(b&&!_){const T=i.filter(F=>N(F.manufacturer));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}const A=_&&C?`${_} ${C}`:"";if(A){const T=i.filter(k=>N(k.manufacturer)&&k.material?.toLowerCase()===A);if(T.length>0)return T.map(k=>({name:k.color_name,hex:k.hex_color.replace("#","").substring(0,6),manufacturer:k.manufacturer,material:typeof k.material=="string"?k.material:void 0}));const F=A.replace(/\+$/,"");if(F!==A){const k=i.filter(D=>N(D.manufacturer)&&D.material?.toLowerCase()===F);if(k.length>0)return k.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}}if(_){const T=i.filter(F=>N(F.manufacturer)&&(!F.material||F.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),x=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const b=c.toLowerCase();return f.filter(C=>C.name.toLowerCase().includes(b)||(C.manufacturer?.toLowerCase().includes(b)??!1)||(C.material?.toLowerCase().includes(b)??!1))},[c,f]),v=f.length>0,g=w.useMemo(()=>c?bY.filter(b=>b.name.toLowerCase().includes(c.toLowerCase())):o?bY:Ole,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(Qn,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(b=>a.jsx("button",{type:"button",onClick:()=>p(b.hex,b.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(b.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${b.hex}`},title:b.name},b.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:b=>d(b.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.map(b=>a.jsx("button",{type:"button",onClick:()=>p(b.hex,b.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(b.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${b.hex}`},title:b.manufacturer&&b.material?`${b.name} (${b.manufacturer} — ${b.material})`:b.manufacturer?`${b.name} (${b.manufacturer})`:b.name,children:a.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:b.manufacturer&&b.material?`${b.name} (${b.manufacturer} — ${b.material})`:b.manufacturer?`${b.name} (${b.manufacturer})`:b.name})},`${b.hex}-${b.name}-${b.manufacturer??""}`)),x.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(ac,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(Un,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(b=>a.jsx("button",{type:"button",onClick:()=>p(b.hex,b.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(b.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${b.hex}`},title:b.name,children:a.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:b.name})},b.hex)),g.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.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:b=>e("color_name",b.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.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:u.toUpperCase(),onChange:b=>{const _=b.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:b=>{const _=b.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Srt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=g=>{u.current&&!u.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(b=>b.id===r);if(g&&g.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=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]),f=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 f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(EQ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.jsx("input",{ref:m,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),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.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:p.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.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:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.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)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Gle({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Rt(),{showToast:s}=bn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=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(()=>{p||m(String(x))},[p,x]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Srt,{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)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:g=>{m(g.target.value)},onBlur:()=>{f(!1);const g=u.trim(),b=Number(g);if(!g||!Number.isFinite(b)||b<0||b>t.label_weight){m(String(x));return}const _=Math.round(b);e("weight_used",Math.max(0,t.label_weight-_)),m(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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:g=>{l(g.target.value)},onBlur:()=>{d(!1);const g=o.trim(),b=Number(g),_=t.core_weight,C=t.core_weight+t.label_weight;if(!g||!Number.isFinite(b)||b<_||b>C){s(i("inventory.measuredWeightError",{min:_,max:C}),"error"),l(String(v));return}const P=Math.round(b),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(String(P))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:g=>{const b=g.target.value===""?null:parseFloat(g.target.value);e("cost_per_kg",b)},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"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.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:i("inventory.notePlaceholder"),value:t.note,onChange:g=>e("note",g.target.value)})]})]})}function Wle({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Rt(),l=p=>{s(f=>{const x=new Set(f);return x.has(p)?x.delete(p):x.add(p),x})},c=(p,f,x)=>{const v=`${p}:${f}:${x??"null"}`,g=`${p}:${x??"null"}`;r(b=>{const _=new Set(b);if(_.has(v))_.delete(v);else{for(const C of Array.from(_)){const P=C.split(":");`${P[0]}:${P[2]}`===g&&_.delete(C)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:x}of e){if(!f.connected)continue;const v=x.filter(b=>v3(b,t)),g=new Map;for(const b of v){const _=`${b.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(b)}for(const[b,_]of g)if(_.length>0){const P=[..._].sort((N,A)=>A.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${b}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:x})=>f.connected?p+x.filter(v=>v3(v,t)).length:p,0),m=(p,f)=>{const x=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(x);return a.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:[a.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&a.jsxs("button",{type:"button",onClick:d,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:[a.jsx(Ax,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const x=i.has(String(p.id)),v=f.filter(P=>v3(P,t)),g=v.length,b=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),C=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{type:"button",onClick:()=>l(String(p.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[x?a.jsx(Un,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Ka,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),g>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?g===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):b?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),C.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:C.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function _rt(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 krt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Nrt({spoolId:t}){const{t:e}=Rt(),n=sn(),{showToast:r}=bn(),{data:i,isLoading:s}=Qe({queryKey:["spool-usage",t],queryFn:()=>me.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>me.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(dt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(Qn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Fe,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(rn,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:_rt(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:krt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Crt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Rt(),l=sn(),{showToast:c}=bn(),d=!!n,[u,m]=w.useState(QL),[p,f]=w.useState({}),[x,v]=w.useState("filament"),[g,b]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(1),[A,T]=w.useState(!1),[F,k]=w.useState(!1),[D,H]=w.useState([]),[z,X]=w.useState(""),[L,ne]=w.useState([]),[ie,ee]=w.useState([]),[ue,le]=w.useState([]),[oe,W]=w.useState([]),[re,ce]=w.useState([]),[xe,Ne]=w.useState(new Set),[$,Y]=w.useState(new Set),E=r.length>0?r:re,j=w.useMemo(()=>xe.size,[xe]);w.useEffect(()=>{W(Hle())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Re=await me.getCloudStatus();if(T(Re.is_authenticated),Re.is_authenticated){const Ee=await me.getFilamentPresets();H(Ee)}}catch(Re){console.error("Failed to fetch cloud presets:",Re),T(!1)}finally{k(!1)}})(),me.getSpoolCatalog().then(ne).catch(console.error),me.getColorCatalog().then(le).catch(console.error),me.getLocalPresets().then(Re=>ee(Re.filament)).catch(console.error),r.length===0&&(async()=>{try{const Re=await me.getPrinters(),Ee=await Promise.all(Re.map(Me=>me.getPrinterStatus(Me.id).catch(()=>null))),Te=[];for(let Me=0;Me<Re.length;Me++){const Be=Re[Me],tt=Ee[Me]?.connected??!1;let te=[];if(tt)try{te=(await me.getKProfiles(Be.id)).profiles.map(be=>({cali_idx:be.slot_id,filament_id:be.filament_id,setting_id:be.setting_id||"",name:be.name,k_value:parseFloat(be.k_value)||0,n_coef:parseFloat(be.n_coef)||0,extruder_id:be.extruder_id,nozzle_diameter:be.nozzle_diameter}))}catch{}Te.push({printer:{...Be,connected:tt},calibrations:te})}ce(Te)}catch(Re){console.error("Failed to fetch printer calibrations:",Re)}})())},[t,r.length]);const O=w.useMemo(()=>Ule(D,new Set,ie),[D,ie]),K=w.useMemo(()=>{const je=zle(D,ie),Re=ue.map(Te=>Te.manufacturer?.trim()).filter(Te=>!!Te),Ee=new Set([...je,...Re]);return Array.from(Ee).sort((Te,Me)=>Te.localeCompare(Me))},[D,ie,ue]),B=w.useMemo(()=>{const je=ue.map(Ee=>Ee.material?.trim()).filter(Ee=>!!Ee),Re=new Set([...Lle,...je]);return Array.from(Re).sort((Ee,Te)=>Ee.localeCompare(Te))},[ue]),he=w.useMemo(()=>{const je=[];for(const Re of ue){const Ee=Re.manufacturer?.trim(),Te=Re.material?.trim();Ee&&Te&&je.push({brand:Ee,material:Te})}for(const Re of D){const Ee=pp(Re.name);Ee.brand&&Ee.material&&je.push({brand:Ee.brand,material:Ee.material})}for(const Re of ie){const Ee=pp(Re.name),Te=Re.filament_vendor?.trim()||Ee.brand,Me=Ee.material;Te&&Me&&je.push({brand:Te,material:Me})}return je},[D,ue,ie]),I=w.useMemo(()=>{const je=new Map;for(const Re of he){const Ee=Re.brand.toLowerCase(),Te=Re.material.toLowerCase();je.has(Ee)||je.set(Ee,new Set),je.get(Ee).add(Te)}return je},[he]),V=w.useMemo(()=>{const je=new Map;for(const Re of he){const Ee=Re.brand.toLowerCase(),Te=Re.material.toLowerCase();je.has(Te)||je.set(Te,new Set),je.get(Te).add(Ee)}return je},[he]),Q=w.useMemo(()=>{if(!u.material)return K;const je=u.material.toLowerCase(),Re=V.get(je);return!Re||Re.size===0?K:K.filter(Ee=>Re.has(Ee.toLowerCase()))},[K,u.material,V]),G=w.useMemo(()=>{if(!u.brand)return B;const je=u.brand.toLowerCase(),Re=I.get(je);return!Re||Re.size===0?B:B.filter(Ee=>Re.has(Ee.toLowerCase()))},[B,u.brand,I]),J=w.useMemo(()=>Ble(u.slicer_filament,O),[u.slicer_filament,O]);w.useEffect(()=>{if(t){if(n)if(m({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}),X(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const je=new Set;for(const Re of n.k_profiles)Re.cali_idx!==null&&Re.cali_idx!==void 0&&je.add(`${Re.printer_id}:${Re.cali_idx}:${Re.extruder??"null"}`);Ne(je)}else Ne(new Set);else m(QL),X(""),Ne(new Set),C(!1),N(1);f({}),v("filament"),b(!1)}},[t,n]),w.useEffect(()=>{t&&E.length>0&&Y(new Set(E.map(je=>String(je.printer.id))))},[t,E]);const se=(je,Re)=>{m(Ee=>({...Ee,[je]:Re})),je==="weight_used"&&b(!0),p[je]&&f(Ee=>({...Ee,[je]:void 0}))},fe=je=>{W(Re=>qle(je,Re))},pe=it({mutationFn:je=>me.createSpool(je),onSuccess:async je=>{xe.size>0&&je?.id&&await ye(je.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([je]),c(o("inventory.spoolCreated"),"success"),e()},onError:je=>{c(je.message,"error")}}),de=it({mutationFn:({data:je,qty:Re})=>me.bulkCreateSpools(je,Re),onSuccess:async je=>{if(xe.size>0)for(const Re of je)await ye(Re.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(je),c(o("inventory.spoolsCreated",{count:je.length}),"success"),e()},onError:je=>{c(je.message,"error")}}),U=it({mutationFn:je=>me.updateSpool(n.id,je),onSuccess:async()=>{n?.id&&await ye(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:je=>{c(je.message,"error")}}),R=it({mutationFn:()=>me.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:je=>{c(je.message,"error")}}),{data:ae}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),enabled:t&&d}),_e=n?ae?.find(je=>je.spool_id===n.id):void 0,Se=it({mutationFn:()=>{if(!_e)throw new Error("No assignment");return me.unassignSpool(_e.printer_id,_e.ams_id,_e.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:je=>{c(je.message,"error")}}),ye=async je=>{if(xe.size===0){try{await me.saveSpoolKProfiles(je,[])}catch{}return}const Re=[];for(const Ee of xe){const[Te,Me,Be]=Ee.split(":"),Ke=parseInt(Te),tt=parseInt(Me),te=Be==="null"?0:parseInt(Be),Ie=E.find(be=>be.printer.id===Ke);if(Ie){const be=Ie.calibrations.find($e=>$e.cali_idx===tt);be&&Re.push({printer_id:Ke,extruder:te,nozzle_diameter:be.nozzle_diameter||"0.4",k_value:be.k_value,name:be.name||null,cali_idx:be.cali_idx,setting_id:be.setting_id||null})}}if(Re.length>0)try{await me.saveSpoolKProfiles(je,Re)}catch(Ee){console.error("Failed to save K-profiles:",Ee)}};if(w.useEffect(()=>{if(!t)return;const je=Re=>{Re.key==="Escape"&&e()};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[t,e]),!t)return null;const Ae=()=>{const je=Rle(u,_);if(!je.isValid){f(je.errors),(je.errors.slicer_filament||je.errors.material||je.errors.brand||je.errors.subtype)&&v("filament");return}const Re=J?.displayName||z||null,Ee={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:Re,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||g)&&(Ee.weight_used=u.weight_used),d?U.mutate(Ee):P>1?de.mutate({data:Ee,qty:P}):pe.mutate(Ee)},ve=pe.isPending||de.isPending||U.isPending||R.isPending||Se.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ic,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{C(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${x==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Iw,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${x==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(ype,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:x==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx($le,{formData:u,updateField:se,cloudAuthenticated:A,loadingCloudPresets:F,presetInputValue:z,setPresetInputValue:X,selectedPresetOption:J,filamentOptions:O,availableBrands:Q,availableMaterials:G,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(Vle,{formData:u,updateField:se,recentColors:oe,onColorUsed:fe,catalogColors:ue})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(Gle,{formData:u,updateField:se,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(Nrt,{spoolId:n.id})})]}):a.jsx(Wle,{formData:u,updateField:se,printersWithCalibrations:E,selectedProfiles:xe,setSelectedProfiles:Ne,expandedPrinters:$,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(Fe,{variant:"secondary",onClick:()=>R.mutate(),disabled:ve||!n?.tag_uid,children:[a.jsx(im,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(Fe,{variant:"secondary",onClick:()=>Se.mutate(),disabled:ve||!_e,children:[a.jsx(ap,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(Fe,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Fe,{onClick:Ae,disabled:ve,children:ve?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(gs,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Prt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Rt(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((A,T)=>T===P?{...A,visible:!A.visible}:A))},p=(P,N)=>{N<0||N>=o.length||l(A=>{const T=[...A],[F]=T.splice(P,1);return T.splice(N,0,F),T})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},x=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const A=u.current;A!==null&&A!==N&&(p(A,N),u.current=N,d(N))},v=P=>{P.preventDefault()},g=()=>{u.current=null,d(null)},b=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},C=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Mt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",C," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:A=>f(A,N),onDragOver:A=>x(A,N),onDrop:v,onDragEnd:g,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx($h,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===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:a.jsx(ac,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===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:a.jsx(Un,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(ul,{className:"w-4 h-4"}):a.jsx(vg,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Fe,{variant:"secondary",onClick:b,className:"mr-auto",children:[a.jsx(eo,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Fe,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Fe,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function xY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Kle="bambuddy-inventory-columns",Yk=[{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:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Trt(){try{const t=localStorage.getItem(Kle);if(t){const e=JSON.parse(t),n=new Set(Yk.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=Yk.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return Yk.map(t=>({...t}))}function Art(t){try{localStorage.setItem(Kle,JSON.stringify(t))}catch{}}function Nd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const jrt={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 w3(t,e="system"){if(!t)return"-";const n=er(t);return n?J3(n,e):"-"}const Mrt={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"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},ZL={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:w3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:w3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?w3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/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})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:FP(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.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 a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=bS(n.ams_id,n.tray_id,s,i);return a.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,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:Nd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:Nd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Nd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Nd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.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?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n<r?(s=n-r,o=!0):(s=n-i,o=Math.abs(s)<=50);const l=s>0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g
- Calculated: ${Math.round(i)}g
- Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g
- Calculated: ${Math.round(i)}g
- Difference: ${l}g (mismatch!)`;return a.jsxs("div",{className:`flex items-center gap-1 text-sm font-medium ${o?"text-green-400":"text-yellow-400"}`,title:c,children:[a.jsxs("span",{children:[Math.round(n),"g"]}),o?a.jsx(Rr,{className:"w-3 h-3"}):a.jsxs(a.Fragment,{children:[a.jsx(Rn,{className:"w-3 h-3"}),e&&a.jsx("button",{type:"button",onClick:d=>{d.stopPropagation(),d.preventDefault(),e(t)},className:"p-1 hover:bg-bambu-green/20 rounded transition-colors text-bambu-green",title:"Sync: trust scale weight and reset tracking",children:a.jsx(cr,{className:"w-3.5 h-3.5"})})]})]})}},S3={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,i=!r&&n.ams_id>=128,s=n.ams_label?` (${n.ams_label})`:"";return`${n.printer_name||""} ${bS(n.ams_id,n.tray_id,i,r)}${s}`},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,spool_name:t=>t.core_weight_catalog_id??0,cost_per_kg:t=>t.cost_per_kg??0,weight_check:t=>{if(t.last_scale_weight==null)return-1;const e=Math.max(0,t.label_weight-t.weight_used)+t.core_weight;return Math.abs(t.last_scale_weight-e)}},JL="bambuddy-inventory-sort";function Ert(){try{const t=localStorage.getItem(JL);if(t)return JSON.parse(t)}catch{}return null}function Drt(t){try{t?localStorage.setItem(JL,JSON.stringify(t)):localStorage.removeItem(JL)}catch{}}function Frt(){const{data:t}=Qe({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings,staleTime:3e5});return t?.spoolman_enabled==="true"&&t?.spoolman_url?a.jsx("iframe",{src:`${t.spoolman_url.replace(/\/+$/,"")}/spool`,className:"h-full w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}):a.jsx(Rrt,{})}function Rrt(){const{t}=Rt(),e=sn(),{showToast:n}=bn(),[r,i]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[d,u]=w.useState("all"),[m,p]=w.useState(""),[f,x]=w.useState(""),[v,g]=w.useState(""),[b,_]=w.useState("all"),[C,P]=w.useState(""),[N,A]=w.useState("table"),[T,F]=w.useState(Ert),[k,D]=w.useState(Trt),[H,z]=w.useState(!1),[X,L]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[ne,ie]=w.useState(new Set),[ee,ue]=w.useState(0),[le,oe]=w.useState(()=>{try{const ge=localStorage.getItem("bambuddy-inventory-pageSize");if(ge){const Pe=Number(ge);if([15,30,50,100,-1].includes(Pe))return Pe}}catch{}return 15}),{data:W}=Qe({queryKey:["settings"],queryFn:me.getSettings}),re=W?.date_format||"system",{data:ce,isLoading:xe}=Qe({queryKey:["inventory-spools"],queryFn:()=>me.getSpools(!0),refetchInterval:3e4}),{data:Ne}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),refetchInterval:3e4}),{data:$}=Qe({queryKey:["spool-catalog"],queryFn:()=>me.getSpoolCatalog()}),Y=it({mutationFn:ge=>me.deleteSpool(ge),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),E=it({mutationFn:ge=>me.archiveSpool(ge),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),j=it({mutationFn:ge=>me.restoreSpool(ge),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),O=async ge=>{if(ge.last_scale_weight!=null)try{await Ur.updateSpoolWeight(ge.id,ge.last_scale_weight),e.invalidateQueries({queryKey:["inventory-spools"]});const Pe=[ge.brand,ge.material,ge.color_name].filter(Boolean).join(" ");n(`Synced "${Pe}" to scale weight`,"success")}catch{n("Failed to sync weight","error")}},K=W?.low_stock_threshold??20,[B,he]=w.useState(!1),[I,V]=w.useState(K.toString());w.useEffect(()=>{B||V(K.toString())},[K,B]);const Q=it({mutationFn:ge=>me.updateSettings({low_stock_threshold:ge}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),n(t("common.saved"),"success"),he(!1)},onError:()=>{n(t("inventory.lowStockThresholdError"),"error")}}),G=w.useMemo(()=>{if(!ce)return null;let ge=0,Pe=0,qe=0,Ze=0;const ut={};for(const vt of ce){if(vt.archived_at)continue;Ze++;const wt=Math.max(0,vt.label_weight-vt.weight_used);ge+=wt,Pe+=vt.weight_used,(vt.label_weight>0?wt/vt.label_weight*100:0)<K&&qe++;const Qt=vt.material||"Unknown";ut[Qt]||(ut[Qt]={count:0,weight:0}),ut[Qt].count++,ut[Qt].weight+=wt}return{totalWeight:ge,totalConsumed:Pe,lowStock:qe,byMaterial:ut,totalSpools:Ze}},[ce,K]),J=Ne?.length??0,se=So(W?.currency||"USD"),fe=w.useMemo(()=>{const ge={};for(const Pe of Ne||[])ge[Pe.spool_id]=Pe;return ge},[Ne]),pe=w.useMemo(()=>{const ge={};for(const Pe of $||[])ge[Pe.id]=Pe;return ge},[$]),de=w.useMemo(()=>G?Object.entries(G.byMaterial).sort((ge,Pe)=>Pe[1].weight-ge[1].weight).slice(0,4):[],[G]),U=w.useMemo(()=>{let ge=ce||[];if(l==="active"?ge=ge.filter(Pe=>!Pe.archived_at):ge=ge.filter(Pe=>!!Pe.archived_at),d==="used"?ge=ge.filter(Pe=>Pe.weight_used>0):d==="new"?ge=ge.filter(Pe=>Pe.weight_used===0):d==="lowstock"&&(ge=ge.filter(Pe=>{const qe=Math.max(0,Pe.label_weight-Pe.weight_used);return(Pe.label_weight>0?qe/Pe.label_weight*100:0)<K})),m&&(ge=ge.filter(Pe=>Pe.material===m)),f&&(ge=ge.filter(Pe=>Pe.brand===f)),v){const Pe=Number(v);ge=ge.filter(qe=>qe.core_weight_catalog_id===Pe)}if(b==="stock"?ge=ge.filter(Pe=>!Pe.slicer_filament):b==="configured"&&(ge=ge.filter(Pe=>!!Pe.slicer_filament)),C){const Pe=C.toLowerCase();ge=ge.filter(qe=>qe.brand?.toLowerCase().includes(Pe)||qe.material.toLowerCase().includes(Pe)||qe.color_name?.toLowerCase().includes(Pe)||qe.subtype?.toLowerCase().includes(Pe)||qe.note?.toLowerCase().includes(Pe)||qe.slicer_filament_name?.toLowerCase().includes(Pe))}return ge},[ce,l,d,m,f,v,b,C,K]),R=()=>ue(0),ae=[...new Set(ce?.map(ge=>ge.material)||[])].sort(),_e=[...new Set(ce?.map(ge=>ge.brand).filter(Boolean)||[])].sort(),Se=[...new Set(ce?.map(ge=>ge.core_weight_catalog_id).filter(ge=>ge!=null)||[])].sort((ge,Pe)=>{const qe=(pe[ge]?.name||"").toLowerCase(),Ze=(pe[Pe]?.name||"").toLowerCase();return qe.localeCompare(Ze)}),ye=l!=="active"||d!=="all"||!!m||!!f||!!v||b!=="all"||!!C,Ae=ge=>{D(ge),Art(ge)},ve=w.useMemo(()=>k.filter(ge=>ge.visible).map(ge=>ge.id),[k]),je=ge=>{S3[ge]&&(F(Pe=>{let qe;return Pe?.column===ge?qe=Pe.direction==="asc"?{column:ge,direction:"desc"}:null:qe={column:ge,direction:"asc"},Drt(qe),qe}),R())},Re=w.useMemo(()=>{if(!T)return U;const ge=S3[T.column];return ge?[...U].sort((qe,Ze)=>{const ut=ge(qe,fe),vt=ge(Ze,fe);return ut<vt?T.direction==="asc"?-1:1:ut>vt?T.direction==="asc"?1:-1:0}):U},[U,T,fe]),Ee=w.useMemo(()=>{if(!X)return Re.map(Ze=>({type:"single",spool:Ze}));const ge=new Map;for(const Ze of Re)if(!(Ze.weight_used>0||fe[Ze.id])){const ut=xY(Ze),vt=ge.get(ut);vt?vt.push(Ze):ge.set(ut,[Ze])}const Pe=[],qe=new Set;for(const Ze of Re){if(Ze.weight_used>0||fe[Ze.id]){Pe.push({type:"single",spool:Ze});continue}const ut=xY(Ze);if(qe.has(ut))continue;qe.add(ut);const vt=ge.get(ut);vt.length===1?Pe.push({type:"single",spool:vt[0]}):Pe.push({type:"group",key:ut,spools:vt,representative:vt[0]})}return Pe},[Re,X,fe]),Te=le===-1,Me=Ee.length,Be=Te?Me||1:le,Ke=Math.max(1,Math.ceil(Me/Be)),tt=Te?0:Math.min(ee,Ke-1),te=Te?Ee:Ee.slice(tt*Be,(tt+1)*Be),Ie=()=>{const ge=!X;L(ge),ie(new Set),R();try{localStorage.setItem("bambuddy-inventory-group",String(ge))}catch{}},be=ge=>{ie(Pe=>{const qe=new Set(Pe);return qe.has(ge)?qe.delete(ge):qe.add(ge),qe})},$e=ge=>{oe(ge),ue(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(ge))}catch{}},He=()=>{c("active"),u("all"),p(""),x(""),g(""),_("all"),P(""),R()};return a.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(ja,{className:"w-6 h-6 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),a.jsxs(Fe,{onClick:()=>i({spool:null}),children:[a.jsx(or,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),G&&!xe&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(ja,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Nd(G.totalWeight,!0)}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[G.totalSpools," ",G.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(_O,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:Nd(G.totalConsumed,!0)}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(aa,{className:"w-4 h-4 text-green-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:de.map(([ge,Pe])=>a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${jrt[ge]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ge," ",a.jsx("span",{className:"opacity-70",children:Nd(Pe.weight,!0)})]},ge))})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Ar,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),a.jsx("div",{className:"text-xl font-bold text-white",children:J}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx(Rn,{className:"w-4 h-4 text-yellow-400"}),a.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),a.jsx("div",{className:`text-xl font-bold ${G.lowStock>0?"text-yellow-400":"text-white"}`,children:G.lowStock}),a.jsx("div",{className:"text-xs text-bambu-gray mt-1 flex items-center gap-2",children:B?a.jsxs("form",{onSubmit:ge=>{ge.preventDefault();const Pe=parseFloat(I);!isNaN(Pe)&&Pe>=.1&&Pe<=99.9?Q.mutate(Pe):n(t("inventory.lowStockThresholdError"),"error")},className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"<"}),a.jsx("input",{type:"text",inputMode:"decimal",pattern:"^\\d{0,2}(\\.\\d?)?$",maxLength:4,value:I,onChange:ge=>{const Pe=ge.target.value.replace(/[^\d.]/g,"");/^\d{0,2}(\.\d?)?$/.test(Pe)&&V(Pe)},className:"px-1.5 py-1 rounded border border-bambu-dark-tertiary text-xs text-white bg-bambu-dark-secondary focus:outline-none focus:border-bambu-green w-14 text-center",onWheel:ge=>ge.currentTarget.blur(),disabled:Q.isPending}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"%"}),a.jsx(Fe,{type:"submit",size:"sm",disabled:Q.isPending,children:t("common.save")}),a.jsx(Fe,{type:"button",size:"sm",variant:"ghost",onClick:()=>he(!1),disabled:Q.isPending,children:t("common.cancel")})]}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"text-bambu-gray",children:["< ",K,"%"]}),a.jsx("button",{className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("common.edit"),onClick:()=>{V(K.toString()),he(!0)},children:a.jsx(Iu,{className:"w-4 h-4"})})]})})]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[a.jsxs("div",{className:"relative flex-1 max-w-md",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:C,onChange:ge=>{P(ge.target.value),R()},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"}),C&&a.jsx("button",{onClick:()=>{P(""),R()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[N==="table"&&a.jsxs("button",{onClick:()=>z(!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:[a.jsx(kfe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),a.jsxs("button",{onClick:Ie,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${X?"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:[a.jsx(Pge,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),a.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>A("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:[a.jsx(kxe,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),a.jsxs("button",{onClick:()=>A("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:[a.jsx(Lw,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("button",{onClick:()=>{c("active"),R()},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:[a.jsx(ja,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),a.jsxs("button",{onClick:()=>{c("archived"),R()},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:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{u("all"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${d==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsxs("button",{onClick:()=>{u("used"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${d==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Qn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),a.jsx("button",{onClick:()=>{u("new"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${d==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")}),a.jsxs("button",{onClick:()=>{u("lowstock"),R()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${d==="lowstock"?"bg-yellow-500/20 text-yellow-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),t("inventory.lowStock")]})]}),a.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsx("button",{onClick:()=>{_("all"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${b==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),a.jsx("button",{onClick:()=>{_("stock"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${b==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),a.jsx("button",{onClick:()=>{_("configured"),R()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${b==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("select",{value:m,onChange:ge=>{p(ge.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${m?"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:[a.jsx("option",{value:"",children:t("inventory.material")}),ae.map(ge=>a.jsx("option",{value:ge,children:ge},ge))]}),a.jsxs("select",{value:f,onChange:ge=>{x(ge.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${f?"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:[a.jsx("option",{value:"",children:t("inventory.brand")}),_e.map(ge=>a.jsx("option",{value:ge,children:ge},ge))]}),Se.length>0&&a.jsxs("select",{value:v,onChange:ge=>{g(ge.target.value),R()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${v?"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:[a.jsx("option",{value:"",children:t("inventory.spoolName")}),Se.map(ge=>a.jsx("option",{value:ge,children:pe[ge]?.name||`#${ge}`},ge))]}),ye&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),a.jsxs("button",{onClick:He,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[a.jsx(Bt,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),a.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Re.length," ",Re.length!==1?t("inventory.spools"):t("inventory.spool"),X&&Me<Re.length&&` (${Me} ${t("inventory.groupedRows")})`]})]}),xe?a.jsx("div",{className:"flex justify-center py-16",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):N==="cards"?te.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:te.map(ge=>{if(ge.type==="group"){const{key:vt,spools:wt,representative:$t}=ge,Qt=$t.rgba?`#${$t.rgba.substring(0,6)}`:"#808080",en=ne.has(vt);return a.jsxs("div",{className:"col-span-full",children:[a.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(vt),children:[a.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:Qt},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:FP($t.color_name,$t.rgba)||"-"})}),a.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Un,{className:`w-4 h-4 text-bambu-gray transition-transform ${en?"":"-rotate-90"}`}),a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[$t.material,$t.subtype?` ${$t.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:$t.brand||"-"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:Nd($t.label_weight)}),a.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:wt.length})})]})]})]}),en&&a.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:wt.map(Xt=>{const tn=Math.max(0,Xt.label_weight-Xt.weight_used),Ge=Xt.label_weight>0?tn/Xt.label_weight*100:0,Ft=Xt.rgba?`#${Xt.rgba.substring(0,6)}`:"#808080";return a.jsx(yY,{spool:Xt,remaining:tn,pct:Ge,colorStyle:Ft,onClick:()=>i({spool:Xt}),t},Xt.id)})})]},`group-${vt}`)}const Pe=ge.spool,qe=Math.max(0,Pe.label_weight-Pe.weight_used),Ze=Pe.label_weight>0?qe/Pe.label_weight*100:0,ut=Pe.rgba?`#${Pe.rgba.substring(0,6)}`:"#808080";return a.jsx(yY,{spool:Pe,remaining:qe,pct:Ze,colorStyle:ut,onClick:()=>i({spool:Pe}),t},Pe.id)})}),a.jsx(Lrt,{pageIndex:tt,pageSize:le,totalRows:Me,totalPages:Ke,onPageChange:ue,onPageSizeChange:$e,t})]}):a.jsx(vY,{hasFilters:ye,onAddSpool:()=>i({spool:null}),t}):te.length>0?a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[ve.map(ge=>{const Pe=!!S3[ge],qe=T?.column===ge;return a.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${ge==="remaining"?"min-w-[150px]":""} ${Pe?"cursor-pointer hover:text-bambu-green transition-colors":""} ${qe?"text-bambu-green":"text-bambu-gray"}`,onClick:Pe?()=>je(ge):void 0,children:a.jsxs("span",{className:"inline-flex items-center gap-1",children:[Mrt[ge]?.(t)??ge,Pe&&(qe?T.direction==="asc"?a.jsx(Wf,{className:"w-3 h-3"}):a.jsx(Cx,{className:"w-3 h-3"}):a.jsx(fO,{className:"w-3 h-3 opacity-30"}))]})},ge)}),a.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),a.jsx("tbody",{children:te.map(ge=>{if(ge.type==="group"){const{key:ut,spools:vt,representative:wt}=ge,$t=ne.has(ut),Qt=Math.max(0,wt.label_weight-wt.weight_used),en=wt.label_weight>0?Qt/wt.label_weight*100:0;return a.jsx(Ort,{spools:vt,representative:wt,remaining:Qt,pct:en,isExpanded:$t,onToggle:()=>be(ut),onEdit:Xt=>i({spool:Xt}),onArchive:Xt=>o({type:"archive",spoolId:Xt}),onDelete:Xt=>o({type:"delete",spoolId:Xt}),visibleColumns:ve,assignmentMap:fe,catalogMap:pe,currencySymbol:se,dateFormat:re,t,onSyncWeight:O},`group-${ut}`)}const Pe=ge.spool,qe=Math.max(0,Pe.label_weight-Pe.weight_used),Ze=Pe.label_weight>0?qe/Pe.label_weight*100:0;return a.jsx(Xle,{spool:Pe,remaining:qe,pct:Ze,onEdit:()=>i({spool:Pe}),onRestore:()=>j.mutate(Pe.id),onArchive:()=>o({type:"archive",spoolId:Pe.id}),onDelete:()=>o({type:"delete",spoolId:Pe.id}),visibleColumns:ve,assignmentMap:fe,catalogMap:pe,currencySymbol:se,dateFormat:re,t,onSyncWeight:O},Pe.id)})})]})}),a.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:[a.jsx("span",{className:"text-bambu-gray",children:Te?`${Me} ${t(Me!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[t("inventory.showing")," ",tt*Be+1," ",t("inventory.to")," ",Math.min((tt+1)*Be,Me)," ",t("inventory.of")," ",Me," ",t("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),a.jsxs("select",{value:le,onChange:ge=>$e(Number(ge.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(ge=>a.jsx("option",{value:ge,children:ge},ge)),a.jsx("option",{value:-1,children:t("inventory.all")})]}),!Te&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>ue(0),disabled:tt===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:a.jsx(bO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>ue(ge=>Math.max(0,ge-1)),disabled:tt===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(dl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",tt+1," ",t("inventory.of")," ",Ke]}),a.jsx("button",{onClick:()=>ue(ge=>Math.min(Ke-1,ge+1)),disabled:tt>=Ke-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:a.jsx(Ka,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>ue(Ke-1),disabled:tt>=Ke-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:a.jsx(xO,{className:"w-4 h-4"})})]})]})]})]}):a.jsx(vY,{hasFilters:ye,onAddSpool:()=>i({spool:null}),t}),r!==null&&a.jsx(Crt,{isOpen:!0,onClose:()=>i(null),spool:r.spool,currencySymbol:se}),s&&a.jsx(_n,{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"?Y.mutate(s.spoolId):E.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),a.jsx(Prt,{isOpen:H,onClose:()=>z(!1),columns:k,defaultColumns:Yk,onSave:Ae})]})}function Lrt({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return a.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:a.jsxs(a.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),a.jsxs("select",{value:e,onChange:d=>s(Number(d.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(d=>a.jsx("option",{value:d,children:d},d)),a.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>i(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:a.jsx(bO,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(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:a.jsx(dl,{className:"w-4 h-4"})}),a.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),a.jsx("button",{onClick:()=>i(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:a.jsx(Ka,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>i(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:a.jsx(xO,{className:"w-4 h-4"})})]})]})]})}function yY({spool:t,remaining:e,pct:n,colorStyle:r,onClick:i,t:s}){return a.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:i,children:[a.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:a.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:FP(t.color_name,t.rgba)||"-"})}),a.jsxs("div",{className:"p-4 space-y-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{children:[a.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),a.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[a.jsx("span",{children:s("inventory.remaining")}),a.jsxs("span",{children:[Math.round(n),"%"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.labelWeight"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:Nd(t.label_weight)})]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),a.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?Nd(t.weight_used):"-"})]})]}),t.note&&a.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 Xle({spool:t,remaining:e,pct:n,onEdit:r,onRestore:i,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,catalogMap:d,currencySymbol:u,dateFormat:m,t:p,onSyncWeight:f}){return a.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(x=>a.jsx("td",{className:"py-3 px-4",children:ZL[x]?.({spool:t,remaining:e,pct:n,assignmentMap:c,catalogMap:d,currencySymbol:u,dateFormat:m,t:p,onSyncWeight:f})},x)),a.jsx("td",{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:x=>x.stopPropagation(),children:[a.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:p("common.edit"),children:a.jsx(Iu,{className:"w-4 h-4"})}),t.archived_at?a.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:p("inventory.restore"),children:a.jsx(eo,{className:"w-4 h-4"})}):a.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:p("inventory.archive"),children:a.jsx(Qs,{className:"w-4 h-4"})}),a.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:p("common.delete"),children:a.jsx(rn,{className:"w-4 h-4"})})]})})]})}function Ort({spools:t,representative:e,remaining:n,pct:r,isExpanded:i,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:d,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:x,onSyncWeight:v}){return a.jsxs(a.Fragment,{children:[a.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:[d.map((g,b)=>a.jsx("td",{className:"py-3 px-4",children:b===0?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Un,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"":"-rotate-90"}`}),ZL[g]?.({spool:e,remaining:n,pct:r,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:x,onSyncWeight:v})]}):g==="id"?a.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:x("inventory.groupedSpools",{count:t.length})}):ZL[g]?.({spool:e,remaining:n,pct:r,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:x,onSyncWeight:v})},g)),a.jsx("td",{className:"py-3 px-4",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(g=>`#${g.id}`).join(", ")})})]}),i&&t.map(g=>{const b=Math.max(0,g.label_weight-g.weight_used),_=g.label_weight>0?b/g.label_weight*100:0;return a.jsx(Xle,{spool:g,remaining:b,pct:_,onEdit:()=>o(g),onRestore:()=>{},onArchive:()=>l(g.id),onDelete:()=>c(g.id),visibleColumns:d,assignmentMap:u,catalogMap:m,currencySymbol:p,dateFormat:f,t:x,onSyncWeight:v},g.id)})]})}function vY({hasFilters:t,onAddSpool:e,t:n}){return a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[a.jsxs("div",{className:"relative mb-6",children:[a.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),a.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:[a.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),a.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?a.jsx(kr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:a.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),a.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:a.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),a.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&a.jsxs(Fe,{onClick:e,children:[a.jsx(ja,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const wY=["DEBUG","INFO","WARNING","ERROR"],_3={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},Irt={DEBUG:Px,INFO:fs,WARNING:Rn,ERROR:Wa};function zrt(){const t=sn(),[e,n]=w.useState(!0),[r,i]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[d,u]=w.useState(!1),[m,p]=w.useState(!1),f=w.useRef(null),{data:x,isLoading:v,refetch:g}=Qe({queryKey:["application-logs",l,s],queryFn:()=>ux.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:m?2e3:!1,enabled:d});w.useEffect(()=>{d||p(!1)},[d]);const b=it({mutationFn:()=>ux.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&f.current&&x?.entries&&(f.current.scrollTop=f.current.scrollHeight)},[x?.entries,e]);const _=T=>{i(F=>{const k=new Set(F);return k.has(T)?k.delete(T):k.add(T),k})},C=T=>{const F=T.split(" ");return F.length>=2?F[1]:T},P=w.useMemo(()=>x?.entries??[],[x?.entries]),N=w.useMemo(()=>[...P].reverse(),[P]),A=({level:T})=>{const F=Irt[T]||fs;return a.jsx(F,{className:`w-3.5 h-3.5 ${_3[T]||"text-gray-400"}`})};return a.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>u(!d),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${m?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(Px,{className:"w-5 h-5"})}),a.jsxs("div",{className:"text-left",children:[a.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:m?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[m&&a.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[a.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),d?a.jsx(ac,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(Un,{className:"w-5 h-5 text-bambu-gray"})]})]}),d&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m?a.jsxs("button",{onClick:T=>{T.stopPropagation(),p(!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:[a.jsx(to,{className:"w-4 h-4"}),"Stop"]}):a.jsxs("button",{onClick:T=>{T.stopPropagation(),p(!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:[a.jsx($i,{className:"w-4 h-4"}),"Start"]}),a.jsxs("button",{onClick:()=>b.mutate(),disabled:b.isPending||P.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:[a.jsx(rn,{className:"w-4 h-4"}),"Clear"]}),a.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:a.jsx(cr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),a.jsx("div",{className:"flex-1"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:e,onChange:T=>n(T.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:T=>o(T.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&&a.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[a.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"}),wY.map((T,F)=>a.jsx("button",{onClick:()=>c(T),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${F===wY.length-1?"rounded-r":""} ${l===T?`${_3[T]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:T},T))]})]})]}),a.jsx("div",{ref:f,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:P.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:"No log entries found"}),a.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:N.map((T,F)=>{const k=r.has(F),D=T.message.includes(`
- `);return a.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${k?"bg-bambu-dark-secondary/30":""}`,onClick:()=>D&&_(F),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:C(T.timestamp)}),a.jsx("span",{className:"shrink-0",children:a.jsx(A,{level:T.level})}),a.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:T.logger_name,children:["[",T.logger_name,"]"]}),a.jsx("span",{className:`flex-1 ${_3[T.level]||"text-white/80"} ${!k&&D?"truncate":""}`,children:k?a.jsx("pre",{className:"whitespace-pre-wrap break-all",children:T.message}):T.message.split(`
- `)[0]}),D&&a.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:k?a.jsx(ac,{className:"w-3.5 h-3.5"}):a.jsx(Un,{className:"w-3.5 h-3.5"})})]})},F)})})}),a.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:m?a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):a.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function Urt(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 wa({icon:t,label:e,value:n,subValue:r,color:i="text-bambu-green"}){return a.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function SY({percent:t,color:e="bg-bambu-green"}){return a.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function uh({title:t,icon:e,children:n}){return a.jsxs(At,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[a.jsx(e,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function Brt(){const{t}=Rt(),e=sn(),[n,r]=w.useState(null),[i,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:d,refetch:u,isFetching:m}=Qe({queryKey:["systemInfo"],queryFn:me.getSystemInfo,refetchInterval:3e4}),{data:p}=Qe({queryKey:["debugLogging"],queryFn:ux.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:f}=Qe({queryKey:["settings"],queryFn:me.getSettings}),{data:x}=Qe({queryKey:["library-stats"],queryFn:me.getLibraryStats}),v=f?.time_format||"system",g=async()=>{l(!0);try{const P=await ux.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],P)}catch(P){console.error("Failed to toggle debug logging:",P)}finally{l(!1)}},b=async()=>{r(null),s(!0);try{await ux.downloadSupportBundle()}catch(P){r(P instanceof Error?P.message:"Failed to download support bundle")}finally{s(!1)}};if(d)return a.jsx("div",{className:"flex items-center justify-center h-64",children:a.jsx(dt,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return a.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",C=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return a.jsxs("div",{className:"p-6 space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),a.jsxs("button",{onClick:()=>u(),disabled:m,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:[a.jsx(cr,{className:`w-4 h-4 ${m?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),a.jsx(uh,{title:t("system.application","Application"),icon:sf,children:a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(wa,{icon:sf,label:t("system.version","Version"),value:`v${c.app.version}`}),a.jsx(wa,{icon:Qn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),a.jsx(wa,{icon:sf,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),a.jsx(uh,{title:t("support.title","Support & Troubleshooting"),icon:Dge,children:a.jsxs("div",{className:"space-y-4",children:[a.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.")}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:a.jsx(Px,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[p?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),p?.enabled&&p.duration_seconds!==null&&a.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),a.jsxs("button",{onClick:g,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${p?.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&&a.jsx(dt,{className:"w-4 h-4 animate-spin"}),p?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:a.jsx(ca,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),a.jsxs("button",{onClick:b,disabled:i||!p?.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:p?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[i&&a.jsx(dt,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!p?.enabled&&a.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:a.jsxs("p",{className:"text-sm text-bambu-gray",children:[a.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),a.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),a.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),a.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),a.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),a.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),a.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),a.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),a.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),a.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),a.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),a.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),a.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),a.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),a.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[a.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),a.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),a.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),a.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),a.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),a.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]}),a.jsxs("li",{children:["• ",t("support.notItem7","IP addresses")]})]})]})]}),a.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], serial numbers with [SERIAL], and IP addresses with [IP].")})]}),a.jsx(zrt,{})]})}),a.jsxs(uh,{title:t("system.database","Database"),icon:Kl,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[a.jsx(wa,{icon:Kl,label:t("system.dbEngine","Database Engine"),value:c.database.engine||"SQLite"}),a.jsx(wa,{icon:Kl,label:t("system.dbVersion","Version"),value:c.database.version||"unknown"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[a.jsx(wa,{icon:Qs,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),a.jsx(wa,{icon:nl,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),a.jsx(wa,{icon:Na,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),a.jsx(wa,{icon:dt,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(wa,{icon:Ar,label:t("system.printers","Printers"),value:c.database.printers}),a.jsx(wa,{icon:Iw,label:t("system.filaments","Filaments"),value:c.database.filaments}),a.jsx(wa,{icon:Es,label:t("system.projects","Projects"),value:c.database.projects}),a.jsx(wa,{icon:Ql,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[a.jsx(wa,{icon:Qn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),a.jsx(wa,{icon:Qs,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),a.jsxs(uh,{title:t("system.connectedPrinters","Connected Printers"),icon:Ar,children:[a.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[a.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),a.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?a.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(P=>a.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),a.jsx("span",{className:"font-medium text-white",children:P.name})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[a.jsx("span",{children:P.model}),a.jsx("span",{className:`px-2 py-0.5 rounded ${P.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":P.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:P.state})]})]},P.id))}):a.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),a.jsx(uh,{title:t("system.storage","Storage"),icon:rp,children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),a.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),a.jsx(SY,{percent:c.storage.disk_percent_used,color:_}),a.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),"%)"]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a.jsx(wa,{icon:Qs,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),a.jsx(wa,{icon:Kl,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&a.jsx(wa,{icon:Uc,label:t("system.fileManagerStorage","File Manager"),value:Urt(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[a.jsx(uh,{title:t("system.memory","Memory"),icon:ube,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),a.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),a.jsx(SY,{percent:c.memory.percent_used,color:C}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),a.jsx(uh,{title:t("system.cpu","CPU"),icon:Kv,children:a.jsx("div",{className:"space-y-4",children:a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsx(wa,{icon:Kv,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),a.jsx(wa,{icon:Kv,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),a.jsx(uh,{title:t("system.systemDetails","System Details"),icon:sf,children:a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(wa,{icon:sf,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),a.jsx(wa,{icon:Kv,label:t("system.architecture","Architecture"),value:c.system.architecture}),a.jsx(wa,{icon:sf,label:t("system.python","Python"),value:c.system.python_version}),a.jsx(wa,{icon:Qn,label:t("system.bootTime","Boot Time"),value:Zf(c.system.boot_time,v)})]})})]})}function Hrt(){const t=Do(),[e]=PP(),{t:n}=Rt(),{login:r,loginWithToken:i}=wr(),{showToast:s}=bn(),{mode:o}=wg(),[l,c]=w.useState(""),[d,u]=w.useState(""),[m,p]=w.useState(!1),[f,x]=w.useState(""),[v,g]=w.useState("credentials"),[b,_]=w.useState(""),[C,P]=w.useState([]),[N,A]=w.useState("totp"),[T,F]=w.useState(""),[k,D]=w.useState(!1),H=w.useRef(null),[z,X]=w.useState(""),[L,ne]=w.useState(""),[ie,ee]=w.useState(""),{data:ue}=Qe({queryKey:["advancedAuthStatus"],queryFn:()=>me.getAdvancedAuthStatus()}),{data:le}=Qe({queryKey:["oidcProviders"],queryFn:()=>me.getOIDCProviders()});w.useEffect(()=>{const O=window.location.hash,K=O.startsWith("#reset_token=")?O.slice(13):null;K&&(X(K),g("reset-password"),t("/login",{replace:!0}))},[]),w.useEffect(()=>{const O=window.location.hash,K=O.startsWith("#oidc_token=")?O.slice(12):null,B=e.get("oidc_error");if(B){const I={oidc_provider_error:n("login.oidcErrors.providerError"),missing_parameters:n("login.oidcErrors.missingParameters"),invalid_state:n("login.oidcErrors.invalidState"),state_expired:n("login.oidcErrors.stateExpired"),provider_not_found:n("login.oidcErrors.providerNotFound"),discovery_failed:n("login.oidcErrors.discoveryFailed"),invalid_discovery_document:n("login.oidcErrors.invalidDiscovery"),token_exchange_network_error:n("login.oidcErrors.networkError"),token_exchange_bad_response:n("login.oidcErrors.badResponse"),no_id_token:n("login.oidcErrors.noIdToken"),token_validation_failed:n("login.oidcErrors.validationFailed"),nonce_mismatch:n("login.oidcErrors.nonceMismatch"),missing_sub_claim:n("login.oidcErrors.missingSubClaim"),no_linked_account:n("login.oidcErrors.noLinkedAccount"),account_inactive:n("login.oidcErrors.accountInactive"),user_resolution_failed:n("login.oidcErrors.userResolutionFailed"),internal_error:n("login.oidcErrors.internalError")}[B]??(B.startsWith("token_exchange_")?n("login.oidcErrors.tokenExchangeFailed"):n("login.oidcLoginFailed"));s(I,"error"),t("/login",{replace:!0});return}K&&me.exchangeOIDCToken(K).then(he=>{if(he.requires_2fa&&he.pre_auth_token){_(he.pre_auth_token);const I=he.two_fa_methods??[];P(I),I.includes("totp")?A("totp"):I.includes("email")?A("email"):A("backup"),g("2fa"),t("/login",{replace:!0})}else he.access_token&&he.user&&(i(he.access_token,he.user),s(n("login.loginSuccess")),t("/",{replace:!0}))}).catch(he=>{s(he.message||n("login.oidcLoginFailed"),"error"),t("/login",{replace:!0})})},[e]);const oe=it({mutationFn:()=>r(l,d),onSuccess:O=>{if(O.requires_2fa&&O.pre_auth_token){_(O.pre_auth_token);const K=O.two_fa_methods??[];P(K),K.includes("totp")?A("totp"):K.includes("email")?A("email"):A("backup"),g("2fa")}else O.access_token&&O.user&&(s(n("login.loginSuccess")),t("/"))},onError:O=>{s(O.message||n("login.loginFailed"),"error")}}),W=it({mutationFn:O=>me.forgotPassword({email:O}),onSuccess:O=>{s(O.message,"success"),p(!1),x("")},onError:O=>{s(O.message,"error")}}),re=it({mutationFn:()=>me.forgotPasswordConfirm(z,L),onSuccess:O=>{s(O.message,"success"),g("credentials"),X(""),ne(""),ee("")},onError:O=>{s(O.message||n("login.resetPassword.resetFailed"),"error")}}),ce=it({mutationFn:()=>me.sendEmailOTP(b),onSuccess:O=>{D(!0),O.pre_auth_token&&_(O.pre_auth_token),s(O.message,"success")},onError:O=>{s(O.message||n("login.twoFA.sendCodeFailed"),"error")}}),xe=it({mutationFn:()=>me.verify2FA({pre_auth_token:b,code:T,method:N}),onSuccess:O=>{O.access_token&&O.user&&(i(O.access_token,O.user),s(n("login.loginSuccess")),t("/"))},onError:O=>{s(O.message||n("login.twoFA.invalidCode"),"error"),F("")}}),Ne=it({mutationFn:O=>me.getOIDCAuthorizeUrl(O),onSuccess:O=>{window.location.href=O.auth_url},onError:O=>{s(O.message||n("login.oidcLoginFailed"),"error")}}),$=O=>{if(O.preventDefault(),!l||!d){s(n("login.enterCredentials"),"error");return}oe.mutate()},Y=O=>{if(O.preventDefault(),!T.trim()){s(n("login.twoFA.enterCode"),"error");return}xe.mutate()},E=O=>{if(O.preventDefault(),!f){s(n("login.enterEmail"),"error");return}W.mutate(f)},j=O=>{A(O),F(""),D(!1),setTimeout(()=>H.current?.focus(),0)};if(v==="reset-password"){const O=K=>{if(K.preventDefault(),L!==ie){s(n("login.resetPassword.passwordsDoNotMatch"),"error");return}if(L.length<8){s(n("login.resetPassword.passwordTooShort"),"error");return}re.mutate()};return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:a.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:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-4",children:a.jsx("div",{className:"w-14 h-14 rounded-full bg-bambu-green/20 flex items-center justify-center",children:a.jsx(Ws,{className:"w-7 h-7 text-bambu-green"})})}),a.jsx("h2",{className:"text-2xl font-bold text-white",children:n("login.resetPassword.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.resetPassword.subtitle")})]}),a.jsxs("form",{onSubmit:O,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"new-password",className:"block text-sm font-medium text-white mb-2",children:n("login.resetPassword.newPassword")}),a.jsx("input",{id:"new-password",type:"password",required:!0,value:L,onChange:K=>ne(K.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:n("login.resetPassword.newPasswordPlaceholder"),autoFocus:!0,autoComplete:"new-password",minLength:8})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:n("login.resetPassword.confirmPassword")}),a.jsx("input",{id:"confirm-password",type:"password",required:!0,value:ie,onChange:K=>ee(K.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:n("login.resetPassword.confirmPasswordPlaceholder"),autoComplete:"new-password"})]}),a.jsx("button",{type:"submit",disabled:re.isPending||!L||!ie,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",children:re.isPending?n("login.resetPassword.saving"):n("login.resetPassword.submit")})]}),a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",onClick:()=>{g("credentials"),X(""),ne(""),ee("")},className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.resetPassword.backToLogin")})})]})})}return v==="2fa"?a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:a.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:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-4",children:a.jsx("div",{className:"w-14 h-14 rounded-full bg-bambu-green/20 flex items-center justify-center",children:a.jsx(Du,{className:"w-7 h-7 text-bambu-green"})})}),a.jsx("h2",{className:"text-2xl font-bold text-white",children:n("login.twoFA.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.twoFA.subtitle")})]}),C.length>1&&a.jsxs("div",{className:"flex gap-2",children:[C.includes("totp")&&a.jsxs("button",{type:"button",onClick:()=>j("totp"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${N==="totp"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[a.jsx(Y3,{className:"w-4 h-4"}),n("login.twoFA.methodAuthenticator")]}),C.includes("email")&&a.jsxs("button",{type:"button",onClick:()=>j("email"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${N==="email"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[a.jsx(am,{className:"w-4 h-4"}),n("login.twoFA.methodEmail")]}),C.includes("backup")&&a.jsxs("button",{type:"button",onClick:()=>j("backup"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${N==="backup"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[a.jsx(Ws,{className:"w-4 h-4"}),n("login.twoFA.methodBackup")]})]}),a.jsxs("form",{onSubmit:Y,className:"space-y-4",children:[N==="totp"&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n("login.twoFA.instructionsTotp")}),N==="email"&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n(k?"login.twoFA.instructionsEmail":"login.twoFA.instructionsEmailNotSent")}),!k&&a.jsx(Fe,{type:"button",variant:"secondary",className:"w-full",onClick:()=>ce.mutate(),disabled:ce.isPending,children:ce.isPending?n("login.twoFA.sendingCode"):n("login.twoFA.sendCodeButton")}),k&&a.jsx("button",{type:"button",onClick:()=>{D(!1),ce.mutate()},className:"text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.twoFA.resendCode")})]}),N==="backup"&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n("login.twoFA.instructionsBackup")}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"twofa-code",className:"block text-sm font-medium text-white mb-2",children:n(N==="backup"?"login.twoFA.backupCodeLabel":"login.twoFA.codeLabel")}),a.jsx("input",{ref:H,id:"twofa-code",type:"text",inputMode:N==="backup"?"text":"numeric",autoComplete:"one-time-code",value:T,onChange:O=>F(O.target.value.trim()),disabled:N==="email"&&!k,className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-center tracking-widest text-xl font-mono focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-40",placeholder:n(N==="backup"?"login.twoFA.backupCodePlaceholder":"login.twoFA.codePlaceholder"),maxLength:N==="backup"?8:6,autoFocus:!0})]}),a.jsx("button",{type:"submit",disabled:xe.isPending||!T.trim()||N==="email"&&!k,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",children:xe.isPending?n("login.twoFA.verifyingButton"):n("login.twoFA.verifyButton")})]}),a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",onClick:()=>{g("credentials"),_(""),F(""),D(!1)},className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.twoFA.backToLogin")})})]})}):a.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[a.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:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:o==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:n("login.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:$,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:ue?.advanced_auth_enabled?n("login.usernameOrEmail"):n("login.username")}),a.jsx("input",{id:"username",type:"text",required:!0,value:l,onChange:O=>c(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:ue?.advanced_auth_enabled?n("login.usernameOrEmailPlaceholder"):n("login.usernamePlaceholder"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:n("login.password")||"Password"}),a.jsx("input",{id:"password",type:"password",required:!0,value:d,onChange:O=>u(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:n("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:oe.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:oe.isPending?n("login.signingIn"):n("login.signIn")})}),a.jsx("div",{className:"text-center",children:a.jsx("button",{type:"button",onClick:()=>p(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.forgotPassword")})})]}),le&&le.length>0&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("div",{className:"w-full border-t border-bambu-dark-tertiary"})}),a.jsx("div",{className:"relative flex justify-center text-sm",children:a.jsx("span",{className:"px-2 bg-bambu-dark-secondary text-bambu-gray",children:n("login.twoFA.orContinueWith")})})]}),a.jsx("div",{className:"space-y-2",children:le.map(O=>a.jsxs("button",{type:"button",onClick:()=>Ne.mutate(O.id),disabled:Ne.isPending,className:"w-full flex items-center justify-center gap-3 py-3 px-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary hover:border-bambu-green/50 rounded-lg text-white font-medium transition-colors disabled:opacity-50",children:[O.icon_url?a.jsx("img",{src:O.icon_url,alt:"",className:"w-5 h-5 object-contain"}):a.jsx(Du,{className:"w-5 h-5 text-bambu-green"}),n("login.twoFA.signInWith",{provider:O.name})]},O.id))})]})]}),m&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>p(!1),children:a.jsxs(At,{className:"w-full max-w-md",onClick:O=>O.stopPropagation(),children:[a.jsx(wn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(am,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("login.forgotPasswordTitle")})]}),a.jsx(Fe,{variant:"ghost",size:"sm",onClick:()=>{p(!1),x("")},children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsx(Mt,{children:ue?.advanced_auth_enabled?a.jsxs("form",{onSubmit:E,className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray text-sm",children:n("login.forgotPasswordEmailMessage")}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:n("login.emailAddress")}),a.jsx("input",{id:"forgot-email",type:"email",required:!0,value:f,onChange:O=>x(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:n("login.emailPlaceholder")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Fe,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{p(!1),x("")},children:n("login.cancel")}),a.jsx(Fe,{type:"submit",className:"flex-1",disabled:W.isPending,children:W.isPending?n("login.sending"):n("login.sendResetEmail")})]})]}):a.jsxs("div",{className:"space-y-4",children:[a.jsx("p",{className:"text-bambu-gray",children:n("login.forgotPasswordMessage")}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[a.jsx("p",{className:"text-sm text-white font-medium",children:n("login.howToReset")}),a.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[a.jsx("li",{children:n("login.resetStep1")}),a.jsx("li",{children:n("login.resetStep2")}),a.jsx("li",{children:n("login.resetStep3")}),a.jsx("li",{children:n("login.resetStep4")})]})]}),a.jsx(Fe,{variant:"secondary",className:"w-full",onClick:()=>p(!1),children:n("login.gotIt")})]})})]})})]})}function qrt(){const t=Do(),{t:e}=Rt(),{showToast:n}=bn(),{mode:r}=wg(),{refreshAuth:i}=wr(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[d,u]=w.useState(""),[m,p]=w.useState(""),f=it({mutationFn:()=>me.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?d:void 0}),onSuccess:async v=>{await i(),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||d)){if(!l||!d){n(e("setup.toast.enterBothCredentials"),"error");return}if(d!==m){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(d.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}f.mutate()};return a.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:a.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:[a.jsxs("div",{className:"text-center",children:[a.jsx("div",{className:"flex items-center justify-center mb-6",children:a.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),a.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),a.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[a.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"}),a.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&a.jsxs("div",{className:"space-y-4 mt-4",children:[a.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(fs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),a.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.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"})]}),a.jsxs("div",{children:[a.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",a.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),a.jsx("input",{id:"admin-password",type:"password",value:d,onChange:v=>u(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"})]}),d&&a.jsxs("div",{children:[a.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),a.jsx("input",{id:"confirm-password",type:"password",value:m,onChange:v=>p(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"})]})]})]}),a.jsx("div",{children:a.jsx("button",{type:"submit",disabled:f.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:f.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function $rt(){const{t}=Rt(),{user:e}=wr(),{showToast:n}=bn(),r=sn(),i=Do(),[s,o]=w.useState(!0),[l,c]=w.useState(!0),[d,u]=w.useState(!0),[m,p]=w.useState(!0),[f,x]=w.useState(!1),{data:v,isLoading:g}=Qe({queryKey:["advancedAuthStatus"],queryFn:me.getAdvancedAuthStatus,staleTime:300*1e3}),{data:b,isLoading:_}=Qe({queryKey:["settings"],queryFn:me.getSettings,staleTime:300*1e3}),{data:C,isLoading:P}=Qe({queryKey:["user-email-preferences"],queryFn:()=>me.getUserEmailPreferences()});w.useEffect(()=>{(v&&!v.advanced_auth_enabled||b&&!b.user_notifications_enabled)&&i("/settings",{replace:!0})},[v,b,i]),w.useEffect(()=>{C&&(o(C.notify_print_start),c(C.notify_print_complete),u(C.notify_print_failed),p(C.notify_print_stopped),x(!1))},[C]);const N=it({mutationFn:()=>me.updateUserEmailPreferences({notify_print_start:s,notify_print_complete:l,notify_print_failed:d,notify_print_stopped:m}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-email-preferences"]}),x(!1),n(t("notifications.userEmail.saveSuccess"),"success")},onError:T=>{n(T.message||t("notifications.userEmail.saveError"),"error")}}),A=(T,F)=>{T(!F),x(!0)};return P||g||_?a.jsx("div",{className:"flex items-center justify-center h-64",children:a.jsx(dt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"p-4 md:p-6 max-w-2xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsx(Uh,{className:"w-7 h-7 text-bambu-green"}),a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("notifications.userEmail.title")})]}),a.jsx(At,{className:"mb-6 border-blue-500/30 bg-blue-500/5",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(am,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:t("notifications.userEmail.emailNotifications")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.emailNotificationsDesc")}),e?.email?a.jsxs("p",{className:"text-sm text-blue-400 mt-2",children:[t("notifications.userEmail.sendingTo"),": ",a.jsx("strong",{children:e.email})]}):a.jsx("p",{className:"text-sm text-yellow-400 mt-2",children:t("notifications.userEmail.noEmailWarning")})]})]})})}),a.jsxs(At,{className:"mb-6",children:[a.jsxs(wn,{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("notifications.userEmail.printJobNotifications")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.printJobNotificationsDesc")})]}),a.jsxs(Mt,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${s?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(nl,{className:`w-5 h-5 ${s?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStarts")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStartsDesc")})]})]}),a.jsx("button",{onClick:()=>A(o,s),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${s?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":s,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(nl,{className:`w-5 h-5 ${l?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobFinishes")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobFinishesDesc")})]})]}),a.jsx("button",{onClick:()=>A(c,l),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":l,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${d?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(nl,{className:`w-5 h-5 ${d?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printErrors")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printErrorsDesc")})]})]}),a.jsx("button",{onClick:()=>A(u,d),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${d?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":d,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${d?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${m?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(nl,{className:`w-5 h-5 ${m?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStops")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStopsDesc")})]})]}),a.jsx("button",{onClick:()=>A(p,m),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${m?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,role:"switch","aria-checked":m,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${m?"translate-x-6":"translate-x-1"}`})})]})]})]}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Fe,{onClick:()=>N.mutate(),disabled:!f||N.isPending||!e?.email,children:N.isPending?a.jsxs(a.Fragment,{children:[a.jsx(dt,{className:"w-4 h-4 animate-spin"}),t("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(gs,{className:"w-4 h-4"}),t("common.save")]})})})]})}function Vrt(){const t=w.useRef(null),e=w.useRef(null),n=sn(),[r,i]=w.useState(!1),s=w.useRef(new Map),{showToast:o}=bn(),{t:l}=Rt(),c=w.useRef(new Set),d=w.useRef(null),u=w.useRef(new Map),m=w.useRef(null),p=w.useRef([]),f=w.useRef(!1),x=w.useRef(()=>{}),v=w.useCallback(()=>{if(f.current||p.current.length===0)return;f.current=!0;const N=()=>{const A=p.current.shift();A?requestAnimationFrame(()=>{x.current(A),p.current.length>0?setTimeout(N,16):f.current=!1}):f.current=!1};N()},[]),g=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const A=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,T=new WebSocket(A);let F=null;T.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),F=window.setInterval(()=>{T.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"ping"}))},3e4)},T.onmessage=k=>{try{const D=JSON.parse(k.data);D.type==="printer_status"&&D.printer_id!==void 0&&D.data?x.current(D):(p.current.push(D),v())}catch{}},T.onclose=k=>{console.log("[WebSocket] Closed",k.code,k.reason),F&&(clearInterval(F),F=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{g()},3e3)},T.onerror=k=>{console.error("[WebSocket] Error",k),T.close()},t.current=T},[v]),b=w.useCallback((N,A)=>{const T=u.current.get(N)||{};u.current.set(N,{...T,...A}),m.current||(m.current=window.setTimeout(()=>{const F=new Map(u.current);u.current.clear(),m.current=null,requestAnimationFrame(()=>{F.forEach((k,D)=>{n.setQueryData(["printerStatus",D],H=>{const z={...H,...k};return z.wifi_signal==null&&H?.wifi_signal!=null&&(z.wifi_signal=H.wifi_signal),z})})})},100))},[n]),_=w.useCallback(N=>{c.current.add(N),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{const A=Array.from(c.current);c.current.clear(),d.current=null;let T=0;A.forEach(F=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[F]})})},T),T+=500})},3e3)},[n]),C=w.useCallback(N=>{switch(N.type){case"printer_status":N.printer_id!==void 0&&N.data&&b(N.printer_id,N.data);break;case"print_start":N.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",N.printer_id]});break;case"missing_spool_assignment":{if(N.printer_id===void 0||!Array.isArray(N.missing_slots))break;const A=N.missing_slots.map(D=>D&&typeof D.slot=="string"?D.slot:"Unknown").filter(D=>D.length>0);if(A.length===0){s.current.delete(N.printer_id);break}const T=A.join("|");if(s.current.get(N.printer_id)===T)break;s.current.set(N.printer_id,T);const F=N.printer_name||`Printer ${N.printer_id}`,k=l("printers.toast.missingSpoolAssignment",{printer:F,slots:A.join(", ")});o(k,"warning");break}case"print_complete":_("archives"),_("archiveStats");break;case"archive_created":_("archives"),_("archiveStats");break;case"archive_updated":_("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:N.printer_id,printer_name:N.printer_name,message:N.message}}));break;case"inventory_changed":_("inventory-spools");break;case"spool_assignment_changed":_("spool-assignments"),_("slotPresets");break;case"spool_auto_assigned":_("inventory-spools"),_("spool-assignments");break;case"spool_usage_logged":_("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:N.printer_id,ams_id:N.ams_id,tray_id:N.tray_id,tag_uid:N.tag_uid,tray_uuid:N.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:N.data||{}}));break;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:N}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:N})),_("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:N}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:N}));break;case"spoolbuddy_tag_written":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-written",{detail:N})),_("inventory-spools");break;case"spoolbuddy_tag_write_failed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-write-failed",{detail:N}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:N})),_("spoolbuddy-devices"),_("spoolbuddy-update-check");break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:N})),_("spoolbuddy-devices");break;case"spoolbuddy_update":_("spoolbuddy-devices"),_("spoolbuddy-update-check");break}},[n,_,b,o,l]);w.useEffect(()=>{x.current=C},[C]),w.useEffect(()=>(g(),()=>{e.current&&clearTimeout(e.current),d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),t.current&&t.current.close()}),[g]);const P=w.useCallback(N=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(N))},[]);return{isConnected:r,sendMessage:P}}function Grt(){const{authEnabled:t}=wr(),e=sn(),n=w.useRef(!1),{data:r}=Qe({queryKey:["camera-stream-token"],queryFn:()=>me.getCameraStreamToken(),enabled:t,staleTime:3e3*1e3,refetchInterval:3e3*1e3});w.useEffect(()=>(kH(r?.token??null),()=>kH(null)),[r?.token]),w.useEffect(()=>{if(!t)return;const i=s=>{const o=s.target;if(!(o instanceof HTMLImageElement||o instanceof HTMLVideoElement))return;const l=o.src||"",c=oye();!c||!l.includes(`token=${encodeURIComponent(c)}`)||n.current||(n.current=!0,e.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{n.current=!1},5e3))};return document.addEventListener("error",i,!0),()=>document.removeEventListener("error",i,!0)},[t,e])}function Wrt({children:t}){const{authEnabled:e,user:n,loading:r}=wr(),i=!r&&(!e||n!==null),{data:s}=Qe({queryKey:["color-catalog-map"],queryFn:async()=>(await me.getColorNameMap()).colors,staleTime:1/0,gcTime:1/0,retry:2,enabled:i});return w.useEffect(()=>{s&&gye(s)},[s]),a.jsx(a.Fragment,{children:t})}function Krt({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:r}=Rt(),[i,s]=w.useState(new Date),{data:o=[]}=Qe({queryKey:["printers"],queryFn:()=>me.getPrinters()}),l=fp({queries:o.map(u=>({queryKey:["printerStatus",u.id],queryFn:()=>me.getPrinterStatus(u.id),refetchInterval:1e4}))}),c=w.useMemo(()=>o.filter((u,m)=>l[m]?.data?.connected),[o,l]);w.useEffect(()=>{const u=c.some(m=>m.id===t);(!t||!u)&&c.length>0&&e(c[0].id)},[c,t,e]);const{data:d}=Qe({queryKey:["settings"],queryFn:me.getSettings});return w.useEffect(()=>{const u=setInterval(()=>s(new Date),1e3);return()=>clearInterval(u)},[]),a.jsxs("div",{className:"h-12 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-3 gap-4 shrink-0",children:[a.jsx("div",{className:"flex items-center shrink-0",children:a.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",width:113,height:28,className:"h-7 w-auto"})}),a.jsx("div",{className:"flex-1 flex justify-center",children:a.jsx("select",{value:t??"",onChange:u=>e(Number(u.target.value)),className:"bg-bambu-dark text-white text-base px-4 py-2 rounded border border-bambu-dark-tertiary focus:outline-none focus:border-bambu-green min-w-[180px]",children:c.length===0?a.jsx("option",{value:"",children:r("spoolbuddy.status.noPrinters","No printers online")}):c.map(u=>a.jsx("option",{value:u.id,children:u.name},u.id))})}),a.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[a.jsx("div",{className:"flex items-center",title:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline"),children:n?a.jsx("div",{className:"flex items-end gap-0.5 h-4",children:[1,2,3,4].map(u=>a.jsx("div",{className:`w-1 rounded-sm ${u<=4?"bg-white":"bg-bambu-dark-tertiary"}`,style:{height:`${u*4}px`}},u))}):a.jsx(Md,{className:"w-5 h-5 text-red-400"})}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${n?"bg-bambu-green shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-bambu-gray"}`}),a.jsx("span",{className:"text-sm text-white/50",children:n?r("spoolbuddy.status.backend","Backend"):r("spoolbuddy.status.offline","Offline")})]}),a.jsx("span",{className:"text-white/50 text-base font-mono min-w-[50px] text-right",children:YQ(i,d?.time_format||"system")})]})]})}const Xrt=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})})},{to:"/spoolbuddy/ams",labelKey:"spoolbuddy.nav.ams",fallback:"AMS",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})},{to:"/spoolbuddy/write-tag",labelKey:"spoolbuddy.nav.writeTag",fallback:"Write",icon:a.jsxs("svg",{className:"w-6 h-6",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})},{to:"/spoolbuddy/inventory",labelKey:"spoolbuddy.nav.inventory",fallback:"Inventory",icon:a.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})},{to:"/spoolbuddy/settings",labelKey:"spoolbuddy.nav.settings",fallback:"Settings",icon:a.jsxs("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function Yrt(){const{t}=Rt();return a.jsx("nav",{className:"h-14 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-stretch shrink-0",children:Xrt.map(e=>a.jsxs(nx,{to:e.to,end:e.to==="/spoolbuddy",className:({isActive:n})=>`flex-1 flex flex-col items-center justify-center gap-1 transition-colors ${n?"text-bambu-green bg-bambu-dark":"text-white/50 hover:text-white/70 hover:bg-bambu-dark-tertiary"}`,children:[e.icon,a.jsx("span",{className:"text-xs font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}function Qrt({alert:t}){const{t:e}=Rt(),n=t?t.type==="error"?"bg-red-500":t.type==="warning"?"bg-amber-500":"bg-bambu-green":"bg-bambu-green",r=t?t.type==="error"?"border-red-500":t.type==="warning"?"border-amber-500":"border-bambu-dark-tertiary":"border-bambu-dark-tertiary";return a.jsxs("div",{className:`h-9 bg-bambu-dark-secondary border-t-2 ${r} flex items-center px-3 gap-3 shrink-0`,children:[a.jsx("div",{className:`w-3.5 h-3.5 rounded-full ${n}`}),a.jsx("div",{className:"flex-1 text-sm text-white/50 truncate",children:t?a.jsx("span",{children:t.message}):a.jsx("span",{className:"text-bambu-green",children:e("spoolbuddy.status.systemReady","System Ready")})})]})}function Zrt({isOpen:t,onClose:e,deviceId:n,deviceOnline:r}){const{t:i}=Rt(),[s,o]=w.useState(null),[l,c]=w.useState(!1),[d,u]=w.useState(new Map),{data:m=[]}=Qe({queryKey:["printers"],queryFn:()=>me.getPrinters(),enabled:t}),{data:p=[]}=Qe({queryKey:["smart-plugs"],queryFn:()=>me.getSmartPlugs(),enabled:t}),f=m.map(_=>{const C=p.find(N=>N.printer_id===_.id&&N.plug_type!=="mqtt"&&N.enabled);if(!C)return null;const P=d.get(C.id);return{plug:C,printer:_,status:P?{state:P.state,reachable:!0,device_name:null,energy:null}:null,loading:P?.loading??!1}}).filter(Boolean);w.useEffect(()=>{if(!t||p.length===0)return;p.filter(C=>C.printer_id!==null&&C.plug_type!=="mqtt"&&C.enabled).forEach(async C=>{try{const P=await me.getSmartPlugStatus(C.id);u(N=>{const A=new Map(N);return A.set(C.id,{loading:!1,state:P.state}),A})}catch{u(P=>{const N=new Map(P);return N.set(C.id,{loading:!1,state:null}),N})}})},[t,p]),w.useEffect(()=>{t||(o(null),c(!1))},[t]);const x=w.useCallback(async _=>{u(C=>{const P=new Map(C),N=P.get(_.id);return P.set(_.id,{loading:!0,state:N?.state??null}),P});try{await me.controlSmartPlug(_.id,"toggle");const C=await me.getSmartPlugStatus(_.id);u(P=>{const N=new Map(P);return N.set(_.id,{loading:!1,state:C.state}),N})}catch{u(C=>{const P=new Map(C),N=P.get(_.id);return P.set(_.id,{loading:!1,state:N?.state??null}),P})}},[]),v=w.useCallback(async _=>{if(n){c(!0);try{await Ur.systemCommand(n,_),setTimeout(()=>e(),500)}catch{c(!1)}}},[n,e]),g=w.useCallback(()=>{s&&(s.type==="system"?v(s.command):x(s.plug),o(null))},[s,v,x]);if(!t)return null;const b=_=>_==="ON"||_==="on";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-40 bg-black/50",onPointerDown:e}),a.jsxs("div",{className:"fixed top-0 left-0 right-0 z-50 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-b-2xl shadow-2xl animate-slide-down",children:[a.jsx("div",{className:"flex justify-center pt-2 pb-1",children:a.jsx("div",{className:"w-10 h-1 rounded-full bg-zinc-600"})}),a.jsxs("div",{className:"px-4 pb-4 max-h-[80vh] overflow-y-auto",children:[f.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.printerPower","Printer Power")}),a.jsx("div",{className:"space-y-1",children:f.map(({plug:_,printer:C,loading:P})=>{const N=d.get(_.id),A=b(N?.state??null);return a.jsxs("button",{onClick:()=>o({type:"plug",plug:_,printer:C,currentState:N?.state??null}),disabled:P,className:"w-full flex items-center gap-2 px-3 py-1.5 rounded-lg bg-zinc-800/60 hover:bg-zinc-700/60 transition-colors min-h-[36px]",children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${A?"bg-green-500":"bg-zinc-600"}`}),P&&a.jsx(dt,{className:"w-3 h-3 animate-spin text-zinc-400 shrink-0"}),a.jsx("span",{className:"flex-1 text-sm text-zinc-200 text-left truncate",children:C.name}),a.jsx("span",{className:`text-xs font-medium ${A?"text-green-400":"text-zinc-500"}`,children:N?.state??"—"})]},_.id)})})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.systemControls","System")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsx(wk,{icon:a.jsx(H0,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartDaemon","Restart Daemon"),onClick:()=>o({type:"system",command:"restart_daemon"}),disabled:!n||!r||l}),a.jsx(wk,{icon:a.jsx(wO,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartBrowser","Restart Browser"),onClick:()=>o({type:"system",command:"restart_browser"}),disabled:!n||!r||l}),a.jsx(wk,{icon:a.jsx(H0,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.reboot","Reboot"),onClick:()=>o({type:"system",command:"reboot"}),disabled:!n||!r||l,variant:"warning"}),a.jsx(wk,{icon:a.jsx(Uw,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.shutdown","Shutdown"),onClick:()=>o({type:"system",command:"shutdown"}),disabled:!n||!r||l,variant:"danger"})]})]}),a.jsx("div",{className:"flex justify-center mt-3",children:a.jsxs("div",{className:"flex items-center gap-1 text-xs text-zinc-600",children:[a.jsx(Un,{className:"w-3 h-3"}),a.jsx("span",{children:i("spoolbuddy.quickMenu.swipeToClose","Swipe down to close")})]})})]})]}),s&&a.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/60",children:a.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-5 mx-4 max-w-sm w-full border border-zinc-700",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-2",children:i("spoolbuddy.quickMenu.confirmTitle","Confirm")}),a.jsx("p",{className:"text-sm text-zinc-400 mb-5",children:s.type==="plug"?b(s.currentState)?i("spoolbuddy.quickMenu.confirmPlugOff","Turn off {{name}}?",{name:s.printer.name}):i("spoolbuddy.quickMenu.confirmPlugOn","Turn on {{name}}?",{name:s.printer.name}):s.command==="shutdown"?i("spoolbuddy.quickMenu.confirmShutdown","Are you sure you want to shut down the SpoolBuddy? You will need physical access to turn it back on."):s.command==="reboot"?i("spoolbuddy.quickMenu.confirmReboot","Are you sure you want to reboot the SpoolBuddy?"):s.command==="restart_daemon"?i("spoolbuddy.quickMenu.confirmRestartDaemon","Restart the SpoolBuddy daemon? NFC and scale will be temporarily unavailable."):i("spoolbuddy.quickMenu.confirmRestartBrowser","Restart the kiosk browser? The display will briefly go blank.")}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:()=>o(null),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:i("common.cancel","Cancel")}),a.jsx("button",{onClick:g,disabled:l,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium text-white transition-colors min-h-[44px] ${s.type==="plug"?b(s.currentState)?"bg-red-600 hover:bg-red-700":"bg-green-600 hover:bg-green-700":s.command==="shutdown"?"bg-red-600 hover:bg-red-700":s.command==="reboot"?"bg-amber-600 hover:bg-amber-700":"bg-blue-600 hover:bg-blue-700"} disabled:opacity-50`,children:l?a.jsx(dt,{className:"w-4 h-4 animate-spin mx-auto"}):s.type==="plug"?b(s.currentState)?i("spoolbuddy.quickMenu.turnOff","Turn Off"):i("spoolbuddy.quickMenu.turnOn","Turn On"):i("spoolbuddy.quickMenu.confirm","Confirm")})]})]})})]})}function wk({icon:t,label:e,onClick:n,disabled:r,variant:i="default"}){const s={default:"bg-zinc-800/60 hover:bg-zinc-700/60 text-zinc-300",warning:"bg-amber-900/30 hover:bg-amber-900/50 text-amber-400",danger:"bg-red-900/30 hover:bg-red-900/50 text-red-400"};return a.jsxs("button",{onClick:n,disabled:r,className:`flex items-center gap-2.5 p-3 rounded-xl transition-colors min-h-[48px] disabled:opacity-40 ${s[i]}`,children:[t,a.jsx("span",{className:"text-sm font-medium",children:e})]})}const Jrt={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,deviceOnline:!1,deviceId:null};function eat(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.weight,weightStable:e.stable,rawAdc:e.rawAdc,deviceId:e.deviceId,deviceOnline:!0};case"TAG_MATCHED":return{...t,matchedSpool:e.spool,unknownTagUid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0,deviceId:e.deviceId};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null,weightStable:!1,rawAdc:null};default:return t}}function tat(){const[t,e]=w.useReducer(eat,Jrt),n=w.useCallback(u=>{const m=u.detail;e({type:"WEIGHT_UPDATE",weight:m.weight_grams??m.data?.weight_grams,stable:m.stable??m.data?.stable??!1,rawAdc:m.raw_adc??m.data?.raw_adc??null,deviceId:m.device_id??m.data?.device_id??""})},[]),r=w.useCallback(u=>{const m=u.detail,p=m.spool??m.data?.spool;p&&e({type:"TAG_MATCHED",spool:{id:p.id,tag_uid:m.tag_uid??m.data?.tag_uid??"",material:p.material??"",subtype:p.subtype??null,color_name:p.color_name??null,rgba:p.rgba??null,brand:p.brand??null,label_weight:p.label_weight??0,core_weight:p.core_weight??0,weight_used:p.weight_used??0},deviceId:m.device_id??m.data?.device_id??""})},[]),i=w.useCallback(u=>{const m=u.detail;e({type:"UNKNOWN_TAG",tagUid:m.tag_uid??m.data?.tag_uid??"",deviceId:m.device_id??m.data?.device_id??""})},[]),s=w.useCallback(u=>{const m=u.detail;e({type:"TAG_REMOVED",deviceId:m.device_id??m.data?.device_id??""})},[]),o=w.useCallback(u=>{const m=u.detail;e({type:"DEVICE_ONLINE",deviceId:m.device_id??m.data?.device_id??""})},[]),l=w.useCallback(u=>{const m=u.detail;e({type:"DEVICE_OFFLINE",deviceId:m.device_id??m.data?.device_id??""})},[]);w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",i),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-online",o),window.addEventListener("spoolbuddy-offline",l),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",i),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,r,i,s,o,l]);const c=t.matchedSpool?Math.max(0,t.matchedSpool.label_weight-t.matchedSpool.weight_used):null,d=t.weight!==null&&t.matchedSpool?Math.max(0,t.weight-t.matchedSpool.core_weight):null;return{...t,remainingWeight:c,netWeight:d}}var Qk={exports:{}};var nat=Qk.exports,_Y;function rat(){return _Y||(_Y=1,(function(t,e){(function(n,r){t.exports=r(xg())})(nat,(function(n){return(function(){var r={981:function(){typeof Element>"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function(l){if("Element"in l){var c="classList",d="prototype",u=l.Element[d],m=Object,p=String[d].trim||function(){return this.replace(/^\s+|\s+$/g,"")},f=Array[d].indexOf||function(P){for(var N=0,A=this.length;N<A;N++)if(N in this&&this[N]===P)return N;return-1},x=function(P,N){this.name=P,this.code=DOMException[P],this.message=N},v=function(P,N){if(N==="")throw new x("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(N))throw new x("INVALID_CHARACTER_ERR","The token must not contain space characters.");return f.call(P,N)},g=function(P){for(var N=p.call(P.getAttribute("class")||""),A=N?N.split(/\s+/):[],T=0,F=A.length;T<F;T++)this.push(A[T]);this._updateClassName=function(){P.setAttribute("class",this.toString())}},b=g[d]=[],_=function(){return new g(this)};if(x[d]=Error[d],b.item=function(P){return this[P]||null},b.contains=function(P){return~v(this,P+"")},b.add=function(){var P,N=arguments,A=0,T=N.length,F=!1;do~v(this,P=N[A]+"")||(this.push(P),F=!0);while(++A<T);F&&this._updateClassName()},b.remove=function(){var P,N,A=arguments,T=0,F=A.length,k=!1;do for(N=v(this,P=A[T]+"");~N;)this.splice(N,1),k=!0,N=v(this,P);while(++T<F);k&&this._updateClassName()},b.toggle=function(P,N){var A=this.contains(P),T=A?N!==!0&&"remove":N!==!1&&"add";return T&&this[T](P),N===!0||N===!1?N:!A},b.replace=function(P,N){var A=v(P+"");~A&&(this.splice(A,1,N),this._updateClassName())},b.toString=function(){return this.join(" ")},m.defineProperty){var C={get:_,enumerable:!0,configurable:!0};try{m.defineProperty(u,c,C)}catch(P){P.number!==void 0&&P.number!==-2146823252||(C.enumerable=!1,m.defineProperty(u,c,C))}}else m[d].__defineGetter__&&u.__defineGetter__(c,_)}})(self),(function(){var l=document.createElement("_");if(l.classList.add("c1","c2"),!l.classList.contains("c2")){var c=function(u){var m=DOMTokenList.prototype[u];DOMTokenList.prototype[u]=function(p){var f,x=arguments.length;for(f=0;f<x;f++)p=arguments[f],m.call(this,p)}};c("add"),c("remove")}if(l.classList.toggle("c3",!1),l.classList.contains("c3")){var d=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(u,m){return 1 in arguments&&!this.contains(u)==!m?m:d.call(this,u)}}"replace"in document.createElement("_").classList||(DOMTokenList.prototype.replace=function(u,m){var p=this.toString().split(" "),f=p.indexOf(u+"");~f&&(p=p.slice(f),this.remove.apply(this,p),this.add(m),this.add.apply(this,p.slice(1)))}),l=null})())},548:function(l){l.exports=(function(){var c={9306:function($,Y,E){var j=E(4901),O=E(6823),K=TypeError;$.exports=function(B){if(j(B))return B;throw new K(O(B)+" is not a function")}},5548:function($,Y,E){var j=E(3517),O=E(6823),K=TypeError;$.exports=function(B){if(j(B))return B;throw new K(O(B)+" is not a constructor")}},3506:function($,Y,E){var j=E(3925),O=String,K=TypeError;$.exports=function(B){if(j(B))return B;throw new K("Can't set "+O(B)+" as a prototype")}},6469:function($,Y,E){var j=E(8227),O=E(2360),K=E(4913).f,B=j("unscopables"),he=Array.prototype;he[B]===void 0&&K(he,B,{configurable:!0,value:O(null)}),$.exports=function(I){he[B][I]=!0}},7829:function($,Y,E){var j=E(8183).charAt;$.exports=function(O,K,B){return K+(B?j(O,K).length:1)}},8551:function($,Y,E){var j=E(34),O=String,K=TypeError;$.exports=function(B){if(j(B))return B;throw new K(O(B)+" is not an object")}},235:function($,Y,E){var j=E(9213).forEach,O=E(4598)("forEach");$.exports=O?[].forEach:function(K){return j(this,K,arguments.length>1?arguments[1]:void 0)}},7916:function($,Y,E){var j=E(6080),O=E(9565),K=E(8981),B=E(6319),he=E(4209),I=E(3517),V=E(6198),Q=E(4659),G=E(4527),J=E(81),se=E(851),fe=Array;$.exports=function(pe){var de=K(pe),U=I(this),R=arguments.length,ae=R>1?arguments[1]:void 0,_e=ae!==void 0;_e&&(ae=j(ae,R>2?arguments[2]:void 0));var Se,ye,Ae,ve,je,Re,Ee=se(de),Te=0;if(!Ee||this===fe&&he(Ee))for(Se=V(de),ye=U?new this(Se):fe(Se);Se>Te;Te++)Re=_e?ae(de[Te],Te):de[Te],Q(ye,Te,Re);else for(ye=U?new this:[],je=(ve=J(de,Ee)).next;!(Ae=O(je,ve)).done;Te++)Re=_e?B(ve,ae,[Ae.value,Te],!0):Ae.value,Q(ye,Te,Re);return G(ye,Te),ye}},9617:function($,Y,E){var j=E(5397),O=E(5610),K=E(6198),B=function(he){return function(I,V,Q){var G=j(I),J=K(G);if(J===0)return!he&&-1;var se,fe=O(Q,J);if(he&&V!=V){for(;J>fe;)if((se=G[fe++])!=se)return!0}else for(;J>fe;fe++)if((he||fe in G)&&G[fe]===V)return he||fe||0;return!he&&-1}};$.exports={includes:B(!0),indexOf:B(!1)}},9213:function($,Y,E){var j=E(6080),O=E(7055),K=E(8981),B=E(6198),he=E(1469),I=E(4659),V=function(Q){var G=Q===1,J=Q===2,se=Q===3,fe=Q===4,pe=Q===6,de=Q===7,U=Q===5||pe;return function(R,ae,_e){for(var Se,ye,Ae=K(R),ve=O(Ae),je=B(ve),Re=j(ae,_e),Ee=0,Te=0,Me=G?he(R,je):J||de?he(R,0):void 0;je>Ee;Ee++)if((U||Ee in ve)&&(ye=Re(Se=ve[Ee],Ee,Ae),Q))if(G)I(Me,Ee,ye);else if(ye)switch(Q){case 3:return!0;case 5:return Se;case 6:return Ee;case 2:I(Me,Te++,Se)}else switch(Q){case 4:return!1;case 7:I(Me,Te++,Se)}return pe?-1:se||fe?fe:Me}};$.exports={forEach:V(0),map:V(1),filter:V(2),some:V(3),every:V(4),find:V(5),findIndex:V(6),filterReject:V(7)}},597:function($,Y,E){var j=E(9039),O=E(8227),K=E(9519),B=O("species");$.exports=function(he){return K>=51||!j((function(){var I=[];return(I.constructor={})[B]=function(){return{foo:1}},I[he](Boolean).foo!==1}))}},4598:function($,Y,E){var j=E(9039);$.exports=function(O,K){var B=[][O];return!!B&&j((function(){B.call(null,K||function(){return 1},1)}))}},926:function($,Y,E){var j=E(9306),O=E(8981),K=E(7055),B=E(6198),he=TypeError,I="Reduce of empty array with no initial value",V=function(Q){return function(G,J,se,fe){var pe=O(G),de=K(pe),U=B(pe);if(j(J),U===0&&se<2)throw new he(I);var R=Q?U-1:0,ae=Q?-1:1;if(se<2)for(;;){if(R in de){fe=de[R],R+=ae;break}if(R+=ae,Q?R<0:U<=R)throw new he(I)}for(;Q?R>=0:U>R;R+=ae)R in de&&(fe=J(fe,de[R],R,pe));return fe}};$.exports={left:V(!1),right:V(!0)}},4527:function($,Y,E){var j=E(3724),O=E(4376),K=TypeError,B=Object.getOwnPropertyDescriptor,he=j&&!(function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(I){return I instanceof TypeError}})();$.exports=he?function(I,V){if(O(I)&&!B(I,"length").writable)throw new K("Cannot set read only .length");return I.length=V}:function(I,V){return I.length=V}},7680:function($,Y,E){var j=E(9504);$.exports=j([].slice)},4488:function($,Y,E){var j=E(7680),O=Math.floor,K=function(B,he){var I=B.length;if(I<8)for(var V,Q,G=1;G<I;){for(Q=G,V=B[G];Q&&he(B[Q-1],V)>0;)B[Q]=B[--Q];Q!==G++&&(B[Q]=V)}else for(var J=O(I/2),se=K(j(B,0,J),he),fe=K(j(B,J),he),pe=se.length,de=fe.length,U=0,R=0;U<pe||R<de;)B[U+R]=U<pe&&R<de?he(se[U],fe[R])<=0?se[U++]:fe[R++]:U<pe?se[U++]:fe[R++];return B};$.exports=K},7433:function($,Y,E){var j=E(4376),O=E(3517),K=E(34),B=E(8227)("species"),he=Array;$.exports=function(I){var V;return j(I)&&(V=I.constructor,(O(V)&&(V===he||j(V.prototype))||K(V)&&(V=V[B])===null)&&(V=void 0)),V===void 0?he:V}},1469:function($,Y,E){var j=E(7433);$.exports=function(O,K){return new(j(O))(K===0?0:K)}},6319:function($,Y,E){var j=E(8551),O=E(9539);$.exports=function(K,B,he,I){try{return I?B(j(he)[0],he[1]):B(he)}catch(V){O(K,"throw",V)}}},4428:function($,Y,E){var j=E(8227)("iterator"),O=!1;try{var K=0,B={next:function(){return{done:!!K++}},return:function(){O=!0}};B[j]=function(){return this},Array.from(B,(function(){throw 2}))}catch{}$.exports=function(he,I){try{if(!I&&!O)return!1}catch{return!1}var V=!1;try{var Q={};Q[j]=function(){return{next:function(){return{done:V=!0}}}},he(Q)}catch{}return V}},2195:function($,Y,E){var j=E(9504),O=j({}.toString),K=j("".slice);$.exports=function(B){return K(O(B),8,-1)}},6955:function($,Y,E){var j=E(2140),O=E(4901),K=E(2195),B=E(8227)("toStringTag"),he=Object,I=K((function(){return arguments})())==="Arguments";$.exports=j?K:function(V){var Q,G,J;return V===void 0?"Undefined":V===null?"Null":typeof(G=(function(se,fe){try{return se[fe]}catch{}})(Q=he(V),B))=="string"?G:I?K(Q):(J=K(Q))==="Object"&&O(Q.callee)?"Arguments":J}},7740:function($,Y,E){var j=E(9297),O=E(5031),K=E(7347),B=E(4913);$.exports=function(he,I,V){for(var Q=O(I),G=B.f,J=K.f,se=0;se<Q.length;se++){var fe=Q[se];j(he,fe)||V&&j(V,fe)||G(he,fe,J(I,fe))}}},1436:function($,Y,E){var j=E(8227)("match");$.exports=function(O){var K=/./;try{"/./"[O](K)}catch{try{return K[j]=!1,"/./"[O](K)}catch{}}return!1}},2211:function($,Y,E){var j=E(9039);$.exports=!j((function(){function O(){}return O.prototype.constructor=null,Object.getPrototypeOf(new O)!==O.prototype}))},2529:function($){$.exports=function(Y,E){return{value:Y,done:E}}},6699:function($,Y,E){var j=E(3724),O=E(4913),K=E(6980);$.exports=j?function(B,he,I){return O.f(B,he,K(1,I))}:function(B,he,I){return B[he]=I,B}},6980:function($){$.exports=function(Y,E){return{enumerable:!(1&Y),configurable:!(2&Y),writable:!(4&Y),value:E}}},4659:function($,Y,E){var j=E(3724),O=E(4913),K=E(6980);$.exports=function(B,he,I){j?O.f(B,he,K(0,I)):B[he]=I}},3640:function($,Y,E){var j=E(8551),O=E(4270),K=TypeError;$.exports=function(B){if(j(this),B==="string"||B==="default")B="string";else if(B!=="number")throw new K("Incorrect hint");return O(this,B)}},2106:function($,Y,E){var j=E(283),O=E(4913);$.exports=function(K,B,he){return he.get&&j(he.get,B,{getter:!0}),he.set&&j(he.set,B,{setter:!0}),O.f(K,B,he)}},6840:function($,Y,E){var j=E(4901),O=E(4913),K=E(283),B=E(9433);$.exports=function(he,I,V,Q){Q||(Q={});var G=Q.enumerable,J=Q.name!==void 0?Q.name:I;if(j(V)&&K(V,J,Q),Q.global)G?he[I]=V:B(I,V);else{try{Q.unsafe?he[I]&&(G=!0):delete he[I]}catch{}G?he[I]=V:O.f(he,I,{value:V,enumerable:!1,configurable:!Q.nonConfigurable,writable:!Q.nonWritable})}return he}},9433:function($,Y,E){var j=E(4576),O=Object.defineProperty;$.exports=function(K,B){try{O(j,K,{value:B,configurable:!0,writable:!0})}catch{j[K]=B}return B}},4606:function($,Y,E){var j=E(6823),O=TypeError;$.exports=function(K,B){if(!delete K[B])throw new O("Cannot delete property "+j(B)+" of "+j(K))}},3724:function($,Y,E){var j=E(9039);$.exports=!j((function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}))},4055:function($,Y,E){var j=E(4576),O=E(34),K=j.document,B=O(K)&&O(K.createElement);$.exports=function(he){return B?K.createElement(he):{}}},6837:function($){var Y=TypeError;$.exports=function(E){if(E>9007199254740991)throw Y("Maximum allowed index exceeded");return E}},7400:function($){$.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},9296:function($,Y,E){var j=E(4055)("span").classList,O=j&&j.constructor&&j.constructor.prototype;$.exports=O===Object.prototype?void 0:O},8727:function($){$.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3709:function($,Y,E){var j=E(2839).match(/firefox\/(\d+)/i);$.exports=!!j&&+j[1]},3763:function($,Y,E){var j=E(2839);$.exports=/MSIE|Trident/.test(j)},6193:function($,Y,E){var j=E(4215);$.exports=j==="NODE"},2839:function($,Y,E){var j=E(4576).navigator,O=j&&j.userAgent;$.exports=O?String(O):""},9519:function($,Y,E){var j,O,K=E(4576),B=E(2839),he=K.process,I=K.Deno,V=he&&he.versions||I&&I.version,Q=V&&V.v8;Q&&(O=(j=Q.split("."))[0]>0&&j[0]<4?1:+(j[0]+j[1])),!O&&B&&(!(j=B.match(/Edge\/(\d+)/))||j[1]>=74)&&(j=B.match(/Chrome\/(\d+)/))&&(O=+j[1]),$.exports=O},3607:function($,Y,E){var j=E(2839).match(/AppleWebKit\/(\d+)\./);$.exports=!!j&&+j[1]},4215:function($,Y,E){var j=E(4576),O=E(2839),K=E(2195),B=function(he){return O.slice(0,he.length)===he};$.exports=B("Bun/")?"BUN":B("Cloudflare-Workers")?"CLOUDFLARE":B("Deno/")?"DENO":B("Node.js/")?"NODE":j.Bun&&typeof Bun.version=="string"?"BUN":j.Deno&&typeof Deno.version=="object"?"DENO":K(j.process)==="process"?"NODE":j.window&&j.document?"BROWSER":"REST"},6518:function($,Y,E){var j=E(4576),O=E(7347).f,K=E(6699),B=E(6840),he=E(9433),I=E(7740),V=E(2796);$.exports=function(Q,G){var J,se,fe,pe,de,U=Q.target,R=Q.global,ae=Q.stat;if(J=R?j:ae?j[U]||he(U,{}):j[U]&&j[U].prototype)for(se in G){if(pe=G[se],fe=Q.dontCallGetSet?(de=O(J,se))&&de.value:J[se],!V(R?se:U+(ae?".":"#")+se,Q.forced)&&fe!==void 0){if(typeof pe==typeof fe)continue;I(pe,fe)}(Q.sham||fe&&fe.sham)&&K(pe,"sham",!0),B(J,se,pe,Q)}}},9039:function($){$.exports=function(Y){try{return!!Y()}catch{return!0}}},9228:function($,Y,E){E(7495);var j=E(9565),O=E(6840),K=E(7323),B=E(9039),he=E(8227),I=E(6699),V=he("species"),Q=RegExp.prototype;$.exports=function(G,J,se,fe){var pe=he(G),de=!B((function(){var _e={};return _e[pe]=function(){return 7},""[G](_e)!==7})),U=de&&!B((function(){var _e=!1,Se=/a/;if(G==="split"){var ye={};ye[V]=function(){return Se},(Se={constructor:ye,flags:""})[pe]=/./[pe]}return Se.exec=function(){return _e=!0,null},Se[pe](""),!_e}));if(!de||!U||se){var R=/./[pe],ae=J(pe,""[G],(function(_e,Se,ye,Ae,ve){var je=Se.exec;return je===K||je===Q.exec?de&&!ve?{done:!0,value:j(R,Se,ye,Ae)}:{done:!0,value:j(_e,ye,Se,Ae)}:{done:!1}}));O(String.prototype,G,ae[0]),O(Q,pe,ae[1])}fe&&I(Q[pe],"sham",!0)}},8745:function($,Y,E){var j=E(616),O=Function.prototype,K=O.apply,B=O.call;$.exports=typeof Reflect=="object"&&Reflect.apply||(j?B.bind(K):function(){return B.apply(K,arguments)})},6080:function($,Y,E){var j=E(7476),O=E(9306),K=E(616),B=j(j.bind);$.exports=function(he,I){return O(he),I===void 0?he:K?B(he,I):function(){return he.apply(I,arguments)}}},616:function($,Y,E){var j=E(9039);$.exports=!j((function(){var O=(function(){}).bind();return typeof O!="function"||O.hasOwnProperty("prototype")}))},566:function($,Y,E){var j=E(9504),O=E(9306),K=E(34),B=E(9297),he=E(7680),I=E(616),V=Function,Q=j([].concat),G=j([].join),J={};$.exports=I?V.bind:function(se){var fe=O(this),pe=fe.prototype,de=he(arguments,1),U=function(){var R=Q(de,he(arguments));return this instanceof U?(function(ae,_e,Se){if(!B(J,_e)){for(var ye=[],Ae=0;Ae<_e;Ae++)ye[Ae]="a["+Ae+"]";J[_e]=V("C,a","return new C("+G(ye,",")+")")}return J[_e](ae,Se)})(fe,R.length,R):fe.apply(se,R)};return K(pe)&&(U.prototype=pe),U}},9565:function($,Y,E){var j=E(616),O=Function.prototype.call;$.exports=j?O.bind(O):function(){return O.apply(O,arguments)}},350:function($,Y,E){var j=E(3724),O=E(9297),K=Function.prototype,B=j&&Object.getOwnPropertyDescriptor,he=O(K,"name"),I=he&&(function(){}).name==="something",V=he&&(!j||j&&B(K,"name").configurable);$.exports={EXISTS:he,PROPER:I,CONFIGURABLE:V}},6706:function($,Y,E){var j=E(9504),O=E(9306);$.exports=function(K,B,he){try{return j(O(Object.getOwnPropertyDescriptor(K,B)[he]))}catch{}}},7476:function($,Y,E){var j=E(2195),O=E(9504);$.exports=function(K){if(j(K)==="Function")return O(K)}},9504:function($,Y,E){var j=E(616),O=Function.prototype,K=O.call,B=j&&O.bind.bind(K,K);$.exports=j?B:function(he){return function(){return K.apply(he,arguments)}}},7751:function($,Y,E){var j=E(4576),O=E(4901);$.exports=function(K,B){return arguments.length<2?(he=j[K],O(he)?he:void 0):j[K]&&j[K][B];var he}},851:function($,Y,E){var j=E(6955),O=E(5966),K=E(4117),B=E(6269),he=E(8227)("iterator");$.exports=function(I){if(!K(I))return O(I,he)||O(I,"@@iterator")||B[j(I)]}},81:function($,Y,E){var j=E(9565),O=E(9306),K=E(8551),B=E(6823),he=E(851),I=TypeError;$.exports=function(V,Q){var G=arguments.length<2?he(V):Q;if(O(G))return K(j(G,V));throw new I(B(V)+" is not iterable")}},5966:function($,Y,E){var j=E(9306),O=E(4117);$.exports=function(K,B){var he=K[B];return O(he)?void 0:j(he)}},2478:function($,Y,E){var j=E(9504),O=E(8981),K=Math.floor,B=j("".charAt),he=j("".replace),I=j("".slice),V=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Q=/\$([$&'`]|\d{1,2})/g;$.exports=function(G,J,se,fe,pe,de){var U=se+G.length,R=fe.length,ae=Q;return pe!==void 0&&(pe=O(pe),ae=V),he(de,ae,(function(_e,Se){var ye;switch(B(Se,0)){case"$":return"$";case"&":return G;case"`":return I(J,0,se);case"'":return I(J,U);case"<":ye=pe[I(Se,1,-1)];break;default:var Ae=+Se;if(Ae===0)return _e;if(Ae>R){var ve=K(Ae/10);return ve===0?_e:ve<=R?fe[ve-1]===void 0?B(Se,1):fe[ve-1]+B(Se,1):_e}ye=fe[Ae-1]}return ye===void 0?"":ye}))}},4576:function($,Y,E){var j=function(O){return O&&O.Math===Math&&O};$.exports=j(typeof globalThis=="object"&&globalThis)||j(typeof window=="object"&&window)||j(typeof self=="object"&&self)||j(typeof E.g=="object"&&E.g)||j(typeof this=="object"&&this)||(function(){return this})()||Function("return this")()},9297:function($,Y,E){var j=E(9504),O=E(8981),K=j({}.hasOwnProperty);$.exports=Object.hasOwn||function(B,he){return K(O(B),he)}},421:function($){$.exports={}},397:function($,Y,E){var j=E(7751);$.exports=j("document","documentElement")},5917:function($,Y,E){var j=E(3724),O=E(9039),K=E(4055);$.exports=!j&&!O((function(){return Object.defineProperty(K("div"),"a",{get:function(){return 7}}).a!==7}))},7055:function($,Y,E){var j=E(9504),O=E(9039),K=E(2195),B=Object,he=j("".split);$.exports=O((function(){return!B("z").propertyIsEnumerable(0)}))?function(I){return K(I)==="String"?he(I,""):B(I)}:B},3167:function($,Y,E){var j=E(4901),O=E(34),K=E(2967);$.exports=function(B,he,I){var V,Q;return K&&j(V=he.constructor)&&V!==I&&O(Q=V.prototype)&&Q!==I.prototype&&K(B,Q),B}},3706:function($,Y,E){var j=E(9504),O=E(4901),K=E(7629),B=j(Function.toString);O(K.inspectSource)||(K.inspectSource=function(he){return B(he)}),$.exports=K.inspectSource},1181:function($,Y,E){var j,O,K,B=E(8622),he=E(4576),I=E(34),V=E(6699),Q=E(9297),G=E(7629),J=E(6119),se=E(421),fe="Object already initialized",pe=he.TypeError,de=he.WeakMap;if(B||G.state){var U=G.state||(G.state=new de);U.get=U.get,U.has=U.has,U.set=U.set,j=function(ae,_e){if(U.has(ae))throw new pe(fe);return _e.facade=ae,U.set(ae,_e),_e},O=function(ae){return U.get(ae)||{}},K=function(ae){return U.has(ae)}}else{var R=J("state");se[R]=!0,j=function(ae,_e){if(Q(ae,R))throw new pe(fe);return _e.facade=ae,V(ae,R,_e),_e},O=function(ae){return Q(ae,R)?ae[R]:{}},K=function(ae){return Q(ae,R)}}$.exports={set:j,get:O,has:K,enforce:function(ae){return K(ae)?O(ae):j(ae,{})},getterFor:function(ae){return function(_e){var Se;if(!I(_e)||(Se=O(_e)).type!==ae)throw new pe("Incompatible receiver, "+ae+" required");return Se}}}},4209:function($,Y,E){var j=E(8227),O=E(6269),K=j("iterator"),B=Array.prototype;$.exports=function(he){return he!==void 0&&(O.Array===he||B[K]===he)}},4376:function($,Y,E){var j=E(2195);$.exports=Array.isArray||function(O){return j(O)==="Array"}},4901:function($){var Y=typeof document=="object"&&document.all;$.exports=Y===void 0&&Y!==void 0?function(E){return typeof E=="function"||E===Y}:function(E){return typeof E=="function"}},3517:function($,Y,E){var j=E(9504),O=E(9039),K=E(4901),B=E(6955),he=E(7751),I=E(3706),V=function(){},Q=he("Reflect","construct"),G=/^\s*(?:class|function)\b/,J=j(G.exec),se=!G.test(V),fe=function(de){if(!K(de))return!1;try{return Q(V,[],de),!0}catch{return!1}},pe=function(de){if(!K(de))return!1;switch(B(de)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return se||!!J(G,I(de))}catch{return!0}};pe.sham=!0,$.exports=!Q||O((function(){var de;return fe(fe.call)||!fe(Object)||!fe((function(){de=!0}))||de}))?pe:fe},2796:function($,Y,E){var j=E(9039),O=E(4901),K=/#|\.prototype\./,B=function(G,J){var se=I[he(G)];return se===Q||se!==V&&(O(J)?j(J):!!J)},he=B.normalize=function(G){return String(G).replace(K,".").toLowerCase()},I=B.data={},V=B.NATIVE="N",Q=B.POLYFILL="P";$.exports=B},2087:function($,Y,E){var j=E(34),O=Math.floor;$.exports=Number.isInteger||function(K){return!j(K)&&isFinite(K)&&O(K)===K}},4117:function($){$.exports=function(Y){return Y==null}},34:function($,Y,E){var j=E(4901);$.exports=function(O){return typeof O=="object"?O!==null:j(O)}},3925:function($,Y,E){var j=E(34);$.exports=function(O){return j(O)||O===null}},6395:function($){$.exports=!1},5810:function($,Y,E){var j=E(34),O=E(1181).get;$.exports=function(K){if(!j(K))return!1;var B=O(K);return!!B&&B.type==="RawJSON"}},788:function($,Y,E){var j=E(34),O=E(2195),K=E(8227)("match");$.exports=function(B){var he;return j(B)&&((he=B[K])!==void 0?!!he:O(B)==="RegExp")}},757:function($,Y,E){var j=E(7751),O=E(4901),K=E(1625),B=E(7040),he=Object;$.exports=B?function(I){return typeof I=="symbol"}:function(I){var V=j("Symbol");return O(V)&&K(V.prototype,he(I))}},9539:function($,Y,E){var j=E(9565),O=E(8551),K=E(5966);$.exports=function(B,he,I){var V,Q;O(B);try{if(!(V=K(B,"return"))){if(he==="throw")throw I;return I}V=j(V,B)}catch(G){Q=!0,V=G}if(he==="throw")throw I;if(Q)throw V;return O(V),I}},3994:function($,Y,E){var j=E(7657).IteratorPrototype,O=E(2360),K=E(6980),B=E(687),he=E(6269),I=function(){return this};$.exports=function(V,Q,G,J){var se=Q+" Iterator";return V.prototype=O(j,{next:K(+!J,G)}),B(V,se,!1,!0),he[se]=I,V}},1088:function($,Y,E){var j=E(6518),O=E(9565),K=E(6395),B=E(350),he=E(4901),I=E(3994),V=E(2787),Q=E(2967),G=E(687),J=E(6699),se=E(6840),fe=E(8227),pe=E(6269),de=E(7657),U=B.PROPER,R=B.CONFIGURABLE,ae=de.IteratorPrototype,_e=de.BUGGY_SAFARI_ITERATORS,Se=fe("iterator"),ye="keys",Ae="values",ve="entries",je=function(){return this};$.exports=function(Re,Ee,Te,Me,Be,Ke,tt){I(Te,Ee,Me);var te,Ie,be,$e=function(vt){if(vt===Be&&Ze)return Ze;if(!_e&&vt&&vt in Pe)return Pe[vt];switch(vt){case ye:case Ae:case ve:return function(){return new Te(this,vt)}}return function(){return new Te(this)}},He=Ee+" Iterator",ge=!1,Pe=Re.prototype,qe=Pe[Se]||Pe["@@iterator"]||Be&&Pe[Be],Ze=!_e&&qe||$e(Be),ut=Ee==="Array"&&Pe.entries||qe;if(ut&&(te=V(ut.call(new Re)))!==Object.prototype&&te.next&&(K||V(te)===ae||(Q?Q(te,ae):he(te[Se])||se(te,Se,je)),G(te,He,!0,!0),K&&(pe[He]=je)),U&&Be===Ae&&qe&&qe.name!==Ae&&(!K&&R?J(Pe,"name",Ae):(ge=!0,Ze=function(){return O(qe,this)})),Be)if(Ie={values:$e(Ae),keys:Ke?Ze:$e(ye),entries:$e(ve)},tt)for(be in Ie)(_e||ge||!(be in Pe))&&se(Pe,be,Ie[be]);else j({target:Ee,proto:!0,forced:_e||ge},Ie);return K&&!tt||Pe[Se]===Ze||se(Pe,Se,Ze,{name:Be}),pe[Ee]=Ze,Ie}},7657:function($,Y,E){var j,O,K,B=E(9039),he=E(4901),I=E(34),V=E(2360),Q=E(2787),G=E(6840),J=E(8227),se=E(6395),fe=J("iterator"),pe=!1;[].keys&&("next"in(K=[].keys())?(O=Q(Q(K)))!==Object.prototype&&(j=O):pe=!0),!I(j)||B((function(){var de={};return j[fe].call(de)!==de}))?j={}:se&&(j=V(j)),he(j[fe])||G(j,fe,(function(){return this})),$.exports={IteratorPrototype:j,BUGGY_SAFARI_ITERATORS:pe}},6269:function($){$.exports={}},6198:function($,Y,E){var j=E(8014);$.exports=function(O){return j(O.length)}},283:function($,Y,E){var j=E(9504),O=E(9039),K=E(4901),B=E(9297),he=E(3724),I=E(350).CONFIGURABLE,V=E(3706),Q=E(1181),G=Q.enforce,J=Q.get,se=String,fe=Object.defineProperty,pe=j("".slice),de=j("".replace),U=j([].join),R=he&&!O((function(){return fe((function(){}),"length",{value:8}).length!==8})),ae=String(String).split("String"),_e=$.exports=function(Se,ye,Ae){pe(se(ye),0,7)==="Symbol("&&(ye="["+de(se(ye),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),Ae&&Ae.getter&&(ye="get "+ye),Ae&&Ae.setter&&(ye="set "+ye),(!B(Se,"name")||I&&Se.name!==ye)&&(he?fe(Se,"name",{value:ye,configurable:!0}):Se.name=ye),R&&Ae&&B(Ae,"arity")&&Se.length!==Ae.arity&&fe(Se,"length",{value:Ae.arity});try{Ae&&B(Ae,"constructor")&&Ae.constructor?he&&fe(Se,"prototype",{writable:!1}):Se.prototype&&(Se.prototype=void 0)}catch{}var ve=G(Se);return B(ve,"source")||(ve.source=U(ae,typeof ye=="string"?ye:"")),Se};Function.prototype.toString=_e((function(){return K(this)&&J(this).source||V(this)}),"toString")},741:function($){var Y=Math.ceil,E=Math.floor;$.exports=Math.trunc||function(j){var O=+j;return(O>0?E:Y)(O)}},7819:function($,Y,E){var j=E(9039);$.exports=!j((function(){var O="9007199254740993",K=JSON.rawJSON(O);return!JSON.isRawJSON(K)||JSON.stringify(K)!==O}))},5749:function($,Y,E){var j=E(788),O=TypeError;$.exports=function(K){if(j(K))throw new O("The method doesn't accept regular expressions");return K}},4213:function($,Y,E){var j=E(3724),O=E(9504),K=E(9565),B=E(9039),he=E(1072),I=E(3717),V=E(8773),Q=E(8981),G=E(7055),J=Object.assign,se=Object.defineProperty,fe=O([].concat);$.exports=!J||B((function(){if(j&&J({b:1},J(se({},"a",{enumerable:!0,get:function(){se(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var pe={},de={},U=Symbol("assign detection"),R="abcdefghijklmnopqrst";return pe[U]=7,R.split("").forEach((function(ae){de[ae]=ae})),J({},pe)[U]!==7||he(J({},de)).join("")!==R}))?function(pe,de){for(var U=Q(pe),R=arguments.length,ae=1,_e=I.f,Se=V.f;R>ae;)for(var ye,Ae=G(arguments[ae++]),ve=_e?fe(he(Ae),_e(Ae)):he(Ae),je=ve.length,Re=0;je>Re;)ye=ve[Re++],j&&!K(Se,Ae,ye)||(U[ye]=Ae[ye]);return U}:J},2360:function($,Y,E){var j,O=E(8551),K=E(6801),B=E(8727),he=E(421),I=E(397),V=E(4055),Q=E(6119),G="prototype",J="script",se=Q("IE_PROTO"),fe=function(){},pe=function(R){return"<"+J+">"+R+"</"+J+">"},de=function(R){R.write(pe("")),R.close();var ae=R.parentWindow.Object;return R=null,ae},U=function(){try{j=new ActiveXObject("htmlfile")}catch{}var R,ae,_e;U=typeof document<"u"?document.domain&&j?de(j):(ae=V("iframe"),_e="java"+J+":",ae.style.display="none",I.appendChild(ae),ae.src=String(_e),(R=ae.contentWindow.document).open(),R.write(pe("document.F=Object")),R.close(),R.F):de(j);for(var Se=B.length;Se--;)delete U[G][B[Se]];return U()};he[se]=!0,$.exports=Object.create||function(R,ae){var _e;return R!==null?(fe[G]=O(R),_e=new fe,fe[G]=null,_e[se]=R):_e=U(),ae===void 0?_e:K.f(_e,ae)}},6801:function($,Y,E){var j=E(3724),O=E(8686),K=E(4913),B=E(8551),he=E(5397),I=E(1072);Y.f=j&&!O?Object.defineProperties:function(V,Q){B(V);for(var G,J=he(Q),se=I(Q),fe=se.length,pe=0;fe>pe;)K.f(V,G=se[pe++],J[G]);return V}},4913:function($,Y,E){var j=E(3724),O=E(5917),K=E(8686),B=E(8551),he=E(6969),I=TypeError,V=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,G="enumerable",J="configurable",se="writable";Y.f=j?K?function(fe,pe,de){if(B(fe),pe=he(pe),B(de),typeof fe=="function"&&pe==="prototype"&&"value"in de&&se in de&&!de[se]){var U=Q(fe,pe);U&&U[se]&&(fe[pe]=de.value,de={configurable:J in de?de[J]:U[J],enumerable:G in de?de[G]:U[G],writable:!1})}return V(fe,pe,de)}:V:function(fe,pe,de){if(B(fe),pe=he(pe),B(de),O)try{return V(fe,pe,de)}catch{}if("get"in de||"set"in de)throw new I("Accessors not supported");return"value"in de&&(fe[pe]=de.value),fe}},7347:function($,Y,E){var j=E(3724),O=E(9565),K=E(8773),B=E(6980),he=E(5397),I=E(6969),V=E(9297),Q=E(5917),G=Object.getOwnPropertyDescriptor;Y.f=j?G:function(J,se){if(J=he(J),se=I(se),Q)try{return G(J,se)}catch{}if(V(J,se))return B(!O(K.f,J,se),J[se])}},298:function($,Y,E){var j=E(2195),O=E(5397),K=E(8480).f,B=E(7680),he=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];$.exports.f=function(I){return he&&j(I)==="Window"?(function(V){try{return K(V)}catch{return B(he)}})(I):K(O(I))}},8480:function($,Y,E){var j=E(1828),O=E(8727).concat("length","prototype");Y.f=Object.getOwnPropertyNames||function(K){return j(K,O)}},3717:function($,Y){Y.f=Object.getOwnPropertySymbols},2787:function($,Y,E){var j=E(9297),O=E(4901),K=E(8981),B=E(6119),he=E(2211),I=B("IE_PROTO"),V=Object,Q=V.prototype;$.exports=he?V.getPrototypeOf:function(G){var J=K(G);if(j(J,I))return J[I];var se=J.constructor;return O(se)&&J instanceof se?se.prototype:J instanceof V?Q:null}},1625:function($,Y,E){var j=E(9504);$.exports=j({}.isPrototypeOf)},1828:function($,Y,E){var j=E(9504),O=E(9297),K=E(5397),B=E(9617).indexOf,he=E(421),I=j([].push);$.exports=function(V,Q){var G,J=K(V),se=0,fe=[];for(G in J)!O(he,G)&&O(J,G)&&I(fe,G);for(;Q.length>se;)O(J,G=Q[se++])&&(~B(fe,G)||I(fe,G));return fe}},1072:function($,Y,E){var j=E(1828),O=E(8727);$.exports=Object.keys||function(K){return j(K,O)}},8773:function($,Y){var E={}.propertyIsEnumerable,j=Object.getOwnPropertyDescriptor,O=j&&!E.call({1:2},1);Y.f=O?function(K){var B=j(this,K);return!!B&&B.enumerable}:E},2551:function($,Y,E){var j=E(6395),O=E(4576),K=E(9039),B=E(3607);$.exports=j||!K((function(){if(!(B&&B<535)){var he=Math.random();__defineSetter__.call(null,he,(function(){})),delete O[he]}}))},2967:function($,Y,E){var j=E(6706),O=E(34),K=E(7750),B=E(3506);$.exports=Object.setPrototypeOf||("__proto__"in{}?(function(){var he,I=!1,V={};try{(he=j(Object.prototype,"__proto__","set"))(V,[]),I=V instanceof Array}catch{}return function(Q,G){return K(Q),B(G),O(Q)&&(I?he(Q,G):Q.__proto__=G),Q}})():void 0)},3179:function($,Y,E){var j=E(2140),O=E(6955);$.exports=j?{}.toString:function(){return"[object "+O(this)+"]"}},4270:function($,Y,E){var j=E(9565),O=E(4901),K=E(34),B=TypeError;$.exports=function(he,I){var V,Q;if(I==="string"&&O(V=he.toString)&&!K(Q=j(V,he))||O(V=he.valueOf)&&!K(Q=j(V,he))||I!=="string"&&O(V=he.toString)&&!K(Q=j(V,he)))return Q;throw new B("Can't convert object to primitive value")}},5031:function($,Y,E){var j=E(7751),O=E(9504),K=E(8480),B=E(3717),he=E(8551),I=O([].concat);$.exports=j("Reflect","ownKeys")||function(V){var Q=K.f(he(V)),G=B.f;return G?I(Q,G(V)):Q}},8235:function($,Y,E){var j=E(9504),O=E(9297),K=SyntaxError,B=parseInt,he=String.fromCharCode,I=j("".charAt),V=j("".slice),Q=j(/./.exec),G={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
- `,"\\r":"\r","\\t":" "},J=/^[\da-f]{4}$/i,se=/^[\u0000-\u001F]$/;$.exports=function(fe,pe){for(var de=!0,U="";pe<fe.length;){var R=I(fe,pe);if(R==="\\"){var ae=V(fe,pe,pe+2);if(O(G,ae))U+=G[ae],pe+=2;else{if(ae!=="\\u")throw new K('Unknown escape sequence: "'+ae+'"');var _e=V(fe,pe+=2,pe+4);if(!Q(J,_e))throw new K("Bad Unicode escape at: "+pe);U+=he(B(_e,16)),pe+=4}}else{if(R==='"'){de=!1,pe++;break}if(Q(se,R))throw new K("Bad control character in string literal at: "+pe);U+=R,pe++}}if(de)throw new K("Unterminated string at: "+pe);return{value:U,end:pe}}},9167:function($,Y,E){var j=E(4576);$.exports=j},1056:function($,Y,E){var j=E(4913).f;$.exports=function(O,K,B){B in O||j(O,B,{configurable:!0,get:function(){return K[B]},set:function(he){K[B]=he}})}},6682:function($,Y,E){var j=E(9565),O=E(8551),K=E(4901),B=E(2195),he=E(7323),I=TypeError;$.exports=function(V,Q){var G=V.exec;if(K(G)){var J=j(G,V,Q);return J!==null&&O(J),J}if(B(V)==="RegExp")return j(he,V,Q);throw new I("RegExp#exec called on incompatible receiver")}},7323:function($,Y,E){var j,O,K=E(9565),B=E(9504),he=E(655),I=E(7979),V=E(8429),Q=E(5745),G=E(2360),J=E(1181).get,se=E(3635),fe=E(8814),pe=Q("native-string-replace",String.prototype.replace),de=RegExp.prototype.exec,U=de,R=B("".charAt),ae=B("".indexOf),_e=B("".replace),Se=B("".slice),ye=(O=/b*/g,K(de,j=/a/,"a"),K(de,O,"a"),j.lastIndex!==0||O.lastIndex!==0),Ae=V.BROKEN_CARET,ve=/()??/.exec("")[1]!==void 0;(ye||ve||Ae||se||fe)&&(U=function(je){var Re,Ee,Te,Me,Be,Ke,tt,te=this,Ie=J(te),be=he(je),$e=Ie.raw;if($e)return $e.lastIndex=te.lastIndex,Re=K(U,$e,be),te.lastIndex=$e.lastIndex,Re;var He=Ie.groups,ge=Ae&&te.sticky,Pe=K(I,te),qe=te.source,Ze=0,ut=be;if(ge&&(Pe=_e(Pe,"y",""),ae(Pe,"g")===-1&&(Pe+="g"),ut=Se(be,te.lastIndex),te.lastIndex>0&&(!te.multiline||te.multiline&&R(be,te.lastIndex-1)!==`
- `)&&(qe="(?: "+qe+")",ut=" "+ut,Ze++),Ee=new RegExp("^(?:"+qe+")",Pe)),ve&&(Ee=new RegExp("^"+qe+"$(?!\\s)",Pe)),ye&&(Te=te.lastIndex),Me=K(de,ge?Ee:te,ut),ge?Me?(Me.input=Se(Me.input,Ze),Me[0]=Se(Me[0],Ze),Me.index=te.lastIndex,te.lastIndex+=Me[0].length):te.lastIndex=0:ye&&Me&&(te.lastIndex=te.global?Me.index+Me[0].length:Te),ve&&Me&&Me.length>1&&K(pe,Me[0],Ee,(function(){for(Be=1;Be<arguments.length-2;Be++)arguments[Be]===void 0&&(Me[Be]=void 0)})),Me&&He)for(Me.groups=Ke=G(null),Be=0;Be<He.length;Be++)Ke[(tt=He[Be])[0]]=Me[tt[1]];return Me}),$.exports=U},5213:function($,Y,E){var j=E(4576),O=E(9039),K=j.RegExp,B=!O((function(){var he=!0;try{K(".","d")}catch{he=!1}var I={},V="",Q=he?"dgimsy":"gimsy",G=function(fe,pe){Object.defineProperty(I,fe,{get:function(){return V+=pe,!0}})},J={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var se in he&&(J.hasIndices="d"),J)G(se,J[se]);return Object.getOwnPropertyDescriptor(K.prototype,"flags").get.call(I)!==Q||V!==Q}));$.exports={correct:B}},7979:function($,Y,E){var j=E(8551);$.exports=function(){var O=j(this),K="";return O.hasIndices&&(K+="d"),O.global&&(K+="g"),O.ignoreCase&&(K+="i"),O.multiline&&(K+="m"),O.dotAll&&(K+="s"),O.unicode&&(K+="u"),O.unicodeSets&&(K+="v"),O.sticky&&(K+="y"),K}},1034:function($,Y,E){var j=E(9565),O=E(9297),K=E(1625),B=E(5213),he=E(7979),I=RegExp.prototype;$.exports=B.correct?function(V){return V.flags}:function(V){return B.correct||!K(I,V)||O(V,"flags")?V.flags:j(he,V)}},8429:function($,Y,E){var j=E(9039),O=E(4576).RegExp,K=j((function(){var I=O("a","y");return I.lastIndex=2,I.exec("abcd")!==null})),B=K||j((function(){return!O("a","y").sticky})),he=K||j((function(){var I=O("^r","gy");return I.lastIndex=2,I.exec("str")!==null}));$.exports={BROKEN_CARET:he,MISSED_STICKY:B,UNSUPPORTED_Y:K}},3635:function($,Y,E){var j=E(9039),O=E(4576).RegExp;$.exports=j((function(){var K=O(".","s");return!(K.dotAll&&K.test(`
- `)&&K.flags==="s")}))},8814:function($,Y,E){var j=E(9039),O=E(4576).RegExp;$.exports=j((function(){var K=O("(?<a>b)","g");return K.exec("b").groups.a!=="b"||"b".replace(K,"$<a>c")!=="bc"}))},7750:function($,Y,E){var j=E(4117),O=TypeError;$.exports=function(K){if(j(K))throw new O("Can't call method on "+K);return K}},7633:function($,Y,E){var j=E(7751),O=E(2106),K=E(8227),B=E(3724),he=K("species");$.exports=function(I){var V=j(I);B&&V&&!V[he]&&O(V,he,{configurable:!0,get:function(){return this}})}},687:function($,Y,E){var j=E(4913).f,O=E(9297),K=E(8227)("toStringTag");$.exports=function(B,he,I){B&&!I&&(B=B.prototype),B&&!O(B,K)&&j(B,K,{configurable:!0,value:he})}},6119:function($,Y,E){var j=E(5745),O=E(3392),K=j("keys");$.exports=function(B){return K[B]||(K[B]=O(B))}},7629:function($,Y,E){var j=E(6395),O=E(4576),K=E(9433),B="__core-js_shared__",he=$.exports=O[B]||K(B,{});(he.versions||(he.versions=[])).push({version:"3.48.0",mode:j?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"})},5745:function($,Y,E){var j=E(7629);$.exports=function(O,K){return j[O]||(j[O]=K||{})}},2293:function($,Y,E){var j=E(8551),O=E(5548),K=E(4117),B=E(8227)("species");$.exports=function(he,I){var V,Q=j(he).constructor;return Q===void 0||K(V=j(Q)[B])?I:O(V)}},8183:function($,Y,E){var j=E(9504),O=E(1291),K=E(655),B=E(7750),he=j("".charAt),I=j("".charCodeAt),V=j("".slice),Q=function(G){return function(J,se){var fe,pe,de=K(B(J)),U=O(se),R=de.length;return U<0||U>=R?G?"":void 0:(fe=I(de,U))<55296||fe>56319||U+1===R||(pe=I(de,U+1))<56320||pe>57343?G?he(de,U):fe:G?V(de,U,U+2):pe-56320+(fe-55296<<10)+65536}};$.exports={codeAt:Q(!1),charAt:Q(!0)}},706:function($,Y,E){var j=E(350).PROPER,O=E(9039),K=E(7452);$.exports=function(B){return O((function(){return!!K[B]()||"
"[B]()!=="
"||j&&K[B].name!==B}))}},3802:function($,Y,E){var j=E(9504),O=E(7750),K=E(655),B=E(7452),he=j("".replace),I=RegExp("^["+B+"]+"),V=RegExp("(^|[^"+B+"])["+B+"]+$"),Q=function(G){return function(J){var se=K(O(J));return 1&G&&(se=he(se,I,"")),2&G&&(se=he(se,V,"$1")),se}};$.exports={start:Q(1),end:Q(2),trim:Q(3)}},4495:function($,Y,E){var j=E(9519),O=E(9039),K=E(4576).String;$.exports=!!Object.getOwnPropertySymbols&&!O((function(){var B=Symbol("symbol detection");return!K(B)||!(Object(B)instanceof Symbol)||!Symbol.sham&&j&&j<41}))},8242:function($,Y,E){var j=E(9565),O=E(7751),K=E(8227),B=E(6840);$.exports=function(){var he=O("Symbol"),I=he&&he.prototype,V=I&&I.valueOf,Q=K("toPrimitive");I&&!I[Q]&&B(I,Q,(function(G){return j(V,this)}),{arity:1})}},1296:function($,Y,E){var j=E(4495);$.exports=j&&!!Symbol.for&&!!Symbol.keyFor},1240:function($,Y,E){var j=E(9504);$.exports=j(1.1.valueOf)},5610:function($,Y,E){var j=E(1291),O=Math.max,K=Math.min;$.exports=function(B,he){var I=j(B);return I<0?O(I+he,0):K(I,he)}},5397:function($,Y,E){var j=E(7055),O=E(7750);$.exports=function(K){return j(O(K))}},1291:function($,Y,E){var j=E(741);$.exports=function(O){var K=+O;return K!=K||K===0?0:j(K)}},8014:function($,Y,E){var j=E(1291),O=Math.min;$.exports=function(K){var B=j(K);return B>0?O(B,9007199254740991):0}},8981:function($,Y,E){var j=E(7750),O=Object;$.exports=function(K){return O(j(K))}},2777:function($,Y,E){var j=E(9565),O=E(34),K=E(757),B=E(5966),he=E(4270),I=E(8227),V=TypeError,Q=I("toPrimitive");$.exports=function(G,J){if(!O(G)||K(G))return G;var se,fe=B(G,Q);if(fe){if(J===void 0&&(J="default"),se=j(fe,G,J),!O(se)||K(se))return se;throw new V("Can't convert object to primitive value")}return J===void 0&&(J="number"),he(G,J)}},6969:function($,Y,E){var j=E(2777),O=E(757);$.exports=function(K){var B=j(K,"string");return O(B)?B:B+""}},2140:function($,Y,E){var j={};j[E(8227)("toStringTag")]="z",$.exports=String(j)==="[object z]"},655:function($,Y,E){var j=E(6955),O=String;$.exports=function(K){if(j(K)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return O(K)}},6823:function($){var Y=String;$.exports=function(E){try{return Y(E)}catch{return"Object"}}},3392:function($,Y,E){var j=E(9504),O=0,K=Math.random(),B=j(1.1.toString);$.exports=function(he){return"Symbol("+(he===void 0?"":he)+")_"+B(++O+K,36)}},7040:function($,Y,E){var j=E(4495);$.exports=j&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},8686:function($,Y,E){var j=E(3724),O=E(9039);$.exports=j&&O((function(){return Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype!==42}))},8622:function($,Y,E){var j=E(4576),O=E(4901),K=j.WeakMap;$.exports=O(K)&&/native code/.test(String(K))},511:function($,Y,E){var j=E(9167),O=E(9297),K=E(1951),B=E(4913).f;$.exports=function(he){var I=j.Symbol||(j.Symbol={});O(I,he)||B(I,he,{value:K.f(he)})}},1951:function($,Y,E){var j=E(8227);Y.f=j},8227:function($,Y,E){var j=E(4576),O=E(5745),K=E(9297),B=E(3392),he=E(4495),I=E(7040),V=j.Symbol,Q=O("wks"),G=I?V.for||V:V&&V.withoutSetter||B;$.exports=function(J){return K(Q,J)||(Q[J]=he&&K(V,J)?V[J]:G("Symbol."+J)),Q[J]}},7452:function($){$.exports=`
- \v\f\r \u2028\u2029\uFEFF`},8706:function($,Y,E){var j=E(6518),O=E(9039),K=E(4376),B=E(34),he=E(8981),I=E(6198),V=E(6837),Q=E(4659),G=E(4527),J=E(1469),se=E(597),fe=E(8227),pe=E(9519),de=fe("isConcatSpreadable"),U=pe>=51||!O((function(){var ae=[];return ae[de]=!1,ae.concat()[0]!==ae})),R=function(ae){if(!B(ae))return!1;var _e=ae[de];return _e!==void 0?!!_e:K(ae)};j({target:"Array",proto:!0,arity:1,forced:!U||!se("concat")},{concat:function(ae){var _e,Se,ye,Ae,ve,je=he(this),Re=J(je,0),Ee=0;for(_e=-1,ye=arguments.length;_e<ye;_e++)if(R(ve=_e===-1?je:arguments[_e]))for(Ae=I(ve),V(Ee+Ae),Se=0;Se<Ae;Se++,Ee++)Se in ve&&Q(Re,Ee,ve[Se]);else V(Ee+1),Q(Re,Ee++,ve);return G(Re,Ee),Re}})},2008:function($,Y,E){var j=E(6518),O=E(9213).filter;j({target:"Array",proto:!0,forced:!E(597)("filter")},{filter:function(K){return O(this,K,arguments.length>1?arguments[1]:void 0)}})},3418:function($,Y,E){var j=E(6518),O=E(7916);j({target:"Array",stat:!0,forced:!E(4428)((function(K){Array.from(K)}))},{from:O})},4423:function($,Y,E){var j=E(6518),O=E(9617).includes,K=E(9039),B=E(6469);j({target:"Array",proto:!0,forced:K((function(){return!Array(1).includes()}))},{includes:function(he){return O(this,he,arguments.length>1?arguments[1]:void 0)}}),B("includes")},5276:function($,Y,E){var j=E(6518),O=E(7476),K=E(9617).indexOf,B=E(4598),he=O([].indexOf),I=!!he&&1/he([1],1,-0)<0;j({target:"Array",proto:!0,forced:I||!B("indexOf")},{indexOf:function(V){var Q=arguments.length>1?arguments[1]:void 0;return I?he(this,V,Q)||0:K(this,V,Q)}})},3792:function($,Y,E){var j=E(5397),O=E(6469),K=E(6269),B=E(1181),he=E(4913).f,I=E(1088),V=E(2529),Q=E(6395),G=E(3724),J="Array Iterator",se=B.set,fe=B.getterFor(J);$.exports=I(Array,"Array",(function(de,U){se(this,{type:J,target:j(de),index:0,kind:U})}),(function(){var de=fe(this),U=de.target,R=de.index++;if(!U||R>=U.length)return de.target=null,V(void 0,!0);switch(de.kind){case"keys":return V(R,!1);case"values":return V(U[R],!1)}return V([R,U[R]],!1)}),"values");var pe=K.Arguments=K.Array;if(O("keys"),O("values"),O("entries"),!Q&&G&&pe.name!=="values")try{he(pe,"name",{value:"values"})}catch{}},8598:function($,Y,E){var j=E(6518),O=E(9504),K=E(7055),B=E(5397),he=E(4598),I=O([].join);j({target:"Array",proto:!0,forced:K!==Object||!he("join",",")},{join:function(V){return I(B(this),V===void 0?",":V)}})},2062:function($,Y,E){var j=E(6518),O=E(9213).map;j({target:"Array",proto:!0,forced:!E(597)("map")},{map:function(K){return O(this,K,arguments.length>1?arguments[1]:void 0)}})},2712:function($,Y,E){var j=E(6518),O=E(926).left,K=E(4598),B=E(9519);j({target:"Array",proto:!0,forced:!E(6193)&&B>79&&B<83||!K("reduce")},{reduce:function(he){var I=arguments.length;return O(this,he,I,I>1?arguments[1]:void 0)}})},4782:function($,Y,E){var j=E(6518),O=E(4376),K=E(3517),B=E(34),he=E(5610),I=E(6198),V=E(5397),Q=E(4659),G=E(4527),J=E(8227),se=E(597),fe=E(7680),pe=se("slice"),de=J("species"),U=Array,R=Math.max;j({target:"Array",proto:!0,forced:!pe},{slice:function(ae,_e){var Se,ye,Ae,ve=V(this),je=I(ve),Re=he(ae,je),Ee=he(_e===void 0?je:_e,je);if(O(ve)&&(Se=ve.constructor,(K(Se)&&(Se===U||O(Se.prototype))||B(Se)&&(Se=Se[de])===null)&&(Se=void 0),Se===U||Se===void 0))return fe(ve,Re,Ee);for(ye=new(Se===void 0?U:Se)(R(Ee-Re,0)),Ae=0;Re<Ee;Re++,Ae++)Re in ve&&Q(ye,Ae,ve[Re]);return G(ye,Ae),ye}})},6910:function($,Y,E){var j=E(6518),O=E(9504),K=E(9306),B=E(8981),he=E(6198),I=E(4606),V=E(655),Q=E(9039),G=E(4488),J=E(4598),se=E(3709),fe=E(3763),pe=E(9519),de=E(3607),U=[],R=O(U.sort),ae=O(U.push),_e=Q((function(){U.sort(void 0)})),Se=Q((function(){U.sort(null)})),ye=J("sort"),Ae=!Q((function(){if(pe)return pe<70;if(!(se&&se>3)){if(fe)return!0;if(de)return de<603;var ve,je,Re,Ee,Te="";for(ve=65;ve<76;ve++){switch(je=String.fromCharCode(ve),ve){case 66:case 69:case 70:case 72:Re=3;break;case 68:case 71:Re=4;break;default:Re=2}for(Ee=0;Ee<47;Ee++)U.push({k:je+Ee,v:Re})}for(U.sort((function(Me,Be){return Be.v-Me.v})),Ee=0;Ee<U.length;Ee++)je=U[Ee].k.charAt(0),Te.charAt(Te.length-1)!==je&&(Te+=je);return Te!=="DGBEFHACIJK"}}));j({target:"Array",proto:!0,forced:_e||!Se||!ye||!Ae},{sort:function(ve){ve!==void 0&&K(ve);var je=B(this);if(Ae)return ve===void 0?R(je):R(je,ve);var Re,Ee,Te=[],Me=he(je);for(Ee=0;Ee<Me;Ee++)Ee in je&&ae(Te,je[Ee]);for(G(Te,(function(Be){return function(Ke,tt){return tt===void 0?-1:Ke===void 0?1:Be!==void 0?+Be(Ke,tt)||0:V(Ke)>V(tt)?1:-1}})(ve)),Re=he(Te),Ee=0;Ee<Re;)je[Ee]=Te[Ee++];for(;Ee<Me;)I(je,Ee++);return je}})},4554:function($,Y,E){var j=E(6518),O=E(8981),K=E(5610),B=E(1291),he=E(6198),I=E(4527),V=E(6837),Q=E(1469),G=E(4659),J=E(4606),se=E(597)("splice"),fe=Math.max,pe=Math.min;j({target:"Array",proto:!0,forced:!se},{splice:function(de,U){var R,ae,_e,Se,ye,Ae,ve=O(this),je=he(ve),Re=K(de,je),Ee=arguments.length;for(Ee===0?R=ae=0:Ee===1?(R=0,ae=je-Re):(R=Ee-2,ae=pe(fe(B(U),0),je-Re)),V(je+R-ae),_e=Q(ve,ae),Se=0;Se<ae;Se++)(ye=Re+Se)in ve&&G(_e,Se,ve[ye]);if(I(_e,ae),R<ae){for(Se=Re;Se<je-ae;Se++)Ae=Se+R,(ye=Se+ae)in ve?ve[Ae]=ve[ye]:J(ve,Ae);for(Se=je;Se>je-ae+R;Se--)J(ve,Se-1)}else if(R>ae)for(Se=je-ae;Se>Re;Se--)Ae=Se+R-1,(ye=Se+ae-1)in ve?ve[Ae]=ve[ye]:J(ve,Ae);for(Se=0;Se<R;Se++)ve[Se+Re]=arguments[Se+2];return I(ve,je-ae+R),_e}})},739:function($,Y,E){var j=E(6518),O=E(9039),K=E(8981),B=E(2777);j({target:"Date",proto:!0,arity:1,forced:O((function(){return new Date(NaN).toJSON()!==null||Date.prototype.toJSON.call({toISOString:function(){return 1}})!==1}))},{toJSON:function(he){var I=K(this),V=B(I,"number");return typeof V!="number"||isFinite(V)?I.toISOString():null}})},9572:function($,Y,E){var j=E(9297),O=E(6840),K=E(3640),B=E(8227)("toPrimitive"),he=Date.prototype;j(he,B)||O(he,B,K)},2010:function($,Y,E){var j=E(3724),O=E(350).EXISTS,K=E(9504),B=E(2106),he=Function.prototype,I=K(he.toString),V=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,Q=K(V.exec);j&&!O&&B(he,"name",{configurable:!0,get:function(){try{return Q(V,I(this))[1]}catch{return""}}})},3110:function($,Y,E){var j=E(6518),O=E(7751),K=E(8745),B=E(9565),he=E(9504),I=E(9039),V=E(4376),Q=E(4901),G=E(5810),J=E(757),se=E(2195),fe=E(655),pe=E(7680),de=E(8235),U=E(3392),R=E(4495),ae=E(7819),_e=String,Se=O("JSON","stringify"),ye=he(/./.exec),Ae=he("".charAt),ve=he("".charCodeAt),je=he("".replace),Re=he("".slice),Ee=he([].push),Te=he(1.1.toString),Me=/[\uD800-\uDFFF]/g,Be=/^[\uD800-\uDBFF]$/,Ke=/^[\uDC00-\uDFFF]$/,tt=U(),te=tt.length,Ie=!R||I((function(){var Pe=O("Symbol")("stringify detection");return Se([Pe])!=="[null]"||Se({a:Pe})!=="{}"||Se(Object(Pe))!=="{}"})),be=I((function(){return Se("\uDF06\uD834")!=='"\\udf06\\ud834"'||Se("\uDEAD")!=='"\\udead"'})),$e=Ie?function(Pe,qe){var Ze=pe(arguments),ut=ge(qe);if(Q(ut)||Pe!==void 0&&!J(Pe))return Ze[1]=function(vt,wt){if(Q(ut)&&(wt=B(ut,this,_e(vt),wt)),!J(wt))return wt},K(Se,null,Ze)}:Se,He=function(Pe,qe,Ze){var ut=Ae(Ze,qe-1),vt=Ae(Ze,qe+1);return ye(Be,Pe)&&!ye(Ke,vt)||ye(Ke,Pe)&&!ye(Be,ut)?"\\u"+Te(ve(Pe,0),16):Pe},ge=function(Pe){if(Q(Pe))return Pe;if(V(Pe)){for(var qe=Pe.length,Ze=[],ut=0;ut<qe;ut++){var vt=Pe[ut];typeof vt=="string"?Ee(Ze,vt):typeof vt!="number"&&se(vt)!=="Number"&&se(vt)!=="String"||Ee(Ze,fe(vt))}var wt=Ze.length,$t=!0;return function(Qt,en){if($t)return $t=!1,en;if(V(this))return en;for(var Xt=0;Xt<wt;Xt++)if(Ze[Xt]===Qt)return en}}};Se&&j({target:"JSON",stat:!0,arity:3,forced:Ie||be||!ae},{stringify:function(Pe,qe,Ze){var ut=ge(qe),vt=[],wt=$e(Pe,(function(Ft,Yt){var Pt=Q(ut)?B(ut,this,_e(Ft),Yt):Yt;return!ae&&G(Pt)?tt+(Ee(vt,Pt.rawJSON)-1):Pt}),Ze);if(typeof wt!="string"||(be&&(wt=je(wt,Me,He)),ae))return wt;for(var $t="",Qt=wt.length,en=0;en<Qt;en++){var Xt=Ae(wt,en);if(Xt==='"'){var tn=de(wt,++en).end-1,Ge=Re(wt,en,tn);$t+=Re(Ge,0,te)===tt?vt[Re(Ge,te)]:'"'+Ge+'"',en=tn}else $t+=Xt}return $t}})},2892:function($,Y,E){var j=E(6518),O=E(6395),K=E(3724),B=E(4576),he=E(9167),I=E(9504),V=E(2796),Q=E(9297),G=E(3167),J=E(1625),se=E(757),fe=E(2777),pe=E(9039),de=E(8480).f,U=E(7347).f,R=E(4913).f,ae=E(1240),_e=E(3802).trim,Se="Number",ye=B[Se],Ae=he[Se],ve=ye.prototype,je=B.TypeError,Re=I("".slice),Ee=I("".charCodeAt),Te=function(tt){var te,Ie,be,$e,He,ge,Pe,qe,Ze=fe(tt,"number");if(se(Ze))throw new je("Cannot convert a Symbol value to a number");if(typeof Ze=="string"&&Ze.length>2){if(Ze=_e(Ze),(te=Ee(Ze,0))===43||te===45){if((Ie=Ee(Ze,2))===88||Ie===120)return NaN}else if(te===48){switch(Ee(Ze,1)){case 66:case 98:be=2,$e=49;break;case 79:case 111:be=8,$e=55;break;default:return+Ze}for(ge=(He=Re(Ze,2)).length,Pe=0;Pe<ge;Pe++)if((qe=Ee(He,Pe))<48||qe>$e)return NaN;return parseInt(He,be)}}return+Ze},Me=V(Se,!ye(" 0o1")||!ye("0b1")||ye("+0x1")),Be=function(tt){var te,Ie=arguments.length<1?0:ye((function(be){var $e=fe(be,"number");return typeof $e=="bigint"?$e:Te($e)})(tt));return J(ve,te=this)&&pe((function(){ae(te)}))?G(Object(Ie),this,Be):Ie};Be.prototype=ve,Me&&!O&&(ve.constructor=Be),j({global:!0,constructor:!0,wrap:!0,forced:Me},{Number:Be});var Ke=function(tt,te){for(var Ie,be=K?de(te):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),$e=0;be.length>$e;$e++)Q(te,Ie=be[$e])&&!Q(tt,Ie)&&R(tt,Ie,U(te,Ie))};O&&Ae&&Ke(he[Se],Ae),(Me||O)&&Ke(he[Se],ye)},2637:function($,Y,E){E(6518)({target:"Number",stat:!0},{isInteger:E(2087)})},9085:function($,Y,E){var j=E(6518),O=E(4213);j({target:"Object",stat:!0,arity:2,forced:Object.assign!==O},{assign:O})},7427:function($,Y,E){var j=E(6518),O=E(3724),K=E(2551),B=E(9306),he=E(8981),I=E(4913);O&&j({target:"Object",proto:!0,forced:K},{__defineGetter__:function(V,Q){I.f(he(this),V,{get:B(Q),enumerable:!0,configurable:!0})}})},3851:function($,Y,E){var j=E(6518),O=E(9039),K=E(5397),B=E(7347).f,he=E(3724);j({target:"Object",stat:!0,forced:!he||O((function(){B(1)})),sham:!he},{getOwnPropertyDescriptor:function(I,V){return B(K(I),V)}})},1278:function($,Y,E){var j=E(6518),O=E(3724),K=E(5031),B=E(5397),he=E(7347),I=E(4659);j({target:"Object",stat:!0,sham:!O},{getOwnPropertyDescriptors:function(V){for(var Q,G,J=B(V),se=he.f,fe=K(J),pe={},de=0;fe.length>de;)(G=se(J,Q=fe[de++]))!==void 0&&I(pe,Q,G);return pe}})},1480:function($,Y,E){var j=E(6518),O=E(9039),K=E(298).f;j({target:"Object",stat:!0,forced:O((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:K})},9773:function($,Y,E){var j=E(6518),O=E(4495),K=E(9039),B=E(3717),he=E(8981);j({target:"Object",stat:!0,forced:!O||K((function(){B.f(1)}))},{getOwnPropertySymbols:function(I){var V=B.f;return V?V(he(I)):[]}})},9432:function($,Y,E){var j=E(6518),O=E(8981),K=E(1072);j({target:"Object",stat:!0,forced:E(9039)((function(){K(1)}))},{keys:function(B){return K(O(B))}})},6099:function($,Y,E){var j=E(2140),O=E(6840),K=E(3179);j||O(Object.prototype,"toString",K,{unsafe:!0})},825:function($,Y,E){var j=E(6518),O=E(7751),K=E(8745),B=E(566),he=E(5548),I=E(8551),V=E(34),Q=E(2360),G=E(9039),J=O("Reflect","construct"),se=Object.prototype,fe=[].push,pe=G((function(){function R(){}return!(J((function(){}),[],R)instanceof R)})),de=!G((function(){J((function(){}))})),U=pe||de;j({target:"Reflect",stat:!0,forced:U,sham:U},{construct:function(R,ae){he(R),I(ae);var _e=arguments.length<3?R:he(arguments[2]);if(de&&!pe)return J(R,ae,_e);if(R===_e){switch(ae.length){case 0:return new R;case 1:return new R(ae[0]);case 2:return new R(ae[0],ae[1]);case 3:return new R(ae[0],ae[1],ae[2]);case 4:return new R(ae[0],ae[1],ae[2],ae[3])}var Se=[null];return K(fe,Se,ae),new(K(B,R,Se))}var ye=_e.prototype,Ae=Q(V(ye)?ye:se),ve=K(R,Ae,ae);return V(ve)?ve:Ae}})},4864:function($,Y,E){var j=E(3724),O=E(4576),K=E(9504),B=E(2796),he=E(3167),I=E(6699),V=E(2360),Q=E(8480).f,G=E(1625),J=E(788),se=E(655),fe=E(1034),pe=E(8429),de=E(1056),U=E(6840),R=E(9039),ae=E(9297),_e=E(1181).enforce,Se=E(7633),ye=E(8227),Ae=E(3635),ve=E(8814),je=ye("match"),Re=O.RegExp,Ee=Re.prototype,Te=O.SyntaxError,Me=K(Ee.exec),Be=K("".charAt),Ke=K("".replace),tt=K("".indexOf),te=K("".slice),Ie=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,be=/a/g,$e=/a/g,He=new Re(be)!==be,ge=pe.MISSED_STICKY,Pe=pe.UNSUPPORTED_Y;if(B("RegExp",j&&(!He||ge||Ae||ve||R((function(){return $e[je]=!1,Re(be)!==be||Re($e)===$e||String(Re(be,"i"))!=="/a/i"}))))){for(var qe=function(vt,wt){var $t,Qt,en,Xt,tn,Ge,Ft=G(Ee,this),Yt=J(vt),Pt=wt===void 0,pt=[],Wt=vt;if(!Ft&&Yt&&Pt&&vt.constructor===qe)return vt;if((Yt||G(Ee,vt))&&(vt=vt.source,Pt&&(wt=fe(Wt))),vt=vt===void 0?"":se(vt),wt=wt===void 0?"":se(wt),Wt=vt,Ae&&"dotAll"in be&&(Qt=!!wt&&tt(wt,"s")>-1)&&(wt=Ke(wt,/s/g,"")),$t=wt,ge&&"sticky"in be&&(en=!!wt&&tt(wt,"y")>-1)&&Pe&&(wt=Ke(wt,/y/g,"")),ve&&(Xt=(function(Ut){for(var ze,st=Ut.length,ht=0,rt="",Le=[],Oe=V(null),Ce=!1,We=!1,Je=0,Xe="";ht<st;ht++){if((ze=Be(Ut,ht))==="\\")ze+=Be(Ut,++ht);else if(ze==="]")Ce=!1;else if(!Ce)switch(!0){case ze==="[":Ce=!0;break;case ze==="(":if(rt+=ze,te(Ut,ht+1,ht+3)==="?:")continue;Me(Ie,te(Ut,ht+1))&&(ht+=2,We=!0),Je++;continue;case(ze===">"&&We):if(Xe===""||ae(Oe,Xe))throw new Te("Invalid capture group name");Oe[Xe]=!0,Le[Le.length]=[Xe,Je],We=!1,Xe="";continue}We?Xe+=ze:rt+=ze}return[rt,Le]})(vt),vt=Xt[0],pt=Xt[1]),tn=he(Re(vt,wt),Ft?this:Ee,qe),(Qt||en||pt.length)&&(Ge=_e(tn),Qt&&(Ge.dotAll=!0,Ge.raw=qe((function(Ut){for(var ze,st=Ut.length,ht=0,rt="",Le=!1;ht<st;ht++)(ze=Be(Ut,ht))!=="\\"?Le||ze!=="."?(ze==="["?Le=!0:ze==="]"&&(Le=!1),rt+=ze):rt+="[\\s\\S]":rt+=ze+Be(Ut,++ht);return rt})(vt),$t)),en&&(Ge.sticky=!0),pt.length&&(Ge.groups=pt)),vt!==Wt)try{I(tn,"source",Wt===""?"(?:)":Wt)}catch{}return tn},Ze=Q(Re),ut=0;Ze.length>ut;)de(qe,Re,Ze[ut++]);Ee.constructor=qe,qe.prototype=Ee,U(O,"RegExp",qe,{constructor:!0})}Se("RegExp")},7495:function($,Y,E){var j=E(6518),O=E(7323);j({target:"RegExp",proto:!0,forced:/./.exec!==O},{exec:O})},8781:function($,Y,E){var j=E(350).PROPER,O=E(6840),K=E(8551),B=E(655),he=E(9039),I=E(1034),V="toString",Q=RegExp.prototype,G=Q[V],J=he((function(){return G.call({source:"a",flags:"b"})!=="/a/b"})),se=j&&G.name!==V;(J||se)&&O(Q,V,(function(){var fe=K(this);return"/"+B(fe.source)+"/"+B(I(fe))}),{unsafe:!0})},1699:function($,Y,E){var j=E(6518),O=E(9504),K=E(5749),B=E(7750),he=E(655),I=E(1436),V=O("".indexOf);j({target:"String",proto:!0,forced:!I("includes")},{includes:function(Q){return!!~V(he(B(this)),he(K(Q)),arguments.length>1?arguments[1]:void 0)}})},7764:function($,Y,E){var j=E(8183).charAt,O=E(655),K=E(1181),B=E(1088),he=E(2529),I="String Iterator",V=K.set,Q=K.getterFor(I);B(String,"String",(function(G){V(this,{type:I,string:O(G),index:0})}),(function(){var G,J=Q(this),se=J.string,fe=J.index;return fe>=se.length?he(void 0,!0):(G=j(se,fe),J.index+=G.length,he(G,!1))}))},8543:function($,Y,E){var j=E(6518),O=E(9565),K=E(7476),B=E(3994),he=E(2529),I=E(7750),V=E(8014),Q=E(655),G=E(8551),J=E(34),se=E(2195),fe=E(788),pe=E(1034),de=E(5966),U=E(6840),R=E(9039),ae=E(8227),_e=E(2293),Se=E(7829),ye=E(6682),Ae=E(1181),ve=E(6395),je=ae("matchAll"),Re="RegExp String",Ee=Re+" Iterator",Te=Ae.set,Me=Ae.getterFor(Ee),Be=RegExp.prototype,Ke=TypeError,tt=K("".indexOf),te=K("".matchAll),Ie=!!te&&!R((function(){te("a",/./)})),be=B((function(He,ge,Pe,qe){Te(this,{type:Ee,regexp:He,string:ge,global:Pe,unicode:qe,done:!1})}),Re,(function(){var He=Me(this);if(He.done)return he(void 0,!0);var ge=He.regexp,Pe=He.string,qe=ye(ge,Pe);return qe===null?(He.done=!0,he(void 0,!0)):He.global?(Q(qe[0])===""&&(ge.lastIndex=Se(Pe,V(ge.lastIndex),He.unicode)),he(qe,!1)):(He.done=!0,he(qe,!1))})),$e=function(He){var ge,Pe,qe,Ze=G(this),ut=Q(He),vt=_e(Ze,RegExp),wt=Q(pe(Ze));return ge=new vt(vt===RegExp?Ze.source:Ze,wt),Pe=!!~tt(wt,"g"),qe=!!~tt(wt,"u"),ge.lastIndex=V(Ze.lastIndex),new be(ge,ut,Pe,qe)};j({target:"String",proto:!0,forced:Ie},{matchAll:function(He){var ge,Pe,qe,Ze,ut=I(this);if(J(He)){if(fe(He)&&(ge=Q(I(pe(He))),!~tt(ge,"g")))throw new Ke("`.matchAll` does not allow non-global regexes");if(Ie)return te(ut,He);if((qe=de(He,je))===void 0&&ve&&se(He)==="RegExp"&&(qe=$e),qe)return O(qe,He,ut)}else if(Ie)return te(ut,He);return Pe=Q(ut),Ze=new RegExp(He,"g"),ve?O($e,Ze,Pe):Ze[je](Pe)}}),ve||je in Be||U(Be,je,$e)},1761:function($,Y,E){var j=E(9565),O=E(9504),K=E(9228),B=E(8551),he=E(34),I=E(8014),V=E(655),Q=E(7750),G=E(5966),J=E(7829),se=E(1034),fe=E(6682),pe=O("".indexOf);K("match",(function(de,U,R){return[function(ae){var _e=Q(this),Se=he(ae)?G(ae,de):void 0;return Se?j(Se,ae,_e):new RegExp(ae)[de](V(_e))},function(ae){var _e=B(this),Se=V(ae),ye=R(U,_e,Se);if(ye.done)return ye.value;var Ae=V(se(_e));if(pe(Ae,"g")===-1)return fe(_e,Se);var ve=pe(Ae,"u")!==-1;_e.lastIndex=0;for(var je,Re=[],Ee=0;(je=fe(_e,Se))!==null;){var Te=V(je[0]);Re[Ee]=Te,Te===""&&(_e.lastIndex=J(Se,I(_e.lastIndex),ve)),Ee++}return Ee===0?null:Re}]}))},5440:function($,Y,E){var j=E(8745),O=E(9565),K=E(9504),B=E(9228),he=E(9039),I=E(8551),V=E(4901),Q=E(34),G=E(1291),J=E(8014),se=E(655),fe=E(7750),pe=E(7829),de=E(5966),U=E(2478),R=E(1034),ae=E(6682),_e=E(8227)("replace"),Se=Math.max,ye=Math.min,Ae=K([].concat),ve=K([].push),je=K("".indexOf),Re=K("".slice),Ee="a".replace(/./,"$0")==="$0",Te=!!/./[_e]&&/./[_e]("a","$0")==="";B("replace",(function(Me,Be,Ke){var tt=Te?"$":"$0";return[function(te,Ie){var be=fe(this),$e=Q(te)?de(te,_e):void 0;return $e?O($e,te,be,Ie):O(Be,se(be),te,Ie)},function(te,Ie){var be=I(this),$e=se(te);if(typeof Ie=="string"&&je(Ie,tt)===-1&&je(Ie,"$<")===-1){var He=Ke(Be,be,$e,Ie);if(He.done)return He.value}var ge=V(Ie);ge||(Ie=se(Ie));var Pe,qe=se(R(be)),Ze=je(qe,"g")!==-1;Ze&&(Pe=je(qe,"u")!==-1,be.lastIndex=0);for(var ut,vt=[];(ut=ae(be,$e))!==null&&(ve(vt,ut),Ze);)se(ut[0])===""&&(be.lastIndex=pe($e,J(be.lastIndex),Pe));for(var wt,$t="",Qt=0,en=0;en<vt.length;en++){for(var Xt,tn=se((ut=vt[en])[0]),Ge=Se(ye(G(ut.index),$e.length),0),Ft=[],Yt=1;Yt<ut.length;Yt++)ve(Ft,(wt=ut[Yt])===void 0?wt:String(wt));var Pt=ut.groups;if(ge){var pt=Ae([tn],Ft,Ge,$e);Pt!==void 0&&ve(pt,Pt),Xt=se(j(Ie,void 0,pt))}else Xt=U(tn,$e,Ge,Ft,Pt,Ie);Ge>=Qt&&($t+=Re($e,Qt,Ge)+Xt,Qt=Ge+tn.length)}return $t+Re($e,Qt)}]}),!!he((function(){var Me=/./;return Me.exec=function(){var Be=[];return Be.groups={a:"7"},Be},"".replace(Me,"$<a>")!=="7"}))||!Ee||Te)},744:function($,Y,E){var j=E(9565),O=E(9504),K=E(9228),B=E(8551),he=E(34),I=E(7750),V=E(2293),Q=E(7829),G=E(8014),J=E(655),se=E(5966),fe=E(6682),pe=E(8429),de=E(9039),U=pe.UNSUPPORTED_Y,R=Math.min,ae=O([].push),_e=O("".slice),Se=!de((function(){var Ae=/(?:)/,ve=Ae.exec;Ae.exec=function(){return ve.apply(this,arguments)};var je="ab".split(Ae);return je.length!==2||je[0]!=="a"||je[1]!=="b"})),ye="abbc".split(/(b)*/)[1]==="c"||"test".split(/(?:)/,-1).length!==4||"ab".split(/(?:ab)*/).length!==2||".".split(/(.?)(.?)/).length!==4||".".split(/()()/).length>1||"".split(/.?/).length;K("split",(function(Ae,ve,je){var Re="0".split(void 0,0).length?function(Ee,Te){return Ee===void 0&&Te===0?[]:j(ve,this,Ee,Te)}:ve;return[function(Ee,Te){var Me=I(this),Be=he(Ee)?se(Ee,Ae):void 0;return Be?j(Be,Ee,Me,Te):j(Re,J(Me),Ee,Te)},function(Ee,Te){var Me=B(this),Be=J(Ee);if(!ye){var Ke=je(Re,Me,Be,Te,Re!==ve);if(Ke.done)return Ke.value}var tt=V(Me,RegExp),te=Me.unicode,Ie=(Me.ignoreCase?"i":"")+(Me.multiline?"m":"")+(Me.unicode?"u":"")+(U?"g":"y"),be=new tt(U?"^(?:"+Me.source+")":Me,Ie),$e=Te===void 0?4294967295:Te>>>0;if($e===0)return[];if(Be.length===0)return fe(be,Be)===null?[Be]:[];for(var He=0,ge=0,Pe=[];ge<Be.length;){be.lastIndex=U?0:ge;var qe,Ze=fe(be,U?_e(Be,ge):Be);if(Ze===null||(qe=R(G(be.lastIndex+(U?ge:0)),Be.length))===He)ge=Q(Be,ge,te);else{if(ae(Pe,_e(Be,He,ge)),Pe.length===$e)return Pe;for(var ut=1;ut<=Ze.length-1;ut++)if(ae(Pe,Ze[ut]),Pe.length===$e)return Pe;ge=He=qe}}return ae(Pe,_e(Be,He)),Pe}]}),ye||!Se,U)},2762:function($,Y,E){var j=E(6518),O=E(3802).trim;j({target:"String",proto:!0,forced:E(706)("trim")},{trim:function(){return O(this)}})},6761:function($,Y,E){var j=E(6518),O=E(4576),K=E(9565),B=E(9504),he=E(6395),I=E(3724),V=E(4495),Q=E(9039),G=E(9297),J=E(1625),se=E(8551),fe=E(5397),pe=E(6969),de=E(655),U=E(6980),R=E(2360),ae=E(1072),_e=E(8480),Se=E(298),ye=E(3717),Ae=E(7347),ve=E(4913),je=E(6801),Re=E(8773),Ee=E(6840),Te=E(2106),Me=E(5745),Be=E(6119),Ke=E(421),tt=E(3392),te=E(8227),Ie=E(1951),be=E(511),$e=E(8242),He=E(687),ge=E(1181),Pe=E(9213).forEach,qe=Be("hidden"),Ze="Symbol",ut="prototype",vt=ge.set,wt=ge.getterFor(Ze),$t=Object[ut],Qt=O.Symbol,en=Qt&&Qt[ut],Xt=O.RangeError,tn=O.TypeError,Ge=O.QObject,Ft=Ae.f,Yt=ve.f,Pt=Se.f,pt=Re.f,Wt=B([].push),Ut=Me("symbols"),ze=Me("op-symbols"),st=Me("wks"),ht=!Ge||!Ge[ut]||!Ge[ut].findChild,rt=function(et,jt,bt){var Ve=Ft($t,jt);Ve&&delete $t[jt],Yt(et,jt,bt),Ve&&et!==$t&&Yt($t,jt,Ve)},Le=I&&Q((function(){return R(Yt({},"a",{get:function(){return Yt(this,"a",{value:7}).a}})).a!==7}))?rt:Yt,Oe=function(et,jt){var bt=Ut[et]=R(en);return vt(bt,{type:Ze,tag:et,description:jt}),I||(bt.description=jt),bt},Ce=function(et,jt,bt){et===$t&&Ce(ze,jt,bt),se(et);var Ve=pe(jt);return se(bt),G(Ut,Ve)?(bt.enumerable?(G(et,qe)&&et[qe][Ve]&&(et[qe][Ve]=!1),bt=R(bt,{enumerable:U(0,!1)})):(G(et,qe)||Yt(et,qe,U(1,R(null))),et[qe][Ve]=!0),Le(et,Ve,bt)):Yt(et,Ve,bt)},We=function(et,jt){se(et);var bt=fe(jt),Ve=ae(bt).concat(St(bt));return Pe(Ve,(function(gt){I&&!K(Je,bt,gt)||Ce(et,gt,bt[gt])})),et},Je=function(et){var jt=pe(et),bt=K(pt,this,jt);return!(this===$t&&G(Ut,jt)&&!G(ze,jt))&&(!(bt||!G(this,jt)||!G(Ut,jt)||G(this,qe)&&this[qe][jt])||bt)},Xe=function(et,jt){var bt=fe(et),Ve=pe(jt);if(bt!==$t||!G(Ut,Ve)||G(ze,Ve)){var gt=Ft(bt,Ve);return!gt||!G(Ut,Ve)||G(bt,qe)&&bt[qe][Ve]||(gt.enumerable=!0),gt}},Ye=function(et){var jt=Pt(fe(et)),bt=[];return Pe(jt,(function(Ve){G(Ut,Ve)||G(Ke,Ve)||Wt(bt,Ve)})),bt},St=function(et){var jt=et===$t,bt=Pt(jt?ze:fe(et)),Ve=[];return Pe(bt,(function(gt){!G(Ut,gt)||jt&&!G($t,gt)||Wt(Ve,Ut[gt])})),Ve};V||(Qt=function(){if(J(en,this))throw new tn("Symbol is not a constructor");var et=arguments.length&&arguments[0]!==void 0?de(arguments[0]):void 0,jt=tt(et),bt=function(Ve){var gt=this===void 0?O:this;gt===$t&&K(bt,ze,Ve),G(gt,qe)&&G(gt[qe],jt)&&(gt[qe][jt]=!1);var Et=U(1,Ve);try{Le(gt,jt,Et)}catch(Gt){if(!(Gt instanceof Xt))throw Gt;rt(gt,jt,Et)}};return I&&ht&&Le($t,jt,{configurable:!0,set:bt}),Oe(jt,et)},Ee(en=Qt[ut],"toString",(function(){return wt(this).tag})),Ee(Qt,"withoutSetter",(function(et){return Oe(tt(et),et)})),Re.f=Je,ve.f=Ce,je.f=We,Ae.f=Xe,_e.f=Se.f=Ye,ye.f=St,Ie.f=function(et){return Oe(te(et),et)},I&&(Te(en,"description",{configurable:!0,get:function(){return wt(this).description}}),he||Ee($t,"propertyIsEnumerable",Je,{unsafe:!0}))),j({global:!0,constructor:!0,wrap:!0,forced:!V,sham:!V},{Symbol:Qt}),Pe(ae(st),(function(et){be(et)})),j({target:Ze,stat:!0,forced:!V},{useSetter:function(){ht=!0},useSimple:function(){ht=!1}}),j({target:"Object",stat:!0,forced:!V,sham:!I},{create:function(et,jt){return jt===void 0?R(et):We(R(et),jt)},defineProperty:Ce,defineProperties:We,getOwnPropertyDescriptor:Xe}),j({target:"Object",stat:!0,forced:!V},{getOwnPropertyNames:Ye}),$e(),He(Qt,Ze),Ke[qe]=!0},9463:function($,Y,E){var j=E(6518),O=E(3724),K=E(4576),B=E(9504),he=E(9297),I=E(4901),V=E(1625),Q=E(655),G=E(2106),J=E(7740),se=K.Symbol,fe=se&&se.prototype;if(O&&I(se)&&(!("description"in fe)||se().description!==void 0)){var pe={},de=function(){var Ae=arguments.length<1||arguments[0]===void 0?void 0:Q(arguments[0]),ve=V(fe,this)?new se(Ae):Ae===void 0?se():se(Ae);return Ae===""&&(pe[ve]=!0),ve};J(de,se),de.prototype=fe,fe.constructor=de;var U=String(se("description detection"))==="Symbol(description detection)",R=B(fe.valueOf),ae=B(fe.toString),_e=/^Symbol\((.*)\)[^)]+$/,Se=B("".replace),ye=B("".slice);G(fe,"description",{configurable:!0,get:function(){var Ae=R(this);if(he(pe,Ae))return"";var ve=ae(Ae),je=U?ye(ve,7,-1):Se(ve,_e,"$1");return je===""?void 0:je}}),j({global:!0,constructor:!0,forced:!0},{Symbol:de})}},1510:function($,Y,E){var j=E(6518),O=E(7751),K=E(9297),B=E(655),he=E(5745),I=E(1296),V=he("string-to-symbol-registry"),Q=he("symbol-to-string-registry");j({target:"Symbol",stat:!0,forced:!I},{for:function(G){var J=B(G);if(K(V,J))return V[J];var se=O("Symbol")(J);return V[J]=se,Q[se]=J,se}})},2259:function($,Y,E){E(511)("iterator")},2675:function($,Y,E){E(6761),E(1510),E(7812),E(3110),E(9773)},7812:function($,Y,E){var j=E(6518),O=E(9297),K=E(757),B=E(6823),he=E(5745),I=E(1296),V=he("symbol-to-string-registry");j({target:"Symbol",stat:!0,forced:!I},{keyFor:function(Q){if(!K(Q))throw new TypeError(B(Q)+" is not a symbol");if(O(V,Q))return V[Q]}})},5700:function($,Y,E){var j=E(511),O=E(8242);j("toPrimitive"),O()},8344:function($,Y,E){E(8543)},3500:function($,Y,E){var j=E(4576),O=E(7400),K=E(9296),B=E(235),he=E(6699),I=function(Q){if(Q&&Q.forEach!==B)try{he(Q,"forEach",B)}catch{Q.forEach=B}};for(var V in O)O[V]&&I(j[V]&&j[V].prototype);I(K)},2953:function($,Y,E){var j=E(4576),O=E(7400),K=E(9296),B=E(3792),he=E(6699),I=E(687),V=E(8227)("iterator"),Q=B.values,G=function(se,fe){if(se){if(se[V]!==Q)try{he(se,V,Q)}catch{se[V]=Q}if(I(se,fe,!0),O[fe]){for(var pe in B)if(se[pe]!==B[pe])try{he(se,pe,B[pe])}catch{se[pe]=B[pe]}}}};for(var J in O)G(j[J]&&j[J].prototype,J);G(K,"DOMTokenList")}},d={};function u($){var Y=d[$];if(Y!==void 0)return Y.exports;var E=d[$]={exports:{}};return c[$].call(E.exports,E,E.exports,u),E.exports}u.d=function($,Y){for(var E in Y)u.o(Y,E)&&!u.o($,E)&&Object.defineProperty($,E,{enumerable:!0,get:Y[E]})},u.g=(function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}})(),u.o=function($,Y){return Object.prototype.hasOwnProperty.call($,Y)},u.r=function($){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty($,Symbol.toStringTag,{value:"Module"}),Object.defineProperty($,"__esModule",{value:!0})};var m={};function p($){return(function(Y){if(Array.isArray(Y))return x(Y)})($)||(function(Y){if(typeof Symbol<"u"&&Y[Symbol.iterator]!=null||Y["@@iterator"]!=null)return Array.from(Y)})($)||f($)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function f($,Y){if($){if(typeof $=="string")return x($,Y);var E={}.toString.call($).slice(8,-1);return E==="Object"&&$.constructor&&(E=$.constructor.name),E==="Map"||E==="Set"?Array.from($):E==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(E)?x($,Y):void 0}}function x($,Y){(Y==null||Y>$.length)&&(Y=$.length);for(var E=0,j=Array(Y);E<Y;E++)j[E]=$[E];return j}function v($){return v=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},v($)}function g($,Y){for(var E=0;E<Y.length;E++){var j=Y[E];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty($,_(j.key),j)}}function b($,Y,E){return(Y=_(Y))in $?Object.defineProperty($,Y,{value:E,enumerable:!0,configurable:!0,writable:!0}):$[Y]=E,$}function _($){var Y=(function(E,j){if(v(E)!="object"||!E)return E;var O=E[Symbol.toPrimitive];if(O!==void 0){var K=O.call(E,j);if(v(K)!="object")return K;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(E)})($,"string");return v(Y)=="symbol"?Y:Y+""}u.r(m),u.d(m,{SimpleKeyboard:function(){return xe},default:function(){return Ne}}),u(5276),u(8598),u(4782),u(4554),u(2010),u(7427),u(6099),u(7495),u(8781),u(5440),u(744),u(2762),typeof Element>"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function($){if("Element"in $){var Y="classList",E="prototype",j=$.Element[E],O=Object,K=String[E].trim||function(){return this.replace(/^\s+|\s+$/g,"")},B=Array[E].indexOf||function(se){for(var fe=0,pe=this.length;fe<pe;fe++)if(fe in this&&this[fe]===se)return fe;return-1},he=function(se,fe){this.name=se,this.code=DOMException[se],this.message=fe},I=function(se,fe){if(fe==="")throw new he("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(fe))throw new he("INVALID_CHARACTER_ERR","The token must not contain space characters.");return B.call(se,fe)},V=function(se){for(var fe=K.call(se.getAttribute("class")||""),pe=fe?fe.split(/\s+/):[],de=0,U=pe.length;de<U;de++)this.push(pe[de]);this._updateClassName=function(){se.setAttribute("class",this.toString())}},Q=V[E]=[],G=function(){return new V(this)};if(he[E]=Error[E],Q.item=function(se){return this[se]||null},Q.contains=function(se){return~I(this,se+"")},Q.add=function(){var se,fe=arguments,pe=0,de=fe.length,U=!1;do~I(this,se=fe[pe]+"")||(this.push(se),U=!0);while(++pe<de);U&&this._updateClassName()},Q.remove=function(){var se,fe,pe=arguments,de=0,U=pe.length,R=!1;do for(fe=I(this,se=pe[de]+"");~fe;)this.splice(fe,1),R=!0,fe=I(this,se);while(++de<U);R&&this._updateClassName()},Q.toggle=function(se,fe){var pe=this.contains(se),de=pe?fe!==!0&&"remove":fe!==!1&&"add";return de&&this[de](se),fe===!0||fe===!1?fe:!pe},Q.replace=function(se,fe){var pe=I(se+"");~pe&&(this.splice(pe,1,fe),this._updateClassName())},Q.toString=function(){return this.join(" ")},O.defineProperty){var J={get:G,enumerable:!0,configurable:!0};try{O.defineProperty(j,Y,J)}catch(se){se.number!==void 0&&se.number!==-2146823252||(J.enumerable=!1,O.defineProperty(j,Y,J))}}else O[E].__defineGetter__&&j.__defineGetter__(Y,G)}})(self),(function(){var $=document.createElement("_");if($.classList.add("c1","c2"),!$.classList.contains("c2")){var Y=function(j){var O=DOMTokenList.prototype[j];DOMTokenList.prototype[j]=function(K){var B,he=arguments.length;for(B=0;B<he;B++)K=arguments[B],O.call(this,K)}};Y("add"),Y("remove")}if($.classList.toggle("c3",!1),$.classList.contains("c3")){var E=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(j,O){return 1 in arguments&&!this.contains(j)==!O?O:E.call(this,j)}}"replace"in document.createElement("_").classList||(DOMTokenList.prototype.replace=function(j,O){var K=this.toString().split(" "),B=K.indexOf(j+"");~B&&(K=K.slice(B),this.remove.apply(this,K),this.add(O),this.add.apply(this,K.slice(1)))}),$=null})()),u(2675),u(9463),u(2259),u(5700),u(8706),u(2008),u(3418),u(4423),u(3792),u(2062),u(6910),u(739),u(9572),u(2892),u(9085),u(3851),u(1278),u(9432),u(4864),u(1699),u(7764),u(8344),u(3500),u(2953),u(2712),u(2637),u(1480),u(825),u(1761);var C=(function(){return $=function j(O){var K=O.getOptions,B=O.getCaretPosition,he=O.getCaretPositionEnd,I=O.dispatch;(function(V,Q){if(!(V instanceof Q))throw new TypeError("Cannot call a class as a function")})(this,j),b(this,"getOptions",void 0),b(this,"getCaretPosition",void 0),b(this,"getCaretPositionEnd",void 0),b(this,"dispatch",void 0),b(this,"maxLengthReached",void 0),b(this,"isStandardButton",(function(V){return V&&!(V[0]==="{"&&V[V.length-1]==="}")})),this.getOptions=K,this.getCaretPosition=B,this.getCaretPositionEnd=he,this.dispatch=I,j.bindMethods(j,this)},Y=[{key:"getButtonType",value:function(j){return j.includes("{")&&j.includes("}")&&j!=="{//}"?"functionBtn":"standardBtn"}},{key:"getButtonClass",value:function(j){var O=this.getButtonType(j),K=j.replace("{","").replace("}",""),B="";return O!=="standardBtn"&&(B=" hg-button-".concat(K)),"hg-".concat(O).concat(B)}},{key:"getDefaultDiplay",value:function(){return{"{bksp}":"backspace","{backspace}":"backspace","{enter}":"< enter","{shift}":"shift","{shiftleft}":"shift","{shiftright}":"shift","{alt}":"alt","{s}":"shift","{tab}":"tab","{lock}":"caps","{capslock}":"caps","{accept}":"Submit","{space}":" ","{//}":" ","{esc}":"esc","{escape}":"esc","{f1}":"f1","{f2}":"f2","{f3}":"f3","{f4}":"f4","{f5}":"f5","{f6}":"f6","{f7}":"f7","{f8}":"f8","{f9}":"f9","{f10}":"f10","{f11}":"f11","{f12}":"f12","{numpaddivide}":"/","{numlock}":"lock","{arrowup}":"↑","{arrowleft}":"←","{arrowdown}":"↓","{arrowright}":"→","{prtscr}":"print","{scrolllock}":"scroll","{pause}":"pause","{insert}":"ins","{home}":"home","{pageup}":"up","{delete}":"del","{forwarddelete}":"del","{end}":"end","{pagedown}":"down","{numpadmultiply}":"*","{numpadsubtract}":"-","{numpadadd}":"+","{numpadenter}":"enter","{period}":".","{numpaddecimal}":".","{numpad0}":"0","{numpad1}":"1","{numpad2}":"2","{numpad3}":"3","{numpad4}":"4","{numpad5}":"5","{numpad6}":"6","{numpad7}":"7","{numpad8}":"8","{numpad9}":"9"}}},{key:"getButtonDisplayName",value:function(j,O){return(O=arguments.length>2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),O):O||this.getDefaultDiplay())[j]||j}},{key:"getUpdatedInput",value:function(j,O,K){var B=arguments.length>3&&arguments[3]!==void 0?arguments[3]:K,he=arguments.length>4&&arguments[4]!==void 0&&arguments[4],I=this.getOptions(),V=[K,B,he],Q=O;return(j==="{bksp}"||j==="{backspace}")&&Q.length>0?Q=this.removeAt.apply(this,[Q].concat(V)):(j==="{delete}"||j==="{forwarddelete}")&&Q.length>0?Q=this.removeForwardsAt.apply(this,[Q].concat(V)):j==="{space}"?Q=this.addStringAt.apply(this,[Q," "].concat(V)):j!=="{tab}"||typeof I.tabCharOnTab=="boolean"&&I.tabCharOnTab===!1?j!=="{enter}"&&j!=="{numpadenter}"||!I.newLineOnEnter?j.includes("numpad")&&Number.isInteger(Number(j[j.length-2]))?Q=this.addStringAt.apply(this,[Q,j[j.length-2]].concat(V)):j==="{numpaddivide}"?Q=this.addStringAt.apply(this,[Q,"/"].concat(V)):j==="{numpadmultiply}"?Q=this.addStringAt.apply(this,[Q,"*"].concat(V)):j==="{numpadsubtract}"?Q=this.addStringAt.apply(this,[Q,"-"].concat(V)):j==="{numpadadd}"?Q=this.addStringAt.apply(this,[Q,"+"].concat(V)):j==="{numpaddecimal}"?Q=this.addStringAt.apply(this,[Q,"."].concat(V)):j==="{"||j==="}"?Q=this.addStringAt.apply(this,[Q,j].concat(V)):j.includes("{")||j.includes("}")||(Q=this.addStringAt.apply(this,[Q,j].concat(V))):Q=this.addStringAt.apply(this,[Q,`
- `].concat(V)):Q=this.addStringAt.apply(this,[Q," "].concat(V)),I.debug&&console.log("Input will be: "+Q),Q}},{key:"updateCaretPos",value:function(j){var O=arguments.length>1&&arguments[1]!==void 0&&arguments[1],K=this.updateCaretPosAction(j,O);this.dispatch((function(B){B.setCaretPosition(K)}))}},{key:"updateCaretPosAction",value:function(j){var O=arguments.length>1&&arguments[1]!==void 0&&arguments[1],K=this.getOptions(),B=this.getCaretPosition();return B!=null&&(O?B>0&&(B-=j):B+=j),K.debug&&console.log("Caret at:",B),B}},{key:"addStringAt",value:function(j,O){var K,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,he=arguments.length>3&&arguments[3]!==void 0?arguments[3]:j.length,I=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return B||B===0?(K=[j.slice(0,B),O,j.slice(he)].join(""),this.isMaxLengthReached()||I&&this.updateCaretPos(O.length)):K=j+O,K}},{key:"removeAt",value:function(j){var O,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j.length,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,he=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(K===0&&B===0)return j;if(K===B){var I=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;K&&K>=0?j.substring(K-2,K).match(I)?(O=j.substr(0,K-2)+j.substr(K),he&&this.updateCaretPos(2,!0)):(O=j.substr(0,K-1)+j.substr(K),he&&this.updateCaretPos(1,!0)):j.slice(-2).match(I)?(O=j.slice(0,-2),he&&this.updateCaretPos(2,!0)):(O=j.slice(0,-1),he&&this.updateCaretPos(1,!0))}else O=j.slice(0,K)+j.slice(B),he&&this.dispatch((function(V){V.setCaretPosition(K)}));return O}},{key:"removeForwardsAt",value:function(j){var O,K=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j.length,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:j.length,he=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return j!=null&&j.length&&K!==null?(K===B?O=j.substring(K,K+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?j.substr(0,K)+j.substr(K+2):j.substr(0,K)+j.substr(K+1):(O=j.slice(0,K)+j.slice(B),he&&this.dispatch((function(I){I.setCaretPosition(K)}))),O):j}},{key:"handleMaxLength",value:function(j,O){var K=this.getOptions(),B=K.maxLength,he=j[K.inputName||"default"],I=O.length-1>=B;if(O.length<=he.length)return!1;if(Number.isInteger(B))return K.debug&&console.log("maxLength (num) reached:",I),I?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(v(B)==="object"){var V=O.length-1>=B[K.inputName||"default"];return K.debug&&console.log("maxLength (obj) reached:",V),V?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1)}}},{key:"isMaxLengthReached",value:function(){return!!this.maxLengthReached}},{key:"isTouchDevice",value:function(){return"ontouchstart"in window||navigator.maxTouchPoints}},{key:"pointerEventsSupported",value:function(){return!!window.PointerEvent}},{key:"camelCase",value:function(j){return j?j.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(O,K){return K.length?O+K[0].toUpperCase()+K.slice(1):O})):""}},{key:"chunkArray",value:function(j,O){return p(Array(Math.ceil(j.length/O))).map((function(K,B){return j.slice(O*B,O+O*B)}))}},{key:"escapeRegex",value:function(j){return j.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}},{key:"getRtlOffset",value:function(j,O){var K=j,B=O.indexOf("");return B<j&&B!=-1&&K--,O.indexOf("")<j&&B!=-1&&K--,K<0?0:K}},{key:"isConstructor",value:function(j){try{Reflect.construct(String,[],j)}catch{return!1}return!0}}],E=[{key:"bindMethods",value:function(j,O){var K,B=(function(I,V){var Q=typeof Symbol<"u"&&I[Symbol.iterator]||I["@@iterator"];if(!Q){if(Array.isArray(I)||(Q=f(I))||V){Q&&(I=Q);var G=0,J=function(){};return{s:J,n:function(){return G>=I.length?{done:!0}:{done:!1,value:I[G++]}},e:function(de){throw de},f:J}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var se,fe=!0,pe=!1;return{s:function(){Q=Q.call(I)},n:function(){var de=Q.next();return fe=de.done,de},e:function(de){pe=!0,se=de},f:function(){try{fe||Q.return==null||Q.return()}finally{if(pe)throw se}}}})(Object.getOwnPropertyNames(j.prototype));try{for(B.s();!(K=B.n()).done;){var he=K.value;he==="constructor"||he==="bindMethods"||(O[he]=O[he].bind(O))}}catch(I){B.e(I)}finally{B.f()}}}],Y&&g($.prototype,Y),E&&g($,E),Object.defineProperty($,"prototype",{writable:!1}),$;var $,Y,E})();b(C,"noop",(function(){}));var P=C;function N($){return N=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},N($)}function A($,Y){for(var E=0;E<Y.length;E++){var j=Y[E];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty($,F(j.key),j)}}function T($,Y,E){return(Y=F(Y))in $?Object.defineProperty($,Y,{value:E,enumerable:!0,configurable:!0,writable:!0}):$[Y]=E,$}function F($){var Y=(function(E,j){if(N(E)!="object"||!E)return E;var O=E[Symbol.toPrimitive];if(O!==void 0){var K=O.call(E,j);if(N(K)!="object")return K;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(E)})($,"string");return N(Y)=="symbol"?Y:Y+""}var k=(function(){return $=function j(O){var K=this,B=O.dispatch,he=O.getOptions;(function(I,V){if(!(I instanceof V))throw new TypeError("Cannot call a class as a function")})(this,j),T(this,"getOptions",void 0),T(this,"dispatch",void 0),T(this,"isModifierKey",(function(I){return I.altKey||I.ctrlKey||I.shiftKey||["Tab","CapsLock","Esc","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(I.code||I.key||K.keyCodeToKey(I?.keyCode))})),this.dispatch=B,this.getOptions=he,P.bindMethods(j,this)},Y=[{key:"handleHighlightKeyDown",value:function(j){var O=this.getOptions();O.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(j)&&(j.preventDefault(),j.stopImmediatePropagation());var K=this.getSimpleKeyboardLayoutKey(j);this.dispatch((function(B){var he,I,V=B.getButtonElement(K),Q=B.getButtonElement("{".concat(K,"}"));if(V)he=V,I=K;else{if(!Q)return;he=Q,I="{".concat(K,"}")}var G,J,se,fe,pe=function(U){U.style.background=O.physicalKeyboardHighlightBgColor||"#dadce4",U.style.color=O.physicalKeyboardHighlightTextColor||"black"};if(he)if(Array.isArray(he)){if(he.forEach((function(U){return pe(U)})),O.physicalKeyboardHighlightPress)if(O.physicalKeyboardHighlightPressUsePointerEvents)(G=he[0])===null||G===void 0||(J=G.onpointerdown)===null||J===void 0||J.call(G,j);else if(O.physicalKeyboardHighlightPressUseClick){var de;(de=he[0])===null||de===void 0||de.click()}else B.handleButtonClicked(I,j)}else pe(he),O.physicalKeyboardHighlightPress&&(O.physicalKeyboardHighlightPressUsePointerEvents?(se=he)===null||se===void 0||(fe=se.onpointerdown)===null||fe===void 0||fe.call(se,j):O.physicalKeyboardHighlightPressUseClick?he.click():B.handleButtonClicked(I,j))}))}},{key:"handleHighlightKeyUp",value:function(j){var O=this.getOptions();O.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(j)&&(j.preventDefault(),j.stopImmediatePropagation());var K=this.getSimpleKeyboardLayoutKey(j);this.dispatch((function(B){var he,I,V,Q=B.getButtonElement(K)||B.getButtonElement("{".concat(K,"}")),G=function(J){J.removeAttribute&&J.removeAttribute("style")};Q&&(Array.isArray(Q)?(Q.forEach((function(J){return G(J)})),O.physicalKeyboardHighlightPressUsePointerEvents&&((he=Q[0])===null||he===void 0||(I=he.onpointerup)===null||I===void 0||I.call(he,j))):(G(Q),O.physicalKeyboardHighlightPressUsePointerEvents&&(Q==null||(V=Q.onpointerup)===null||V===void 0||V.call(Q,j))))}))}},{key:"getSimpleKeyboardLayoutKey",value:function(j){var O,K="",B=j.code||j.key||this.keyCodeToKey(j?.keyCode);return(K=B!=null&&B.includes("Numpad")||B!=null&&B.includes("Shift")||B!=null&&B.includes("Space")||B!=null&&B.includes("Backspace")||B!=null&&B.includes("Control")||B!=null&&B.includes("Alt")||B!=null&&B.includes("Meta")?j.code||"":j.key||this.keyCodeToKey(j?.keyCode)||"").length>1?(O=K)===null||O===void 0?void 0:O.toLowerCase():K}},{key:"keyCodeToKey",value:function(j){return{8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"A",66:"B",67:"C",68:"D",69:"E",70:"F",71:"G",72:"H",73:"I",74:"J",75:"K",76:"L",77:"M",78:"N",79:"O",80:"P",81:"Q",82:"R",83:"S",84:"T",85:"U",86:"V",87:"W",88:"X",89:"Y",90:"Z",91:"Meta",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",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",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}[j]||""}}],Y&&A($.prototype,Y),E&&A($,E),Object.defineProperty($,"prototype",{writable:!1}),$;var $,Y,E})();function D($){return D=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},D($)}function H($,Y){for(var E=0;E<Y.length;E++){var j=Y[E];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty($,X(j.key),j)}}function z($,Y,E){return(Y=X(Y))in $?Object.defineProperty($,Y,{value:E,enumerable:!0,configurable:!0,writable:!0}):$[Y]=E,$}function X($){var Y=(function(E,j){if(D(E)!="object"||!E)return E;var O=E[Symbol.toPrimitive];if(O!==void 0){var K=O.call(E,j);if(D(K)!="object")return K;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(E)})($,"string");return D(Y)=="symbol"?Y:Y+""}var L=(function(){return $=function j(O){var K=O.utilities,B=O.options;(function(he,I){if(!(he instanceof I))throw new TypeError("Cannot call a class as a function")})(this,j),z(this,"utilities",void 0),z(this,"options",void 0),z(this,"candidateBoxElement",void 0),z(this,"pageIndex",0),z(this,"pageSize",void 0),this.utilities=K,this.options=B,P.bindMethods(j,this),this.pageSize=this.utilities.getOptions().layoutCandidatesPageSize||5},Y=[{key:"destroy",value:function(){this.candidateBoxElement&&(this.candidateBoxElement.remove(),this.pageIndex=0)}},{key:"show",value:function(j){var O=this,K=j.candidateValue,B=j.targetElement,he=j.onSelect;if(K&&K.length){var I=this.utilities.chunkArray(K.split(" "),this.pageSize);this.renderPage({candidateListPages:I,targetElement:B,pageIndex:this.pageIndex,nbPages:I.length,onItemSelected:function(V,Q){he(V,Q),O.destroy()}})}}},{key:"renderPage",value:function(j){var O,K=this,B=j.candidateListPages,he=j.targetElement,I=j.pageIndex,V=j.nbPages,Q=j.onItemSelected;(O=this.candidateBoxElement)===null||O===void 0||O.remove(),this.candidateBoxElement=document.createElement("div"),this.candidateBoxElement.className="hg-candidate-box";var G=document.createElement("ul");G.className="hg-candidate-box-list",B[I].forEach((function(R){var ae,_e=document.createElement("li"),Se=function(){var ye=new(K.options.useTouchEvents?TouchEvent:MouseEvent)("click");return Object.defineProperty(ye,"target",{value:_e}),ye};_e.className="hg-candidate-box-list-item",_e.innerHTML=((ae=K.options.display)===null||ae===void 0?void 0:ae[R])||R,K.options.useTouchEvents?_e.ontouchstart=function(ye){return Q(R,ye||Se())}:_e.onclick=function(){var ye=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Se();return Q(R,ye)},G.appendChild(_e)}));var J=I>0,se=document.createElement("div");se.classList.add("hg-candidate-box-prev"),J&&se.classList.add("hg-candidate-box-btn-active");var fe=function(){J&&K.renderPage({candidateListPages:B,targetElement:he,pageIndex:I-1,nbPages:V,onItemSelected:Q})};this.options.useTouchEvents?se.ontouchstart=fe:se.onclick=fe,this.candidateBoxElement.appendChild(se),this.candidateBoxElement.appendChild(G);var pe=I<V-1,de=document.createElement("div");de.classList.add("hg-candidate-box-next"),pe&&de.classList.add("hg-candidate-box-btn-active");var U=function(){pe&&K.renderPage({candidateListPages:B,targetElement:he,pageIndex:I+1,nbPages:V,onItemSelected:Q})};this.options.useTouchEvents?de.ontouchstart=U:de.onclick=U,this.candidateBoxElement.appendChild(de),he.prepend(this.candidateBoxElement)}}],Y&&H($.prototype,Y),E&&H($,E),Object.defineProperty($,"prototype",{writable:!1}),$;var $,Y,E})(),ne=L;function ie($){return(function(Y){if(Array.isArray(Y))return ee(Y)})($)||(function(Y){if(typeof Symbol<"u"&&Y[Symbol.iterator]!=null||Y["@@iterator"]!=null)return Array.from(Y)})($)||(function(Y,E){if(Y){if(typeof Y=="string")return ee(Y,E);var j={}.toString.call(Y).slice(8,-1);return j==="Object"&&Y.constructor&&(j=Y.constructor.name),j==="Map"||j==="Set"?Array.from(Y):j==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(j)?ee(Y,E):void 0}})($)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function ee($,Y){(Y==null||Y>$.length)&&(Y=$.length);for(var E=0,j=Array(Y);E<Y;E++)j[E]=$[E];return j}function ue($){return ue=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Y){return typeof Y}:function(Y){return Y&&typeof Symbol=="function"&&Y.constructor===Symbol&&Y!==Symbol.prototype?"symbol":typeof Y},ue($)}function le($,Y){var E=Object.keys($);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols($);Y&&(j=j.filter((function(O){return Object.getOwnPropertyDescriptor($,O).enumerable}))),E.push.apply(E,j)}return E}function oe($,Y){for(var E=0;E<Y.length;E++){var j=Y[E];j.enumerable=j.enumerable||!1,j.configurable=!0,"value"in j&&(j.writable=!0),Object.defineProperty($,re(j.key),j)}}function W($,Y,E){return(Y=re(Y))in $?Object.defineProperty($,Y,{value:E,enumerable:!0,configurable:!0,writable:!0}):$[Y]=E,$}function re($){var Y=(function(E,j){if(ue(E)!="object"||!E)return E;var O=E[Symbol.toPrimitive];if(O!==void 0){var K=O.call(E,j);if(ue(K)!="object")return K;throw new TypeError("@@toPrimitive must return a primitive value.")}return(j==="string"?String:Number)(E)})($,"string");return ue(Y)=="symbol"?Y:Y+""}var ce=(function(){return $=function j(O,K){var B=this;if((function(fe,pe){if(!(fe instanceof pe))throw new TypeError("Cannot call a class as a function")})(this,j),W(this,"input",void 0),W(this,"options",void 0),W(this,"utilities",void 0),W(this,"caretPosition",void 0),W(this,"caretPositionEnd",void 0),W(this,"keyboardDOM",void 0),W(this,"keyboardPluginClasses",void 0),W(this,"keyboardDOMClass",void 0),W(this,"buttonElements",void 0),W(this,"currentInstanceName",void 0),W(this,"allKeyboardInstances",void 0),W(this,"keyboardInstanceNames",void 0),W(this,"isFirstKeyboardInstance",void 0),W(this,"physicalKeyboard",void 0),W(this,"modules",void 0),W(this,"activeButtonClass",void 0),W(this,"holdInteractionTimeout",void 0),W(this,"holdTimeout",void 0),W(this,"isMouseHold",void 0),W(this,"initialized",void 0),W(this,"candidateBox",void 0),W(this,"keyboardRowsDOM",void 0),W(this,"defaultName","default"),W(this,"activeInputElement",null),W(this,"handleParams",(function(fe,pe){var de,U,R;if(typeof fe=="string")de=fe.split(".").join(""),U=document.querySelector(".".concat(de)),R=pe;else if(fe instanceof HTMLDivElement){if(!fe.className)throw console.warn("Any DOM element passed as parameter must have a class."),new Error("KEYBOARD_DOM_CLASS_ERROR");de=fe.className.split(" ")[0],U=fe,R=pe}else de="simple-keyboard",U=document.querySelector(".".concat(de)),R=fe;return{keyboardDOMClass:de,keyboardDOM:U,options:R}})),W(this,"getOptions",(function(){return B.options})),W(this,"getCaretPosition",(function(){return B.caretPosition})),W(this,"getCaretPositionEnd",(function(){return B.caretPositionEnd})),W(this,"registerModule",(function(fe,pe){B.modules[fe]||(B.modules[fe]={}),pe(B.modules[fe])})),W(this,"getKeyboardClassString",(function(){for(var fe=arguments.length,pe=new Array(fe),de=0;de<fe;de++)pe[de]=arguments[de];return[B.keyboardDOMClass].concat(pe).filter((function(U){return!!U})).join(" ")})),typeof window<"u"){var he=this.handleParams(O,K),I=he.keyboardDOMClass,V=he.keyboardDOM,Q=he.options,G=Q===void 0?{}:Q;this.utilities=new P({getOptions:this.getOptions,getCaretPosition:this.getCaretPosition,getCaretPositionEnd:this.getCaretPositionEnd,dispatch:this.dispatch}),this.caretPosition=null,this.caretPositionEnd=null,this.keyboardDOM=V,this.options=(function(fe){for(var pe=1;pe<arguments.length;pe++){var de=arguments[pe]!=null?arguments[pe]:{};pe%2?le(Object(de),!0).forEach((function(U){W(fe,U,de[U])})):Object.getOwnPropertyDescriptors?Object.defineProperties(fe,Object.getOwnPropertyDescriptors(de)):le(Object(de)).forEach((function(U){Object.defineProperty(fe,U,Object.getOwnPropertyDescriptor(de,U))}))}return fe})({layoutName:"default",theme:"hg-theme-default",inputName:"default",preventMouseDownDefault:!1,enableLayoutCandidates:!0,excludeFromLayout:{}},G),this.keyboardPluginClasses="",P.bindMethods(j,this);var J=this.options.inputName,se=J===void 0?this.defaultName:J;if(this.input={},this.input[se]="",this.keyboardDOMClass=I,this.buttonElements={},window.SimpleKeyboardInstances||(window.SimpleKeyboardInstances={}),this.currentInstanceName=this.utilities.camelCase(this.keyboardDOMClass),window.SimpleKeyboardInstances[this.currentInstanceName]=this,this.allKeyboardInstances=window.SimpleKeyboardInstances,this.keyboardInstanceNames=Object.keys(window.SimpleKeyboardInstances),this.isFirstKeyboardInstance=this.keyboardInstanceNames[0]===this.currentInstanceName,this.physicalKeyboard=new k({dispatch:this.dispatch,getOptions:this.getOptions}),this.candidateBox=this.options.enableLayoutCandidates?new ne({utilities:this.utilities,options:this.options}):null,!this.keyboardDOM)throw console.warn('".'.concat(I,'" was not found in the DOM.')),new Error("KEYBOARD_DOM_ERROR");this.render(),this.modules={},this.loadModules()}},Y=[{key:"setCaretPosition",value:function(j){var O=arguments.length>1&&arguments[1]!==void 0?arguments[1]:j;this.caretPosition=j,this.caretPositionEnd=O}},{key:"getInputCandidates",value:function(j){var O=this,K=this.options,B=K.layoutCandidates,he=K.layoutCandidatesCaseSensitiveMatch;if(!B||ue(B)!=="object")return{};var I=Object.keys(B).filter((function(G){var J=j.substring(0,O.getCaretPositionEnd()||0)||j,se=new RegExp("".concat(O.utilities.escapeRegex(G),"$"),he?"g":"gi");return!!ie(J.matchAll(se)).length}));if(I.length>1){var V=I.sort((function(G,J){return J.length-G.length}))[0];return{candidateKey:V,candidateValue:B[V]}}if(I.length){var Q=I[0];return{candidateKey:Q,candidateValue:B[Q]}}return{}}},{key:"showCandidatesBox",value:function(j,O,K){var B=this;this.candidateBox&&this.candidateBox.show({candidateValue:O,targetElement:K,onSelect:function(he,I){var V=B.options,Q=V.layoutCandidatesCaseSensitiveMatch,G=V.disableCandidateNormalization,J=V.enableLayoutCandidatesKeyPress,se=he;G||(se=he.normalize("NFD")),typeof B.options.beforeInputUpdate=="function"&&B.options.beforeInputUpdate(B);var fe=B.getInput(B.options.inputName,!0),pe=B.getCaretPositionEnd()||0,de=fe.substring(0,pe||0)||fe,U=new RegExp("".concat(B.utilities.escapeRegex(j),"$"),Q?"g":"gi"),R=de.replace(U,se),ae=fe.replace(de,R),_e=R.length-de.length,Se=(pe||fe.length)+_e;Se<0&&(Se=0),B.setInput(ae,B.options.inputName,!0),B.setCaretPosition(Se),J&&typeof B.options.onKeyPress=="function"&&B.options.onKeyPress(he,I),typeof B.options.onChange=="function"&&B.options.onChange(B.getInput(B.options.inputName,!0),I),typeof B.options.onChangeAll=="function"&&B.options.onChangeAll(B.getAllInputs(),I)}})}},{key:"handleButtonClicked",value:function(j,O){var K=this.options,B=K.inputName,he=B===void 0?this.defaultName:B,I=K.debug;if(j!=="{//}"){this.input[he]||(this.input[he]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var V=this.utilities.getUpdatedInput(j,this.input[he],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(j)&&this.activeInputElement&&this.input[he]&&this.input[he]===V&&this.caretPosition===0&&this.caretPositionEnd===V.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(j,O);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(j,O),this.input[he]!==V&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid(V))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,V))return;var Q=this.utilities.getUpdatedInput(j,this.input[he],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(Q,this.options.inputName,!0),I&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),O?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),O),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),O),O!=null&&O.target&&this.options.enableLayoutCandidates){var G,J=this.getInputCandidates(V),se=J.candidateKey,fe=J.candidateValue;se&&fe?this.showCandidatesBox(se,fe,this.keyboardDOM):(G=this.candidateBox)===null||G===void 0||G.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log("Caret position aligned",this.caretPosition)),I&&console.log("Key pressed:",j)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(j){this.options.syncInstanceInputs?this.dispatch((function(O){O.isMouseHold=j})):this.isMouseHold=j}},{key:"handleButtonMouseDown",value:function(j,O){var K=this;O&&(this.options.preventMouseDownDefault&&O.preventDefault(),this.options.stopMouseDownPropagation&&O.stopPropagation(),O.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(K.getMouseHold()&&(!j.includes("{")&&!j.includes("}")||j==="{delete}"||j==="{backspace}"||j==="{bksp}"||j==="{space}"||j==="{tab}")||j==="{arrowright}"||j==="{arrowleft}"||j==="{arrowup}"||j==="{arrowdown}")&&(K.options.debug&&console.log("Button held:",j),K.handleButtonHold(j)),clearTimeout(K.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(j,O){var K=this;O&&(this.options.preventMouseUpDefault&&O.preventDefault&&O.preventDefault(),this.options.stopMouseUpPropagation&&O.stopPropagation&&O.stopPropagation(),!(O.target===this.keyboardDOM||O.target&&this.keyboardDOM.contains(O.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(O.target===this.candidateBox.candidateBoxElement||O.target&&this.candidateBox.candidateBoxElement.contains(O.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(B){B.classList.remove(K.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),j&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(j,O)}},{key:"handleKeyboardContainerMouseDown",value:function(j){this.options.preventMouseDownDefault&&j.preventDefault()}},{key:"handleButtonHold",value:function(j){var O=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){O.getMouseHold()?(O.handleButtonClicked(j),O.handleButtonHold(j)):clearTimeout(O.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var j=this;this.dispatch((function(O){O.replaceInput(j.input),O.setCaretPosition(j.caretPosition,j.caretPositionEnd)}))}},{key:"clearInput",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[j]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,O=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!O&&this.syncInstanceInputs(),this.options.rtl?""+this.input[j].replace("","").replace("","")+"":this.input[j]}},{key:"getAllInputs",value:function(){var j=this,O={};return Object.keys(this.input).forEach((function(K){O[K]=j.getInput(K,!0)})),O}},{key:"setInput",value:function(j){var O=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,K=arguments.length>2?arguments[2]:void 0;this.input[O]=j,!K&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(j){this.input=j}},{key:"setOptions",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=this.changedOptions(j);this.options=Object.assign(this.options,j),O.length&&(this.options.debug&&console.log("changedOptions",O),this.onSetOptions(O),this.render())}},{key:"changedOptions",value:function(j){var O=this;return Object.keys(j).filter((function(K){return JSON.stringify(j[K])!==JSON.stringify(O.options[K])}))}},{key:"onSetOptions",value:function(){var j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];j.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(j.includes("layoutCandidatesPageSize")||j.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new ne({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(j){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(O){j(window.SimpleKeyboardInstances[O],O)}))}},{key:"addButtonTheme",value:function(j,O){var K=this;O&&j&&(j.split(" ").forEach((function(B){O.split(" ").forEach((function(he){K.options.buttonTheme||(K.options.buttonTheme=[]);var I=!1;K.options.buttonTheme.map((function(V){if(V!=null&&V.class.split(" ").includes(he)){I=!0;var Q=V.buttons.split(" ");Q.includes(B)||(I=!0,Q.push(B),V.buttons=Q.join(" "))}return V})),I||K.options.buttonTheme.push({class:he,buttons:j})}))})),this.render())}},{key:"removeButtonTheme",value:function(j,O){var K=this;if(!j&&!O)return this.options.buttonTheme=[],void this.render();j&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(j.split(" ").forEach((function(B){var he;(he=K.options)===null||he===void 0||(he=he.buttonTheme)===null||he===void 0||he.map((function(I,V){if(I&&O&&O.includes(I.class)||!O){var Q,G,J=(Q=I)===null||Q===void 0?void 0:Q.buttons.split(" ").filter((function(se){return se!==B}));I&&J!=null&&J.length?I.buttons=J.join(" "):((G=K.options.buttonTheme)===null||G===void 0||G.splice(V,1),I=null)}return I}))})),this.render())}},{key:"getButtonElement",value:function(j){var O,K=this.buttonElements[j];return K&&(O=K.length>1?K:K[0]),O}},{key:"inputPatternIsValid",value:function(j){var O,K=this.options.inputPattern;if((O=K instanceof RegExp?K:K[this.options.inputName||this.defaultName])&&j){var B=O.test(j);return this.options.debug&&console.log('inputPattern ("'.concat(O,'"): ').concat(B?"passed":"did not pass!")),B}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var j=this.options.physicalKeyboardHighlightPreventDefault,O=j!==void 0&&j;document.addEventListener("keyup",this.handleKeyUp,O),document.addEventListener("keydown",this.handleKeyDown,O),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(j){this.caretEventHandler(j),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(j)}},{key:"handleKeyDown",value:function(j){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(j)}},{key:"handleMouseUp",value:function(j){this.caretEventHandler(j)}},{key:"handleTouchEnd",value:function(j){this.caretEventHandler(j)}},{key:"handleSelect",value:function(j){this.caretEventHandler(j)}},{key:"handleSelectionChange",value:function(j){navigator.userAgent.includes("Firefox")||this.caretEventHandler(j)}},{key:"caretEventHandler",value:function(j){var O,K=this;j.target.tagName&&(O=j.target.tagName.toLowerCase()),this.dispatch((function(B){var he=j.target===B.keyboardDOM||j.target&&B.keyboardDOM.contains(j.target);if(K.options.syncInstanceInputs&&Array.isArray(j.path)&&(he=j.path.some((function(Q){var G;return Q==null||(G=Q.hasAttribute)===null||G===void 0?void 0:G.call(Q,"data-skInstance")}))),(O==="textarea"||O==="input"&&["text","search","url","tel","password"].includes(j.target.type))&&!B.options.disableCaretPositioning){var I=j.target.selectionStart,V=j.target.selectionEnd;B.options.rtl&&(I=B.utilities.getRtlOffset(I,B.getInput()),V=B.utilities.getRtlOffset(V,B.getInput())),B.setCaretPosition(I,V),B.activeInputElement=j.target,B.options.debug&&console.log("Caret at: ",B.getCaretPosition(),B.getCaretPositionEnd(),j&&j.target.tagName.toLowerCase(),"(".concat(B.keyboardDOMClass,")"),j?.type)}else!B.options.disableCaretPositioning&&he||j?.type==="selectionchange"||(B.setCaretPosition(null),B.activeInputElement=null,B.options.debug&&console.log('Caret position reset due to "'.concat(j?.type,'" event'),j))}))}},{key:"recurseButtons",value:function(j){var O=this;j&&Object.keys(this.buttonElements).forEach((function(K){return O.buttonElements[K].forEach(j)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var j=this.options.physicalKeyboardHighlightPreventDefault,O=j!==void 0&&j;document.removeEventListener("keyup",this.handleKeyUp,O),document.removeEventListener("keydown",this.handleKeyDown,O),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("touchend",this.handleTouchEnd),document.removeEventListener("select",this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener("selectionchange",this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(K){K&&(K.onpointerdown=null,K.onpointerup=null,K.onpointercancel=null,K.ontouchstart=null,K.ontouchend=null,K.ontouchcancel=null,K.onclick=null,K.onmousedown=null,K.onmouseup=null,K.remove(),K=null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=null),this.activeInputElement=null,this.keyboardDOM.removeAttribute("data-skInstance"),this.keyboardDOM.innerHTML="",window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:"getButtonThemeClasses",value:function(j){var O=this.options.buttonTheme,K=[];return Array.isArray(O)&&O.forEach((function(B){if(B&&B.class&&typeof B.class=="string"&&B.buttons&&typeof B.buttons=="string"){var he=B.class.split(" ");B.buttons.split(" ").includes(j)&&(K=[].concat(ie(K),ie(he)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',B)})),K}},{key:"setDOMButtonAttributes",value:function(j,O){var K=this.options.buttonAttributes;Array.isArray(K)&&K.forEach((function(B){B.attribute&&typeof B.attribute=="string"&&B.value&&typeof B.value=="string"?B.buttons&&typeof B.buttons=="string"?B.buttons.split(" ").includes(j)&&O(B.attribute,B.value):O(B.attribute,B.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',B)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(j){var O;if((O=j.target.classList)!==null&&O!==void 0&&O.contains("hg-button"))return j.preventDefault(),j.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var j=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(O){var K=j.utilities.isConstructor(O)?new O(j):O(j);K.init&&K.init(j)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(j,O){return!!this.modules[j]&&this.modules[j][O]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(j,O,K,B){var he=this,I=Array.from(j.children),V=0;return I.length&&K.forEach((function(Q,G){var J=B[G];if(!(J&&J>Q))return!1;var se=Q-V,fe=J-V,pe=document.createElement("div");pe.className+="hg-button-container";var de="".concat(he.options.layoutName,"-r").concat(O,"c").concat(G);pe.setAttribute("data-skUID",de);var U=I.splice(se,fe-se+1);V+=fe-se,U.forEach((function(R){return pe.appendChild(R)})),I.splice(se,0,pe),j.innerHTML="",I.forEach((function(R){return j.appendChild(R)})),he.options.debug&&console.log("rowDOMContainer",U,se,fe,V+1)})),j}},{key:"render",value:function(){var j=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var O="hg-layout-".concat(this.options.layoutName),K=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","{lock} a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}",".com @ {space}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'{lock} A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}",".com @ {space}"]},B=this.options.useTouchEvents||!1,he=B?"hg-touch-events":"",I=this.options.useMouseEvents||!1,V=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,O,this.keyboardPluginClasses,he),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",K[this.options.layoutName||this.defaultName].forEach((function(Q,G){var J=Q.split(" ");j.options.excludeFromLayout&&j.options.excludeFromLayout[j.options.layoutName||j.defaultName]&&(J=J.filter((function(de){return j.options.excludeFromLayout&&!j.options.excludeFromLayout[j.options.layoutName||j.defaultName].includes(de)})));var se=document.createElement("div");se.className+="hg-row";var fe=[],pe=[];J.forEach((function(de,U){var R,ae=!V&&typeof de=="string"&&de.length>1&&de.indexOf("[")===0,_e=!V&&typeof de=="string"&&de.length>1&&de.indexOf("]")===de.length-1;ae&&(fe.push(U),de=de.replace(/\[/g,"")),_e&&(pe.push(U),de=de.replace(/\]/g,""));var Se=j.utilities.getButtonClass(de),ye=j.utilities.getButtonDisplayName(de,j.options.display,j.options.mergeDisplay),Ae=j.options.useButtonTag?"button":"div",ve=document.createElement(Ae);ve.className+="hg-button ".concat(Se),(R=ve.classList).add.apply(R,ie(j.getButtonThemeClasses(de))),j.setDOMButtonAttributes(de,(function(Ee,Te){ve.setAttribute(Ee,Te)})),j.activeButtonClass="hg-activeButton",!j.utilities.pointerEventsSupported()||B||I?B?(ve.ontouchstart=function(Ee){j.handleButtonClicked(de,Ee),j.handleButtonMouseDown(de,Ee)},ve.ontouchend=function(Ee){j.handleButtonMouseUp(de,Ee)},ve.ontouchcancel=function(Ee){j.handleButtonMouseUp(de,Ee)}):(ve.onclick=function(Ee){j.setMouseHold(!1),typeof j.options.onKeyReleased=="function"||j.options.useMouseEvents&&j.options.clickOnMouseDown||j.handleButtonClicked(de,Ee)},ve.onmousedown=function(Ee){(typeof j.options.onKeyReleased=="function"||j.options.useMouseEvents&&j.options.clickOnMouseDown)&&!j.isMouseHold&&j.handleButtonClicked(de,Ee),j.handleButtonMouseDown(de,Ee)},ve.onmouseup=function(Ee){j.handleButtonMouseUp(de,Ee)}):(ve.onpointerdown=function(Ee){j.handleButtonClicked(de,Ee),j.handleButtonMouseDown(de,Ee)},ve.onpointerup=function(Ee){j.handleButtonMouseUp(de,Ee)},ve.onpointercancel=function(Ee){j.handleButtonMouseUp(de,Ee)}),ve.setAttribute("data-skBtn",de);var je="".concat(j.options.layoutName,"-r").concat(G,"b").concat(U);ve.setAttribute("data-skBtnUID",je);var Re=document.createElement("span");Re.innerHTML=ye,ve.appendChild(Re),j.buttonElements[de]||(j.buttonElements[de]=[]),j.buttonElements[de].push(ve),se.appendChild(ve)})),se=j.parseRowDOMContainers(se,G,fe,pe),j.keyboardRowsDOM.appendChild(se)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||B||I?B?(document.ontouchend=function(Q){return j.handleButtonMouseUp(void 0,Q)},document.ontouchcancel=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.ontouchstart=function(Q){return j.handleKeyboardContainerMouseDown(Q)}):B||(document.onmouseup=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.onmousedown=function(Q){return j.handleKeyboardContainerMouseDown(Q)}):(document.onpointerup=function(Q){return j.handleButtonMouseUp(void 0,Q)},this.keyboardDOM.onpointerdown=function(Q){return j.handleKeyboardContainerMouseDown(Q)}),this.onInit())}}],Y&&oe($.prototype,Y),E&&oe($,E),Object.defineProperty($,"prototype",{writable:!1}),$;var $,Y,E})(),xe=ce,Ne=xe;return m})()},442:function(l){l.exports=n}},i={};function s(l){var c=i[l];if(c!==void 0)return c.exports;var d=i[l]={exports:{}};return r[l].call(d.exports,d,d.exports,s),d.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var d in c)s.o(c,d)&&!s.o(l,d)&&Object.defineProperty(l,d,{enumerable:!0,get:c[d]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return g}}),s(981);var l=s(442),c=s(548),d=s.n(c);function u(b){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},u(b)}function m(b,_){var C=Object.keys(b);if(Object.getOwnPropertySymbols){var P=Object.getOwnPropertySymbols(b);_&&(P=P.filter((function(N){return Object.getOwnPropertyDescriptor(b,N).enumerable}))),C.push.apply(C,P)}return C}function p(b){for(var _=1;_<arguments.length;_++){var C=arguments[_]!=null?arguments[_]:{};_%2?m(Object(C),!0).forEach((function(P){f(b,P,C[P])})):Object.getOwnPropertyDescriptors?Object.defineProperties(b,Object.getOwnPropertyDescriptors(C)):m(Object(C)).forEach((function(P){Object.defineProperty(b,P,Object.getOwnPropertyDescriptor(C,P))}))}return b}function f(b,_,C){return(_=(function(P){var N=(function(A,T){if(u(A)!="object"||!A)return A;var F=A[Symbol.toPrimitive];if(F!==void 0){var k=F.call(A,T);if(u(k)!="object")return k;throw new TypeError("@@toPrimitive must return a primitive value.")}return(T==="string"?String:Number)(A)})(P,"string");return u(N)=="symbol"?N:N+""})(_))in b?Object.defineProperty(b,_,{value:C,enumerable:!0,configurable:!0,writable:!0}):b[_]=C,b}var x=function(b){return p(p({},b),{},{keyboardRef:null})},v=function(b){var _=b.baseClass||"react-simple-keyboard",C=l.useRef(null),P=l.useRef(null),N=l.useRef(null),A=l.useRef(b);return l.useEffect((function(){return function(){N.current&&N.current.destroy(),C.current=!1}}),[]),l.useEffect((function(){var T=(function(z){return p(p({},z),{},{theme:"simple-keyboard ".concat(z.theme||"hg-theme-default")})})(b);if(!C.current){C.current=!0,T.debug&&console.log("ReactSimpleKeyboard: Init");var F=P.current,k=".".concat(_);N.current=new(d())(F||k,T),T.keyboardRef&&T.keyboardRef(N.current)}var D=(function(z,X){var L=x(X),ne=x(z);return Object.keys(L).filter((function(ie){return L[ie]!==ne[ie]}))})(A.current,T);if(D.length){var H=N.current;A.current=T,H?.setOptions(T),T.debug&&console.log("ReactSimpleKeyboard - setOptions called due to updated props:",D)}}),[C,_,A,b]),l.createElement("div",{className:_,ref:P})},g=v})(),o})()}))})(Qk)),Qk.exports}var aat=rat();const iat=mc(aat),sat=new Set(["text","password","email","search","url","number"]);function k3(t,e){(Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set??Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set)?.call(t,e),t.dispatchEvent(new Event("input",{bubbles:!0}))}function oat({onVisibilityChange:t}){const[e,n]=w.useState(!1),[r,i]=w.useState(!1),s=w.useRef(!1),[o,l]=w.useState("default"),c=w.useRef(null),d=w.useRef(null),u=w.useRef(null);w.useEffect(()=>{t?.(e)},[e,t]);const m=w.useCallback(v=>{if(s.current)return;const g=v.target;if(!g.closest('[data-vkb="false"]')){if(g instanceof HTMLInputElement){if(!sat.has(g.type))return}else if(!(g instanceof HTMLTextAreaElement))return;c.current=g,n(!0),l("default"),d.current?.setInput?.(c.current.value),setTimeout(()=>{(g.closest(".bg-zinc-800, .rounded-lg, [data-vkb-group]")??g).scrollIntoView({behavior:"smooth",block:"nearest"})},100)}},[]),p=w.useCallback(()=>{setTimeout(()=>{const v=document.activeElement;v&&(u.current?.contains(v)||v===c.current)||(n(!1),c.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",m),document.addEventListener("focusout",p),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",p)}),[m,p]);const f=w.useCallback(()=>{s.current=!0,i(!0),c.current?.blur(),c.current=null,setTimeout(()=>{n(!1),i(!1),s.current=!1},400)},[]),x=w.useCallback(v=>{const g=c.current;if(g){if(v==="{shift}"){l(b=>b==="default"?"shift":"default");return}if(v==="{lock}"){l(b=>b==="default"?"shift":"default");return}if(v==="{close}"){f();return}v==="{bksp}"?k3(g,g.value.slice(0,-1)):v==="{space}"?k3(g,g.value+" "):(k3(g,g.value+v),o==="shift"&&l("default")),g.focus(),d.current?.setInput?.(g.value)}},[o,f]);return e?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:v=>{v.preventDefault(),v.stopPropagation(),r||f()},onTouchStart:v=>{v.preventDefault(),v.stopPropagation(),r||f()},onClick:v=>{v.preventDefault(),v.stopPropagation()}}),!r&&a.jsx("div",{ref:u,className:"relative z-[9999] shrink-0",onMouseDown:v=>v.preventDefault(),onTouchStart:v=>{v.target.closest(".hg-button")||v.preventDefault()},children:a.jsx(iat,{keyboardRef:v=>{d.current=v},layoutName:o,onKeyPress:x,theme:"simple-keyboard vkb-theme",layout:{default:["1 2 3 4 5 6 7 8 9 0 {bksp}","q w e r t y u i o p","{lock} a s d f g h j k l","{shift} z x c v b n m . @","{space} {close}"],shift:["! @ # $ % ^ & * ( ) {bksp}","Q W E R T Y U I O P","{lock} A S D F G H J K L","{shift} Z X C V B N M , _","{space} {close}"]},display:{"{bksp}":"⌫","{close}":"✕ Close","{shift}":"⇧","{lock}":"⇪","{space}":" "}})})]}):null}function lat(){GQ();const[t,e]=w.useState(null),[n,r]=w.useState(null),[i,s]=w.useState(100),{i18n:o}=Rt(),l=Do(),c=$c(),d=tat(),{data:u}=Qe({queryKey:["settings"],queryFn:me.getSettings});w.useEffect(()=>{u?.language&&u.language!==o.language&&o.changeLanguage(u.language)},[u?.language,o]);const{data:m=[]}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:3e4}),p=m[0],f=d.deviceOnline||!!p?.online,x=w.useMemo(()=>({...d,deviceOnline:f}),[d,f]),v=w.useRef(!1);w.useEffect(()=>{p&&!v.current&&(s(p.display_brightness),v.current=!0)},[p]),w.useEffect(()=>{const ue=document.documentElement,le=ue.classList.contains("dark");return ue.classList.add("dark"),()=>{le||ue.classList.remove("dark")}},[]);const{data:g}=Qe({queryKey:["spoolbuddy-update-check",p?.device_id],queryFn:()=>p?Ur.checkDaemonUpdate(p.device_id):Promise.resolve(null),enabled:!!p,refetchInterval:300*1e3,staleTime:0}),b=w.useRef(null);w.useEffect(()=>{if(f)if(g?.update_available&&g.latest_version){const ue=`Update available: v${g.latest_version}`;r({type:"info",message:ue}),b.current=ue}else b.current&&(r(null),b.current=null);else{const ue="SpoolBuddy device disconnected";r({type:"warning",message:ue}),b.current=ue}},[f,g?.update_available,g?.latest_version]);const _=!!(d.matchedSpool||d.unknownTagUid),C=w.useRef(!1);w.useEffect(()=>{_&&!C.current&&c.pathname!=="/spoolbuddy"&&l("/spoolbuddy"),C.current=_},[_,c.pathname,l]);const{data:P=[]}=Qe({queryKey:["printers"],queryFn:()=>me.getPrinters()}),N=fp({queries:P.map(ue=>({queryKey:["printerStatus",ue.id],queryFn:()=>me.getPrinterStatus(ue.id),refetchInterval:1e4,select:le=>({connected:le?.connected})}))}),A=w.useMemo(()=>P.filter((ue,le)=>N[le]?.data?.connected),[P,N]),T=w.useRef(null),F=w.useRef(!1),k=50,D=w.useRef(null),H=w.useCallback(ue=>{T.current={x:ue.touches[0].clientX,y:ue.touches[0].clientY},F.current=!1},[]),z=w.useCallback(ue=>{if(!T.current)return;const le=ue.changedTouches[0].clientX-T.current.x,oe=ue.changedTouches[0].clientY-T.current.y,W=T.current.y;if(T.current=null,F.current=!1,oe>=k&&Math.abs(oe)>Math.abs(le)&&W<120){ie(!0);return}if(A.length<2||Math.abs(le)<k||Math.abs(oe)>Math.abs(le))return;const re=A.findIndex(xe=>xe.id===t),ce=le<0?(re+1)%A.length:(re-1+A.length)%A.length;e(A[ce].id)},[A,t,e]);w.useEffect(()=>{const ue=D.current;if(!ue)return;const le=oe=>{if(!T.current)return;const W=Math.abs(oe.touches[0].clientX-T.current.x),re=Math.abs(oe.touches[0].clientY-T.current.y);if(F.current){oe.preventDefault();return}W>10&&W>re&&(F.current=!0,oe.preventDefault())};return ue.addEventListener("touchmove",le,{passive:!1}),()=>ue.removeEventListener("touchmove",le)},[]);const[X,L]=w.useState(!1),[ne,ie]=w.useState(!1),ee=i<100?{filter:`brightness(${i/100})`}:void 0;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:D,"data-spoolbuddy-kiosk":!0,className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:{...ee,overscrollBehaviorX:"none"},onTouchStart:H,onTouchEnd:z,children:[a.jsx("button",{onClick:()=>ie(!0),className:"w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none","aria-label":"Open quick menu",children:a.jsx("div",{className:"w-8 h-0.5 rounded-full bg-zinc-600"})}),a.jsx(Krt,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:f}),a.jsx("main",{className:"flex-1 overflow-y-auto",children:a.jsx(nQ,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:x,setAlert:r,displayBrightness:i,setDisplayBrightness:s}})}),!X&&a.jsx(Qrt,{alert:n}),!X&&a.jsx(Yrt,{}),a.jsx(oat,{onVisibilityChange:L})]}),a.jsx(Zrt,{isOpen:ne,onClose:()=>ie(!1),deviceId:p?.device_id??null,deviceOnline:f})]})}function lA({color:t,isEmpty:e,size:n=32}){return e?a.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:a.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):a.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[a.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),a.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const cat="spoolbuddy-default-core-weight";function Yle(){try{const t=localStorage.getItem(cat);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function dat({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:i}){const{t:s}=Rt(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:Yle(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,x=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/x*100)):null,g=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,C=p!==null?p-_:null,P=C!==null?Math.abs(C)<=50:null,N=async()=>{if(e!==null){l(!0);try{await Ur.updateSpoolWeight(t.id,Math.round(e)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(A){console.error("Failed to sync weight:",A)}finally{l(!1)}}};return a.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[a.jsxs("div",{className:"flex items-start gap-5",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(lA,{color:u,isEmpty:!1,size:100}),v!==null&&a.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:g},children:[v,"%"]})]}),a.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),a.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),a.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",x,"g"]})]}),a.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),a.jsx("div",{className:"mt-2 max-w-xs",children:a.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:g}})})})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),a.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[x,"g"]})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?a.jsxs("span",{className:`flex items-center gap-1 font-mono ${P?"text-green-500":"text-yellow-500"}`,children:[p,"g",P?a.jsx(Rr,{className:"w-3.5 h-3.5"}):a.jsxs(a.Fragment,{children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),a.jsx("button",{onClick:N,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:a.jsx(cr,{className:"w-4 h-4"})})]})]}):a.jsx("span",{className:"text-zinc-500",children:"—"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),a.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),a.jsxs("div",{className:"flex gap-2 justify-center",children:[i&&a.jsx("button",{onClick:i,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),a.jsx("button",{onClick:N,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":i?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&a.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function uat({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:i,onClose:s}){const{t:o}=Rt(),l=n??Yle(),c=e!==null?Math.round(Math.max(0,e)):null,d=c!==null?Math.round(Math.max(0,c-l)):null;return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[a.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:a.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),a.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&a.jsxs("div",{className:"text-sm text-zinc-400",children:[a.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),d!==null&&d>0&&a.jsxs("span",{className:"text-zinc-500",children:[" • ~",d,"g filament"]})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[i&&a.jsx("button",{onClick:i,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&a.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[a.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&a.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function mat(t){return t?`#${t.slice(0,6)}`:"#808080"}function Qle(t){return!t.tray_type||t.tray_type===""}function hat(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function pat({className:t}){return a.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a.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 fat({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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 gat({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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 bat({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function xat({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),a.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 yat({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),a.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),a.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 Zle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,i;return t<=e?(r="#22a352",i=pat):t<=n?(r="#d4a017",i=fat):(r="#c62828",i=gat),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx(i,{className:"w-3 h-3.5"}),a.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function Jle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,i;return t<=e?(r="#22a352",i=bat):t<=n?(r="#d4a017",i=xat):(r="#c62828",i=yat),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx(i,{className:"w-3 h-3.5"}),a.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function a5({side:t}){return a.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function vat({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:i,onClick:s}){const o=Qle(t),l=mat(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,d=r===0&&c!==null&&c>0?null:r,u=i??d??c;return a.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[a.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&a.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),a.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&u!==null&&u>=0&&a.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:wx(u)}})}),a.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function ece({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:i,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],d=t.is_ams_ht,u=d?1:4;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-white font-medium text-base",children:hat(t.id)}),r&&i&&a.jsx(a5,{side:i})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&a.jsx(Jle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&a.jsx(Zle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),a.jsx("div",{className:`grid ${d?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:u}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return a.jsx(vat,{tray:f,slotIndex:p,isActive:e===p,fillOverride:o?.[`${t.id}-${p}`]??null,spoolmanFill:l?.[`${t.id}-${p}`]??null,onClick:n?()=>n(t.id,p,Qle(f)?null:f):void 0},p)})})]})}function N3(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function C3(t){return!t.tray_type||t.tray_type===""}function wat(t){return t?`#${t.slice(0,6)}`:"#808080"}const _P=t=>(t??"").trim().toUpperCase();function Sat(t,e){const n=_P(t),r=_P(e);return!n||!r?"none":n===r?"exact":r.includes(n)||n.includes(r)?"partial":"none"}function _at(t,e){const n=_P(t),r=_P(e);return!n||!r?!1:n===r}function tce({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:i}=Rt(),s=sn(),[o,l]=w.useState(null),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[x,v]=w.useState(null);w.useEffect(()=>{t&&(l(null),d(null),m(!1),f(null),v(null))},[t]);const g=w.useCallback(Ne=>{Ne.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)),[t,g]);const{data:b}=Qe({queryKey:["printerStatus",r],queryFn:()=>me.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:_}=Qe({queryKey:["printer",r],queryFn:()=>me.getPrinter(r),enabled:t&&r!==null}),{data:C}=Qe({queryKey:["settings"],queryFn:()=>me.getSettings(),enabled:t,staleTime:300*1e3}),{data:P}=Qe({queryKey:["spool-assignments",r],queryFn:()=>me.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),N=w.useMemo(()=>{const Ne={};if(!P)return Ne;for(const $ of P){const Y=$.spool;if(Y&&Y.label_weight>0&&Y.weight_used!=null){const E=Math.round(Math.max(0,Y.label_weight-Y.weight_used)/Y.label_weight*100);Ne[`${$.ams_id}-${$.tray_id}`]=E}}return Ne},[P]),A=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,T=b?.connected??!1,F=w.useMemo(()=>b?.ams??[],[b?.ams]),k=w.useMemo(()=>F.filter(Ne=>!Ne.is_ams_ht),[F]),D=w.useMemo(()=>F.filter(Ne=>Ne.is_ams_ht),[F]),H=w.useMemo(()=>[...b?.vt_tray??[]].sort((Ne,$)=>(Ne.id??254)-($.id??254)),[b?.vt_tray]),z=_?.nozzle_count===2||b?.temperatures?.nozzle_2!==void 0,X=w.useRef({});w.useEffect(()=>{b?.ams_extruder_map&&Object.keys(b.ams_extruder_map).length>0&&(X.current=b.ams_extruder_map)},[b?.ams_extruder_map]);const L=b?.ams_extruder_map&&Object.keys(b.ams_extruder_map).length>0?b.ams_extruder_map:X.current,ne=w.useCallback(Ne=>{if(!z)return null;const $=L[String(Ne)],Y=Ne>=128?Ne-128:Ne;return($!==void 0?$:Y)===1?"L":"R"},[z,L]),ie=it({mutationFn:async({amsId:Ne,trayId:$})=>{if(!r)throw new Error("No printer selected");await me.assignSpool({spool_id:n.id,printer_id:r,ams_id:Ne,tray_id:$})},onSuccess:()=>{d("success"),l(i("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:Ne=>{d("error"),l(Ne instanceof Error?Ne.message:i("spoolbuddy.modal.assignError","Failed to assign spool."))}}),ee=ie.isPending,ue=w.useCallback((Ne,$)=>{if(Ne===254||Ne===255){const E=Ne===254?254:254+$;return H.find(j=>(j.id??254)===E)||null}return F.find(E=>E.id===Ne)?.tray?.find(E=>E.id===$)||null},[F,H]),le=w.useCallback((Ne,$)=>Ne<=3?`${N3(Ne)} ${i("ams.slot","Slot")} ${$+1}`:Ne>=128&&Ne<=135?N3(Ne):Ne===254?i("printers.extL","Ext-L"):z?i("printers.extR","Ext-R"):i("printers.ext","Ext"),[i,z]),oe=w.useCallback((Ne,$)=>{d("info"),l(i("spoolbuddy.modal.assigning","Configuring slot...")),ie.mutate({amsId:Ne,trayId:$})},[ie,i]),W=w.useCallback((Ne,$)=>{if(!ee){if(!C?.disable_filament_warnings){const Y=ue(Ne,$);if(Y&&!C3(Y)){const E=Y.tray_sub_brands||Y.tray_type||"",j=Sat(n.material,E),O=n.slicer_filament_name||n.slicer_filament,K=Y.tray_type||"",B=_at(O,K);if(j!=="exact"||!B){let he="profile";j==="none"&&!B?he="material_profile":j==="partial"&&!B?he="partial_profile":j==="none"?he="material":j==="partial"&&(he="partial");const I=le(Ne,$);v({amsId:Ne,trayId:$}),f({type:he,spoolMaterial:n.material||"",trayMaterial:E||"",spoolProfile:O||void 0,trayProfile:K||void 0,location:I}),m(!0);return}}}oe(Ne,$)}},[ee,C?.disable_filament_warnings,n,ue,le,oe]),re=w.useCallback(()=>{x&&(m(!1),f(null),oe(x.amsId,x.trayId),v(null))},[x,oe]),ce=w.useMemo(()=>{const Ne=[];for(const $ of D){const Y=$.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},E=N[`${$.id}-0`]??null,j=Y.remain!=null&&Y.remain>=0?Y.remain:null,O=E===0&&j!==null&&j>0?null:E;Ne.push({key:`ht-${$.id}`,label:N3($.id),amsId:$.id,trayId:0,tray:Y,isEmpty:C3(Y),nozzleSide:ne($.id),effectiveFill:O??j})}for(const $ of H){const Y=$.id??254,E=Y-254,j=N[`255-${E}`]??null,O=$.remain!=null&&$.remain>=0?$.remain:null,K=j===0&&O!==null&&O>0?null:j;Ne.push({key:`ext-${Y}`,label:z?Y===254?i("printers.extL","Ext-L"):i("printers.extR","Ext-R"):i("printers.ext","Ext"),amsId:255,trayId:E,tray:$,isEmpty:C3($),nozzleSide:z?Y===254?"L":"R":null,effectiveFill:K??O})}return Ne},[D,H,z,i,ne,N]);if(!t)return null;const xe=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:xe}}),a.jsx("div",{className:"min-w-0",children:a.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[i("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),a.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),a.jsx("button",{onClick:e,disabled:ee,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),o&&a.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&a.jsx(dt,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&a.jsx(xr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&a.jsx(Na,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),a.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto",children:!T&&r?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsx("div",{className:"text-center text-white/50",children:a.jsx("p",{className:"text-lg mb-2",children:i("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):F.length===0&&H.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx(aa,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-lg mb-2",children:i("spoolbuddy.ams.noData","No AMS detected")}),a.jsx("p",{className:"text-sm",children:i("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):a.jsxs(a.Fragment,{children:[k.length>0&&a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:k.map(Ne=>a.jsx(ece,{unit:Ne,activeSlot:null,onConfigureSlot:($,Y)=>W(Ne.id,Y),isDualNozzle:z,nozzleSide:ne(Ne.id),thresholds:A,fillOverrides:N},Ne.id))}),ce.length>0&&a.jsx("div",{className:"flex gap-2 shrink-0",children:ce.map(({key:Ne,label:$,amsId:Y,trayId:E,tray:j,isEmpty:O,nozzleSide:K,effectiveFill:B})=>{const he=wat(j.tray_color);return a.jsxs("div",{onClick:()=>W(Y,E),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${ee?"opacity-50 pointer-events-none":""}`,children:[a.jsx("div",{className:"relative w-10 h-10 shrink-0",children:O?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:he}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:he,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-xs text-white/50 font-medium",children:$}),K&&a.jsx(a5,{side:K})]}),a.jsx("div",{className:"text-sm text-white/80 truncate",children:O?"Empty":j.tray_type||"?"})]}),!O&&B!=null&&B>=0&&a.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:a.jsx("div",{className:"w-full rounded-full",style:{height:`${B}%`,backgroundColor:wx(B)}})})]},Ne)})})]})}),a.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:a.jsx("button",{onClick:e,disabled:ee,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?i("spoolbuddy.dashboard.close","Close"):i("spoolbuddy.modal.cancel","Cancel")})})]}),u&&p&&(()=>{let Ne="";return p.type==="material"?Ne=i("inventory.assignMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type==="partial"?Ne=i("inventory.assignPartialMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type==="material_profile"?Ne=`${i("inventory.assignMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}
- ${i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})}`:p.type==="partial_profile"?Ne=`${i("inventory.assignPartialMismatchMessage",{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}
- ${i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})}`:p.type==="profile"&&(Ne=i("inventory.assignProfileMismatchMessage",{spoolProfile:p.spoolProfile||i("common.unknown"),trayProfile:p.trayProfile||i("common.unknown"),location:p.location})),a.jsx(_n,{title:i("inventory.assignMismatchTitle"),message:Ne,confirmText:i("inventory.assignMismatchConfirm"),variant:"warning",isLoading:ie.isPending,onConfirm:re,onCancel:()=>{ie.isPending||(m(!1),v(null),f(null))}})})()]})}function kat({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:i}){const{t:s}=Rt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),d=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(i(o),l(null))};return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:a.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),a.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),a.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[a.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?a.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):a.jsx("div",{className:"space-y-2",children:r.map(m=>a.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[a.jsx(lA,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),a.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),a.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),a.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[a.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),a.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}function kY(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Nat(t,e){const n=kY(t),r=kY(e);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}const NY=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Cat(){const{t}=Rt(),[e,n]=w.useState(0);w.useEffect(()=>{const i=setInterval(()=>{n(s=>(s+1)%NY.length)},5e3);return()=>clearInterval(i)},[]);const r=NY[e];return a.jsxs("div",{className:"flex flex-col items-center text-center",children:[a.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[a.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:[0,1].map(i=>a.jsx("div",{className:"absolute rounded-full border spoolbuddy-optimized-ping",style:{width:80,height:80,borderColor:`${r}4D`,transition:"border-color 140ms linear",animationDelay:`${i*.8}s`}},i))}),a.jsxs("div",{className:"relative overflow-hidden rounded-full",children:[a.jsx("div",{className:"absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow",style:{background:`radial-gradient(circle, ${r} 0%, transparent 70%)`}}),a.jsx("div",{className:"relative",style:{transition:"opacity 140ms linear"},children:a.jsx(lA,{color:r,isEmpty:!1,size:100})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),a.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),a.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),a.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Pat(){const{t}=Rt();return a.jsxs("div",{className:"flex flex-col items-center text-center",children:[a.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:a.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:a.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),a.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),a.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),a.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Tat(){const{sbState:t,selectedPrinterId:e}=iy(),{t:n}=Rt(),{showToast:r}=bn(),{data:i=[],refetch:s}=Qe({queryKey:["inventory-spools"],queryFn:()=>me.getSpools(!1)}),{data:o=[]}=Qe({queryKey:["printers"],queryFn:()=>me.getPrinters()}),l=fp({queries:o.map(re=>({queryKey:["printerStatus",re.id],queryFn:()=>me.getPrinterStatus(re.id),refetchInterval:1e4,select:ce=>({connected:ce?.connected})}))}),[c,d]=w.useState(null),[u,m]=w.useState(null),[p,f]=w.useState(null),[x,v]=w.useState(!1),[g,b]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(!1),A=t.matchedSpool?.tag_uid??t.unknownTagUid??null,T=t.weight,F=t.weightStable,k=w.useRef(null);T===null?k.current=null:(k.current===null||Math.abs(T-k.current)>=3||F)&&(k.current=T);const H=k.current,z=w.useMemo(()=>{if(t.matchedSpool?.id){const re=i.find(ce=>ce.id===t.matchedSpool?.id);if(re)return re}return c?i.find(re=>Nat(re.tag_uid,c))??null:null},[c,t.matchedSpool,i]),X=w.useMemo(()=>i.filter(re=>!re.tag_uid&&!re.archived_at),[i]);w.useEffect(()=>{if(A){const re=p===A;(c!==null&&c!==A||!re&&c!==A)&&(d(A),m(null),f(null)),!re&&T!==null&&F&&m(Math.round(Math.max(0,T)))}else p&&(d(null),f(null),m(null))},[A,T,F,c,p]);const L=()=>{f(c)},ne=async re=>{if(c)try{await me.linkTagToSpool(re.id,{tag_uid:c,tag_type:"generic",data_origin:"nfc_link"}),v(!1),s()}catch(ce){console.error("Failed to link tag:",ce)}},ie=async()=>{if(c){N(!0);try{const re=ue??u;await me.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:c,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:re!==null?Math.round(re):null,last_weighed_at:re!==null?new Date().toISOString():null})}catch(re){const ce=re instanceof Error?re.message:String(re);console.error("Failed to quick-add spool:",ce),r(ce||n("spoolbuddy.errors.quickAddFailed","Failed to add spool"),"error")}finally{C(!1),N(!1),s()}}},ue=T!==null&&(A===c||A===null&&c!==null)?T:null,le=i.length,oe=new Set(i.map(re=>re.material)).size,W=new Set(i.filter(re=>re.brand).map(re=>re.brand)).size;return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:le}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),a.jsx("div",{className:"w-px h-5 bg-zinc-700"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:oe}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),a.jsx("div",{className:"w-px h-5 bg-zinc-700"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xl font-bold text-zinc-100",children:W}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),a.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[a.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[a.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),a.jsxs("div",{className:"space-y-2.5",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500":"bg-red-500"}`}),a.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),a.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),a.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),a.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:H!==null?`${Math.abs(H)<=20?0:Math.round(Math.max(0,H))}g`:"—"})]}),a.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),a.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),a.jsx("span",{className:`text-sm font-medium ${A?"text-green-500":"text-zinc-500"}`,children:A?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),o.length>0&&a.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),a.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:o.map((re,ce)=>{const xe=l[ce]?.data?.connected??!1;return a.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${re.name} — ${xe?"Online":"Offline"}`,children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${xe?"bg-green-500":"bg-zinc-600"}`}),a.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:re.name})]},re.id)})})]})]}),a.jsx("div",{className:"w-7/12 min-h-0",children:a.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[a.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),a.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(z||t.matchedSpool)&&c&&p!==c?a.jsx(dat,{spool:(()=>{const re=z??t.matchedSpool;return{id:re.id,tag_uid:c,material:re.material,subtype:re.subtype,color_name:re.color_name,rgba:re.rgba,brand:re.brand,label_weight:re.label_weight,core_weight:re.core_weight,weight_used:re.weight_used}})(),scaleWeight:ue??u,onSyncWeight:()=>s(),onAssignToAms:()=>b(!0),onClose:L}):A&&c&&!z&&!t.matchedSpool&&p!==c?a.jsx(uat,{tagUid:c,scaleWeight:ue??u,onLinkSpool:X.length>0?()=>v(!0):void 0,onAddToInventory:()=>C(!0),onClose:L}):a.jsx(Cat,{}):a.jsx(Pat,{})})]})})]}),z&&c&&a.jsx(tce,{isOpen:g,onClose:()=>b(!1),spool:z,printerId:e}),c&&a.jsx(kat,{isOpen:x,onClose:()=>v(!1),tagId:c,untaggedSpools:X,onLink:ne}),_&&c&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:a.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),a.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[a.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),a.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),a.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),a.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:c}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:()=>C(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),a.jsx("button",{onClick:ie,disabled:P,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:P?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function CY(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Aat(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"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 af(t){return!t.tray_type||t.tray_type===""}function jat(t){return t?`#${t.slice(0,6)}`:"#808080"}function Mat(){const{selectedPrinterId:t,setAlert:e}=iy(),{t:n}=Rt(),r=sn(),{showToast:i}=bn(),{data:s}=Qe({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=Qe({queryKey:["printer",t],queryFn:()=>me.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=Qe({queryKey:["slotPresets",t],queryFn:()=>me.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=Qe({queryKey:["settings"],queryFn:()=>me.getSettings(),staleTime:300*1e3}),{data:d}=Qe({queryKey:["spoolman-status"],queryFn:me.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=Qe({queryKey:["linked-spools"],queryFn:me.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f}=Qe({queryKey:["spool-assignments",t],queryFn:()=>me.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),x=w.useMemo(()=>{const Q={};if(!f)return Q;for(const G of f){const J=G.spool;if(J&&J.label_weight>0&&J.weight_used!=null){const se=Math.round(Math.max(0,J.label_weight-J.weight_used)/J.label_weight*100);Q[`${G.ams_id}-${G.tray_id}`]=se}}return Q},[f]),v=o?.serial_number??"",g=w.useCallback((Q,G,J)=>{if(!p||!v)return null;const se=(J?.tray_uuid||J?.tag_uid||Eu(v,Q,G))?.toUpperCase(),fe=se?p[se]:void 0;return Uk(fe)},[p,v]),b=s?.connected??!1,_=w.useRef({});w.useEffect(()=>{t&&s?.ams&&s.ams.length>0&&(_.current[t]=s.ams)},[s?.ams,t]);const C=w.useMemo(()=>{const Q=s?.ams;return Q&&Q.length>0?Q:(t?_.current[t]:null)??[]},[s?.ams,t]),P=w.useMemo(()=>C.filter(Q=>!Q.is_ams_ht),[C]),N=w.useMemo(()=>C.filter(Q=>Q.is_ams_ht),[C]),A=w.useMemo(()=>{const Q={};if(!p||!v)return Q;for(const G of P)for(let J=0;J<(G.tray?.length??0);J++){const se=G.tray[J],fe=g(G.id,J,af(se)?null:se);fe!==null&&(Q[`${G.id}-${J}`]=fe)}return Q},[p,v,P,g]),T=w.useRef(void 0),F=s?.tray_now;F!==void 0&&F!==255?T.current=F:F===255&&(T.current=void 0);const k=F!==void 0&&F!==255?F:T.current,D=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,H=w.useMemo(()=>[...s?.vt_tray??[]].sort((Q,G)=>(Q.id??254)-(G.id??254)),[s?.vt_tray]),z=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,X=w.useRef({});w.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(X.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const L=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:X.current,ne=w.useCallback(Q=>{if(!D)return null;const G=L[String(Q)],J=Q>=128?Q-128:Q;return(G!==void 0?G:J)===1?"L":"R"},[D,L]),[ie,ee]=w.useState(null),[ue,le]=w.useState(null),[oe,W]=w.useState(null),[re,ce]=w.useState(null),xe=w.useCallback((Q,G)=>f?.find(J=>J.ams_id===Number(Q)&&J.tray_id===Number(G)),[f]),Ne=w.useCallback((Q,G,J)=>{if(!p||!v)return;const se=(J?.tray_uuid||J?.tag_uid||Eu(v,Q,G))?.toUpperCase();return se?p[se]:void 0},[p,v]),$=it({mutationFn:({printerId:Q,amsId:G,trayId:J})=>me.unassignSpool(Q,G,J),onSuccess:()=>{r.invalidateQueries({queryKey:["spool-assignments",t]}),i(n("inventory.unassignSuccess","Spool unassigned"),"success"),le(null)}}),Y=it({mutationFn:Q=>me.unlinkSpool(Q),onSuccess:Q=>{i(n("spoolman.unlinkSuccess")||Q?.message,"success"),r.invalidateQueries({queryKey:["linked-spools"]}),r.invalidateQueries({queryKey:["unlinked-spools"]}),le(null)},onError:Q=>{i(Q.message||n("spoolman.unlinkFailed"),"error")}}),E=w.useCallback(Q=>k===void 0?null:Q<=3&&Math.floor(k/4)===Q?k%4:Q>=128&&Q<=135&&k===Wx(Q,0,!1)?0:null,[k]),j=w.useCallback((Q,G,J)=>{const se=Q>=128?(Q-128)*4+G+64:Q*4+G,fe=l?.[se],pe=L[String(Q)],de=Q>=128?Q-128:Q,U=pe!==void 0?pe:de,R={amsId:Q,trayId:G,trayCount:J&&Q>=128?1:4,tray:J,trayType:J?.tray_type||void 0,trayColor:J?.tray_color||void 0,traySubBrands:J?.tray_sub_brands||void 0,trayInfoIdx:J?.tray_info_idx||void 0,extruderId:D?U:void 0,caliIdx:J?.cali_idx,savedPresetId:fe?.preset_id,location:`${CY(Q)} Slot ${G+1}`};le(R)},[l,L,D]),O=w.useCallback(Q=>{const G=Q.id??254,J=G-254,se=l?.[1020+J],fe={amsId:255,trayId:J,trayCount:1,tray:af(Q)?null:Q,trayType:Q.tray_type||void 0,trayColor:Q.tray_color||void 0,traySubBrands:Q.tray_sub_brands||void 0,trayInfoIdx:Q.tray_info_idx||void 0,extruderId:D?G===254?1:0:void 0,caliIdx:Q.cali_idx,savedPresetId:se?.preset_id,location:D?G===254?"Ext-L":"Ext-R":"External"};le(fe)},[l,D]),K=w.useCallback(()=>{if(!ue)return;const{tray:Q,location:G,...J}=ue;le(null),ee(J)},[ue]),B=w.useCallback(()=>{if(!ue||!t)return;const{amsId:Q,trayId:G,trayType:J,trayColor:se,location:fe}=ue;le(null),W({printerId:t,amsId:Q,trayId:G,trayInfo:{type:J||"",material:J,color:se?.slice(0,6)||"",location:fe}})},[ue,t]),he=w.useCallback(()=>{if(!ue||!t)return;const{amsId:Q,trayId:G,tray:J}=ue,se=(J?.tray_uuid||J?.tag_uid||Eu(v,Q,G))?.toUpperCase()||"";le(null),ce({tagUid:J?.tag_uid||se,trayUuid:J?.tray_uuid||"",printerId:t,amsId:Q,trayId:G})},[ue,t,v]),I=w.useCallback(()=>{if(!ue||!t)return;const{amsId:Q,trayId:G}=ue;$.mutate({printerId:t,amsId:Q,trayId:G})},[ue,t,$]);w.useEffect(()=>{if(!b&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const Q of C){const G=Q.tray||[];for(let J=0;J<G.length;J++){const se=G[J];if(se.remain!==null&&se.remain>=0&&se.remain<15&&se.tray_type){const fe=Q.id===254||Q.id===255,pe=!fe&&Q.id>=128,de=bS(Q.id,J,pe,fe);e({type:"warning",message:`Low Filament: ${se.tray_type} (${de}) - ${se.remain}% remaining`});return}}}e(null)},[C,b,t,e,n]);const V=w.useMemo(()=>{const Q=[];for(const G of N){const J=G.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},se=g(G.id,0,af(J)?null:J),fe=x[`${G.id}-0`]??null,pe=J.remain!=null&&J.remain>=0?J.remain:null,de=fe===0&&pe!==null&&pe>0?null:fe;Q.push({key:`ht-${G.id}`,label:CY(G.id),tray:J,isEmpty:af(J),isActive:E(G.id)===0,temp:G.temp,humidity:G.humidity,nozzleSide:ne(G.id),effectiveFill:se??de??pe,onClick:()=>j(G.id,0,af(J)?null:J)})}for(const G of H){const J=G.id??254,se=D&&k===254?J===254&&s?.active_extruder===1||J===255&&s?.active_extruder===0:k===J,fe=J-254,pe=g(255,fe,af(G)?null:G),de=x[`255-${fe}`]??null,U=G.remain!=null&&G.remain>=0?G.remain:null,R=de===0&&U!==null&&U>0?null:de;Q.push({key:`ext-${J}`,label:D?J===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:G,isEmpty:af(G),isActive:se,nozzleSide:null,effectiveFill:pe??R??U,onClick:()=>O(G)})}return Q},[N,H,D,k,s?.active_extruder,n,E,ne,j,O,x,g]);return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsx("div",{className:"flex-1 min-h-0",children:t?b?C.length===0&&H.length===0?a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx(aa,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),a.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):a.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:P.map(Q=>a.jsx(ece,{unit:Q,activeSlot:E(Q.id),onConfigureSlot:j,isDualNozzle:D,nozzleSide:ne(Q.id),thresholds:z,fillOverrides:x,spoolmanFillOverrides:A},Q.id))}),V.length>0&&a.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:V.map(({key:Q,label:G,tray:J,isEmpty:se,isActive:fe,temp:pe,humidity:de,nozzleSide:U,effectiveFill:R,onClick:ae})=>{const _e=jat(J.tray_color);return a.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${fe?"ring-2 ring-bambu-green":""}`,onClick:ae,children:[a.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[se?a.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:a.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):a.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:_e}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:_e,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),fe&&a.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:G}),U&&a.jsx(a5,{side:U})]}),a.jsx("div",{className:"text-sm text-white/80 truncate",children:se?"Empty":J.tray_type||"?"}),(pe!=null||de!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[pe!=null&&a.jsx(Jle,{temp:pe,goodThreshold:z?.tempGood,fairThreshold:z?.tempFair}),de!=null&&a.jsx(Zle,{humidity:de,goodThreshold:z?.humidityGood,fairThreshold:z?.humidityFair})]})]}),!se&&R!=null&&R>=0&&a.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:a.jsx("div",{className:"w-full rounded-full",style:{height:`${R}%`,backgroundColor:wx(R)}})})]},Q)})})]}):a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsx("div",{className:"text-center text-white/50",children:a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):a.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center text-white/50",children:[a.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),a.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ie&&t&&a.jsx(zae,{isOpen:!!ie,onClose:()=>ee(null),printerId:t,slotInfo:ie,printerModel:Aat(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}}),ue&&t&&(()=>{const Q=xe(ue.amsId,ue.trayId),G=Ne(ue.amsId,ue.trayId,ue.tray);return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>le(null)}),a.jsxs("div",{className:"relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[ue.trayColor&&a.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${ue.trayColor.slice(0,6)}`}}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:ue.location}),ue.traySubBrands&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",ue.traySubBrands,")"]})]}),a.jsx("button",{onClick:()=>le(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-2",children:[!u&&Q?.spool&&a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),a.jsxs("div",{className:"flex items-center gap-2",children:[Q.spool.rgba&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${Q.spool.rgba.substring(0,6)}`}}),a.jsxs("span",{className:"text-sm text-white",children:[Q.spool.brand?`${Q.spool.brand} `:"",Q.spool.material,Q.spool.color_name?` - ${Q.spool.color_name}`:""]})]})]}),u&&G&&a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("spoolman.linkedSpool","Linked spool")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",G.id,G.remaining_weight!=null?` (${Math.round(G.remaining_weight)}g)`:""]})})]}),a.jsxs("button",{onClick:K,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left",children:[a.jsx(jd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("configureAmsSlot.title")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Q?a.jsxs("button",{onClick:I,disabled:$.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[a.jsx(ap,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool","Unassign")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):a.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[a.jsx(ja,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(G?.id?a.jsxs("button",{onClick:()=>Y.mutate(G.id),disabled:Y.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[a.jsx(ap,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-amber-400 font-medium",children:n("spoolman.unlinkSpool")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):a.jsxs("button",{onClick:he,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[a.jsx(Ku,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:n("spoolman.linkToSpoolman")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),oe&&a.jsx(Iae,{isOpen:!!oe,onClose:()=>{W(null),r.invalidateQueries({queryKey:["spool-assignments",t]})},printerId:oe.printerId,amsId:oe.amsId,trayId:oe.trayId,trayInfo:oe.trayInfo}),re&&a.jsx(Oae,{isOpen:!!re,onClose:()=>ce(null),tagUid:re.tagUid,trayUuid:re.trayUuid,printerId:re.printerId,amsId:re.amsId,trayId:re.trayId})]})}function Eat({type:t,deviceId:e,onClose:n}){const{t:r}=Rt(),[i,s]=w.useState(!1),[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState(!1);w.useEffect(()=>{const x=v=>{v.key==="Escape"&&!i&&n()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[i,n]);const p=w.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(r("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device...
- `)),await Ur.queueDiagnostics(e,t);let x=null;const v=60;let g=0;for(;g<v&&!x;){await new Promise(b=>setTimeout(b,500));try{x=await Ur.getDiagnosticResult(e,t);break}catch{g++,g%4===0&&l(b=>b+".")}}if(!x)throw new Error("Diagnostic timed out - device did not report results");l(x.output),x.success||d(`Exit code: ${x.exit_code}`)}catch(x){d(x instanceof Error?x.message:"Unknown error"),l("")}finally{s(!1)}},[t,e,r]),f=t==="scale"?r("spoolbuddy.diagnostic.scaleTitle","Scale Diagnostic"):t==="read_tag"?r("spoolbuddy.diagnostic.readTagTitle","Read Tag Diagnostic"):r("spoolbuddy.diagnostic.nfcTitle","NFC Reader Diagnostic");return a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:n,children:a.jsxs("div",{className:"bg-zinc-800 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col animate-slide-up",onClick:x=>x.stopPropagation(),children:[a.jsxs("div",{className:"flex justify-between items-center p-4 border-b border-zinc-700",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:f}),a.jsx("button",{onClick:n,className:"text-zinc-400 hover:text-white transition-colors","aria-label":"Close",children:a.jsx(Bt,{size:20})})]}),a.jsx("div",{className:"flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm",children:i?a.jsxs("div",{className:"flex items-center gap-2 text-green-400",children:[a.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full"}),a.jsx("span",{children:r("spoolbuddy.diagnostic.running","Running diagnostic on device...")})]}):o?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"text-green-400 whitespace-pre-wrap break-words",children:o}),c&&a.jsxs("div",{className:"text-red-400 mt-2",children:["❌ ",c]})]}):u?a.jsx("div",{children:c?a.jsxs("div",{className:"text-red-400",children:["ERROR: ",c]}):a.jsx("span",{className:"text-green-400",children:r("spoolbuddy.diagnostic.completed","Diagnostic completed successfully.")})}):a.jsxs("div",{className:"text-zinc-500",children:[r("spoolbuddy.diagnostic.clickStart",'Click "Run Diagnostic" to start the hardware diagnostic on')," ",e,"."]})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800",children:[a.jsx("button",{onClick:p,disabled:i,className:"flex-1 flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed px-4 py-2 rounded font-semibold text-white transition-colors",children:i?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),r("spoolbuddy.diagnostic.runningBtn","Running...")]}):u?a.jsxs(a.Fragment,{children:[a.jsx(H0,{size:16}),r("spoolbuddy.diagnostic.runAgain","Run Again")]}):a.jsxs(a.Fragment,{children:[a.jsx($i,{size:16}),r("spoolbuddy.diagnostic.runBtn","Run Diagnostic")]})}),a.jsx("button",{onClick:n,className:"px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors",children:r("spoolbuddy.diagnostic.close","Close")})]})]})})}function Dat(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function Fat(t){if(!t)return"-";try{const e=new Date(t);return e.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return"-"}}const Rat=[{label:"Off",value:0},{label:"1m",value:60},{label:"2m",value:120},{label:"5m",value:300},{label:"10m",value:600},{label:"30m",value:1800}];function Lat({device:t}){const{t:e}=Rt(),[n,r]=w.useState(null),[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{!i&&t.backend_url&&s(t.backend_url)},[t.backend_url,i]);const p=async()=>{if(!i.trim()){m({type:"error",text:e("spoolbuddy.settings.systemFieldsRequired","Backend URL is required.")});return}d(!0),m(null);try{await Ur.updateSystemConfig(t.device_id,i.trim(),o.trim()||void 0),m({type:"ok",text:e("spoolbuddy.settings.systemQueued","Config queued.")})}catch(f){m({type:"error",text:f instanceof Error?f.message:e("common.error","Error")})}finally{d(!1)}};return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),a.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),a.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"IP"}),a.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),a.jsx("span",{className:"text-zinc-300",children:Dat(t.uptime_s)})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"ID"}),a.jsx("span",{className:"text-zinc-400 font-mono truncate ml-2",children:t.device_id})]})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-2",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:e("spoolbuddy.settings.systemConfig","Backend & Auth")}),a.jsx("input",{value:i,onChange:f=>s(f.target.value),placeholder:"http://192.168.1.100:5000",className:"w-full px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"password",value:o,onChange:f=>l(f.target.value),placeholder:e("spoolbuddy.settings.apiTokenPlaceholder","API token"),className:"flex-1 px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),a.jsx("button",{onClick:p,disabled:c,className:"px-3 py-1.5 rounded bg-green-700 hover:bg-green-600 disabled:bg-zinc-700 text-xs font-medium text-zinc-100",children:e("spoolbuddy.settings.saveConfig","Save")})]}),u&&a.jsx("div",{className:`text-xs ${u.type==="ok"?"text-green-400":"text-red-400"}`,children:u.text})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 flex flex-col gap-2",children:[a.jsxs("button",{onClick:()=>r("nfc"),className:"flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(zQ,{className:"w-4 h-4 text-blue-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-blue-100",children:e("spoolbuddy.settings.nfcDiagnostic","NFC Diagnostic")})]}),a.jsxs("button",{onClick:()=>r("scale"),className:"flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(ic,{className:"w-4 h-4 text-yellow-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-yellow-100",children:e("spoolbuddy.settings.scaleDiagnostic","Scale Diagnostic")})]}),a.jsxs("button",{onClick:()=>r("read_tag"),className:"flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[a.jsx(Ms,{className:"w-4 h-4 text-emerald-300 shrink-0"}),a.jsx("span",{className:"text-xs font-medium text-emerald-100",children:e("spoolbuddy.settings.readTagDiagnostic","Read Tag")})]})]})]}),n&&t&&a.jsx(Eat,{type:n,deviceId:t.device_id,onClose:()=>r(null)})]})}function Oat({device:t,onBrightnessChange:e}){const{t:n}=Rt(),[r,i]=w.useState(t.display_brightness),[s,o]=w.useState(t.display_blank_timeout),[l,c]=w.useState(!1),d=w.useRef(void 0),u=w.useRef(void 0);w.useEffect(()=>{i(t.display_brightness),o(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const m=w.useCallback(()=>{c(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>c(!1),1500)},[]),p=w.useCallback((v,g)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{Ur.updateDisplay(t.device_id,v,g).then(()=>m()).catch(b=>console.error("Failed to update display:",b))},300)},[t.device_id,m]),f=v=>{i(v),e(v),p(v,s)},x=v=>{o(v),p(r,v)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:n("spoolbuddy.settings.brightness","Brightness")}),l&&a.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[a.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),n("spoolbuddy.settings.saved","Saved")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("svg",{className:"w-4 h-4 text-zinc-500 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}),a.jsx("input",{type:"range",min:0,max:100,value:r,onChange:v=>f(parseInt(v.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[r,"%"]})]}),!t.has_backlight&&a.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:n("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:n("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),a.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:n("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),a.jsx("div",{className:"grid grid-cols-3 gap-2",children:Rat.map(v=>a.jsx("button",{onClick:()=>x(v.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${s===v.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:v.label},v.value))})]}),a.jsx("p",{className:"text-xs text-zinc-600 text-center",children:n("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function Iat({step:t,labels:e}){return a.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[a.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?a.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),a.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),a.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),a.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),a.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function zat({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:i}=Rt(),[s,o]=w.useState("idle"),[l,c]=w.useState("500"),[d,u]=w.useState(null),[m,p]=w.useState(!1),[f,x]=w.useState(null),v=_=>{_==="backspace"?c(C=>C.slice(0,-1)||""):_==="."&&!l.includes(".")?c(C=>C+"."):_>="0"&&_<="9"&&c(C=>C==="0"?_:C+_)},g=async()=>{p(!0),x(null);try{await Ur.tare(t.device_id),x({type:"ok",msg:i("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{x({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},b=async()=>{if(s==="tare"){p(!0),x(null);try{u(r),await Ur.tare(t.device_id),x({type:"ok",msg:i("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{x({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const _=parseFloat(l);if(r===null||!_||_<=0)return;p(!0),x(null);try{await Ur.setCalibrationFactor(t.device_id,_,r,d??void 0),x({type:"ok",msg:i("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{x({type:"error",msg:i("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),a.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[a.jsxs("span",{children:[i("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),a.jsx("span",{className:"mx-1.5",children:"·"}),a.jsxs("span",{children:[i("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&a.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[i("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Fat(t.last_calibrated_at)]})]}),f&&a.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:g,disabled:m,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2",children:[m&&a.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),i("spoolbuddy.weight.tare","Tare")]}),a.jsx("button",{onClick:()=>{o("tare"),x(null)},className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:i("spoolbuddy.weight.calibrate","Calibrate")})]})]}):a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Iat,{step:s,labels:{tare:i("spoolbuddy.weight.tare","Tare"),weight:i("spoolbuddy.settings.knownWeight","Known weight")}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[a.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),a.jsx("span",{className:`text-xs ml-auto ${n?"text-green-400":"text-amber-400"}`,children:n?i("spoolbuddy.settings.stable","Stable"):i("spoolbuddy.settings.settling","Settling...")})]}),f&&a.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),s==="tare"?a.jsx("p",{className:"text-sm text-zinc-300 mb-3",children:i("spoolbuddy.settings.calStep1","Remove all items from the scale and press Set Zero.")}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:i("spoolbuddy.settings.knownWeight","Known weight")}),a.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100",children:[l||"0",a.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1 mb-1.5",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(_=>a.jsx("button",{onClick:()=>v(_),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${_==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:_==="backspace"?"⌫":_},_))})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>{o("idle"),x(null)},className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]",children:i("common.cancel","Cancel")}),a.jsxs("button",{onClick:b,disabled:m,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2",children:[m&&a.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s==="tare"?i("spoolbuddy.settings.setZero","Set Zero"):i("spoolbuddy.settings.calibrateNow","Calibrate")]})]})]})]})}function Uat({device:t}){const{t:e}=Rt(),[n,r]=w.useState(null),[i,s]=w.useState(null),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.update_status==="pending"||t.update_status==="updating";w.useEffect(()=>{u&&n==="applying"&&r(null)},[u,n]),w.useEffect(()=>{const C=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",C),()=>window.removeEventListener("spoolbuddy-online",C)},[u]);const{data:m,refetch:p}=Qe({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>Ur.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=Qe({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>Ur.getSSHPublicKey(),enabled:o,staleTime:1/0}),x=async()=>{r("checking"),s(null);try{await p()}finally{r(null)}},v=async()=>{r("applying"),s(null);try{await Ur.triggerUpdate(t.device_id)}catch(C){s(C instanceof Error?C.message:"Failed to trigger update"),r(null)}},g=n!=null||u,b=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),d(!0),setTimeout(()=>d(!1),2e3))},_=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),a.jsx("span",{className:"text-zinc-200 font-mono",children:_||a.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),g?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[a.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),a.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a.jsx("span",{className:"text-green-300 text-xs",children:n==="checking"?e("spoolbuddy.settings.checking","Checking for updates..."):t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}):t.update_status==="error"?a.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):i?a.jsx("p",{className:"text-xs text-red-300",children:i}):m?.update_available?a.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",_," → ",m.latest_version]}):null,!g&&(m?.update_available?a.jsx("button",{onClick:v,disabled:!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors",children:t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")}):a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:x,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:e("spoolbuddy.settings.checkUpdates","Check for Updates")}),a.jsx("button",{onClick:v,disabled:!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors",children:e("spoolbuddy.settings.forceUpdate","Force Update")})]}))]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[a.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),a.jsx("svg",{className:`w-3 h-3 text-zinc-500 transition-transform ${o?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&a.jsxs("div",{className:"mt-2 space-y-2",children:[a.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),f?.public_key?a.jsxs("div",{className:"relative",children:[a.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:f.public_key}),a.jsx("button",{onClick:b,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):a.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function PY({percent:t,color:e}){return a.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all ${e}`,style:{width:`${Math.min(100,Math.max(0,t))}%`}})})}function Bat(t){const e=Math.floor(t/86400),n=Math.floor(t%86400/3600),r=Math.floor(t%3600/60);return e>0?`${e}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function Hat({device:t}){const{t:e}=Rt(),n=t.system_stats;if(!n)return a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("p",{className:"text-sm text-zinc-500",children:e("spoolbuddy.settings.systemStatsWaiting","Waiting for system stats...")})});const r=n.memory,i=n.disk,s=(n.cpu_temp_c??0)>=80?"text-red-400":(n.cpu_temp_c??0)>=65?"text-amber-400":"text-green-400",o=(r?.percent??0)>=90?"bg-red-500":(r?.percent??0)>=70?"bg-amber-500":"bg-green-500",l=(i?.percent??0)>=90?"bg-red-500":(i?.percent??0)>=70?"bg-amber-500":"bg-green-500";return a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:"CPU"}),a.jsxs("div",{className:"space-y-1.5 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.cores","Cores")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.cpu_count??"-"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.loadAvg","Load Avg")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.load_avg?n.load_avg.join(" / "):"-"})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.temp","Temp")}),a.jsx("span",{className:`font-mono font-medium ${s}`,children:n.cpu_temp_c!=null?`${n.cpu_temp_c}°C`:"-"})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.memory","Memory")}),r?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx(PY,{percent:r.percent??0,color:o}),a.jsxs("div",{className:"space-y-1 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.used","Used")}),a.jsxs("span",{className:"text-zinc-300 font-mono",children:[r.used_mb," / ",r.total_mb," MB"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.available","Free")}),a.jsxs("span",{className:"text-zinc-300 font-mono",children:[r.available_mb," MB"]})]})]})]}):a.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})]}),a.jsx("div",{className:"bg-zinc-800 rounded-lg px-3 py-2",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 shrink-0",children:e("spoolbuddy.settings.disk","Disk")}),i?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex-1",children:a.jsx(PY,{percent:i.percent??0,color:l})}),a.jsxs("span",{className:"text-xs text-zinc-300 font-mono shrink-0",children:[i.used_gb," / ",i.total_gb," GB"]})]}):a.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.osInfo","OS")}),a.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.os&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.distro","Distro")}),a.jsx("span",{className:"text-zinc-300 truncate ml-2",children:n.os.os})]}),n.os?.kernel&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.kernel","Kernel")}),a.jsx("span",{className:"text-zinc-300 font-mono truncate ml-2",children:n.os.kernel})]}),n.os?.arch&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.arch","Arch")}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.arch})]})]})]}),a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[a.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.runtime","Runtime")}),a.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.python&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:"Python"}),a.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.python})]}),n.system_uptime_s!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.systemUptime","Uptime")}),a.jsx("span",{className:"text-zinc-300",children:Bat(n.system_uptime_s)})]})]})]})]})]})}function qat(){const{sbState:t,setDisplayBrightness:e}=iy(),{t:n}=Rt(),[r,i]=w.useState("device"),{data:s=[]}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:1e4}),o=t.deviceId?s.find(c=>c.device_id===t.deviceId)??s[0]:s[0],l=[{id:"device",label:n("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:n("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:n("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:n("spoolbuddy.settings.tabUpdates","Updates")},{id:"system",label:n("spoolbuddy.settings.tabSystem","System")}];return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.nav.settings","Settings")}),a.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:l.map(c=>a.jsx("button",{onClick:()=>i(c.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${r===c.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:c.label},c.id))}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:o?a.jsxs(a.Fragment,{children:[r==="device"&&a.jsx(Lat,{device:o}),r==="display"&&a.jsx(Oat,{device:o,onBrightnessChange:e}),r==="scale"&&a.jsx(zat,{device:o,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),r==="updates"&&a.jsx(Uat,{device:o}),r==="system"&&a.jsx(Hat,{device:o})]}):a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-center text-zinc-500",children:a.jsx("p",{className:"text-sm",children:n("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function $at({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:i}=Rt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[d,u]=w.useState("500"),[m,p]=w.useState(null),[f,x]=w.useState(!1),v=C=>{C==="backspace"?u(P=>P.slice(0,-1)||""):C==="."&&!d.includes(".")?u(P=>P+"."):C>="0"&&C<="9"&&u(P=>P==="0"?C:P+C)},g=async()=>{x(!0);try{await Ur.tare(t.device_id)}catch(C){console.error("Failed to tare:",C)}finally{x(!1)}},b=()=>{c("tare")},_=async()=>{if(l==="tare"){o(!0);try{p(r),await Ur.tare(t.device_id),c("weight")}catch(C){console.error("Failed to tare:",C)}finally{o(!1)}}else if(l==="weight"){const C=parseFloat(d);if(r===null||!C||C<=0)return;o(!0);try{await Ur.setCalibrationFactor(t.device_id,C,r,m??void 0),c("idle")}catch(P){console.error("Failed to calibrate:",P)}finally{o(!1)}}};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-zinc-400",children:i("spoolbuddy.settings.currentWeight","Current weight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),a.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.tareOffset","Tare offset")}),a.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.calFactor","Cal. factor")}),a.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:g,disabled:f,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:f?"...":i("spoolbuddy.weight.tare","Tare")}),a.jsx("button",{onClick:b,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:i("spoolbuddy.weight.calibrate","Calibrate")})]}):a.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[a.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?i("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):i("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-zinc-400",children:i("spoolbuddy.settings.knownWeight","Known weight (g)")}),a.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100",children:[d||"0",a.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(C=>a.jsx("button",{onClick:()=>v(C),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${C==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:C==="backspace"?"⌫":C},C))})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:i("common.cancel","Cancel")}),a.jsx("button",{onClick:_,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?i("spoolbuddy.settings.setZero","Set Zero"):i("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function Vat(){const{sbState:t}=iy(),{t:e}=Rt(),n=Do(),{data:r=[]}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:1e4}),i=t.deviceId?r.find(s=>s.device_id===t.deviceId)??r[0]:r[0];return a.jsxs("div",{className:"h-full flex flex-col p-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("button",{onClick:()=>n("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),a.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:i?a.jsx($at,{device:i,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-center text-zinc-500",children:a.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const Gat=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function Wat(){const{t}=Rt(),{sbState:e}=iy(),[n,r]=w.useState("existing"),[i,s]=w.useState(null),[o,l]=w.useState(""),[c,d]=w.useState("idle"),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[g,b]=w.useState(null),{data:_=[],refetch:C}=Qe({queryKey:["inventory-spools"],queryFn:()=>me.getSpools(!1),refetchInterval:1e4}),{data:P=[]}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Ur.getDevices(),refetchInterval:5e3}),{data:N}=Qe({queryKey:["settings"],queryFn:me.getSettings}),A=P[0],T=e.deviceOnline,F=So(N?.currency||"USD"),k=w.useMemo(()=>{let oe;if(n==="existing")oe=_.filter(W=>!W.tag_uid&&!W.archived_at);else if(n==="replace")oe=_.filter(W=>(W.tag_uid||W.tray_uuid)&&!W.archived_at);else return[];if(o){const W=o.toLowerCase();oe=oe.filter(re=>re.material?.toLowerCase().includes(W)||re.color_name?.toLowerCase().includes(W)||re.brand?.toLowerCase().includes(W)||re.subtype?.toLowerCase().includes(W))}return oe},[_,n,o]),D=w.useCallback(oe=>{const W=oe.detail;(W.sak??W.data?.sak)===0&&(v(!0),b(W.tag_uid??W.data?.tag_uid??null))},[]),H=w.useCallback(oe=>{const W=oe.detail;v(!0),b(W.tag_uid??W.data?.tag_uid??null)},[]),z=w.useCallback(()=>{v(!1),b(null)},[]),X=w.useCallback(oe=>{const W=oe.detail;(W.spool_id===i?.id||W.data?.spool_id===i?.id)&&(d("success"),m(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),C(),setTimeout(()=>{d("idle"),s(null),m("")},5e3))},[i,t,C]),L=w.useCallback(oe=>{const W=oe.detail;(W.spool_id===i?.id||W.data?.spool_id===i?.id)&&(d("error"),m(W.message??W.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[i,t]);w.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",D),window.addEventListener("spoolbuddy-tag-matched",H),window.addEventListener("spoolbuddy-tag-removed",z),window.addEventListener("spoolbuddy-tag-written",X),window.addEventListener("spoolbuddy-tag-write-failed",L),()=>{window.removeEventListener("spoolbuddy-unknown-tag",D),window.removeEventListener("spoolbuddy-tag-matched",H),window.removeEventListener("spoolbuddy-tag-removed",z),window.removeEventListener("spoolbuddy-tag-written",X),window.removeEventListener("spoolbuddy-tag-write-failed",L)}),[D,H,z,X,L]),w.useEffect(()=>{s(null),d("idle"),m(""),l("")},[n]);const ne=async()=>{if(!(!i||!A)){d("writing"),m(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{await Ur.writeTag(A.device_id,i.id)}catch{d("error"),m(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},ie=async()=>{if(A){try{await Ur.cancelWrite(A.device_id)}catch{}d("idle"),m("")}},ee=async()=>{if(!(!i||!TY(i))){f(!0),d("idle"),m("");try{await me.linkTagToSpool(i.id,{tag_uid:"",tray_uuid:"",data_origin:"manual"}),await C(),s(null),d("success"),m(t("spoolbuddy.writeTag.untagSuccess","Tag removed from spool")),setTimeout(()=>{d("idle"),m("")},2500)}catch{d("error"),m(t("spoolbuddy.writeTag.untagFailed","Failed to remove tag from spool"))}finally{f(!1)}}},ue=w.useCallback(oe=>{s(oe),d("idle"),m(""),C()},[C]),le=i&&T&&c!=="writing"&&c!=="success";return a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(oe=>a.jsx("button",{onClick:()=>r(oe.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===oe.key?"text-bambu-green border-b-2 border-bambu-green bg-bambu-dark":"text-zinc-400 hover:text-zinc-200 hover:bg-bambu-dark-tertiary"}`,children:oe.label},oe.key))}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?a.jsx(Xat,{currencySymbol:F,onCreated:ue,selectedSpool:i,t}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"p-3 shrink-0",children:a.jsx("input",{type:"text",value:o,onChange:oe=>l(oe.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:k.length===0?a.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):k.map(oe=>a.jsx(Kat,{spool:oe,selected:i?.id===oe.id,showTag:n==="replace",onClick:()=>{s(oe),d("idle"),m("")}},oe.id))})]})}),a.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:a.jsx(Yat,{writeStatus:c,writeMessage:u,selectedSpool:i,tagOnReader:x,tagUid:g,deviceOnline:T,canWrite:!!le,isReplace:n==="replace",canUntag:n==="replace"&&!!i&&TY(i),untagging:p,onWrite:ne,onUntag:ee,onCancel:ie,onRetry:()=>{d("idle"),m("")},t})})]})]})}function TY(t){return!!(t.tag_uid||t.tray_uuid)}function Kat({spool:t,selected:e,showTag:n,onClick:r}){const i=t.rgba?`#${t.rgba.slice(0,6)}`:"#666",s=Math.max(0,t.label_weight-t.weight_used),o=t.label_weight>0?Math.round(s/t.label_weight*100):0;return a.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[a.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:i}}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]})}),a.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&a.jsx("span",{children:t.color_name}),a.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&a.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&a.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:a.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]})}function Xat({currencySymbol:t,onCreated:e,selectedSpool:n,t:r}){const[i,s]=w.useState("simple"),[o,l]=w.useState("filament"),[c,d]=w.useState(QL),[u,m]=w.useState({}),[p,f]=w.useState(!1),[x,v]=w.useState(1),[g,b]=w.useState(!1),[_,C]=w.useState(null),[P,N]=w.useState(!1),[A,T]=w.useState(!1),[F,k]=w.useState([]),[D,H]=w.useState([]),[z,X]=w.useState([]),[L,ne]=w.useState([]),[ie,ee]=w.useState(""),[ue,le]=w.useState([]),[oe,W]=w.useState([]),[re,ce]=w.useState(new Set),[xe,Ne]=w.useState(new Set);w.useEffect(()=>{le(Hle())},[]),w.useEffect(()=>{(async()=>{if(i==="full"){T(!0);try{const pe=await me.getCloudStatus();if(N(pe.is_authenticated),pe.is_authenticated){const de=await me.getFilamentPresets();k(de)}}catch{N(!1)}finally{T(!1)}me.getSpoolCatalog().then(X).catch(()=>{}),me.getColorCatalog().then(ne).catch(()=>{}),me.getLocalPresets().then(pe=>H(pe.filament)).catch(()=>{});try{const pe=await me.getPrinters(),de=await Promise.all(pe.map(R=>me.getPrinterStatus(R.id).catch(()=>null))),U=[];for(let R=0;R<pe.length;R++){const ae=pe[R],Se=de[R]?.connected??!1;let ye=[];if(Se)try{ye=(await me.getKProfiles(ae.id)).profiles.map(ve=>({cali_idx:ve.slot_id,filament_id:ve.filament_id,setting_id:ve.setting_id||"",name:ve.name,k_value:parseFloat(ve.k_value)||0,n_coef:parseFloat(ve.n_coef)||0,extruder_id:ve.extruder_id,nozzle_diameter:ve.nozzle_diameter}))}catch{}U.push({printer:{...ae,connected:Se},calibrations:ye})}W(U)}catch{}}})()},[i]),w.useEffect(()=>{oe.length>0&&Ne(new Set(oe.map(fe=>String(fe.printer.id))))},[oe]);const $=w.useMemo(()=>Ule(F,new Set,D),[F,D]),Y=w.useMemo(()=>Ble(c.slicer_filament,$),[c.slicer_filament,$]),E=w.useMemo(()=>{const fe=zle(F,D),pe=L.map(de=>de.manufacturer?.trim()).filter(de=>!!de);return Array.from(new Set([...fe,...pe])).sort((de,U)=>de.localeCompare(U))},[F,D,L]),j=w.useMemo(()=>{const fe=L.map(pe=>pe.material?.trim()).filter(pe=>!!pe);return Array.from(new Set([...Lle,...fe])).sort((pe,de)=>pe.localeCompare(de))},[L]),O=w.useMemo(()=>{const fe=[];for(const pe of L){const de=pe.manufacturer?.trim(),U=pe.material?.trim();de&&U&&fe.push({brand:de,material:U})}for(const pe of F){const de=pp(pe.name);de.brand&&de.material&&fe.push({brand:de.brand,material:de.material})}for(const pe of D){const de=pp(pe.name),U=pe.filament_vendor?.trim()||de.brand,R=de.material;U&&R&&fe.push({brand:U,material:R})}return fe},[F,L,D]),K=w.useMemo(()=>{const fe=new Map;for(const pe of O){const de=pe.brand.toLowerCase(),U=pe.material.toLowerCase();fe.has(de)||fe.set(de,new Set),fe.get(de).add(U)}return fe},[O]),B=w.useMemo(()=>{const fe=new Map;for(const pe of O){const de=pe.brand.toLowerCase(),U=pe.material.toLowerCase();fe.has(U)||fe.set(U,new Set),fe.get(U).add(de)}return fe},[O]),he=w.useMemo(()=>{if(!c.material)return E;const fe=c.material.toLowerCase(),pe=B.get(fe);return!pe||pe.size===0?E:E.filter(de=>pe.has(de.toLowerCase()))},[E,c.material,B]),I=w.useMemo(()=>{if(!c.brand)return j;const fe=c.brand.toLowerCase(),pe=K.get(fe);return!pe||pe.size===0?j:j.filter(de=>pe.has(de.toLowerCase()))},[j,c.brand,K]),V=(fe,pe)=>{d(de=>({...de,[fe]:pe})),u[fe]&&m(de=>({...de,[fe]:void 0}))},Q=fe=>{le(pe=>qle(fe,pe))},G=async fe=>{if(re.size===0){try{await me.saveSpoolKProfiles(fe,[])}catch{}return}const pe=[];for(const de of re){const[U,R,ae]=de.split(":"),_e=parseInt(U),Se=parseInt(R),ye=ae==="null"?0:parseInt(ae),Ae=oe.find(ve=>ve.printer.id===_e);if(Ae){const ve=Ae.calibrations.find(je=>je.cali_idx===Se);ve&&pe.push({printer_id:_e,extruder:ye,nozzle_diameter:ve.nozzle_diameter||"0.4",k_value:ve.k_value,name:ve.name||null,cali_idx:ve.cali_idx,setting_id:ve.setting_id||null})}}pe.length>0&&await me.saveSpoolKProfiles(fe,pe)},J=async()=>{C(null);const fe=Rle(c,i==="simple"?!0:p);if(!fe.isValid){m(fe.errors),l("filament");return}const pe=Y?.displayName||ie||null,de={material:c.material,subtype:c.subtype||null,brand:c.brand||null,color_name:c.color_name||null,rgba:c.rgba||null,label_weight:c.label_weight,core_weight:c.core_weight,core_weight_catalog_id:c.core_weight_catalog_id,weight_used:c.weight_used,slicer_filament:c.slicer_filament||null,slicer_filament_name:pe,nozzle_temp_min:null,nozzle_temp_max:null,note:c.note||null,cost_per_kg:c.cost_per_kg,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,last_scale_weight:null,last_weighed_at:null};b(!0);try{if(x>1){const U=await me.bulkCreateSpools(de,x);for(const R of U)await G(R.id);U.length>0&&e(U[0])}else{const U=await me.createSpool(de);await G(U.id),e(U)}}catch{C(r("spoolbuddy.writeTag.createFailed","Failed to create spool"))}finally{b(!1)}},se=`#${(c.rgba||"808080FF").slice(0,6)}`;return a.jsxs("div",{className:"p-3 space-y-3 overflow-y-auto h-full",children:[a.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-zinc-200",children:r("spoolbuddy.writeTag.viewMode","View")}),a.jsxs("div",{className:"flex rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[a.jsx("button",{type:"button",onClick:()=>s("simple"),className:`px-3 py-1.5 text-xs font-medium ${i==="simple"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.simpleView","Simple")}),a.jsx("button",{type:"button",onClick:()=>s("full"),className:`px-3 py-1.5 text-xs font-medium ${i==="full"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.fullView","Full")})]})]}),i==="simple"?n?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),a.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),a.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),a.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):a.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.material","Material")}),a.jsx("select",{value:c.material,onChange:fe=>V("material",fe.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",children:Gat.map(fe=>a.jsx("option",{value:fe,children:fe},fe))})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.colorName","Color Name")}),a.jsx("input",{type:"text",value:c.color_name,onChange:fe=>V("color_name",fe.target.value),placeholder:"Jade White",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.color","Color")}),a.jsx("input",{type:"color",value:se,onChange:fe=>V("rgba",fe.target.value.replace("#","").toUpperCase()+"FF"),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.brand","Brand")}),a.jsx("input",{type:"text",value:c.brand,onChange:fe=>V("brand",fe.target.value),placeholder:"Polymaker",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.weight","Weight (g)")}),a.jsx("input",{type:"number",value:c.label_weight,onChange:fe=>V("label_weight",parseInt(fe.target.value)||0),min:0,max:1e4,className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green"})]}),a.jsx("button",{onClick:J,disabled:g||!c.material,className:"w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:g?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-zinc-200",children:r("inventory.quickAdd","Quick Add")}),a.jsx("button",{type:"button",onClick:()=>f(fe=>!fe),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"flex border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{onClick:()=>l("filament"),className:`flex-1 py-2.5 text-sm font-medium ${o==="filament"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.filamentInfoTab","Filament")}),!p&&a.jsx("button",{onClick:()=>l("pa-profile"),className:`flex-1 py-2.5 text-sm font-medium ${o==="pa-profile"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.paProfileTab","PA Profile")})]}),a.jsx("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3",children:o==="filament"?a.jsxs("div",{className:"space-y-4",children:[a.jsx($le,{formData:c,updateField:V,cloudAuthenticated:P,loadingCloudPresets:A,presetInputValue:ie,setPresetInputValue:ee,selectedPresetOption:Y,filamentOptions:$,availableBrands:he,availableMaterials:I,quickAdd:p,quantity:x,onQuantityChange:v,errors:u}),a.jsx(Vle,{formData:c,updateField:V,recentColors:ue,onColorUsed:Q,catalogColors:L}),a.jsx(Gle,{formData:c,updateField:V,spoolCatalog:z,currencySymbol:t})]}):a.jsx(Wle,{formData:c,updateField:V,printersWithCalibrations:oe,selectedProfiles:re,setSelectedProfiles:ce,expandedPrinters:xe,setExpandedPrinters:Ne})})]}),_&&a.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2",children:_}),i==="full"&&a.jsx("button",{onClick:J,disabled:g,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:g?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")}),i==="full"&&n&&a.jsxs("div",{className:"flex flex-col items-center justify-center p-4 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),a.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),a.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),a.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]})]})}function Yat({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:r,tagUid:i,deviceOnline:s,canWrite:o,isReplace:l,canUntag:c,untagging:d,onWrite:u,onUntag:m,onCancel:p,onRetry:f,t:x}){if(t==="success")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),a.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&a.jsxs("p",{className:"text-zinc-400 text-sm",children:[n.brand?`${n.brand} `:"",n.material,n.color_name?` - ${n.color_name}`:""]})]});if(t==="error")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),a.jsx("p",{className:"text-red-400 font-medium",children:e}),a.jsx("button",{onClick:f,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:x("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[a.jsxs("div",{className:"relative w-16 h-16",children:[a.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),a.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(Wv,{className:"w-8 h-8 text-bambu-green"})})]}),a.jsx("p",{className:"text-bambu-green font-medium",children:x("spoolbuddy.writeTag.writing","Writing tag...")}),a.jsx("p",{className:"text-zinc-500 text-xs",children:e}),a.jsx("button",{onClick:p,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:x("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[a.jsx(Wv,{className:"w-12 h-12 text-zinc-600"}),a.jsx("p",{className:"text-zinc-500 text-sm",children:x("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[a.jsx(Wv,{className:"w-12 h-12 text-zinc-600"}),a.jsx("p",{className:"text-zinc-400 text-sm",children:x("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const v=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return a.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[a.jsx("div",{className:"relative w-16 h-16",children:r?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(Wv,{className:"w-8 h-8 text-bambu-green"})})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsx(Wv,{className:"w-8 h-8 text-zinc-500"})})]})}),r?a.jsxs("div",{className:"space-y-1",children:[a.jsx("p",{className:"text-bambu-green text-sm font-medium",children:x("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),i&&a.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:i})]}):a.jsx("p",{className:"text-zinc-400 text-sm",children:x("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),a.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:v}}),a.jsxs("div",{className:"text-left min-w-0",children:[a.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&a.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),a.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&a.jsx("p",{className:"text-yellow-500/80 text-xs",children:x("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),a.jsx("button",{onClick:u,disabled:!o,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm",children:l?x("spoolbuddy.writeTag.replaceTag","Replace Tag"):x("spoolbuddy.writeTag.writeTag","Write Tag")}),l&&c&&a.jsx("button",{onClick:m,disabled:d,className:"w-full py-2.5 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary disabled:opacity-40 disabled:cursor-not-allowed text-zinc-200 rounded-lg transition-colors text-sm",children:d?x("spoolbuddy.writeTag.untagging","Removing tag..."):x("spoolbuddy.writeTag.untagSpool","Untag Selected Spool")})]})}function Wv({className:t}){return a.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const Qat="spoolbuddy-default-core-weight";function Zat(){try{const t=localStorage.getItem(Qat);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function Jat({spool:t,liveScaleWeight:e,persistedGrossWeight:n,onClose:r,onSyncWeight:i,onAssignToAms:s,className:o}){const{t:l}=Rt(),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(null),{data:x}=Qe({queryKey:["spool-k-profiles",t.id],queryFn:()=>me.getSpoolKProfiles(t.id),enabled:!t.k_profiles||t.k_profiles.length===0,staleTime:300*1e3}),v=t.k_profiles&&t.k_profiles.length>0?t.k_profiles:x,g=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",b=t.core_weight&&t.core_weight>0?t.core_weight:Zat(),_=e!==null?Math.round(Math.max(0,e)):null,C=p??(n!==void 0?n!==null?Math.round(Math.max(0,n)):null:_),P=Math.round(Math.max(0,(t.label_weight||0)-(t.weight_used||0))),T=_!==null&&_>=10?Math.round(Math.max(0,_-b)):P,F=Math.round(t.label_weight||1e3),k=F>0?Math.min(100,Math.round(T/F*100)):null,D=k!==null?k>50?"#22c55e":k>20?"#eab308":"#ef4444":"#808080",z=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+b,X=_!==null?_-z:null,L=X!==null?Math.abs(X)<=50:null,ne=Math.round(z),ie=C??ne,ee=t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null?`${t.nozzle_temp_min}-${t.nozzle_temp_max}°C`:null,ue=t.slicer_filament_name||t.slicer_filament||null,le=t.note?.trim()||null,oe=v&&v.length>0?Array.from(new Set(v.map(re=>re.k_value.toFixed(3)))).join(", "):null,W=async()=>{if(e===null)return;const re=Math.round(Math.max(0,e));d(!0);try{await Ur.updateSpoolWeight(t.id,re),f(re),m(!0),i?.(),setTimeout(()=>m(!1),3e3)}catch(ce){console.error("Failed to sync weight:",ce)}finally{d(!1)}};return a.jsxs("div",{className:`flex flex-col items-center space-y-4 max-w-md ${o??""}`,children:[a.jsxs("div",{className:"flex items-start gap-5",children:[a.jsxs("div",{className:"relative shrink-0",children:[a.jsx(lA,{color:g,isEmpty:!1,size:100}),k!==null&&a.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:D},children:[k,"%"]})]}),a.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),a.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[T,"g"]}),a.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",F,"g"]})]}),a.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:l("spoolbuddy.spool.remaining","Remaining")}),a.jsx("div",{className:"mt-2 max-w-xs",children:a.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${k??0}%`,backgroundColor:D}})})})]})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.grossWeight","Gross weight")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[ie,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.coreWeight","Core")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[b,"g"]})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.spoolSize","Spool size")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[F,"g"]})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.scaleWeight","Scale")}),_!==null?a.jsxs("span",{className:`flex items-center gap-1 font-mono ${L?"text-green-500":"text-yellow-500"}`,children:[_,"g",L?a.jsx(Rr,{className:"w-3.5 h-3.5"}):a.jsxs(a.Fragment,{children:[a.jsx(Rn,{className:"w-3.5 h-3.5"}),a.jsx("button",{onClick:W,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:l("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:a.jsx(cr,{className:"w-4 h-4"})})]})]}):a.jsx("span",{className:"text-zinc-500",children:"—"})]}),a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.tagId","Tag")}),a.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]}),ee&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.nozzleTemp","Nozzle")}),a.jsx("span",{className:"font-mono text-zinc-300",children:ee})]}),t.cost_per_kg!=null&&t.cost_per_kg>0&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.costPerKg","Cost/kg")}),a.jsxs("span",{className:"font-mono text-zinc-300",children:[t.cost_per_kg.toFixed(2),"/kg"]})]}),oe&&a.jsxs("div",{className:"flex justify-between items-center",children:[a.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.inventory.kProfiles","K-Profile")}),a.jsx("span",{className:"font-mono text-zinc-300 truncate max-w-[220px] text-right",title:oe,children:oe})]}),ue&&a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:l("spoolbuddy.inventory.slicerFilament","Slicer Filament")}),a.jsx("p",{className:"text-sm text-zinc-300 whitespace-pre-wrap break-words",children:ue})]}),le&&a.jsxs("div",{className:"col-span-2",children:[a.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:l("spoolbuddy.inventory.note","Note")}),a.jsx("p",{className:"text-sm leading-5 text-zinc-300 whitespace-pre-wrap break-words max-h-[3.75rem] overflow-y-auto pr-1",children:le})]})]}),a.jsxs("div",{className:"flex gap-2 justify-center",children:[s&&a.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:l("spoolbuddy.modal.assignToAms","Assign to AMS")}),a.jsx("button",{onClick:W,disabled:e===null||c,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${u?"bg-green-600/20 text-green-400":s?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:c?"...":u?l("spoolbuddy.dashboard.weightSynced","Synced!"):l("spoolbuddy.dashboard.syncWeight","Sync Weight")}),r&&a.jsx("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:l("spoolbuddy.dashboard.close","Close")})]})]})}function eit(t){return t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"}function tit(t){return Math.max(0,t.label_weight-t.weight_used)}function nit(t){return t.label_weight<=0?0:Math.max(0,Math.min(100,(t.label_weight-t.weight_used)/t.label_weight*100))}function rit(t){const e=[t.material];return t.subtype&&e.push(t.subtype),e.join(" ")}function nce(t){const e=t.ams_id===254||t.ams_id===255,n=!e&&t.ams_id>=128;return bS(t.ams_id,t.tray_id,n,e)}function ait({color:t,size:e=56}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 56 56",children:[a.jsx("circle",{cx:"28",cy:"28",r:"26",fill:t}),a.jsx("circle",{cx:"28",cy:"28",r:"20",fill:t,style:{filter:"brightness(0.85)"}}),a.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),a.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),a.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}function iit(){const{sbState:t,selectedPrinterId:e}=iy(),{t:n}=Rt(),[r,i]=w.useState(""),[s,o]=w.useState("all"),[l,c]=w.useState(null),[d,u]=w.useState(!1),{data:m}=Qe({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings,staleTime:300*1e3}),{data:p=[],isLoading:f,refetch:x}=Qe({queryKey:["inventory-spools"],queryFn:()=>me.getSpools(!1),refetchInterval:3e4}),{data:v=[]}=Qe({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),refetchInterval:3e4}),g=w.useMemo(()=>{const T={};return v.forEach(F=>{T[F.spool_id]=F}),T},[v]),b=w.useMemo(()=>p.filter(T=>!T.archived_at),[p]),_=w.useMemo(()=>new Set(v.map(T=>T.spool_id)),[v]),C=w.useMemo(()=>b.filter(T=>_.has(T.id)).length,[b,_]),P=w.useMemo(()=>{const T=new Set;return b.forEach(F=>T.add(F.material)),Array.from(T).sort()},[b]),N=w.useMemo(()=>{let T=b;if(s==="in_ams"?T=T.filter(F=>_.has(F.id)):s!=="all"&&(T=T.filter(F=>F.material===s)),r.trim()){const F=r.toLowerCase().trim();T=T.filter(k=>k.material.toLowerCase().includes(F)||k.subtype&&k.subtype.toLowerCase().includes(F)||k.brand&&k.brand.toLowerCase().includes(F)||k.color_name&&k.color_name.toLowerCase().includes(F)||k.note&&k.note.toLowerCase().includes(F))}return[...T].sort((F,k)=>{const D=_.has(F.id)?0:1,H=_.has(k.id)?0:1;return D!==H?D-H:new Date(k.updated_at).getTime()-new Date(F.updated_at).getTime()})},[b,s,r,_]);return m?.spoolman_enabled==="true"&&m?.spoolman_url?a.jsx("div",{className:"h-full flex flex-col",children:a.jsx("iframe",{src:`${m.spoolman_url.replace(/\/+$/,"")}/spool`,className:"flex-1 w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}):a.jsxs("div",{className:"h-full flex flex-col",children:[a.jsxs("div",{className:"px-3 pt-3 pb-2 space-y-2.5",children:[a.jsxs("div",{className:"relative",children:[a.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40"}),a.jsx("input",{type:"text",value:r,onChange:T=>i(T.target.value),placeholder:n("spoolbuddy.inventory.searchPlaceholder","Search spools..."),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-white/30 focus:outline-none focus:border-bambu-green"}),r&&a.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/60",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-1.5 overflow-x-auto no-scrollbar",children:[a.jsx(P3,{active:s==="all",onClick:()=>o("all"),label:`${n("spoolbuddy.inventory.all","All")} (${b.length})`,green:!0}),C>0&&a.jsx(P3,{active:s==="in_ams",onClick:()=>o("in_ams"),label:`${n("spoolbuddy.inventory.inAms","In AMS")} (${C})`}),P.map(T=>a.jsx(P3,{active:s===T,onClick:()=>o(s===T?"all":T),label:T},T))]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3",children:f?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx("div",{className:"w-8 h-8 border-2 border-bambu-green border-t-transparent rounded-full animate-spin"})}):N.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-white/30",children:[a.jsx(ja,{className:"w-12 h-12 mb-3"}),a.jsx("p",{className:"text-sm",children:r||s!=="all"?n("spoolbuddy.inventory.noResults","No spools match your filters"):n("spoolbuddy.inventory.empty","No spools in inventory")})]}):a.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(130px,1fr))] gap-2",children:N.map(T=>a.jsx(sit,{spool:T,assignment:g[T.id],onClick:()=>c(T.id)},T.id))})}),l!=null&&(()=>{const T=p.find(k=>k.id===l);if(!T)return null;const F=()=>{c(null),u(!1)};return a.jsxs(a.Fragment,{children:[a.jsx(oit,{spool:T,assignment:g[T.id],sbState:t,onSyncWeight:()=>{x()},onAssignToAms:()=>u(!0),onClose:F}),a.jsx(tce,{isOpen:d,onClose:()=>u(!1),spool:T,printerId:e})]})})()]})}function P3({active:t,onClick:e,label:n,green:r}){return a.jsx("button",{onClick:e,className:`px-4 py-1.5 rounded-full text-sm font-medium border whitespace-nowrap shrink-0 transition-colors ${t?r?"bg-bambu-green/20 text-bambu-green border-bambu-green/50":"bg-white/10 text-white border-white/20":"bg-transparent text-white/40 border-bambu-dark-tertiary hover:text-white/60"}`,children:n})}function sit({spool:t,assignment:e,onClick:n}){const r=eit(t),i=nit(t),s=tit(t),o=FP(t.color_name,t.rgba);return a.jsxs("button",{onClick:n,className:"bg-bambu-dark-secondary rounded-xl p-3 flex flex-col items-center text-center gap-1.5 border border-transparent hover:border-bambu-green/50 transition-colors",children:[a.jsx(ait,{color:r,size:56}),a.jsx("p",{className:"text-xs font-semibold text-white leading-tight truncate w-full",children:rit(t)}),a.jsxs("div",{className:"flex items-center gap-1 min-w-0 max-w-full",children:[a.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 border border-white/10",style:{backgroundColor:r}}),a.jsx("span",{className:"text-[11px] text-white/50 truncate",children:o||"-"})]}),a.jsxs("div",{className:"w-full space-y-0.5",children:[a.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full ${i>50?"bg-bambu-green":i>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(i,100)}%`}})}),a.jsxs("p",{className:"text-[11px] text-white/40",children:[Math.round(s),"g (",Math.round(i),"%)"]})]}),e&&a.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-bambu-green/20 text-bambu-green",children:nce(e)})]})}function oit({spool:t,assignment:e,sbState:n,onSyncWeight:r,onAssignToAms:i,onClose:s}){const l=n.deviceOnline&&n.weight!==null?Math.round(n.weight):null,c=t.last_scale_weight!=null?Math.round(t.last_scale_weight):null;return a.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4",onClick:s,children:a.jsx("div",{className:"w-full max-w-md bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-2xl p-4 overflow-y-auto max-h-[90vh]",onClick:d=>d.stopPropagation(),children:a.jsxs("div",{className:"space-y-3",children:[e&&a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-bambu-green/20 text-bambu-green",children:nce(e)}),e.printer_name&&a.jsx("span",{className:"text-xs text-zinc-400",children:e.printer_name})]}),a.jsx("div",{className:"flex justify-center",children:a.jsx(Jat,{spool:t,liveScaleWeight:l,persistedGrossWeight:c,onSyncWeight:r,onAssignToAms:i,onClose:s,className:"max-w-md"})})]})})})}class lit extends w.Component{state={error:null,errorInfo:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,n){this.setState({errorInfo:n}),console.error("React crash:",e,n)}render(){return this.state.error?a.jsxs("div",{style:{padding:24,color:"#ef4444",backgroundColor:"#18181b",minHeight:"100vh",fontFamily:"monospace"},children:[a.jsx("h1",{style:{fontSize:20,marginBottom:12},children:"UI Crash"}),a.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:14},children:this.state.error.message}),a.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:12,color:"#a1a1aa",marginTop:12},children:this.state.error.stack}),a.jsx("button",{onClick:()=>{this.setState({error:null,errorInfo:null})},style:{marginTop:16,padding:"8px 16px",backgroundColor:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:"Retry"})]}):this.props.children}}const cit=new Xhe({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function dit(){return Grt(),null}function AY({children:t}){return Vrt(),a.jsx(a.Fragment,{children:t})}function jY({children:t}){const{authEnabled:e,loading:n,user:r}=wr();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?a.jsx(Nx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function T3({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:i}=wr();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?i?a.jsx(a.Fragment,{children:t}):a.jsx(Nx,{to:"/",replace:!0}):a.jsx(Nx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function uit({children:t}){const{authEnabled:e,loading:n}=wr();return n?a.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?a.jsx(Nx,{to:"/login",replace:!0}):a.jsx(a.Fragment,{children:t})}function mit(){return a.jsx(lit,{children:a.jsx(cye,{children:a.jsx(vye,{children:a.jsx(Yhe,{client:cit,children:a.jsx(xye,{children:a.jsxs(Wrt,{children:[a.jsx(dit,{}),a.jsx(fhe,{children:a.jsxs($me,{children:[a.jsx(Er,{path:"/setup",element:a.jsx(uit,{children:a.jsx(qrt,{})})}),a.jsx(Er,{path:"/login",element:a.jsx(Hrt,{})}),a.jsx(Er,{path:"/camera/:printerId",element:a.jsx(drt,{})}),a.jsx(Er,{path:"/overlay/:printerId",element:a.jsx(frt,{})}),a.jsxs(Er,{element:a.jsx(jY,{children:a.jsx(AY,{children:a.jsx(lat,{})})}),children:[a.jsx(Er,{path:"spoolbuddy",element:a.jsx(Tat,{})}),a.jsx(Er,{path:"spoolbuddy/ams",element:a.jsx(Mat,{})}),a.jsx(Er,{path:"spoolbuddy/write-tag",element:a.jsx(Wat,{})}),a.jsx(Er,{path:"spoolbuddy/inventory",element:a.jsx(iit,{})}),a.jsx(Er,{path:"spoolbuddy/settings",element:a.jsx(qat,{})}),a.jsx(Er,{path:"spoolbuddy/calibration",element:a.jsx(Vat,{})})]}),a.jsxs(Er,{element:a.jsx(jY,{children:a.jsx(AY,{children:a.jsx(Fye,{})})}),children:[a.jsx(Er,{index:!0,element:a.jsx(R7e,{})}),a.jsx(Er,{path:"archives",element:a.jsx(PJe,{})}),a.jsx(Er,{path:"queue",element:a.jsx(_tt,{})}),a.jsx(Er,{path:"stats",element:a.jsx(Btt,{})}),a.jsx(Er,{path:"profiles",element:a.jsx(Unt,{})}),a.jsx(Er,{path:"maintenance",element:a.jsx(Vnt,{})}),a.jsx(Er,{path:"projects",element:a.jsx(Wnt,{})}),a.jsx(Er,{path:"projects/:id",element:a.jsx(Jnt,{})}),a.jsx(Er,{path:"inventory",element:a.jsx(Frt,{})}),a.jsx(Er,{path:"files",element:a.jsx(srt,{})}),a.jsx(Er,{path:"settings",element:a.jsx(T3,{children:a.jsx(Cnt,{})})}),a.jsx(Er,{path:"groups/new",element:a.jsx(T3,{children:a.jsx(gY,{})})}),a.jsx(Er,{path:"groups/:id/edit",element:a.jsx(T3,{children:a.jsx(gY,{})})}),a.jsx(Er,{path:"users",element:a.jsx(Nx,{to:"/settings?tab=users",replace:!0})}),a.jsx(Er,{path:"groups",element:a.jsx(Nx,{to:"/settings?tab=users",replace:!0})}),a.jsx(Er,{path:"system",element:a.jsx(Brt,{})}),a.jsx(Er,{path:"notifications",element:a.jsx($rt,{})}),a.jsx(Er,{path:"external/:id",element:a.jsx(grt,{})})]})]})})]})})})})})})}zde.createRoot(document.getElementById("root")).render(a.jsx(w.StrictMode,{children:a.jsx(mit,{})}));
|