index-CHKJFwmW.js 6.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737
  1. function que(t,e){for(var n=0;n<e.length;n++){const a=e[n];if(typeof a!="string"&&!Array.isArray(a)){for(const i in a)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(a,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>a[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"]'))a(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"&&a(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 a(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var _k=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Tc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var KM={exports:{}},Yv={};var x8;function $ue(){if(x8)return Yv;x8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(a,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:a,key:o,ref:i!==void 0?i:null,props:s}}return Yv.Fragment=e,Yv.jsx=n,Yv.jsxs=n,Yv}var y8;function Vue(){return y8||(y8=1,KM.exports=$ue()),KM.exports}var r=Vue(),QM={exports:{}},Qn={};var v8;function Gue(){if(v8)return Qn;v8=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=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(Q){return Q===null||typeof Q!="object"?null:(Q=p&&Q[p]||Q["@@iterator"],typeof Q=="function"?Q:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w=Object.assign,b={};function x(Q,le,pe){this.props=Q,this.context=le,this.refs=b,this.updater=pe||g}x.prototype.isReactComponent={},x.prototype.setState=function(Q,le){if(typeof Q!="object"&&typeof Q!="function"&&Q!=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,Q,le,"setState")},x.prototype.forceUpdate=function(Q){this.updater.enqueueForceUpdate(this,Q,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(Q,le,pe){this.props=Q,this.context=le,this.refs=b,this.updater=pe||g}var C=k.prototype=new S;C.constructor=k,w(C,x.prototype),C.isPureReactComponent=!0;var P=Array.isArray;function T(){}var A={H:null,A:null,T:null,S:null},F=Object.prototype.hasOwnProperty;function _(Q,le,pe){var he=pe.ref;return{$$typeof:t,type:Q,key:le,ref:he!==void 0?he:null,props:pe}}function M(Q,le){return _(Q.type,le,Q.props)}function H(Q){return typeof Q=="object"&&Q!==null&&Q.$$typeof===t}function I(Q){var le={"=":"=0",":":"=2"};return"$"+Q.replace(/[=:]/g,function(pe){return le[pe]})}var z=/\/+/g;function L(Q,le){return typeof Q=="object"&&Q!==null&&Q.key!=null?I(""+Q.key):le.toString(36)}function Z(Q){switch(Q.status){case"fulfilled":return Q.value;case"rejected":throw Q.reason;default:switch(typeof Q.status=="string"?Q.then(T,T):(Q.status="pending",Q.then(function(le){Q.status==="pending"&&(Q.status="fulfilled",Q.value=le)},function(le){Q.status==="pending"&&(Q.status="rejected",Q.reason=le)})),Q.status){case"fulfilled":return Q.value;case"rejected":throw Q.reason}}throw Q}function ne(Q,le,pe,he,we){var $=typeof Q;($==="undefined"||$==="boolean")&&(Q=null);var J=!1;if(Q===null)J=!0;else switch($){case"bigint":case"string":case"number":J=!0;break;case"object":switch(Q.$$typeof){case t:case e:J=!0;break;case u:return J=Q._init,ne(J(Q._payload),le,pe,he,we)}}if(J)return we=we(Q),J=he===""?"."+L(Q,0):he,P(we)?(pe="",J!=null&&(pe=J.replace(z,"$&/")+"/"),ne(we,le,pe,"",function(B){return B})):we!=null&&(H(we)&&(we=M(we,pe+(we.key==null||Q&&Q.key===we.key?"":(""+we.key).replace(z,"$&/")+"/")+J)),le.push(we)),1;J=0;var j=he===""?".":he+":";if(P(Q))for(var E=0;E<Q.length;E++)he=Q[E],$=j+L(he,E),J+=ne(he,le,pe,$,we);else if(E=f(Q),typeof E=="function")for(Q=E.call(Q),E=0;!(he=Q.next()).done;)he=he.value,$=j+L(he,E++),J+=ne(he,le,pe,$,we);else if($==="object"){if(typeof Q.then=="function")return ne(Z(Q),le,pe,he,we);throw le=String(Q),Error("Objects are not valid as a React child (found: "+(le==="[object Object]"?"object with keys {"+Object.keys(Q).join(", ")+"}":le)+"). If you meant to render a collection of children, use an array instead.")}return J}function Y(Q,le,pe){if(Q==null)return Q;var he=[],we=0;return ne(Q,he,"","",function($){return le.call(pe,$,we++)}),he}function ce(Q){if(Q._status===-1){var le=Q._result;le=le(),le.then(function(pe){(Q._status===0||Q._status===-1)&&(Q._status=1,Q._result=pe)},function(pe){(Q._status===0||Q._status===-1)&&(Q._status=2,Q._result=pe)}),Q._status===-1&&(Q._status=0,Q._result=le)}if(Q._status===1)return Q._result.default;throw Q._result}var ue=typeof reportError=="function"?reportError:function(Q){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var le=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof Q=="object"&&Q!==null&&typeof Q.message=="string"?String(Q.message):String(Q),error:Q});if(!window.dispatchEvent(le))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",Q);return}console.error(Q)},oe={map:Y,forEach:function(Q,le,pe){Y(Q,function(){le.apply(this,arguments)},pe)},count:function(Q){var le=0;return Y(Q,function(){le++}),le},toArray:function(Q){return Y(Q,function(le){return le})||[]},only:function(Q){if(!H(Q))throw Error("React.Children.only expected to receive a single React element child.");return Q}};return Qn.Activity=m,Qn.Children=oe,Qn.Component=x,Qn.Fragment=n,Qn.Profiler=i,Qn.PureComponent=k,Qn.StrictMode=a,Qn.Suspense=c,Qn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,Qn.__COMPILER_RUNTIME={__proto__:null,c:function(Q){return A.H.useMemoCache(Q)}},Qn.cache=function(Q){return function(){return Q.apply(null,arguments)}},Qn.cacheSignal=function(){return null},Qn.cloneElement=function(Q,le,pe){if(Q==null)throw Error("The argument must be a React element, but you passed "+Q+".");var he=w({},Q.props),we=Q.key;if(le!=null)for($ in le.key!==void 0&&(we=""+le.key),le)!F.call(le,$)||$==="key"||$==="__self"||$==="__source"||$==="ref"&&le.ref===void 0||(he[$]=le[$]);var $=arguments.length-2;if($===1)he.children=pe;else if(1<$){for(var J=Array($),j=0;j<$;j++)J[j]=arguments[j+2];he.children=J}return _(Q.type,we,he)},Qn.createContext=function(Q){return Q={$$typeof:o,_currentValue:Q,_currentValue2:Q,_threadCount:0,Provider:null,Consumer:null},Q.Provider=Q,Q.Consumer={$$typeof:s,_context:Q},Q},Qn.createElement=function(Q,le,pe){var he,we={},$=null;if(le!=null)for(he in le.key!==void 0&&($=""+le.key),le)F.call(le,he)&&he!=="key"&&he!=="__self"&&he!=="__source"&&(we[he]=le[he]);var J=arguments.length-2;if(J===1)we.children=pe;else if(1<J){for(var j=Array(J),E=0;E<J;E++)j[E]=arguments[E+2];we.children=j}if(Q&&Q.defaultProps)for(he in J=Q.defaultProps,J)we[he]===void 0&&(we[he]=J[he]);return _(Q,$,we)},Qn.createRef=function(){return{current:null}},Qn.forwardRef=function(Q){return{$$typeof:l,render:Q}},Qn.isValidElement=H,Qn.lazy=function(Q){return{$$typeof:u,_payload:{_status:-1,_result:Q},_init:ce}},Qn.memo=function(Q,le){return{$$typeof:d,type:Q,compare:le===void 0?null:le}},Qn.startTransition=function(Q){var le=A.T,pe={};A.T=pe;try{var he=Q(),we=A.S;we!==null&&we(pe,he),typeof he=="object"&&he!==null&&typeof he.then=="function"&&he.then(T,ue)}catch($){ue($)}finally{le!==null&&pe.types!==null&&(le.types=pe.types),A.T=le}},Qn.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},Qn.use=function(Q){return A.H.use(Q)},Qn.useActionState=function(Q,le,pe){return A.H.useActionState(Q,le,pe)},Qn.useCallback=function(Q,le){return A.H.useCallback(Q,le)},Qn.useContext=function(Q){return A.H.useContext(Q)},Qn.useDebugValue=function(){},Qn.useDeferredValue=function(Q,le){return A.H.useDeferredValue(Q,le)},Qn.useEffect=function(Q,le){return A.H.useEffect(Q,le)},Qn.useEffectEvent=function(Q){return A.H.useEffectEvent(Q)},Qn.useId=function(){return A.H.useId()},Qn.useImperativeHandle=function(Q,le,pe){return A.H.useImperativeHandle(Q,le,pe)},Qn.useInsertionEffect=function(Q,le){return A.H.useInsertionEffect(Q,le)},Qn.useLayoutEffect=function(Q,le){return A.H.useLayoutEffect(Q,le)},Qn.useMemo=function(Q,le){return A.H.useMemo(Q,le)},Qn.useOptimistic=function(Q,le){return A.H.useOptimistic(Q,le)},Qn.useReducer=function(Q,le,pe){return A.H.useReducer(Q,le,pe)},Qn.useRef=function(Q){return A.H.useRef(Q)},Qn.useState=function(Q){return A.H.useState(Q)},Qn.useSyncExternalStore=function(Q,le,pe){return A.H.useSyncExternalStore(Q,le,pe)},Qn.useTransition=function(){return A.H.useTransition()},Qn.version="19.2.4",Qn}var w8;function tb(){return w8||(w8=1,QM.exports=Gue()),QM.exports}var y=tb();const pa=Tc(y),Wue=que({__proto__:null,default:pa},[y]);var YM={exports:{}},Xv={},XM={exports:{}},ZM={};var S8;function Kue(){return S8||(S8=1,(function(t){function e(ne,Y){var ce=ne.length;ne.push(Y);e:for(;0<ce;){var ue=ce-1>>>1,oe=ne[ue];if(0<i(oe,Y))ne[ue]=Y,ne[ce]=oe,ce=ue;else break e}}function n(ne){return ne.length===0?null:ne[0]}function a(ne){if(ne.length===0)return null;var Y=ne[0],ce=ne.pop();if(ce!==Y){ne[0]=ce;e:for(var ue=0,oe=ne.length,Q=oe>>>1;ue<Q;){var le=2*(ue+1)-1,pe=ne[le],he=le+1,we=ne[he];if(0>i(pe,ce))he<oe&&0>i(we,pe)?(ne[ue]=we,ne[he]=ce,ue=he):(ne[ue]=pe,ne[le]=ce,ue=le);else if(he<oe&&0>i(we,ce))ne[ue]=we,ne[he]=ce,ue=he;else break e}}return Y}function i(ne,Y){var ce=ne.sortIndex-Y.sortIndex;return ce!==0?ce:ne.id-Y.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,g=!1,w=!1,b=!1,x=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function C(ne){for(var Y=n(d);Y!==null;){if(Y.callback===null)a(d);else if(Y.startTime<=ne)a(d),Y.sortIndex=Y.expirationTime,e(c,Y);else break;Y=n(d)}}function P(ne){if(w=!1,C(ne),!g)if(n(c)!==null)g=!0,T||(T=!0,I());else{var Y=n(d);Y!==null&&Z(P,Y.startTime-ne)}}var T=!1,A=-1,F=5,_=-1;function M(){return b?!0:!(t.unstable_now()-_<F)}function H(){if(b=!1,T){var ne=t.unstable_now();_=ne;var Y=!0;try{e:{g=!1,w&&(w=!1,S(A),A=-1),f=!0;var ce=p;try{t:{for(C(ne),m=n(c);m!==null&&!(m.expirationTime>ne&&M());){var ue=m.callback;if(typeof ue=="function"){m.callback=null,p=m.priorityLevel;var oe=ue(m.expirationTime<=ne);if(ne=t.unstable_now(),typeof oe=="function"){m.callback=oe,C(ne),Y=!0;break t}m===n(c)&&a(c),C(ne)}else a(c);m=n(c)}if(m!==null)Y=!0;else{var Q=n(d);Q!==null&&Z(P,Q.startTime-ne),Y=!1}}break e}finally{m=null,p=ce,f=!1}Y=void 0}}finally{Y?I():T=!1}}}var I;if(typeof k=="function")I=function(){k(H)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,L=z.port2;z.port1.onmessage=H,I=function(){L.postMessage(null)}}else I=function(){x(H,0)};function Z(ne,Y){A=x(function(){ne(t.unstable_now())},Y)}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(ne){ne.callback=null},t.unstable_forceFrameRate=function(ne){0>ne||125<ne?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):F=0<ne?Math.floor(1e3/ne):5},t.unstable_getCurrentPriorityLevel=function(){return p},t.unstable_next=function(ne){switch(p){case 1:case 2:case 3:var Y=3;break;default:Y=p}var ce=p;p=Y;try{return ne()}finally{p=ce}},t.unstable_requestPaint=function(){b=!0},t.unstable_runWithPriority=function(ne,Y){switch(ne){case 1:case 2:case 3:case 4:case 5:break;default:ne=3}var ce=p;p=ne;try{return Y()}finally{p=ce}},t.unstable_scheduleCallback=function(ne,Y,ce){var ue=t.unstable_now();switch(typeof ce=="object"&&ce!==null?(ce=ce.delay,ce=typeof ce=="number"&&0<ce?ue+ce:ue):ce=ue,ne){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=ce+oe,ne={id:u++,callback:Y,priorityLevel:ne,startTime:ce,expirationTime:oe,sortIndex:-1},ce>ue?(ne.sortIndex=ce,e(d,ne),n(c)===null&&ne===n(d)&&(w?(S(A),A=-1):w=!0,Z(P,ce-ue))):(ne.sortIndex=oe,e(c,ne),g||f||(g=!0,T||(T=!0,I()))),ne},t.unstable_shouldYield=M,t.unstable_wrapCallback=function(ne){var Y=p;return function(){var ce=p;p=Y;try{return ne.apply(this,arguments)}finally{p=ce}}}})(ZM)),ZM}var _8;function Que(){return _8||(_8=1,XM.exports=Kue()),XM.exports}var JM={exports:{}},Hs={};var k8;function Yue(){if(k8)return Hs;k8=1;var t=tb();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 a={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 Hs.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,Hs.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)},Hs.flushSync=function(c){var d=o.T,u=a.p;try{if(o.T=null,a.p=2,c)return c()}finally{o.T=d,a.p=u,a.d.f()}},Hs.preconnect=function(c,d){typeof c=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,a.d.C(c,d))},Hs.prefetchDNS=function(c){typeof c=="string"&&a.d.D(c)},Hs.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"?a.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:m,integrity:p,fetchPriority:f}):u==="script"&&a.d.X(c,{crossOrigin:m,integrity:p,fetchPriority:f,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},Hs.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);a.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&&a.d.M(c)},Hs.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);a.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})}},Hs.preloadModule=function(c,d){if(typeof c=="string")if(d){var u=l(d.as,d.crossOrigin);a.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 a.d.m(c)},Hs.requestFormReset=function(c){a.d.r(c)},Hs.unstable_batchedUpdates=function(c,d){return c(d)},Hs.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},Hs.useFormStatus=function(){return o.H.useHostTransitionStatus()},Hs.version="19.2.4",Hs}var N8;function BX(){if(N8)return JM.exports;N8=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(),JM.exports=Yue(),JM.exports}var C8;function Xue(){if(C8)return Xv;C8=1;var t=Que(),e=tb(),n=BX();function a(h){var v="https://react.dev/errors/"+h;if(1<arguments.length){v+="?args[]="+encodeURIComponent(arguments[1]);for(var N=2;N<arguments.length;N++)v+="&args[]="+encodeURIComponent(arguments[N])}return"Minified React error #"+h+"; visit "+v+" 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 v=h,N=h;if(h.alternate)for(;v.return;)v=v.return;else{h=v;do v=h,(v.flags&4098)!==0&&(N=v.return),h=v.return;while(h)}return v.tag===3?N:null}function o(h){if(h.tag===13){var v=h.memoizedState;if(v===null&&(h=h.alternate,h!==null&&(v=h.memoizedState)),v!==null)return v.dehydrated}return null}function l(h){if(h.tag===31){var v=h.memoizedState;if(v===null&&(h=h.alternate,h!==null&&(v=h.memoizedState)),v!==null)return v.dehydrated}return null}function c(h){if(s(h)!==h)throw Error(a(188))}function d(h){var v=h.alternate;if(!v){if(v=s(h),v===null)throw Error(a(188));return v!==h?null:h}for(var N=h,D=v;;){var V=N.return;if(V===null)break;var ee=V.alternate;if(ee===null){if(D=V.return,D!==null){N=D;continue}break}if(V.child===ee.child){for(ee=V.child;ee;){if(ee===N)return c(V),h;if(ee===D)return c(V),v;ee=ee.sibling}throw Error(a(188))}if(N.return!==D.return)N=V,D=ee;else{for(var Se=!1,$e=V.child;$e;){if($e===N){Se=!0,N=V,D=ee;break}if($e===D){Se=!0,D=V,N=ee;break}$e=$e.sibling}if(!Se){for($e=ee.child;$e;){if($e===N){Se=!0,N=ee,D=V;break}if($e===D){Se=!0,D=ee,N=V;break}$e=$e.sibling}if(!Se)throw Error(a(189))}}if(N.alternate!==D)throw Error(a(190))}if(N.tag!==3)throw Error(a(188));return N.stateNode.current===N?h:v}function u(h){var v=h.tag;if(v===5||v===26||v===27||v===6)return h;for(h=h.child;h!==null;){if(v=u(h),v!==null)return v;h=h.sibling}return null}var m=Object.assign,p=Symbol.for("react.element"),f=Symbol.for("react.transitional.element"),g=Symbol.for("react.portal"),w=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),A=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),_=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),H=Symbol.iterator;function I(h){return h===null||typeof h!="object"?null:(h=H&&h[H]||h["@@iterator"],typeof h=="function"?h:null)}var z=Symbol.for("react.client.reference");function L(h){if(h==null)return null;if(typeof h=="function")return h.$$typeof===z?null:h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case w:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case P:return"Suspense";case T:return"SuspenseList";case _:return"Activity"}if(typeof h=="object")switch(h.$$typeof){case g:return"Portal";case k:return h.displayName||"Context";case S:return(h._context.displayName||"Context")+".Consumer";case C:var v=h.render;return h=h.displayName,h||(h=v.displayName||v.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case A:return v=h.displayName||null,v!==null?v:L(h.type)||"Memo";case F:v=h._payload,h=h._init;try{return L(h(v))}catch{}}return null}var Z=Array.isArray,ne=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Y=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce={pending:!1,data:null,method:null,action:null},ue=[],oe=-1;function Q(h){return{current:h}}function le(h){0>oe||(h.current=ue[oe],ue[oe]=null,oe--)}function pe(h,v){oe++,ue[oe]=h.current,h.current=v}var he=Q(null),we=Q(null),$=Q(null),J=Q(null);function j(h,v){switch(pe($,v),pe(we,h),pe(he,null),v.nodeType){case 9:case 11:h=(h=v.documentElement)&&(h=h.namespaceURI)?BH(h):0;break;default:if(h=v.tagName,v=v.namespaceURI)v=BH(v),h=HH(v,h);else switch(h){case"svg":h=1;break;case"math":h=2;break;default:h=0}}le(he),pe(he,h)}function E(){le(he),le(we),le($)}function B(h){h.memoizedState!==null&&pe(J,h);var v=he.current,N=HH(v,h.type);v!==N&&(pe(we,h),pe(he,N))}function W(h){we.current===h&&(le(he),le(we)),J.current===h&&(le(J),Gv._currentValue=ce)}var O,ie;function U(h){if(O===void 0)try{throw Error()}catch(N){var v=N.stack.trim().match(/\n( *(at )?)/);O=v&&v[1]||"",ie=-1<N.stack.indexOf(`
  2. at`)?" (<anonymous>)":-1<N.stack.indexOf("@")?"@unknown:0:0":""}return`
  3. `+O+h+ie}var G=!1;function K(h,v){if(!h||G)return"";G=!0;var N=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var D={DetermineComponentFrameRoot:function(){try{if(v){var Gt=function(){throw Error()};if(Object.defineProperty(Gt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Gt,[])}catch(Ot){var Ft=Ot}Reflect.construct(h,[],Gt)}else{try{Gt.call()}catch(Ot){Ft=Ot}h.call(Gt.prototype)}}else{try{throw Error()}catch(Ot){Ft=Ot}(Gt=h())&&typeof Gt.catch=="function"&&Gt.catch(function(){})}}catch(Ot){if(Ot&&Ft&&typeof Ot.stack=="string")return[Ot.stack,Ft.stack]}return[null,null]}};D.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var V=Object.getOwnPropertyDescriptor(D.DetermineComponentFrameRoot,"name");V&&V.configurable&&Object.defineProperty(D.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var ee=D.DetermineComponentFrameRoot(),Se=ee[0],$e=ee[1];if(Se&&$e){var pt=Se.split(`
  4. `),Mt=$e.split(`
  5. `);for(V=D=0;D<pt.length&&!pt[D].includes("DetermineComponentFrameRoot");)D++;for(;V<Mt.length&&!Mt[V].includes("DetermineComponentFrameRoot");)V++;if(D===pt.length||V===Mt.length)for(D=pt.length-1,V=Mt.length-1;1<=D&&0<=V&&pt[D]!==Mt[V];)V--;for(;1<=D&&0<=V;D--,V--)if(pt[D]!==Mt[V]){if(D!==1||V!==1)do if(D--,V--,0>V||pt[D]!==Mt[V]){var Ht=`
  6. `+pt[D].replace(" at new "," at ");return h.displayName&&Ht.includes("<anonymous>")&&(Ht=Ht.replace("<anonymous>",h.displayName)),Ht}while(1<=D&&0<=V);break}}}finally{G=!1,Error.prepareStackTrace=N}return(N=h?h.displayName||h.name:"")?U(N):""}function X(h,v){switch(h.tag){case 26:case 27:case 5:return U(h.type);case 16:return U("Lazy");case 13:return h.child!==v&&v!==null?U("Suspense Fallback"):U("Suspense");case 19:return U("SuspenseList");case 0:case 15:return K(h.type,!1);case 11:return K(h.type.render,!1);case 1:return K(h.type,!0);case 31:return U("Activity");default:return""}}function se(h){try{var v="",N=null;do v+=X(h,N),N=h,h=h.return;while(h);return v}catch(D){return`
  7. Error generating stack: `+D.message+`
  8. `+D.stack}}var te=Object.prototype.hasOwnProperty,fe=t.unstable_scheduleCallback,de=t.unstable_cancelCallback,me=t.unstable_shouldYield,q=t.unstable_requestPaint,R=t.unstable_now,re=t.unstable_getCurrentPriorityLevel,be=t.unstable_ImmediatePriority,ye=t.unstable_UserBlockingPriority,_e=t.unstable_NormalPriority,xe=t.unstable_LowPriority,ge=t.unstable_IdlePriority,Me=t.log,Be=t.unstable_setDisableYieldValue,Fe=null,Oe=null;function Re(h){if(typeof Me=="function"&&Be(h),Oe&&typeof Oe.setStrictMode=="function")try{Oe.setStrictMode(Fe,h)}catch{}}var We=Math.clz32?Math.clz32:Ee,ze=Math.log,st=Math.LN2;function Ee(h){return h>>>=0,h===0?32:31-(ze(h)/st|0)|0}var it=256,Ce=262144,Ze=4194304;function Ie(h){var v=h&42;if(v!==0)return v;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 ke(h,v,N){var D=h.pendingLanes;if(D===0)return 0;var V=0,ee=h.suspendedLanes,Se=h.pingedLanes;h=h.warmLanes;var $e=D&134217727;return $e!==0?(D=$e&~ee,D!==0?V=Ie(D):(Se&=$e,Se!==0?V=Ie(Se):N||(N=$e&~h,N!==0&&(V=Ie(N))))):($e=D&~ee,$e!==0?V=Ie($e):Se!==0?V=Ie(Se):N||(N=D&~h,N!==0&&(V=Ie(N)))),V===0?0:v!==0&&v!==V&&(v&ee)===0&&(ee=V&-V,N=v&-v,ee>=N||ee===32&&(N&4194048)!==0)?v:V}function Ve(h,v){return(h.pendingLanes&~(h.suspendedLanes&~h.pingedLanes)&v)===0}function rt(h,v){switch(h){case 1:case 2:case 4:case 8:case 64:return v+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 v+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 Qe(){var h=Ze;return Ze<<=1,(Ze&62914560)===0&&(Ze=4194304),h}function Te(h){for(var v=[],N=0;31>N;N++)v.push(h);return v}function tt(h,v){h.pendingLanes|=v,v!==268435456&&(h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0)}function ot(h,v,N,D,V,ee){var Se=h.pendingLanes;h.pendingLanes=N,h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0,h.expiredLanes&=N,h.entangledLanes&=N,h.errorRecoveryDisabledLanes&=N,h.shellSuspendCounter=0;var $e=h.entanglements,pt=h.expirationTimes,Mt=h.hiddenUpdates;for(N=Se&~N;0<N;){var Ht=31-We(N),Gt=1<<Ht;$e[Ht]=0,pt[Ht]=-1;var Ft=Mt[Ht];if(Ft!==null)for(Mt[Ht]=null,Ht=0;Ht<Ft.length;Ht++){var Ot=Ft[Ht];Ot!==null&&(Ot.lane&=-536870913)}N&=~Gt}D!==0&&Tt(h,D,0),ee!==0&&V===0&&h.tag!==0&&(h.suspendedLanes|=ee&~(Se&~v))}function Tt(h,v,N){h.pendingLanes|=v,h.suspendedLanes&=~v;var D=31-We(v);h.entangledLanes|=v,h.entanglements[D]=h.entanglements[D]|1073741824|N&261930}function Ut(h,v){var N=h.entangledLanes|=v;for(h=h.entanglements;N;){var D=31-We(N),V=1<<D;V&v|h[D]&v&&(h[D]|=v),N&=~V}}function bt(h,v){var N=v&-v;return N=(N&42)!==0?1:Wt(N),(N&(h.suspendedLanes|v))!==0?0:N}function Wt(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 Zt(h){return h&=-h,2<h?8<h?(h&134217727)!==0?32:268435456:8:2}function ln(){var h=Y.p;return h!==0?h:(h=window.event,h===void 0?32:u8(h.type))}function cn(h,v){var N=Y.p;try{return Y.p=h,v()}finally{Y.p=N}}var ct=Math.random().toString(36).slice(2),kt="__reactFiber$"+ct,Nt="__reactProps$"+ct,ut="__reactContainer$"+ct,Ct="__reactEvents$"+ct,Le="__reactListeners$"+ct,Ae="__reactHandles$"+ct,Ge="__reactResources$"+ct,Je="__reactMarker$"+ct;function De(h){delete h[kt],delete h[Nt],delete h[Ct],delete h[Le],delete h[Ae]}function mt(h){var v=h[kt];if(v)return v;for(var N=h.parentNode;N;){if(v=N[ut]||N[kt]){if(N=v.alternate,v.child!==null||N!==null&&N.child!==null)for(h=QH(h);h!==null;){if(N=h[kt])return N;h=QH(h)}return v}h=N,N=h.parentNode}return null}function Ne(h){if(h=h[kt]||h[ut]){var v=h.tag;if(v===5||v===6||v===13||v===31||v===26||v===27||v===3)return h}return null}function Ye(h){var v=h.tag;if(v===5||v===26||v===27||v===6)return h.stateNode;throw Error(a(33))}function nt(h){var v=h[Ge];return v||(v=h[Ge]={hoistableStyles:new Map,hoistableScripts:new Map}),v}function at(h){h[Je]=!0}var et=new Set,vt={};function wt(h,v){Ue(h,v),Ue(h+"Capture",v)}function Ue(h,v){for(vt[h]=v,h=0;h<v.length;h++)et.add(v[h])}var He=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]*$"),Dt={},Rt={};function qe(h){return te.call(Rt,h)?!0:te.call(Dt,h)?!1:He.test(h)?Rt[h]=!0:(Dt[h]=!0,!1)}function Ke(h,v,N){if(qe(v))if(N===null)h.removeAttribute(v);else{switch(typeof N){case"undefined":case"function":case"symbol":h.removeAttribute(v);return;case"boolean":var D=v.toLowerCase().slice(0,5);if(D!=="data-"&&D!=="aria-"){h.removeAttribute(v);return}}h.setAttribute(v,""+N)}}function Bt(h,v,N){if(N===null)h.removeAttribute(v);else{switch(typeof N){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(v);return}h.setAttribute(v,""+N)}}function Qt(h,v,N,D){if(D===null)h.removeAttribute(N);else{switch(typeof D){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(N);return}h.setAttributeNS(v,N,""+D)}}function dn(h){switch(typeof h){case"bigint":case"boolean":case"number":case"string":case"undefined":return h;case"object":return h;default:return""}}function nn(h){var v=h.type;return(h=h.nodeName)&&h.toLowerCase()==="input"&&(v==="checkbox"||v==="radio")}function rn(h,v,N){var D=Object.getOwnPropertyDescriptor(h.constructor.prototype,v);if(!h.hasOwnProperty(v)&&typeof D<"u"&&typeof D.get=="function"&&typeof D.set=="function"){var V=D.get,ee=D.set;return Object.defineProperty(h,v,{configurable:!0,get:function(){return V.call(this)},set:function(Se){N=""+Se,ee.call(this,Se)}}),Object.defineProperty(h,v,{enumerable:D.enumerable}),{getValue:function(){return N},setValue:function(Se){N=""+Se},stopTracking:function(){h._valueTracker=null,delete h[v]}}}}function yn(h){if(!h._valueTracker){var v=nn(h)?"checked":"value";h._valueTracker=rn(h,v,""+h[v])}}function Mn(h){if(!h)return!1;var v=h._valueTracker;if(!v)return!0;var N=v.getValue(),D="";return h&&(D=nn(h)?h.checked?"true":"false":h.value),h=D,h!==N?(v.setValue(h),!0):!1}function or(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 Dr=/[\n"\\]/g;function Gn(h){return h.replace(Dr,function(v){return"\\"+v.charCodeAt(0).toString(16)+" "})}function pi(h,v,N,D,V,ee,Se,$e){h.name="",Se!=null&&typeof Se!="function"&&typeof Se!="symbol"&&typeof Se!="boolean"?h.type=Se:h.removeAttribute("type"),v!=null?Se==="number"?(v===0&&h.value===""||h.value!=v)&&(h.value=""+dn(v)):h.value!==""+dn(v)&&(h.value=""+dn(v)):Se!=="submit"&&Se!=="reset"||h.removeAttribute("value"),v!=null?vr(h,Se,dn(v)):N!=null?vr(h,Se,dn(N)):D!=null&&h.removeAttribute("value"),V==null&&ee!=null&&(h.defaultChecked=!!ee),V!=null&&(h.checked=V&&typeof V!="function"&&typeof V!="symbol"),$e!=null&&typeof $e!="function"&&typeof $e!="symbol"&&typeof $e!="boolean"?h.name=""+dn($e):h.removeAttribute("name")}function Un(h,v,N,D,V,ee,Se,$e){if(ee!=null&&typeof ee!="function"&&typeof ee!="symbol"&&typeof ee!="boolean"&&(h.type=ee),v!=null||N!=null){if(!(ee!=="submit"&&ee!=="reset"||v!=null)){yn(h);return}N=N!=null?""+dn(N):"",v=v!=null?""+dn(v):N,$e||v===h.value||(h.value=v),h.defaultValue=v}D=D??V,D=typeof D!="function"&&typeof D!="symbol"&&!!D,h.checked=$e?h.checked:!!D,h.defaultChecked=!!D,Se!=null&&typeof Se!="function"&&typeof Se!="symbol"&&typeof Se!="boolean"&&(h.name=Se),yn(h)}function vr(h,v,N){v==="number"&&or(h.ownerDocument)===h||h.defaultValue===""+N||(h.defaultValue=""+N)}function ua(h,v,N,D){if(h=h.options,v){v={};for(var V=0;V<N.length;V++)v["$"+N[V]]=!0;for(N=0;N<h.length;N++)V=v.hasOwnProperty("$"+h[N].value),h[N].selected!==V&&(h[N].selected=V),V&&D&&(h[N].defaultSelected=!0)}else{for(N=""+dn(N),v=null,V=0;V<h.length;V++){if(h[V].value===N){h[V].selected=!0,D&&(h[V].defaultSelected=!0);return}v!==null||h[V].disabled||(v=h[V])}v!==null&&(v.selected=!0)}}function Fr(h,v,N){if(v!=null&&(v=""+dn(v),v!==h.value&&(h.value=v),N==null)){h.defaultValue!==v&&(h.defaultValue=v);return}h.defaultValue=N!=null?""+dn(N):""}function ba(h,v,N,D){if(v==null){if(D!=null){if(N!=null)throw Error(a(92));if(Z(D)){if(1<D.length)throw Error(a(93));D=D[0]}N=D}N==null&&(N=""),v=N}N=dn(v),h.defaultValue=N,D=h.textContent,D===N&&D!==""&&D!==null&&(h.value=D),yn(h)}function Mi(h,v){if(v){var N=h.firstChild;if(N&&N===h.lastChild&&N.nodeType===3){N.nodeValue=v;return}}h.textContent=v}var Ki=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 wd(h,v,N){var D=v.indexOf("--")===0;N==null||typeof N=="boolean"||N===""?D?h.setProperty(v,""):v==="float"?h.cssFloat="":h[v]="":D?h.setProperty(v,N):typeof N!="number"||N===0||Ki.has(v)?v==="float"?h.cssFloat=N:h[v]=(""+N).trim():h[v]=N+"px"}function Mc(h,v,N){if(v!=null&&typeof v!="object")throw Error(a(62));if(h=h.style,N!=null){for(var D in N)!N.hasOwnProperty(D)||v!=null&&v.hasOwnProperty(D)||(D.indexOf("--")===0?h.setProperty(D,""):D==="float"?h.cssFloat="":h[D]="");for(var V in v)D=v[V],v.hasOwnProperty(V)&&N[V]!==D&&wd(h,V,D)}else for(var ee in v)v.hasOwnProperty(ee)&&wd(h,ee,v[ee])}function zs(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 It=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"]]),_n=/^[\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 ur(h){return _n.test(""+h)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":h}function Kt(){}var Ec=null;function Dc(h){return h=h.target||h.srcElement||window,h.correspondingUseElement&&(h=h.correspondingUseElement),h.nodeType===3?h.parentNode:h}var Fc=null,Ei=null;function cp(h){var v=Ne(h);if(v&&(h=v.stateNode)){var N=h[Nt]||null;e:switch(h=v.stateNode,v.type){case"input":if(pi(h,N.value,N.defaultValue,N.defaultValue,N.checked,N.defaultChecked,N.type,N.name),v=N.name,N.type==="radio"&&v!=null){for(N=h;N.parentNode;)N=N.parentNode;for(N=N.querySelectorAll('input[name="'+Gn(""+v)+'"][type="radio"]'),v=0;v<N.length;v++){var D=N[v];if(D!==h&&D.form===h.form){var V=D[Nt]||null;if(!V)throw Error(a(90));pi(D,V.value,V.defaultValue,V.defaultValue,V.checked,V.defaultChecked,V.type,V.name)}}for(v=0;v<N.length;v++)D=N[v],D.form===h.form&&Mn(D)}break e;case"textarea":Fr(h,N.value,N.defaultValue);break e;case"select":v=N.value,v!=null&&ua(h,!!N.multiple,v,!1)}}}var Tu=!1;function kr(h,v,N){if(Tu)return h(v,N);Tu=!0;try{var D=h(v);return D}finally{if(Tu=!1,(Fc!==null||Ei!==null)&&(tk(),Fc&&(v=Fc,h=Ei,Ei=Fc=null,cp(v),h)))for(v=0;v<h.length;v++)cp(h[v])}}function Sd(h,v){var N=h.stateNode;if(N===null)return null;var D=N[Nt]||null;if(D===null)return null;N=D[v];e:switch(v){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(D=!D.disabled)||(h=h.type,D=!(h==="button"||h==="input"||h==="select"||h==="textarea")),h=!D;break e;default:h=!1}if(h)return null;if(N&&typeof N!="function")throw Error(a(231,v,typeof N));return N}var jo=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Us=!1;if(jo)try{var Lc={};Object.defineProperty(Lc,"passive",{get:function(){Us=!0}}),window.addEventListener("test",Lc,Lc),window.removeEventListener("test",Lc,Lc)}catch{Us=!1}var Ma=null,dp=null,up=null;function hi(){if(up)return up;var h,v=dp,N=v.length,D,V="value"in Ma?Ma.value:Ma.textContent,ee=V.length;for(h=0;h<N&&v[h]===V[h];h++);var Se=N-h;for(D=1;D<=Se&&v[N-D]===V[ee-D];D++);return up=V.slice(h,1<D?1-D:void 0)}function nl(h){var v=h.keyCode;return"charCode"in h?(h=h.charCode,h===0&&v===13&&(h=13)):h=v,h===10&&(h=13),32<=h||h===13?h:0}function Rc(){return!0}function mp(){return!1}function Ea(h){function v(N,D,V,ee,Se){this._reactName=N,this._targetInst=V,this.type=D,this.nativeEvent=ee,this.target=Se,this.currentTarget=null;for(var $e in h)h.hasOwnProperty($e)&&(N=h[$e],this[$e]=N?N(ee):ee[$e]);return this.isDefaultPrevented=(ee.defaultPrevented!=null?ee.defaultPrevented:ee.returnValue===!1)?Rc:mp,this.isPropagationStopped=mp,this}return m(v.prototype,{preventDefault:function(){this.defaultPrevented=!0;var N=this.nativeEvent;N&&(N.preventDefault?N.preventDefault():typeof N.returnValue!="unknown"&&(N.returnValue=!1),this.isDefaultPrevented=Rc)},stopPropagation:function(){var N=this.nativeEvent;N&&(N.stopPropagation?N.stopPropagation():typeof N.cancelBubble!="unknown"&&(N.cancelBubble=!0),this.isPropagationStopped=Rc)},persist:function(){},isPersistent:Rc}),v}var Mo={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(h){return h.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Eo=Ea(Mo),Ic=m({},Mo,{view:0,detail:0}),_d=Ea(Ic),kd,lo,Bs,Au=m({},Ic,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:co,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!==Bs&&(Bs&&h.type==="mousemove"?(kd=h.screenX-Bs.screenX,lo=h.screenY-Bs.screenY):lo=kd=0,Bs=h),kd)},movementY:function(h){return"movementY"in h?h.movementY:lo}}),hb=Ea(Au),fb=m({},Au,{dataTransfer:0}),gb=Ea(fb),gv=m({},Ic,{relatedTarget:0}),Oc=Ea(gv),pp=m({},Mo,{animationName:0,elapsedTime:0,pseudoElement:0}),Ml=Ea(pp),El=m({},Mo,{clipboardData:function(h){return"clipboardData"in h?h.clipboardData:window.clipboardData}}),zc=Ea(El),Uc=m({},Mo,{data:0}),Qi=Ea(Uc),Nd={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ju={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"},hp={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Cd(h){var v=this.nativeEvent;return v.getModifierState?v.getModifierState(h):(h=hp[h])?!!v[h]:!1}function co(){return Cd}var Cn=m({},Ic,{key:function(h){if(h.key){var v=Nd[h.key]||h.key;if(v!=="Unidentified")return v}return h.type==="keypress"?(h=nl(h),h===13?"Enter":String.fromCharCode(h)):h.type==="keydown"||h.type==="keyup"?ju[h.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:co,charCode:function(h){return h.type==="keypress"?nl(h):0},keyCode:function(h){return h.type==="keydown"||h.type==="keyup"?h.keyCode:0},which:function(h){return h.type==="keypress"?nl(h):h.type==="keydown"||h.type==="keyup"?h.keyCode:0}}),Pd=Ea(Cn),Td=m({},Au,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Ad=Ea(Td),ff=m({},Ic,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:co}),bb=Ea(ff),Dl=m({},Mo,{propertyName:0,elapsedTime:0,pseudoElement:0}),gf=Ea(Dl),fp=m({},Au,{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}),xb=Ea(fp),bv=m({},Mo,{newState:0,oldState:0}),Bc=Ea(bv),ys=[9,13,27,32],Yi=jo&&"CompositionEvent"in window,Fl=null;jo&&"documentMode"in document&&(Fl=document.documentMode);var bf=jo&&"TextEvent"in window&&!Fl,yb=jo&&(!Yi||Fl&&8<Fl&&11>=Fl),ve=" ",zt=!1;function mn(h,v){switch(h){case"keyup":return ys.indexOf(v.keyCode)!==-1;case"keydown":return v.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function An(h){return h=h.detail,typeof h=="object"&&"data"in h?h.data:null}var zn=!1;function dt(h,v){switch(h){case"compositionend":return An(v);case"keypress":return v.which!==32?null:(zt=!0,ve);case"textInput":return h=v.data,h===ve&&zt?null:h;default:return null}}function qt(h,v){if(zn)return h==="compositionend"||!Yi&&mn(h,v)?(h=hi(),up=dp=Ma=null,zn=!1,h):null;switch(h){case"paste":return null;case"keypress":if(!(v.ctrlKey||v.altKey||v.metaKey)||v.ctrlKey&&v.altKey){if(v.char&&1<v.char.length)return v.char;if(v.which)return String.fromCharCode(v.which)}return null;case"compositionend":return yb&&v.locale!=="ko"?null:v.data;default:return null}}var Xt={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 ht(h){var v=h&&h.nodeName&&h.nodeName.toLowerCase();return v==="input"?!!Xt[h.type]:v==="textarea"}function In(h,v,N,D){Fc?Ei?Ei.push(D):Ei=[D]:Fc=D,v=lk(v,"onChange"),0<v.length&&(N=new Eo("onChange","change",null,N,D),h.push({event:N,listeners:v}))}var Nr=null,Hn=null;function xa(h){LH(h,0)}function ya(h){var v=Ye(h);if(Mn(v))return h}function an(h,v){if(h==="change")return v}var Tn=!1;if(jo){var ka;if(jo){var Ka="oninput"in document;if(!Ka){var Di=document.createElement("div");Di.setAttribute("oninput","return;"),Ka=typeof Di.oninput=="function"}ka=Ka}else ka=!1;Tn=ka&&(!document.documentMode||9<document.documentMode)}function Ll(){Nr&&(Nr.detachEvent("onpropertychange",Rl),Hn=Nr=null)}function Rl(h){if(h.propertyName==="value"&&ya(Hn)){var v=[];In(v,Hn,h,Dc(h)),kr(xa,v)}}function Mu(h,v,N){h==="focusin"?(Ll(),Nr=v,Hn=N,Nr.attachEvent("onpropertychange",Rl)):h==="focusout"&&Ll()}function Wr(h){if(h==="selectionchange"||h==="keyup"||h==="keydown")return ya(Hn)}function Qa(h,v){if(h==="click")return ya(v)}function Il(h,v){if(h==="input"||h==="change")return ya(v)}function rl(h,v){return h===v&&(h!==0||1/h===1/v)||h!==h&&v!==v}var Na=typeof Object.is=="function"?Object.is:rl;function Br(h,v){if(Na(h,v))return!0;if(typeof h!="object"||h===null||typeof v!="object"||v===null)return!1;var N=Object.keys(h),D=Object.keys(v);if(N.length!==D.length)return!1;for(D=0;D<N.length;D++){var V=N[D];if(!te.call(v,V)||!Na(h[V],v[V]))return!1}return!0}function Do(h){for(;h&&h.firstChild;)h=h.firstChild;return h}function uo(h,v){var N=Do(h);h=0;for(var D;N;){if(N.nodeType===3){if(D=h+N.textContent.length,h<=v&&D>=v)return{node:N,offset:v-h};h=D}e:{for(;N;){if(N.nextSibling){N=N.nextSibling;break e}N=N.parentNode}N=void 0}N=Do(N)}}function Fi(h,v){return h&&v?h===v?!0:h&&h.nodeType===3?!1:v&&v.nodeType===3?Fi(h,v.parentNode):"contains"in h?h.contains(v):h.compareDocumentPosition?!!(h.compareDocumentPosition(v)&16):!1:!1}function Hc(h){h=h!=null&&h.ownerDocument!=null&&h.ownerDocument.defaultView!=null?h.ownerDocument.defaultView:window;for(var v=or(h.document);v instanceof h.HTMLIFrameElement;){try{var N=typeof v.contentWindow.location.href=="string"}catch{N=!1}if(N)h=v.contentWindow;else break;v=or(h.document)}return v}function Xi(h){var v=h&&h.nodeName&&h.nodeName.toLowerCase();return v&&(v==="input"&&(h.type==="text"||h.type==="search"||h.type==="tel"||h.type==="url"||h.type==="password")||v==="textarea"||h.contentEditable==="true")}var wr=jo&&"documentMode"in document&&11>=document.documentMode,Mr=null,Ya=null,qc=null,pn=!1;function xf(h,v,N){var D=N.window===N?N.document:N.nodeType===9?N:N.ownerDocument;pn||Mr==null||Mr!==or(D)||(D=Mr,"selectionStart"in D&&Xi(D)?D={start:D.selectionStart,end:D.selectionEnd}:(D=(D.ownerDocument&&D.ownerDocument.defaultView||window).getSelection(),D={anchorNode:D.anchorNode,anchorOffset:D.anchorOffset,focusNode:D.focusNode,focusOffset:D.focusOffset}),qc&&Br(qc,D)||(qc=D,D=lk(Ya,"onSelect"),0<D.length&&(v=new Eo("onSelect","select",null,v,N),h.push({event:v,listeners:D}),v.target=Mr)))}function Lr(h,v){var N={};return N[h.toLowerCase()]=v.toLowerCase(),N["Webkit"+h]="webkit"+v,N["Moz"+h]="moz"+v,N}var $c={animationend:Lr("Animation","AnimationEnd"),animationiteration:Lr("Animation","AnimationIteration"),animationstart:Lr("Animation","AnimationStart"),transitionrun:Lr("Transition","TransitionRun"),transitionstart:Lr("Transition","TransitionStart"),transitioncancel:Lr("Transition","TransitionCancel"),transitionend:Lr("Transition","TransitionEnd")},vb={},v_={};jo&&(v_=document.createElement("div").style,"AnimationEvent"in window||(delete $c.animationend.animation,delete $c.animationiteration.animation,delete $c.animationstart.animation),"TransitionEvent"in window||delete $c.transitionend.transition);function Eu(h){if(vb[h])return vb[h];if(!$c[h])return h;var v=$c[h],N;for(N in v)if(v.hasOwnProperty(N)&&N in v_)return vb[h]=v[N];return h}var uU=Eu("animationend"),mU=Eu("animationiteration"),pU=Eu("animationstart"),_de=Eu("transitionrun"),kde=Eu("transitionstart"),Nde=Eu("transitioncancel"),hU=Eu("transitionend"),fU=new Map,oj="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(" ");oj.push("scrollEnd");function Vc(h,v){fU.set(h,v),wt(v,[h])}var w_=typeof reportError=="function"?reportError:function(h){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var v=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(v))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",h);return}console.error(h)},Ol=[],wb=0,lj=0;function S_(){for(var h=wb,v=lj=wb=0;v<h;){var N=Ol[v];Ol[v++]=null;var D=Ol[v];Ol[v++]=null;var V=Ol[v];Ol[v++]=null;var ee=Ol[v];if(Ol[v++]=null,D!==null&&V!==null){var Se=D.pending;Se===null?V.next=V:(V.next=Se.next,Se.next=V),D.pending=V}ee!==0&&gU(N,V,ee)}}function __(h,v,N,D){Ol[wb++]=h,Ol[wb++]=v,Ol[wb++]=N,Ol[wb++]=D,lj|=D,h.lanes|=D,h=h.alternate,h!==null&&(h.lanes|=D)}function cj(h,v,N,D){return __(h,v,N,D),k_(h)}function yf(h,v){return __(h,null,null,v),k_(h)}function gU(h,v,N){h.lanes|=N;var D=h.alternate;D!==null&&(D.lanes|=N);for(var V=!1,ee=h.return;ee!==null;)ee.childLanes|=N,D=ee.alternate,D!==null&&(D.childLanes|=N),ee.tag===22&&(h=ee.stateNode,h===null||h._visibility&1||(V=!0)),h=ee,ee=ee.return;return h.tag===3?(ee=h.stateNode,V&&v!==null&&(V=31-We(N),h=ee.hiddenUpdates,D=h[V],D===null?h[V]=[v]:D.push(v),v.lane=N|536870912),ee):null}function k_(h){if(50<zv)throw zv=0,xM=null,Error(a(185));for(var v=h.return;v!==null;)h=v,v=h.return;return h.tag===3?h.stateNode:null}var Sb={};function Cde(h,v,N,D){this.tag=h,this.key=N,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=v,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=D,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function al(h,v,N,D){return new Cde(h,v,N,D)}function dj(h){return h=h.prototype,!(!h||!h.isReactComponent)}function Du(h,v){var N=h.alternate;return N===null?(N=al(h.tag,v,h.key,h.mode),N.elementType=h.elementType,N.type=h.type,N.stateNode=h.stateNode,N.alternate=h,h.alternate=N):(N.pendingProps=v,N.type=h.type,N.flags=0,N.subtreeFlags=0,N.deletions=null),N.flags=h.flags&65011712,N.childLanes=h.childLanes,N.lanes=h.lanes,N.child=h.child,N.memoizedProps=h.memoizedProps,N.memoizedState=h.memoizedState,N.updateQueue=h.updateQueue,v=h.dependencies,N.dependencies=v===null?null:{lanes:v.lanes,firstContext:v.firstContext},N.sibling=h.sibling,N.index=h.index,N.ref=h.ref,N.refCleanup=h.refCleanup,N}function bU(h,v){h.flags&=65011714;var N=h.alternate;return N===null?(h.childLanes=0,h.lanes=v,h.child=null,h.subtreeFlags=0,h.memoizedProps=null,h.memoizedState=null,h.updateQueue=null,h.dependencies=null,h.stateNode=null):(h.childLanes=N.childLanes,h.lanes=N.lanes,h.child=N.child,h.subtreeFlags=0,h.deletions=null,h.memoizedProps=N.memoizedProps,h.memoizedState=N.memoizedState,h.updateQueue=N.updateQueue,h.type=N.type,v=N.dependencies,h.dependencies=v===null?null:{lanes:v.lanes,firstContext:v.firstContext}),h}function N_(h,v,N,D,V,ee){var Se=0;if(D=h,typeof h=="function")dj(h)&&(Se=1);else if(typeof h=="string")Se=Mue(h,N,he.current)?26:h==="html"||h==="head"||h==="body"?27:5;else e:switch(h){case _:return h=al(31,N,v,V),h.elementType=_,h.lanes=ee,h;case w:return vf(N.children,V,ee,v);case b:Se=8,V|=24;break;case x:return h=al(12,N,v,V|2),h.elementType=x,h.lanes=ee,h;case P:return h=al(13,N,v,V),h.elementType=P,h.lanes=ee,h;case T:return h=al(19,N,v,V),h.elementType=T,h.lanes=ee,h;default:if(typeof h=="object"&&h!==null)switch(h.$$typeof){case k:Se=10;break e;case S:Se=9;break e;case C:Se=11;break e;case A:Se=14;break e;case F:Se=16,D=null;break e}Se=29,N=Error(a(130,h===null?"null":typeof h,"")),D=null}return v=al(Se,N,v,V),v.elementType=h,v.type=D,v.lanes=ee,v}function vf(h,v,N,D){return h=al(7,h,D,v),h.lanes=N,h}function uj(h,v,N){return h=al(6,h,null,v),h.lanes=N,h}function xU(h){var v=al(18,null,null,0);return v.stateNode=h,v}function mj(h,v,N){return v=al(4,h.children!==null?h.children:[],h.key,v),v.lanes=N,v.stateNode={containerInfo:h.containerInfo,pendingChildren:null,implementation:h.implementation},v}var yU=new WeakMap;function zl(h,v){if(typeof h=="object"&&h!==null){var N=yU.get(h);return N!==void 0?N:(v={value:h,source:v,stack:se(v)},yU.set(h,v),v)}return{value:h,source:v,stack:se(v)}}var _b=[],kb=0,C_=null,xv=0,Ul=[],Bl=0,gp=null,jd=1,Md="";function Fu(h,v){_b[kb++]=xv,_b[kb++]=C_,C_=h,xv=v}function vU(h,v,N){Ul[Bl++]=jd,Ul[Bl++]=Md,Ul[Bl++]=gp,gp=h;var D=jd;h=Md;var V=32-We(D)-1;D&=~(1<<V),N+=1;var ee=32-We(v)+V;if(30<ee){var Se=V-V%5;ee=(D&(1<<Se)-1).toString(32),D>>=Se,V-=Se,jd=1<<32-We(v)+V|N<<V|D,Md=ee+h}else jd=1<<ee|N<<V|D,Md=h}function pj(h){h.return!==null&&(Fu(h,1),vU(h,1,0))}function hj(h){for(;h===C_;)C_=_b[--kb],_b[kb]=null,xv=_b[--kb],_b[kb]=null;for(;h===gp;)gp=Ul[--Bl],Ul[Bl]=null,Md=Ul[--Bl],Ul[Bl]=null,jd=Ul[--Bl],Ul[Bl]=null}function wU(h,v){Ul[Bl++]=jd,Ul[Bl++]=Md,Ul[Bl++]=gp,jd=v.id,Md=v.overflow,gp=h}var vs=null,Ca=null,Cr=!1,bp=null,Hl=!1,fj=Error(a(519));function xp(h){var v=Error(a(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw yv(zl(v,h)),fj}function SU(h){var v=h.stateNode,N=h.type,D=h.memoizedProps;switch(v[kt]=h,v[Nt]=D,N){case"dialog":gr("cancel",v),gr("close",v);break;case"iframe":case"object":case"embed":gr("load",v);break;case"video":case"audio":for(N=0;N<Bv.length;N++)gr(Bv[N],v);break;case"source":gr("error",v);break;case"img":case"image":case"link":gr("error",v),gr("load",v);break;case"details":gr("toggle",v);break;case"input":gr("invalid",v),Un(v,D.value,D.defaultValue,D.checked,D.defaultChecked,D.type,D.name,!0);break;case"select":gr("invalid",v);break;case"textarea":gr("invalid",v),ba(v,D.value,D.defaultValue,D.children)}N=D.children,typeof N!="string"&&typeof N!="number"&&typeof N!="bigint"||v.textContent===""+N||D.suppressHydrationWarning===!0||zH(v.textContent,N)?(D.popover!=null&&(gr("beforetoggle",v),gr("toggle",v)),D.onScroll!=null&&gr("scroll",v),D.onScrollEnd!=null&&gr("scrollend",v),D.onClick!=null&&(v.onclick=Kt),v=!0):v=!1,v||xp(h,!0)}function _U(h){for(vs=h.return;vs;)switch(vs.tag){case 5:case 31:case 13:Hl=!1;return;case 27:case 3:Hl=!0;return;default:vs=vs.return}}function Nb(h){if(h!==vs)return!1;if(!Cr)return _U(h),Cr=!0,!1;var v=h.tag,N;if((N=v!==3&&v!==27)&&((N=v===5)&&(N=h.type,N=!(N!=="form"&&N!=="button")||DM(h.type,h.memoizedProps)),N=!N),N&&Ca&&xp(h),_U(h),v===13){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));Ca=KH(h)}else if(v===31){if(h=h.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));Ca=KH(h)}else v===27?(v=Ca,Ep(h.type)?(h=OM,OM=null,Ca=h):Ca=v):Ca=vs?$l(h.stateNode.nextSibling):null;return!0}function wf(){Ca=vs=null,Cr=!1}function gj(){var h=bp;return h!==null&&(Io===null?Io=h:Io.push.apply(Io,h),bp=null),h}function yv(h){bp===null?bp=[h]:bp.push(h)}var bj=Q(null),Sf=null,Lu=null;function yp(h,v,N){pe(bj,v._currentValue),v._currentValue=N}function Ru(h){h._currentValue=bj.current,le(bj)}function xj(h,v,N){for(;h!==null;){var D=h.alternate;if((h.childLanes&v)!==v?(h.childLanes|=v,D!==null&&(D.childLanes|=v)):D!==null&&(D.childLanes&v)!==v&&(D.childLanes|=v),h===N)break;h=h.return}}function yj(h,v,N,D){var V=h.child;for(V!==null&&(V.return=h);V!==null;){var ee=V.dependencies;if(ee!==null){var Se=V.child;ee=ee.firstContext;e:for(;ee!==null;){var $e=ee;ee=V;for(var pt=0;pt<v.length;pt++)if($e.context===v[pt]){ee.lanes|=N,$e=ee.alternate,$e!==null&&($e.lanes|=N),xj(ee.return,N,h),D||(Se=null);break e}ee=$e.next}}else if(V.tag===18){if(Se=V.return,Se===null)throw Error(a(341));Se.lanes|=N,ee=Se.alternate,ee!==null&&(ee.lanes|=N),xj(Se,N,h),Se=null}else Se=V.child;if(Se!==null)Se.return=V;else for(Se=V;Se!==null;){if(Se===h){Se=null;break}if(V=Se.sibling,V!==null){V.return=Se.return,Se=V;break}Se=Se.return}V=Se}}function Cb(h,v,N,D){h=null;for(var V=v,ee=!1;V!==null;){if(!ee){if((V.flags&524288)!==0)ee=!0;else if((V.flags&262144)!==0)break}if(V.tag===10){var Se=V.alternate;if(Se===null)throw Error(a(387));if(Se=Se.memoizedProps,Se!==null){var $e=V.type;Na(V.pendingProps.value,Se.value)||(h!==null?h.push($e):h=[$e])}}else if(V===J.current){if(Se=V.alternate,Se===null)throw Error(a(387));Se.memoizedState.memoizedState!==V.memoizedState.memoizedState&&(h!==null?h.push(Gv):h=[Gv])}V=V.return}h!==null&&yj(v,h,N,D),v.flags|=262144}function P_(h){for(h=h.firstContext;h!==null;){if(!Na(h.context._currentValue,h.memoizedValue))return!0;h=h.next}return!1}function _f(h){Sf=h,Lu=null,h=h.dependencies,h!==null&&(h.firstContext=null)}function ws(h){return kU(Sf,h)}function T_(h,v){return Sf===null&&_f(h),kU(h,v)}function kU(h,v){var N=v._currentValue;if(v={context:v,memoizedValue:N,next:null},Lu===null){if(h===null)throw Error(a(308));Lu=v,h.dependencies={lanes:0,firstContext:v},h.flags|=524288}else Lu=Lu.next=v;return N}var Pde=typeof AbortController<"u"?AbortController:function(){var h=[],v=this.signal={aborted:!1,addEventListener:function(N,D){h.push(D)}};this.abort=function(){v.aborted=!0,h.forEach(function(N){return N()})}},Tde=t.unstable_scheduleCallback,Ade=t.unstable_NormalPriority,fi={$$typeof:k,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function vj(){return{controller:new Pde,data:new Map,refCount:0}}function vv(h){h.refCount--,h.refCount===0&&Tde(Ade,function(){h.controller.abort()})}var wv=null,wj=0,Pb=0,Tb=null;function jde(h,v){if(wv===null){var N=wv=[];wj=0,Pb=kM(),Tb={status:"pending",value:void 0,then:function(D){N.push(D)}}}return wj++,v.then(NU,NU),v}function NU(){if(--wj===0&&wv!==null){Tb!==null&&(Tb.status="fulfilled");var h=wv;wv=null,Pb=0,Tb=null;for(var v=0;v<h.length;v++)(0,h[v])()}}function Mde(h,v){var N=[],D={status:"pending",value:null,reason:null,then:function(V){N.push(V)}};return h.then(function(){D.status="fulfilled",D.value=v;for(var V=0;V<N.length;V++)(0,N[V])(v)},function(V){for(D.status="rejected",D.reason=V,V=0;V<N.length;V++)(0,N[V])(void 0)}),D}var CU=ne.S;ne.S=function(h,v){cH=R(),typeof v=="object"&&v!==null&&typeof v.then=="function"&&jde(h,v),CU!==null&&CU(h,v)};var kf=Q(null);function Sj(){var h=kf.current;return h!==null?h:ma.pooledCache}function A_(h,v){v===null?pe(kf,kf.current):pe(kf,v.pool)}function PU(){var h=Sj();return h===null?null:{parent:fi._currentValue,pool:h}}var Ab=Error(a(460)),_j=Error(a(474)),j_=Error(a(542)),M_={then:function(){}};function TU(h){return h=h.status,h==="fulfilled"||h==="rejected"}function AU(h,v,N){switch(N=h[N],N===void 0?h.push(v):N!==v&&(v.then(Kt,Kt),v=N),v.status){case"fulfilled":return v.value;case"rejected":throw h=v.reason,MU(h),h;default:if(typeof v.status=="string")v.then(Kt,Kt);else{if(h=ma,h!==null&&100<h.shellSuspendCounter)throw Error(a(482));h=v,h.status="pending",h.then(function(D){if(v.status==="pending"){var V=v;V.status="fulfilled",V.value=D}},function(D){if(v.status==="pending"){var V=v;V.status="rejected",V.reason=D}})}switch(v.status){case"fulfilled":return v.value;case"rejected":throw h=v.reason,MU(h),h}throw Cf=v,Ab}}function Nf(h){try{var v=h._init;return v(h._payload)}catch(N){throw N!==null&&typeof N=="object"&&typeof N.then=="function"?(Cf=N,Ab):N}}var Cf=null;function jU(){if(Cf===null)throw Error(a(459));var h=Cf;return Cf=null,h}function MU(h){if(h===Ab||h===j_)throw Error(a(483))}var jb=null,Sv=0;function E_(h){var v=Sv;return Sv+=1,jb===null&&(jb=[]),AU(jb,h,v)}function _v(h,v){v=v.props.ref,h.ref=v!==void 0?v:null}function D_(h,v){throw v.$$typeof===p?Error(a(525)):(h=Object.prototype.toString.call(v),Error(a(31,h==="[object Object]"?"object with keys {"+Object.keys(v).join(", ")+"}":h)))}function EU(h){function v(St,xt){if(h){var jt=St.deletions;jt===null?(St.deletions=[xt],St.flags|=16):jt.push(xt)}}function N(St,xt){if(!h)return null;for(;xt!==null;)v(St,xt),xt=xt.sibling;return null}function D(St){for(var xt=new Map;St!==null;)St.key!==null?xt.set(St.key,St):xt.set(St.index,St),St=St.sibling;return xt}function V(St,xt){return St=Du(St,xt),St.index=0,St.sibling=null,St}function ee(St,xt,jt){return St.index=jt,h?(jt=St.alternate,jt!==null?(jt=jt.index,jt<xt?(St.flags|=67108866,xt):jt):(St.flags|=67108866,xt)):(St.flags|=1048576,xt)}function Se(St){return h&&St.alternate===null&&(St.flags|=67108866),St}function $e(St,xt,jt,$t){return xt===null||xt.tag!==6?(xt=uj(jt,St.mode,$t),xt.return=St,xt):(xt=V(xt,jt),xt.return=St,xt)}function pt(St,xt,jt,$t){var Fn=jt.type;return Fn===w?Ht(St,xt,jt.props.children,$t,jt.key):xt!==null&&(xt.elementType===Fn||typeof Fn=="object"&&Fn!==null&&Fn.$$typeof===F&&Nf(Fn)===xt.type)?(xt=V(xt,jt.props),_v(xt,jt),xt.return=St,xt):(xt=N_(jt.type,jt.key,jt.props,null,St.mode,$t),_v(xt,jt),xt.return=St,xt)}function Mt(St,xt,jt,$t){return xt===null||xt.tag!==4||xt.stateNode.containerInfo!==jt.containerInfo||xt.stateNode.implementation!==jt.implementation?(xt=mj(jt,St.mode,$t),xt.return=St,xt):(xt=V(xt,jt.children||[]),xt.return=St,xt)}function Ht(St,xt,jt,$t,Fn){return xt===null||xt.tag!==7?(xt=vf(jt,St.mode,$t,Fn),xt.return=St,xt):(xt=V(xt,jt),xt.return=St,xt)}function Gt(St,xt,jt){if(typeof xt=="string"&&xt!==""||typeof xt=="number"||typeof xt=="bigint")return xt=uj(""+xt,St.mode,jt),xt.return=St,xt;if(typeof xt=="object"&&xt!==null){switch(xt.$$typeof){case f:return jt=N_(xt.type,xt.key,xt.props,null,St.mode,jt),_v(jt,xt),jt.return=St,jt;case g:return xt=mj(xt,St.mode,jt),xt.return=St,xt;case F:return xt=Nf(xt),Gt(St,xt,jt)}if(Z(xt)||I(xt))return xt=vf(xt,St.mode,jt,null),xt.return=St,xt;if(typeof xt.then=="function")return Gt(St,E_(xt),jt);if(xt.$$typeof===k)return Gt(St,T_(St,xt),jt);D_(St,xt)}return null}function Ft(St,xt,jt,$t){var Fn=xt!==null?xt.key:null;if(typeof jt=="string"&&jt!==""||typeof jt=="number"||typeof jt=="bigint")return Fn!==null?null:$e(St,xt,""+jt,$t);if(typeof jt=="object"&&jt!==null){switch(jt.$$typeof){case f:return jt.key===Fn?pt(St,xt,jt,$t):null;case g:return jt.key===Fn?Mt(St,xt,jt,$t):null;case F:return jt=Nf(jt),Ft(St,xt,jt,$t)}if(Z(jt)||I(jt))return Fn!==null?null:Ht(St,xt,jt,$t,null);if(typeof jt.then=="function")return Ft(St,xt,E_(jt),$t);if(jt.$$typeof===k)return Ft(St,xt,T_(St,jt),$t);D_(St,jt)}return null}function Ot(St,xt,jt,$t,Fn){if(typeof $t=="string"&&$t!==""||typeof $t=="number"||typeof $t=="bigint")return St=St.get(jt)||null,$e(xt,St,""+$t,Fn);if(typeof $t=="object"&&$t!==null){switch($t.$$typeof){case f:return St=St.get($t.key===null?jt:$t.key)||null,pt(xt,St,$t,Fn);case g:return St=St.get($t.key===null?jt:$t.key)||null,Mt(xt,St,$t,Fn);case F:return $t=Nf($t),Ot(St,xt,jt,$t,Fn)}if(Z($t)||I($t))return St=St.get(jt)||null,Ht(xt,St,$t,Fn,null);if(typeof $t.then=="function")return Ot(St,xt,jt,E_($t),Fn);if($t.$$typeof===k)return Ot(St,xt,jt,T_(xt,$t),Fn);D_(xt,$t)}return null}function vn(St,xt,jt,$t){for(var Fn=null,Rr=null,Pn=xt,Jn=xt=0,_r=null;Pn!==null&&Jn<jt.length;Jn++){Pn.index>Jn?(_r=Pn,Pn=null):_r=Pn.sibling;var Ir=Ft(St,Pn,jt[Jn],$t);if(Ir===null){Pn===null&&(Pn=_r);break}h&&Pn&&Ir.alternate===null&&v(St,Pn),xt=ee(Ir,xt,Jn),Rr===null?Fn=Ir:Rr.sibling=Ir,Rr=Ir,Pn=_r}if(Jn===jt.length)return N(St,Pn),Cr&&Fu(St,Jn),Fn;if(Pn===null){for(;Jn<jt.length;Jn++)Pn=Gt(St,jt[Jn],$t),Pn!==null&&(xt=ee(Pn,xt,Jn),Rr===null?Fn=Pn:Rr.sibling=Pn,Rr=Pn);return Cr&&Fu(St,Jn),Fn}for(Pn=D(Pn);Jn<jt.length;Jn++)_r=Ot(Pn,St,Jn,jt[Jn],$t),_r!==null&&(h&&_r.alternate!==null&&Pn.delete(_r.key===null?Jn:_r.key),xt=ee(_r,xt,Jn),Rr===null?Fn=_r:Rr.sibling=_r,Rr=_r);return h&&Pn.forEach(function(Ip){return v(St,Ip)}),Cr&&Fu(St,Jn),Fn}function Bn(St,xt,jt,$t){if(jt==null)throw Error(a(151));for(var Fn=null,Rr=null,Pn=xt,Jn=xt=0,_r=null,Ir=jt.next();Pn!==null&&!Ir.done;Jn++,Ir=jt.next()){Pn.index>Jn?(_r=Pn,Pn=null):_r=Pn.sibling;var Ip=Ft(St,Pn,Ir.value,$t);if(Ip===null){Pn===null&&(Pn=_r);break}h&&Pn&&Ip.alternate===null&&v(St,Pn),xt=ee(Ip,xt,Jn),Rr===null?Fn=Ip:Rr.sibling=Ip,Rr=Ip,Pn=_r}if(Ir.done)return N(St,Pn),Cr&&Fu(St,Jn),Fn;if(Pn===null){for(;!Ir.done;Jn++,Ir=jt.next())Ir=Gt(St,Ir.value,$t),Ir!==null&&(xt=ee(Ir,xt,Jn),Rr===null?Fn=Ir:Rr.sibling=Ir,Rr=Ir);return Cr&&Fu(St,Jn),Fn}for(Pn=D(Pn);!Ir.done;Jn++,Ir=jt.next())Ir=Ot(Pn,St,Jn,Ir.value,$t),Ir!==null&&(h&&Ir.alternate!==null&&Pn.delete(Ir.key===null?Jn:Ir.key),xt=ee(Ir,xt,Jn),Rr===null?Fn=Ir:Rr.sibling=Ir,Rr=Ir);return h&&Pn.forEach(function(Hue){return v(St,Hue)}),Cr&&Fu(St,Jn),Fn}function na(St,xt,jt,$t){if(typeof jt=="object"&&jt!==null&&jt.type===w&&jt.key===null&&(jt=jt.props.children),typeof jt=="object"&&jt!==null){switch(jt.$$typeof){case f:e:{for(var Fn=jt.key;xt!==null;){if(xt.key===Fn){if(Fn=jt.type,Fn===w){if(xt.tag===7){N(St,xt.sibling),$t=V(xt,jt.props.children),$t.return=St,St=$t;break e}}else if(xt.elementType===Fn||typeof Fn=="object"&&Fn!==null&&Fn.$$typeof===F&&Nf(Fn)===xt.type){N(St,xt.sibling),$t=V(xt,jt.props),_v($t,jt),$t.return=St,St=$t;break e}N(St,xt);break}else v(St,xt);xt=xt.sibling}jt.type===w?($t=vf(jt.props.children,St.mode,$t,jt.key),$t.return=St,St=$t):($t=N_(jt.type,jt.key,jt.props,null,St.mode,$t),_v($t,jt),$t.return=St,St=$t)}return Se(St);case g:e:{for(Fn=jt.key;xt!==null;){if(xt.key===Fn)if(xt.tag===4&&xt.stateNode.containerInfo===jt.containerInfo&&xt.stateNode.implementation===jt.implementation){N(St,xt.sibling),$t=V(xt,jt.children||[]),$t.return=St,St=$t;break e}else{N(St,xt);break}else v(St,xt);xt=xt.sibling}$t=mj(jt,St.mode,$t),$t.return=St,St=$t}return Se(St);case F:return jt=Nf(jt),na(St,xt,jt,$t)}if(Z(jt))return vn(St,xt,jt,$t);if(I(jt)){if(Fn=I(jt),typeof Fn!="function")throw Error(a(150));return jt=Fn.call(jt),Bn(St,xt,jt,$t)}if(typeof jt.then=="function")return na(St,xt,E_(jt),$t);if(jt.$$typeof===k)return na(St,xt,T_(St,jt),$t);D_(St,jt)}return typeof jt=="string"&&jt!==""||typeof jt=="number"||typeof jt=="bigint"?(jt=""+jt,xt!==null&&xt.tag===6?(N(St,xt.sibling),$t=V(xt,jt),$t.return=St,St=$t):(N(St,xt),$t=uj(jt,St.mode,$t),$t.return=St,St=$t),Se(St)):N(St,xt)}return function(St,xt,jt,$t){try{Sv=0;var Fn=na(St,xt,jt,$t);return jb=null,Fn}catch(Pn){if(Pn===Ab||Pn===j_)throw Pn;var Rr=al(29,Pn,null,St.mode);return Rr.lanes=$t,Rr.return=St,Rr}}}var Pf=EU(!0),DU=EU(!1),vp=!1;function kj(h){h.updateQueue={baseState:h.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Nj(h,v){h=h.updateQueue,v.updateQueue===h&&(v.updateQueue={baseState:h.baseState,firstBaseUpdate:h.firstBaseUpdate,lastBaseUpdate:h.lastBaseUpdate,shared:h.shared,callbacks:null})}function wp(h){return{lane:h,tag:0,payload:null,callback:null,next:null}}function Sp(h,v,N){var D=h.updateQueue;if(D===null)return null;if(D=D.shared,(Hr&2)!==0){var V=D.pending;return V===null?v.next=v:(v.next=V.next,V.next=v),D.pending=v,v=k_(h),gU(h,null,N),v}return __(h,D,v,N),k_(h)}function kv(h,v,N){if(v=v.updateQueue,v!==null&&(v=v.shared,(N&4194048)!==0)){var D=v.lanes;D&=h.pendingLanes,N|=D,v.lanes=N,Ut(h,N)}}function Cj(h,v){var N=h.updateQueue,D=h.alternate;if(D!==null&&(D=D.updateQueue,N===D)){var V=null,ee=null;if(N=N.firstBaseUpdate,N!==null){do{var Se={lane:N.lane,tag:N.tag,payload:N.payload,callback:null,next:null};ee===null?V=ee=Se:ee=ee.next=Se,N=N.next}while(N!==null);ee===null?V=ee=v:ee=ee.next=v}else V=ee=v;N={baseState:D.baseState,firstBaseUpdate:V,lastBaseUpdate:ee,shared:D.shared,callbacks:D.callbacks},h.updateQueue=N;return}h=N.lastBaseUpdate,h===null?N.firstBaseUpdate=v:h.next=v,N.lastBaseUpdate=v}var Pj=!1;function Nv(){if(Pj){var h=Tb;if(h!==null)throw h}}function Cv(h,v,N,D){Pj=!1;var V=h.updateQueue;vp=!1;var ee=V.firstBaseUpdate,Se=V.lastBaseUpdate,$e=V.shared.pending;if($e!==null){V.shared.pending=null;var pt=$e,Mt=pt.next;pt.next=null,Se===null?ee=Mt:Se.next=Mt,Se=pt;var Ht=h.alternate;Ht!==null&&(Ht=Ht.updateQueue,$e=Ht.lastBaseUpdate,$e!==Se&&($e===null?Ht.firstBaseUpdate=Mt:$e.next=Mt,Ht.lastBaseUpdate=pt))}if(ee!==null){var Gt=V.baseState;Se=0,Ht=Mt=pt=null,$e=ee;do{var Ft=$e.lane&-536870913,Ot=Ft!==$e.lane;if(Ot?(Sr&Ft)===Ft:(D&Ft)===Ft){Ft!==0&&Ft===Pb&&(Pj=!0),Ht!==null&&(Ht=Ht.next={lane:0,tag:$e.tag,payload:$e.payload,callback:null,next:null});e:{var vn=h,Bn=$e;Ft=v;var na=N;switch(Bn.tag){case 1:if(vn=Bn.payload,typeof vn=="function"){Gt=vn.call(na,Gt,Ft);break e}Gt=vn;break e;case 3:vn.flags=vn.flags&-65537|128;case 0:if(vn=Bn.payload,Ft=typeof vn=="function"?vn.call(na,Gt,Ft):vn,Ft==null)break e;Gt=m({},Gt,Ft);break e;case 2:vp=!0}}Ft=$e.callback,Ft!==null&&(h.flags|=64,Ot&&(h.flags|=8192),Ot=V.callbacks,Ot===null?V.callbacks=[Ft]:Ot.push(Ft))}else Ot={lane:Ft,tag:$e.tag,payload:$e.payload,callback:$e.callback,next:null},Ht===null?(Mt=Ht=Ot,pt=Gt):Ht=Ht.next=Ot,Se|=Ft;if($e=$e.next,$e===null){if($e=V.shared.pending,$e===null)break;Ot=$e,$e=Ot.next,Ot.next=null,V.lastBaseUpdate=Ot,V.shared.pending=null}}while(!0);Ht===null&&(pt=Gt),V.baseState=pt,V.firstBaseUpdate=Mt,V.lastBaseUpdate=Ht,ee===null&&(V.shared.lanes=0),Pp|=Se,h.lanes=Se,h.memoizedState=Gt}}function FU(h,v){if(typeof h!="function")throw Error(a(191,h));h.call(v)}function LU(h,v){var N=h.callbacks;if(N!==null)for(h.callbacks=null,h=0;h<N.length;h++)FU(N[h],v)}var Mb=Q(null),F_=Q(0);function RU(h,v){h=Vu,pe(F_,h),pe(Mb,v),Vu=h|v.baseLanes}function Tj(){pe(F_,Vu),pe(Mb,Mb.current)}function Aj(){Vu=F_.current,le(Mb),le(F_)}var il=Q(null),ql=null;function _p(h){var v=h.alternate;pe(li,li.current&1),pe(il,h),ql===null&&(v===null||Mb.current!==null||v.memoizedState!==null)&&(ql=h)}function jj(h){pe(li,li.current),pe(il,h),ql===null&&(ql=h)}function IU(h){h.tag===22?(pe(li,li.current),pe(il,h),ql===null&&(ql=h)):kp()}function kp(){pe(li,li.current),pe(il,il.current)}function sl(h){le(il),ql===h&&(ql=null),le(li)}var li=Q(0);function L_(h){for(var v=h;v!==null;){if(v.tag===13){var N=v.memoizedState;if(N!==null&&(N=N.dehydrated,N===null||RM(N)||IM(N)))return v}else if(v.tag===19&&(v.memoizedProps.revealOrder==="forwards"||v.memoizedProps.revealOrder==="backwards"||v.memoizedProps.revealOrder==="unstable_legacy-backwards"||v.memoizedProps.revealOrder==="together")){if((v.flags&128)!==0)return v}else if(v.child!==null){v.child.return=v,v=v.child;continue}if(v===h)break;for(;v.sibling===null;){if(v.return===null||v.return===h)return null;v=v.return}v.sibling.return=v.return,v=v.sibling}return null}var Iu=0,Xn=null,ea=null,gi=null,R_=!1,Eb=!1,Tf=!1,I_=0,Pv=0,Db=null,Ede=0;function Xa(){throw Error(a(321))}function Mj(h,v){if(v===null)return!1;for(var N=0;N<v.length&&N<h.length;N++)if(!Na(h[N],v[N]))return!1;return!0}function Ej(h,v,N,D,V,ee){return Iu=ee,Xn=v,v.memoizedState=null,v.updateQueue=null,v.lanes=0,ne.H=h===null||h.memoizedState===null?vB:Wj,Tf=!1,ee=N(D,V),Tf=!1,Eb&&(ee=zU(v,N,D,V)),OU(h),ee}function OU(h){ne.H=jv;var v=ea!==null&&ea.next!==null;if(Iu=0,gi=ea=Xn=null,R_=!1,Pv=0,Db=null,v)throw Error(a(300));h===null||bi||(h=h.dependencies,h!==null&&P_(h)&&(bi=!0))}function zU(h,v,N,D){Xn=h;var V=0;do{if(Eb&&(Db=null),Pv=0,Eb=!1,25<=V)throw Error(a(301));if(V+=1,gi=ea=null,h.updateQueue!=null){var ee=h.updateQueue;ee.lastEffect=null,ee.events=null,ee.stores=null,ee.memoCache!=null&&(ee.memoCache.index=0)}ne.H=wB,ee=v(N,D)}while(Eb);return ee}function Dde(){var h=ne.H,v=h.useState()[0];return v=typeof v.then=="function"?Tv(v):v,h=h.useState()[0],(ea!==null?ea.memoizedState:null)!==h&&(Xn.flags|=1024),v}function Dj(){var h=I_!==0;return I_=0,h}function Fj(h,v,N){v.updateQueue=h.updateQueue,v.flags&=-2053,h.lanes&=~N}function Lj(h){if(R_){for(h=h.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}R_=!1}Iu=0,gi=ea=Xn=null,Eb=!1,Pv=I_=0,Db=null}function mo(){var h={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return gi===null?Xn.memoizedState=gi=h:gi=gi.next=h,gi}function ci(){if(ea===null){var h=Xn.alternate;h=h!==null?h.memoizedState:null}else h=ea.next;var v=gi===null?Xn.memoizedState:gi.next;if(v!==null)gi=v,ea=h;else{if(h===null)throw Xn.alternate===null?Error(a(467)):Error(a(310));ea=h,h={memoizedState:ea.memoizedState,baseState:ea.baseState,baseQueue:ea.baseQueue,queue:ea.queue,next:null},gi===null?Xn.memoizedState=gi=h:gi=gi.next=h}return gi}function O_(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Tv(h){var v=Pv;return Pv+=1,Db===null&&(Db=[]),h=AU(Db,h,v),v=Xn,(gi===null?v.memoizedState:gi.next)===null&&(v=v.alternate,ne.H=v===null||v.memoizedState===null?vB:Wj),h}function z_(h){if(h!==null&&typeof h=="object"){if(typeof h.then=="function")return Tv(h);if(h.$$typeof===k)return ws(h)}throw Error(a(438,String(h)))}function Rj(h){var v=null,N=Xn.updateQueue;if(N!==null&&(v=N.memoCache),v==null){var D=Xn.alternate;D!==null&&(D=D.updateQueue,D!==null&&(D=D.memoCache,D!=null&&(v={data:D.data.map(function(V){return V.slice()}),index:0})))}if(v==null&&(v={data:[],index:0}),N===null&&(N=O_(),Xn.updateQueue=N),N.memoCache=v,N=v.data[v.index],N===void 0)for(N=v.data[v.index]=Array(h),D=0;D<h;D++)N[D]=M;return v.index++,N}function Ou(h,v){return typeof v=="function"?v(h):v}function U_(h){var v=ci();return Ij(v,ea,h)}function Ij(h,v,N){var D=h.queue;if(D===null)throw Error(a(311));D.lastRenderedReducer=N;var V=h.baseQueue,ee=D.pending;if(ee!==null){if(V!==null){var Se=V.next;V.next=ee.next,ee.next=Se}v.baseQueue=V=ee,D.pending=null}if(ee=h.baseState,V===null)h.memoizedState=ee;else{v=V.next;var $e=Se=null,pt=null,Mt=v,Ht=!1;do{var Gt=Mt.lane&-536870913;if(Gt!==Mt.lane?(Sr&Gt)===Gt:(Iu&Gt)===Gt){var Ft=Mt.revertLane;if(Ft===0)pt!==null&&(pt=pt.next={lane:0,revertLane:0,gesture:null,action:Mt.action,hasEagerState:Mt.hasEagerState,eagerState:Mt.eagerState,next:null}),Gt===Pb&&(Ht=!0);else if((Iu&Ft)===Ft){Mt=Mt.next,Ft===Pb&&(Ht=!0);continue}else Gt={lane:0,revertLane:Mt.revertLane,gesture:null,action:Mt.action,hasEagerState:Mt.hasEagerState,eagerState:Mt.eagerState,next:null},pt===null?($e=pt=Gt,Se=ee):pt=pt.next=Gt,Xn.lanes|=Ft,Pp|=Ft;Gt=Mt.action,Tf&&N(ee,Gt),ee=Mt.hasEagerState?Mt.eagerState:N(ee,Gt)}else Ft={lane:Gt,revertLane:Mt.revertLane,gesture:Mt.gesture,action:Mt.action,hasEagerState:Mt.hasEagerState,eagerState:Mt.eagerState,next:null},pt===null?($e=pt=Ft,Se=ee):pt=pt.next=Ft,Xn.lanes|=Gt,Pp|=Gt;Mt=Mt.next}while(Mt!==null&&Mt!==v);if(pt===null?Se=ee:pt.next=$e,!Na(ee,h.memoizedState)&&(bi=!0,Ht&&(N=Tb,N!==null)))throw N;h.memoizedState=ee,h.baseState=Se,h.baseQueue=pt,D.lastRenderedState=ee}return V===null&&(D.lanes=0),[h.memoizedState,D.dispatch]}function Oj(h){var v=ci(),N=v.queue;if(N===null)throw Error(a(311));N.lastRenderedReducer=h;var D=N.dispatch,V=N.pending,ee=v.memoizedState;if(V!==null){N.pending=null;var Se=V=V.next;do ee=h(ee,Se.action),Se=Se.next;while(Se!==V);Na(ee,v.memoizedState)||(bi=!0),v.memoizedState=ee,v.baseQueue===null&&(v.baseState=ee),N.lastRenderedState=ee}return[ee,D]}function UU(h,v,N){var D=Xn,V=ci(),ee=Cr;if(ee){if(N===void 0)throw Error(a(407));N=N()}else N=v();var Se=!Na((ea||V).memoizedState,N);if(Se&&(V.memoizedState=N,bi=!0),V=V.queue,Bj(qU.bind(null,D,V,h),[h]),V.getSnapshot!==v||Se||gi!==null&&gi.memoizedState.tag&1){if(D.flags|=2048,Fb(9,{destroy:void 0},HU.bind(null,D,V,N,v),null),ma===null)throw Error(a(349));ee||(Iu&127)!==0||BU(D,v,N)}return N}function BU(h,v,N){h.flags|=16384,h={getSnapshot:v,value:N},v=Xn.updateQueue,v===null?(v=O_(),Xn.updateQueue=v,v.stores=[h]):(N=v.stores,N===null?v.stores=[h]:N.push(h))}function HU(h,v,N,D){v.value=N,v.getSnapshot=D,$U(v)&&VU(h)}function qU(h,v,N){return N(function(){$U(v)&&VU(h)})}function $U(h){var v=h.getSnapshot;h=h.value;try{var N=v();return!Na(h,N)}catch{return!0}}function VU(h){var v=yf(h,2);v!==null&&Oo(v,h,2)}function zj(h){var v=mo();if(typeof h=="function"){var N=h;if(h=N(),Tf){Re(!0);try{N()}finally{Re(!1)}}}return v.memoizedState=v.baseState=h,v.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ou,lastRenderedState:h},v}function GU(h,v,N,D){return h.baseState=N,Ij(h,ea,typeof D=="function"?D:Ou)}function Fde(h,v,N,D,V){if(q_(h))throw Error(a(485));if(h=v.action,h!==null){var ee={payload:V,action:h,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(Se){ee.listeners.push(Se)}};ne.T!==null?N(!0):ee.isTransition=!1,D(ee),N=v.pending,N===null?(ee.next=v.pending=ee,WU(v,ee)):(ee.next=N.next,v.pending=N.next=ee)}}function WU(h,v){var N=v.action,D=v.payload,V=h.state;if(v.isTransition){var ee=ne.T,Se={};ne.T=Se;try{var $e=N(V,D),pt=ne.S;pt!==null&&pt(Se,$e),KU(h,v,$e)}catch(Mt){Uj(h,v,Mt)}finally{ee!==null&&Se.types!==null&&(ee.types=Se.types),ne.T=ee}}else try{ee=N(V,D),KU(h,v,ee)}catch(Mt){Uj(h,v,Mt)}}function KU(h,v,N){N!==null&&typeof N=="object"&&typeof N.then=="function"?N.then(function(D){QU(h,v,D)},function(D){return Uj(h,v,D)}):QU(h,v,N)}function QU(h,v,N){v.status="fulfilled",v.value=N,YU(v),h.state=N,v=h.pending,v!==null&&(N=v.next,N===v?h.pending=null:(N=N.next,v.next=N,WU(h,N)))}function Uj(h,v,N){var D=h.pending;if(h.pending=null,D!==null){D=D.next;do v.status="rejected",v.reason=N,YU(v),v=v.next;while(v!==D)}h.action=null}function YU(h){h=h.listeners;for(var v=0;v<h.length;v++)(0,h[v])()}function XU(h,v){return v}function ZU(h,v){if(Cr){var N=ma.formState;if(N!==null){e:{var D=Xn;if(Cr){if(Ca){t:{for(var V=Ca,ee=Hl;V.nodeType!==8;){if(!ee){V=null;break t}if(V=$l(V.nextSibling),V===null){V=null;break t}}ee=V.data,V=ee==="F!"||ee==="F"?V:null}if(V){Ca=$l(V.nextSibling),D=V.data==="F!";break e}}xp(D)}D=!1}D&&(v=N[0])}}return N=mo(),N.memoizedState=N.baseState=v,D={pending:null,lanes:0,dispatch:null,lastRenderedReducer:XU,lastRenderedState:v},N.queue=D,N=bB.bind(null,Xn,D),D.dispatch=N,D=zj(!1),ee=Gj.bind(null,Xn,!1,D.queue),D=mo(),V={state:v,dispatch:null,action:h,pending:null},D.queue=V,N=Fde.bind(null,Xn,V,ee,N),V.dispatch=N,D.memoizedState=h,[v,N,!1]}function JU(h){var v=ci();return eB(v,ea,h)}function eB(h,v,N){if(v=Ij(h,v,XU)[0],h=U_(Ou)[0],typeof v=="object"&&v!==null&&typeof v.then=="function")try{var D=Tv(v)}catch(Se){throw Se===Ab?j_:Se}else D=v;v=ci();var V=v.queue,ee=V.dispatch;return N!==v.memoizedState&&(Xn.flags|=2048,Fb(9,{destroy:void 0},Lde.bind(null,V,N),null)),[D,ee,h]}function Lde(h,v){h.action=v}function tB(h){var v=ci(),N=ea;if(N!==null)return eB(v,N,h);ci(),v=v.memoizedState,N=ci();var D=N.queue.dispatch;return N.memoizedState=h,[v,D,!1]}function Fb(h,v,N,D){return h={tag:h,create:N,deps:D,inst:v,next:null},v=Xn.updateQueue,v===null&&(v=O_(),Xn.updateQueue=v),N=v.lastEffect,N===null?v.lastEffect=h.next=h:(D=N.next,N.next=h,h.next=D,v.lastEffect=h),h}function nB(){return ci().memoizedState}function B_(h,v,N,D){var V=mo();Xn.flags|=h,V.memoizedState=Fb(1|v,{destroy:void 0},N,D===void 0?null:D)}function H_(h,v,N,D){var V=ci();D=D===void 0?null:D;var ee=V.memoizedState.inst;ea!==null&&D!==null&&Mj(D,ea.memoizedState.deps)?V.memoizedState=Fb(v,ee,N,D):(Xn.flags|=h,V.memoizedState=Fb(1|v,ee,N,D))}function rB(h,v){B_(8390656,8,h,v)}function Bj(h,v){H_(2048,8,h,v)}function Rde(h){Xn.flags|=4;var v=Xn.updateQueue;if(v===null)v=O_(),Xn.updateQueue=v,v.events=[h];else{var N=v.events;N===null?v.events=[h]:N.push(h)}}function aB(h){var v=ci().memoizedState;return Rde({ref:v,nextImpl:h}),function(){if((Hr&2)!==0)throw Error(a(440));return v.impl.apply(void 0,arguments)}}function iB(h,v){return H_(4,2,h,v)}function sB(h,v){return H_(4,4,h,v)}function oB(h,v){if(typeof v=="function"){h=h();var N=v(h);return function(){typeof N=="function"?N():v(null)}}if(v!=null)return h=h(),v.current=h,function(){v.current=null}}function lB(h,v,N){N=N!=null?N.concat([h]):null,H_(4,4,oB.bind(null,v,h),N)}function Hj(){}function cB(h,v){var N=ci();v=v===void 0?null:v;var D=N.memoizedState;return v!==null&&Mj(v,D[1])?D[0]:(N.memoizedState=[h,v],h)}function dB(h,v){var N=ci();v=v===void 0?null:v;var D=N.memoizedState;if(v!==null&&Mj(v,D[1]))return D[0];if(D=h(),Tf){Re(!0);try{h()}finally{Re(!1)}}return N.memoizedState=[D,v],D}function qj(h,v,N){return N===void 0||(Iu&1073741824)!==0&&(Sr&261930)===0?h.memoizedState=v:(h.memoizedState=N,h=uH(),Xn.lanes|=h,Pp|=h,N)}function uB(h,v,N,D){return Na(N,v)?N:Mb.current!==null?(h=qj(h,N,D),Na(h,v)||(bi=!0),h):(Iu&42)===0||(Iu&1073741824)!==0&&(Sr&261930)===0?(bi=!0,h.memoizedState=N):(h=uH(),Xn.lanes|=h,Pp|=h,v)}function mB(h,v,N,D,V){var ee=Y.p;Y.p=ee!==0&&8>ee?ee:8;var Se=ne.T,$e={};ne.T=$e,Gj(h,!1,v,N);try{var pt=V(),Mt=ne.S;if(Mt!==null&&Mt($e,pt),pt!==null&&typeof pt=="object"&&typeof pt.then=="function"){var Ht=Mde(pt,D);Av(h,v,Ht,cl(h))}else Av(h,v,D,cl(h))}catch(Gt){Av(h,v,{then:function(){},status:"rejected",reason:Gt},cl())}finally{Y.p=ee,Se!==null&&$e.types!==null&&(Se.types=$e.types),ne.T=Se}}function Ide(){}function $j(h,v,N,D){if(h.tag!==5)throw Error(a(476));var V=pB(h).queue;mB(h,V,v,ce,N===null?Ide:function(){return hB(h),N(D)})}function pB(h){var v=h.memoizedState;if(v!==null)return v;v={memoizedState:ce,baseState:ce,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ou,lastRenderedState:ce},next:null};var N={};return v.next={memoizedState:N,baseState:N,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ou,lastRenderedState:N},next:null},h.memoizedState=v,h=h.alternate,h!==null&&(h.memoizedState=v),v}function hB(h){var v=pB(h);v.next===null&&(v=h.alternate.memoizedState),Av(h,v.next.queue,{},cl())}function Vj(){return ws(Gv)}function fB(){return ci().memoizedState}function gB(){return ci().memoizedState}function Ode(h){for(var v=h.return;v!==null;){switch(v.tag){case 24:case 3:var N=cl();h=wp(N);var D=Sp(v,h,N);D!==null&&(Oo(D,v,N),kv(D,v,N)),v={cache:vj()},h.payload=v;return}v=v.return}}function zde(h,v,N){var D=cl();N={lane:D,revertLane:0,gesture:null,action:N,hasEagerState:!1,eagerState:null,next:null},q_(h)?xB(v,N):(N=cj(h,v,N,D),N!==null&&(Oo(N,h,D),yB(N,v,D)))}function bB(h,v,N){var D=cl();Av(h,v,N,D)}function Av(h,v,N,D){var V={lane:D,revertLane:0,gesture:null,action:N,hasEagerState:!1,eagerState:null,next:null};if(q_(h))xB(v,V);else{var ee=h.alternate;if(h.lanes===0&&(ee===null||ee.lanes===0)&&(ee=v.lastRenderedReducer,ee!==null))try{var Se=v.lastRenderedState,$e=ee(Se,N);if(V.hasEagerState=!0,V.eagerState=$e,Na($e,Se))return __(h,v,V,0),ma===null&&S_(),!1}catch{}if(N=cj(h,v,V,D),N!==null)return Oo(N,h,D),yB(N,v,D),!0}return!1}function Gj(h,v,N,D){if(D={lane:2,revertLane:kM(),gesture:null,action:D,hasEagerState:!1,eagerState:null,next:null},q_(h)){if(v)throw Error(a(479))}else v=cj(h,N,D,2),v!==null&&Oo(v,h,2)}function q_(h){var v=h.alternate;return h===Xn||v!==null&&v===Xn}function xB(h,v){Eb=R_=!0;var N=h.pending;N===null?v.next=v:(v.next=N.next,N.next=v),h.pending=v}function yB(h,v,N){if((N&4194048)!==0){var D=v.lanes;D&=h.pendingLanes,N|=D,v.lanes=N,Ut(h,N)}}var jv={readContext:ws,use:z_,useCallback:Xa,useContext:Xa,useEffect:Xa,useImperativeHandle:Xa,useLayoutEffect:Xa,useInsertionEffect:Xa,useMemo:Xa,useReducer:Xa,useRef:Xa,useState:Xa,useDebugValue:Xa,useDeferredValue:Xa,useTransition:Xa,useSyncExternalStore:Xa,useId:Xa,useHostTransitionStatus:Xa,useFormState:Xa,useActionState:Xa,useOptimistic:Xa,useMemoCache:Xa,useCacheRefresh:Xa};jv.useEffectEvent=Xa;var vB={readContext:ws,use:z_,useCallback:function(h,v){return mo().memoizedState=[h,v===void 0?null:v],h},useContext:ws,useEffect:rB,useImperativeHandle:function(h,v,N){N=N!=null?N.concat([h]):null,B_(4194308,4,oB.bind(null,v,h),N)},useLayoutEffect:function(h,v){return B_(4194308,4,h,v)},useInsertionEffect:function(h,v){B_(4,2,h,v)},useMemo:function(h,v){var N=mo();v=v===void 0?null:v;var D=h();if(Tf){Re(!0);try{h()}finally{Re(!1)}}return N.memoizedState=[D,v],D},useReducer:function(h,v,N){var D=mo();if(N!==void 0){var V=N(v);if(Tf){Re(!0);try{N(v)}finally{Re(!1)}}}else V=v;return D.memoizedState=D.baseState=V,h={pending:null,lanes:0,dispatch:null,lastRenderedReducer:h,lastRenderedState:V},D.queue=h,h=h.dispatch=zde.bind(null,Xn,h),[D.memoizedState,h]},useRef:function(h){var v=mo();return h={current:h},v.memoizedState=h},useState:function(h){h=zj(h);var v=h.queue,N=bB.bind(null,Xn,v);return v.dispatch=N,[h.memoizedState,N]},useDebugValue:Hj,useDeferredValue:function(h,v){var N=mo();return qj(N,h,v)},useTransition:function(){var h=zj(!1);return h=mB.bind(null,Xn,h.queue,!0,!1),mo().memoizedState=h,[!1,h]},useSyncExternalStore:function(h,v,N){var D=Xn,V=mo();if(Cr){if(N===void 0)throw Error(a(407));N=N()}else{if(N=v(),ma===null)throw Error(a(349));(Sr&127)!==0||BU(D,v,N)}V.memoizedState=N;var ee={value:N,getSnapshot:v};return V.queue=ee,rB(qU.bind(null,D,ee,h),[h]),D.flags|=2048,Fb(9,{destroy:void 0},HU.bind(null,D,ee,N,v),null),N},useId:function(){var h=mo(),v=ma.identifierPrefix;if(Cr){var N=Md,D=jd;N=(D&~(1<<32-We(D)-1)).toString(32)+N,v="_"+v+"R_"+N,N=I_++,0<N&&(v+="H"+N.toString(32)),v+="_"}else N=Ede++,v="_"+v+"r_"+N.toString(32)+"_";return h.memoizedState=v},useHostTransitionStatus:Vj,useFormState:ZU,useActionState:ZU,useOptimistic:function(h){var v=mo();v.memoizedState=v.baseState=h;var N={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return v.queue=N,v=Gj.bind(null,Xn,!0,N),N.dispatch=v,[h,v]},useMemoCache:Rj,useCacheRefresh:function(){return mo().memoizedState=Ode.bind(null,Xn)},useEffectEvent:function(h){var v=mo(),N={impl:h};return v.memoizedState=N,function(){if((Hr&2)!==0)throw Error(a(440));return N.impl.apply(void 0,arguments)}}},Wj={readContext:ws,use:z_,useCallback:cB,useContext:ws,useEffect:Bj,useImperativeHandle:lB,useInsertionEffect:iB,useLayoutEffect:sB,useMemo:dB,useReducer:U_,useRef:nB,useState:function(){return U_(Ou)},useDebugValue:Hj,useDeferredValue:function(h,v){var N=ci();return uB(N,ea.memoizedState,h,v)},useTransition:function(){var h=U_(Ou)[0],v=ci().memoizedState;return[typeof h=="boolean"?h:Tv(h),v]},useSyncExternalStore:UU,useId:fB,useHostTransitionStatus:Vj,useFormState:JU,useActionState:JU,useOptimistic:function(h,v){var N=ci();return GU(N,ea,h,v)},useMemoCache:Rj,useCacheRefresh:gB};Wj.useEffectEvent=aB;var wB={readContext:ws,use:z_,useCallback:cB,useContext:ws,useEffect:Bj,useImperativeHandle:lB,useInsertionEffect:iB,useLayoutEffect:sB,useMemo:dB,useReducer:Oj,useRef:nB,useState:function(){return Oj(Ou)},useDebugValue:Hj,useDeferredValue:function(h,v){var N=ci();return ea===null?qj(N,h,v):uB(N,ea.memoizedState,h,v)},useTransition:function(){var h=Oj(Ou)[0],v=ci().memoizedState;return[typeof h=="boolean"?h:Tv(h),v]},useSyncExternalStore:UU,useId:fB,useHostTransitionStatus:Vj,useFormState:tB,useActionState:tB,useOptimistic:function(h,v){var N=ci();return ea!==null?GU(N,ea,h,v):(N.baseState=h,[h,N.queue.dispatch])},useMemoCache:Rj,useCacheRefresh:gB};wB.useEffectEvent=aB;function Kj(h,v,N,D){v=h.memoizedState,N=N(D,v),N=N==null?v:m({},v,N),h.memoizedState=N,h.lanes===0&&(h.updateQueue.baseState=N)}var Qj={enqueueSetState:function(h,v,N){h=h._reactInternals;var D=cl(),V=wp(D);V.payload=v,N!=null&&(V.callback=N),v=Sp(h,V,D),v!==null&&(Oo(v,h,D),kv(v,h,D))},enqueueReplaceState:function(h,v,N){h=h._reactInternals;var D=cl(),V=wp(D);V.tag=1,V.payload=v,N!=null&&(V.callback=N),v=Sp(h,V,D),v!==null&&(Oo(v,h,D),kv(v,h,D))},enqueueForceUpdate:function(h,v){h=h._reactInternals;var N=cl(),D=wp(N);D.tag=2,v!=null&&(D.callback=v),v=Sp(h,D,N),v!==null&&(Oo(v,h,N),kv(v,h,N))}};function SB(h,v,N,D,V,ee,Se){return h=h.stateNode,typeof h.shouldComponentUpdate=="function"?h.shouldComponentUpdate(D,ee,Se):v.prototype&&v.prototype.isPureReactComponent?!Br(N,D)||!Br(V,ee):!0}function _B(h,v,N,D){h=v.state,typeof v.componentWillReceiveProps=="function"&&v.componentWillReceiveProps(N,D),typeof v.UNSAFE_componentWillReceiveProps=="function"&&v.UNSAFE_componentWillReceiveProps(N,D),v.state!==h&&Qj.enqueueReplaceState(v,v.state,null)}function Af(h,v){var N=v;if("ref"in v){N={};for(var D in v)D!=="ref"&&(N[D]=v[D])}if(h=h.defaultProps){N===v&&(N=m({},N));for(var V in h)N[V]===void 0&&(N[V]=h[V])}return N}function kB(h){w_(h)}function NB(h){console.error(h)}function CB(h){w_(h)}function $_(h,v){try{var N=h.onUncaughtError;N(v.value,{componentStack:v.stack})}catch(D){setTimeout(function(){throw D})}}function PB(h,v,N){try{var D=h.onCaughtError;D(N.value,{componentStack:N.stack,errorBoundary:v.tag===1?v.stateNode:null})}catch(V){setTimeout(function(){throw V})}}function Yj(h,v,N){return N=wp(N),N.tag=3,N.payload={element:null},N.callback=function(){$_(h,v)},N}function TB(h){return h=wp(h),h.tag=3,h}function AB(h,v,N,D){var V=N.type.getDerivedStateFromError;if(typeof V=="function"){var ee=D.value;h.payload=function(){return V(ee)},h.callback=function(){PB(v,N,D)}}var Se=N.stateNode;Se!==null&&typeof Se.componentDidCatch=="function"&&(h.callback=function(){PB(v,N,D),typeof V!="function"&&(Tp===null?Tp=new Set([this]):Tp.add(this));var $e=D.stack;this.componentDidCatch(D.value,{componentStack:$e!==null?$e:""})})}function Ude(h,v,N,D,V){if(N.flags|=32768,D!==null&&typeof D=="object"&&typeof D.then=="function"){if(v=N.alternate,v!==null&&Cb(v,N,V,!0),N=il.current,N!==null){switch(N.tag){case 31:case 13:return ql===null?nk():N.alternate===null&&Za===0&&(Za=3),N.flags&=-257,N.flags|=65536,N.lanes=V,D===M_?N.flags|=16384:(v=N.updateQueue,v===null?N.updateQueue=new Set([D]):v.add(D),wM(h,D,V)),!1;case 22:return N.flags|=65536,D===M_?N.flags|=16384:(v=N.updateQueue,v===null?(v={transitions:null,markerInstances:null,retryQueue:new Set([D])},N.updateQueue=v):(N=v.retryQueue,N===null?v.retryQueue=new Set([D]):N.add(D)),wM(h,D,V)),!1}throw Error(a(435,N.tag))}return wM(h,D,V),nk(),!1}if(Cr)return v=il.current,v!==null?((v.flags&65536)===0&&(v.flags|=256),v.flags|=65536,v.lanes=V,D!==fj&&(h=Error(a(422),{cause:D}),yv(zl(h,N)))):(D!==fj&&(v=Error(a(423),{cause:D}),yv(zl(v,N))),h=h.current.alternate,h.flags|=65536,V&=-V,h.lanes|=V,D=zl(D,N),V=Yj(h.stateNode,D,V),Cj(h,V),Za!==4&&(Za=2)),!1;var ee=Error(a(520),{cause:D});if(ee=zl(ee,N),Ov===null?Ov=[ee]:Ov.push(ee),Za!==4&&(Za=2),v===null)return!0;D=zl(D,N),N=v;do{switch(N.tag){case 3:return N.flags|=65536,h=V&-V,N.lanes|=h,h=Yj(N.stateNode,D,h),Cj(N,h),!1;case 1:if(v=N.type,ee=N.stateNode,(N.flags&128)===0&&(typeof v.getDerivedStateFromError=="function"||ee!==null&&typeof ee.componentDidCatch=="function"&&(Tp===null||!Tp.has(ee))))return N.flags|=65536,V&=-V,N.lanes|=V,V=TB(V),AB(V,h,N,D),Cj(N,V),!1}N=N.return}while(N!==null);return!1}var Xj=Error(a(461)),bi=!1;function Ss(h,v,N,D){v.child=h===null?DU(v,null,N,D):Pf(v,h.child,N,D)}function jB(h,v,N,D,V){N=N.render;var ee=v.ref;if("ref"in D){var Se={};for(var $e in D)$e!=="ref"&&(Se[$e]=D[$e])}else Se=D;return _f(v),D=Ej(h,v,N,Se,ee,V),$e=Dj(),h!==null&&!bi?(Fj(h,v,V),zu(h,v,V)):(Cr&&$e&&pj(v),v.flags|=1,Ss(h,v,D,V),v.child)}function MB(h,v,N,D,V){if(h===null){var ee=N.type;return typeof ee=="function"&&!dj(ee)&&ee.defaultProps===void 0&&N.compare===null?(v.tag=15,v.type=ee,EB(h,v,ee,D,V)):(h=N_(N.type,null,D,v,v.mode,V),h.ref=v.ref,h.return=v,v.child=h)}if(ee=h.child,!iM(h,V)){var Se=ee.memoizedProps;if(N=N.compare,N=N!==null?N:Br,N(Se,D)&&h.ref===v.ref)return zu(h,v,V)}return v.flags|=1,h=Du(ee,D),h.ref=v.ref,h.return=v,v.child=h}function EB(h,v,N,D,V){if(h!==null){var ee=h.memoizedProps;if(Br(ee,D)&&h.ref===v.ref)if(bi=!1,v.pendingProps=D=ee,iM(h,V))(h.flags&131072)!==0&&(bi=!0);else return v.lanes=h.lanes,zu(h,v,V)}return Zj(h,v,N,D,V)}function DB(h,v,N,D){var V=D.children,ee=h!==null?h.memoizedState:null;if(h===null&&v.stateNode===null&&(v.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),D.mode==="hidden"){if((v.flags&128)!==0){if(ee=ee!==null?ee.baseLanes|N:N,h!==null){for(D=v.child=h.child,V=0;D!==null;)V=V|D.lanes|D.childLanes,D=D.sibling;D=V&~ee}else D=0,v.child=null;return FB(h,v,ee,N,D)}if((N&536870912)!==0)v.memoizedState={baseLanes:0,cachePool:null},h!==null&&A_(v,ee!==null?ee.cachePool:null),ee!==null?RU(v,ee):Tj(),IU(v);else return D=v.lanes=536870912,FB(h,v,ee!==null?ee.baseLanes|N:N,N,D)}else ee!==null?(A_(v,ee.cachePool),RU(v,ee),kp(),v.memoizedState=null):(h!==null&&A_(v,null),Tj(),kp());return Ss(h,v,V,N),v.child}function Mv(h,v){return h!==null&&h.tag===22||v.stateNode!==null||(v.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),v.sibling}function FB(h,v,N,D,V){var ee=Sj();return ee=ee===null?null:{parent:fi._currentValue,pool:ee},v.memoizedState={baseLanes:N,cachePool:ee},h!==null&&A_(v,null),Tj(),IU(v),h!==null&&Cb(h,v,D,!0),v.childLanes=V,null}function V_(h,v){return v=W_({mode:v.mode,children:v.children},h.mode),v.ref=h.ref,h.child=v,v.return=h,v}function LB(h,v,N){return Pf(v,h.child,null,N),h=V_(v,v.pendingProps),h.flags|=2,sl(v),v.memoizedState=null,h}function Bde(h,v,N){var D=v.pendingProps,V=(v.flags&128)!==0;if(v.flags&=-129,h===null){if(Cr){if(D.mode==="hidden")return h=V_(v,D),v.lanes=536870912,Mv(null,h);if(jj(v),(h=Ca)?(h=WH(h,Hl),h=h!==null&&h.data==="&"?h:null,h!==null&&(v.memoizedState={dehydrated:h,treeContext:gp!==null?{id:jd,overflow:Md}:null,retryLane:536870912,hydrationErrors:null},N=xU(h),N.return=v,v.child=N,vs=v,Ca=null)):h=null,h===null)throw xp(v);return v.lanes=536870912,null}return V_(v,D)}var ee=h.memoizedState;if(ee!==null){var Se=ee.dehydrated;if(jj(v),V)if(v.flags&256)v.flags&=-257,v=LB(h,v,N);else if(v.memoizedState!==null)v.child=h.child,v.flags|=128,v=null;else throw Error(a(558));else if(bi||Cb(h,v,N,!1),V=(N&h.childLanes)!==0,bi||V){if(D=ma,D!==null&&(Se=bt(D,N),Se!==0&&Se!==ee.retryLane))throw ee.retryLane=Se,yf(h,Se),Oo(D,h,Se),Xj;nk(),v=LB(h,v,N)}else h=ee.treeContext,Ca=$l(Se.nextSibling),vs=v,Cr=!0,bp=null,Hl=!1,h!==null&&wU(v,h),v=V_(v,D),v.flags|=4096;return v}return h=Du(h.child,{mode:D.mode,children:D.children}),h.ref=v.ref,v.child=h,h.return=v,h}function G_(h,v){var N=v.ref;if(N===null)h!==null&&h.ref!==null&&(v.flags|=4194816);else{if(typeof N!="function"&&typeof N!="object")throw Error(a(284));(h===null||h.ref!==N)&&(v.flags|=4194816)}}function Zj(h,v,N,D,V){return _f(v),N=Ej(h,v,N,D,void 0,V),D=Dj(),h!==null&&!bi?(Fj(h,v,V),zu(h,v,V)):(Cr&&D&&pj(v),v.flags|=1,Ss(h,v,N,V),v.child)}function RB(h,v,N,D,V,ee){return _f(v),v.updateQueue=null,N=zU(v,D,N,V),OU(h),D=Dj(),h!==null&&!bi?(Fj(h,v,ee),zu(h,v,ee)):(Cr&&D&&pj(v),v.flags|=1,Ss(h,v,N,ee),v.child)}function IB(h,v,N,D,V){if(_f(v),v.stateNode===null){var ee=Sb,Se=N.contextType;typeof Se=="object"&&Se!==null&&(ee=ws(Se)),ee=new N(D,ee),v.memoizedState=ee.state!==null&&ee.state!==void 0?ee.state:null,ee.updater=Qj,v.stateNode=ee,ee._reactInternals=v,ee=v.stateNode,ee.props=D,ee.state=v.memoizedState,ee.refs={},kj(v),Se=N.contextType,ee.context=typeof Se=="object"&&Se!==null?ws(Se):Sb,ee.state=v.memoizedState,Se=N.getDerivedStateFromProps,typeof Se=="function"&&(Kj(v,N,Se,D),ee.state=v.memoizedState),typeof N.getDerivedStateFromProps=="function"||typeof ee.getSnapshotBeforeUpdate=="function"||typeof ee.UNSAFE_componentWillMount!="function"&&typeof ee.componentWillMount!="function"||(Se=ee.state,typeof ee.componentWillMount=="function"&&ee.componentWillMount(),typeof ee.UNSAFE_componentWillMount=="function"&&ee.UNSAFE_componentWillMount(),Se!==ee.state&&Qj.enqueueReplaceState(ee,ee.state,null),Cv(v,D,ee,V),Nv(),ee.state=v.memoizedState),typeof ee.componentDidMount=="function"&&(v.flags|=4194308),D=!0}else if(h===null){ee=v.stateNode;var $e=v.memoizedProps,pt=Af(N,$e);ee.props=pt;var Mt=ee.context,Ht=N.contextType;Se=Sb,typeof Ht=="object"&&Ht!==null&&(Se=ws(Ht));var Gt=N.getDerivedStateFromProps;Ht=typeof Gt=="function"||typeof ee.getSnapshotBeforeUpdate=="function",$e=v.pendingProps!==$e,Ht||typeof ee.UNSAFE_componentWillReceiveProps!="function"&&typeof ee.componentWillReceiveProps!="function"||($e||Mt!==Se)&&_B(v,ee,D,Se),vp=!1;var Ft=v.memoizedState;ee.state=Ft,Cv(v,D,ee,V),Nv(),Mt=v.memoizedState,$e||Ft!==Mt||vp?(typeof Gt=="function"&&(Kj(v,N,Gt,D),Mt=v.memoizedState),(pt=vp||SB(v,N,pt,D,Ft,Mt,Se))?(Ht||typeof ee.UNSAFE_componentWillMount!="function"&&typeof ee.componentWillMount!="function"||(typeof ee.componentWillMount=="function"&&ee.componentWillMount(),typeof ee.UNSAFE_componentWillMount=="function"&&ee.UNSAFE_componentWillMount()),typeof ee.componentDidMount=="function"&&(v.flags|=4194308)):(typeof ee.componentDidMount=="function"&&(v.flags|=4194308),v.memoizedProps=D,v.memoizedState=Mt),ee.props=D,ee.state=Mt,ee.context=Se,D=pt):(typeof ee.componentDidMount=="function"&&(v.flags|=4194308),D=!1)}else{ee=v.stateNode,Nj(h,v),Se=v.memoizedProps,Ht=Af(N,Se),ee.props=Ht,Gt=v.pendingProps,Ft=ee.context,Mt=N.contextType,pt=Sb,typeof Mt=="object"&&Mt!==null&&(pt=ws(Mt)),$e=N.getDerivedStateFromProps,(Mt=typeof $e=="function"||typeof ee.getSnapshotBeforeUpdate=="function")||typeof ee.UNSAFE_componentWillReceiveProps!="function"&&typeof ee.componentWillReceiveProps!="function"||(Se!==Gt||Ft!==pt)&&_B(v,ee,D,pt),vp=!1,Ft=v.memoizedState,ee.state=Ft,Cv(v,D,ee,V),Nv();var Ot=v.memoizedState;Se!==Gt||Ft!==Ot||vp||h!==null&&h.dependencies!==null&&P_(h.dependencies)?(typeof $e=="function"&&(Kj(v,N,$e,D),Ot=v.memoizedState),(Ht=vp||SB(v,N,Ht,D,Ft,Ot,pt)||h!==null&&h.dependencies!==null&&P_(h.dependencies))?(Mt||typeof ee.UNSAFE_componentWillUpdate!="function"&&typeof ee.componentWillUpdate!="function"||(typeof ee.componentWillUpdate=="function"&&ee.componentWillUpdate(D,Ot,pt),typeof ee.UNSAFE_componentWillUpdate=="function"&&ee.UNSAFE_componentWillUpdate(D,Ot,pt)),typeof ee.componentDidUpdate=="function"&&(v.flags|=4),typeof ee.getSnapshotBeforeUpdate=="function"&&(v.flags|=1024)):(typeof ee.componentDidUpdate!="function"||Se===h.memoizedProps&&Ft===h.memoizedState||(v.flags|=4),typeof ee.getSnapshotBeforeUpdate!="function"||Se===h.memoizedProps&&Ft===h.memoizedState||(v.flags|=1024),v.memoizedProps=D,v.memoizedState=Ot),ee.props=D,ee.state=Ot,ee.context=pt,D=Ht):(typeof ee.componentDidUpdate!="function"||Se===h.memoizedProps&&Ft===h.memoizedState||(v.flags|=4),typeof ee.getSnapshotBeforeUpdate!="function"||Se===h.memoizedProps&&Ft===h.memoizedState||(v.flags|=1024),D=!1)}return ee=D,G_(h,v),D=(v.flags&128)!==0,ee||D?(ee=v.stateNode,N=D&&typeof N.getDerivedStateFromError!="function"?null:ee.render(),v.flags|=1,h!==null&&D?(v.child=Pf(v,h.child,null,V),v.child=Pf(v,null,N,V)):Ss(h,v,N,V),v.memoizedState=ee.state,h=v.child):h=zu(h,v,V),h}function OB(h,v,N,D){return wf(),v.flags|=256,Ss(h,v,N,D),v.child}var Jj={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function eM(h){return{baseLanes:h,cachePool:PU()}}function tM(h,v,N){return h=h!==null?h.childLanes&~N:0,v&&(h|=ll),h}function zB(h,v,N){var D=v.pendingProps,V=!1,ee=(v.flags&128)!==0,Se;if((Se=ee)||(Se=h!==null&&h.memoizedState===null?!1:(li.current&2)!==0),Se&&(V=!0,v.flags&=-129),Se=(v.flags&32)!==0,v.flags&=-33,h===null){if(Cr){if(V?_p(v):kp(),(h=Ca)?(h=WH(h,Hl),h=h!==null&&h.data!=="&"?h:null,h!==null&&(v.memoizedState={dehydrated:h,treeContext:gp!==null?{id:jd,overflow:Md}:null,retryLane:536870912,hydrationErrors:null},N=xU(h),N.return=v,v.child=N,vs=v,Ca=null)):h=null,h===null)throw xp(v);return IM(h)?v.lanes=32:v.lanes=536870912,null}var $e=D.children;return D=D.fallback,V?(kp(),V=v.mode,$e=W_({mode:"hidden",children:$e},V),D=vf(D,V,N,null),$e.return=v,D.return=v,$e.sibling=D,v.child=$e,D=v.child,D.memoizedState=eM(N),D.childLanes=tM(h,Se,N),v.memoizedState=Jj,Mv(null,D)):(_p(v),nM(v,$e))}var pt=h.memoizedState;if(pt!==null&&($e=pt.dehydrated,$e!==null)){if(ee)v.flags&256?(_p(v),v.flags&=-257,v=rM(h,v,N)):v.memoizedState!==null?(kp(),v.child=h.child,v.flags|=128,v=null):(kp(),$e=D.fallback,V=v.mode,D=W_({mode:"visible",children:D.children},V),$e=vf($e,V,N,null),$e.flags|=2,D.return=v,$e.return=v,D.sibling=$e,v.child=D,Pf(v,h.child,null,N),D=v.child,D.memoizedState=eM(N),D.childLanes=tM(h,Se,N),v.memoizedState=Jj,v=Mv(null,D));else if(_p(v),IM($e)){if(Se=$e.nextSibling&&$e.nextSibling.dataset,Se)var Mt=Se.dgst;Se=Mt,D=Error(a(419)),D.stack="",D.digest=Se,yv({value:D,source:null,stack:null}),v=rM(h,v,N)}else if(bi||Cb(h,v,N,!1),Se=(N&h.childLanes)!==0,bi||Se){if(Se=ma,Se!==null&&(D=bt(Se,N),D!==0&&D!==pt.retryLane))throw pt.retryLane=D,yf(h,D),Oo(Se,h,D),Xj;RM($e)||nk(),v=rM(h,v,N)}else RM($e)?(v.flags|=192,v.child=h.child,v=null):(h=pt.treeContext,Ca=$l($e.nextSibling),vs=v,Cr=!0,bp=null,Hl=!1,h!==null&&wU(v,h),v=nM(v,D.children),v.flags|=4096);return v}return V?(kp(),$e=D.fallback,V=v.mode,pt=h.child,Mt=pt.sibling,D=Du(pt,{mode:"hidden",children:D.children}),D.subtreeFlags=pt.subtreeFlags&65011712,Mt!==null?$e=Du(Mt,$e):($e=vf($e,V,N,null),$e.flags|=2),$e.return=v,D.return=v,D.sibling=$e,v.child=D,Mv(null,D),D=v.child,$e=h.child.memoizedState,$e===null?$e=eM(N):(V=$e.cachePool,V!==null?(pt=fi._currentValue,V=V.parent!==pt?{parent:pt,pool:pt}:V):V=PU(),$e={baseLanes:$e.baseLanes|N,cachePool:V}),D.memoizedState=$e,D.childLanes=tM(h,Se,N),v.memoizedState=Jj,Mv(h.child,D)):(_p(v),N=h.child,h=N.sibling,N=Du(N,{mode:"visible",children:D.children}),N.return=v,N.sibling=null,h!==null&&(Se=v.deletions,Se===null?(v.deletions=[h],v.flags|=16):Se.push(h)),v.child=N,v.memoizedState=null,N)}function nM(h,v){return v=W_({mode:"visible",children:v},h.mode),v.return=h,h.child=v}function W_(h,v){return h=al(22,h,null,v),h.lanes=0,h}function rM(h,v,N){return Pf(v,h.child,null,N),h=nM(v,v.pendingProps.children),h.flags|=2,v.memoizedState=null,h}function UB(h,v,N){h.lanes|=v;var D=h.alternate;D!==null&&(D.lanes|=v),xj(h.return,v,N)}function aM(h,v,N,D,V,ee){var Se=h.memoizedState;Se===null?h.memoizedState={isBackwards:v,rendering:null,renderingStartTime:0,last:D,tail:N,tailMode:V,treeForkCount:ee}:(Se.isBackwards=v,Se.rendering=null,Se.renderingStartTime=0,Se.last=D,Se.tail=N,Se.tailMode=V,Se.treeForkCount=ee)}function BB(h,v,N){var D=v.pendingProps,V=D.revealOrder,ee=D.tail;D=D.children;var Se=li.current,$e=(Se&2)!==0;if($e?(Se=Se&1|2,v.flags|=128):Se&=1,pe(li,Se),Ss(h,v,D,N),D=Cr?xv:0,!$e&&h!==null&&(h.flags&128)!==0)e:for(h=v.child;h!==null;){if(h.tag===13)h.memoizedState!==null&&UB(h,N,v);else if(h.tag===19)UB(h,N,v);else if(h.child!==null){h.child.return=h,h=h.child;continue}if(h===v)break e;for(;h.sibling===null;){if(h.return===null||h.return===v)break e;h=h.return}h.sibling.return=h.return,h=h.sibling}switch(V){case"forwards":for(N=v.child,V=null;N!==null;)h=N.alternate,h!==null&&L_(h)===null&&(V=N),N=N.sibling;N=V,N===null?(V=v.child,v.child=null):(V=N.sibling,N.sibling=null),aM(v,!1,V,N,ee,D);break;case"backwards":case"unstable_legacy-backwards":for(N=null,V=v.child,v.child=null;V!==null;){if(h=V.alternate,h!==null&&L_(h)===null){v.child=V;break}h=V.sibling,V.sibling=N,N=V,V=h}aM(v,!0,N,null,ee,D);break;case"together":aM(v,!1,null,null,void 0,D);break;default:v.memoizedState=null}return v.child}function zu(h,v,N){if(h!==null&&(v.dependencies=h.dependencies),Pp|=v.lanes,(N&v.childLanes)===0)if(h!==null){if(Cb(h,v,N,!1),(N&v.childLanes)===0)return null}else return null;if(h!==null&&v.child!==h.child)throw Error(a(153));if(v.child!==null){for(h=v.child,N=Du(h,h.pendingProps),v.child=N,N.return=v;h.sibling!==null;)h=h.sibling,N=N.sibling=Du(h,h.pendingProps),N.return=v;N.sibling=null}return v.child}function iM(h,v){return(h.lanes&v)!==0?!0:(h=h.dependencies,!!(h!==null&&P_(h)))}function Hde(h,v,N){switch(v.tag){case 3:j(v,v.stateNode.containerInfo),yp(v,fi,h.memoizedState.cache),wf();break;case 27:case 5:B(v);break;case 4:j(v,v.stateNode.containerInfo);break;case 10:yp(v,v.type,v.memoizedProps.value);break;case 31:if(v.memoizedState!==null)return v.flags|=128,jj(v),null;break;case 13:var D=v.memoizedState;if(D!==null)return D.dehydrated!==null?(_p(v),v.flags|=128,null):(N&v.child.childLanes)!==0?zB(h,v,N):(_p(v),h=zu(h,v,N),h!==null?h.sibling:null);_p(v);break;case 19:var V=(h.flags&128)!==0;if(D=(N&v.childLanes)!==0,D||(Cb(h,v,N,!1),D=(N&v.childLanes)!==0),V){if(D)return BB(h,v,N);v.flags|=128}if(V=v.memoizedState,V!==null&&(V.rendering=null,V.tail=null,V.lastEffect=null),pe(li,li.current),D)break;return null;case 22:return v.lanes=0,DB(h,v,N,v.pendingProps);case 24:yp(v,fi,h.memoizedState.cache)}return zu(h,v,N)}function HB(h,v,N){if(h!==null)if(h.memoizedProps!==v.pendingProps)bi=!0;else{if(!iM(h,N)&&(v.flags&128)===0)return bi=!1,Hde(h,v,N);bi=(h.flags&131072)!==0}else bi=!1,Cr&&(v.flags&1048576)!==0&&vU(v,xv,v.index);switch(v.lanes=0,v.tag){case 16:e:{var D=v.pendingProps;if(h=Nf(v.elementType),v.type=h,typeof h=="function")dj(h)?(D=Af(h,D),v.tag=1,v=IB(null,v,h,D,N)):(v.tag=0,v=Zj(null,v,h,D,N));else{if(h!=null){var V=h.$$typeof;if(V===C){v.tag=11,v=jB(null,v,h,D,N);break e}else if(V===A){v.tag=14,v=MB(null,v,h,D,N);break e}}throw v=L(h)||h,Error(a(306,v,""))}}return v;case 0:return Zj(h,v,v.type,v.pendingProps,N);case 1:return D=v.type,V=Af(D,v.pendingProps),IB(h,v,D,V,N);case 3:e:{if(j(v,v.stateNode.containerInfo),h===null)throw Error(a(387));D=v.pendingProps;var ee=v.memoizedState;V=ee.element,Nj(h,v),Cv(v,D,null,N);var Se=v.memoizedState;if(D=Se.cache,yp(v,fi,D),D!==ee.cache&&yj(v,[fi],N,!0),Nv(),D=Se.element,ee.isDehydrated)if(ee={element:D,isDehydrated:!1,cache:Se.cache},v.updateQueue.baseState=ee,v.memoizedState=ee,v.flags&256){v=OB(h,v,D,N);break e}else if(D!==V){V=zl(Error(a(424)),v),yv(V),v=OB(h,v,D,N);break e}else for(h=v.stateNode.containerInfo,h.nodeType===9?h=h.body:h=h.nodeName==="HTML"?h.ownerDocument.body:h,Ca=$l(h.firstChild),vs=v,Cr=!0,bp=null,Hl=!0,N=DU(v,null,D,N),v.child=N;N;)N.flags=N.flags&-3|4096,N=N.sibling;else{if(wf(),D===V){v=zu(h,v,N);break e}Ss(h,v,D,N)}v=v.child}return v;case 26:return G_(h,v),h===null?(N=JH(v.type,null,v.pendingProps,null))?v.memoizedState=N:Cr||(N=v.type,h=v.pendingProps,D=ck($.current).createElement(N),D[kt]=v,D[Nt]=h,_s(D,N,h),at(D),v.stateNode=D):v.memoizedState=JH(v.type,h.memoizedProps,v.pendingProps,h.memoizedState),null;case 27:return B(v),h===null&&Cr&&(D=v.stateNode=YH(v.type,v.pendingProps,$.current),vs=v,Hl=!0,V=Ca,Ep(v.type)?(OM=V,Ca=$l(D.firstChild)):Ca=V),Ss(h,v,v.pendingProps.children,N),G_(h,v),h===null&&(v.flags|=4194304),v.child;case 5:return h===null&&Cr&&((V=D=Ca)&&(D=xue(D,v.type,v.pendingProps,Hl),D!==null?(v.stateNode=D,vs=v,Ca=$l(D.firstChild),Hl=!1,V=!0):V=!1),V||xp(v)),B(v),V=v.type,ee=v.pendingProps,Se=h!==null?h.memoizedProps:null,D=ee.children,DM(V,ee)?D=null:Se!==null&&DM(V,Se)&&(v.flags|=32),v.memoizedState!==null&&(V=Ej(h,v,Dde,null,null,N),Gv._currentValue=V),G_(h,v),Ss(h,v,D,N),v.child;case 6:return h===null&&Cr&&((h=N=Ca)&&(N=yue(N,v.pendingProps,Hl),N!==null?(v.stateNode=N,vs=v,Ca=null,h=!0):h=!1),h||xp(v)),null;case 13:return zB(h,v,N);case 4:return j(v,v.stateNode.containerInfo),D=v.pendingProps,h===null?v.child=Pf(v,null,D,N):Ss(h,v,D,N),v.child;case 11:return jB(h,v,v.type,v.pendingProps,N);case 7:return Ss(h,v,v.pendingProps,N),v.child;case 8:return Ss(h,v,v.pendingProps.children,N),v.child;case 12:return Ss(h,v,v.pendingProps.children,N),v.child;case 10:return D=v.pendingProps,yp(v,v.type,D.value),Ss(h,v,D.children,N),v.child;case 9:return V=v.type._context,D=v.pendingProps.children,_f(v),V=ws(V),D=D(V),v.flags|=1,Ss(h,v,D,N),v.child;case 14:return MB(h,v,v.type,v.pendingProps,N);case 15:return EB(h,v,v.type,v.pendingProps,N);case 19:return BB(h,v,N);case 31:return Bde(h,v,N);case 22:return DB(h,v,N,v.pendingProps);case 24:return _f(v),D=ws(fi),h===null?(V=Sj(),V===null&&(V=ma,ee=vj(),V.pooledCache=ee,ee.refCount++,ee!==null&&(V.pooledCacheLanes|=N),V=ee),v.memoizedState={parent:D,cache:V},kj(v),yp(v,fi,V)):((h.lanes&N)!==0&&(Nj(h,v),Cv(v,null,null,N),Nv()),V=h.memoizedState,ee=v.memoizedState,V.parent!==D?(V={parent:D,cache:D},v.memoizedState=V,v.lanes===0&&(v.memoizedState=v.updateQueue.baseState=V),yp(v,fi,D)):(D=ee.cache,yp(v,fi,D),D!==V.cache&&yj(v,[fi],N,!0))),Ss(h,v,v.pendingProps.children,N),v.child;case 29:throw v.pendingProps}throw Error(a(156,v.tag))}function Uu(h){h.flags|=4}function sM(h,v,N,D,V){if((v=(h.mode&32)!==0)&&(v=!1),v){if(h.flags|=16777216,(V&335544128)===V)if(h.stateNode.complete)h.flags|=8192;else if(fH())h.flags|=8192;else throw Cf=M_,_j}else h.flags&=-16777217}function qB(h,v){if(v.type!=="stylesheet"||(v.state.loading&4)!==0)h.flags&=-16777217;else if(h.flags|=16777216,!a8(v))if(fH())h.flags|=8192;else throw Cf=M_,_j}function K_(h,v){v!==null&&(h.flags|=4),h.flags&16384&&(v=h.tag!==22?Qe():536870912,h.lanes|=v,Ob|=v)}function Ev(h,v){if(!Cr)switch(h.tailMode){case"hidden":v=h.tail;for(var N=null;v!==null;)v.alternate!==null&&(N=v),v=v.sibling;N===null?h.tail=null:N.sibling=null;break;case"collapsed":N=h.tail;for(var D=null;N!==null;)N.alternate!==null&&(D=N),N=N.sibling;D===null?v||h.tail===null?h.tail=null:h.tail.sibling=null:D.sibling=null}}function Pa(h){var v=h.alternate!==null&&h.alternate.child===h.child,N=0,D=0;if(v)for(var V=h.child;V!==null;)N|=V.lanes|V.childLanes,D|=V.subtreeFlags&65011712,D|=V.flags&65011712,V.return=h,V=V.sibling;else for(V=h.child;V!==null;)N|=V.lanes|V.childLanes,D|=V.subtreeFlags,D|=V.flags,V.return=h,V=V.sibling;return h.subtreeFlags|=D,h.childLanes=N,v}function qde(h,v,N){var D=v.pendingProps;switch(hj(v),v.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Pa(v),null;case 1:return Pa(v),null;case 3:return N=v.stateNode,D=null,h!==null&&(D=h.memoizedState.cache),v.memoizedState.cache!==D&&(v.flags|=2048),Ru(fi),E(),N.pendingContext&&(N.context=N.pendingContext,N.pendingContext=null),(h===null||h.child===null)&&(Nb(v)?Uu(v):h===null||h.memoizedState.isDehydrated&&(v.flags&256)===0||(v.flags|=1024,gj())),Pa(v),null;case 26:var V=v.type,ee=v.memoizedState;return h===null?(Uu(v),ee!==null?(Pa(v),qB(v,ee)):(Pa(v),sM(v,V,null,D,N))):ee?ee!==h.memoizedState?(Uu(v),Pa(v),qB(v,ee)):(Pa(v),v.flags&=-16777217):(h=h.memoizedProps,h!==D&&Uu(v),Pa(v),sM(v,V,h,D,N)),null;case 27:if(W(v),N=$.current,V=v.type,h!==null&&v.stateNode!=null)h.memoizedProps!==D&&Uu(v);else{if(!D){if(v.stateNode===null)throw Error(a(166));return Pa(v),null}h=he.current,Nb(v)?SU(v):(h=YH(V,D,N),v.stateNode=h,Uu(v))}return Pa(v),null;case 5:if(W(v),V=v.type,h!==null&&v.stateNode!=null)h.memoizedProps!==D&&Uu(v);else{if(!D){if(v.stateNode===null)throw Error(a(166));return Pa(v),null}if(ee=he.current,Nb(v))SU(v);else{var Se=ck($.current);switch(ee){case 1:ee=Se.createElementNS("http://www.w3.org/2000/svg",V);break;case 2:ee=Se.createElementNS("http://www.w3.org/1998/Math/MathML",V);break;default:switch(V){case"svg":ee=Se.createElementNS("http://www.w3.org/2000/svg",V);break;case"math":ee=Se.createElementNS("http://www.w3.org/1998/Math/MathML",V);break;case"script":ee=Se.createElement("div"),ee.innerHTML="<script><\/script>",ee=ee.removeChild(ee.firstChild);break;case"select":ee=typeof D.is=="string"?Se.createElement("select",{is:D.is}):Se.createElement("select"),D.multiple?ee.multiple=!0:D.size&&(ee.size=D.size);break;default:ee=typeof D.is=="string"?Se.createElement(V,{is:D.is}):Se.createElement(V)}}ee[kt]=v,ee[Nt]=D;e:for(Se=v.child;Se!==null;){if(Se.tag===5||Se.tag===6)ee.appendChild(Se.stateNode);else if(Se.tag!==4&&Se.tag!==27&&Se.child!==null){Se.child.return=Se,Se=Se.child;continue}if(Se===v)break e;for(;Se.sibling===null;){if(Se.return===null||Se.return===v)break e;Se=Se.return}Se.sibling.return=Se.return,Se=Se.sibling}v.stateNode=ee;e:switch(_s(ee,V,D),V){case"button":case"input":case"select":case"textarea":D=!!D.autoFocus;break e;case"img":D=!0;break e;default:D=!1}D&&Uu(v)}}return Pa(v),sM(v,v.type,h===null?null:h.memoizedProps,v.pendingProps,N),null;case 6:if(h&&v.stateNode!=null)h.memoizedProps!==D&&Uu(v);else{if(typeof D!="string"&&v.stateNode===null)throw Error(a(166));if(h=$.current,Nb(v)){if(h=v.stateNode,N=v.memoizedProps,D=null,V=vs,V!==null)switch(V.tag){case 27:case 5:D=V.memoizedProps}h[kt]=v,h=!!(h.nodeValue===N||D!==null&&D.suppressHydrationWarning===!0||zH(h.nodeValue,N)),h||xp(v,!0)}else h=ck(h).createTextNode(D),h[kt]=v,v.stateNode=h}return Pa(v),null;case 31:if(N=v.memoizedState,h===null||h.memoizedState!==null){if(D=Nb(v),N!==null){if(h===null){if(!D)throw Error(a(318));if(h=v.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(557));h[kt]=v}else wf(),(v.flags&128)===0&&(v.memoizedState=null),v.flags|=4;Pa(v),h=!1}else N=gj(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=N),h=!0;if(!h)return v.flags&256?(sl(v),v):(sl(v),null);if((v.flags&128)!==0)throw Error(a(558))}return Pa(v),null;case 13:if(D=v.memoizedState,h===null||h.memoizedState!==null&&h.memoizedState.dehydrated!==null){if(V=Nb(v),D!==null&&D.dehydrated!==null){if(h===null){if(!V)throw Error(a(318));if(V=v.memoizedState,V=V!==null?V.dehydrated:null,!V)throw Error(a(317));V[kt]=v}else wf(),(v.flags&128)===0&&(v.memoizedState=null),v.flags|=4;Pa(v),V=!1}else V=gj(),h!==null&&h.memoizedState!==null&&(h.memoizedState.hydrationErrors=V),V=!0;if(!V)return v.flags&256?(sl(v),v):(sl(v),null)}return sl(v),(v.flags&128)!==0?(v.lanes=N,v):(N=D!==null,h=h!==null&&h.memoizedState!==null,N&&(D=v.child,V=null,D.alternate!==null&&D.alternate.memoizedState!==null&&D.alternate.memoizedState.cachePool!==null&&(V=D.alternate.memoizedState.cachePool.pool),ee=null,D.memoizedState!==null&&D.memoizedState.cachePool!==null&&(ee=D.memoizedState.cachePool.pool),ee!==V&&(D.flags|=2048)),N!==h&&N&&(v.child.flags|=8192),K_(v,v.updateQueue),Pa(v),null);case 4:return E(),h===null&&TM(v.stateNode.containerInfo),Pa(v),null;case 10:return Ru(v.type),Pa(v),null;case 19:if(le(li),D=v.memoizedState,D===null)return Pa(v),null;if(V=(v.flags&128)!==0,ee=D.rendering,ee===null)if(V)Ev(D,!1);else{if(Za!==0||h!==null&&(h.flags&128)!==0)for(h=v.child;h!==null;){if(ee=L_(h),ee!==null){for(v.flags|=128,Ev(D,!1),h=ee.updateQueue,v.updateQueue=h,K_(v,h),v.subtreeFlags=0,h=N,N=v.child;N!==null;)bU(N,h),N=N.sibling;return pe(li,li.current&1|2),Cr&&Fu(v,D.treeForkCount),v.child}h=h.sibling}D.tail!==null&&R()>J_&&(v.flags|=128,V=!0,Ev(D,!1),v.lanes=4194304)}else{if(!V)if(h=L_(ee),h!==null){if(v.flags|=128,V=!0,h=h.updateQueue,v.updateQueue=h,K_(v,h),Ev(D,!0),D.tail===null&&D.tailMode==="hidden"&&!ee.alternate&&!Cr)return Pa(v),null}else 2*R()-D.renderingStartTime>J_&&N!==536870912&&(v.flags|=128,V=!0,Ev(D,!1),v.lanes=4194304);D.isBackwards?(ee.sibling=v.child,v.child=ee):(h=D.last,h!==null?h.sibling=ee:v.child=ee,D.last=ee)}return D.tail!==null?(h=D.tail,D.rendering=h,D.tail=h.sibling,D.renderingStartTime=R(),h.sibling=null,N=li.current,pe(li,V?N&1|2:N&1),Cr&&Fu(v,D.treeForkCount),h):(Pa(v),null);case 22:case 23:return sl(v),Aj(),D=v.memoizedState!==null,h!==null?h.memoizedState!==null!==D&&(v.flags|=8192):D&&(v.flags|=8192),D?(N&536870912)!==0&&(v.flags&128)===0&&(Pa(v),v.subtreeFlags&6&&(v.flags|=8192)):Pa(v),N=v.updateQueue,N!==null&&K_(v,N.retryQueue),N=null,h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(N=h.memoizedState.cachePool.pool),D=null,v.memoizedState!==null&&v.memoizedState.cachePool!==null&&(D=v.memoizedState.cachePool.pool),D!==N&&(v.flags|=2048),h!==null&&le(kf),null;case 24:return N=null,h!==null&&(N=h.memoizedState.cache),v.memoizedState.cache!==N&&(v.flags|=2048),Ru(fi),Pa(v),null;case 25:return null;case 30:return null}throw Error(a(156,v.tag))}function $de(h,v){switch(hj(v),v.tag){case 1:return h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 3:return Ru(fi),E(),h=v.flags,(h&65536)!==0&&(h&128)===0?(v.flags=h&-65537|128,v):null;case 26:case 27:case 5:return W(v),null;case 31:if(v.memoizedState!==null){if(sl(v),v.alternate===null)throw Error(a(340));wf()}return h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 13:if(sl(v),h=v.memoizedState,h!==null&&h.dehydrated!==null){if(v.alternate===null)throw Error(a(340));wf()}return h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 19:return le(li),null;case 4:return E(),null;case 10:return Ru(v.type),null;case 22:case 23:return sl(v),Aj(),h!==null&&le(kf),h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 24:return Ru(fi),null;case 25:return null;default:return null}}function $B(h,v){switch(hj(v),v.tag){case 3:Ru(fi),E();break;case 26:case 27:case 5:W(v);break;case 4:E();break;case 31:v.memoizedState!==null&&sl(v);break;case 13:sl(v);break;case 19:le(li);break;case 10:Ru(v.type);break;case 22:case 23:sl(v),Aj(),h!==null&&le(kf);break;case 24:Ru(fi)}}function Dv(h,v){try{var N=v.updateQueue,D=N!==null?N.lastEffect:null;if(D!==null){var V=D.next;N=V;do{if((N.tag&h)===h){D=void 0;var ee=N.create,Se=N.inst;D=ee(),Se.destroy=D}N=N.next}while(N!==V)}}catch($e){Qr(v,v.return,$e)}}function Np(h,v,N){try{var D=v.updateQueue,V=D!==null?D.lastEffect:null;if(V!==null){var ee=V.next;D=ee;do{if((D.tag&h)===h){var Se=D.inst,$e=Se.destroy;if($e!==void 0){Se.destroy=void 0,V=v;var pt=N,Mt=$e;try{Mt()}catch(Ht){Qr(V,pt,Ht)}}}D=D.next}while(D!==ee)}}catch(Ht){Qr(v,v.return,Ht)}}function VB(h){var v=h.updateQueue;if(v!==null){var N=h.stateNode;try{LU(v,N)}catch(D){Qr(h,h.return,D)}}}function GB(h,v,N){N.props=Af(h.type,h.memoizedProps),N.state=h.memoizedState;try{N.componentWillUnmount()}catch(D){Qr(h,v,D)}}function Fv(h,v){try{var N=h.ref;if(N!==null){switch(h.tag){case 26:case 27:case 5:var D=h.stateNode;break;case 30:D=h.stateNode;break;default:D=h.stateNode}typeof N=="function"?h.refCleanup=N(D):N.current=D}}catch(V){Qr(h,v,V)}}function Ed(h,v){var N=h.ref,D=h.refCleanup;if(N!==null)if(typeof D=="function")try{D()}catch(V){Qr(h,v,V)}finally{h.refCleanup=null,h=h.alternate,h!=null&&(h.refCleanup=null)}else if(typeof N=="function")try{N(null)}catch(V){Qr(h,v,V)}else N.current=null}function WB(h){var v=h.type,N=h.memoizedProps,D=h.stateNode;try{e:switch(v){case"button":case"input":case"select":case"textarea":N.autoFocus&&D.focus();break e;case"img":N.src?D.src=N.src:N.srcSet&&(D.srcset=N.srcSet)}}catch(V){Qr(h,h.return,V)}}function oM(h,v,N){try{var D=h.stateNode;mue(D,h.type,N,v),D[Nt]=v}catch(V){Qr(h,h.return,V)}}function KB(h){return h.tag===5||h.tag===3||h.tag===26||h.tag===27&&Ep(h.type)||h.tag===4}function lM(h){e:for(;;){for(;h.sibling===null;){if(h.return===null||KB(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&&Ep(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 cM(h,v,N){var D=h.tag;if(D===5||D===6)h=h.stateNode,v?(N.nodeType===9?N.body:N.nodeName==="HTML"?N.ownerDocument.body:N).insertBefore(h,v):(v=N.nodeType===9?N.body:N.nodeName==="HTML"?N.ownerDocument.body:N,v.appendChild(h),N=N._reactRootContainer,N!=null||v.onclick!==null||(v.onclick=Kt));else if(D!==4&&(D===27&&Ep(h.type)&&(N=h.stateNode,v=null),h=h.child,h!==null))for(cM(h,v,N),h=h.sibling;h!==null;)cM(h,v,N),h=h.sibling}function Q_(h,v,N){var D=h.tag;if(D===5||D===6)h=h.stateNode,v?N.insertBefore(h,v):N.appendChild(h);else if(D!==4&&(D===27&&Ep(h.type)&&(N=h.stateNode),h=h.child,h!==null))for(Q_(h,v,N),h=h.sibling;h!==null;)Q_(h,v,N),h=h.sibling}function QB(h){var v=h.stateNode,N=h.memoizedProps;try{for(var D=h.type,V=v.attributes;V.length;)v.removeAttributeNode(V[0]);_s(v,D,N),v[kt]=h,v[Nt]=N}catch(ee){Qr(h,h.return,ee)}}var Bu=!1,xi=!1,dM=!1,YB=typeof WeakSet=="function"?WeakSet:Set,Zi=null;function Vde(h,v){if(h=h.containerInfo,MM=gk,h=Hc(h),Xi(h)){if("selectionStart"in h)var N={start:h.selectionStart,end:h.selectionEnd};else e:{N=(N=h.ownerDocument)&&N.defaultView||window;var D=N.getSelection&&N.getSelection();if(D&&D.rangeCount!==0){N=D.anchorNode;var V=D.anchorOffset,ee=D.focusNode;D=D.focusOffset;try{N.nodeType,ee.nodeType}catch{N=null;break e}var Se=0,$e=-1,pt=-1,Mt=0,Ht=0,Gt=h,Ft=null;t:for(;;){for(var Ot;Gt!==N||V!==0&&Gt.nodeType!==3||($e=Se+V),Gt!==ee||D!==0&&Gt.nodeType!==3||(pt=Se+D),Gt.nodeType===3&&(Se+=Gt.nodeValue.length),(Ot=Gt.firstChild)!==null;)Ft=Gt,Gt=Ot;for(;;){if(Gt===h)break t;if(Ft===N&&++Mt===V&&($e=Se),Ft===ee&&++Ht===D&&(pt=Se),(Ot=Gt.nextSibling)!==null)break;Gt=Ft,Ft=Gt.parentNode}Gt=Ot}N=$e===-1||pt===-1?null:{start:$e,end:pt}}else N=null}N=N||{start:0,end:0}}else N=null;for(EM={focusedElem:h,selectionRange:N},gk=!1,Zi=v;Zi!==null;)if(v=Zi,h=v.child,(v.subtreeFlags&1028)!==0&&h!==null)h.return=v,Zi=h;else for(;Zi!==null;){switch(v=Zi,ee=v.alternate,h=v.flags,v.tag){case 0:if((h&4)!==0&&(h=v.updateQueue,h=h!==null?h.events:null,h!==null))for(N=0;N<h.length;N++)V=h[N],V.ref.impl=V.nextImpl;break;case 11:case 15:break;case 1:if((h&1024)!==0&&ee!==null){h=void 0,N=v,V=ee.memoizedProps,ee=ee.memoizedState,D=N.stateNode;try{var vn=Af(N.type,V);h=D.getSnapshotBeforeUpdate(vn,ee),D.__reactInternalSnapshotBeforeUpdate=h}catch(Bn){Qr(N,N.return,Bn)}}break;case 3:if((h&1024)!==0){if(h=v.stateNode.containerInfo,N=h.nodeType,N===9)LM(h);else if(N===1)switch(h.nodeName){case"HEAD":case"HTML":case"BODY":LM(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(a(163))}if(h=v.sibling,h!==null){h.return=v.return,Zi=h;break}Zi=v.return}}function XB(h,v,N){var D=N.flags;switch(N.tag){case 0:case 11:case 15:qu(h,N),D&4&&Dv(5,N);break;case 1:if(qu(h,N),D&4)if(h=N.stateNode,v===null)try{h.componentDidMount()}catch(Se){Qr(N,N.return,Se)}else{var V=Af(N.type,v.memoizedProps);v=v.memoizedState;try{h.componentDidUpdate(V,v,h.__reactInternalSnapshotBeforeUpdate)}catch(Se){Qr(N,N.return,Se)}}D&64&&VB(N),D&512&&Fv(N,N.return);break;case 3:if(qu(h,N),D&64&&(h=N.updateQueue,h!==null)){if(v=null,N.child!==null)switch(N.child.tag){case 27:case 5:v=N.child.stateNode;break;case 1:v=N.child.stateNode}try{LU(h,v)}catch(Se){Qr(N,N.return,Se)}}break;case 27:v===null&&D&4&&QB(N);case 26:case 5:qu(h,N),v===null&&D&4&&WB(N),D&512&&Fv(N,N.return);break;case 12:qu(h,N);break;case 31:qu(h,N),D&4&&eH(h,N);break;case 13:qu(h,N),D&4&&tH(h,N),D&64&&(h=N.memoizedState,h!==null&&(h=h.dehydrated,h!==null&&(N=eue.bind(null,N),vue(h,N))));break;case 22:if(D=N.memoizedState!==null||Bu,!D){v=v!==null&&v.memoizedState!==null||xi,V=Bu;var ee=xi;Bu=D,(xi=v)&&!ee?$u(h,N,(N.subtreeFlags&8772)!==0):qu(h,N),Bu=V,xi=ee}break;case 30:break;default:qu(h,N)}}function ZB(h){var v=h.alternate;v!==null&&(h.alternate=null,ZB(v)),h.child=null,h.deletions=null,h.sibling=null,h.tag===5&&(v=h.stateNode,v!==null&&De(v)),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 Da=null,Fo=!1;function Hu(h,v,N){for(N=N.child;N!==null;)JB(h,v,N),N=N.sibling}function JB(h,v,N){if(Oe&&typeof Oe.onCommitFiberUnmount=="function")try{Oe.onCommitFiberUnmount(Fe,N)}catch{}switch(N.tag){case 26:xi||Ed(N,v),Hu(h,v,N),N.memoizedState?N.memoizedState.count--:N.stateNode&&(N=N.stateNode,N.parentNode.removeChild(N));break;case 27:xi||Ed(N,v);var D=Da,V=Fo;Ep(N.type)&&(Da=N.stateNode,Fo=!1),Hu(h,v,N),qv(N.stateNode),Da=D,Fo=V;break;case 5:xi||Ed(N,v);case 6:if(D=Da,V=Fo,Da=null,Hu(h,v,N),Da=D,Fo=V,Da!==null)if(Fo)try{(Da.nodeType===9?Da.body:Da.nodeName==="HTML"?Da.ownerDocument.body:Da).removeChild(N.stateNode)}catch(ee){Qr(N,v,ee)}else try{Da.removeChild(N.stateNode)}catch(ee){Qr(N,v,ee)}break;case 18:Da!==null&&(Fo?(h=Da,VH(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,N.stateNode),Gb(h)):VH(Da,N.stateNode));break;case 4:D=Da,V=Fo,Da=N.stateNode.containerInfo,Fo=!0,Hu(h,v,N),Da=D,Fo=V;break;case 0:case 11:case 14:case 15:Np(2,N,v),xi||Np(4,N,v),Hu(h,v,N);break;case 1:xi||(Ed(N,v),D=N.stateNode,typeof D.componentWillUnmount=="function"&&GB(N,v,D)),Hu(h,v,N);break;case 21:Hu(h,v,N);break;case 22:xi=(D=xi)||N.memoizedState!==null,Hu(h,v,N),xi=D;break;default:Hu(h,v,N)}}function eH(h,v){if(v.memoizedState===null&&(h=v.alternate,h!==null&&(h=h.memoizedState,h!==null))){h=h.dehydrated;try{Gb(h)}catch(N){Qr(v,v.return,N)}}}function tH(h,v){if(v.memoizedState===null&&(h=v.alternate,h!==null&&(h=h.memoizedState,h!==null&&(h=h.dehydrated,h!==null))))try{Gb(h)}catch(N){Qr(v,v.return,N)}}function Gde(h){switch(h.tag){case 31:case 13:case 19:var v=h.stateNode;return v===null&&(v=h.stateNode=new YB),v;case 22:return h=h.stateNode,v=h._retryCache,v===null&&(v=h._retryCache=new YB),v;default:throw Error(a(435,h.tag))}}function Y_(h,v){var N=Gde(h);v.forEach(function(D){if(!N.has(D)){N.add(D);var V=tue.bind(null,h,D);D.then(V,V)}})}function Lo(h,v){var N=v.deletions;if(N!==null)for(var D=0;D<N.length;D++){var V=N[D],ee=h,Se=v,$e=Se;e:for(;$e!==null;){switch($e.tag){case 27:if(Ep($e.type)){Da=$e.stateNode,Fo=!1;break e}break;case 5:Da=$e.stateNode,Fo=!1;break e;case 3:case 4:Da=$e.stateNode.containerInfo,Fo=!0;break e}$e=$e.return}if(Da===null)throw Error(a(160));JB(ee,Se,V),Da=null,Fo=!1,ee=V.alternate,ee!==null&&(ee.return=null),V.return=null}if(v.subtreeFlags&13886)for(v=v.child;v!==null;)nH(v,h),v=v.sibling}var Gc=null;function nH(h,v){var N=h.alternate,D=h.flags;switch(h.tag){case 0:case 11:case 14:case 15:Lo(v,h),Ro(h),D&4&&(Np(3,h,h.return),Dv(3,h),Np(5,h,h.return));break;case 1:Lo(v,h),Ro(h),D&512&&(xi||N===null||Ed(N,N.return)),D&64&&Bu&&(h=h.updateQueue,h!==null&&(D=h.callbacks,D!==null&&(N=h.shared.hiddenCallbacks,h.shared.hiddenCallbacks=N===null?D:N.concat(D))));break;case 26:var V=Gc;if(Lo(v,h),Ro(h),D&512&&(xi||N===null||Ed(N,N.return)),D&4){var ee=N!==null?N.memoizedState:null;if(D=h.memoizedState,N===null)if(D===null)if(h.stateNode===null){e:{D=h.type,N=h.memoizedProps,V=V.ownerDocument||V;t:switch(D){case"title":ee=V.getElementsByTagName("title")[0],(!ee||ee[Je]||ee[kt]||ee.namespaceURI==="http://www.w3.org/2000/svg"||ee.hasAttribute("itemprop"))&&(ee=V.createElement(D),V.head.insertBefore(ee,V.querySelector("head > title"))),_s(ee,D,N),ee[kt]=h,at(ee),D=ee;break e;case"link":var Se=n8("link","href",V).get(D+(N.href||""));if(Se){for(var $e=0;$e<Se.length;$e++)if(ee=Se[$e],ee.getAttribute("href")===(N.href==null||N.href===""?null:N.href)&&ee.getAttribute("rel")===(N.rel==null?null:N.rel)&&ee.getAttribute("title")===(N.title==null?null:N.title)&&ee.getAttribute("crossorigin")===(N.crossOrigin==null?null:N.crossOrigin)){Se.splice($e,1);break t}}ee=V.createElement(D),_s(ee,D,N),V.head.appendChild(ee);break;case"meta":if(Se=n8("meta","content",V).get(D+(N.content||""))){for($e=0;$e<Se.length;$e++)if(ee=Se[$e],ee.getAttribute("content")===(N.content==null?null:""+N.content)&&ee.getAttribute("name")===(N.name==null?null:N.name)&&ee.getAttribute("property")===(N.property==null?null:N.property)&&ee.getAttribute("http-equiv")===(N.httpEquiv==null?null:N.httpEquiv)&&ee.getAttribute("charset")===(N.charSet==null?null:N.charSet)){Se.splice($e,1);break t}}ee=V.createElement(D),_s(ee,D,N),V.head.appendChild(ee);break;default:throw Error(a(468,D))}ee[kt]=h,at(ee),D=ee}h.stateNode=D}else r8(V,h.type,h.stateNode);else h.stateNode=t8(V,D,h.memoizedProps);else ee!==D?(ee===null?N.stateNode!==null&&(N=N.stateNode,N.parentNode.removeChild(N)):ee.count--,D===null?r8(V,h.type,h.stateNode):t8(V,D,h.memoizedProps)):D===null&&h.stateNode!==null&&oM(h,h.memoizedProps,N.memoizedProps)}break;case 27:Lo(v,h),Ro(h),D&512&&(xi||N===null||Ed(N,N.return)),N!==null&&D&4&&oM(h,h.memoizedProps,N.memoizedProps);break;case 5:if(Lo(v,h),Ro(h),D&512&&(xi||N===null||Ed(N,N.return)),h.flags&32){V=h.stateNode;try{Mi(V,"")}catch(vn){Qr(h,h.return,vn)}}D&4&&h.stateNode!=null&&(V=h.memoizedProps,oM(h,V,N!==null?N.memoizedProps:V)),D&1024&&(dM=!0);break;case 6:if(Lo(v,h),Ro(h),D&4){if(h.stateNode===null)throw Error(a(162));D=h.memoizedProps,N=h.stateNode;try{N.nodeValue=D}catch(vn){Qr(h,h.return,vn)}}break;case 3:if(mk=null,V=Gc,Gc=dk(v.containerInfo),Lo(v,h),Gc=V,Ro(h),D&4&&N!==null&&N.memoizedState.isDehydrated)try{Gb(v.containerInfo)}catch(vn){Qr(h,h.return,vn)}dM&&(dM=!1,rH(h));break;case 4:D=Gc,Gc=dk(h.stateNode.containerInfo),Lo(v,h),Ro(h),Gc=D;break;case 12:Lo(v,h),Ro(h);break;case 31:Lo(v,h),Ro(h),D&4&&(D=h.updateQueue,D!==null&&(h.updateQueue=null,Y_(h,D)));break;case 13:Lo(v,h),Ro(h),h.child.flags&8192&&h.memoizedState!==null!=(N!==null&&N.memoizedState!==null)&&(Z_=R()),D&4&&(D=h.updateQueue,D!==null&&(h.updateQueue=null,Y_(h,D)));break;case 22:V=h.memoizedState!==null;var pt=N!==null&&N.memoizedState!==null,Mt=Bu,Ht=xi;if(Bu=Mt||V,xi=Ht||pt,Lo(v,h),xi=Ht,Bu=Mt,Ro(h),D&8192)e:for(v=h.stateNode,v._visibility=V?v._visibility&-2:v._visibility|1,V&&(N===null||pt||Bu||xi||jf(h)),N=null,v=h;;){if(v.tag===5||v.tag===26){if(N===null){pt=N=v;try{if(ee=pt.stateNode,V)Se=ee.style,typeof Se.setProperty=="function"?Se.setProperty("display","none","important"):Se.display="none";else{$e=pt.stateNode;var Gt=pt.memoizedProps.style,Ft=Gt!=null&&Gt.hasOwnProperty("display")?Gt.display:null;$e.style.display=Ft==null||typeof Ft=="boolean"?"":(""+Ft).trim()}}catch(vn){Qr(pt,pt.return,vn)}}}else if(v.tag===6){if(N===null){pt=v;try{pt.stateNode.nodeValue=V?"":pt.memoizedProps}catch(vn){Qr(pt,pt.return,vn)}}}else if(v.tag===18){if(N===null){pt=v;try{var Ot=pt.stateNode;V?GH(Ot,!0):GH(pt.stateNode,!1)}catch(vn){Qr(pt,pt.return,vn)}}}else if((v.tag!==22&&v.tag!==23||v.memoizedState===null||v===h)&&v.child!==null){v.child.return=v,v=v.child;continue}if(v===h)break e;for(;v.sibling===null;){if(v.return===null||v.return===h)break e;N===v&&(N=null),v=v.return}N===v&&(N=null),v.sibling.return=v.return,v=v.sibling}D&4&&(D=h.updateQueue,D!==null&&(N=D.retryQueue,N!==null&&(D.retryQueue=null,Y_(h,N))));break;case 19:Lo(v,h),Ro(h),D&4&&(D=h.updateQueue,D!==null&&(h.updateQueue=null,Y_(h,D)));break;case 30:break;case 21:break;default:Lo(v,h),Ro(h)}}function Ro(h){var v=h.flags;if(v&2){try{for(var N,D=h.return;D!==null;){if(KB(D)){N=D;break}D=D.return}if(N==null)throw Error(a(160));switch(N.tag){case 27:var V=N.stateNode,ee=lM(h);Q_(h,ee,V);break;case 5:var Se=N.stateNode;N.flags&32&&(Mi(Se,""),N.flags&=-33);var $e=lM(h);Q_(h,$e,Se);break;case 3:case 4:var pt=N.stateNode.containerInfo,Mt=lM(h);cM(h,Mt,pt);break;default:throw Error(a(161))}}catch(Ht){Qr(h,h.return,Ht)}h.flags&=-3}v&4096&&(h.flags&=-4097)}function rH(h){if(h.subtreeFlags&1024)for(h=h.child;h!==null;){var v=h;rH(v),v.tag===5&&v.flags&1024&&v.stateNode.reset(),h=h.sibling}}function qu(h,v){if(v.subtreeFlags&8772)for(v=v.child;v!==null;)XB(h,v.alternate,v),v=v.sibling}function jf(h){for(h=h.child;h!==null;){var v=h;switch(v.tag){case 0:case 11:case 14:case 15:Np(4,v,v.return),jf(v);break;case 1:Ed(v,v.return);var N=v.stateNode;typeof N.componentWillUnmount=="function"&&GB(v,v.return,N),jf(v);break;case 27:qv(v.stateNode);case 26:case 5:Ed(v,v.return),jf(v);break;case 22:v.memoizedState===null&&jf(v);break;case 30:jf(v);break;default:jf(v)}h=h.sibling}}function $u(h,v,N){for(N=N&&(v.subtreeFlags&8772)!==0,v=v.child;v!==null;){var D=v.alternate,V=h,ee=v,Se=ee.flags;switch(ee.tag){case 0:case 11:case 15:$u(V,ee,N),Dv(4,ee);break;case 1:if($u(V,ee,N),D=ee,V=D.stateNode,typeof V.componentDidMount=="function")try{V.componentDidMount()}catch(Mt){Qr(D,D.return,Mt)}if(D=ee,V=D.updateQueue,V!==null){var $e=D.stateNode;try{var pt=V.shared.hiddenCallbacks;if(pt!==null)for(V.shared.hiddenCallbacks=null,V=0;V<pt.length;V++)FU(pt[V],$e)}catch(Mt){Qr(D,D.return,Mt)}}N&&Se&64&&VB(ee),Fv(ee,ee.return);break;case 27:QB(ee);case 26:case 5:$u(V,ee,N),N&&D===null&&Se&4&&WB(ee),Fv(ee,ee.return);break;case 12:$u(V,ee,N);break;case 31:$u(V,ee,N),N&&Se&4&&eH(V,ee);break;case 13:$u(V,ee,N),N&&Se&4&&tH(V,ee);break;case 22:ee.memoizedState===null&&$u(V,ee,N),Fv(ee,ee.return);break;case 30:break;default:$u(V,ee,N)}v=v.sibling}}function uM(h,v){var N=null;h!==null&&h.memoizedState!==null&&h.memoizedState.cachePool!==null&&(N=h.memoizedState.cachePool.pool),h=null,v.memoizedState!==null&&v.memoizedState.cachePool!==null&&(h=v.memoizedState.cachePool.pool),h!==N&&(h!=null&&h.refCount++,N!=null&&vv(N))}function mM(h,v){h=null,v.alternate!==null&&(h=v.alternate.memoizedState.cache),v=v.memoizedState.cache,v!==h&&(v.refCount++,h!=null&&vv(h))}function Wc(h,v,N,D){if(v.subtreeFlags&10256)for(v=v.child;v!==null;)aH(h,v,N,D),v=v.sibling}function aH(h,v,N,D){var V=v.flags;switch(v.tag){case 0:case 11:case 15:Wc(h,v,N,D),V&2048&&Dv(9,v);break;case 1:Wc(h,v,N,D);break;case 3:Wc(h,v,N,D),V&2048&&(h=null,v.alternate!==null&&(h=v.alternate.memoizedState.cache),v=v.memoizedState.cache,v!==h&&(v.refCount++,h!=null&&vv(h)));break;case 12:if(V&2048){Wc(h,v,N,D),h=v.stateNode;try{var ee=v.memoizedProps,Se=ee.id,$e=ee.onPostCommit;typeof $e=="function"&&$e(Se,v.alternate===null?"mount":"update",h.passiveEffectDuration,-0)}catch(pt){Qr(v,v.return,pt)}}else Wc(h,v,N,D);break;case 31:Wc(h,v,N,D);break;case 13:Wc(h,v,N,D);break;case 23:break;case 22:ee=v.stateNode,Se=v.alternate,v.memoizedState!==null?ee._visibility&2?Wc(h,v,N,D):Lv(h,v):ee._visibility&2?Wc(h,v,N,D):(ee._visibility|=2,Lb(h,v,N,D,(v.subtreeFlags&10256)!==0||!1)),V&2048&&uM(Se,v);break;case 24:Wc(h,v,N,D),V&2048&&mM(v.alternate,v);break;default:Wc(h,v,N,D)}}function Lb(h,v,N,D,V){for(V=V&&((v.subtreeFlags&10256)!==0||!1),v=v.child;v!==null;){var ee=h,Se=v,$e=N,pt=D,Mt=Se.flags;switch(Se.tag){case 0:case 11:case 15:Lb(ee,Se,$e,pt,V),Dv(8,Se);break;case 23:break;case 22:var Ht=Se.stateNode;Se.memoizedState!==null?Ht._visibility&2?Lb(ee,Se,$e,pt,V):Lv(ee,Se):(Ht._visibility|=2,Lb(ee,Se,$e,pt,V)),V&&Mt&2048&&uM(Se.alternate,Se);break;case 24:Lb(ee,Se,$e,pt,V),V&&Mt&2048&&mM(Se.alternate,Se);break;default:Lb(ee,Se,$e,pt,V)}v=v.sibling}}function Lv(h,v){if(v.subtreeFlags&10256)for(v=v.child;v!==null;){var N=h,D=v,V=D.flags;switch(D.tag){case 22:Lv(N,D),V&2048&&uM(D.alternate,D);break;case 24:Lv(N,D),V&2048&&mM(D.alternate,D);break;default:Lv(N,D)}v=v.sibling}}var Rv=8192;function Rb(h,v,N){if(h.subtreeFlags&Rv)for(h=h.child;h!==null;)iH(h,v,N),h=h.sibling}function iH(h,v,N){switch(h.tag){case 26:Rb(h,v,N),h.flags&Rv&&h.memoizedState!==null&&Eue(N,Gc,h.memoizedState,h.memoizedProps);break;case 5:Rb(h,v,N);break;case 3:case 4:var D=Gc;Gc=dk(h.stateNode.containerInfo),Rb(h,v,N),Gc=D;break;case 22:h.memoizedState===null&&(D=h.alternate,D!==null&&D.memoizedState!==null?(D=Rv,Rv=16777216,Rb(h,v,N),Rv=D):Rb(h,v,N));break;default:Rb(h,v,N)}}function sH(h){var v=h.alternate;if(v!==null&&(h=v.child,h!==null)){v.child=null;do v=h.sibling,h.sibling=null,h=v;while(h!==null)}}function Iv(h){var v=h.deletions;if((h.flags&16)!==0){if(v!==null)for(var N=0;N<v.length;N++){var D=v[N];Zi=D,lH(D,h)}sH(h)}if(h.subtreeFlags&10256)for(h=h.child;h!==null;)oH(h),h=h.sibling}function oH(h){switch(h.tag){case 0:case 11:case 15:Iv(h),h.flags&2048&&Np(9,h,h.return);break;case 3:Iv(h);break;case 12:Iv(h);break;case 22:var v=h.stateNode;h.memoizedState!==null&&v._visibility&2&&(h.return===null||h.return.tag!==13)?(v._visibility&=-3,X_(h)):Iv(h);break;default:Iv(h)}}function X_(h){var v=h.deletions;if((h.flags&16)!==0){if(v!==null)for(var N=0;N<v.length;N++){var D=v[N];Zi=D,lH(D,h)}sH(h)}for(h=h.child;h!==null;){switch(v=h,v.tag){case 0:case 11:case 15:Np(8,v,v.return),X_(v);break;case 22:N=v.stateNode,N._visibility&2&&(N._visibility&=-3,X_(v));break;default:X_(v)}h=h.sibling}}function lH(h,v){for(;Zi!==null;){var N=Zi;switch(N.tag){case 0:case 11:case 15:Np(8,N,v);break;case 23:case 22:if(N.memoizedState!==null&&N.memoizedState.cachePool!==null){var D=N.memoizedState.cachePool.pool;D!=null&&D.refCount++}break;case 24:vv(N.memoizedState.cache)}if(D=N.child,D!==null)D.return=N,Zi=D;else e:for(N=h;Zi!==null;){D=Zi;var V=D.sibling,ee=D.return;if(ZB(D),D===N){Zi=null;break e}if(V!==null){V.return=ee,Zi=V;break e}Zi=ee}}}var Wde={getCacheForType:function(h){var v=ws(fi),N=v.data.get(h);return N===void 0&&(N=h(),v.data.set(h,N)),N},cacheSignal:function(){return ws(fi).controller.signal}},Kde=typeof WeakMap=="function"?WeakMap:Map,Hr=0,ma=null,fr=null,Sr=0,Kr=0,ol=null,Cp=!1,Ib=!1,pM=!1,Vu=0,Za=0,Pp=0,Mf=0,hM=0,ll=0,Ob=0,Ov=null,Io=null,fM=!1,Z_=0,cH=0,J_=1/0,ek=null,Tp=null,Li=0,Ap=null,zb=null,Gu=0,gM=0,bM=null,dH=null,zv=0,xM=null;function cl(){return(Hr&2)!==0&&Sr!==0?Sr&-Sr:ne.T!==null?kM():ln()}function uH(){if(ll===0)if((Sr&536870912)===0||Cr){var h=Ce;Ce<<=1,(Ce&3932160)===0&&(Ce=262144),ll=h}else ll=536870912;return h=il.current,h!==null&&(h.flags|=32),ll}function Oo(h,v,N){(h===ma&&(Kr===2||Kr===9)||h.cancelPendingCommit!==null)&&(Ub(h,0),jp(h,Sr,ll,!1)),tt(h,N),((Hr&2)===0||h!==ma)&&(h===ma&&((Hr&2)===0&&(Mf|=N),Za===4&&jp(h,Sr,ll,!1)),Dd(h))}function mH(h,v,N){if((Hr&6)!==0)throw Error(a(327));var D=!N&&(v&127)===0&&(v&h.expiredLanes)===0||Ve(h,v),V=D?Xde(h,v):vM(h,v,!0),ee=D;do{if(V===0){Ib&&!D&&jp(h,v,0,!1);break}else{if(N=h.current.alternate,ee&&!Qde(N)){V=vM(h,v,!1),ee=!1;continue}if(V===2){if(ee=v,h.errorRecoveryDisabledLanes&ee)var Se=0;else Se=h.pendingLanes&-536870913,Se=Se!==0?Se:Se&536870912?536870912:0;if(Se!==0){v=Se;e:{var $e=h;V=Ov;var pt=$e.current.memoizedState.isDehydrated;if(pt&&(Ub($e,Se).flags|=256),Se=vM($e,Se,!1),Se!==2){if(pM&&!pt){$e.errorRecoveryDisabledLanes|=ee,Mf|=ee,V=4;break e}ee=Io,Io=V,ee!==null&&(Io===null?Io=ee:Io.push.apply(Io,ee))}V=Se}if(ee=!1,V!==2)continue}}if(V===1){Ub(h,0),jp(h,v,0,!0);break}e:{switch(D=h,ee=V,ee){case 0:case 1:throw Error(a(345));case 4:if((v&4194048)!==v)break;case 6:jp(D,v,ll,!Cp);break e;case 2:Io=null;break;case 3:case 5:break;default:throw Error(a(329))}if((v&62914560)===v&&(V=Z_+300-R(),10<V)){if(jp(D,v,ll,!Cp),ke(D,0,!0)!==0)break e;Gu=v,D.timeoutHandle=qH(pH.bind(null,D,N,Io,ek,fM,v,ll,Mf,Ob,Cp,ee,"Throttled",-0,0),V);break e}pH(D,N,Io,ek,fM,v,ll,Mf,Ob,Cp,ee,null,-0,0)}}break}while(!0);Dd(h)}function pH(h,v,N,D,V,ee,Se,$e,pt,Mt,Ht,Gt,Ft,Ot){if(h.timeoutHandle=-1,Gt=v.subtreeFlags,Gt&8192||(Gt&16785408)===16785408){Gt={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Kt},iH(v,ee,Gt);var vn=(ee&62914560)===ee?Z_-R():(ee&4194048)===ee?cH-R():0;if(vn=Due(Gt,vn),vn!==null){Gu=ee,h.cancelPendingCommit=vn(wH.bind(null,h,v,ee,N,D,V,Se,$e,pt,Ht,Gt,null,Ft,Ot)),jp(h,ee,Se,!Mt);return}}wH(h,v,ee,N,D,V,Se,$e,pt)}function Qde(h){for(var v=h;;){var N=v.tag;if((N===0||N===11||N===15)&&v.flags&16384&&(N=v.updateQueue,N!==null&&(N=N.stores,N!==null)))for(var D=0;D<N.length;D++){var V=N[D],ee=V.getSnapshot;V=V.value;try{if(!Na(ee(),V))return!1}catch{return!1}}if(N=v.child,v.subtreeFlags&16384&&N!==null)N.return=v,v=N;else{if(v===h)break;for(;v.sibling===null;){if(v.return===null||v.return===h)return!0;v=v.return}v.sibling.return=v.return,v=v.sibling}}return!0}function jp(h,v,N,D){v&=~hM,v&=~Mf,h.suspendedLanes|=v,h.pingedLanes&=~v,D&&(h.warmLanes|=v),D=h.expirationTimes;for(var V=v;0<V;){var ee=31-We(V),Se=1<<ee;D[ee]=-1,V&=~Se}N!==0&&Tt(h,N,v)}function tk(){return(Hr&6)===0?(Uv(0),!1):!0}function yM(){if(fr!==null){if(Kr===0)var h=fr.return;else h=fr,Lu=Sf=null,Lj(h),jb=null,Sv=0,h=fr;for(;h!==null;)$B(h.alternate,h),h=h.return;fr=null}}function Ub(h,v){var N=h.timeoutHandle;N!==-1&&(h.timeoutHandle=-1,fue(N)),N=h.cancelPendingCommit,N!==null&&(h.cancelPendingCommit=null,N()),Gu=0,yM(),ma=h,fr=N=Du(h.current,null),Sr=v,Kr=0,ol=null,Cp=!1,Ib=Ve(h,v),pM=!1,Ob=ll=hM=Mf=Pp=Za=0,Io=Ov=null,fM=!1,(v&8)!==0&&(v|=v&32);var D=h.entangledLanes;if(D!==0)for(h=h.entanglements,D&=v;0<D;){var V=31-We(D),ee=1<<V;v|=h[V],D&=~ee}return Vu=v,S_(),N}function hH(h,v){Xn=null,ne.H=jv,v===Ab||v===j_?(v=jU(),Kr=3):v===_j?(v=jU(),Kr=4):Kr=v===Xj?8:v!==null&&typeof v=="object"&&typeof v.then=="function"?6:1,ol=v,fr===null&&(Za=1,$_(h,zl(v,h.current)))}function fH(){var h=il.current;return h===null?!0:(Sr&4194048)===Sr?ql===null:(Sr&62914560)===Sr||(Sr&536870912)!==0?h===ql:!1}function gH(){var h=ne.H;return ne.H=jv,h===null?jv:h}function bH(){var h=ne.A;return ne.A=Wde,h}function nk(){Za=4,Cp||(Sr&4194048)!==Sr&&il.current!==null||(Ib=!0),(Pp&134217727)===0&&(Mf&134217727)===0||ma===null||jp(ma,Sr,ll,!1)}function vM(h,v,N){var D=Hr;Hr|=2;var V=gH(),ee=bH();(ma!==h||Sr!==v)&&(ek=null,Ub(h,v)),v=!1;var Se=Za;e:do try{if(Kr!==0&&fr!==null){var $e=fr,pt=ol;switch(Kr){case 8:yM(),Se=6;break e;case 3:case 2:case 9:case 6:il.current===null&&(v=!0);var Mt=Kr;if(Kr=0,ol=null,Bb(h,$e,pt,Mt),N&&Ib){Se=0;break e}break;default:Mt=Kr,Kr=0,ol=null,Bb(h,$e,pt,Mt)}}Yde(),Se=Za;break}catch(Ht){hH(h,Ht)}while(!0);return v&&h.shellSuspendCounter++,Lu=Sf=null,Hr=D,ne.H=V,ne.A=ee,fr===null&&(ma=null,Sr=0,S_()),Se}function Yde(){for(;fr!==null;)xH(fr)}function Xde(h,v){var N=Hr;Hr|=2;var D=gH(),V=bH();ma!==h||Sr!==v?(ek=null,J_=R()+500,Ub(h,v)):Ib=Ve(h,v);e:do try{if(Kr!==0&&fr!==null){v=fr;var ee=ol;t:switch(Kr){case 1:Kr=0,ol=null,Bb(h,v,ee,1);break;case 2:case 9:if(TU(ee)){Kr=0,ol=null,yH(v);break}v=function(){Kr!==2&&Kr!==9||ma!==h||(Kr=7),Dd(h)},ee.then(v,v);break e;case 3:Kr=7;break e;case 4:Kr=5;break e;case 7:TU(ee)?(Kr=0,ol=null,yH(v)):(Kr=0,ol=null,Bb(h,v,ee,7));break;case 5:var Se=null;switch(fr.tag){case 26:Se=fr.memoizedState;case 5:case 27:var $e=fr;if(Se?a8(Se):$e.stateNode.complete){Kr=0,ol=null;var pt=$e.sibling;if(pt!==null)fr=pt;else{var Mt=$e.return;Mt!==null?(fr=Mt,rk(Mt)):fr=null}break t}}Kr=0,ol=null,Bb(h,v,ee,5);break;case 6:Kr=0,ol=null,Bb(h,v,ee,6);break;case 8:yM(),Za=6;break e;default:throw Error(a(462))}}Zde();break}catch(Ht){hH(h,Ht)}while(!0);return Lu=Sf=null,ne.H=D,ne.A=V,Hr=N,fr!==null?0:(ma=null,Sr=0,S_(),Za)}function Zde(){for(;fr!==null&&!me();)xH(fr)}function xH(h){var v=HB(h.alternate,h,Vu);h.memoizedProps=h.pendingProps,v===null?rk(h):fr=v}function yH(h){var v=h,N=v.alternate;switch(v.tag){case 15:case 0:v=RB(N,v,v.pendingProps,v.type,void 0,Sr);break;case 11:v=RB(N,v,v.pendingProps,v.type.render,v.ref,Sr);break;case 5:Lj(v);default:$B(N,v),v=fr=bU(v,Vu),v=HB(N,v,Vu)}h.memoizedProps=h.pendingProps,v===null?rk(h):fr=v}function Bb(h,v,N,D){Lu=Sf=null,Lj(v),jb=null,Sv=0;var V=v.return;try{if(Ude(h,V,v,N,Sr)){Za=1,$_(h,zl(N,h.current)),fr=null;return}}catch(ee){if(V!==null)throw fr=V,ee;Za=1,$_(h,zl(N,h.current)),fr=null;return}v.flags&32768?(Cr||D===1?h=!0:Ib||(Sr&536870912)!==0?h=!1:(Cp=h=!0,(D===2||D===9||D===3||D===6)&&(D=il.current,D!==null&&D.tag===13&&(D.flags|=16384))),vH(v,h)):rk(v)}function rk(h){var v=h;do{if((v.flags&32768)!==0){vH(v,Cp);return}h=v.return;var N=qde(v.alternate,v,Vu);if(N!==null){fr=N;return}if(v=v.sibling,v!==null){fr=v;return}fr=v=h}while(v!==null);Za===0&&(Za=5)}function vH(h,v){do{var N=$de(h.alternate,h);if(N!==null){N.flags&=32767,fr=N;return}if(N=h.return,N!==null&&(N.flags|=32768,N.subtreeFlags=0,N.deletions=null),!v&&(h=h.sibling,h!==null)){fr=h;return}fr=h=N}while(h!==null);Za=6,fr=null}function wH(h,v,N,D,V,ee,Se,$e,pt){h.cancelPendingCommit=null;do ak();while(Li!==0);if((Hr&6)!==0)throw Error(a(327));if(v!==null){if(v===h.current)throw Error(a(177));if(ee=v.lanes|v.childLanes,ee|=lj,ot(h,N,ee,Se,$e,pt),h===ma&&(fr=ma=null,Sr=0),zb=v,Ap=h,Gu=N,gM=ee,bM=V,dH=D,(v.subtreeFlags&10256)!==0||(v.flags&10256)!==0?(h.callbackNode=null,h.callbackPriority=0,nue(_e,function(){return CH(),null})):(h.callbackNode=null,h.callbackPriority=0),D=(v.flags&13878)!==0,(v.subtreeFlags&13878)!==0||D){D=ne.T,ne.T=null,V=Y.p,Y.p=2,Se=Hr,Hr|=4;try{Vde(h,v,N)}finally{Hr=Se,Y.p=V,ne.T=D}}Li=1,SH(),_H(),kH()}}function SH(){if(Li===1){Li=0;var h=Ap,v=zb,N=(v.flags&13878)!==0;if((v.subtreeFlags&13878)!==0||N){N=ne.T,ne.T=null;var D=Y.p;Y.p=2;var V=Hr;Hr|=4;try{nH(v,h);var ee=EM,Se=Hc(h.containerInfo),$e=ee.focusedElem,pt=ee.selectionRange;if(Se!==$e&&$e&&$e.ownerDocument&&Fi($e.ownerDocument.documentElement,$e)){if(pt!==null&&Xi($e)){var Mt=pt.start,Ht=pt.end;if(Ht===void 0&&(Ht=Mt),"selectionStart"in $e)$e.selectionStart=Mt,$e.selectionEnd=Math.min(Ht,$e.value.length);else{var Gt=$e.ownerDocument||document,Ft=Gt&&Gt.defaultView||window;if(Ft.getSelection){var Ot=Ft.getSelection(),vn=$e.textContent.length,Bn=Math.min(pt.start,vn),na=pt.end===void 0?Bn:Math.min(pt.end,vn);!Ot.extend&&Bn>na&&(Se=na,na=Bn,Bn=Se);var St=uo($e,Bn),xt=uo($e,na);if(St&&xt&&(Ot.rangeCount!==1||Ot.anchorNode!==St.node||Ot.anchorOffset!==St.offset||Ot.focusNode!==xt.node||Ot.focusOffset!==xt.offset)){var jt=Gt.createRange();jt.setStart(St.node,St.offset),Ot.removeAllRanges(),Bn>na?(Ot.addRange(jt),Ot.extend(xt.node,xt.offset)):(jt.setEnd(xt.node,xt.offset),Ot.addRange(jt))}}}}for(Gt=[],Ot=$e;Ot=Ot.parentNode;)Ot.nodeType===1&&Gt.push({element:Ot,left:Ot.scrollLeft,top:Ot.scrollTop});for(typeof $e.focus=="function"&&$e.focus(),$e=0;$e<Gt.length;$e++){var $t=Gt[$e];$t.element.scrollLeft=$t.left,$t.element.scrollTop=$t.top}}gk=!!MM,EM=MM=null}finally{Hr=V,Y.p=D,ne.T=N}}h.current=v,Li=2}}function _H(){if(Li===2){Li=0;var h=Ap,v=zb,N=(v.flags&8772)!==0;if((v.subtreeFlags&8772)!==0||N){N=ne.T,ne.T=null;var D=Y.p;Y.p=2;var V=Hr;Hr|=4;try{XB(h,v.alternate,v)}finally{Hr=V,Y.p=D,ne.T=N}}Li=3}}function kH(){if(Li===4||Li===3){Li=0,q();var h=Ap,v=zb,N=Gu,D=dH;(v.subtreeFlags&10256)!==0||(v.flags&10256)!==0?Li=5:(Li=0,zb=Ap=null,NH(h,h.pendingLanes));var V=h.pendingLanes;if(V===0&&(Tp=null),Zt(N),v=v.stateNode,Oe&&typeof Oe.onCommitFiberRoot=="function")try{Oe.onCommitFiberRoot(Fe,v,void 0,(v.current.flags&128)===128)}catch{}if(D!==null){v=ne.T,V=Y.p,Y.p=2,ne.T=null;try{for(var ee=h.onRecoverableError,Se=0;Se<D.length;Se++){var $e=D[Se];ee($e.value,{componentStack:$e.stack})}}finally{ne.T=v,Y.p=V}}(Gu&3)!==0&&ak(),Dd(h),V=h.pendingLanes,(N&261930)!==0&&(V&42)!==0?h===xM?zv++:(zv=0,xM=h):zv=0,Uv(0)}}function NH(h,v){(h.pooledCacheLanes&=v)===0&&(v=h.pooledCache,v!=null&&(h.pooledCache=null,vv(v)))}function ak(){return SH(),_H(),kH(),CH()}function CH(){if(Li!==5)return!1;var h=Ap,v=gM;gM=0;var N=Zt(Gu),D=ne.T,V=Y.p;try{Y.p=32>N?32:N,ne.T=null,N=bM,bM=null;var ee=Ap,Se=Gu;if(Li=0,zb=Ap=null,Gu=0,(Hr&6)!==0)throw Error(a(331));var $e=Hr;if(Hr|=4,oH(ee.current),aH(ee,ee.current,Se,N),Hr=$e,Uv(0,!1),Oe&&typeof Oe.onPostCommitFiberRoot=="function")try{Oe.onPostCommitFiberRoot(Fe,ee)}catch{}return!0}finally{Y.p=V,ne.T=D,NH(h,v)}}function PH(h,v,N){v=zl(N,v),v=Yj(h.stateNode,v,2),h=Sp(h,v,2),h!==null&&(tt(h,2),Dd(h))}function Qr(h,v,N){if(h.tag===3)PH(h,h,N);else for(;v!==null;){if(v.tag===3){PH(v,h,N);break}else if(v.tag===1){var D=v.stateNode;if(typeof v.type.getDerivedStateFromError=="function"||typeof D.componentDidCatch=="function"&&(Tp===null||!Tp.has(D))){h=zl(N,h),N=TB(2),D=Sp(v,N,2),D!==null&&(AB(N,D,v,h),tt(D,2),Dd(D));break}}v=v.return}}function wM(h,v,N){var D=h.pingCache;if(D===null){D=h.pingCache=new Kde;var V=new Set;D.set(v,V)}else V=D.get(v),V===void 0&&(V=new Set,D.set(v,V));V.has(N)||(pM=!0,V.add(N),h=Jde.bind(null,h,v,N),v.then(h,h))}function Jde(h,v,N){var D=h.pingCache;D!==null&&D.delete(v),h.pingedLanes|=h.suspendedLanes&N,h.warmLanes&=~N,ma===h&&(Sr&N)===N&&(Za===4||Za===3&&(Sr&62914560)===Sr&&300>R()-Z_?(Hr&2)===0&&Ub(h,0):hM|=N,Ob===Sr&&(Ob=0)),Dd(h)}function TH(h,v){v===0&&(v=Qe()),h=yf(h,v),h!==null&&(tt(h,v),Dd(h))}function eue(h){var v=h.memoizedState,N=0;v!==null&&(N=v.retryLane),TH(h,N)}function tue(h,v){var N=0;switch(h.tag){case 31:case 13:var D=h.stateNode,V=h.memoizedState;V!==null&&(N=V.retryLane);break;case 19:D=h.stateNode;break;case 22:D=h.stateNode._retryCache;break;default:throw Error(a(314))}D!==null&&D.delete(v),TH(h,N)}function nue(h,v){return fe(h,v)}var ik=null,Hb=null,SM=!1,sk=!1,_M=!1,Mp=0;function Dd(h){h!==Hb&&h.next===null&&(Hb===null?ik=Hb=h:Hb=Hb.next=h),sk=!0,SM||(SM=!0,aue())}function Uv(h,v){if(!_M&&sk){_M=!0;do for(var N=!1,D=ik;D!==null;){if(h!==0){var V=D.pendingLanes;if(V===0)var ee=0;else{var Se=D.suspendedLanes,$e=D.pingedLanes;ee=(1<<31-We(42|h)+1)-1,ee&=V&~(Se&~$e),ee=ee&201326741?ee&201326741|1:ee?ee|2:0}ee!==0&&(N=!0,EH(D,ee))}else ee=Sr,ee=ke(D,D===ma?ee:0,D.cancelPendingCommit!==null||D.timeoutHandle!==-1),(ee&3)===0||Ve(D,ee)||(N=!0,EH(D,ee));D=D.next}while(N);_M=!1}}function rue(){AH()}function AH(){sk=SM=!1;var h=0;Mp!==0&&hue()&&(h=Mp);for(var v=R(),N=null,D=ik;D!==null;){var V=D.next,ee=jH(D,v);ee===0?(D.next=null,N===null?ik=V:N.next=V,V===null&&(Hb=N)):(N=D,(h!==0||(ee&3)!==0)&&(sk=!0)),D=V}Li!==0&&Li!==5||Uv(h),Mp!==0&&(Mp=0)}function jH(h,v){for(var N=h.suspendedLanes,D=h.pingedLanes,V=h.expirationTimes,ee=h.pendingLanes&-62914561;0<ee;){var Se=31-We(ee),$e=1<<Se,pt=V[Se];pt===-1?(($e&N)===0||($e&D)!==0)&&(V[Se]=rt($e,v)):pt<=v&&(h.expiredLanes|=$e),ee&=~$e}if(v=ma,N=Sr,N=ke(h,h===v?N:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),D=h.callbackNode,N===0||h===v&&(Kr===2||Kr===9)||h.cancelPendingCommit!==null)return D!==null&&D!==null&&de(D),h.callbackNode=null,h.callbackPriority=0;if((N&3)===0||Ve(h,N)){if(v=N&-N,v===h.callbackPriority)return v;switch(D!==null&&de(D),Zt(N)){case 2:case 8:N=ye;break;case 32:N=_e;break;case 268435456:N=ge;break;default:N=_e}return D=MH.bind(null,h),N=fe(N,D),h.callbackPriority=v,h.callbackNode=N,v}return D!==null&&D!==null&&de(D),h.callbackPriority=2,h.callbackNode=null,2}function MH(h,v){if(Li!==0&&Li!==5)return h.callbackNode=null,h.callbackPriority=0,null;var N=h.callbackNode;if(ak()&&h.callbackNode!==N)return null;var D=Sr;return D=ke(h,h===ma?D:0,h.cancelPendingCommit!==null||h.timeoutHandle!==-1),D===0?null:(mH(h,D,v),jH(h,R()),h.callbackNode!=null&&h.callbackNode===N?MH.bind(null,h):null)}function EH(h,v){if(ak())return null;mH(h,v,!0)}function aue(){gue(function(){(Hr&6)!==0?fe(be,rue):AH()})}function kM(){if(Mp===0){var h=Pb;h===0&&(h=it,it<<=1,(it&261888)===0&&(it=256)),Mp=h}return Mp}function DH(h){return h==null||typeof h=="symbol"||typeof h=="boolean"?null:typeof h=="function"?h:ur(""+h)}function FH(h,v){var N=v.ownerDocument.createElement("input");return N.name=v.name,N.value=v.value,h.id&&N.setAttribute("form",h.id),v.parentNode.insertBefore(N,v),h=new FormData(h),N.parentNode.removeChild(N),h}function iue(h,v,N,D,V){if(v==="submit"&&N&&N.stateNode===V){var ee=DH((V[Nt]||null).action),Se=D.submitter;Se&&(v=(v=Se[Nt]||null)?DH(v.formAction):Se.getAttribute("formAction"),v!==null&&(ee=v,Se=null));var $e=new Eo("action","action",null,D,V);h.push({event:$e,listeners:[{instance:null,listener:function(){if(D.defaultPrevented){if(Mp!==0){var pt=Se?FH(V,Se):new FormData(V);$j(N,{pending:!0,data:pt,method:V.method,action:ee},null,pt)}}else typeof ee=="function"&&($e.preventDefault(),pt=Se?FH(V,Se):new FormData(V),$j(N,{pending:!0,data:pt,method:V.method,action:ee},ee,pt))},currentTarget:V}]})}}for(var NM=0;NM<oj.length;NM++){var CM=oj[NM],sue=CM.toLowerCase(),oue=CM[0].toUpperCase()+CM.slice(1);Vc(sue,"on"+oue)}Vc(uU,"onAnimationEnd"),Vc(mU,"onAnimationIteration"),Vc(pU,"onAnimationStart"),Vc("dblclick","onDoubleClick"),Vc("focusin","onFocus"),Vc("focusout","onBlur"),Vc(_de,"onTransitionRun"),Vc(kde,"onTransitionStart"),Vc(Nde,"onTransitionCancel"),Vc(hU,"onTransitionEnd"),Ue("onMouseEnter",["mouseout","mouseover"]),Ue("onMouseLeave",["mouseout","mouseover"]),Ue("onPointerEnter",["pointerout","pointerover"]),Ue("onPointerLeave",["pointerout","pointerover"]),wt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),wt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),wt("onBeforeInput",["compositionend","keypress","textInput","paste"]),wt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),wt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),wt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Bv="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(" "),lue=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Bv));function LH(h,v){v=(v&4)!==0;for(var N=0;N<h.length;N++){var D=h[N],V=D.event;D=D.listeners;e:{var ee=void 0;if(v)for(var Se=D.length-1;0<=Se;Se--){var $e=D[Se],pt=$e.instance,Mt=$e.currentTarget;if($e=$e.listener,pt!==ee&&V.isPropagationStopped())break e;ee=$e,V.currentTarget=Mt;try{ee(V)}catch(Ht){w_(Ht)}V.currentTarget=null,ee=pt}else for(Se=0;Se<D.length;Se++){if($e=D[Se],pt=$e.instance,Mt=$e.currentTarget,$e=$e.listener,pt!==ee&&V.isPropagationStopped())break e;ee=$e,V.currentTarget=Mt;try{ee(V)}catch(Ht){w_(Ht)}V.currentTarget=null,ee=pt}}}}function gr(h,v){var N=v[Ct];N===void 0&&(N=v[Ct]=new Set);var D=h+"__bubble";N.has(D)||(RH(v,h,2,!1),N.add(D))}function PM(h,v,N){var D=0;v&&(D|=4),RH(N,h,D,v)}var ok="_reactListening"+Math.random().toString(36).slice(2);function TM(h){if(!h[ok]){h[ok]=!0,et.forEach(function(N){N!=="selectionchange"&&(lue.has(N)||PM(N,!1,h),PM(N,!0,h))});var v=h.nodeType===9?h:h.ownerDocument;v===null||v[ok]||(v[ok]=!0,PM("selectionchange",!1,v))}}function RH(h,v,N,D){switch(u8(v)){case 2:var V=Rue;break;case 8:V=Iue;break;default:V=qM}N=V.bind(null,v,N,h),V=void 0,!Us||v!=="touchstart"&&v!=="touchmove"&&v!=="wheel"||(V=!0),D?V!==void 0?h.addEventListener(v,N,{capture:!0,passive:V}):h.addEventListener(v,N,!0):V!==void 0?h.addEventListener(v,N,{passive:V}):h.addEventListener(v,N,!1)}function AM(h,v,N,D,V){var ee=D;if((v&1)===0&&(v&2)===0&&D!==null)e:for(;;){if(D===null)return;var Se=D.tag;if(Se===3||Se===4){var $e=D.stateNode.containerInfo;if($e===V)break;if(Se===4)for(Se=D.return;Se!==null;){var pt=Se.tag;if((pt===3||pt===4)&&Se.stateNode.containerInfo===V)return;Se=Se.return}for(;$e!==null;){if(Se=mt($e),Se===null)return;if(pt=Se.tag,pt===5||pt===6||pt===26||pt===27){D=ee=Se;continue e}$e=$e.parentNode}}D=D.return}kr(function(){var Mt=ee,Ht=Dc(N),Gt=[];e:{var Ft=fU.get(h);if(Ft!==void 0){var Ot=Eo,vn=h;switch(h){case"keypress":if(nl(N)===0)break e;case"keydown":case"keyup":Ot=Pd;break;case"focusin":vn="focus",Ot=Oc;break;case"focusout":vn="blur",Ot=Oc;break;case"beforeblur":case"afterblur":Ot=Oc;break;case"click":if(N.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Ot=hb;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Ot=gb;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Ot=bb;break;case uU:case mU:case pU:Ot=Ml;break;case hU:Ot=gf;break;case"scroll":case"scrollend":Ot=_d;break;case"wheel":Ot=xb;break;case"copy":case"cut":case"paste":Ot=zc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Ot=Ad;break;case"toggle":case"beforetoggle":Ot=Bc}var Bn=(v&4)!==0,na=!Bn&&(h==="scroll"||h==="scrollend"),St=Bn?Ft!==null?Ft+"Capture":null:Ft;Bn=[];for(var xt=Mt,jt;xt!==null;){var $t=xt;if(jt=$t.stateNode,$t=$t.tag,$t!==5&&$t!==26&&$t!==27||jt===null||St===null||($t=Sd(xt,St),$t!=null&&Bn.push(Hv(xt,$t,jt))),na)break;xt=xt.return}0<Bn.length&&(Ft=new Ot(Ft,vn,null,N,Ht),Gt.push({event:Ft,listeners:Bn}))}}if((v&7)===0){e:{if(Ft=h==="mouseover"||h==="pointerover",Ot=h==="mouseout"||h==="pointerout",Ft&&N!==Ec&&(vn=N.relatedTarget||N.fromElement)&&(mt(vn)||vn[ut]))break e;if((Ot||Ft)&&(Ft=Ht.window===Ht?Ht:(Ft=Ht.ownerDocument)?Ft.defaultView||Ft.parentWindow:window,Ot?(vn=N.relatedTarget||N.toElement,Ot=Mt,vn=vn?mt(vn):null,vn!==null&&(na=s(vn),Bn=vn.tag,vn!==na||Bn!==5&&Bn!==27&&Bn!==6)&&(vn=null)):(Ot=null,vn=Mt),Ot!==vn)){if(Bn=hb,$t="onMouseLeave",St="onMouseEnter",xt="mouse",(h==="pointerout"||h==="pointerover")&&(Bn=Ad,$t="onPointerLeave",St="onPointerEnter",xt="pointer"),na=Ot==null?Ft:Ye(Ot),jt=vn==null?Ft:Ye(vn),Ft=new Bn($t,xt+"leave",Ot,N,Ht),Ft.target=na,Ft.relatedTarget=jt,$t=null,mt(Ht)===Mt&&(Bn=new Bn(St,xt+"enter",vn,N,Ht),Bn.target=jt,Bn.relatedTarget=na,$t=Bn),na=$t,Ot&&vn)t:{for(Bn=cue,St=Ot,xt=vn,jt=0,$t=St;$t;$t=Bn($t))jt++;$t=0;for(var Fn=xt;Fn;Fn=Bn(Fn))$t++;for(;0<jt-$t;)St=Bn(St),jt--;for(;0<$t-jt;)xt=Bn(xt),$t--;for(;jt--;){if(St===xt||xt!==null&&St===xt.alternate){Bn=St;break t}St=Bn(St),xt=Bn(xt)}Bn=null}else Bn=null;Ot!==null&&IH(Gt,Ft,Ot,Bn,!1),vn!==null&&na!==null&&IH(Gt,na,vn,Bn,!0)}}e:{if(Ft=Mt?Ye(Mt):window,Ot=Ft.nodeName&&Ft.nodeName.toLowerCase(),Ot==="select"||Ot==="input"&&Ft.type==="file")var Rr=an;else if(ht(Ft))if(Tn)Rr=Il;else{Rr=Wr;var Pn=Mu}else Ot=Ft.nodeName,!Ot||Ot.toLowerCase()!=="input"||Ft.type!=="checkbox"&&Ft.type!=="radio"?Mt&&zs(Mt.elementType)&&(Rr=an):Rr=Qa;if(Rr&&(Rr=Rr(h,Mt))){In(Gt,Rr,N,Ht);break e}Pn&&Pn(h,Ft,Mt),h==="focusout"&&Mt&&Ft.type==="number"&&Mt.memoizedProps.value!=null&&vr(Ft,"number",Ft.value)}switch(Pn=Mt?Ye(Mt):window,h){case"focusin":(ht(Pn)||Pn.contentEditable==="true")&&(Mr=Pn,Ya=Mt,qc=null);break;case"focusout":qc=Ya=Mr=null;break;case"mousedown":pn=!0;break;case"contextmenu":case"mouseup":case"dragend":pn=!1,xf(Gt,N,Ht);break;case"selectionchange":if(wr)break;case"keydown":case"keyup":xf(Gt,N,Ht)}var Jn;if(Yi)e:{switch(h){case"compositionstart":var _r="onCompositionStart";break e;case"compositionend":_r="onCompositionEnd";break e;case"compositionupdate":_r="onCompositionUpdate";break e}_r=void 0}else zn?mn(h,N)&&(_r="onCompositionEnd"):h==="keydown"&&N.keyCode===229&&(_r="onCompositionStart");_r&&(yb&&N.locale!=="ko"&&(zn||_r!=="onCompositionStart"?_r==="onCompositionEnd"&&zn&&(Jn=hi()):(Ma=Ht,dp="value"in Ma?Ma.value:Ma.textContent,zn=!0)),Pn=lk(Mt,_r),0<Pn.length&&(_r=new Qi(_r,h,null,N,Ht),Gt.push({event:_r,listeners:Pn}),Jn?_r.data=Jn:(Jn=An(N),Jn!==null&&(_r.data=Jn)))),(Jn=bf?dt(h,N):qt(h,N))&&(_r=lk(Mt,"onBeforeInput"),0<_r.length&&(Pn=new Qi("onBeforeInput","beforeinput",null,N,Ht),Gt.push({event:Pn,listeners:_r}),Pn.data=Jn)),iue(Gt,h,Mt,N,Ht)}LH(Gt,v)})}function Hv(h,v,N){return{instance:h,listener:v,currentTarget:N}}function lk(h,v){for(var N=v+"Capture",D=[];h!==null;){var V=h,ee=V.stateNode;if(V=V.tag,V!==5&&V!==26&&V!==27||ee===null||(V=Sd(h,N),V!=null&&D.unshift(Hv(h,V,ee)),V=Sd(h,v),V!=null&&D.push(Hv(h,V,ee))),h.tag===3)return D;h=h.return}return[]}function cue(h){if(h===null)return null;do h=h.return;while(h&&h.tag!==5&&h.tag!==27);return h||null}function IH(h,v,N,D,V){for(var ee=v._reactName,Se=[];N!==null&&N!==D;){var $e=N,pt=$e.alternate,Mt=$e.stateNode;if($e=$e.tag,pt!==null&&pt===D)break;$e!==5&&$e!==26&&$e!==27||Mt===null||(pt=Mt,V?(Mt=Sd(N,ee),Mt!=null&&Se.unshift(Hv(N,Mt,pt))):V||(Mt=Sd(N,ee),Mt!=null&&Se.push(Hv(N,Mt,pt)))),N=N.return}Se.length!==0&&h.push({event:v,listeners:Se})}var due=/\r\n?/g,uue=/\u0000|\uFFFD/g;function OH(h){return(typeof h=="string"?h:""+h).replace(due,`
  9. `).replace(uue,"")}function zH(h,v){return v=OH(v),OH(h)===v}function ta(h,v,N,D,V,ee){switch(N){case"children":typeof D=="string"?v==="body"||v==="textarea"&&D===""||Mi(h,D):(typeof D=="number"||typeof D=="bigint")&&v!=="body"&&Mi(h,""+D);break;case"className":Bt(h,"class",D);break;case"tabIndex":Bt(h,"tabindex",D);break;case"dir":case"role":case"viewBox":case"width":case"height":Bt(h,N,D);break;case"style":Mc(h,D,ee);break;case"data":if(v!=="object"){Bt(h,"data",D);break}case"src":case"href":if(D===""&&(v!=="a"||N!=="href")){h.removeAttribute(N);break}if(D==null||typeof D=="function"||typeof D=="symbol"||typeof D=="boolean"){h.removeAttribute(N);break}D=ur(""+D),h.setAttribute(N,D);break;case"action":case"formAction":if(typeof D=="function"){h.setAttribute(N,"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 ee=="function"&&(N==="formAction"?(v!=="input"&&ta(h,v,"name",V.name,V,null),ta(h,v,"formEncType",V.formEncType,V,null),ta(h,v,"formMethod",V.formMethod,V,null),ta(h,v,"formTarget",V.formTarget,V,null)):(ta(h,v,"encType",V.encType,V,null),ta(h,v,"method",V.method,V,null),ta(h,v,"target",V.target,V,null)));if(D==null||typeof D=="symbol"||typeof D=="boolean"){h.removeAttribute(N);break}D=ur(""+D),h.setAttribute(N,D);break;case"onClick":D!=null&&(h.onclick=Kt);break;case"onScroll":D!=null&&gr("scroll",h);break;case"onScrollEnd":D!=null&&gr("scrollend",h);break;case"dangerouslySetInnerHTML":if(D!=null){if(typeof D!="object"||!("__html"in D))throw Error(a(61));if(N=D.__html,N!=null){if(V.children!=null)throw Error(a(60));h.innerHTML=N}}break;case"multiple":h.multiple=D&&typeof D!="function"&&typeof D!="symbol";break;case"muted":h.muted=D&&typeof D!="function"&&typeof D!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(D==null||typeof D=="function"||typeof D=="boolean"||typeof D=="symbol"){h.removeAttribute("xlink:href");break}N=ur(""+D),h.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",N);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":D!=null&&typeof D!="function"&&typeof D!="symbol"?h.setAttribute(N,""+D):h.removeAttribute(N);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":D&&typeof D!="function"&&typeof D!="symbol"?h.setAttribute(N,""):h.removeAttribute(N);break;case"capture":case"download":D===!0?h.setAttribute(N,""):D!==!1&&D!=null&&typeof D!="function"&&typeof D!="symbol"?h.setAttribute(N,D):h.removeAttribute(N);break;case"cols":case"rows":case"size":case"span":D!=null&&typeof D!="function"&&typeof D!="symbol"&&!isNaN(D)&&1<=D?h.setAttribute(N,D):h.removeAttribute(N);break;case"rowSpan":case"start":D==null||typeof D=="function"||typeof D=="symbol"||isNaN(D)?h.removeAttribute(N):h.setAttribute(N,D);break;case"popover":gr("beforetoggle",h),gr("toggle",h),Ke(h,"popover",D);break;case"xlinkActuate":Qt(h,"http://www.w3.org/1999/xlink","xlink:actuate",D);break;case"xlinkArcrole":Qt(h,"http://www.w3.org/1999/xlink","xlink:arcrole",D);break;case"xlinkRole":Qt(h,"http://www.w3.org/1999/xlink","xlink:role",D);break;case"xlinkShow":Qt(h,"http://www.w3.org/1999/xlink","xlink:show",D);break;case"xlinkTitle":Qt(h,"http://www.w3.org/1999/xlink","xlink:title",D);break;case"xlinkType":Qt(h,"http://www.w3.org/1999/xlink","xlink:type",D);break;case"xmlBase":Qt(h,"http://www.w3.org/XML/1998/namespace","xml:base",D);break;case"xmlLang":Qt(h,"http://www.w3.org/XML/1998/namespace","xml:lang",D);break;case"xmlSpace":Qt(h,"http://www.w3.org/XML/1998/namespace","xml:space",D);break;case"is":Ke(h,"is",D);break;case"innerText":case"textContent":break;default:(!(2<N.length)||N[0]!=="o"&&N[0]!=="O"||N[1]!=="n"&&N[1]!=="N")&&(N=It.get(N)||N,Ke(h,N,D))}}function jM(h,v,N,D,V,ee){switch(N){case"style":Mc(h,D,ee);break;case"dangerouslySetInnerHTML":if(D!=null){if(typeof D!="object"||!("__html"in D))throw Error(a(61));if(N=D.__html,N!=null){if(V.children!=null)throw Error(a(60));h.innerHTML=N}}break;case"children":typeof D=="string"?Mi(h,D):(typeof D=="number"||typeof D=="bigint")&&Mi(h,""+D);break;case"onScroll":D!=null&&gr("scroll",h);break;case"onScrollEnd":D!=null&&gr("scrollend",h);break;case"onClick":D!=null&&(h.onclick=Kt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!vt.hasOwnProperty(N))e:{if(N[0]==="o"&&N[1]==="n"&&(V=N.endsWith("Capture"),v=N.slice(2,V?N.length-7:void 0),ee=h[Nt]||null,ee=ee!=null?ee[N]:null,typeof ee=="function"&&h.removeEventListener(v,ee,V),typeof D=="function")){typeof ee!="function"&&ee!==null&&(N in h?h[N]=null:h.hasAttribute(N)&&h.removeAttribute(N)),h.addEventListener(v,D,V);break e}N in h?h[N]=D:D===!0?h.setAttribute(N,""):Ke(h,N,D)}}}function _s(h,v,N){switch(v){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":gr("error",h),gr("load",h);var D=!1,V=!1,ee;for(ee in N)if(N.hasOwnProperty(ee)){var Se=N[ee];if(Se!=null)switch(ee){case"src":D=!0;break;case"srcSet":V=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(a(137,v));default:ta(h,v,ee,Se,N,null)}}V&&ta(h,v,"srcSet",N.srcSet,N,null),D&&ta(h,v,"src",N.src,N,null);return;case"input":gr("invalid",h);var $e=ee=Se=V=null,pt=null,Mt=null;for(D in N)if(N.hasOwnProperty(D)){var Ht=N[D];if(Ht!=null)switch(D){case"name":V=Ht;break;case"type":Se=Ht;break;case"checked":pt=Ht;break;case"defaultChecked":Mt=Ht;break;case"value":ee=Ht;break;case"defaultValue":$e=Ht;break;case"children":case"dangerouslySetInnerHTML":if(Ht!=null)throw Error(a(137,v));break;default:ta(h,v,D,Ht,N,null)}}Un(h,ee,$e,pt,Mt,Se,V,!1);return;case"select":gr("invalid",h),D=Se=ee=null;for(V in N)if(N.hasOwnProperty(V)&&($e=N[V],$e!=null))switch(V){case"value":ee=$e;break;case"defaultValue":Se=$e;break;case"multiple":D=$e;default:ta(h,v,V,$e,N,null)}v=ee,N=Se,h.multiple=!!D,v!=null?ua(h,!!D,v,!1):N!=null&&ua(h,!!D,N,!0);return;case"textarea":gr("invalid",h),ee=V=D=null;for(Se in N)if(N.hasOwnProperty(Se)&&($e=N[Se],$e!=null))switch(Se){case"value":D=$e;break;case"defaultValue":V=$e;break;case"children":ee=$e;break;case"dangerouslySetInnerHTML":if($e!=null)throw Error(a(91));break;default:ta(h,v,Se,$e,N,null)}ba(h,D,V,ee);return;case"option":for(pt in N)N.hasOwnProperty(pt)&&(D=N[pt],D!=null)&&(pt==="selected"?h.selected=D&&typeof D!="function"&&typeof D!="symbol":ta(h,v,pt,D,N,null));return;case"dialog":gr("beforetoggle",h),gr("toggle",h),gr("cancel",h),gr("close",h);break;case"iframe":case"object":gr("load",h);break;case"video":case"audio":for(D=0;D<Bv.length;D++)gr(Bv[D],h);break;case"image":gr("error",h),gr("load",h);break;case"details":gr("toggle",h);break;case"embed":case"source":case"link":gr("error",h),gr("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(Mt in N)if(N.hasOwnProperty(Mt)&&(D=N[Mt],D!=null))switch(Mt){case"children":case"dangerouslySetInnerHTML":throw Error(a(137,v));default:ta(h,v,Mt,D,N,null)}return;default:if(zs(v)){for(Ht in N)N.hasOwnProperty(Ht)&&(D=N[Ht],D!==void 0&&jM(h,v,Ht,D,N,void 0));return}}for($e in N)N.hasOwnProperty($e)&&(D=N[$e],D!=null&&ta(h,v,$e,D,N,null))}function mue(h,v,N,D){switch(v){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var V=null,ee=null,Se=null,$e=null,pt=null,Mt=null,Ht=null;for(Ot in N){var Gt=N[Ot];if(N.hasOwnProperty(Ot)&&Gt!=null)switch(Ot){case"checked":break;case"value":break;case"defaultValue":pt=Gt;default:D.hasOwnProperty(Ot)||ta(h,v,Ot,null,D,Gt)}}for(var Ft in D){var Ot=D[Ft];if(Gt=N[Ft],D.hasOwnProperty(Ft)&&(Ot!=null||Gt!=null))switch(Ft){case"type":ee=Ot;break;case"name":V=Ot;break;case"checked":Mt=Ot;break;case"defaultChecked":Ht=Ot;break;case"value":Se=Ot;break;case"defaultValue":$e=Ot;break;case"children":case"dangerouslySetInnerHTML":if(Ot!=null)throw Error(a(137,v));break;default:Ot!==Gt&&ta(h,v,Ft,Ot,D,Gt)}}pi(h,Se,$e,pt,Mt,Ht,ee,V);return;case"select":Ot=Se=$e=Ft=null;for(ee in N)if(pt=N[ee],N.hasOwnProperty(ee)&&pt!=null)switch(ee){case"value":break;case"multiple":Ot=pt;default:D.hasOwnProperty(ee)||ta(h,v,ee,null,D,pt)}for(V in D)if(ee=D[V],pt=N[V],D.hasOwnProperty(V)&&(ee!=null||pt!=null))switch(V){case"value":Ft=ee;break;case"defaultValue":$e=ee;break;case"multiple":Se=ee;default:ee!==pt&&ta(h,v,V,ee,D,pt)}v=$e,N=Se,D=Ot,Ft!=null?ua(h,!!N,Ft,!1):!!D!=!!N&&(v!=null?ua(h,!!N,v,!0):ua(h,!!N,N?[]:"",!1));return;case"textarea":Ot=Ft=null;for($e in N)if(V=N[$e],N.hasOwnProperty($e)&&V!=null&&!D.hasOwnProperty($e))switch($e){case"value":break;case"children":break;default:ta(h,v,$e,null,D,V)}for(Se in D)if(V=D[Se],ee=N[Se],D.hasOwnProperty(Se)&&(V!=null||ee!=null))switch(Se){case"value":Ft=V;break;case"defaultValue":Ot=V;break;case"children":break;case"dangerouslySetInnerHTML":if(V!=null)throw Error(a(91));break;default:V!==ee&&ta(h,v,Se,V,D,ee)}Fr(h,Ft,Ot);return;case"option":for(var vn in N)Ft=N[vn],N.hasOwnProperty(vn)&&Ft!=null&&!D.hasOwnProperty(vn)&&(vn==="selected"?h.selected=!1:ta(h,v,vn,null,D,Ft));for(pt in D)Ft=D[pt],Ot=N[pt],D.hasOwnProperty(pt)&&Ft!==Ot&&(Ft!=null||Ot!=null)&&(pt==="selected"?h.selected=Ft&&typeof Ft!="function"&&typeof Ft!="symbol":ta(h,v,pt,Ft,D,Ot));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 Bn in N)Ft=N[Bn],N.hasOwnProperty(Bn)&&Ft!=null&&!D.hasOwnProperty(Bn)&&ta(h,v,Bn,null,D,Ft);for(Mt in D)if(Ft=D[Mt],Ot=N[Mt],D.hasOwnProperty(Mt)&&Ft!==Ot&&(Ft!=null||Ot!=null))switch(Mt){case"children":case"dangerouslySetInnerHTML":if(Ft!=null)throw Error(a(137,v));break;default:ta(h,v,Mt,Ft,D,Ot)}return;default:if(zs(v)){for(var na in N)Ft=N[na],N.hasOwnProperty(na)&&Ft!==void 0&&!D.hasOwnProperty(na)&&jM(h,v,na,void 0,D,Ft);for(Ht in D)Ft=D[Ht],Ot=N[Ht],!D.hasOwnProperty(Ht)||Ft===Ot||Ft===void 0&&Ot===void 0||jM(h,v,Ht,Ft,D,Ot);return}}for(var St in N)Ft=N[St],N.hasOwnProperty(St)&&Ft!=null&&!D.hasOwnProperty(St)&&ta(h,v,St,null,D,Ft);for(Gt in D)Ft=D[Gt],Ot=N[Gt],!D.hasOwnProperty(Gt)||Ft===Ot||Ft==null&&Ot==null||ta(h,v,Gt,Ft,D,Ot)}function UH(h){switch(h){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function pue(){if(typeof performance.getEntriesByType=="function"){for(var h=0,v=0,N=performance.getEntriesByType("resource"),D=0;D<N.length;D++){var V=N[D],ee=V.transferSize,Se=V.initiatorType,$e=V.duration;if(ee&&$e&&UH(Se)){for(Se=0,$e=V.responseEnd,D+=1;D<N.length;D++){var pt=N[D],Mt=pt.startTime;if(Mt>$e)break;var Ht=pt.transferSize,Gt=pt.initiatorType;Ht&&UH(Gt)&&(pt=pt.responseEnd,Se+=Ht*(pt<$e?1:($e-Mt)/(pt-Mt)))}if(--D,v+=8*(ee+Se)/(V.duration/1e3),h++,10<h)break}}if(0<h)return v/h/1e6}return navigator.connection&&(h=navigator.connection.downlink,typeof h=="number")?h:5}var MM=null,EM=null;function ck(h){return h.nodeType===9?h:h.ownerDocument}function BH(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 HH(h,v){if(h===0)switch(v){case"svg":return 1;case"math":return 2;default:return 0}return h===1&&v==="foreignObject"?0:h}function DM(h,v){return h==="textarea"||h==="noscript"||typeof v.children=="string"||typeof v.children=="number"||typeof v.children=="bigint"||typeof v.dangerouslySetInnerHTML=="object"&&v.dangerouslySetInnerHTML!==null&&v.dangerouslySetInnerHTML.__html!=null}var FM=null;function hue(){var h=window.event;return h&&h.type==="popstate"?h===FM?!1:(FM=h,!0):(FM=null,!1)}var qH=typeof setTimeout=="function"?setTimeout:void 0,fue=typeof clearTimeout=="function"?clearTimeout:void 0,$H=typeof Promise=="function"?Promise:void 0,gue=typeof queueMicrotask=="function"?queueMicrotask:typeof $H<"u"?function(h){return $H.resolve(null).then(h).catch(bue)}:qH;function bue(h){setTimeout(function(){throw h})}function Ep(h){return h==="head"}function VH(h,v){var N=v,D=0;do{var V=N.nextSibling;if(h.removeChild(N),V&&V.nodeType===8)if(N=V.data,N==="/$"||N==="/&"){if(D===0){h.removeChild(V),Gb(v);return}D--}else if(N==="$"||N==="$?"||N==="$~"||N==="$!"||N==="&")D++;else if(N==="html")qv(h.ownerDocument.documentElement);else if(N==="head"){N=h.ownerDocument.head,qv(N);for(var ee=N.firstChild;ee;){var Se=ee.nextSibling,$e=ee.nodeName;ee[Je]||$e==="SCRIPT"||$e==="STYLE"||$e==="LINK"&&ee.rel.toLowerCase()==="stylesheet"||N.removeChild(ee),ee=Se}}else N==="body"&&qv(h.ownerDocument.body);N=V}while(N);Gb(v)}function GH(h,v){var N=h;h=0;do{var D=N.nextSibling;if(N.nodeType===1?v?(N._stashedDisplay=N.style.display,N.style.display="none"):(N.style.display=N._stashedDisplay||"",N.getAttribute("style")===""&&N.removeAttribute("style")):N.nodeType===3&&(v?(N._stashedText=N.nodeValue,N.nodeValue=""):N.nodeValue=N._stashedText||""),D&&D.nodeType===8)if(N=D.data,N==="/$"){if(h===0)break;h--}else N!=="$"&&N!=="$?"&&N!=="$~"&&N!=="$!"||h++;N=D}while(N)}function LM(h){var v=h.firstChild;for(v&&v.nodeType===10&&(v=v.nextSibling);v;){var N=v;switch(v=v.nextSibling,N.nodeName){case"HTML":case"HEAD":case"BODY":LM(N),De(N);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(N.rel.toLowerCase()==="stylesheet")continue}h.removeChild(N)}}function xue(h,v,N,D){for(;h.nodeType===1;){var V=N;if(h.nodeName.toLowerCase()!==v.toLowerCase()){if(!D&&(h.nodeName!=="INPUT"||h.type!=="hidden"))break}else if(D){if(!h[Je])switch(v){case"meta":if(!h.hasAttribute("itemprop"))break;return h;case"link":if(ee=h.getAttribute("rel"),ee==="stylesheet"&&h.hasAttribute("data-precedence"))break;if(ee!==V.rel||h.getAttribute("href")!==(V.href==null||V.href===""?null:V.href)||h.getAttribute("crossorigin")!==(V.crossOrigin==null?null:V.crossOrigin)||h.getAttribute("title")!==(V.title==null?null:V.title))break;return h;case"style":if(h.hasAttribute("data-precedence"))break;return h;case"script":if(ee=h.getAttribute("src"),(ee!==(V.src==null?null:V.src)||h.getAttribute("type")!==(V.type==null?null:V.type)||h.getAttribute("crossorigin")!==(V.crossOrigin==null?null:V.crossOrigin))&&ee&&h.hasAttribute("async")&&!h.hasAttribute("itemprop"))break;return h;default:return h}}else if(v==="input"&&h.type==="hidden"){var ee=V.name==null?null:""+V.name;if(V.type==="hidden"&&h.getAttribute("name")===ee)return h}else return h;if(h=$l(h.nextSibling),h===null)break}return null}function yue(h,v,N){if(v==="")return null;for(;h.nodeType!==3;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!N||(h=$l(h.nextSibling),h===null))return null;return h}function WH(h,v){for(;h.nodeType!==8;)if((h.nodeType!==1||h.nodeName!=="INPUT"||h.type!=="hidden")&&!v||(h=$l(h.nextSibling),h===null))return null;return h}function RM(h){return h.data==="$?"||h.data==="$~"}function IM(h){return h.data==="$!"||h.data==="$?"&&h.ownerDocument.readyState!=="loading"}function vue(h,v){var N=h.ownerDocument;if(h.data==="$~")h._reactRetry=v;else if(h.data!=="$?"||N.readyState!=="loading")v();else{var D=function(){v(),N.removeEventListener("DOMContentLoaded",D)};N.addEventListener("DOMContentLoaded",D),h._reactRetry=D}}function $l(h){for(;h!=null;h=h.nextSibling){var v=h.nodeType;if(v===1||v===3)break;if(v===8){if(v=h.data,v==="$"||v==="$!"||v==="$?"||v==="$~"||v==="&"||v==="F!"||v==="F")break;if(v==="/$"||v==="/&")return null}}return h}var OM=null;function KH(h){h=h.nextSibling;for(var v=0;h;){if(h.nodeType===8){var N=h.data;if(N==="/$"||N==="/&"){if(v===0)return $l(h.nextSibling);v--}else N!=="$"&&N!=="$!"&&N!=="$?"&&N!=="$~"&&N!=="&"||v++}h=h.nextSibling}return null}function QH(h){h=h.previousSibling;for(var v=0;h;){if(h.nodeType===8){var N=h.data;if(N==="$"||N==="$!"||N==="$?"||N==="$~"||N==="&"){if(v===0)return h;v--}else N!=="/$"&&N!=="/&"||v++}h=h.previousSibling}return null}function YH(h,v,N){switch(v=ck(N),h){case"html":if(h=v.documentElement,!h)throw Error(a(452));return h;case"head":if(h=v.head,!h)throw Error(a(453));return h;case"body":if(h=v.body,!h)throw Error(a(454));return h;default:throw Error(a(451))}}function qv(h){for(var v=h.attributes;v.length;)h.removeAttributeNode(v[0]);De(h)}var Vl=new Map,XH=new Set;function dk(h){return typeof h.getRootNode=="function"?h.getRootNode():h.nodeType===9?h:h.ownerDocument}var Wu=Y.d;Y.d={f:wue,r:Sue,D:_ue,C:kue,L:Nue,m:Cue,X:Tue,S:Pue,M:Aue};function wue(){var h=Wu.f(),v=tk();return h||v}function Sue(h){var v=Ne(h);v!==null&&v.tag===5&&v.type==="form"?hB(v):Wu.r(h)}var qb=typeof document>"u"?null:document;function ZH(h,v,N){var D=qb;if(D&&typeof v=="string"&&v){var V=Gn(v);V='link[rel="'+h+'"][href="'+V+'"]',typeof N=="string"&&(V+='[crossorigin="'+N+'"]'),XH.has(V)||(XH.add(V),h={rel:h,crossOrigin:N,href:v},D.querySelector(V)===null&&(v=D.createElement("link"),_s(v,"link",h),at(v),D.head.appendChild(v)))}}function _ue(h){Wu.D(h),ZH("dns-prefetch",h,null)}function kue(h,v){Wu.C(h,v),ZH("preconnect",h,v)}function Nue(h,v,N){Wu.L(h,v,N);var D=qb;if(D&&h&&v){var V='link[rel="preload"][as="'+Gn(v)+'"]';v==="image"&&N&&N.imageSrcSet?(V+='[imagesrcset="'+Gn(N.imageSrcSet)+'"]',typeof N.imageSizes=="string"&&(V+='[imagesizes="'+Gn(N.imageSizes)+'"]')):V+='[href="'+Gn(h)+'"]';var ee=V;switch(v){case"style":ee=$b(h);break;case"script":ee=Vb(h)}Vl.has(ee)||(h=m({rel:"preload",href:v==="image"&&N&&N.imageSrcSet?void 0:h,as:v},N),Vl.set(ee,h),D.querySelector(V)!==null||v==="style"&&D.querySelector($v(ee))||v==="script"&&D.querySelector(Vv(ee))||(v=D.createElement("link"),_s(v,"link",h),at(v),D.head.appendChild(v)))}}function Cue(h,v){Wu.m(h,v);var N=qb;if(N&&h){var D=v&&typeof v.as=="string"?v.as:"script",V='link[rel="modulepreload"][as="'+Gn(D)+'"][href="'+Gn(h)+'"]',ee=V;switch(D){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":ee=Vb(h)}if(!Vl.has(ee)&&(h=m({rel:"modulepreload",href:h},v),Vl.set(ee,h),N.querySelector(V)===null)){switch(D){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(N.querySelector(Vv(ee)))return}D=N.createElement("link"),_s(D,"link",h),at(D),N.head.appendChild(D)}}}function Pue(h,v,N){Wu.S(h,v,N);var D=qb;if(D&&h){var V=nt(D).hoistableStyles,ee=$b(h);v=v||"default";var Se=V.get(ee);if(!Se){var $e={loading:0,preload:null};if(Se=D.querySelector($v(ee)))$e.loading=5;else{h=m({rel:"stylesheet",href:h,"data-precedence":v},N),(N=Vl.get(ee))&&zM(h,N);var pt=Se=D.createElement("link");at(pt),_s(pt,"link",h),pt._p=new Promise(function(Mt,Ht){pt.onload=Mt,pt.onerror=Ht}),pt.addEventListener("load",function(){$e.loading|=1}),pt.addEventListener("error",function(){$e.loading|=2}),$e.loading|=4,uk(Se,v,D)}Se={type:"stylesheet",instance:Se,count:1,state:$e},V.set(ee,Se)}}}function Tue(h,v){Wu.X(h,v);var N=qb;if(N&&h){var D=nt(N).hoistableScripts,V=Vb(h),ee=D.get(V);ee||(ee=N.querySelector(Vv(V)),ee||(h=m({src:h,async:!0},v),(v=Vl.get(V))&&UM(h,v),ee=N.createElement("script"),at(ee),_s(ee,"link",h),N.head.appendChild(ee)),ee={type:"script",instance:ee,count:1,state:null},D.set(V,ee))}}function Aue(h,v){Wu.M(h,v);var N=qb;if(N&&h){var D=nt(N).hoistableScripts,V=Vb(h),ee=D.get(V);ee||(ee=N.querySelector(Vv(V)),ee||(h=m({src:h,async:!0,type:"module"},v),(v=Vl.get(V))&&UM(h,v),ee=N.createElement("script"),at(ee),_s(ee,"link",h),N.head.appendChild(ee)),ee={type:"script",instance:ee,count:1,state:null},D.set(V,ee))}}function JH(h,v,N,D){var V=(V=$.current)?dk(V):null;if(!V)throw Error(a(446));switch(h){case"meta":case"title":return null;case"style":return typeof N.precedence=="string"&&typeof N.href=="string"?(v=$b(N.href),N=nt(V).hoistableStyles,D=N.get(v),D||(D={type:"style",instance:null,count:0,state:null},N.set(v,D)),D):{type:"void",instance:null,count:0,state:null};case"link":if(N.rel==="stylesheet"&&typeof N.href=="string"&&typeof N.precedence=="string"){h=$b(N.href);var ee=nt(V).hoistableStyles,Se=ee.get(h);if(Se||(V=V.ownerDocument||V,Se={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},ee.set(h,Se),(ee=V.querySelector($v(h)))&&!ee._p&&(Se.instance=ee,Se.state.loading=5),Vl.has(h)||(N={rel:"preload",as:"style",href:N.href,crossOrigin:N.crossOrigin,integrity:N.integrity,media:N.media,hrefLang:N.hrefLang,referrerPolicy:N.referrerPolicy},Vl.set(h,N),ee||jue(V,h,N,Se.state))),v&&D===null)throw Error(a(528,""));return Se}if(v&&D!==null)throw Error(a(529,""));return null;case"script":return v=N.async,N=N.src,typeof N=="string"&&v&&typeof v!="function"&&typeof v!="symbol"?(v=Vb(N),N=nt(V).hoistableScripts,D=N.get(v),D||(D={type:"script",instance:null,count:0,state:null},N.set(v,D)),D):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,h))}}function $b(h){return'href="'+Gn(h)+'"'}function $v(h){return'link[rel="stylesheet"]['+h+"]"}function e8(h){return m({},h,{"data-precedence":h.precedence,precedence:null})}function jue(h,v,N,D){h.querySelector('link[rel="preload"][as="style"]['+v+"]")?D.loading=1:(v=h.createElement("link"),D.preload=v,v.addEventListener("load",function(){return D.loading|=1}),v.addEventListener("error",function(){return D.loading|=2}),_s(v,"link",N),at(v),h.head.appendChild(v))}function Vb(h){return'[src="'+Gn(h)+'"]'}function Vv(h){return"script[async]"+h}function t8(h,v,N){if(v.count++,v.instance===null)switch(v.type){case"style":var D=h.querySelector('style[data-href~="'+Gn(N.href)+'"]');if(D)return v.instance=D,at(D),D;var V=m({},N,{"data-href":N.href,"data-precedence":N.precedence,href:null,precedence:null});return D=(h.ownerDocument||h).createElement("style"),at(D),_s(D,"style",V),uk(D,N.precedence,h),v.instance=D;case"stylesheet":V=$b(N.href);var ee=h.querySelector($v(V));if(ee)return v.state.loading|=4,v.instance=ee,at(ee),ee;D=e8(N),(V=Vl.get(V))&&zM(D,V),ee=(h.ownerDocument||h).createElement("link"),at(ee);var Se=ee;return Se._p=new Promise(function($e,pt){Se.onload=$e,Se.onerror=pt}),_s(ee,"link",D),v.state.loading|=4,uk(ee,N.precedence,h),v.instance=ee;case"script":return ee=Vb(N.src),(V=h.querySelector(Vv(ee)))?(v.instance=V,at(V),V):(D=N,(V=Vl.get(ee))&&(D=m({},N),UM(D,V)),h=h.ownerDocument||h,V=h.createElement("script"),at(V),_s(V,"link",D),h.head.appendChild(V),v.instance=V);case"void":return null;default:throw Error(a(443,v.type))}else v.type==="stylesheet"&&(v.state.loading&4)===0&&(D=v.instance,v.state.loading|=4,uk(D,N.precedence,h));return v.instance}function uk(h,v,N){for(var D=N.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),V=D.length?D[D.length-1]:null,ee=V,Se=0;Se<D.length;Se++){var $e=D[Se];if($e.dataset.precedence===v)ee=$e;else if(ee!==V)break}ee?ee.parentNode.insertBefore(h,ee.nextSibling):(v=N.nodeType===9?N.head:N,v.insertBefore(h,v.firstChild))}function zM(h,v){h.crossOrigin==null&&(h.crossOrigin=v.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=v.referrerPolicy),h.title==null&&(h.title=v.title)}function UM(h,v){h.crossOrigin==null&&(h.crossOrigin=v.crossOrigin),h.referrerPolicy==null&&(h.referrerPolicy=v.referrerPolicy),h.integrity==null&&(h.integrity=v.integrity)}var mk=null;function n8(h,v,N){if(mk===null){var D=new Map,V=mk=new Map;V.set(N,D)}else V=mk,D=V.get(N),D||(D=new Map,V.set(N,D));if(D.has(h))return D;for(D.set(h,null),N=N.getElementsByTagName(h),V=0;V<N.length;V++){var ee=N[V];if(!(ee[Je]||ee[kt]||h==="link"&&ee.getAttribute("rel")==="stylesheet")&&ee.namespaceURI!=="http://www.w3.org/2000/svg"){var Se=ee.getAttribute(v)||"";Se=h+Se;var $e=D.get(Se);$e?$e.push(ee):D.set(Se,[ee])}}return D}function r8(h,v,N){h=h.ownerDocument||h,h.head.insertBefore(N,v==="title"?h.querySelector("head > title"):null)}function Mue(h,v,N){if(N===1||v.itemProp!=null)return!1;switch(h){case"meta":case"title":return!0;case"style":if(typeof v.precedence!="string"||typeof v.href!="string"||v.href==="")break;return!0;case"link":if(typeof v.rel!="string"||typeof v.href!="string"||v.href===""||v.onLoad||v.onError)break;return v.rel==="stylesheet"?(h=v.disabled,typeof v.precedence=="string"&&h==null):!0;case"script":if(v.async&&typeof v.async!="function"&&typeof v.async!="symbol"&&!v.onLoad&&!v.onError&&v.src&&typeof v.src=="string")return!0}return!1}function a8(h){return!(h.type==="stylesheet"&&(h.state.loading&3)===0)}function Eue(h,v,N,D){if(N.type==="stylesheet"&&(typeof D.media!="string"||matchMedia(D.media).matches!==!1)&&(N.state.loading&4)===0){if(N.instance===null){var V=$b(D.href),ee=v.querySelector($v(V));if(ee){v=ee._p,v!==null&&typeof v=="object"&&typeof v.then=="function"&&(h.count++,h=pk.bind(h),v.then(h,h)),N.state.loading|=4,N.instance=ee,at(ee);return}ee=v.ownerDocument||v,D=e8(D),(V=Vl.get(V))&&zM(D,V),ee=ee.createElement("link"),at(ee);var Se=ee;Se._p=new Promise(function($e,pt){Se.onload=$e,Se.onerror=pt}),_s(ee,"link",D),N.instance=ee}h.stylesheets===null&&(h.stylesheets=new Map),h.stylesheets.set(N,v),(v=N.state.preload)&&(N.state.loading&3)===0&&(h.count++,N=pk.bind(h),v.addEventListener("load",N),v.addEventListener("error",N))}}var BM=0;function Due(h,v){return h.stylesheets&&h.count===0&&fk(h,h.stylesheets),0<h.count||0<h.imgCount?function(N){var D=setTimeout(function(){if(h.stylesheets&&fk(h,h.stylesheets),h.unsuspend){var ee=h.unsuspend;h.unsuspend=null,ee()}},6e4+v);0<h.imgBytes&&BM===0&&(BM=62500*pue());var V=setTimeout(function(){if(h.waitingForImages=!1,h.count===0&&(h.stylesheets&&fk(h,h.stylesheets),h.unsuspend)){var ee=h.unsuspend;h.unsuspend=null,ee()}},(h.imgBytes>BM?50:800)+v);return h.unsuspend=N,function(){h.unsuspend=null,clearTimeout(D),clearTimeout(V)}}:null}function pk(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)fk(this,this.stylesheets);else if(this.unsuspend){var h=this.unsuspend;this.unsuspend=null,h()}}}var hk=null;function fk(h,v){h.stylesheets=null,h.unsuspend!==null&&(h.count++,hk=new Map,v.forEach(Fue,h),hk=null,pk.call(h))}function Fue(h,v){if(!(v.state.loading&4)){var N=hk.get(h);if(N)var D=N.get(null);else{N=new Map,hk.set(h,N);for(var V=h.querySelectorAll("link[data-precedence],style[data-precedence]"),ee=0;ee<V.length;ee++){var Se=V[ee];(Se.nodeName==="LINK"||Se.getAttribute("media")!=="not all")&&(N.set(Se.dataset.precedence,Se),D=Se)}D&&N.set(null,D)}V=v.instance,Se=V.getAttribute("data-precedence"),ee=N.get(Se)||D,ee===D&&N.set(null,V),N.set(Se,V),this.count++,D=pk.bind(this),V.addEventListener("load",D),V.addEventListener("error",D),ee?ee.parentNode.insertBefore(V,ee.nextSibling):(h=h.nodeType===9?h.head:h,h.insertBefore(V,h.firstChild)),v.state.loading|=4}}var Gv={$$typeof:k,Provider:null,Consumer:null,_currentValue:ce,_currentValue2:ce,_threadCount:0};function Lue(h,v,N,D,V,ee,Se,$e,pt){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=Te(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Te(0),this.hiddenUpdates=Te(null),this.identifierPrefix=D,this.onUncaughtError=V,this.onCaughtError=ee,this.onRecoverableError=Se,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=pt,this.incompleteTransitions=new Map}function i8(h,v,N,D,V,ee,Se,$e,pt,Mt,Ht,Gt){return h=new Lue(h,v,N,Se,pt,Mt,Ht,Gt,$e),v=1,ee===!0&&(v|=24),ee=al(3,null,null,v),h.current=ee,ee.stateNode=h,v=vj(),v.refCount++,h.pooledCache=v,v.refCount++,ee.memoizedState={element:D,isDehydrated:N,cache:v},kj(ee),h}function s8(h){return h?(h=Sb,h):Sb}function o8(h,v,N,D,V,ee){V=s8(V),D.context===null?D.context=V:D.pendingContext=V,D=wp(v),D.payload={element:N},ee=ee===void 0?null:ee,ee!==null&&(D.callback=ee),N=Sp(h,D,v),N!==null&&(Oo(N,h,v),kv(N,h,v))}function l8(h,v){if(h=h.memoizedState,h!==null&&h.dehydrated!==null){var N=h.retryLane;h.retryLane=N!==0&&N<v?N:v}}function HM(h,v){l8(h,v),(h=h.alternate)&&l8(h,v)}function c8(h){if(h.tag===13||h.tag===31){var v=yf(h,67108864);v!==null&&Oo(v,h,67108864),HM(h,67108864)}}function d8(h){if(h.tag===13||h.tag===31){var v=cl();v=Wt(v);var N=yf(h,v);N!==null&&Oo(N,h,v),HM(h,v)}}var gk=!0;function Rue(h,v,N,D){var V=ne.T;ne.T=null;var ee=Y.p;try{Y.p=2,qM(h,v,N,D)}finally{Y.p=ee,ne.T=V}}function Iue(h,v,N,D){var V=ne.T;ne.T=null;var ee=Y.p;try{Y.p=8,qM(h,v,N,D)}finally{Y.p=ee,ne.T=V}}function qM(h,v,N,D){if(gk){var V=$M(D);if(V===null)AM(h,v,D,bk,N),m8(h,D);else if(zue(V,h,v,N,D))D.stopPropagation();else if(m8(h,D),v&4&&-1<Oue.indexOf(h)){for(;V!==null;){var ee=Ne(V);if(ee!==null)switch(ee.tag){case 3:if(ee=ee.stateNode,ee.current.memoizedState.isDehydrated){var Se=Ie(ee.pendingLanes);if(Se!==0){var $e=ee;for($e.pendingLanes|=2,$e.entangledLanes|=2;Se;){var pt=1<<31-We(Se);$e.entanglements[1]|=pt,Se&=~pt}Dd(ee),(Hr&6)===0&&(J_=R()+500,Uv(0))}}break;case 31:case 13:$e=yf(ee,2),$e!==null&&Oo($e,ee,2),tk(),HM(ee,2)}if(ee=$M(D),ee===null&&AM(h,v,D,bk,N),ee===V)break;V=ee}V!==null&&D.stopPropagation()}else AM(h,v,D,null,N)}}function $M(h){return h=Dc(h),VM(h)}var bk=null;function VM(h){if(bk=null,h=mt(h),h!==null){var v=s(h);if(v===null)h=null;else{var N=v.tag;if(N===13){if(h=o(v),h!==null)return h;h=null}else if(N===31){if(h=l(v),h!==null)return h;h=null}else if(N===3){if(v.stateNode.current.memoizedState.isDehydrated)return v.tag===3?v.stateNode.containerInfo:null;h=null}else v!==h&&(h=null)}}return bk=h,null}function u8(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(re()){case be:return 2;case ye:return 8;case _e:case xe:return 32;case ge:return 268435456;default:return 32}default:return 32}}var GM=!1,Dp=null,Fp=null,Lp=null,Wv=new Map,Kv=new Map,Rp=[],Oue="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 m8(h,v){switch(h){case"focusin":case"focusout":Dp=null;break;case"dragenter":case"dragleave":Fp=null;break;case"mouseover":case"mouseout":Lp=null;break;case"pointerover":case"pointerout":Wv.delete(v.pointerId);break;case"gotpointercapture":case"lostpointercapture":Kv.delete(v.pointerId)}}function Qv(h,v,N,D,V,ee){return h===null||h.nativeEvent!==ee?(h={blockedOn:v,domEventName:N,eventSystemFlags:D,nativeEvent:ee,targetContainers:[V]},v!==null&&(v=Ne(v),v!==null&&c8(v)),h):(h.eventSystemFlags|=D,v=h.targetContainers,V!==null&&v.indexOf(V)===-1&&v.push(V),h)}function zue(h,v,N,D,V){switch(v){case"focusin":return Dp=Qv(Dp,h,v,N,D,V),!0;case"dragenter":return Fp=Qv(Fp,h,v,N,D,V),!0;case"mouseover":return Lp=Qv(Lp,h,v,N,D,V),!0;case"pointerover":var ee=V.pointerId;return Wv.set(ee,Qv(Wv.get(ee)||null,h,v,N,D,V)),!0;case"gotpointercapture":return ee=V.pointerId,Kv.set(ee,Qv(Kv.get(ee)||null,h,v,N,D,V)),!0}return!1}function p8(h){var v=mt(h.target);if(v!==null){var N=s(v);if(N!==null){if(v=N.tag,v===13){if(v=o(N),v!==null){h.blockedOn=v,cn(h.priority,function(){d8(N)});return}}else if(v===31){if(v=l(N),v!==null){h.blockedOn=v,cn(h.priority,function(){d8(N)});return}}else if(v===3&&N.stateNode.current.memoizedState.isDehydrated){h.blockedOn=N.tag===3?N.stateNode.containerInfo:null;return}}}h.blockedOn=null}function xk(h){if(h.blockedOn!==null)return!1;for(var v=h.targetContainers;0<v.length;){var N=$M(h.nativeEvent);if(N===null){N=h.nativeEvent;var D=new N.constructor(N.type,N);Ec=D,N.target.dispatchEvent(D),Ec=null}else return v=Ne(N),v!==null&&c8(v),h.blockedOn=N,!1;v.shift()}return!0}function h8(h,v,N){xk(h)&&N.delete(v)}function Uue(){GM=!1,Dp!==null&&xk(Dp)&&(Dp=null),Fp!==null&&xk(Fp)&&(Fp=null),Lp!==null&&xk(Lp)&&(Lp=null),Wv.forEach(h8),Kv.forEach(h8)}function yk(h,v){h.blockedOn===v&&(h.blockedOn=null,GM||(GM=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Uue)))}var vk=null;function f8(h){vk!==h&&(vk=h,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){vk===h&&(vk=null);for(var v=0;v<h.length;v+=3){var N=h[v],D=h[v+1],V=h[v+2];if(typeof D!="function"){if(VM(D||N)===null)continue;break}var ee=Ne(N);ee!==null&&(h.splice(v,3),v-=3,$j(ee,{pending:!0,data:V,method:N.method,action:D},D,V))}}))}function Gb(h){function v(pt){return yk(pt,h)}Dp!==null&&yk(Dp,h),Fp!==null&&yk(Fp,h),Lp!==null&&yk(Lp,h),Wv.forEach(v),Kv.forEach(v);for(var N=0;N<Rp.length;N++){var D=Rp[N];D.blockedOn===h&&(D.blockedOn=null)}for(;0<Rp.length&&(N=Rp[0],N.blockedOn===null);)p8(N),N.blockedOn===null&&Rp.shift();if(N=(h.ownerDocument||h).$$reactFormReplay,N!=null)for(D=0;D<N.length;D+=3){var V=N[D],ee=N[D+1],Se=V[Nt]||null;if(typeof ee=="function")Se||f8(N);else if(Se){var $e=null;if(ee&&ee.hasAttribute("formAction")){if(V=ee,Se=ee[Nt]||null)$e=Se.formAction;else if(VM(V)!==null)continue}else $e=Se.action;typeof $e=="function"?N[D+1]=$e:(N.splice(D,3),D-=3),f8(N)}}}function g8(){function h(ee){ee.canIntercept&&ee.info==="react-transition"&&ee.intercept({handler:function(){return new Promise(function(Se){return V=Se})},focusReset:"manual",scroll:"manual"})}function v(){V!==null&&(V(),V=null),D||setTimeout(N,20)}function N(){if(!D&&!navigation.transition){var ee=navigation.currentEntry;ee&&ee.url!=null&&navigation.navigate(ee.url,{state:ee.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var D=!1,V=null;return navigation.addEventListener("navigate",h),navigation.addEventListener("navigatesuccess",v),navigation.addEventListener("navigateerror",v),setTimeout(N,100),function(){D=!0,navigation.removeEventListener("navigate",h),navigation.removeEventListener("navigatesuccess",v),navigation.removeEventListener("navigateerror",v),V!==null&&(V(),V=null)}}}function WM(h){this._internalRoot=h}wk.prototype.render=WM.prototype.render=function(h){var v=this._internalRoot;if(v===null)throw Error(a(409));var N=v.current,D=cl();o8(N,D,h,v,null,null)},wk.prototype.unmount=WM.prototype.unmount=function(){var h=this._internalRoot;if(h!==null){this._internalRoot=null;var v=h.containerInfo;o8(h.current,2,null,h,null,null),tk(),v[ut]=null}};function wk(h){this._internalRoot=h}wk.prototype.unstable_scheduleHydration=function(h){if(h){var v=ln();h={blockedOn:null,target:h,priority:v};for(var N=0;N<Rp.length&&v!==0&&v<Rp[N].priority;N++);Rp.splice(N,0,h),N===0&&p8(h)}};var b8=e.version;if(b8!=="19.2.4")throw Error(a(527,b8,"19.2.4"));Y.findDOMNode=function(h){var v=h._reactInternals;if(v===void 0)throw typeof h.render=="function"?Error(a(188)):(h=Object.keys(h).join(","),Error(a(268,h)));return h=d(v),h=h!==null?u(h):null,h=h===null?null:h.stateNode,h};var Bue={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:ne,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Sk=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Sk.isDisabled&&Sk.supportsFiber)try{Fe=Sk.inject(Bue),Oe=Sk}catch{}}return Xv.createRoot=function(h,v){if(!i(h))throw Error(a(299));var N=!1,D="",V=kB,ee=NB,Se=CB;return v!=null&&(v.unstable_strictMode===!0&&(N=!0),v.identifierPrefix!==void 0&&(D=v.identifierPrefix),v.onUncaughtError!==void 0&&(V=v.onUncaughtError),v.onCaughtError!==void 0&&(ee=v.onCaughtError),v.onRecoverableError!==void 0&&(Se=v.onRecoverableError)),v=i8(h,1,!1,null,null,N,D,null,V,ee,Se,g8),h[ut]=v.current,TM(h),new WM(v)},Xv.hydrateRoot=function(h,v,N){if(!i(h))throw Error(a(299));var D=!1,V="",ee=kB,Se=NB,$e=CB,pt=null;return N!=null&&(N.unstable_strictMode===!0&&(D=!0),N.identifierPrefix!==void 0&&(V=N.identifierPrefix),N.onUncaughtError!==void 0&&(ee=N.onUncaughtError),N.onCaughtError!==void 0&&(Se=N.onCaughtError),N.onRecoverableError!==void 0&&($e=N.onRecoverableError),N.formState!==void 0&&(pt=N.formState)),v=i8(h,1,!0,v,N??null,D,V,pt,ee,Se,$e,g8),v.context=s8(null),N=v.current,D=cl(),D=Wt(D),V=wp(D),V.callback=null,Sp(N,V,D),N=D,v.current.lanes=N,tt(v,N),Dd(v),h[ut]=v.current,TM(h),new wk(v)},Xv.version="19.2.4",Xv}var P8;function Zue(){if(P8)return YM.exports;P8=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(),YM.exports=Xue(),YM.exports}var Jue=Zue();const qn=t=>typeof t=="string",Zv=()=>{let t,e;const n=new Promise((a,i)=>{t=a,e=i});return n.resolve=t,n.reject=e,n},T8=t=>t==null?"":""+t,eme=(t,e,n)=>{t.forEach(a=>{e[a]&&(n[a]=e[a])})},tme=/###/g,A8=t=>t&&t.indexOf("###")>-1?t.replace(tme,"."):t,j8=t=>!t||qn(t),Q0=(t,e,n)=>{const a=qn(e)?e.split("."):e;let i=0;for(;i<a.length-1;){if(j8(t))return{};const s=A8(a[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return j8(t)?{}:{obj:t,k:A8(a[i])}},M8=(t,e,n)=>{const{obj:a,k:i}=Q0(t,e,Object);if(a!==void 0||e.length===1){a[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),l=Q0(t,o,Object);for(;l.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),l=Q0(t,o,Object),l?.obj&&typeof l.obj[`${l.k}.${s}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${s}`]=n},nme=(t,e,n,a)=>{const{obj:i,k:s}=Q0(t,e,Object);i[s]=i[s]||[],i[s].push(n)},GN=(t,e)=>{const{obj:n,k:a}=Q0(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,a))return n[a]},rme=(t,e,n)=>{const a=GN(t,n);return a!==void 0?a:GN(e,n)},HX=(t,e,n)=>{for(const a in e)a!=="__proto__"&&a!=="constructor"&&(a in t?qn(t[a])||t[a]instanceof String||qn(e[a])||e[a]instanceof String?n&&(t[a]=e[a]):HX(t[a],e[a],n):t[a]=e[a]);return t},Wb=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var ame={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const ime=t=>qn(t)?t.replace(/[&<>"'\/]/g,e=>ame[e]):t;class sme{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 a=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,a),this.regExpQueue.push(e),a}}const ome=[" ",",","?","!",";"],lme=new sme(20),cme=(t,e,n)=>{e=e||"",n=n||"";const a=ome.filter(o=>e.indexOf(o)<0&&n.indexOf(o)<0);if(a.length===0)return!0;const i=lme.getRegExp(`(${a.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},AF=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const a=e.split(n);let i=t;for(let s=0;s<a.length;){if(!i||typeof i!="object")return;let o,l="";for(let c=s;c<a.length;++c)if(c!==s&&(l+=n),l+=a[c],o=i[l],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<a.length-1)continue;s+=c-s+1;break}i=o}return i},Pw=t=>t?.replace("_","-"),dme={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 WN{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||dme,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,a,i){return i&&!this.debug?null:(qn(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new WN(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new WN(this.logger,e)}}var Xd=new WN;let yT=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(a=>{this.observers[a]||(this.observers[a]=new Map);const i=this.observers[a].get(n)||0;this.observers[a].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 E8 extends yT{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,a,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],a&&(Array.isArray(a)?l.push(...a):qn(a)&&s?l.push(...a.split(s)):l.push(a)));const c=GN(this.data,l);return!c&&!n&&!a&&e.indexOf(".")>-1&&(e=l[0],n=l[1],a=l.slice(2).join(".")),c||!o||!qn(a)?c:AF(this.data?.[e]?.[n],a,s)}addResource(e,n,a,i,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let l=[e,n];a&&(l=l.concat(o?a.split(o):a)),e.indexOf(".")>-1&&(l=e.split("."),i=n,n=l[1]),this.addNamespaces(n),M8(this.data,l,i),s.silent||this.emit("added",e,n,a,i)}addResources(e,n,a,i={silent:!1}){for(const s in a)(qn(a[s])||Array.isArray(a[s]))&&this.addResource(e,n,s,a[s],{silent:!0});i.silent||this.emit("added",e,n,a)}addResourceBundle(e,n,a,i,s,o={silent:!1,skipCopy:!1}){let l=[e,n];e.indexOf(".")>-1&&(l=e.split("."),i=a,a=n,n=l[1]),this.addNamespaces(n);let c=GN(this.data,l)||{};o.skipCopy||(a=JSON.parse(JSON.stringify(a))),i?HX(c,a,s):c={...c,...a},M8(this.data,l,c),o.silent||this.emit("added",e,n,a)}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 qX={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,a,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,a,i)??e}),e}};const $X=Symbol("i18next/PATH_KEY");function ume(){const t=[],e=Object.create(null);let n;return e.get=(a,i)=>(n?.revoke?.(),i===$X?t:(t.push(i),n=Proxy.revocable(a,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function jF(t,e){const{[$X]:n}=t(ume());return n.join(e?.keySeparator??".")}const D8={},eE=t=>!qn(t)&&typeof t!="boolean"&&typeof t!="number";class KN extends yT{constructor(e,n={}){super(),eme(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Xd.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const a={...n};if(e==null)return!1;const i=this.resolve(e,a);if(i?.res===void 0)return!1;const s=eE(i.res);return!(a.returnObjects===!1&&s)}extractFromKey(e,n){let a=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;a===void 0&&(a=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=a&&e.indexOf(a)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!cme(e,a,i);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:qn(s)?[s]:s};const d=e.split(a);(a!==i||a===i&&this.options.ns.indexOf(d[0])>-1)&&(s=d.shift()),e=d.join(i)}return{key:e,namespaces:qn(s)?[s]:s}}translate(e,n,a){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=jF(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 g=f?.res;const w=f?.usedKey||l,b=f?.exactUsedKey||l,x=["[object Number]","[object Function]","[object RegExp]"],S=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,C=i.count!==void 0&&!qn(i.count),P=KN.hasDefaultValue(i),T=C?this.pluralResolver.getSuffix(m,i.count,i):"",A=i.ordinal&&C?this.pluralResolver.getSuffix(m,i.count,{ordinal:!1}):"",F=C&&!i.ordinal&&i.count===0,_=F&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${T}`]||i[`defaultValue${A}`]||i.defaultValue;let M=g;k&&!g&&P&&(M=_);const H=eE(M),I=Object.prototype.toString.apply(M);if(k&&M&&H&&x.indexOf(I)<0&&!(qn(S)&&Array.isArray(M))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const z=this.options.returnedObjectHandler?this.options.returnedObjectHandler(w,M,{...i,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return s?(f.res=z,f.usedParams=this.getUsedParamsDetails(i),f):z}if(o){const z=Array.isArray(M),L=z?[]:{},Z=z?b:w;for(const ne in M)if(Object.prototype.hasOwnProperty.call(M,ne)){const Y=`${Z}${o}${ne}`;P&&!g?L[ne]=this.translate(Y,{...i,defaultValue:eE(_)?_[ne]:void 0,joinArrays:!1,ns:c}):L[ne]=this.translate(Y,{...i,joinArrays:!1,ns:c}),L[ne]===Y&&(L[ne]=M[ne])}g=L}}else if(k&&qn(S)&&Array.isArray(g))g=g.join(S),g&&(g=this.extendTranslation(g,e,i,a));else{let z=!1,L=!1;!this.isValidLookup(g)&&P&&(z=!0,g=_),this.isValidLookup(g)||(L=!0,g=l);const ne=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&L?void 0:g,Y=P&&_!==g&&this.options.updateMissing;if(L||z||Y){if(this.logger.log(Y?"updateKey":"missingKey",m,d,l,Y?_:g),o){const Q=this.resolve(l,{...i,keySeparator:!1});Q&&Q.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 ce=[];const ue=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ue&&ue[0])for(let Q=0;Q<ue.length;Q++)ce.push(ue[Q]);else this.options.saveMissingTo==="all"?ce=this.languageUtils.toResolveHierarchy(i.lng||this.language):ce.push(i.lng||this.language);const oe=(Q,le,pe)=>{const he=P&&pe!==g?pe:ne;this.options.missingKeyHandler?this.options.missingKeyHandler(Q,d,le,he,Y,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Q,d,le,he,Y,i),this.emit("missingKey",Q,d,le,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?ce.forEach(Q=>{const le=this.pluralResolver.getSuffixes(Q,i);F&&i[`defaultValue${this.options.pluralSeparator}zero`]&&le.indexOf(`${this.options.pluralSeparator}zero`)<0&&le.push(`${this.options.pluralSeparator}zero`),le.forEach(pe=>{oe([Q],l+pe,i[`defaultValue${pe}`]||_)})}):oe(ce,l,_))}g=this.extendTranslation(g,e,i,f,a),L&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}${u}${l}`),(L||z)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${l}`:l,z?g:void 0,i))}return s?(f.res=g,f.usedParams=this.getUsedParamsDetails(i),f):g}extendTranslation(e,n,a,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const c=qn(e)&&(a?.interpolation?.skipOnVariables!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(c){const m=e.match(this.interpolator.nestingRegexp);d=m&&m.length}let u=a.replace&&!qn(a.replace)?a.replace:a;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,a.lng||this.language||i.usedLng,a),c){const m=e.match(this.interpolator.nestingRegexp),p=m&&m.length;d<p&&(a.nest=!1)}!a.lng&&i&&i.res&&(a.lng=this.language||i.usedLng),a.nest!==!1&&(e=this.interpolator.nest(e,(...m)=>s?.[0]===m[0]&&!a.context?(this.logger.warn(`It seems you are nesting recursively key: ${m[0]} in key: ${n[0]}`),null):this.translate(...m,n),a)),a.interpolation&&this.interpolator.reset()}const o=a.postProcess||this.options.postProcess,l=qn(o)?[o]:o;return e!=null&&l?.length&&a.applyPostProcessor!==!1&&(e=qX.handle(l,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,n={}){let a,i,s,o,l;return qn(e)&&(e=[e]),e.forEach(c=>{if(this.isValidLookup(a))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&&!qn(n.count),f=p&&!n.ordinal&&n.count===0,g=n.context!==void 0&&(qn(n.context)||typeof n.context=="number")&&n.context!=="",w=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);m.forEach(b=>{this.isValidLookup(a)||(l=b,!D8[`${w[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(l)&&(D8[`${w[0]}-${b}`]=!0,this.logger.warn(`key "${i}" for languages "${w.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!!!")),w.forEach(x=>{if(this.isValidLookup(a))return;o=x;const S=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(S,u,x,b,n);else{let C;p&&(C=this.pluralResolver.getSuffix(x,n.count,n));const P=`${this.options.pluralSeparator}zero`,T=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&C.indexOf(T)===0&&S.push(u+C.replace(T,this.options.pluralSeparator)),S.push(u+C),f&&S.push(u+P)),g){const A=`${u}${this.options.contextSeparator||"_"}${n.context}`;S.push(A),p&&(n.ordinal&&C.indexOf(T)===0&&S.push(A+C.replace(T,this.options.pluralSeparator)),S.push(A+C),f&&S.push(A+P))}}let k;for(;k=S.pop();)this.isValidLookup(a)||(s=k,a=this.getResource(x,b,k,n))}))})}),{res:a,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,a,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,a,i):this.resourceStore.getResource(e,n,a,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!qn(e.replace);let i=a?e.replace:e;if(a&&typeof e.count<"u"&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!a){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&n===a.substring(0,n.length)&&e[a]!==void 0)return!0;return!1}}class F8{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Xd.create("languageUtils")}getScriptPartFromCode(e){if(e=Pw(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=Pw(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(qn(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(a=>{if(n)return;const i=this.formatLanguageCode(a);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(a=>{if(n)return;const i=this.getScriptPartFromCode(a);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(a);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)),qn(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let a=e[n];return a||(a=e[this.getScriptPartFromCode(n)]),a||(a=e[this.formatLanguageCode(n)]),a||(a=e[this.getLanguagePartFromCode(n)]),a||(a=e.default),a||[]}toResolveHierarchy(e,n){const a=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 qn(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))):qn(e)&&s(this.formatLanguageCode(e)),a.forEach(o=>{i.indexOf(o)<0&&s(this.formatLanguageCode(o))}),i}}const L8={zero:0,one:1,two:2,few:3,many:4,other:5},R8={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class mme{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Xd.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const a=Pw(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:a,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(a,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),R8;if(!e.match(/-|_/))return R8;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let a=this.getRule(e,n);return a||(a=this.getRule("dev",n)),a?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,a={}){return this.getSuffixes(e,a).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let a=this.getRule(e,n);return a||(a=this.getRule("dev",n)),a?a.resolvedOptions().pluralCategories.sort((i,s)=>L8[i]-L8[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,a={}){const i=this.getRule(e,a);return i?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,a))}}const I8=(t,e,n,a=".",i=!0)=>{let s=rme(t,e,n);return!s&&i&&qn(n)&&(s=AF(t,n,a),s===void 0&&(s=AF(e,n,a))),s},tE=t=>t.replace(/\$/g,"$$$$");class pme{constructor(e={}){this.logger=Xd.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:a,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:d,unescapeSuffix:u,unescapePrefix:m,nestingPrefix:p,nestingPrefixEscaped:f,nestingSuffix:g,nestingSuffixEscaped:w,nestingOptionsSeparator:b,maxReplaces:x,alwaysFormat:S}=e.interpolation;this.escape=n!==void 0?n:ime,this.escapeValue=a!==void 0?a:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Wb(s):o||"{{",this.suffix=l?Wb(l):c||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":m||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=p?Wb(p):f||Wb("$t("),this.nestingSuffix=g?Wb(g):w||Wb(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=x||1e3,this.alwaysFormat=S!==void 0?S:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,a)=>n?.source===a?(n.lastIndex=0,n):new RegExp(a,"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,a,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 x=I8(n,c,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(x,void 0,a,{...i,...n,interpolationkey:f}):x}const g=f.split(this.formatSeparator),w=g.shift().trim(),b=g.join(this.formatSeparator).trim();return this.format(I8(n,c,w,this.options.keySeparator,this.options.ignoreJSONStructure),b,a,{...i,...n,interpolationkey:w})};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=>tE(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?tE(this.escape(f)):tE(f)}].forEach(f=>{for(l=0;s=f.regex.exec(e);){const g=s[1].trim();if(o=d(g),o===void 0)if(typeof u=="function"){const b=u(e,s,i);o=qn(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,g))o="";else if(m){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),o="";else!qn(o)&&!this.useRawValueToEscape&&(o=T8(o));const w=f.safeValue(o);if(e=e.replace(s[0],w),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,a={}){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),g=p.match(/"/g);((f?.length??0)%2===0&&!g||g.length%2!==0)&&(p=p.replace(/'/g,'"'));try{o=JSON.parse(p),d&&(o={...d,...o})}catch(w){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,w),`${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={...a},o=o.replace&&!qn(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&&!qn(s))return s;qn(s)||(s=T8(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,a.lng,{...a,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const hme=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const a=t.split("(");e=a[0].toLowerCase().trim();const i=a[1].substring(0,a[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}},O8=t=>{const e={};return(n,a,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=a+JSON.stringify(s);let l=e[o];return l||(l=t(Pw(a),i),e[o]=l),l(n)}},fme=t=>(e,n,a)=>t(Pw(n),a)(e);class gme{constructor(e={}){this.logger=Xd.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const a=n.cacheInBuiltFormats?O8:fme;this.formats={number:a((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return l=>o.format(l)}),currency:a((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return l=>o.format(l)}),datetime:a((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return l=>o.format(l)}),relativetime:a((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return l=>o.format(l,s.range||"day")}),list:a((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()]=O8(n)}format(e,n,a,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}=hme(c);if(this.formats[d]){let m=l;try{const p=i?.formatParams?.[i.interpolationkey]||{},f=p.locale||p.lng||i.locale||i.lng||a;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 bme=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class xme extends yT{constructor(e,n,a,i={}){super(),this.backend=e,this.store=n,this.services=a,this.languageUtils=a.languageUtils,this.options=i,this.logger=Xd.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?.(a,i.backend,i)}queueLoad(e,n,a,i){const s={},o={},l={},c={};return e.forEach(d=>{let u=!0;n.forEach(m=>{const p=`${d}|${m}`;!a.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,a){const i=e.split("|"),s=i[0],o=i[1];n&&this.emit("failedLoading",s,o,n),!n&&a&&this.store.addResourceBundle(s,o,a,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&a&&(this.state[e]=0);const l={};this.queue.forEach(c=>{nme(c.loaded,[s],o),bme(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,a,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:a,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,a,i+1,s*2,o)},s);return}o(d,u)},c=this.backend[a].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,a={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();qn(e)&&(e=this.languageUtils.toResolveHierarchy(e)),qn(n)&&(n=[n]);const s=this.queueLoad(e,n,a,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,a){this.prepareLoading(e,n,{},a)}reload(e,n,a){this.prepareLoading(e,n,{reload:!0},a)}loadOne(e,n=""){const a=e.split("|"),i=a[0],s=a[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,a,i,s,o={},l=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${a}" 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(!(a==null||a==="")){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,a,i,c):u=d(e,n,a,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,a,i,l,c)}!e||!e[0]||this.store.addResource(e[0],n,a,i)}}}const z8=()=>({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]),qn(t[1])&&(e.defaultValue=t[1]),qn(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(a=>{e[a]=n[a]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),U8=t=>(qn(t.ns)&&(t.ns=[t.ns]),qn(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),qn(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),kk=()=>{},yme=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class Y0 extends yT{constructor(e={},n){if(super(),this.options=U8(e),this.services={},this.logger=Xd,this.modules={external:[]},yme(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&&(qn(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const a=z8();this.options={...a,...this.options,...U8(e)},this.options.interpolation={...a.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?Xd.init(i(this.modules.logger),this.options):Xd.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=gme;const u=new F8(this.options);this.store=new E8(this.options.resources,this.options);const m=this.services;m.logger=Xd,m.resourceStore=this.store,m.languageUtils=u,m.pluralResolver=new mme(u,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==a.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===a.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 pme(this.options),m.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},m.backendConnector=new xme(i(this.modules.backend),m.resourceStore,m,this.options),m.backendConnector.on("*",(f,...g)=>{this.emit(f,...g)}),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 KN(this.services,this.options),this.translator.on("*",(f,...g)=>{this.emit(f,...g)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,n||(n=kk),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=Zv(),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=kk){let a=n;const i=qn(e)?e:this.language;if(typeof e=="function"&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return a();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),a(l)})}else a(null)}reloadResources(e,n,a){const i=Zv();return typeof e=="function"&&(a=e,e=void 0),typeof n=="function"&&(a=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),a||(a=kk),this.services.backendConnector.reload(e,n,s=>{i.resolve(),a(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"&&qX.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 a=this.languages[n];if(!(["cimode","dev"].indexOf(a)>-1)&&this.store.hasLanguageSomeTranslations(a)){this.resolvedLanguage=a;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 a=Zv();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,a.resolve((...d)=>this.t(...d)),n&&n(l,(...d)=>this.t(...d))},o=l=>{!e&&!l&&this.services.languageDetector&&(l=[]);const c=qn(l)?l:l&&l[0],d=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(qn(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),a}getFixedT(e,n,a){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||a||i.keyPrefix);const d=this.options.keySeparator||".";let u;return c.keyPrefix&&Array.isArray(s)?u=s.map(m=>(typeof m=="function"&&(m=jF(m,{...this.options,...o})),`${c.keyPrefix}${d}${m}`)):(typeof s=="function"&&(s=jF(s,{...this.options,...o})),u=c.keyPrefix?`${c.keyPrefix}${d}${s}`:s),this.t(u,c)};return qn(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=a,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 a=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(a.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(a,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(a,e)&&(!i||o(s,e)))}loadNamespaces(e,n){const a=Zv();return this.options.ns?(qn(e)&&(e=[e]),e.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{a.resolve(),n&&n(i)}),a):(n&&n(),Promise.resolve())}loadLanguages(e,n){const a=Zv();qn(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=>{a.resolve(),n&&n(o)}),a):(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"],a=this.services?.languageUtils||new F8(z8());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(a.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const a=new Y0(e,n);return a.createInstance=Y0.createInstance,a}cloneInstance(e={},n=kk){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new Y0(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)},a){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 E8(l,i),s.services.resourceStore=s.store}return s.translator=new KN(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 Ao=Y0.createInstance();Ao.createInstance;Ao.dir;Ao.init;Ao.loadResources;Ao.reloadResources;Ao.use;Ao.changeLanguage;Ao.getFixedT;Ao.t;Ao.exists;Ao.setDefaultNamespace;Ao.hasLoadedNamespace;Ao.loadNamespaces;Ao.loadLanguages;const vme=(t,e,n,a)=>{const i=[n,{code:e,...a||{}}];if(t?.services?.logger?.forward)return t.services.logger.forward(i,"warn","react-i18next::",!0);Pg(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),t?.services?.logger?.warn?t.services.logger.warn(...i):console?.warn&&console.warn(...i)},B8={},VX=(t,e,n,a)=>{Pg(n)&&B8[n]||(Pg(n)&&(B8[n]=new Date),vme(t,e,n,a))},GX=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},MF=(t,e,n)=>{t.loadNamespaces(e,GX(t,n))},H8=(t,e,n,a)=>{if(Pg(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return MF(t,n,a);n.forEach(i=>{t.options.ns.indexOf(i)<0&&t.options.ns.push(i)}),t.loadLanguages(e,GX(t,a))},wme=(t,e,n={})=>!e.languages||!e.languages.length?(VX(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(a,i)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&a.services.backendConnector.backend&&a.isLanguageChangingTo&&!i(a.isLanguageChangingTo,t))return!1}}),Pg=t=>typeof t=="string",Sme=t=>typeof t=="object"&&t!==null,_me=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,kme={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Nme=t=>kme[t],Cme=t=>t.replace(_me,Nme);let EF={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Cme,transDefaultProps:void 0};const Pme=(t={})=>{EF={...EF,...t}},Tme=()=>EF;let WX;const Ame=t=>{WX=t},jme=()=>WX,Mme={type:"3rdParty",init(t){Pme(t.options.react),Ame(t)}},Eme=y.createContext();class Dme{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var nE={exports:{}},rE={};var q8;function Fme(){if(q8)return rE;q8=1;var t=tb();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,a=t.useState,i=t.useEffect,s=t.useLayoutEffect,o=t.useDebugValue;function l(m,p){var f=p(),g=a({inst:{value:f,getSnapshot:p}}),w=g[0].inst,b=g[1];return s(function(){w.value=f,w.getSnapshot=p,c(w)&&b({inst:w})},[m,f,p]),i(function(){return c(w)&&b({inst:w}),m(function(){c(w)&&b({inst:w})})},[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 rE.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:u,rE}var $8;function KX(){return $8||($8=1,nE.exports=Fme()),nE.exports}var rO=KX();const Lme=(t,e)=>Pg(e)?e:Sme(e)&&Pg(e.defaultValue)?e.defaultValue:Array.isArray(t)?t[t.length-1]:t,Rme={t:Lme,ready:!1},Ime=()=>()=>{},_t=(t,e={})=>{const{i18n:n}=e,{i18n:a,defaultNS:i}=y.useContext(Eme)||{},s=n||a||jme();s&&!s.reportNamespaces&&(s.reportNamespaces=new Dme),s||VX(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=y.useMemo(()=>({...Tme(),...s?.options?.react,...e}),[s,e]),{useSuspense:l,keyPrefix:c}=o,d=i||s?.options?.defaultNS,u=Pg(d)?[d]:d||["translation"],m=y.useMemo(()=>u,u);s?.reportNamespaces?.addUsedNamespaces?.(m);const p=y.useRef(0),f=y.useCallback(_=>{if(!s)return Ime;const{bindI18n:M,bindI18nStore:H}=o,I=()=>{p.current+=1,_()};return M&&s.on(M,I),H&&s.store.on(H,I),()=>{M&&M.split(" ").forEach(z=>s.off(z,I)),H&&H.split(" ").forEach(z=>s.store.off(z,I))}},[s,o]),g=y.useRef(),w=y.useCallback(()=>{if(!s)return Rme;const _=!!(s.isInitialized||s.initializedStoreOnce)&&m.every(Z=>wme(Z,s,o)),M=e.lng||s.language,H=p.current,I=g.current;if(I&&I.ready===_&&I.lng===M&&I.keyPrefix===c&&I.revision===H)return I;const L={t:s.getFixedT(M,o.nsMode==="fallback"?m:m[0],c),ready:_,lng:M,keyPrefix:c,revision:H};return g.current=L,L},[s,m,c,o,e.lng]),[b,x]=y.useState(0),{t:S,ready:k}=rO.useSyncExternalStore(f,w,w);y.useEffect(()=>{if(s&&!k&&!l){const _=()=>x(M=>M+1);e.lng?H8(s,e.lng,m,_):MF(s,m,_)}},[s,e.lng,m,k,l,b]);const C=s||{},P=y.useRef(null),T=y.useRef(),A=_=>{const M=Object.getOwnPropertyDescriptors(_);M.__original&&delete M.__original;const H=Object.create(Object.getPrototypeOf(_),M);if(!Object.prototype.hasOwnProperty.call(H,"__original"))try{Object.defineProperty(H,"__original",{value:_,writable:!1,enumerable:!1,configurable:!1})}catch{}return H},F=y.useMemo(()=>{const _=C,M=_?.language;let H=_;_&&(P.current&&P.current.__original===_?T.current!==M?(H=A(_),P.current=H,T.current=M):H=P.current:(H=A(_),P.current=H,T.current=M));const I=[S,H,k];return I.t=S,I.i18n=H,I.ready=k,I},[S,C,k,C.resolvedLanguage,C.language,C.languages]);if(s&&l&&!k)throw new Promise(_=>{const M=()=>_();e.lng?H8(s,e.lng,m,M):MF(s,m,M)});return F},{slice:Ome,forEach:zme}=[];function Ume(t){return zme.call(Ome.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Bme(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 V8=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Hme=function(t,e){const a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${i}`;if(a.maxAge>0){const o=a.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(a.domain){if(!V8.test(a.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${a.domain}`}if(a.path){if(!V8.test(a.path))throw new TypeError("option path is invalid");s+=`; Path=${a.path}`}if(a.expires){if(typeof a.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${a.expires.toUTCString()}`}if(a.httpOnly&&(s+="; HttpOnly"),a.secure&&(s+="; Secure"),a.sameSite)switch(typeof a.sameSite=="string"?a.sameSite.toLowerCase():a.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 a.partitioned&&(s+="; Partitioned"),s},G8={create(t,e,n,a){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)),a&&(i.domain=a),document.cookie=Hme(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let a=0;a<n.length;a++){let i=n[a];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 qme={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return G8.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:a,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&G8.create(n,t,a,i,s)}},$me={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const s=a.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}},Vme={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,a;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&&(a=o[l].substring(c+1))}}if(a)return a;if(!a&&n>-1){const o=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return a}};let Kb=null;const W8=()=>{if(Kb!==null)return Kb;try{if(Kb=typeof window<"u"&&window.localStorage!==null,!Kb)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Kb=!1}return Kb};var Gme={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&W8())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&W8()&&window.localStorage.setItem(n,t)}};let Qb=null;const K8=()=>{if(Qb!==null)return Qb;try{if(Qb=typeof window<"u"&&window.sessionStorage!==null,!Qb)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Qb=!1}return Qb};var Wme={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&K8())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&K8()&&window.sessionStorage.setItem(n,t)}},Kme={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:a,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);a&&e.push(a),i&&e.push(i)}return e.length>0?e:void 0}},Qme={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const a=e||(typeof document<"u"?document.documentElement:null);return a&&typeof a.getAttribute=="function"&&(n=a.getAttribute("lang")),n}},Yme={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}},Xme={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,a=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(a)return a[n]}};let QX=!1;try{document.cookie,QX=!0}catch{}const YX=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];QX||YX.splice(1,1);const Zme=()=>({order:YX,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class XX{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]:{},a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=Ume(n,this.options||{},Zme()),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=a,this.addDetector(qme),this.addDetector($me),this.addDetector(Gme),this.addDetector(Wme),this.addDetector(Kme),this.addDetector(Qme),this.addDetector(Yme),this.addDetector(Xme),this.addDetector(Vme)}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(a=>{if(this.detectors[a]){let i=this.detectors[a].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(a=>a!=null&&!Bme(a)).map(a=>this.options.convertDetectedLanguage(a)),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(a=>{this.detectors[a]&&this.detectors[a].cacheUserLanguage(e,this.options)}))}}XX.type="languageDetector";const Jme={nav:{printers:"Printers",archives:"Archives",queue:"Print Queue",stats:"Statistics",profiles:"Profiles",maintenance:"Maintenance",projects:"Projects",inventory:"Filament",files:"File Manager",makerworld:"MakerWorld",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",errorLoading:"Error loading data",retry:"Retry",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"},toolbar:{filters:"Filters",view:"View",actions:"Actions"},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",connectionFailedNotAdded:"Could not connect to the printer. Verify the IP, serial number, and access code, and confirm LAN-only mode is on. The printer was not added.",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",loadInitiated:"Loading filament…",unloadInitiated:"Unloading filament…",failedToLoad:"Failed to load filament",failedToUnload:"Failed to unload filament"},connection:{connected:"Connected",offline:"Offline"},plateStatus:{markCleared:"Mark plate as cleared",cleared:"Plate Clear",notCleared:"Plate not Clear",inUse:"Plate in Use"},queue:{inQueue:"{{count}} print in queue",inQueue_plural:"{{count}} prints in queue"},controls:"Controls",rfid:{reread:"Re-read RFID"},ams:{load:"Load",unload:"Unload"},bedJog:{title:"Move build plate",bed:"Bed",step:"Step (mm)",up:"Move plate up",down:"Move plate down",disabledWhilePrinting:"Disabled while printing",notHomedTitle:"Printer is not homed",notHomedMessage:"The printer has not been homed since the last print. Run auto-home first for safe positioning (parks the toolhead, then homes X, Y, and Z), or move anyway — soft endstops will be bypassed.",homeZ:"Auto Home",moveAnyway:"Move anyway",homingStarted:"Auto-homing printer…"},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",haToggleTitle:'Toggle "{{name}}"',haToggleMessage:"Toggle the Home Assistant entity {{entity}}? This may turn power off if it is currently on.",haToggleWarning:'WARNING: "{{name}}" is currently printing! Toggling {{entity}} may cut power and interrupt the print. Continue?',haToggleButton:"Toggle"},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",printLog:"Print Log",goToProject:"Go to Project: {{name}}",addToProject:"Add to Project",removeFromProject:"Remove from Project",loading:"Loading...",noProjectsAvailable:"No projects available",searchProjects:"Search projects…",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"},platePicker:{title:"Select plate to preview",hint:"This archive has multiple plates. Pick one to open in the GCode viewer.",plateLabel:"Plate {{index}}",objectCount:"{{count}} object",objectCount_plural:"{{count}} objects",noGcode:"This archive has no sliced G-code to preview. Open it in Bambu Studio to slice first."},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}}",runsBadge:"{{count}} prints",runsBadgeTitle:"{{count}} prints total — {{successful}} successful, {{failed}} failed. Click to see the full print log.",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"},runLog:{title:"Print Log",modalTitle:"Print Log — {{name}}",modalTitleFallback:"this archive",empty:"No print events recorded for this archive yet.",col:{date:"Date",status:"Status",duration:"Duration",filament:"Filament",cost:"Cost"},status:{completed:"Completed",failed:"Failed",cancelled:"Cancelled",stopped:"Stopped",skipped:"Skipped",printing:"Printing"}},modal:{deleteArchive:"Delete Archive",deleteConfirm:'Are you sure you want to delete "{{name}}"? This action cannot be undone.',deleteButton:"Delete",deletePurgeStats:"Also remove this print from Quick Stats (filament, time, cost, energy)",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",clearPlateSuccess:"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…",awaitingPrinter:"Awaiting printer…",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:"Statistics",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",security:"Security"},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.",advanced:"Advanced",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",spoolmanAmsSyncButton:"Sync Spoolman Weights from AMS",spoolmanAmsSyncTitle:"Sync Spoolman Spool Weights from AMS",spoolmanAmsSyncMessage:"This will update all Spoolman spool weights based on the current AMS remain% values from connected printers. Printers must be online.",spoolmanAmsSyncing:"Syncing...",spoolmanAmsSyncSuccess:"{{synced}} spool(s) synced, {{skipped}} skipped",spoolmanAmsSyncError:"Failed to sync Spoolman weights from AMS",spoolmanAmsSyncErrorUnreachable:"Failed to sync Spoolman weights (Spoolman unreachable)",spoolmanAmsSyncErrorNotConfigured:"Failed to sync Spoolman weights (Spoolman not configured)",spoolmanNotConfigured:"Spoolman not configured",spoolmanFilamentCatalogTitle:"Spoolman Filament Catalog",spoolmanFilamentCatalogDesc:"Filament names and tare weights from your Spoolman instance. Name and spool weight are editable here; all other properties are managed directly in Spoolman.",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",cloudAccess:"Allow cloud access",cloudAccessDescription:"Read Bambu Cloud presets and filaments on your behalf. Requires you to be signed into Bambu Cloud.",cloudBadge:"Cloud",updateEnergyCost:"Update electricity price",updateEnergyCostDescription:"Allow this key to POST a new per-kWh electricity price to /settings/electricity-price. Useful for Home Assistant dynamic-tariff automations (Tibber, Octopus, etc.). This is the only settings field writable via API key.",energyCostBadge:"Energy",legacyKey:"Legacy",legacyKeyTooltip:"Created before per-user ownership; recreate to use cloud access",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. Disabling this also hides the plate status badge and the "Mark plate as cleared" button on printer cards.',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",passwordRequirements:"At least 8 characters, with one uppercase, one lowercase, one digit, and one special character.",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",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev have known CLI bugs that block slicing many Bambu-authored 3MFs — see upstream issues #12426 (segfault on painted multi-extruder files) and #13386 (parameter-range strict-validation reject). Bambu Studio is recommended until the upstream fixes land.",useSlicerApi:"Use Slicer API",useSlicerApiDescription:'When on, "Slice" actions open the in-app slicer modal and call the slicer-API sidecar. When off (default), they hand off to the desktop slicer via URI scheme.',slicerCard:"Slicer",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"URL of the slicer-API sidecar container. Leave blank to use the SLICER_API_URL / BAMBU_STUDIO_API_URL env var defaults.",slicerBundles:{title:"Slicer Bundles",description:'Import a Printer Preset Bundle (.bbscfg) exported from BambuStudio (File → Export → Export Preset Bundle → "Printer preset bundle"). Once imported, slice requests can pick presets from the bundle by name without re-uploading the JSON profile triplet.',uploadButton:"Upload bundle",uploading:"Uploading…",loading:"Loading bundles…",empty:"No bundles imported yet.",summary:"{{processCount}} process · {{filamentCount}} filament presets",delete:"Delete",uploadSuccess:"Imported {{name}}",uploadError:"Bundle upload failed: {{message}}",deleteSuccess:"Bundle removed",deleteError:"Bundle delete failed: {{message}}",confirmDeleteTitle:"Remove this bundle?",confirmDeleteMessage:'Slice requests that reference "{{name}}" will fail until the bundle is re-imported.'},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 8 characters",passwordNeedsUppercase:"Password must contain at least one uppercase letter",passwordNeedsLowercase:"Password must contain at least one lowercase letter",passwordNeedsDigit:"Password must contain at least one digit",passwordNeedsSpecial:"Password must contain at least one special character",enterGroupName:"Please enter a group name",settingsSaved:"Settings saved",noPermissionUpdate:"You do not have permission to change settings",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",material:"Material",spoolWeight:"Spool Weight",color:"Color",updateSpoolWeight:"Update Spool Weight",filamentUpdated:"Filament updated",filamentUpdateFailed:"Failed to update filament",filamentUpdateInvalid:"Invalid filament data",keepExistingSpoolWeight:"Keep old weight for existing spools",keepExistingSpoolWeightDesc:"Spools already created with this filament type retain the old tare weight. New spools use the updated value.",applyToAllSpools:"Apply to all spools",applyToAllSpoolsDesc:"All weight calculations for this filament type immediately use the new tare weight."},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)",cameraSnapshotUrl:"Snapshot URL (optional)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"Single-frame URL used for notification thumbnails, finish photos, layer-timelapse frames, and plate detection. Timelapse and plate detection each require their own per-printer toggle — this URL is just the image source they pull from when active. Leave blank to capture from the live stream above. Useful for go2rtc (/api/frame.jpeg) and IP cameras with a dedicated snapshot endpoint.",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:",updateViaHomeAssistant:"Updates are managed by the Home Assistant Supervisor. Open Settings → Add-ons → Bambuddy in Home Assistant to install the new version.",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.",refreshIcon:"Refresh icon",removeIcon:"Remove icon",iconRefreshed:"Icon refreshed.",iconRemoved:"Icon removed.",iconFetchFailed:"Icon could not be fetched from the provider URL.",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",emailClaim:"Email Claim",emailClaimDesc:"JWT claim used as email identity. Use 'preferred_username' or 'upn' for Azure Entra ID (which does not send email_verified). Only use trusted claim names.",emailClaimPlaceholder:"email",emailClaimCustomClaimAutoLinkWarning:"Custom claims are safe for auto-link only when the value is tenant-administered (e.g. Azure Entra ID upn / preferred_username). Do not enable auto-link if your IdP allows users to self-assert this claim.",requireEmailVerified:"Require email verified",requireEmailVerifiedDesc:"Only accept the email claim when the provider marks it as verified.",requireEmailVerifiedWarning:"Warning: email will be accepted even without verification. Use only with trusted providers.",requireEmailVerifiedAutoLink:"Disable auto-link first to change this setting.",defaultGroup:"Default Group",defaultGroupDesc:"Group assigned to auto-created users. Falls back to Viewers if not set.",defaultGroupViewersFallback:"Viewers (default)"}},encryption:{title:"MFA Encryption Status",enabledFromEnv:"At-rest encryption enabled (key from MFA_ENCRYPTION_KEY environment variable)",enabledFromFile:"At-rest encryption enabled (key loaded from data directory)",enabledGenerated:"At-rest encryption enabled with auto-generated key",notConfigured:"At-rest encryption not configured",notConfiguredDesc:"TOTP secrets and OIDC client_secrets are stored in plaintext. Set MFA_ENCRYPTION_KEY or restart Bambuddy with a writable data directory to auto-generate one.",allEncrypted:"All MFA secrets are encrypted at rest.",legacyRowsLabel:"Legacy plaintext rows",encryptedRowsLabel:"Encrypted rows",legacyRowsWarning:"{{count}} legacy plaintext row(s) detected. Re-save the OIDC provider or re-enroll the user’s authenticator app to migrate to encrypted storage.",backupHint:"The auto-generated key is stored at DATA_DIR/.mfa_encryption_key and is included in local backup ZIPs. Keep your backups secure or set MFA_ENCRYPTION_KEY explicitly.",decryptionBrokenTitle:"Encryption key missing",decryptionBrokenError:"{{count}} encrypted record(s) cannot be decrypted because the encryption key is no longer available. Restore the previous MFA_ENCRYPTION_KEY or DATA_DIR/.mfa_encryption_key to recover.",migrationErrorWarning:"{{count}} legacy row(s) failed to re-encrypt at startup. Check server logs and restart Bambuddy to retry."}},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...",rememberMe:"Remember Me",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",unavailable:"Camera unavailable",diagnose:{button:"Diagnose",modalTitle:"Camera diagnostic",running:"Running diagnostic...",runFailed:"Diagnostic could not run: {{error}}",retry:"Run again",stage:{tcp_reachable:"Network reachability",first_frame:"Frame capture",live_stream_active:"Live stream active"},summary:{all_ok:"Camera is working. The diagnostic completed all stages successfully.",live_stream_active_healthy:"Camera is currently streaming with recent frames — no test needed.",printer_unreachable:"Printer is not reachable. Check the IP address, network connection, and that the printer is powered on.",camera_port_closed:"Printer is reachable but the camera port is closed. Make sure LAN-only mode and Developer Mode are enabled in the printer settings.",no_frame:"Connected to the camera but no frames were received. Try again, or check that the camera is enabled in the printer settings.",unknown_failure:"Camera diagnostic failed for an unknown reason. Check the support log for details."},meta:{protocol:"Protocol",port:"Port",profile:"Profile"}}},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",ldapProvisioned:'Provisioned LDAP user "{{username}}"'},modal:{createUser:"Create User",editUser:"Edit User",cancel:"Cancel",creating:"Creating...",saving:"Saving...",saveChanges:"Save Changes",advancedAuthSubtitle:"with Advanced Authentication",tabsAriaLabel:"User source",localTab:"Local",ldapTab:"LDAP",ldapSearchLabel:"Search directory",ldapSearchPlaceholder:"Type a username, name, or email...",ldapMinChars:"Type at least 2 characters to search",ldapTypeToSearch:"Start typing to search the LDAP directory",ldapSearching:"Searching directory...",ldapNoResults:"No matching users in the directory",ldapSearchError:"Directory search failed. Check the LDAP server status.",ldapAlreadyProvisioned:"Already provisioned",ldapSelectedLabel:"Selected",ldapProvision:"Provision user",ldapProvisioning:"Provisioning...",ldapErrorProvision:"Provisioning failed. Check the LDAP server status and try again."},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 Cloud access token. China-region accounts must use this path (phone-bound — email login unavailable). See the wiki for how to retrieve the token from MakerWorld cookies.",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",collapse:"Collapse",collapseFoldersByDefault:"Collapse folders by default",expandFoldersByDefault:"Expand folders by default",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",noPermissionSlice:"You do not have permission to slice files",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...",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"URL must start with http:// or https://",openExternalUrl:"Open project URL",coverImageLabel:"Cover photo",coverImageAlt:"Project cover photo",coverImageUpload:"Upload",coverImageReplace:"Replace",coverImageRemove:"Remove",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"},slice:{title:"Slice model",action:"Slice",slicing:"Slicing…",printer:"Printer profile",process:"Process profile",filament:"Filament profile",filamentSlot:"Filament {{index}} ({{type}})",selectPreset:"— Select a preset —",loadingPresets:"Loading presets…",analyzingPlateFilaments:"Analyzing plate filaments…",analyzingPlateFilamentsHint:"Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.",previewToast:"Analyzing {{name}} — {{elapsed}}",previewWithProgress:"Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",notUsedByPlate:"— not used by this plate",noPresetsForSlot:"No presets available",presetsLoadFailed:"Failed to load presets. Open Settings → Profiles to import them first.",allPresetsRequired:"All presets must be selected",bundle:"Slicer bundle",bundleNone:"— None (pick presets individually) —",bundleAllRequired:"Bundle process and every filament slot must be picked",enqueuing:"Submitting slice job…",queued:"Queued…",failed:"Slicing failed. Check the slicer sidecar logs.",startedToast:"Slicing {{name}} in the background…",queuedToast:"Queued: {{name}} — {{elapsed}}",runningToast:"Slicing {{name}} — {{elapsed}}",runningWithProgress:"{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",completedToast:"Sliced {{name}}",failedToast:"Slicing {{name}} failed: {{detail}}",tier:{local:"Imported",cloud:"Cloud",standard:"Standard"},cloud:{notAuthenticated:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets.",expired:"Bambu Cloud session expired — sign in again to refresh your cloud presets.",unreachable:"Bambu Cloud is unreachable right now. Local and standard presets still work."},bedType:{label:"Build plate",auto:"Auto (use process preset)",coolPlate:"Cool Plate",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},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:"Unassign Spool?",unlinkConfirmMessage:"This will remove the spool from this slot. The spool data itself will remain unchanged.",selectSpool:"Select Spool",noUnlinkedSpools:"No unassigned spools available",linkSuccess:"Spool assigned successfully",linkFailed:"Failed to assign spool",unlinkSuccess:"Spool unassigned successfully",unlinkFailed:"Failed to unassign spool",linkedSpool:"Assigned 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",subtitle:"Manage your spools",spoolmanMixedContentTitle:"Spoolman can't load over HTTPS — mixed-content blocked by your browser",spoolmanMixedContentBody:"Bambuddy is served over HTTPS (via your reverse proxy), but your Spoolman URL is still plain HTTP. Browsers block mixed content for security, so the embedded Spoolman UI can't render. Spoolman needs to be reachable over HTTPS for this to work.",spoolmanMixedContentFixReverseProxy:"Put Spoolman behind the same reverse proxy as Bambuddy (Traefik / Nginx / Caddy) with HTTPS, then update the Spoolman URL in Settings to the new HTTPS address.",spoolmanMixedContentFixOpenNewTab:"As a workaround, open Spoolman in a new browser tab over HTTP — mixed-content rules only apply to embedded frames, so a standalone tab still works.",spoolmanOpenInNewTab:"Open Spoolman in a new tab",labels:{title:"Print spool labels",selectedCount:"{{count}} selected",pickSpools:"Pick which spools to print labels for:",searchPlaceholder:"Search name, brand, or #ID",filterByMaterial:"Material:",allMaterials:"All",selectVisible:"Select all visible ({{count}})",deselectVisible:"Deselect visible",clearAll:"Clear all",noSpoolsToShow:"No spools to show. Adjust your filter and try again.",noMatches:"No spools match the current search or filter.",printOne:"Print label for this spool",printLabels:"Print labels…",bulkTitle:"Pick spools to print labels for from the {{count}} currently shown",noSpoolsTitle:"No spools to label",error:"Could not generate labels: {{msg}}",sortBy:{label:"Sort:",id:"By ID",color:"By colour"},templates:{amsHolderSmall:{label:"AMS holder — small (74 × 33 mm)",hint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},amsHolderLarge:{label:"AMS holder — large (75 × 55 mm)",hint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},box40x30:{label:"Box label (40 × 30 mm)",hint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},box:{label:"Box label (62 × 29 mm)",hint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"EU sheet stock; 21 labels per A4 page."},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"US sheet stock; 30 labels per Letter page."}}},addSpool:"Add Spool",editSpool:"Edit Spool",copySpool:"Copy 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",storageLocation:"Storage Location",storageLocationPlaceholder:"e.g. Shelf A, Drawer 1",openInInventory:"Open in Inventory",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...",category:"Category",categoryPlaceholder:"e.g. Production, Prototype, Client A",categoryNone:"Uncategorized",storageLocationNone:"No location set",lowStockThresholdOverride:"Low-stock threshold (this spool)",lowStockThresholdOverrideHelp:"Leave blank to use the global threshold ({{global}}%).",clearRfid:"Clear RFID Tag",rfidCleared:"RFID tag cleared",archive:"Archive",restore:"Restore",noSpools:"No spools yet. Add your first spool to get started.",noAvailableSpools:"No spools available. Add a spool to your inventory or unassign one from another slot 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",spoolmanSpools:"Spoolman 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",spoolsPartiallyCreated:"{{created}} of {{total}} spools created (some failed)",spoolCreated:"Spool created",spoolUpdated:"Spool updated",spoolDeleted:"Spool deleted",deepLinkSpoolNotFound:"Spool not found",deepLinkFetchFailed:"Could not load spool — try again",spoolArchived:"Spool archived",spoolRestored:"Spool restored",kProfileSaveFailed:"K-profile settings could not be saved",syncWeightSpoolNotFound:"Spool not found — it may have been deleted",syncWeightSpoolmanUnreachable:"Spoolman is unreachable — try again later",syncWeightFailed:"Failed to sync weight",spoolmanUnreachable:"Spoolman is not reachable — please try again later",deleteSpoolNotFound:"Spool not found — it may have already been deleted",deleteFailed:"Failed to delete spool",archiveSpoolNotFound:"Spool not found — it may have already been deleted",archiveFailed:"Failed to archive spool",restoreSpoolNotFound:"Spool not found — it may have already been deleted",restoreFailed:"Failed to restore spool",saveFailed:"Failed to save changes",tagClearFailed:"Failed to clear tag",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",extraColorsLabel:"Extra colors",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"Paste 2 to 8 hex stops, separated by commas. Renders as a gradient.",extraColorsInvalid:"Ignored invalid hex: {{tokens}}",colorEffectLabel:"Effect",colorEffect:{none:"None",sparkle:"Sparkle",wood:"Wood",marble:"Marble",glow:"Glow",matte:"Matte",silk:"Silk",galaxy:"Galaxy",rainbow:"Rainbow",metal:"Metal",translucent:"Translucent",gradient:"Gradient",dualColor:"Dual Color",triColor:"Tri Color",multicolor:"Multicolor"},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",resetUsage:"Reset usage to 0",resetUsageTooltip:"Zero the consumed-grams counter for this spool",resetUsageConfirm:"Reset this spool's consumed-grams counter to 0? Future prints will track from zero again. The spool itself, its remaining weight calculation, and your settings are not changed.",resetAllUsage:"Reset all spool usage",resetAllUsageTooltip:"Zero the consumed-grams counter on every spool",resetAllUsageConfirm:'Reset the consumed-grams counter to 0 on all {{count}} spools (archived ones included)? This clears the "Total Consumed" stat so future prints track from zero. Spools and remaining weights are not changed.',usageReset:"Spool usage reset to 0",allUsageReset:"Reset {{count}} spool(s)",resetUsageFailed:"Failed to reset spool usage",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?',spoolmanFilamentCatalog:"Spoolman Filament Catalog",pickFromSpoolmanCatalog:"Pick from Spoolman catalog…",spoolmanFilamentSelected:"Filament selected from Spoolman catalog",spoolmanFilamentUnlinked:"Filament catalog link cleared",noSpoolmanFilaments:"No filaments found in Spoolman catalog",spoolmanFilamentColorSwatch:"Filament color",spoolWeightManagedBySpoolman:"Empty spool weight is managed per filament type in Spoolman",spoolmanCatalogLoadFailed:"Failed to load Spoolman filament catalog"},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",slotEmpty:"Empty",emptySlotReset:"No filament assigned",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:{includesEncryptionKey:"Local backups include the MFA encryption key file (DATA_DIR/.mfa_encryption_key) so a backup ZIP is self-contained. Treat the ZIP as sensitive — anyone with the file can decrypt the OIDC client secrets and TOTP secrets stored inside.",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:"Git 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.",repoIsPrivate:"Repository is private — safe to back up to.",repoIsPublicWarning:"Repository is PUBLIC. Bambuddy backups include MQTT credentials, Home Assistant tokens, Prometheus tokens, your Bambu Cloud email, and printer access codes via K-profiles. Saving is blocked until you make the repository private in your provider's settings.",repoVisibilityUnknown:"Could not determine repository visibility. Bambuddy refuses to back up to anything not confirmed private; saving will be blocked.",repositoryUrl:"Repository URL",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"Allow insecure HTTP",allowInsecureHttpHint:"Enable for self-hosted instances on private networks without TLS",personalAccessToken:"Personal Access Token",tokenSaved:"(saved)",enterNewToken:"Enter new token to update",tokenHint:"Fine-grained token with Contents read/write permission",branch:"Branch",provider:"Git Provider",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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."},queueForceColorMatch:{title:"Force color match",description:"Refuse to dispatch onto a printer that does not have the exact filament type and color loaded. Off by default — without this, the queue uses model-only matching and may pick a printer with the wrong color loaded."},tailscaleDisabled:{title:"Tailscale integration",description:"Enable to mark this VP as exposed over Tailscale. Shows the host's Tailscale address so you know which IP to paste into the slicer. The CA-import step is unchanged — this toggle has no effect on certificates."},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"},archiveNameSource:{title:"Archive name source",description:'Choose how new archives are named when files arrive via the virtual printer. "Metadata" uses the slicer-embedded title from the 3MF (default). "Filename" uses the filename Bambu Studio sent over FTP — handy if you renamed the job in the "send to printer" dialog.',metadata:"Metadata",filename:"Filename"},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",copyFailed:"Failed to copy — try selecting the text manually",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",autoOffAfterDrying:"Auto Off After Drying",autoOffAfterDryingDescription:"Turn off when AMS drying completes",delayAfterDryingMinutes:"Drying delay (minutes)",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.
  10. Use multiplier 0.001 for mW→W, 1000 for kW→W.`,mqttEnergyHint:`JSON path extracts value from JSON payload. Leave empty for raw values.
  11. Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh.`,mqttStateHint:`JSON path extracts value from JSON payload. Leave empty for raw values.
  12. 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",inventoryAlerts:"Inventory Alerts",stockReorderAlert:"Reorder Alert",stockReorderAlertDescription:"SKU has reached its reorder point",stockBreakAlert:"Stock Break Alert",stockBreakAlertDescription:"Stock will run out before replenishment arrives",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)",eventPriority:{sectionTitle:"ntfy Priority",helpNtfy:"Pick a priority for each enabled event. ntfy uses these to escalate alerts (sound, visibility, push behavior). Levels not set here use the ntfy server default.",min:"Min",low:"Low",default:"Default",high:"High",urgent:"Urgent"},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:"Git 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",plateReady:"Plate ready: {{name}}",plateReadyLabel:"Plates ready to clear",plateClearAction:"Clear",plateClearedToast:"Plate marked as cleared",plateClearFailed:"Could not mark plate as cleared"},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!",assignPendingInsert:"Assigned. Slot will configure when you insert the spool.",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",incompleteDataWarning:"Tag written with incomplete Spoolman data"},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."},makerworld:{title:"MakerWorld",description:"Paste a MakerWorld model URL to import and print it directly from Bambuddy — without leaving for the Bambu Handy app.",pasteUrlHeader:"Import from MakerWorld",pasteUrlPlaceholder:"https://makerworld.com/en/models/… or paste any MakerWorld link",resolveButton:"Resolve",signInRequiredTitle:"Bambu Cloud sign-in required to download",signInRequiredBody:"You can browse model details anonymously, but MakerWorld requires a Bambu Cloud account to download 3MF files.",openCloudSettings:"Open Cloud settings",untitledModel:"Untitled model",byCreator:"by {{name}}",downloadsCount:"{{count}} downloads",licensePrefix:"License",alreadyImported:"Already in library",openOnMakerworld:"Open on MakerWorld",alreadyInLibrary:"This model is already in your library — find it in File Manager → MakerWorld",importSuccess:"Imported {{filename}} — saved to File Manager → MakerWorld",platesHeader:"Plates ({{count}})",plateDefaultName:"Plate {{n}}",materialCount:"{{count}} filaments",amsRequired:"AMS required",slicedFor:"Sliced for {{printer}}",alsoCompatible:"Also marked compatible: {{printers}}",importToLibrary:"Save",sliceIn:"Save & Slice in {{slicer}}",disclaimer:"MakerWorld integration uses community-documented API endpoints. Bambuddy is not affiliated with or endorsed by MakerWorld or Bambu Lab.",lastImportSuccess:"Imported to your library",lastImportAlreadyInLibrary:"Already in your library",viewInLibrary:"View in File Manager",openInBambuStudio:"Open in Bambu Studio",openInOrcaSlicer:"Open in OrcaSlicer",importTo:"Import to file manager",recentImportsHeader:"Recent imports",phaseResolving:"Resolving",phaseDownloading:"Downloading",folderAuto:"MakerWorld (default)",importAll:"Import all",importAllProgress:"Importing {{current}}/{{total}}",openGallery:"Open image gallery",galleryPrev:"Previous image",galleryNext:"Next image",deleteImport:"Remove from library",importDeleting:"Removing…",importDeleted:"Removed from library",confirmDelete:"Remove {{filename}} from the library? This deletes the local file but the plate can be re-imported from MakerWorld.",errors:{resolveFailed:"Could not resolve that MakerWorld URL.",downloadFailed:"Download failed. Please try again.",deleteFailed:"Could not remove the file from the library."}},gcodeViewer:{back:"Back",backToArchives:"Back to Print Archives",backToFiles:"Back to File Manager"},libraryTrash:{title:"Trash",headerButton:"Trash",headerTooltip:"View files moved to the trash",backToFiles:"Back to File Manager",subtitleAdmin:"Deleted files stay here for {{days}} days, then auto-delete. This view shows trashed files for all users.",subtitleUser:"Deleted files stay here for {{days}} days, then auto-delete.",loading:"Loading trash…",loadError:"Could not load the trash.",empty:"The trash is empty.",summary:"{{count}} files · {{size}}",emptyTrash:"Empty trash",restore:"Restore",purgeNow:"Delete now",autoPurgeIn:"Auto-deletes in {{when}}",days:"days",retentionLabel:"Auto-delete after",selectAll:"Select all",selectOne:"Select {{filename}}",selectionCount:"{{count}} selected",bulkRestore:"Restore selected",bulkPurge:"Delete selected",col:{filename:"File",folder:"Folder",size:"Size",deleted:"Moved to trash",autoPurge:"Auto-deletes",owner:"Owner",actions:"Actions"},confirm:{purgeTitle:"Delete permanently?",purgeBody:"{{filename}} will be deleted from disk and cannot be restored.",emptyTitle:"Empty the trash?",emptyBody:"All {{count}} files will be deleted from disk. This cannot be undone.",bulkPurgeTitle:"Delete selected files permanently?",bulkPurgeBody:"The {{count}} selected files will be deleted from disk and cannot be restored.",cta:"Delete permanently"},toast:{restored:"File restored.",restoreFailed:"Could not restore the file.",purged:"File deleted permanently.",purgeFailed:"Could not delete the file.",emptied:"Deleted {{count}} file(s) from trash.",emptyFailed:"Could not empty the trash.",retentionSaved:"Auto-delete set to {{days}} days.",retentionFailed:"Could not save retention setting.",bulkRestored:"Restored {{count}} file(s).",bulkPurged:"Deleted {{count}} file(s)."}},libraryPurge:{title:"Purge old files",headerButton:"Purge old",headerTooltip:"Bulk-move old files to trash",description:"Sweep old files out of your library in one shot. Files with a print history are aged by their last-printed date; files that were never printed are aged by their upload date.",ageLabel:"Move files older than",days:"days",includeNeverPrinted:"Include files that have never been printed",effectsTitle:"What happens when you click Purge",effect1:"Matching files are moved to Trash — they are not deleted from disk yet.",effect2:"You can restore them from Trash at any time until the retention window expires.",effect3:"After retention, the trash sweeper permanently removes them from disk.",effect4:"Files in external (linked) folders are skipped — Bambuddy never deletes bytes it does not own.",previewLoading:"Checking how many files match…",previewFailed:"Could not preview the purge.",previewSummary:"{{count}} files · {{size}} would move to trash",andMore:"…and {{count}} more",warning:"Trashed files still count against storage until the retention window expires. Empty the Trash afterwards to free disk immediately.",confirmCta:"Move {{count}} to trash",purging:"Moving to trash…",toast:{success:"Moved {{count}} file(s) to trash.",failed:"Could not purge files."}},libraryAutoPurge:{enableLabel:"Auto-purge old files",enableDescription:"Runs the admin purge once per day. Files go to Trash first — they are not deleted immediately.",ageLabel:"Auto-purge files older than",ageDescription:"Minimum 7 days, maximum 10 years. Uses the same age rule as the manual Purge button.",days:"days",includeNeverPrinted:"Include files that have never been printed",saveFailed:"Could not save auto-purge settings."},archivePurge:{headerButton:"Purge old",headerTooltip:"Bulk-delete old archives",title:"Purge old archives",description:"Clear out old print history. Each archive is aged by its most recent print completion — reprinting an archive refreshes its age, so active work is never purged.",ageLabel:"Delete archives not printed in the last",days:"days",effectsTitle:"What happens when you click Purge",effect1:"Each matching archive is hidden from the listings and its files are removed from disk (3MF, thumbnail, timelapse, source 3MF, F3D design file, photos).",effect2:"The archive row stays in the database so Quick Stats keeps the filament, time, cost, and energy contribution — same as the single-archive delete default.",effect3:'Tick "Also remove from statistics" below to drop the Quick Stats contribution too (matches the single-archive delete option). That path is irreversible.',effect4:"Reprinting an archive refreshes its age clock, so archives you still use are safe.",purgeStatsLabel:"Also remove from statistics",purgeStatsHint:"Drops the matching archives from Quick Stats (filament, time, cost, energy). Without this, Quick Stats keeps every contribution and only the files leave disk.",previewLoading:"Checking how many archives match…",previewFailed:"Could not preview the purge.",previewSummary:"{{count}} archives · {{size}} would be removed",andMore:"…and {{count}} more",warning:"Files are removed from disk and cannot be restored. Download or favourite anything you want to keep before continuing.",confirmCta:"Remove {{count}} archive(s)",purging:"Removing…",toast:{success:"Removed {{count}} archive(s).",failed:"Could not purge archives."}},archiveAutoPurge:{enableLabel:"Auto-purge old archives",enableDescription:"Once per day, hides archives from the listings and removes their files from disk when they have not been printed within the threshold. Reprinting an archive resets the clock.",ageLabel:"Auto-delete archives not printed in the last",ageDescription:"Minimum 7 days, maximum 10 years. Based on the most recent print completion — reprinting an archive refreshes its age. Removes the 3MF, thumbnail, timelapse, source 3MF, F3D, and photos.",days:"days",purgeStatsLabel:"Also remove from statistics",purgeStatsDescription:"When enabled, the daily sweeper also drops each purged archive from Quick Stats (filament, time, cost, energy). Default off — Quick Stats keeps the contribution, only the files leave disk.",runNow:"Purge archives now",saveFailed:"Could not save auto-purge settings."},cameraTokens:{title:"Camera API Tokens",navTitle:"Camera API tokens",description:"Long-lived tokens for embedding the camera stream into Home Assistant, Frigate, kiosks, or any other tool that needs a stable URL. Each token is camera-stream-only and can be revoked at any time.",loading:"Loading…",confirmRevoke:{title:"Revoke this token?",body:'Any device using "{{name}}" will lose access immediately. This cannot be undone.',cancel:"Cancel",confirm:"Revoke"},create:{title:"Create new token",nameLabel:"Token name",namePlaceholder:"e.g. Home Assistant",daysLabel:"Days until expiry",submit:"Create",hint:"Maximum lifetime is 365 days. The token value is shown only once on creation — copy it now."},created:{title:"Token created — copy it now",warning:"This is the only time this token will be visible. After you close this dialog you can never view it again.",copy:"Copy",dismiss:"I've saved it"},list:{myTitle:"My tokens",allTitle:"All users (admin view)",empty:"No tokens yet.",name:"Name",owner:"Owner",prefix:"Prefix",created:"Created",expires:"Expires",lastUsed:"Last used",revoke:"Revoke",expired:"Expired"},toast:{created:"Token created",createFailed:"Failed to create token",revoked:"Token revoked",revokeFailed:"Failed to revoke token",loadFailed:"Failed to load tokens",copied:"Copied to clipboard",copyFailed:"Copy failed — select and copy manually"}},forecast:{title:"Forecast",noSpools:"No active spools found. Add spools to your inventory to see forecast data.",noUsageData:"No usage data available — cannot project stock timeline.",sku:"SKU",material:"Material",stock:"Stock",dailyRate:"Rate",daysLeft:"Days Left",emptyBy:"Empty By",reorderBy:"Reorder By",actions:"Actions",trend:"Trend",estimated:"Est.",noData:"No data",timeframe:"Timeframe",chartTitle:"Projected Stock — Top 5 Materials",dashedLinesROP:"Dashed lines = reorder points",stockLevel:"Stock Level",reorderPoint:"Reorder Point",safetyMargin:"Safety Margin",trendLegend:"Trend (history-based, 95% service level)",estimatedLegend:"Estimated (weight delta)",noDataLegend:"No data",ropLabel:"ROP",ssLabel:"SS",safetyStockLegend:"Safety stock",stockArrivalLegend:"Stock arrival",stockoutLegend:"Stockout",alertCount_one:"{{count}} alert",alertCount_other:"{{count}} alerts",order:"Order",save:"Save",cancel:"Cancel",settingsSaved:"Settings saved",failedSaveSettings:"Failed to save settings",globalLeadTimeSaved:"Global lead time saved",globalLeadTime:"Global lead time",globalLeadTimeHint:"Global lead time floor — used in reorder point calculation for all SKUs",skuLeadTimeOverride:"SKU Lead Time Override",skuLeadTimeHint:"0 = use global lead time. Set >0 to override for this SKU.",safetyMarginLabel:"Safety Margin",effectiveLeadTime:"Effective Lead Time",effectiveLeadTimeHint:"max(global {{global}}d, SKU {{sku}}d)",reorderPointHint:"d̄ × LT + safety margin — order when stock hits this level",safetyMarginHint:"Statistical safety stock (z=1.65 × σ × √LT) + user-defined buffer",safetyMarginHintDays:"Buffer added on top of statistical safety stock.{{approx}}",safetyMarginHintDaysApprox:" ≈ {{g}}g at current rate.",safetyMarginHintG:"Fixed weight buffer added on top of statistical safety stock.{{approx}}",safetyMarginHintGApprox:" ≈ {{days}}d at current rate.",individualSpools:"Individual spools",labelWeight:"Label",spoolCount_one:"{{count}} spool",spoolCount_other:"{{count}} spools",stockBreakRisk:"Stock break risk",stockBreakDetail:"{{days}}d remaining, lead time {{lt}}d.",stockBreakBefore:"Stock break before replenishment",reorderNow:"Reorder now",reorderTriggerPassed:"Trigger date {{date}} has passed.",shoppingList:"Shopping List",shoppingListItems_one:"({{count}} item)",shoppingListItems_other:"({{count}} items)",shoppingListEmpty:"Shopping list is empty. Click the cart icon on any row to add items.",addToCart:"Add to shopping list",alertsSnoozed:"Mute alerts for this SKU",alertsEnabled:"Unmute alerts for this SKU",addedToCart:"Added to shopping list",failedAddItem:"Failed to add item",listView:"List",logisticsView:"Logistics",qty:"Qty",weight:"Weight",leadTime:"Lead Time",expectedRestock:"Expected Restock",status:"Status",note:"Note",pending:"Pending",purchased:"Purchased",received:"Received",markPurchased:"Mark as purchased",markReceived:"Mark as received — adds spools to Stock inventory",resetToPending:"Reset to pending",remove:"Remove",clearAll:"Clear all",downloadCsv:"CSV",addToCartTitle:"Add to Shopping List",byQuantity:"By Quantity",byDuration:"By Duration",numberOfSpools:"Number of spools",lastHowManyDays:"Should last how many days?",noUsageQty:"No usage data — quantity set to 1.",noteOptional:"Note (optional)",notePlaceholder:"e.g. for project X, urgent…",addNSpools_one:"Add {{count}} spool",addNSpools_other:"Add {{count}} spools",onArrival:"On Arrival",stockBreakIn:"Stock break in {{days}}d.",stockRunsOutBefore:"Stock runs out before the {{lt}}d lead time elapses.",atRate:"At {{rate}}g/day you need",moreSpools_one:"{{count}} more spool",moreSpools_other:"{{count}} more spools",bridgeGap:"to bridge the gap.",noReadAccess:"You do not have permission to view inventory forecasts.",noWriteAccess:"You do not have permission to modify forecast settings."}},epe={nav:{printers:"Drucker",archives:"Archiv",queue:"Druckwarteschlange",stats:"Statistiken",profiles:"Profile",maintenance:"Wartung",projects:"Projekte",inventory:"Filament",files:"Dateimanager",makerworld:"MakerWorld",notifications:"Benachrichtigungen",settings:"Einstellungen",system:"System",collapseSidebar:"Seitenleiste einklappen",expandSidebar:"Seitenleiste ausklappen",update:"Aktualisieren",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",errorLoading:"Fehler beim Laden",retry:"Erneut versuchen",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"},toolbar:{filters:"Filter",view:"Ansicht",actions:"Aktionen"},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:"Hoher Durchfluss",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",connectionFailedNotAdded:"Keine Verbindung zum Drucker möglich. Prüfen Sie IP-Adresse, Seriennummer und Zugangscode und stellen Sie sicher, dass der Nur-LAN-Modus aktiv ist. Der Drucker wurde nicht hinzugefügt.",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",loadInitiated:"Filament wird geladen…",unloadInitiated:"Filament wird entladen…",failedToLoad:"Filament konnte nicht geladen werden",failedToUnload:"Filament konnte nicht entladen werden"},connection:{connected:"Verbunden",offline:"Offline"},plateStatus:{markCleared:"Platte als freigegeben markieren",cleared:"Platte freigegeben",notCleared:"Platte nicht freigegeben",inUse:"Platte in Benutzung"},queue:{inQueue:"{{count}} Druck in Warteschlange",inQueue_plural:"{{count}} Drucke in Warteschlange"},controls:"Steuerung",rfid:{reread:"RFID neu lesen"},ams:{load:"Laden",unload:"Entladen"},bedJog:{title:"Druckbett bewegen",bed:"Bett",step:"Schritt (mm)",up:"Platte hoch",down:"Platte runter",disabledWhilePrinting:"Während des Drucks deaktiviert",notHomedTitle:"Drucker ist nicht referenziert",notHomedMessage:"Der Drucker wurde seit dem letzten Druck nicht referenziert. Führen Sie zuerst die automatische Referenzfahrt aus (parkt den Werkzeugkopf und referenziert dann X, Y und Z) oder bewegen Sie trotzdem — die Software-Endschalter werden dabei umgangen.",homeZ:"Automatische Referenzfahrt",moveAnyway:"Trotzdem bewegen",homingStarted:"Drucker wird automatisch referenziert…"},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",haToggleTitle:'"{{name}}" umschalten',haToggleMessage:"Home-Assistant-Entität {{entity}} umschalten? Das kann die Stromversorgung ausschalten, falls sie gerade an ist.",haToggleWarning:'WARNUNG: "{{name}}" druckt gerade! Umschalten von {{entity}} kann die Stromversorgung trennen und den Druck abbrechen. Fortfahren?',haToggleButton:"Umschalten"},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:"Aktualisieren",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",printLog:"Druckprotokoll",goToProject:"Zum Projekt: {{name}}",addToProject:"Zu Projekt hinzufügen",removeFromProject:"Aus Projekt entfernen",loading:"Laden...",noProjectsAvailable:"Keine Projekte verfügbar",searchProjects:"Projekte suchen…",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"},platePicker:{title:"Platte zur Vorschau auswählen",hint:"Dieses Archiv enthält mehrere Platten. Wähle eine, um sie im GCode-Viewer zu öffnen.",plateLabel:"Platte {{index}}",objectCount:"{{count}} Objekt",objectCount_plural:"{{count}} Objekte",noGcode:"Dieses Archiv enthält keinen geschnittenen G-Code zur Vorschau. Öffne es zuerst in Bambu Studio zum Slicen."},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}}",runsBadge:"{{count}} Drucke",runsBadgeTitle:"Insgesamt {{count}} Drucke — {{successful}} erfolgreich, {{failed}} fehlgeschlagen. Klicken, um das vollständige Druckprotokoll zu öffnen.",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"},runLog:{title:"Druckprotokoll",modalTitle:"Druckprotokoll — {{name}}",modalTitleFallback:"dieses Archiv",empty:"Für dieses Archiv wurden noch keine Druckereignisse aufgezeichnet.",col:{date:"Datum",status:"Status",duration:"Dauer",filament:"Filament",cost:"Kosten"},status:{completed:"Abgeschlossen",failed:"Fehlgeschlagen",cancelled:"Abgebrochen",stopped:"Gestoppt",skipped:"Übersprungen",printing:"Druckt"}},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",deletePurgeStats:"Diesen Druck auch aus den Quick Stats entfernen (Filament, Zeit, Kosten, Energie)",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",clearPlateSuccess:"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…",awaitingPrinter:"Warte auf Drucker…",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:"Statistiken",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",security:"Sicherheit"},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.",advanced:"Erweitert",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:"Aktualisierungen",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",spoolmanAmsSyncButton:"Spoolman-Gewichte vom AMS synchronisieren",spoolmanAmsSyncTitle:"Spoolman-Spulengewichte vom AMS synchronisieren",spoolmanAmsSyncMessage:"Dabei werden alle Spoolman-Spulengewichte anhand der aktuellen AMS-Füllstandswerte der verbundenen Drucker aktualisiert. Die Drucker müssen online sein.",spoolmanAmsSyncing:"Synchronisiere...",spoolmanAmsSyncSuccess:"{{synced}} Spule(n) synchronisiert, {{skipped}} übersprungen",spoolmanAmsSyncError:"Synchronisierung der Spoolman-Gewichte vom AMS fehlgeschlagen",spoolmanAmsSyncErrorUnreachable:"Synchronisierung fehlgeschlagen (Spoolman nicht erreichbar)",spoolmanAmsSyncErrorNotConfigured:"Synchronisierung fehlgeschlagen (Spoolman nicht konfiguriert)",spoolmanNotConfigured:"Spoolman nicht konfiguriert",spoolmanFilamentCatalogTitle:"Spoolman-Filamentkatalog",spoolmanFilamentCatalogDesc:"Filamentnamen und Leergewichte aus deiner Spoolman-Instanz. Name und Spulengewicht sind hier editierbar; alle anderen Eigenschaften werden direkt in Spoolman verwaltet.",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",cloudAccess:"Cloud-Zugriff erlauben",cloudAccessDescription:"Liest Bambu-Cloud-Presets und -Filamente in Ihrem Namen. Erfordert eine Anmeldung in Bambu Cloud.",cloudBadge:"Cloud",updateEnergyCost:"Strompreis aktualisieren",updateEnergyCostDescription:"Erlaubt diesem Schlüssel, einen neuen Strompreis pro kWh an /settings/electricity-price zu senden. Nützlich für Home-Assistant-Automatisierungen mit dynamischen Tarifen (Tibber, Octopus usw.). Dies ist das einzige Einstellungsfeld, das per API-Schlüssel schreibbar ist.",energyCostBadge:"Energie",legacyKey:"Alt",legacyKeyTooltip:"Wurde vor der nutzerbezogenen Eigentümerschaft erstellt; neu erstellen, um Cloud-Zugriff zu nutzen",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:"Versetzter Start",staggeredStartDescription:"Standard-Gruppengröße und -Intervall beim Staffeln von Mehrdrucker-Batchstarts. Pro Batch im Druck-Dialog überschreibbar.",plateClear:"Druckplatte-Bestätigung",requirePlateClear:"Druckplatte-Bestätigung erforderlich",requirePlateClearDescription:'Wenn aktiviert, wartet der Scheduler auf eine Druckplatten-Bestätigung pro Drucker, bevor geplante Drucke auf Druckern mit abgeschlossenen Aufträgen gestartet werden. Wenn dies deaktiviert ist, werden auch das Druckplatten-Status-Badge und die Schaltfläche "Druckplatte als freigegeben markieren" auf den Druckerkarten ausgeblendet.',gcodeInjection:"G-Code-Injektion",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:"Gruppengröße",staggerGroupSizeHelp:"Anzahl gleichzeitig zu startender Drucker pro Gruppe",staggerInterval:"Intervall (Minuten)",staggerIntervalHelp:"Verzögerung zwischen Gruppenstart",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",passwordRequirements:"Mindestens 8 Zeichen, davon ein Großbuchstabe, ein Kleinbuchstabe, eine Ziffer und ein Sonderzeichen.",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",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev haben bekannte CLI-Bugs, die das Slicen vieler von BambuStudio erstellter 3MF-Dateien blockieren — siehe Upstream-Issues #12426 (Segfault bei bemalten Multi-Extruder-Dateien) und #13386 (zu strikte Parameter-Range-Validierung). Bis die Upstream-Fixes verfügbar sind, wird Bambu Studio empfohlen.",useSlicerApi:"Slicer-API verwenden",useSlicerApiDescription:'Wenn aktiv, öffnen "Slice"-Aktionen das in-App Slicer-Modal und rufen den Slicer-API-Sidecar. Aus (Standard): Übergabe an den Desktop-Slicer per URI-Schema.',slicerCard:"Slicer",orcaslicerApiUrl:"OrcaSlicer Sidecar-URL",bambuStudioApiUrl:"Bambu Studio Sidecar-URL",slicerApiUrlDescription:"URL des Slicer-API-Sidecar-Containers. Leer lassen, um die SLICER_API_URL- bzw. BAMBU_STUDIO_API_URL-Umgebungsvariablen zu nutzen.",slicerBundles:{title:"Slicer-Bundles",description:'Importiere ein Drucker-Voreinstellungspaket (.bbscfg), das aus BambuStudio exportiert wurde (Datei → Exportieren → Voreinstellungspaket exportieren → "Drucker-Voreinstellungspaket"). Nach dem Import können Slice-Anfragen Voreinstellungen aus dem Bundle per Name auswählen, ohne das JSON-Profil-Trio erneut hochzuladen.',uploadButton:"Bundle hochladen",uploading:"Hochladen…",loading:"Bundles werden geladen…",empty:"Noch keine Bundles importiert.",summary:"{{processCount}} Prozess · {{filamentCount}} Filament-Voreinstellungen",delete:"Löschen",uploadSuccess:"{{name}} importiert",uploadError:"Bundle-Upload fehlgeschlagen: {{message}}",deleteSuccess:"Bundle entfernt",deleteError:"Löschen des Bundles fehlgeschlagen: {{message}}",confirmDeleteTitle:"Dieses Bundle entfernen?",confirmDeleteMessage:'Slice-Anfragen, die "{{name}}" referenzieren, schlagen fehl, bis das Bundle erneut importiert wird.'},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 8 Zeichen lang sein",passwordNeedsUppercase:"Passwort muss mindestens einen Großbuchstaben enthalten",passwordNeedsLowercase:"Passwort muss mindestens einen Kleinbuchstaben enthalten",passwordNeedsDigit:"Passwort muss mindestens eine Ziffer enthalten",passwordNeedsSpecial:"Passwort muss mindestens ein Sonderzeichen enthalten",enterGroupName:"Bitte geben Sie einen Gruppennamen ein",settingsSaved:"Einstellungen gespeichert",noPermissionUpdate:"Sie haben keine Berechtigung, Einstellungen zu ändern",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",material:"Material",spoolWeight:"Spulengewicht",color:"Farbe",updateSpoolWeight:"Spulengewicht aktualisieren",filamentUpdated:"Filament aktualisiert",filamentUpdateFailed:"Filament konnte nicht aktualisiert werden",filamentUpdateInvalid:"Ungültige Filamentdaten",keepExistingSpoolWeight:"Altes Gewicht für bestehende Spulen behalten",keepExistingSpoolWeightDesc:"Bereits erstellte Spulen dieses Filamenttyps behalten das alte Leergewicht. Neue Spulen nutzen den neuen Wert.",applyToAllSpools:"Auf alle Spulen anwenden",applyToAllSpoolsDesc:"Alle Gewichtsberechnungen für diesen Filamenttyp nutzen sofort das neue Leergewicht."},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:"Synchron.",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)",cameraSnapshotUrl:"Snapshot-URL (optional)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"URL für Einzelbildaufnahmen — wird für Benachrichtigungs-Vorschaubilder, Abschlussfotos, Schicht-Zeitraffer und Plattenerkennung verwendet. Zeitraffer und Plattenerkennung benötigen jeweils eigene drucker-spezifische Schalter — diese URL ist nur die Bildquelle, die sie verwenden, wenn sie aktiv sind. Leer lassen, um Bilder aus dem oben konfigurierten Live-Stream zu verwenden. Nützlich für go2rtc (/api/frame.jpeg) und IP-Kameras mit dediziertem Snapshot-Endpunkt.",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:",updateViaHomeAssistant:"Updates werden vom Home Assistant Supervisor verwaltet. Öffne Einstellungen → Add-ons → Bambuddy in Home Assistant, um die neue Version zu installieren.",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.",refreshIcon:"Icon neu laden",removeIcon:"Icon entfernen",iconRefreshed:"Icon aktualisiert.",iconRemoved:"Icon entfernt.",iconFetchFailed:"Icon konnte von der Anbieter-URL nicht geladen werden.",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:"Bereiche",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",emailClaim:"E-Mail-Claim",emailClaimDesc:"JWT-Claim für die E-Mail-Identität. Für Azure Entra ID 'preferred_username' oder 'upn' verwenden (sendet kein email_verified). Nur vertrauenswürdige Claim-Namen verwenden.",emailClaimPlaceholder:"E-Mail",emailClaimCustomClaimAutoLinkWarning:"Benutzerdefinierte Claims sind für die Auto-Verknüpfung nur sicher, wenn der Wert vom Mandanten verwaltet wird (z. B. Azure Entra ID upn / preferred_username). Aktiviere Auto-Verknüpfung nicht, wenn dein IdP Benutzern erlaubt, diesen Claim selbst zu setzen.",requireEmailVerified:"E-Mail-Verifizierung erforderlich",requireEmailVerifiedDesc:"E-Mail-Claim nur akzeptieren, wenn der Provider ihn als verifiziert markiert.",requireEmailVerifiedWarning:"Warnung: E-Mail wird auch ohne Verifizierung akzeptiert. Nur bei vertrauenswürdigen Providern verwenden.",requireEmailVerifiedAutoLink:"Auto-Verknüpfung zuerst deaktivieren, um diese Einstellung zu ändern.",defaultGroup:"Standardgruppe",defaultGroupDesc:"Gruppe, der automatisch erstellte Benutzer zugewiesen werden. Fallback auf Viewers, wenn nicht gesetzt.",defaultGroupViewersFallback:"Viewers (Standard)"}},encryption:{title:"MFA-Verschlüsselungsstatus",enabledFromEnv:"At-Rest-Verschlüsselung aktiv (Schlüssel aus Umgebungsvariable MFA_ENCRYPTION_KEY)",enabledFromFile:"At-Rest-Verschlüsselung aktiv (Schlüssel aus dem Datenverzeichnis geladen)",enabledGenerated:"At-Rest-Verschlüsselung aktiv mit automatisch generiertem Schlüssel",notConfigured:"At-Rest-Verschlüsselung nicht konfiguriert",notConfiguredDesc:"TOTP-Geheimnisse und OIDC-Client-Secrets werden im Klartext gespeichert. Setze MFA_ENCRYPTION_KEY oder starte Bambuddy mit beschreibbarem Datenverzeichnis neu, damit ein Schlüssel automatisch erzeugt wird.",allEncrypted:"Alle MFA-Geheimnisse sind verschlüsselt gespeichert.",legacyRowsLabel:"Klartext-Zeilen (Altbestand)",encryptedRowsLabel:"Verschlüsselte Zeilen",legacyRowsWarning:"{{count}} Klartext-Zeile(n) erkannt. Den OIDC-Provider neu speichern oder den Authenticator des Benutzers neu einrichten, um die Daten verschlüsselt abzulegen.",backupHint:"Der automatisch erzeugte Schlüssel liegt unter DATA_DIR/.mfa_encryption_key und wird in lokalen Backup-ZIPs mitgesichert. Backups sicher aufbewahren oder MFA_ENCRYPTION_KEY explizit setzen.",decryptionBrokenTitle:"Verschlüsselungsschlüssel fehlt",decryptionBrokenError:"{{count}} verschlüsselte Datensätze können nicht entschlüsselt werden, weil der Schlüssel nicht mehr verfügbar ist. Den vorherigen MFA_ENCRYPTION_KEY oder DATA_DIR/.mfa_encryption_key wiederherstellen.",migrationErrorWarning:"{{count}} Legacy-Eintrag/Einträge konnten beim Start nicht verschlüsselt werden. Prüfen Sie die Server-Logs und starten Sie Bambuddy neu."}},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:"Thema",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...",rememberMe:"Angemeldet bleiben",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",unavailable:"Kamera nicht verfügbar",diagnose:{button:"Diagnose",modalTitle:"Kamera-Diagnose",running:"Diagnose läuft...",runFailed:"Diagnose konnte nicht ausgeführt werden: {{error}}",retry:"Erneut ausführen",stage:{tcp_reachable:"Netzwerk-Erreichbarkeit",first_frame:"Bilderfassung",live_stream_active:"Live-Stream aktiv"},summary:{all_ok:"Kamera funktioniert. Die Diagnose hat alle Phasen erfolgreich abgeschlossen.",live_stream_active_healthy:"Kamera streamt gerade mit aktuellen Bildern — kein Test nötig.",printer_unreachable:"Drucker ist nicht erreichbar. Prüfe IP-Adresse, Netzwerkverbindung und ob der Drucker eingeschaltet ist.",camera_port_closed:"Drucker ist erreichbar, aber der Kamera-Port ist geschlossen. Stelle sicher, dass LAN-Modus und Entwicklermodus in den Druckereinstellungen aktiviert sind.",no_frame:"Verbindung zur Kamera hergestellt, aber keine Bilder empfangen. Versuche es erneut oder prüfe, ob die Kamera in den Druckereinstellungen aktiviert ist.",unknown_failure:"Kamera-Diagnose aus unbekanntem Grund fehlgeschlagen. Prüfe das Support-Log für Details."},meta:{protocol:"Protokoll",port:"Port",profile:"Profil"}}},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",ldapProvisioned:'LDAP-Benutzer „{{username}}" bereitgestellt'},modal:{createUser:"Benutzer erstellen",editUser:"Benutzer bearbeiten",cancel:"Abbrechen",creating:"Erstellen...",saving:"Speichern...",saveChanges:"Änderungen speichern",advancedAuthSubtitle:"mit erweiterter Authentifizierung",tabsAriaLabel:"Benutzerquelle",localTab:"Lokal",ldapTab:"LDAP",ldapSearchLabel:"Verzeichnis durchsuchen",ldapSearchPlaceholder:"Benutzername, Name oder E-Mail eingeben...",ldapMinChars:"Mindestens 2 Zeichen für die Suche eingeben",ldapTypeToSearch:"Tippen, um das LDAP-Verzeichnis zu durchsuchen",ldapSearching:"Verzeichnis wird durchsucht...",ldapNoResults:"Keine passenden Benutzer im Verzeichnis",ldapSearchError:"Verzeichnissuche fehlgeschlagen. Bitte LDAP-Server-Status prüfen.",ldapAlreadyProvisioned:"Bereits bereitgestellt",ldapSelectedLabel:"Ausgewählt",ldapProvision:"Benutzer bereitstellen",ldapProvisioning:"Wird bereitgestellt...",ldapErrorProvision:"Bereitstellung fehlgeschlagen. Bitte LDAP-Server-Status prüfen und erneut versuchen."},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-Cloud-Zugriffstoken ein. Konten der Region China müssen diesen Weg nutzen (telefonnummerngebunden — kein E-Mail-Login). Im Wiki steht, wie Sie das Token aus den MakerWorld-Cookies auslesen.",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",collapse:"Einklappen",collapseFoldersByDefault:"Ordner standardmäßig einklappen",expandFoldersByDefault:"Ordner standardmäßig ausklappen",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",noPermissionSlice:"Sie haben keine Berechtigung, Dateien zu slicen",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...",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"URL muss mit http:// oder https:// beginnen",openExternalUrl:"Projekt-URL öffnen",coverImageLabel:"Titelbild",coverImageAlt:"Projekt-Titelbild",coverImageUpload:"Hochladen",coverImageReplace:"Ersetzen",coverImageRemove:"Entfernen",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"},slice:{title:"Modell slicen",action:"Slicen",slicing:"Slicen…",printer:"Drucker-Profil",process:"Prozess-Profil",filament:"Filament-Profil",filamentSlot:"Filament {{index}} – {{type}}",selectPreset:"— Profil auswählen —",loadingPresets:"Profile werden geladen…",analyzingPlateFilaments:"Plattenfilamente werden analysiert…",analyzingPlateFilamentsHint:"Es wird ein Probeschnitt ausgeführt, um die belegten AMS-Slots dieser Platte zu ermitteln. Wird zwischengespeichert — erneutes Öffnen ist sofort.",previewToast:"{{name}} wird analysiert — {{elapsed}}",previewWithProgress:"{{name}} wird analysiert — {{stage}} ({{percent}}%) — {{elapsed}}",notUsedByPlate:"— wird von dieser Platte nicht verwendet",noPresetsForSlot:"Keine Profile verfügbar",presetsLoadFailed:"Profile konnten nicht geladen werden. Importiere sie zuerst unter Einstellungen → Profile.",allPresetsRequired:"Alle Profile müssen ausgewählt sein",bundle:"Slicer-Bundle",bundleNone:"— Keines (Profile einzeln auswählen) —",bundleAllRequired:"Bundle-Prozess und jeder Filament-Slot müssen ausgewählt sein",enqueuing:"Slice-Auftrag wird übermittelt…",queued:"In Warteschlange…",failed:"Slicen fehlgeschlagen. Logs des Slicer-Sidecars prüfen.",startedToast:"{{name}} wird im Hintergrund gesliced…",queuedToast:"Warteschlange: {{name}} — {{elapsed}}",runningToast:"{{name}} wird gesliced — {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}} %) – {{elapsed}}",completedToast:"{{name}} wurde gesliced",failedToast:"Slicen von {{name}} fehlgeschlagen: {{detail}}",tier:{local:"Importiert",cloud:"Cloud",standard:"Standard"},cloud:{notAuthenticated:"In Bambu Cloud anmelden (Einstellungen → Profile → Cloud), um deine Cloud-Profile zu sehen.",expired:"Bambu-Cloud-Sitzung abgelaufen — erneut anmelden, um die Cloud-Profile zu aktualisieren.",unreachable:"Bambu Cloud ist gerade nicht erreichbar. Lokale und Standard-Profile funktionieren weiterhin."},bedType:{label:"Druckbett",auto:"Auto (aus Prozess-Profil)",coolPlate:"Cool Plate",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},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 entfernen?",unlinkConfirmMessage:"Die Spule wird vom Slot entfernt. Die Spulendaten selbst bleiben unverändert.",selectSpool:"Spule auswählen",noUnlinkedSpools:"Keine nicht zugewiesenen Spulen verfügbar",linkSuccess:"Spule erfolgreich zugewiesen",linkFailed:"Spule konnte nicht zugewiesen werden",unlinkSuccess:"Spule erfolgreich entfernt",unlinkFailed:"Spule konnte nicht entfernt werden",linkedSpool:"Zugewiesene Spule",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",subtitle:"Verwalten Sie Ihre Spulen",spoolmanMixedContentTitle:"Spoolman lässt sich nicht über HTTPS laden — Browser blockiert gemischte Inhalte",spoolmanMixedContentBody:"Bambuddy wird über HTTPS ausgeliefert (über deinen Reverse-Proxy), aber deine Spoolman-URL ist nach wie vor HTTP. Browser blockieren gemischte Inhalte aus Sicherheitsgründen, daher kann die eingebettete Spoolman-Oberfläche nicht geladen werden. Spoolman muss ebenfalls über HTTPS erreichbar sein.",spoolmanMixedContentFixReverseProxy:"Stelle Spoolman hinter denselben Reverse-Proxy wie Bambuddy (Traefik / Nginx / Caddy) mit HTTPS und aktualisiere die Spoolman-URL in den Einstellungen auf die neue HTTPS-Adresse.",spoolmanMixedContentFixOpenNewTab:"Als Workaround kannst du Spoolman in einem neuen Tab über HTTP öffnen — gemischte Inhalte werden nur innerhalb eingebetteter Frames blockiert, ein eigener Tab funktioniert weiterhin.",spoolmanOpenInNewTab:"Spoolman in neuem Tab öffnen",labels:{title:"Spulen-Etiketten drucken",selectedCount:"{{count}} ausgewählt",pickSpools:"Wählen Sie, für welche Spulen Etiketten gedruckt werden sollen:",searchPlaceholder:"Name, Marke oder #ID suchen",filterByMaterial:"Material:",allMaterials:"Alle",selectVisible:"Alle sichtbaren auswählen ({{count}})",deselectVisible:"Sichtbare abwählen",clearAll:"Alle entfernen",noSpoolsToShow:"Keine Spulen anzuzeigen. Filter anpassen und erneut versuchen.",noMatches:"Keine Spulen entsprechen der aktuellen Suche oder dem Filter.",printOne:"Etikett für diese Spule drucken",printLabels:"Etiketten drucken…",bulkTitle:"Spulen aus den aktuell angezeigten {{count}} zum Etikettieren auswählen",noSpoolsTitle:"Keine Spulen zum Etikettieren",error:"Etiketten konnten nicht erstellt werden: {{msg}}",sortBy:{label:"Sortieren:",id:"Nach ID",color:"Nach Farbe"},templates:{amsHolderSmall:{label:"AMS-Halter — klein (74 × 33 mm)",hint:"Ein Etikett pro Seite; passt zum druckbaren Etikett aus dem MakerWorld-Modell 752566 (AMS-Filament-Etikettenhalter)."},amsHolderLarge:{label:"AMS-Halter — groß (75 × 55 mm)",hint:"Ein Etikett pro Seite; passt zur Kartoneinleger-Variante des AMS-Filament-Etikettenhalters. Genug Platz für Farbprobe, Marke, Material, ID und QR-Code."},box40x30:{label:"Boxetikett (40 × 30 mm)",hint:"Ein Etikett pro Seite; gängige DK/Brother-Rollengröße, ideal für Filament-Beutel und Lager-Etiketten."},box:{label:"Box label (62 × 29 mm)",hint:"Ein Etikett pro Seite; für Brother PT/QL und Dymo-Kleinetiketten dimensioniert."},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"EU-Bogenformat; 21 Etiketten pro A4-Seite."},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"US-Bogenformat; 30 Etiketten pro Letter-Seite."}}},addSpool:"Spule hinzufügen",copySpool:"Spule kopieren",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:"Jadeweiß, Feuerrot...",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",storageLocation:"Lagerstandort",storageLocationPlaceholder:"z.B. Regal A, Schublade 1",openInInventory:"Im Inventar öffnen",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...",category:"Kategorie",categoryPlaceholder:"z. B. Produktion, Prototyp, Kunde A",categoryNone:"Ohne Kategorie",storageLocationNone:"Kein Lagerort",lowStockThresholdOverride:"Niedrigbestandsschwelle (diese Spule)",lowStockThresholdOverrideHelp:"Leer lassen, um den globalen Schwellenwert ({{global}}%) zu verwenden.",clearRfid:"RFID-Tag löschen",rfidCleared:"RFID-Tag gelöscht",archive:"Archivieren",restore:"Wiederherstellen",noSpools:"Noch keine Spulen. Fügen Sie Ihre erste Spule hinzu.",noAvailableSpools:"Keine Spulen verfügbar. Fügen Sie eine Spule zum Inventar hinzu oder lösen Sie eine aus einem anderen Slot.",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",spoolmanSpools:"Spoolman-Spulen",allMaterials:"Alle Materialien",filterByBrand:"Nach Marke filtern...",showArchived:"Archivierte anzeigen",quickAdd:"Schnellerfassung (Lager)",quantity:"Menge",stock:"Lager",configured:"Konfiguriert",spoolsCreated:"{{count}} Spulen erstellt",spoolsPartiallyCreated:"{{created}} von {{total}} Spulen erstellt (einige fehlgeschlagen)",spoolCreated:"Spule erstellt",spoolUpdated:"Spule aktualisiert",spoolDeleted:"Spule gelöscht",deepLinkSpoolNotFound:"Spule nicht gefunden",deepLinkFetchFailed:"Spule konnte nicht geladen werden — bitte erneut versuchen",spoolArchived:"Spule archiviert",spoolRestored:"Spule wiederhergestellt",kProfileSaveFailed:"K-Profil-Einstellungen konnten nicht gespeichert werden",syncWeightSpoolNotFound:"Spule nicht gefunden — sie wurde möglicherweise gelöscht",syncWeightSpoolmanUnreachable:"Spoolman ist nicht erreichbar — bitte später erneut versuchen",syncWeightFailed:"Gewicht konnte nicht synchronisiert werden",spoolmanUnreachable:"Spoolman ist nicht erreichbar — bitte später erneut versuchen",deleteSpoolNotFound:"Spule nicht gefunden — sie wurde möglicherweise bereits gelöscht",deleteFailed:"Spule konnte nicht gelöscht werden",archiveSpoolNotFound:"Spule nicht gefunden — sie wurde möglicherweise bereits gelöscht",archiveFailed:"Spule konnte nicht archiviert werden",restoreSpoolNotFound:"Spule nicht gefunden — sie wurde möglicherweise bereits gelöscht",restoreFailed:"Spule konnte nicht wiederhergestellt werden",saveFailed:"Änderungen konnten nicht gespeichert werden",tagClearFailed:"Tag konnte nicht gelöscht werden",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",extraColorsLabel:"Zusätzliche Farben",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"2 bis 8 Hex-Stops, durch Kommas getrennt. Wird als Verlauf dargestellt.",extraColorsInvalid:"Ungültige Hex-Werte ignoriert: {{tokens}}",colorEffectLabel:"Effekt",colorEffect:{none:"Keiner",sparkle:"Glitzer",wood:"Holz",marble:"Marmor",glow:"Leuchtend",matte:"Matt",silk:"Seide",galaxy:"Galaxie",rainbow:"Regenbogen",metal:"Metallic",translucent:"Lichtdurchlässig",gradient:"Verlauf",dualColor:"Zweifarbig",triColor:"Dreifarbig",multicolor:"Mehrfarbig"},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",resetUsage:"Verbrauch auf 0 zurücksetzen",resetUsageTooltip:"Den verbrauchten Gramm-Zähler dieser Spule auf null setzen",resetUsageConfirm:"Verbrauchten Gramm-Zähler dieser Spule auf 0 zurücksetzen? Künftige Drucke zählen wieder ab null. Die Spule selbst, ihre Restgewichtsberechnung und Ihre Einstellungen bleiben unverändert.",resetAllUsage:"Verbrauch aller Spulen zurücksetzen",resetAllUsageTooltip:"Den verbrauchten Gramm-Zähler auf jeder Spule auf null setzen",resetAllUsageConfirm:"Verbrauchten Gramm-Zähler auf allen {{count}} Spulen (archivierte eingeschlossen) auf 0 zurücksetzen? Das löscht den Wert „Insgesamt verbraucht“, sodass künftige Drucke wieder ab null gezählt werden. Spulen und Restgewichte bleiben unverändert.",usageReset:"Spulenverbrauch auf 0 zurückgesetzt",allUsageReset:"{{count}} Spule(n) zurückgesetzt",resetUsageFailed:"Zurücksetzen des Spulenverbrauchs fehlgeschlagen",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?',spoolmanFilamentCatalog:"Spoolman-Filamentkatalog",pickFromSpoolmanCatalog:"Aus Spoolman-Katalog wählen…",spoolmanFilamentSelected:"Filament aus Spoolman-Katalog ausgewählt",spoolmanFilamentUnlinked:"Verknüpfung mit Filamentkatalog aufgehoben",noSpoolmanFilaments:"Keine Filamente im Spoolman-Katalog gefunden",spoolmanFilamentColorSwatch:"Filamentfarbe",spoolWeightManagedBySpoolman:"Das Leerspulengewicht wird pro Filamenttyp in Spoolman verwaltet",spoolmanCatalogLoadFailed:"Spoolman-Filamentkatalog konnte nicht geladen werden"},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",slotEmpty:"Leer",emptySlotReset:"Keine Spule zugewiesen",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:"Druckerstarts staffeln",staggerGroupSize:"Gruppengröße",staggerInterval:"Intervall (Min.)",staggerPreview:"{{printers}} Drucker → {{groups}} Gruppen à {{size}}, Start alle {{interval}} Min.",staggerLastGroup:"letzte Gruppe: {{count}}",staggerTotal:"insgesamt: {{minutes}} Min.",staggerToPrinters:"Gestaffelt an {{count}} Drucker senden",gcodeInjection:"Auto-Print G-code einfügen"},backup:{includesEncryptionKey:"Lokale Sicherungen enthalten die MFA-Schlüsseldatei (DATA_DIR/.mfa_encryption_key), damit ein Backup-ZIP selbstkonsistent ist. Behandle das ZIP als sensibel — wer Zugriff auf die Datei hat, kann die darin enthaltenen OIDC-Client-Secrets und TOTP-Geheimnisse entschlüsseln.",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:"Git-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.",repoIsPrivate:"Repository ist privat — Sicherung möglich.",repoIsPublicWarning:"Das Repository ist ÖFFENTLICH. Bambuddy-Backups enthalten MQTT-Zugangsdaten, Home-Assistant-Tokens, Prometheus-Tokens, Ihre Bambu-Cloud-E-Mail-Adresse und über K-Profile auch Drucker-Zugangscodes. Speichern ist blockiert, bis Sie das Repository in den Einstellungen Ihres Anbieters auf privat stellen.",repoVisibilityUnknown:"Die Sichtbarkeit des Repositories konnte nicht bestimmt werden. Bambuddy sichert nur in Repositories, die nachweislich privat sind; Speichern wird blockiert.",repositoryUrl:"Repository-URL",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"Unsicheres HTTP erlauben",allowInsecureHttpHint:"Für selbst gehostete Instanzen in privaten Netzwerken ohne TLS aktivieren",personalAccessToken:"Persönlicher Zugriffstoken",tokenSaved:"(gespeichert)",enterNewToken:"Neuen Token eingeben zum Aktualisieren",tokenHint:"Feingranularer Token mit Lese-/Schreibberechtigung für Inhalte",branch:"Branch",provider:"Git-Anbieter",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"Geplante Backups",scheduledBackupDescription:"Backup-Snapshots automatisch nach Zeitplan erstellen. Ausgabeverzeichnis kann auf einen NAS oder externen Speicher gemountet werden.",frequency:"Frequenz",backupTime:"Zeit",retention:"Aufbewahrung",retentionDescription:"Anzahl der zu behaltenden Backups",outputPath:"Ausgabepfad",outputPathPlaceholder:"Standard: {{path}}",outputPathDescription:"Leer lassen für den Standardort",runNow:"Jetzt ausführen",backupFiles:"Backup-Dateien",noScheduledBackups:"Noch keine Backups",deleteBackup:"Löschen",deleteBackupConfirm:"Diese Backup-Datei löschen?",backupRunning:"Backup läuft...",scheduledBackupComplete:"Backup erfolgreich abgeschlossen",scheduledBackupFailed:"Backup fehlgeschlagen",nextBackup:"Nächstes Backup",backupSize:"Größe",utc:"UTC",defaultPathLabel:"Standard:",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:"Hoher Durchfluss",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."},queueForceColorMatch:{title:"Farbabgleich erzwingen",description:"Druckaufträge nur an Drucker senden, bei denen der genaue Filament-Typ und die genaue Farbe geladen sind. Standardmäßig deaktiviert — ohne diese Option verwendet die Warteschlange nur den Drucker-Modell-Abgleich und wählt möglicherweise einen Drucker mit der falschen Farbe."},tailscaleDisabled:{title:"Tailscale-Integration",description:"Aktivieren, um diesen VP als per Tailscale erreichbar zu markieren. Zeigt die Tailscale-Adresse des Hosts an, damit du weißt, welche IP du im Slicer eintragen musst. Der CA-Import bleibt unverändert — diese Option hat keinen Einfluss auf Zertifikate."},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"},archiveNameSource:{title:"Quelle des Archivnamens",description:'Lege fest, wie neue Archive benannt werden, wenn Dateien über den virtuellen Drucker eintreffen. "Metadaten" verwendet den im 3MF eingebetteten Titel des Slicers (Standard). "Dateiname" nutzt den Dateinamen, den Bambu Studio per FTP gesendet hat — praktisch, wenn der Job im Dialog "Zum Drucker senden" umbenannt wurde.',metadata:"Metadaten",filename:"Dateiname"},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",copyFailed:"Kopieren fehlgeschlagen — bitte Text manuell markieren",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",autoOffAfterDrying:"Automatisch aus nach Trocknung",autoOffAfterDryingDescription:"Ausschalten, wenn AMS-Trocknung abgeschlossen ist",delayAfterDryingMinutes:"Verzögerung nach Trocknung (Minuten)",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:"Thema",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.
  13. 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.
  14. 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.
  15. EIN-Wert: der genaue String der "EIN" bedeutet. Leer lassen für Auto-Erkennung (ON, true, 1).`,restControl:"Steuerung",restOnUrl:"Einschalt-URL",restOffUrl:"Ausschalt-URL",restOnBody:"EIN-Anforderungstext",restOffBody:"AUS-Anforderungstext",restMethod:"HTTP-Methode",restHeaders:"Custom Headers (JSON)",restStatusUrl:"Status-URL",restStatusPath:"JSON-Pfad für Status",restStatusOnValue:"EIN-Wert",restPowerUrl:"Strom-URL",restPowerPath:"JSON-Pfad für Leistung",restPowerMultiplier:"Power Multiplikator",restEnergyUrl:"Energie URL",restEnergyPath:"JSON-Pfad für Energie",restEnergyMultiplier:"Energie Multiplikator",restUrlRequired:"Mindestens eine URL (ON oder OFF) ist für REST-Steckdosen erforderlich",restHeadersHint:'z. B. {"Authorization": "Bearer your-token"}',restBodyHint:'z. B. ON, {"state": "on"}',restStatusHint:"URL zum Abfragen des aktuellen Status",restPathHint:"z. B. state oder 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:"Verbindung testen",connectionSuccess:"Verbindung erfolgreich",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",inventoryAlerts:"Bestandswarnungen",stockReorderAlert:"Nachbestellungswarnung",stockReorderAlertDescription:"SKU hat seinen Nachbestellungspunkt erreicht",stockBreakAlert:"Bestandsunterbrechungswarnung",stockBreakAlertDescription:"Der Bestand wird vor dem Eintreffen der Nachbestellung aufgebraucht sein",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)",eventPriority:{sectionTitle:"ntfy-Priorität",helpNtfy:"Wähle eine Priorität pro aktiviertem Ereignis. ntfy nutzt diese, um Hinweise (Ton, Sichtbarkeit, Push-Verhalten) zu eskalieren. Hier nicht gesetzte Stufen verwenden den ntfy-Server-Standard.",min:"Min.",low:"Niedrig",default:"Standard",high:"Hoch",urgent:"Dringend"},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:"Git-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}}min",hoursAgo:"vor {{count}}h",inHours:"in {{count}}Std",daysAgo:"vor {{count}}d",inDays:"in {{count}}T"},spoolbuddy:{nav:{dashboard:"Übersicht",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",plateReady:"Druckplatte bereit: {{name}}",plateReadyLabel:"Bereit-zum-Quittieren-Liste",plateClearAction:"Frei",plateClearedToast:"Druckplatte als geleert markiert",plateClearFailed:"Druckplatte konnte nicht als geleert markiert werden"},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!",assignPendingInsert:"Zugewiesen. Slot wird beim Einsetzen der Spule konfiguriert.",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:"Aktualisierungen",nfcReader:"NFC-Leser",type:"Typ",connection:"Verbindung",notConnected:"N/V",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",incompleteDataWarning:"Tag mit unvollständigen Spoolman-Daten geschrieben"},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 ruft das Kamera-Snapshot per URL ab. 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."},makerworld:{title:"MakerWorld",description:"Füge eine MakerWorld-Modell-URL ein, um es direkt aus Bambuddy zu importieren und zu drucken — ohne die Bambu Handy App zu öffnen.",pasteUrlHeader:"Von MakerWorld importieren",pasteUrlPlaceholder:"https://makerworld.com/de/models/… oder beliebigen MakerWorld-Link einfügen",resolveButton:"Laden",signInRequiredTitle:"Bambu-Cloud-Anmeldung für Download erforderlich",signInRequiredBody:"Modell-Details können anonym angezeigt werden, aber MakerWorld verlangt eine Bambu-Cloud-Anmeldung zum Herunterladen der 3MF-Dateien.",openCloudSettings:"Cloud-Einstellungen öffnen",untitledModel:"Unbenanntes Modell",byCreator:"von {{name}}",downloadsCount:"{{count}} Downloads",licensePrefix:"Lizenz",alreadyImported:"Bereits in Bibliothek",openOnMakerworld:"Auf MakerWorld öffnen",alreadyInLibrary:"Dieses Modell ist bereits in deiner Bibliothek — zu finden im Dateimanager → MakerWorld",importSuccess:"{{filename}} importiert — gespeichert im Dateimanager → MakerWorld",platesHeader:"Platten ({{count}})",plateDefaultName:"Platte {{n}}",materialCount:"{{count}} Filamente",amsRequired:"AMS erforderlich",slicedFor:"Gesliced für {{printer}}",alsoCompatible:"Auch kompatibel: {{printers}}",importToLibrary:"Speichern",sliceIn:"Speichern & in {{slicer}} öffnen",disclaimer:"Die MakerWorld-Integration verwendet von der Community dokumentierte API-Endpunkte. Bambuddy ist nicht mit MakerWorld oder Bambu Lab verbunden oder von diesen unterstützt.",lastImportSuccess:"In deine Bibliothek importiert",lastImportAlreadyInLibrary:"Bereits in deiner Bibliothek",viewInLibrary:"Im Dateimanager anzeigen",openInBambuStudio:"In Bambu Studio öffnen",openInOrcaSlicer:"In OrcaSlicer öffnen",importTo:"In Dateimanager importieren",recentImportsHeader:"Zuletzt importiert",phaseResolving:"Auflösen",phaseDownloading:"Lade herunter",folderAuto:"MakerWorld (Standard)",importAll:"Alle importieren",importAllProgress:"Importiere {{current}}/{{total}}",openGallery:"Bildergalerie öffnen",galleryPrev:"Vorheriges Bild",galleryNext:"Nächstes Bild",deleteImport:"Aus Bibliothek entfernen",importDeleting:"Wird entfernt…",importDeleted:"Aus Bibliothek entfernt",confirmDelete:"{{filename}} aus der Bibliothek entfernen? Die lokale Datei wird gelöscht, die Platte kann aber erneut von MakerWorld importiert werden.",errors:{resolveFailed:"Diese MakerWorld-URL konnte nicht aufgelöst werden.",downloadFailed:"Download fehlgeschlagen. Bitte erneut versuchen.",deleteFailed:"Datei konnte nicht aus der Bibliothek entfernt werden."}},gcodeViewer:{back:"Zurück",backToArchives:"Zurück zum Druckarchiv",backToFiles:"Zurück zum Dateimanager"},libraryTrash:{title:"Papierkorb",headerButton:"Papierkorb",headerTooltip:"In den Papierkorb verschobene Dateien anzeigen",backToFiles:"Zurück zum Dateimanager",subtitleAdmin:"Gelöschte Dateien bleiben {{days}} Tage hier und werden dann automatisch entfernt. Diese Ansicht zeigt Papierkorb-Dateien aller Benutzer.",subtitleUser:"Gelöschte Dateien bleiben {{days}} Tage hier und werden dann automatisch entfernt.",loading:"Papierkorb wird geladen…",loadError:"Papierkorb konnte nicht geladen werden.",empty:"Der Papierkorb ist leer.",summary:"{{count}} Dateien · {{size}}",emptyTrash:"Papierkorb leeren",restore:"Wiederherstellen",purgeNow:"Jetzt löschen",autoPurgeIn:"Wird in {{when}} gelöscht",days:"Tage",retentionLabel:"Automatisch löschen nach",selectAll:"Alle auswählen",selectOne:"{{filename}} auswählen",selectionCount:"{{count}} ausgewählt",bulkRestore:"Auswahl wiederherstellen",bulkPurge:"Auswahl löschen",col:{filename:"Datei",folder:"Ordner",size:"Größe",deleted:"Verschoben",autoPurge:"Löschung",owner:"Besitzer",actions:"Aktionen"},confirm:{purgeTitle:"Endgültig löschen?",purgeBody:"{{filename}} wird von der Festplatte gelöscht und kann nicht wiederhergestellt werden.",emptyTitle:"Papierkorb leeren?",emptyBody:"Alle {{count}} Dateien werden endgültig von der Festplatte gelöscht.",bulkPurgeTitle:"Ausgewählte Dateien endgültig löschen?",bulkPurgeBody:"Die {{count}} ausgewählten Dateien werden von der Festplatte gelöscht und können nicht wiederhergestellt werden.",cta:"Endgültig löschen"},toast:{restored:"Datei wiederhergestellt.",restoreFailed:"Datei konnte nicht wiederhergestellt werden.",purged:"Datei endgültig gelöscht.",purgeFailed:"Datei konnte nicht gelöscht werden.",emptied:"{{count}} Datei(en) aus dem Papierkorb gelöscht.",emptyFailed:"Papierkorb konnte nicht geleert werden.",retentionSaved:"Automatisches Löschen auf {{days}} Tage gesetzt.",retentionFailed:"Einstellung konnte nicht gespeichert werden.",bulkRestored:"{{count}} Datei(en) wiederhergestellt.",bulkPurged:"{{count}} Datei(en) gelöscht."}},libraryPurge:{title:"Alte Dateien entfernen",headerButton:"Alte entfernen",headerTooltip:"Alte Dateien im Block in den Papierkorb verschieben",description:"Räume alte Dateien in einem Rutsch aus deiner Bibliothek. Dateien mit Druckverlauf werden nach dem letzten Druckdatum bewertet; nie gedruckte Dateien nach dem Upload-Datum.",ageLabel:"Dateien älter als",days:"Tage",includeNeverPrinted:"Dateien einbeziehen, die nie gedruckt wurden",effectsTitle:'Was passiert, wenn du auf „Entfernen" klickst',effect1:"Passende Dateien werden in den Papierkorb verschoben — noch nicht von der Festplatte gelöscht.",effect2:"Du kannst sie bis zum Ablauf der Aufbewahrungsfrist jederzeit wiederherstellen.",effect3:"Nach Ablauf der Frist löscht der Papierkorb-Sweeper sie endgültig von der Festplatte.",effect4:"Dateien in externen (verknüpften) Ordnern werden übersprungen — Bambuddy löscht keine Bytes, die ihm nicht gehören.",previewLoading:"Prüfe, wie viele Dateien passen…",previewFailed:"Vorschau konnte nicht geladen werden.",previewSummary:"{{count}} Dateien · {{size}} würden in den Papierkorb verschoben",andMore:"…und {{count}} weitere",warning:"Dateien im Papierkorb zählen weiterhin zum Speicher, bis die Aufbewahrungsfrist abgelaufen ist. Leere den Papierkorb danach, um sofort Speicher freizugeben.",confirmCta:"{{count}} in den Papierkorb verschieben",purging:"Wird verschoben…",toast:{success:"{{count}} Datei(en) in den Papierkorb verschoben.",failed:"Dateien konnten nicht verschoben werden."}},libraryAutoPurge:{enableLabel:"Alte Dateien automatisch entfernen",enableDescription:"Führt die Admin-Bereinigung einmal pro Tag aus. Dateien landen zuerst im Papierkorb — sie werden nicht sofort gelöscht.",ageLabel:"Dateien älter als",ageDescription:"Minimum 7 Tage, Maximum 10 Jahre. Verwendet dieselbe Altersregel wie die manuelle „Alte entfernen“-Schaltfläche.",days:"Tage",includeNeverPrinted:"Dateien einbeziehen, die nie gedruckt wurden",saveFailed:"Einstellungen konnten nicht gespeichert werden."},archivePurge:{headerButton:"Alte löschen",headerTooltip:"Alte Archive in einem Rutsch löschen",title:"Alte Archive löschen",description:"Räume alte Druckhistorie auf. Jedes Archiv wird nach seinem letzten abgeschlossenen Druck bewertet — ein erneuter Druck setzt die Frist zurück, aktive Arbeit bleibt sicher.",ageLabel:"Archive löschen, die zuletzt gedruckt wurden vor",days:"Tage",effectsTitle:'Was passiert, wenn du auf „Löschen" klickst',effect1:"Jedes passende Archiv wird aus der Listenansicht ausgeblendet und seine Dateien werden von der Festplatte entfernt (3MF, Vorschau, Timelapse, Quell-3MF, F3D, Fotos).",effect2:"Die Archivzeile bleibt in der Datenbank, damit die Quick Stats den Filament-, Zeit-, Kosten- und Energiebeitrag behalten — wie der Standard beim Einzel-Löschen.",effect3:'Aktiviere unten „Auch aus Statistiken entfernen", um zusätzlich den Quick-Stats-Beitrag zu verwerfen (entspricht dem Einzel-Löschen-Häkchen). Dieser Pfad ist unwiderruflich.',effect4:"Ein erneuter Druck setzt die Frist zurück, Archive, die du weiterhin nutzt, bleiben sicher.",purgeStatsLabel:"Auch aus Statistiken entfernen",purgeStatsHint:"Verwirft die passenden Archive aus den Quick Stats (Filament, Zeit, Kosten, Energie). Ohne diese Option behalten die Quick Stats jeden Beitrag und nur die Dateien werden gelöscht.",previewLoading:"Prüfe passende Archive…",previewFailed:"Vorschau konnte nicht erstellt werden.",previewSummary:"{{count}} Archive · {{size}} würden entfernt",andMore:"…und {{count}} weitere",warning:"Dateien werden von der Festplatte entfernt und können nicht wiederhergestellt werden. Lade wichtige Archive vorher herunter oder markiere sie als Favorit.",confirmCta:"{{count}} Archiv(e) entfernen",purging:"Entferne…",toast:{success:"{{count}} Archiv(e) entfernt.",failed:"Archive konnten nicht gelöscht werden."}},archiveAutoPurge:{enableLabel:"Alte Archive automatisch löschen",enableDescription:"Blendet einmal pro Tag Archive aus der Listenansicht aus und entfernt ihre Dateien von der Festplatte, wenn sie im angegebenen Zeitraum nicht gedruckt wurden. Ein erneuter Druck setzt die Frist zurück.",ageLabel:"Archive automatisch löschen, die zuletzt gedruckt wurden vor",ageDescription:"Minimum 7 Tage, Maximum 10 Jahre. Basiert auf dem letzten abgeschlossenen Druck — ein erneuter Druck setzt die Frist zurück. Entfernt 3MF, Vorschau, Timelapse, Quell-3MF, F3D und Fotos.",days:"Tage",purgeStatsLabel:"Auch aus Statistiken entfernen",purgeStatsDescription:"Wenn aktiviert, verwirft der tägliche Sweeper auch den Quick-Stats-Beitrag (Filament, Zeit, Kosten, Energie) jedes gelöschten Archivs. Standard aus — Quick Stats behalten den Beitrag, nur die Dateien werden gelöscht.",runNow:"Archive jetzt löschen",saveFailed:"Einstellungen konnten nicht gespeichert werden."},cameraTokens:{title:"Kamera-API-Tokens",navTitle:"Kamera-API-Tokens",description:"Langlebige Tokens zum Einbetten des Kamerastreams in Home Assistant, Frigate, Kioske oder andere Tools, die eine stabile URL benötigen. Jeder Token ist nur für den Kamerastream und kann jederzeit widerrufen werden.",loading:"Laden…",confirmRevoke:{title:"Dieses Token widerrufen?",body:'Jedes Gerät, das "{{name}}" verwendet, verliert sofort den Zugriff. Dies kann nicht rückgängig gemacht werden.',cancel:"Abbrechen",confirm:"Widerrufen"},create:{title:"Neues Token erstellen",nameLabel:"Token-Name",namePlaceholder:"z. B. Home Assistant",daysLabel:"Tage bis Ablauf",submit:"Erstellen",hint:"Maximale Lebensdauer 365 Tage. Der Token-Wert wird nur einmal bei der Erstellung angezeigt – jetzt kopieren."},created:{title:"Token erstellt – jetzt kopieren",warning:"Dies ist das einzige Mal, dass dieser Token sichtbar ist. Nach dem Schließen dieses Dialogs können Sie ihn nie wieder anzeigen.",copy:"Kopieren",dismiss:"Ich habe es gespeichert"},list:{myTitle:"Meine Tokens",allTitle:"Alle Benutzer (Admin-Ansicht)",empty:"Noch keine Tokens.",name:"Name",owner:"Eigentümer",prefix:"Präfix",created:"Erstellt",expires:"Läuft ab",lastUsed:"Zuletzt verwendet",revoke:"Widerrufen",expired:"Abgelaufen"},toast:{created:"Token erstellt",createFailed:"Token konnte nicht erstellt werden",revoked:"Token widerrufen",revokeFailed:"Token konnte nicht widerrufen werden",loadFailed:"Tokens konnten nicht geladen werden",copied:"In Zwischenablage kopiert",copyFailed:"Kopieren fehlgeschlagen – manuell auswählen und kopieren"}},forecast:{title:"Bestandsprognose",noSpools:"Keine aktiven Spulen gefunden. Fügen Sie Spulen zu Ihrem Inventar hinzu, um Prognosedaten zu sehen.",noUsageData:"Keine Verbrauchsdaten verfügbar — die Bestandszeitlinie kann nicht projiziert werden.",sku:"SKU",material:"Material",stock:"Bestand",dailyRate:"Rate",daysLeft:"Verbleibende Tage",emptyBy:"Aufgebraucht am",reorderBy:"Nachbestellen bis",actions:"Aktionen",trend:"Trend",estimated:"Gesch.",noData:"Keine Daten",timeframe:"Zeitraum",chartTitle:"Bestandsprognose — Top 5 Materialien",dashedLinesROP:"Gestrichelte Linien = Nachbestellpunkte",stockLevel:"Bestandsniveau",reorderPoint:"Nachbestellpunkt",safetyMargin:"Sicherheitspuffer",trendLegend:"Trend (verlaufsbasiert, 95 % Serviceniveau)",estimatedLegend:"Geschätzt (Gewichtsdelta)",noDataLegend:"Keine Daten",ropLabel:"NBP",ssLabel:"SB",safetyStockLegend:"Sicherheitsbestand",stockArrivalLegend:"Wareneingang",stockoutLegend:"Fehlbestand",alertCount_one:"{{count}} Warnung",alertCount_other:"{{count}} Warnungen",order:"Bestellen",globalLeadTime:"Globale Lieferzeit",globalLeadTimeHint:"Globale Lieferzeitvorgabe — wird in der Nachbestellpunktberechnung für alle SKUs verwendet",save:"Speichern",cancel:"Abbrechen",settingsSaved:"Einstellungen gespeichert",failedSaveSettings:"Einstellungen konnten nicht gespeichert werden",globalLeadTimeSaved:"Globale Lieferzeit gespeichert",skuLeadTimeOverride:"SKU-Lieferzeitüberschreibung",skuLeadTimeHint:"0 = globale Lieferzeit verwenden. Größer 0 setzen, um für diesen SKU zu überschreiben.",safetyMarginLabel:"Sicherheitspuffer",effectiveLeadTime:"Effektive Lieferzeit",effectiveLeadTimeHint:"max(global {{global}}T, SKU {{sku}}T)",reorderPointHint:"d̄ × LT + safety margin — bei diesem Bestand bestellen",safetyMarginHint:"Statistischer Sicherheitsbestand (z=1,65 × σ × √LT) + benutzerdefinierter Puffer",safetyMarginHintDays:"Zusätzlicher Puffer auf den statistischen Sicherheitsbestand.{{approx}}",safetyMarginHintDaysApprox:" ≈ {{g}}g beim aktuellen Verbrauch.",safetyMarginHintG:"Fester Gewichtspuffer auf den statistischen Sicherheitsbestand.{{approx}}",safetyMarginHintGApprox:" ≈ {{days}}d beim aktuellen Verbrauch.",individualSpools:"Einzelne Spulen",labelWeight:"Etikett",spoolCount_one:"{{count}} Spule",spoolCount_other:"{{count}} Spulen",stockBreakRisk:"Bestandsunterbrechungsrisiko",stockBreakBefore:"Bestandsunterbrechung vor Auffüllung",stockBreakDetail:"{{days}}d verbleibend, Lieferzeit {{lt}}d.",reorderNow:"Jetzt nachbestellen",reorderTriggerPassed:"Auslösedatum {{date}} ist überschritten.",shoppingList:"Einkaufsliste",shoppingListItems_one:"({{count}} Artikel)",shoppingListItems_other:"({{count}} Artikel)",shoppingListEmpty:"Einkaufsliste ist leer. Klicken Sie auf das Warenkorbsymbol in einer Zeile, um Artikel hinzuzufügen.",addToCart:"Zur Einkaufsliste hinzufügen",alertsSnoozed:"Benachrichtigungen für diese SKU stummschalten",alertsEnabled:"Benachrichtigungen für diese SKU aktivieren",addedToCart:"Zur Einkaufsliste hinzugefügt",failedAddItem:"Artikel konnte nicht hinzugefügt werden",listView:"Liste",logisticsView:"Logistik",qty:"Menge",weight:"Gewicht",leadTime:"Lieferzeit",expectedRestock:"Erwartete Auffüllung",status:"Status",note:"Notiz",pending:"Ausstehend",purchased:"Bestellt",received:"Erhalten",markPurchased:"Als bestellt markieren",markReceived:"Als erhalten markieren — fügt Spulen dem Lagerbestand hinzu",resetToPending:"Auf ausstehend zurücksetzen",remove:"Entfernen",clearAll:"Alle löschen",downloadCsv:"CSV",addToCartTitle:"Zur Einkaufsliste hinzufügen",byQuantity:"Nach Menge",byDuration:"Nach Dauer",numberOfSpools:"Anzahl der Spulen",lastHowManyDays:"Wie viele Tage soll es reichen?",noUsageQty:"Keine Verbrauchsdaten — Menge auf 1 gesetzt.",noteOptional:"Notiz (optional)",notePlaceholder:"z. B. für Projekt X, dringend…",addNSpools_one:"{{count}} Spule hinzufügen",addNSpools_other:"{{count}} Spulen hinzufügen",onArrival:"Bei Ankunft",stockBreakIn:"Bestandsunterbrechung in {{days}}d.",stockRunsOutBefore:"Bestand läuft vor Ablauf der {{lt}}d Lieferzeit aus.",atRate:"Bei {{rate}}g/Tag benötigen Sie",moreSpools_one:"{{count}} weitere Spule",moreSpools_other:"{{count}} weitere Spulen",bridgeGap:"um die Lücke zu überbrücken.",noReadAccess:"Sie haben keine Berechtigung, Bestandsprognosen anzuzeigen.",noWriteAccess:"Sie haben keine Berechtigung, Prognoseeinstellungen zu ändern."}},tpe={nav:{printers:"Imprimantes",archives:"Archives",queue:"File d'attente d'impression",stats:"Statistiques",profiles:"Profils",maintenance:"Maintenance",projects:"Projets",inventory:"Filament",files:"Gestionnaire de fichiers",makerworld:"MakerWorld",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",errorLoading:"Erreur de chargement",retry:"Réessayer",success:"Succès",warning:"Avertissement",enabled:"Activé",disabled:"Désactivé",yes:"Oui",no:"Non",on:"On",off:"Désactivé",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"},toolbar:{filters:"Filtres",view:"Vue",actions:"Actions"},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:"Actif",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:"Micrologiciel",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",connectionFailedNotAdded:"Connexion à l'imprimante impossible. Vérifiez l'IP, le numéro de série et le code d'accès, et confirmez que le mode LAN-only est activé. L'imprimante n'a pas été ajoutée.",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",loadInitiated:"Chargement du filament…",unloadInitiated:"Déchargement du filament…",failedToLoad:"Échec du chargement du filament",failedToUnload:"Échec du déchargement du filament"},connection:{connected:"Connecté",offline:"Hors ligne"},plateStatus:{markCleared:"Marquer le plateau comme dégagé",cleared:"Plateau dégagé",notCleared:"Plateau non dégagé",inUse:"Plateau en cours d'utilisation"},queue:{inQueue:"{{count}} impression en file",inQueue_plural:"{{count}} impressions en file"},controls:"Contrôles",rfid:{reread:"Relire RFID"},ams:{load:"Charger",unload:"Décharger"},bedJog:{title:"Déplacer le plateau",bed:"Plateau",step:"Pas (mm)",up:"Monter le plateau",down:"Descendre le plateau",disabledWhilePrinting:"Désactivé pendant l'impression",notHomedTitle:"Imprimante non référencée",notHomedMessage:"L'imprimante n'a pas été référencée depuis la dernière impression. Lancez la référence automatique d'abord pour un positionnement sûr (parque la tête d'outil, puis référence X, Y et Z), ou déplacez quand même — les butées logicielles seront ignorées.",homeZ:"Référence automatique",moveAnyway:"Déplacer quand même",homingStarted:"Référencement automatique en cours…"},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",haToggleTitle:'Basculer "{{name}}"',haToggleMessage:"Basculer l'entité Home Assistant {{entity}} ? Cela peut couper l'alimentation si elle est actuellement activée.",haToggleWarning:`ATTENTION : "{{name}}" imprime ! Basculer {{entity}} peut couper l'alimentation et interrompre l'impression. Continuer ?`,haToggleButton:"Basculer"},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:"Micrologiciel",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.",availableVersions:"Versions disponibles",usable:"Utilisable",unavailable:"Indisponible",installed:"Installé",newerBadge:"plus récent",olderBadge:"plus ancien",currentBadge:"actuel"},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",printLog:"Journal d'impression",goToProject:"Aller au Projet : {{name}}",addToProject:"Ajouter au Projet",removeFromProject:"Retirer du Projet",loading:"Chargement...",noProjectsAvailable:"Aucun projet disponible",searchProjects:"Rechercher des projets…",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"},platePicker:{title:"Choisir une plaque à prévisualiser",hint:"Cette archive contient plusieurs plaques. Sélectionnez-en une pour l'ouvrir dans la visionneuse GCode.",plateLabel:"Plaque {{index}}",objectCount:"{{count}} objet",objectCount_plural:"{{count}} objets",noGcode:"Cette archive ne contient pas de G-code généré à prévisualiser. Ouvrez-la d'abord dans Bambu Studio pour la trancher."},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}}",runsBadge:"{{count}} impressions",runsBadgeTitle:"{{count}} impressions au total — {{successful}} réussies, {{failed}} échouées. Cliquez pour voir le journal complet.",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"},runLog:{title:"Journal d'impression",modalTitle:"Journal d'impression — {{name}}",modalTitleFallback:"cette archive",empty:"Aucun événement d'impression enregistré pour cette archive.",col:{date:"Date",status:"Statut",duration:"Durée",filament:"Filament",cost:"Coût"},status:{completed:"Terminé",failed:"Échoué",cancelled:"Annulé",stopped:"Arrêté",skipped:"Ignoré",printing:"Impression en cours"}},modal:{deleteArchive:"Supprimer l'archive",deleteConfirm:'Supprimer "{{name}}" ? Cette action est irréversible.',deleteButton:"Supprimer",deletePurgeStats:"Retirer également cette impression des Quick Stats (filament, temps, coût, énergie)",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:"Étiquettes",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",clearPlateSuccess:"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:"Time-lapse",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:"Fichier inconnu",unknownPrinter:"Imprimante inconnue",startingPrints:"Démarrage des impressions",progressSummary:"{{complete}}/{{total}} terminés • Envoyés : {{dispatched}} • En cours : {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Ignorer la notification d'envoi",cancelDispatchJob:"Annuler l'envoi",cancel:"Annuler",cancelling:"Annulation…",awaitingPrinter:"En attente de l'imprimante…",status:{dispatched:"Dispatché",processing:"Traitement",completed:"Terminé",failed:"Échoué",cancelled:"Annulé"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Envoi annulé",cancelFailed:"Échec de l'annulation de l'envoi",completeWithFailures:"Envoi en arrière-plan terminé : {{completed}} réussi(s), {{failed}} échoué(s)",completeSuccess:"Envoi en arrière-plan terminé : {{completed}} réussi(s)",printStartedRemaining:"{{completed}} impression(s) lancée(s), {{remaining}} en cours d'envoi..."}},stats:{title:"Statistiques",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:"Enregistrements",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:"Flux de travail",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",security:"Sécurité",spoolbuddy:"SpoolBuddy"},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.",advanced:"Avancé",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",spoolmanAmsSyncButton:"Synchroniser les poids Spoolman depuis l'AMS",spoolmanAmsSyncTitle:"Synchroniser les poids des bobines Spoolman depuis l'AMS",spoolmanAmsSyncMessage:"Cela mettra à jour les poids des bobines Spoolman en fonction des valeurs de remplissage AMS actuelles des imprimantes connectées. Les imprimantes doivent être en ligne.",spoolmanAmsSyncing:"Synchronisation...",spoolmanAmsSyncSuccess:"{{synced}} bobine(s) synchronisée(s), {{skipped}} ignorée(s)",spoolmanAmsSyncError:"Échec de la synchronisation des poids Spoolman depuis l'AMS",spoolmanAmsSyncErrorUnreachable:"Échec de la synchronisation (Spoolman inaccessible)",spoolmanAmsSyncErrorNotConfigured:"Échec de la synchronisation (Spoolman non configuré)",spoolmanNotConfigured:"Spoolman non configuré",spoolmanFilamentCatalogTitle:"Catalogue de filaments Spoolman",spoolmanFilamentCatalogDesc:"Noms de filaments et poids à vide depuis votre instance Spoolman. Le nom et le poids bobine sont modifiables ici ; toutes les autres propriétés sont gérées directement dans Spoolman.",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",cloudAccess:"Autoriser l'accès cloud",cloudAccessDescription:"Lit les préréglages et filaments Bambu Cloud en votre nom. Nécessite d'être connecté à Bambu Cloud.",cloudBadge:"Cloud",updateEnergyCost:"Mettre à jour le tarif électrique",updateEnergyCostDescription:"Autoriser cette clé à POSTer un nouveau tarif électrique par kWh sur /settings/electricity-price. Utile pour les automatisations Home Assistant à tarif dynamique (Tibber, Octopus, etc.). Il s'agit du seul champ de paramètres modifiable via clé API.",energyCostBadge:"Énergie",legacyKey:"Hérité",legacyKeyTooltip:"Créé avant la propriété par utilisateur ; recréez pour l'accès cloud",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:"Time-lapse",defaultTimelapseDesc:"Enregistrer une vidéo timelapse",staggeredStart:"Démarrage échelonné",staggeredStartDescription:"Taille de groupe et intervalle par défaut lors de l'échelonnement des démarrages de lots multi-imprimantes. Modifiable par lot dans la fenêtre d'impression.",plateClear:"Confirmation de plateau libre",requirePlateClear:"Exiger la confirmation de plateau libre",requirePlateClearDescription:"Lorsque cette option est activée, le planificateur attend une confirmation de plateau libre par imprimante avant de lancer les impressions en file d'attente sur les imprimantes ayant terminé. La désactiver masque également le badge d'état du plateau et le bouton « Marquer le plateau comme dégagé » sur les cartes d'imprimante.",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:"Taille du groupe",staggerGroupSizeHelp:"Imprimantes à démarrer simultanément par groupe",staggerInterval:"Intervalle (minutes)",staggerIntervalHelp:"Délai entre chaque démarrage de groupe",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:"Administrateur",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:"Entrez le mot de passe",passwordRequirements:"Au moins 8 caractères, avec une majuscule, une minuscule, un chiffre et un caractère spécial.",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",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev ont des bugs CLI connus qui bloquent le découpage de nombreux 3MF créés par Bambu — voir les issues amont #12426 (segfault sur fichiers multi-extrudeurs peints) et #13386 (rejet de validation stricte des plages de paramètres). Bambu Studio est recommandé jusqu'à ce que les correctifs amont arrivent.",useSlicerApi:"Utiliser l'API Slicer",useSlicerApiDescription:'Lorsque activé, les actions "Slice" ouvrent le slicer intégré et appellent le sidecar slicer-API. Lorsque désactivé (par défaut), elles redirigent vers le slicer desktop via le schéma URI.',slicerCard:"Slicer",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"URL du conteneur sidecar slicer-API. Laisser vide pour utiliser les variables d'environnement SLICER_API_URL / BAMBU_STUDIO_API_URL.",slicerBundles:{title:"Bundles de slicer",description:'Importez un Printer Preset Bundle (.bbscfg) exporté depuis BambuStudio (Fichier → Exporter → Exporter le bundle de préréglages → "Printer preset bundle"). Une fois importé, les requêtes de découpage peuvent sélectionner les préréglages du bundle par nom sans re-téléverser le triplet de profils JSON.',uploadButton:"Téléverser le bundle",uploading:"Téléversement…",loading:"Chargement des bundles…",empty:"Aucun bundle importé pour le moment.",summary:"{{processCount}} processus · {{filamentCount}} préréglages de filament",delete:"Supprimer",uploadSuccess:"{{name}} importé",uploadError:"Échec du téléversement du bundle : {{message}}",deleteSuccess:"Bundle supprimé",deleteError:"Échec de la suppression du bundle : {{message}}",confirmDeleteTitle:"Supprimer ce bundle ?",confirmDeleteMessage:`Les requêtes de découpage référençant "{{name}}" échoueront jusqu'à la réimportation du bundle.`},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:"Le mot de passe doit contenir au moins 8 caractères",passwordNeedsUppercase:"Le mot de passe doit contenir au moins une majuscule",passwordNeedsLowercase:"Le mot de passe doit contenir au moins une minuscule",passwordNeedsDigit:"Le mot de passe doit contenir au moins un chiffre",passwordNeedsSpecial:"Le mot de passe doit contenir au moins un caractère spécial",enterGroupName:"Entrez un nom de groupe",settingsSaved:"Paramètres enregistrés",noPermissionUpdate:"Vous n'avez pas l'autorisation de modifier les paramètres",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",material:"Matériau",spoolWeight:"Poids bobine",color:"Couleur",updateSpoolWeight:"Mettre à jour le poids bobine",filamentUpdated:"Filament mis à jour",filamentUpdateFailed:"Échec de la mise à jour du filament",filamentUpdateInvalid:"Données de filament invalides",keepExistingSpoolWeight:"Conserver l'ancien poids pour les bobines existantes",keepExistingSpoolWeightDesc:"Les bobines déjà créées avec ce type de filament conservent l'ancien poids à vide. Les nouvelles bobines utilisent la valeur mise à jour.",applyToAllSpools:"Appliquer à toutes les bobines",applyToAllSpoolsDesc:"Tous les calculs de poids pour ce type de filament utilisent immédiatement le nouveau poids à vide."},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:"Synchro.",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:"Vif",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)",cameraSnapshotUrl:"URL de capture (facultatif)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"URL d'image unique utilisée pour les miniatures de notification, photos de fin, frames de timelapse par couche et détection de plaque. Le timelapse et la détection de plaque nécessitent chacun leur propre bascule par imprimante — cette URL est juste la source d'image qu'ils utilisent lorsqu'activés. Laisser vide pour capturer depuis le flux en direct ci-dessus. Utile pour go2rtc (/api/frame.jpeg) et caméras IP avec un point de terminaison de capture dédié.",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 :",updateViaHomeAssistant:"Les mises à jour sont gérées par le superviseur Home Assistant. Ouvrez Paramètres → Modules complémentaires → Bambuddy dans Home Assistant pour installer la nouvelle version.",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é.",refreshIcon:"Actualiser l'icône",removeIcon:"Supprimer l'icône",iconRefreshed:"Icône actualisée.",iconRemoved:"Icône supprimée.",iconFetchFailed:"Impossible de récupérer l'icône depuis l'URL du fournisseur.",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:"Portées",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",emailClaim:"Claim e-mail",emailClaimDesc:"Claim JWT utilisé comme identité e-mail. Utiliser 'preferred_username' ou 'upn' pour Azure Entra ID (qui n'envoie pas email_verified). Utiliser uniquement des noms de claims de confiance.",emailClaimPlaceholder:"e-mail",emailClaimCustomClaimAutoLinkWarning:"Les revendications personnalisées sont sûres pour la liaison auto uniquement lorsque la valeur est administrée par le tenant (par ex. Azure Entra ID upn / preferred_username). N'activez pas la liaison auto si votre IdP permet aux utilisateurs de s'auto-attribuer cette revendication.",requireEmailVerified:"Exiger la vérification e-mail",requireEmailVerifiedDesc:"N'accepter le claim e-mail que si le fournisseur le marque comme vérifié.",requireEmailVerifiedWarning:"Avertissement : l'e-mail sera accepté sans vérification. À utiliser uniquement avec des fournisseurs de confiance.",requireEmailVerifiedAutoLink:"Désactiver le lien automatique d'abord pour modifier ce paramètre.",defaultGroup:"Groupe par défaut",defaultGroupDesc:"Groupe attribué aux utilisateurs créés automatiquement. Repli sur Viewers si non défini.",defaultGroupViewersFallback:"Viewers (par défaut)"}},encryption:{title:"Statut du chiffrement MFA",enabledFromEnv:"Chiffrement au repos activé (clé depuis la variable d'environnement MFA_ENCRYPTION_KEY)",enabledFromFile:"Chiffrement au repos activé (clé chargée depuis le répertoire de données)",enabledGenerated:"Chiffrement au repos activé avec une clé auto-générée",notConfigured:"Chiffrement au repos non configuré",notConfiguredDesc:"Les secrets TOTP et client_secrets OIDC sont stockés en clair. Définissez MFA_ENCRYPTION_KEY ou redémarrez Bambuddy avec un répertoire de données accessible en écriture pour en générer un automatiquement.",allEncrypted:"Tous les secrets MFA sont chiffrés au repos.",legacyRowsLabel:"Lignes héritées en clair",encryptedRowsLabel:"Lignes chiffrées",legacyRowsWarning:"{{count}} ligne(s) héritée(s) en clair détectée(s). Réenregistrez le fournisseur OIDC ou réinscrivez l'application d'authentification de l'utilisateur pour migrer vers le stockage chiffré.",backupHint:"La clé auto-générée est stockée dans DATA_DIR/.mfa_encryption_key et incluse dans les ZIP de sauvegarde locale. Conservez vos sauvegardes en sécurité ou définissez MFA_ENCRYPTION_KEY explicitement.",decryptionBrokenTitle:"Clé de chiffrement manquante",decryptionBrokenError:"{{count}} enregistrement(s) chiffré(s) ne peuvent pas être déchiffrés car la clé de chiffrement n'est plus disponible. Restaurez le MFA_ENCRYPTION_KEY précédent ou DATA_DIR/.mfa_encryption_key pour récupérer.",migrationErrorWarning:"{{count}} ligne(s) ancienne(s) n'ont pas pu être rechiffrée(s) au démarrage. Vérifiez les journaux du serveur et redémarrez Bambuddy pour réessayer."},spoolbuddy:{infoTitle:"Périphériques SpoolBuddy",infoBody:"Les bornes SpoolBuddy s'enregistrent automatiquement via heartbeat. Désinscrivez ici un appareil qui n'est plus utilisé ou un doublon obsolète laissé par un crash du daemon.",duplicatesTitle:"{{count}} appareils enregistrés",duplicatesBody:"Seul le premier appareil enregistré est utilisé par l'interface du kiosk. Si l'un de ces appareils est un doublon obsolète issu d'un crash, désinscrivez-le — un appareil en ligne se ré-enregistrera automatiquement au prochain heartbeat.",empty:"Aucun appareil SpoolBuddy enregistré pour le moment.",online:"En ligne",offline:"Hors ligne",unregister:"Désinscrire",unregisterSuccess:"Appareil désinscrit",unregisterError:"Échec de la désinscription",confirmTitle:"Désinscrire l'appareil SpoolBuddy ?",confirmBody:`Cela retirera "{{hostname}}" ({{deviceId}}) de la base de données. Si l'appareil est en ligne, il se ré-enregistrera automatiquement au prochain heartbeat.`,ipAddress:"Adresse IP",firmware:"Micrologiciel",lastSeen:"Dernière activité",daemonUptime:"Uptime du daemon",systemUptime:"Uptime système",never:"jamais",nfc:"NFC",scale:"Balance",cpuTemp:"Temp. CPU",memory:"Mémoire",disk:"Disque",update:"Mettre à jour",updateConfirmTitle:"Mettre à jour le daemon Spoolbuddy ?",updateConfirmBody:'Déclencher une mise à jour logicielle sur "{{hostname}}" ? Le daemon redémarrera une fois la mise à jour appliquée.',restartBrowser:"Redémarrer le navigateur",restartBrowserConfirmTitle:"Redémarrer le navigateur du kiosk ?",restartBrowserConfirmBody:`Redémarrer le navigateur du kiosk sur "{{hostname}}" ? L'écran sera momentanément vide.`,restartDaemon:"Redémarrer le daemon",restartDaemonConfirmTitle:"Redémarrer le daemon Spoolbuddy ?",restartDaemonConfirmBody:`Redémarrer le daemon Spoolbuddy sur "{{hostname}}" ? L'appareil sera hors ligne quelques secondes.`,reboot:"Redémarrer",rebootConfirmTitle:"Redémarrer l'appareil ?",rebootConfirmBody:`Redémarrer "{{hostname}}" ? L'appareil sera hors ligne pendant environ une minute.`,shutdown:"Éteindre",shutdownConfirmTitle:"Éteindre l'appareil ?",shutdownConfirmBody:`Éteindre "{{hostname}}" ? Vous aurez besoin d'un accès physique pour le rallumer.`,commandConfirm:"Confirmer",commandQueued:"Commande en file d'attente",commandError:"Échec de l'envoi de la commande"}},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:"Sujet",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...",rememberMe:"Se souvenir de moi",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."},resetPassword:{title:"Définir un nouveau mot de passe",subtitle:"Saisissez et confirmez votre nouveau mot de passe ci-dessous.",newPassword:"Nouveau mot de passe",newPasswordPlaceholder:"Au moins 8 caractères",confirmPassword:"Confirmer le mot de passe",confirmPasswordPlaceholder:"Répéter le nouveau mot de passe",saving:"Enregistrement…",submit:"Définir le mot de passe",backToLogin:"Retour à la connexion",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Le mot de passe doit contenir au moins 8 caractères",resetFailed:"Échec de la réinitialisation. Le lien a peut-être expiré."}},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",unavailable:"Caméra indisponible",diagnose:{button:"Diagnostic",modalTitle:"Diagnostic de la caméra",running:"Diagnostic en cours...",runFailed:"Impossible d'exécuter le diagnostic : {{error}}",retry:"Relancer",stage:{tcp_reachable:"Accessibilité réseau",first_frame:"Capture d'image",live_stream_active:"Flux en direct actif"},summary:{all_ok:"La caméra fonctionne. Toutes les étapes du diagnostic ont réussi.",live_stream_active_healthy:"La caméra diffuse actuellement avec des images récentes — aucun test nécessaire.",printer_unreachable:"L'imprimante n'est pas joignable. Vérifiez l'adresse IP, la connexion réseau et que l'imprimante est allumée.",camera_port_closed:"L'imprimante répond mais le port de la caméra est fermé. Assurez-vous que le mode LAN et le mode développeur sont activés dans les paramètres de l'imprimante.",no_frame:"Connexion à la caméra établie mais aucune image reçue. Réessayez ou vérifiez que la caméra est activée dans les paramètres de l'imprimante.",unknown_failure:"Le diagnostic de la caméra a échoué pour une raison inconnue. Consultez le journal de support pour plus de détails."},meta:{protocol:"Protocole",port:"Port",profile:"Profil"}}},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:"Administrateur",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",ldapProvisioned:'Utilisateur LDAP "{{username}}" provisionné'},modal:{createUser:"Créer utilisateur",editUser:"Modifier utilisateur",cancel:"Annuler",creating:"Création...",saving:"Enregistrement...",saveChanges:"Enregistrer",advancedAuthSubtitle:"avec Authentification Avancée",tabsAriaLabel:"Source utilisateur",localTab:"Local",ldapTab:"LDAP",ldapSearchLabel:"Rechercher dans l'annuaire",ldapSearchPlaceholder:"Tapez un nom d'utilisateur, un nom ou un e-mail...",ldapMinChars:"Tapez au moins 2 caractères pour rechercher",ldapTypeToSearch:"Commencez à taper pour rechercher dans l'annuaire LDAP",ldapSearching:"Recherche dans l'annuaire...",ldapNoResults:"Aucun utilisateur correspondant dans l'annuaire",ldapSearchError:"Échec de la recherche dans l'annuaire. Vérifiez l'état du serveur LDAP.",ldapAlreadyProvisioned:"Déjà provisionné",ldapSelectedLabel:"Sélectionné",ldapProvision:"Provisionner l'utilisateur",ldapProvisioning:"Provisionnement...",ldapErrorProvision:"Échec du provisionnement. Vérifiez l'état du serveur LDAP et réessayez."},form:{username:"Utilisateur",usernamePlaceholder:"Nom utilisateur",email:"E-mail",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:"Profils K"},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:"E-mail",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 votre jeton Bambu Cloud. Les comptes de la région Chine doivent passer par ici (liés à un numéro de téléphone — pas de connexion par e-mail). Le wiki explique comment récupérer le jeton depuis les cookies MakerWorld.",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",collapse:"Réduire",collapseFoldersByDefault:"Réduire les dossiers par défaut",expandFoldersByDefault:"Développer les dossiers par défaut",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",noPermissionSlice:"Vous n'avez pas la permission de découper des fichiers",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:`Vous n'avez aucun projet "{{status}}". Les projets apparaîtront ici lorsque 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...",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"L'URL doit commencer par http:// ou https://",openExternalUrl:"Ouvrir l’URL du projet",coverImageLabel:"Photo de couverture",coverImageAlt:"Photo de couverture du projet",coverImageUpload:"Téléverser",coverImageReplace:"Remplacer",coverImageRemove:"Supprimer",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"},slice:{title:"Slicer le modèle",action:"Slicer",slicing:"Découpage…",printer:"Profil d'imprimante",process:"Profil de processus",filament:"Profil de filament",filamentSlot:"Filament {{index}} – {{type}}",selectPreset:"— Sélectionner un préréglage —",loadingPresets:"Chargement des préréglages…",analyzingPlateFilaments:"Analyse des filaments de la plaque…",analyzingPlateFilamentsHint:"Exécution d'un découpage d'aperçu pour identifier les emplacements AMS utilisés. Mis en cache après — la réouverture est instantanée.",previewToast:"Analyse de {{name}} – {{elapsed}}",previewWithProgress:"Analyse de {{name}} – {{stage}} ({{percent}} %) – {{elapsed}}",notUsedByPlate:"— non utilisé par cette plaque",noPresetsForSlot:"Aucun préréglage disponible",presetsLoadFailed:"Échec du chargement des préréglages. Ouvrez Paramètres → Profils pour les importer d'abord.",allPresetsRequired:"Tous les préréglages doivent être sélectionnés",bundle:"Pack de découpage",bundleNone:"— Aucun (choisir les préréglages individuellement) —",bundleAllRequired:"Le processus du pack et chaque emplacement de filament doivent être choisis",enqueuing:"Envoi du travail de découpage…",queued:"En file d'attente…",failed:"Échec du découpage. Vérifiez les journaux du sidecar.",startedToast:"Découpage de {{name}} en arrière-plan…",queuedToast:"En attente : {{name}} – {{elapsed}}",runningToast:"Découpage {{name}} – {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}} %) – {{elapsed}}",completedToast:"{{name}} découpé",failedToast:"Échec du découpage de {{name}} : {{detail}}",tier:{local:"Importé",cloud:"Cloud",standard:"Standard"},cloud:{notAuthenticated:"Connectez-vous à Bambu Cloud (Paramètres → Profils → Cloud) pour voir vos préréglages cloud.",expired:"Session Bambu Cloud expirée – reconnectez-vous pour actualiser vos préréglages cloud.",unreachable:"Bambu Cloud est inaccessible. Les préréglages locaux et standards fonctionnent encore."},bedType:{label:"Plateau d'impression",auto:"Auto (utiliser le préréglage de processus)",coolPlate:"Cool Plate",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},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:"Désassigner la bobine ?",unlinkConfirmMessage:"Cela retirera la bobine de cet emplacement. Les données de la bobine elles-mêmes resteront inchangées.",selectSpool:"Choisir bobine",noUnlinkedSpools:"Pas de bobine libre",linkSuccess:"Bobine assignée avec succès",linkFailed:"Échec de l’assignation",unlinkSuccess:"Bobine désassignée avec succès",unlinkFailed:"Échec du désassignement",linkedSpool:"Bobine assignée",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",subtitle:"Gérez vos bobines",spoolmanMixedContentTitle:"Spoolman ne peut pas se charger en HTTPS — contenu mixte bloqué par votre navigateur",spoolmanMixedContentBody:"Bambuddy est servi en HTTPS (via votre reverse proxy), mais votre URL Spoolman est encore en HTTP. Les navigateurs bloquent le contenu mixte pour des raisons de sécurité, donc l'interface Spoolman intégrée ne peut pas s'afficher. Spoolman doit être accessible en HTTPS.",spoolmanMixedContentFixReverseProxy:"Placez Spoolman derrière le même reverse proxy que Bambuddy (Traefik / Nginx / Caddy) en HTTPS, puis mettez à jour l'URL Spoolman dans les Paramètres avec la nouvelle adresse HTTPS.",spoolmanMixedContentFixOpenNewTab:"Alternative : ouvrez Spoolman dans un nouvel onglet en HTTP — les règles de contenu mixte ne s'appliquent qu'aux cadres intégrés, un onglet autonome fonctionne.",spoolmanOpenInNewTab:"Ouvrir Spoolman dans un nouvel onglet",labels:{title:"Imprimer étiquettes de bobines",selectedCount:"{{count}} sélectionné",pickSpools:"Choisissez les bobines pour lesquelles imprimer des étiquettes :",searchPlaceholder:"Rechercher par nom, marque ou #ID",filterByMaterial:"Matériau :",allMaterials:"Tout",selectVisible:"Sélectionner tout visible ({{count}})",deselectVisible:"Désélectionner visible",clearAll:"Tout effacer",noSpoolsToShow:"Aucune bobine à afficher. Ajustez votre filtre et réessayez.",noMatches:"Aucune bobine ne correspond à la recherche ou au filtre actuel.",printOne:"Imprimer l'étiquette de cette bobine",printLabels:"Imprimer les étiquettes…",bulkTitle:"Choisissez les bobines à étiqueter parmi les {{count}} affichées",noSpoolsTitle:"Aucune bobine à étiqueter",error:"Impossible de générer les étiquettes : {{msg}}",sortBy:{label:"Trier :",id:"Par ID",color:"Par couleur"},templates:{amsHolderSmall:{label:"Support AMS — petit (74 × 33 mm)",hint:"Une étiquette par page ; correspond à l'étiquette imprimable du modèle MakerWorld 752566 (Support d'étiquettes pour filament AMS)."},amsHolderLarge:{label:"Support AMS — grand (75 × 55 mm)",hint:"Une étiquette par page ; s'adapte à la variante carton du support d'étiquettes pour filament AMS. Assez d'espace pour pastille, marque, matériau, ID et QR code."},box40x30:{label:"Étiquette boîte (40 × 30 mm)",hint:"Une étiquette par page ; taille de rouleau DK/Brother courante, idéale pour étiqueter sachets de filament et bacs de stockage."},box:{label:"Box label (62 × 29 mm)",hint:"Une étiquette par page ; dimensionnée pour Brother PT/QL et petites étiquettes Dymo."},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"Format de feuille UE ; 21 étiquettes par page A4."},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"Format de feuille US ; 30 étiquettes par page Letter."}}},addSpool:"Ajouter Bobine",editSpool:"Modifier Bobine",copySpool:"Copier 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:"Blanc Jade, Rouge Feu...",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",storageLocation:"Emplacement de stockage",storageLocationPlaceholder:"ex. Étagère A, Tiroir 1",openInInventory:"Ouvrir dans l'inventaire",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...",category:"Catégorie",categoryPlaceholder:"ex. Production, Prototype, Client A",categoryNone:"Sans catégorie",storageLocationNone:"Aucun emplacement défini",lowStockThresholdOverride:"Seuil bas (cette bobine)",lowStockThresholdOverrideHelp:"Laisser vide pour utiliser le seuil global ({{global}} %).",clearRfid:"Effacer le tag RFID",rfidCleared:"Tag RFID effacé",archive:"Archiver",restore:"Restaurer",noSpools:"Aucune bobine. Ajoutez votre première bobine pour commencer.",noAvailableSpools:"Aucune bobine disponible. Ajoutez une bobine à votre inventaire ou désaffectez-en une d'un autre emplacement.",kProfiles:"Profils K",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",spoolmanSpools:"Bobines Spoolman",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",spoolsPartiallyCreated:"{{created}} sur {{total}} bobines créées (certaines ont échoué)",spoolCreated:"Bobine créée",spoolUpdated:"Bobine mise à jour",spoolDeleted:"Bobine supprimée",deepLinkSpoolNotFound:"Bobine introuvable",deepLinkFetchFailed:"Impossible de charger la bobine — réessayez",spoolArchived:"Bobine archivée",spoolRestored:"Bobine restaurée",kProfileSaveFailed:"Les paramètres de profil K n'ont pas pu être enregistrés",syncWeightSpoolNotFound:"Bobine introuvable — elle a peut-être été supprimée",syncWeightSpoolmanUnreachable:"Spoolman est inaccessible — réessayez plus tard",syncWeightFailed:"Échec de la synchronisation du poids",spoolmanUnreachable:"Spoolman est inaccessible — veuillez réessayer plus tard",deleteSpoolNotFound:"Bobine introuvable — elle a peut-être déjà été supprimée",deleteFailed:"Impossible de supprimer la bobine",archiveSpoolNotFound:"Bobine introuvable — elle a peut-être déjà été supprimée",archiveFailed:"Impossible d'archiver la bobine",restoreSpoolNotFound:"Bobine introuvable — elle a peut-être déjà été supprimée",restoreFailed:"Impossible de restaurer la bobine",saveFailed:"Impossible d'enregistrer les modifications",tagClearFailed:"Impossible de supprimer le tag",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",extraColorsLabel:"Couleurs supplémentaires",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"Collez 2 à 8 stops hex, séparés par des virgules. Affiché en dégradé.",extraColorsInvalid:"Hex non valides ignorés : {{tokens}}",colorEffectLabel:"Effet",colorEffect:{none:"Aucun",sparkle:"Pailleté",wood:"Bois",marble:"Marbre",glow:"Lueur",matte:"Mat",silk:"Soie",galaxy:"Galaxie",rainbow:"Arc-en-ciel",metal:"Métal",translucent:"Translucide",gradient:"Dégradé",dualColor:"Bicolore",triColor:"Tricolore",multicolor:"Multicolore"},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",resetUsage:"Réinitialiser l'usage à 0",resetUsageTooltip:"Remettre à zéro le compteur de grammes consommés pour cette bobine",resetUsageConfirm:"Remettre à 0 le compteur de grammes consommés de cette bobine ? Les futures impressions repartiront de zéro. La bobine, son calcul de poids restant et vos paramètres ne sont pas modifiés.",resetAllUsage:"Réinitialiser l'usage de toutes les bobines",resetAllUsageTooltip:"Remettre à zéro le compteur de grammes consommés sur chaque bobine",resetAllUsageConfirm:"Remettre à 0 le compteur de grammes consommés sur les {{count}} bobines (archivées incluses) ? Cela efface la valeur « Total Consommé » pour que les futures impressions repartent de zéro. Les bobines et les poids restants ne sont pas modifiés.",usageReset:"Usage de la bobine remis à 0",allUsageReset:"{{count}} bobine(s) réinitialisée(s)",resetUsageFailed:"Échec de la réinitialisation de l'usage",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:"Réseau",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:"Réinitialiser",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 ?',spoolmanFilamentCatalog:"Catalogue de filaments Spoolman",pickFromSpoolmanCatalog:"Choisir dans le catalogue Spoolman…",spoolmanFilamentSelected:"Filament sélectionné depuis le catalogue Spoolman",spoolmanFilamentUnlinked:"Lien avec le catalogue de filaments supprimé",noSpoolmanFilaments:"Aucun filament trouvé dans le catalogue Spoolman",spoolmanFilamentColorSwatch:"Couleur du filament",spoolWeightManagedBySpoolman:"Le poids de la bobine vide est géré par type de filament dans Spoolman",spoolmanCatalogLoadFailed:"Impossible de charger le catalogue Spoolman"},timelapse:{title:"Time-lapse",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:"Emplacement",empty:"Vide",emptySlot:"Slot vide",slotEmpty:"Vide",emptySlotReset:"Aucune bobine assignée",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:"Time-lapse",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:"Échelonner démarrages",staggerGroupSize:"Taille du groupe",staggerInterval:"Intervalle (min)",staggerPreview:"{{printers}} imprimantes → {{groups}} groupes de {{size}}, démarrage toutes les {{interval}} min",staggerLastGroup:"dernier groupe : {{count}}",staggerTotal:"total : {{minutes}} min",staggerToPrinters:"Échelonner sur {{count}} imprimantes",gcodeInjection:"Injecter le G-code auto-impression"},backup:{includesEncryptionKey:"Les sauvegardes locales incluent le fichier de clé de chiffrement MFA (DATA_DIR/.mfa_encryption_key), donc un ZIP de sauvegarde est autonome. Traitez le ZIP comme sensible — quiconque possède le fichier peut déchiffrer les secrets client OIDC et TOTP qu'il contient.",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.",repoIsPrivate:"Le dépôt est privé — la sauvegarde peut s'y faire en toute sécurité.",repoIsPublicWarning:"Le dépôt est PUBLIC. Les sauvegardes Bambuddy contiennent les identifiants MQTT, les jetons Home Assistant, les jetons Prometheus, votre adresse Bambu Cloud, et les codes d'accès des imprimantes via les K-profils. L'enregistrement est bloqué tant que le dépôt n'est pas passé en privé dans les paramètres de votre hébergeur.",repoVisibilityUnknown:"Impossible de déterminer la visibilité du dépôt. Bambuddy refuse toute sauvegarde vers un dépôt non confirmé privé ; l'enregistrement sera bloqué.",repositoryUrl:"URL du dépôt",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"Autoriser HTTP non sécurisé",allowInsecureHttpHint:"Activer pour les instances auto-hébergées sur des réseaux privés sans TLS",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",provider:"Fournisseur Git",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"Prises connectées",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:"Sauvegardes planifiées",scheduledBackupDescription:"Crée automatiquement des instantanés de sauvegarde selon un planning. Le répertoire de sortie peut être monté sur un NAS ou un stockage externe.",frequency:"Fréquence",backupTime:"Temps",retention:"Rétention",retentionDescription:"Nombre de sauvegardes à conserver",outputPath:"Chemin de sortie",outputPathPlaceholder:"Par défaut : {{path}}",outputPathDescription:"Laisser vide pour l'emplacement par défaut",runNow:"Exécuter maintenant",backupFiles:"Fichiers de sauvegarde",noScheduledBackups:"Aucune sauvegarde",deleteBackup:"Supprimer",deleteBackupConfirm:"Supprimer ce fichier de sauvegarde ?",backupRunning:"Sauvegarde en cours...",scheduledBackupComplete:"Sauvegarde terminée avec succès",scheduledBackupFailed:"Échec de la sauvegarde",nextBackup:"Prochaine sauvegarde",backupSize:"Taille",utc:"UTC",defaultPathLabel:"Par défaut :",categories:{settings:"Paramètres",notification_providers:"Fournisseurs de notifications",notification_templates:"Modèles de notifications",smart_plugs:"Prises connectées",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:"Étiquettes",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:"Étiquettes",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:"Profils K",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."},queueForceColorMatch:{title:"Forcer la correspondance des couleurs",description:"Refuser l'envoi vers une imprimante qui n'a pas exactement le type de filament et la couleur chargés. Désactivé par défaut — sans cela, la file d'attente utilise uniquement la correspondance par modèle et peut choisir une imprimante avec la mauvaise couleur."},tailscaleDisabled:{title:"Intégration Tailscale",description:"Activez pour marquer ce VP comme exposé via Tailscale. Affiche l'adresse Tailscale de l'hôte pour que vous sachiez quelle IP coller dans le slicer. L'étape d'import CA est inchangée — cette bascule n'a aucun effet sur les certificats."},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",copyFailed:"Échec de la copie — veuillez sélectionner le texte manuellement",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.'},archiveNameSource:{title:"Source du nom d'archive",description:`Choisissez comment les nouvelles archives sont nommées lorsque les fichiers arrivent via l'imprimante virtuelle. "Métadonnées" utilise le titre intégré par le slicer dans le 3MF (par défaut). "Nom de fichier" utilise le nom envoyé par Bambu Studio en FTP — pratique si vous avez renommé le job dans la boîte "envoyer à l'imprimante".`,metadata:"Métadonnées",filename:"Nom de fichier"}},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:"Administrateur",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:"À {{time}}",scheduleOff:"Désactivé {{time}}",on:"On",off:"Désactivé",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 Activé",autoOnDescription:"Allumer au démarrage de l'impression",autoOff:"Auto Désactivé",autoOffDescription:"Éteindre à la fin de l'impression (unique)",autoOffPersistent:"Garder activé",autoOffPersistentDescription:"Rester activé entre les impressions au lieu d'une seule fois",autoOffAfterDrying:"Arrêt auto après séchage",autoOffAfterDryingDescription:"Éteindre à la fin du séchage de l'AMS",delayAfterDryingMinutes:"Délai après séchage (minutes)",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:"Sujet",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.
  16. 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.
  17. 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.
  18. Valeur ON : la chaîne exacte signifiant "ON". Laisser vide pour la détection auto (ON, true, 1).`,restControl:"Contrôle",restOnUrl:"URL d'activation",restOffUrl:"URL de désactivation",restOnBody:"Corps de requête ON",restOffBody:"Corps de requête OFF",restMethod:"Méthode HTTP",restHeaders:"Custom Headers (JSON)",restStatusUrl:"URL de statut",restStatusPath:"Chemin JSON état",restStatusOnValue:"Valeur ON",restPowerUrl:"URL de puissance",restPowerPath:"Chemin JSON puissance",restPowerMultiplier:"Multiplicateur de puissance",restEnergyUrl:"URL d'énergie",restEnergyPath:"Chemin JSON énergie",restEnergyMultiplier:"Multiplicateur d'énergie",restUrlRequired:"Au moins une URL (ON ou OFF) est requise pour les prises REST",restHeadersHint:'par ex. {"Authorization": "Bearer your-token"}',restBodyHint:'par ex. ON, {"state": "on"}',restStatusHint:"URL pour interroger l'état actuel",restPathHint:"par ex. state ou 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:"Tester la connexion",connectionSuccess:"Connexion réussie",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",inventoryAlerts:"Alertes de stock",stockReorderAlert:"Alerte de réapprovisionnement",stockReorderAlertDescription:"Le SKU a atteint son point de réapprovisionnement",stockBreakAlert:"Alerte de rupture de stock",stockBreakAlertDescription:"Le stock sera épuisé avant l'arrivée du réapprovisionnement",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)",eventPriority:{sectionTitle:"Priorité ntfy",helpNtfy:"Choisissez une priorité pour chaque événement activé. ntfy l'utilise pour faire remonter les alertes (son, visibilité, comportement push). Les niveaux non définis ici utilisent la valeur par défaut du serveur ntfy.",min:"Min.",low:"Basse",default:"Par défaut",high:"Haute",urgent:"Urgente"},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:"Tester"},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:"Profils K",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:"Tester"},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}} – Emplacement {{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 Git",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:"Réinitialiser le 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:"Étiquette",grossWeight:"Poids brut",spoolSize:"Taille bobine",close:"Fermer",currentSpool:"Bobine actuelle",plateReady:"Plateau prêt : {{name}}",plateReadyLabel:"Plateaux à libérer",plateClearAction:"Libérer",plateClearedToast:"Plateau marqué comme libéré",plateClearFailed:"Impossible de marquer le plateau comme libéré"},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é !",assignPendingInsert:"Assigné. Le slot sera configuré lors de l'insertion de la bobine.",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:"Réseau",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:"Emplacement",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/D",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:"Micrologiciel",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",systemConfig:"Backend & authentification",backendUrl:"URL du backend Bambuddy",apiToken:"Jeton d'API",apiTokenPlaceholder:"Saisir un jeton d'API",saveConfig:"Enregistrer la configuration",systemQueued:"Configuration mise en file.",systemFieldsRequired:"L'URL du backend est obligatoire.",nfcDiagnostic:"Diagnostic NFC",scaleDiagnostic:"Diagnostic balance",readTagDiagnostic:"Diagnostic lecture de tag",testNfc:"Tester le lecteur",testScale:"Tester la précision",testReadTag:"Lire un tag"},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",incompleteDataWarning:"Tag écrit avec des données Spoolman incomplètes"},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 la capture caméra par URL. Définissez l'URL externe dans les paramètres généraux pour que le conteneur API ML 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."},makerworld:{title:"MakerWorld",description:"Collez une URL de modèle MakerWorld pour l'importer et l'imprimer directement depuis Bambuddy — sans passer par l'application Bambu Handy.",pasteUrlHeader:"Importer depuis MakerWorld",pasteUrlPlaceholder:"https://makerworld.com/en/models/… ou collez n'importe quel lien MakerWorld",resolveButton:"Résoudre",signInRequiredTitle:"Connexion Bambu Cloud requise pour télécharger",signInRequiredBody:"Vous pouvez consulter les détails du modèle anonymement, mais MakerWorld nécessite un compte Bambu Cloud pour télécharger les fichiers 3MF.",openCloudSettings:"Ouvrir les paramètres Cloud",untitledModel:"Modèle sans titre",byCreator:"par {{name}}",downloadsCount:"{{count}} téléchargements",licensePrefix:"Licence",alreadyImported:"Déjà dans la bibliothèque",openOnMakerworld:"Ouvrir sur MakerWorld",alreadyInLibrary:"Ce modèle est déjà dans votre bibliothèque — retrouvez-le dans Gestionnaire de fichiers → MakerWorld",importSuccess:"{{filename}} importé — enregistré dans Gestionnaire de fichiers → MakerWorld",platesHeader:"Plateaux ({{count}})",plateDefaultName:"Plateau {{n}}",materialCount:"{{count}} filaments",amsRequired:"AMS requis",slicedFor:"Découpé pour {{printer}}",alsoCompatible:"Également marqué compatible : {{printers}}",importToLibrary:"Enregistrer",sliceIn:"Enregistrer et découper dans {{slicer}}",disclaimer:"L'intégration MakerWorld utilise des points de terminaison API documentés par la communauté. Bambuddy n'est ni affilié ni approuvé par MakerWorld ou Bambu Lab.",lastImportSuccess:"Importé dans votre bibliothèque",lastImportAlreadyInLibrary:"Déjà dans votre bibliothèque",viewInLibrary:"Voir dans le Gestionnaire de fichiers",openInBambuStudio:"Ouvrir dans Bambu Studio",openInOrcaSlicer:"Ouvrir dans OrcaSlicer",importTo:"Importer dans le Gestionnaire de fichiers",recentImportsHeader:"Imports récents",phaseResolving:"Résolution",phaseDownloading:"Téléchargement",folderAuto:"MakerWorld (par défaut)",importAll:"Tout importer",importAllProgress:"Importation de {{current}}/{{total}}",openGallery:"Ouvrir la galerie d'images",galleryPrev:"Image précédente",galleryNext:"Image suivante",deleteImport:"Retirer de la bibliothèque",importDeleting:"Suppression…",importDeleted:"Retiré de la bibliothèque",confirmDelete:"Retirer {{filename}} de la bibliothèque ? Le fichier local est supprimé, mais la plaque peut être ré-importée depuis MakerWorld.",errors:{resolveFailed:"Impossible de résoudre cette URL MakerWorld.",downloadFailed:"Le téléchargement a échoué. Veuillez réessayer.",deleteFailed:"Impossible de retirer le fichier de la bibliothèque."}},gcodeViewer:{back:"Retour",backToArchives:"Retour aux archives d'impression",backToFiles:"Retour au gestionnaire de fichiers"},libraryTrash:{title:"Corbeille",headerButton:"Corbeille",headerTooltip:"Voir les fichiers déplacés dans la corbeille",backToFiles:"Retour au gestionnaire de fichiers",subtitleAdmin:"Les fichiers supprimés restent ici pendant {{days}} jours, puis sont supprimés automatiquement. Cette vue affiche la corbeille de tous les utilisateurs.",subtitleUser:"Les fichiers supprimés restent ici pendant {{days}} jours, puis sont supprimés automatiquement.",loading:"Chargement de la corbeille…",loadError:"Impossible de charger la corbeille.",empty:"La corbeille est vide.",summary:"{{count}} fichiers · {{size}}",emptyTrash:"Vider la corbeille",restore:"Restaurer",purgeNow:"Supprimer maintenant",autoPurgeIn:"Suppression automatique dans {{when}}",days:"jours",retentionLabel:"Supprimer automatiquement après",selectAll:"Tout sélectionner",selectOne:"Sélectionner {{filename}}",selectionCount:"{{count}} sélectionné(s)",bulkRestore:"Restaurer la sélection",bulkPurge:"Supprimer la sélection",col:{filename:"Fichier",folder:"Dossier",size:"Taille",deleted:"Mis à la corbeille",autoPurge:"Suppression auto.",owner:"Propriétaire",actions:"Actions"},confirm:{purgeTitle:"Supprimer définitivement ?",purgeBody:"{{filename}} sera supprimé du disque et ne pourra pas être restauré.",emptyTitle:"Vider la corbeille ?",emptyBody:"Tous les {{count}} fichiers seront supprimés du disque. Cette action est irréversible.",bulkPurgeTitle:"Supprimer définitivement les fichiers sélectionnés ?",bulkPurgeBody:"Les {{count}} fichiers sélectionnés seront supprimés du disque et ne pourront pas être restaurés.",cta:"Supprimer définitivement"},toast:{restored:"Fichier restauré.",restoreFailed:"Impossible de restaurer le fichier.",purged:"Fichier supprimé définitivement.",purgeFailed:"Impossible de supprimer le fichier.",emptied:"{{count}} fichier(s) supprimé(s) de la corbeille.",emptyFailed:"Impossible de vider la corbeille.",retentionSaved:"Suppression automatique réglée sur {{days}} jours.",retentionFailed:"Impossible d'enregistrer le réglage de rétention.",bulkRestored:"{{count}} fichier(s) restauré(s).",bulkPurged:"{{count}} fichier(s) supprimé(s)."}},libraryPurge:{title:"Purger les anciens fichiers",headerButton:"Purger",headerTooltip:"Déplacer en masse les anciens fichiers vers la corbeille",description:"Les fichiers plus anciens que le seuil seront déplacés vers la corbeille. Les dossiers externes sont ignorés. Vous pouvez restaurer depuis la corbeille avant la suppression automatique.",ageLabel:"Déplacer les fichiers plus anciens que",days:"jours",includeNeverPrinted:"Inclure les fichiers jamais imprimés",effectsTitle:"Ce qui se passe lorsque vous cliquez sur Purger",effect1:"Les fichiers correspondants sont déplacés vers la corbeille — pas encore supprimés du disque.",effect2:"Vous pouvez les restaurer depuis la corbeille jusqu'à l'expiration de la fenêtre de rétention.",effect3:"Après la période de rétention, le balayeur de corbeille les supprime définitivement.",effect4:"Les fichiers dans les dossiers externes (liés) sont ignorés — Bambuddy ne supprime jamais d'octets qu'il ne possède pas.",previewLoading:"Vérification du nombre de fichiers concernés…",previewFailed:"Impossible de prévisualiser la purge.",previewSummary:"{{count}} fichiers · {{size}} seraient déplacés vers la corbeille",andMore:"…et {{count}} de plus",warning:"Les fichiers sont supprimés en douceur — vous pouvez les restaurer depuis la corbeille jusqu'à l'expiration de la période de rétention.",confirmCta:"Déplacer {{count}} vers la corbeille",purging:"Déplacement vers la corbeille…",toast:{success:"{{count}} fichier(s) déplacé(s) vers la corbeille.",failed:"Impossible de purger les fichiers."}},libraryAutoPurge:{enableLabel:"Purge automatique des anciens fichiers",enableDescription:"Exécute la purge administrateur une fois par jour. Les fichiers sont d'abord déplacés vers la corbeille — ils ne sont pas supprimés immédiatement.",ageLabel:"Purger automatiquement les fichiers plus anciens que",ageDescription:"Minimum 7 jours, maximum 10 ans. Utilise la même règle d'ancienneté que le bouton Purger manuel.",days:"jours",includeNeverPrinted:"Inclure les fichiers jamais imprimés",saveFailed:"Impossible d'enregistrer les paramètres de purge automatique."},archivePurge:{headerButton:"Purger les anciens",headerTooltip:"Suppression groupée d'anciennes archives",title:"Purger les anciennes archives",description:"Effacer l'ancien historique d'impression. Chaque archive vieillit selon sa dernière impression terminée — réimprimer une archive remet son âge à zéro, donc le travail actif n'est jamais purgé.",ageLabel:"Supprimer les archives non imprimées depuis",days:"jours",effectsTitle:"Ce qui se passe lorsque vous cliquez sur Purger",effect1:"Chaque archive correspondante est masquée des listes et ses fichiers sont retirés du disque (3MF, miniature, timelapse, 3MF source, F3D, photos).",effect2:"La ligne d'archive reste en base pour que les statistiques rapides conservent la contribution en filament, temps, coût et énergie — même comportement que la suppression individuelle par défaut.",effect3:"Cochez « Aussi retirer des statistiques » ci-dessous pour également supprimer la contribution des statistiques rapides (équivalent à l'option de la suppression individuelle). Ce chemin est irréversible.",effect4:"Réimprimer une archive remet son compteur à zéro, les archives actives sont donc protégées.",purgeStatsLabel:"Aussi retirer des statistiques",purgeStatsHint:"Supprime les archives correspondantes des statistiques rapides (filament, temps, coût, énergie). Sans cette option, les statistiques conservent chaque contribution et seuls les fichiers quittent le disque.",previewLoading:"Vérification du nombre d'archives correspondantes…",previewFailed:"Impossible de prévisualiser la purge.",previewSummary:"{{count}} archives · {{size}} seraient retirées",andMore:"…et {{count}} de plus",warning:"Les fichiers sont retirés du disque et ne peuvent pas être restaurés. Téléchargez ou marquez comme favori avant de continuer.",confirmCta:"Retirer {{count}} archive(s)",purging:"Retrait en cours…",toast:{success:"{{count}} archive(s) retirée(s).",failed:"Impossible de purger les archives."}},archiveAutoPurge:{enableLabel:"Purger auto. les anciennes archives",enableDescription:"Une fois par jour, masque des listes les archives non imprimées dans le seuil et retire leurs fichiers du disque. Réimprimer remet le compteur à zéro.",ageLabel:"Suppression auto. des archives non imprimées depuis",ageDescription:"Minimum 7 jours, maximum 10 ans. Basé sur la dernière impression terminée — réimprimer remet l'âge à zéro. Retire 3MF, miniature, timelapse, 3MF source, F3D et photos.",days:"jours",purgeStatsLabel:"Aussi retirer des statistiques",purgeStatsDescription:"Lorsqu'activé, le nettoyage quotidien supprime aussi la contribution de chaque archive purgée des statistiques rapides (filament, temps, coût, énergie). Désactivé par défaut — les statistiques conservent la contribution et seuls les fichiers quittent le disque.",runNow:"Purger les archives maintenant",saveFailed:"Impossible d'enregistrer les paramètres de purge automatique."},cameraTokens:{title:"Jetons API caméra",navTitle:"Jetons API caméra",description:"Jetons longue durée pour intégrer le flux caméra dans Home Assistant, Frigate, kiosques ou tout autre outil nécessitant une URL stable. Chaque jeton est limité au flux caméra et peut être révoqué à tout moment.",loading:"Chargement…",confirmRevoke:{title:"Révoquer ce jeton ?",body:`Tout appareil utilisant "{{name}}" perdra l'accès immédiatement. Action irréversible.`,cancel:"Annuler",confirm:"Révoquer"},create:{title:"Créer un nouveau jeton",nameLabel:"Nom du jeton",namePlaceholder:"par ex. Home Assistant",daysLabel:"Jours avant expiration",submit:"Créer",hint:"Durée de vie maximale 365 jours. La valeur du jeton n'est affichée qu'une seule fois — copiez-la maintenant."},created:{title:"Jeton créé – copiez-le maintenant",warning:"C'est la seule fois où ce jeton sera visible. Après la fermeture de ce dialogue, vous ne pourrez plus jamais le voir.",copy:"Copier",dismiss:"Je l'ai enregistré"},list:{myTitle:"Mes jetons",allTitle:"Tous les utilisateurs (vue admin)",empty:"Aucun jeton pour le moment.",name:"Nom",owner:"Propriétaire",prefix:"Préfixe",created:"Créé",expires:"Expire",lastUsed:"Dernière utilisation",revoke:"Révoquer",expired:"Expiré"},toast:{created:"Jeton créé",createFailed:"Échec de la création du jeton",revoked:"Jeton révoqué",revokeFailed:"Échec de la révocation du jeton",loadFailed:"Échec du chargement des jetons",copied:"Copié dans le presse-papiers",copyFailed:"Échec de la copie – sélectionnez et copiez manuellement"}},forecast:{title:"Prévision des stocks",noSpools:"Aucune bobine active trouvée. Ajoutez des bobines à votre inventaire pour voir les données de prévision.",noUsageData:"Aucune donnée d'utilisation disponible — impossible de projeter la chronologie des stocks.",sku:"SKU",material:"Matériau",stock:"Stock",dailyRate:"Cadence",daysLeft:"Jours restants",emptyBy:"Épuisé le",reorderBy:"Réapprovisionner avant le",actions:"Actions",trend:"Tendance",estimated:"Est.",noData:"Aucune donnée",timeframe:"Période",chartTitle:"Prévision du stock — Top 5 matériaux",dashedLinesROP:"Lignes pointillées = points de réapprovisionnement",stockLevel:"Niveau de stock",reorderPoint:"Point de réapprovisionnement",safetyMargin:"Marge de sécurité",trendLegend:"Tendance (basée sur l'historique, niveau de service 95 %)",estimatedLegend:"Estimée (delta de poids)",noDataLegend:"Aucune donnée",ropLabel:"PR",ssLabel:"SS",safetyStockLegend:"Stock de sécurité",stockArrivalLegend:"Arrivée du stock",stockoutLegend:"Rupture de stock",alertCount_one:"{{count}} alerte",alertCount_other:"{{count}} alertes",order:"Commander",globalLeadTime:"Délai global",globalLeadTimeHint:"Délai global minimum — utilisé dans le calcul du point de réapprovisionnement pour tous les SKUs",save:"Enregistrer",cancel:"Annuler",settingsSaved:"Paramètres enregistrés",failedSaveSettings:"Échec de l'enregistrement des paramètres",globalLeadTimeSaved:"Délai global enregistré",skuLeadTimeOverride:"Délai spécifique au SKU",skuLeadTimeHint:"0 = utiliser le délai global. Définir >0 pour remplacer ce SKU.",safetyMarginLabel:"Marge de sécurité",effectiveLeadTime:"Délai effectif",effectiveLeadTimeHint:"max(global {{global}}j, SKU {{sku}}j)",reorderPointHint:"d̄ × LT + safety margin — commander quand le stock atteint ce niveau",safetyMarginHint:"Stock de sécurité statistique (z=1,65 × σ × √LT) + tampon défini par l'utilisateur",safetyMarginHintDays:"Tampon ajouté par-dessus le stock de sécurité statistique.{{approx}}",safetyMarginHintDaysApprox:" ≈ {{g}}g au taux actuel.",safetyMarginHintG:"Tampon de poids fixe ajouté par-dessus le stock de sécurité statistique.{{approx}}",safetyMarginHintGApprox:" ≈ {{days}}j au taux actuel.",individualSpools:"Bobines individuelles",labelWeight:"Étiquette",spoolCount_one:"{{count}} bobine",spoolCount_other:"{{count}} bobines",stockBreakRisk:"Risque de rupture de stock",stockBreakBefore:"Rupture de stock avant réapprovisionnement",stockBreakDetail:"{{days}}j restants, délai {{lt}}j.",reorderNow:"Réapprovisionner maintenant",reorderTriggerPassed:"La date de déclenchement {{date}} est passée.",shoppingList:"Liste d'achats",shoppingListItems_one:"({{count}} article)",shoppingListItems_other:"({{count}} articles)",shoppingListEmpty:"La liste d'achats est vide. Cliquez sur l'icône panier d'une ligne pour ajouter des articles.",addToCart:"Ajouter à la liste d'achats",alertsSnoozed:"Désactiver les alertes pour ce SKU",alertsEnabled:"Activer les alertes pour ce SKU",addedToCart:"Ajouté à la liste de courses",failedAddItem:"Impossible d'ajouter l'article",listView:"Liste",logisticsView:"Logistique",qty:"Qté",weight:"Poids",leadTime:"Délai",expectedRestock:"Réapprovisionnement prévu",status:"Statut",note:"Note",pending:"En attente",purchased:"Commandé",received:"Reçu",markPurchased:"Marquer comme commandé",markReceived:"Marquer comme reçu — ajoute les bobines au stock",resetToPending:"Remettre en attente",remove:"Supprimer",clearAll:"Tout effacer",downloadCsv:"CSV",addToCartTitle:"Ajouter à la liste de courses",byQuantity:"Par quantité",byDuration:"Par durée",numberOfSpools:"Nombre de bobines",lastHowManyDays:"Combien de jours doit-il durer ?",noUsageQty:"Pas de données d'utilisation — quantité définie à 1.",noteOptional:"Note (optionnel)",notePlaceholder:"ex. pour le projet X, urgent…",addNSpools_one:"Ajouter {{count}} bobine",addNSpools_other:"Ajouter {{count}} bobines",onArrival:"À la livraison",stockBreakIn:"Rupture de stock dans {{days}}j.",stockRunsOutBefore:"Le stock s'épuise avant la fin du délai de {{lt}}j.",atRate:"À {{rate}}g/jour, vous avez besoin de",moreSpools_one:"{{count}} bobine supplémentaire",moreSpools_other:"{{count}} bobines supplémentaires",bridgeGap:"pour combler l'écart.",noReadAccess:"Vous n'avez pas la permission de consulter les prévisions de stock.",noWriteAccess:"Vous n'avez pas la permission de modifier les paramètres de prévision."}},npe={nav:{printers:"プリンター",archives:"アーカイブ",queue:"印刷キュー",stats:"統計",profiles:"プロファイル",maintenance:"メンテナンス",projects:"プロジェクト",inventory:"フィラメント",files:"ファイル管理",makerworld:"MakerWorld",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:"エラー",errorLoading:"データの読み込みエラー",retry:"再試行",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:"すべての場所"},toolbar:{filters:"フィルター",view:"表示",actions:"操作"},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:"アクティブ: {{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:"プリンターの追加に失敗しました",connectionFailedNotAdded:"プリンターに接続できませんでした。IPアドレス、シリアル番号、アクセスコードを確認し、LAN専用モードが有効になっていることを確認してください。プリンターは追加されていません。",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再読み取りを開始しました",loadInitiated:"フィラメントをロード中…",unloadInitiated:"フィラメントをアンロード中…",failedToLoad:"フィラメントのロードに失敗",failedToUnload:"フィラメントのアンロードに失敗"},connection:{connected:"接続中",offline:"オフライン"},plateStatus:{markCleared:"プレートをクリア済みにする",cleared:"プレートクリア済み",notCleared:"プレート未クリア",inUse:"プレート使用中"},queue:{inQueue:"キュー内 {{count}} 件",inQueue_plural:"{{count}}件がキュー内"},controls:"コントロール",rfid:{reread:"RFID再読み取り"},ams:{load:"ロード",unload:"アンロード"},bedJog:{title:"ビルドプレートを移動",bed:"ベッド",step:"ステップ (mm)",up:"プレートを上へ",down:"プレートを下へ",disabledWhilePrinting:"印刷中は無効",notHomedTitle:"プリンターがホーミングされていません",notHomedMessage:"前回の印刷以降、プリンターがホーミングされていません。安全な位置決めのためにまずオートホーミングを実行するか(ツールヘッドをパークしてからX・Y・Zをホーミングします)、このまま移動してください — ソフトエンドストップはバイパスされます。",homeZ:"オートホーミング",moveAnyway:"このまま移動",homingStarted:"プリンターをオートホーミング中…"},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:"電源オフ",haToggleTitle:"「{{name}}」を切り替え",haToggleMessage:"Home Assistant エンティティ {{entity}} を切り替えますか?現在オンの場合、電源がオフになる可能性があります。",haToggleWarning:"警告: 「{{name}}」は現在印刷中です!{{entity}} を切り替えると電源が切れ、印刷が中断される可能性があります。続行しますか?",haToggleButton:"切り替え"},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:"ファームウェアをアップロードしました!プリンター画面からアップデートを実行してください。",availableVersions:"利用可能なバージョン",usable:"利用可",unavailable:"利用不可",installed:"インストール済み",newerBadge:"新しい",olderBadge:"古い",currentBadge:"現在"},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:"写真を表示",viewPhotosCount:"写真を表示 ({{count}})",projectPage:"プロジェクトページ",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",edit:"編集",printLog:"印刷ログ",goToProject:"プロジェクトへ: {{name}}",addToProject:"プロジェクトに追加",removeFromProject:"プロジェクトから削除",loading:"アーカイブを読み込み中...",noProjectsAvailable:"利用可能なプロジェクトがありません",searchProjects:"プロジェクトを検索…",select:"選択",deselect:"選択解除",delete:"削除"},permission:{noReprint:"このアーカイブを再印刷する権限がありません",noAddToQueue:"キューに追加する権限がありません",noUpdateArchives:"アーカイブを更新する権限がありません",noUploadFiles:"ファイルをアップロードする権限がありません",noDownload:"アーカイブをダウンロードする権限がありません",noCopyLink:"ダウンロードリンクをコピーする権限がありません",noDelete:"このアーカイブを削除する権限がありません",noCreate:"アーカイブを作成する権限がありません"},platePicker:{title:"プレビューするプレートを選択",hint:"このアーカイブには複数のプレートがあります。GCodeビューアで開くプレートを選択してください。",plateLabel:"プレート {{index}}",objectCount:"{{count}} オブジェクト",objectCount_plural:"{{count}} オブジェクト",noGcode:"このアーカイブにはプレビュー可能なスライス済みGコードがありません。まずBambu Studioで開いてスライスしてください。"},card:{previousPlate:"前のプレート",nextPlate:"次のプレート",plateNumber:"プレート {{index}}",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:"プロジェクト: {{name}}",runsBadge:"{{count}} 回印刷",runsBadgeTitle:"合計 {{count}} 回 — 成功 {{successful}} 回、失敗 {{failed}} 回。クリックして印刷ログを開きます。",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:"削除"},runLog:{title:"印刷ログ",modalTitle:"印刷ログ — {{name}}",modalTitleFallback:"このアーカイブ",empty:"このアーカイブの印刷イベントはまだ記録されていません。",col:{date:"日付",status:"ステータス",duration:"時間",filament:"フィラメント",cost:"コスト"},status:{completed:"完了",failed:"失敗",cancelled:"キャンセル",stopped:"停止",skipped:"スキップ",printing:"印刷中"}},modal:{deleteArchive:"アーカイブを削除",deleteConfirm:'"{{name}}" を削除しますか?この操作は取り消せません。',deleteButton:"削除",deletePurgeStats:"このプリントをQuick Statsからも削除(フィラメント、時間、コスト、電力)",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:"{{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:"{{name}} が追加",nextInQueue:"次のキュー",clearPlateSuccess:"プレートをクリアしました — 次の印刷の準備完了",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:"キャンセル中…",awaitingPrinter:"プリンターを待機中…",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:"{{count}} 日",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",security:"セキュリティ"},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:"ディスク",update:"アップデート",updateConfirmTitle:"Spoolbuddyデーモンを更新しますか?",updateConfirmBody:'"{{hostname}}"のソフトウェア更新を実行しますか?更新後にデーモンが再起動されます。',restartBrowser:"ブラウザを再起動",restartBrowserConfirmTitle:"キオスクブラウザを再起動しますか?",restartBrowserConfirmBody:'"{{hostname}}"のキオスクブラウザを再起動しますか?画面が一時的に消えます。',restartDaemon:"デーモンを再起動",restartDaemonConfirmTitle:"Spoolbuddyデーモンを再起動しますか?",restartDaemonConfirmBody:'"{{hostname}}"のSpoolbuddyデーモンを再起動しますか?デバイスが数秒間オフラインになります。',reboot:"再起動",rebootConfirmTitle:"デバイスを再起動しますか?",rebootConfirmBody:'"{{hostname}}"を再起動しますか?デバイスは約1分間オフラインになります。',shutdown:"シャットダウン",shutdownConfirmTitle:"デバイスをシャットダウンしますか?",shutdownConfirmBody:'"{{hostname}}"をシャットダウンしますか?再起動には物理的なアクセスが必要です。',commandConfirm:"確認",commandQueued:"コマンドをキューに追加しました",commandError:"コマンドの送信に失敗しました"},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})を使用。",advanced:"詳細設定",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からの重量同期に失敗しました",spoolmanAmsSyncButton:"AMSからSpoolmanの重量を同期",spoolmanAmsSyncTitle:"AMSからSpoolmanスプール重量を同期",spoolmanAmsSyncMessage:"接続されたプリンターの現在のAMS残量値に基づいて、すべてのSpoolmanスプール重量を更新します。プリンターがオンラインである必要があります。",spoolmanAmsSyncing:"同期中...",spoolmanAmsSyncSuccess:"{{synced}}個のSpoolmanスプールを同期、{{skipped}}個をスキップ",spoolmanAmsSyncError:"AMSからのSpoolman重量同期に失敗しました",spoolmanAmsSyncErrorUnreachable:"同期失敗(Spoolmanに接続できません)",spoolmanAmsSyncErrorNotConfigured:"同期失敗(Spoolmanが設定されていません)",spoolmanNotConfigured:"Spoolmanが設定されていません",spoolmanFilamentCatalogTitle:"Spoolmanフィラメントカタログ",spoolmanFilamentCatalogDesc:"Spoolmanインスタンスのフィラメント名と風袋重量。名前とスプール重量はここで編集できます。その他の属性はSpoolmanで直接管理してください。",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:"印刷の一時停止、再開、停止",cloudAccess:"クラウドアクセスを許可",cloudAccessDescription:"Bambu Cloudのプリセットとフィラメントを代わりに読み込みます。Bambu Cloudへのサインインが必要です。",cloudBadge:"クラウド",updateEnergyCost:"電気料金を更新",updateEnergyCostDescription:"このキーが /settings/electricity-price に新しいkWhごとの電気料金をPOSTすることを許可。Home Assistantの動的料金自動化(Tibber、Octopusなど)に便利。これはAPIキーで書き込み可能な唯一の設定フィールドです。",energyCostBadge:"電力",legacyKey:"レガシー",legacyKeyTooltip:"ユーザー所有以前に作成 - クラウドアクセスには再作成が必要",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:"段階的開始",staggeredStartDescription:"複数プリンターのバッチ開始を段階的に行う際のデフォルトのグループサイズと間隔。プリントモーダルでバッチごとに上書き可能。",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:"グループサイズ",staggerGroupSizeHelp:"グループあたり同時に開始するプリンター数",staggerInterval:"間隔(分)",staggerIntervalHelp:"各グループ開始までの遅延",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:"パスワードを入力",passwordRequirements:"大文字、小文字、数字、特殊文字を各1文字以上含む8文字以上。",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:"ファイルを開くスライサーアプリケーションを選択",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-devには、Bambu作成の3MFの多くをスライスできない既知のCLIバグがあります — 上流イシュー#12426(ペイント済みマルチエクストルーダーファイルでのsegfault)および#13386(パラメータ範囲の厳格検証拒否)を参照。上流の修正がリリースされるまで、Bambu Studioを推奨します。",useSlicerApi:"スライサーAPIを使用",useSlicerApiDescription:"オンの場合、「Slice」アクションはアプリ内スライサーモーダルを開き、slicer-APIサイドカーを呼び出します。オフ(デフォルト)の場合、URIスキーム経由でデスクトップスライサーに引き継がれます。",slicerCard:"スライサー",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"slicer-APIサイドカーコンテナのURL。空のままにすると SLICER_API_URL / BAMBU_STUDIO_API_URL 環境変数のデフォルト値が使用されます。",slicerBundles:{title:"スライサーバンドル",description:'BambuStudioからエクスポートされたPrinter Preset Bundle(.bbscfg)をインポートします(ファイル → エクスポート → プリセットバンドルをエクスポート → "Printer preset bundle")。インポート後、スライス要求はJSONプロファイルトリプレットを再アップロードせずにバンドルから名前でプリセットを選択できます。',uploadButton:"バンドルをアップロード",uploading:"アップロード中…",loading:"バンドルを読み込み中…",empty:"バンドルはまだインポートされていません。",summary:"{{processCount}}プロセス · {{filamentCount}}フィラメントプリセット",delete:"削除",uploadSuccess:"{{name}}をインポート済み",uploadError:"バンドルのアップロードに失敗: {{message}}",deleteSuccess:"バンドルを削除しました",deleteError:"バンドルの削除に失敗: {{message}}",confirmDeleteTitle:"このバンドルを削除しますか?",confirmDeleteMessage:"「{{name}}」を参照するスライス要求は、バンドルを再インポートするまで失敗します。"},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:"パスワードは8文字以上必要です",passwordNeedsUppercase:"パスワードには少なくとも1つの大文字を含める必要があります",passwordNeedsLowercase:"パスワードには少なくとも1つの小文字を含める必要があります",passwordNeedsDigit:"パスワードには少なくとも1つの数字を含める必要があります",passwordNeedsSpecial:"パスワードには少なくとも1つの特殊文字を含める必要があります",enterGroupName:"グループ名を入力",settingsSaved:"設定を保存しました",noPermissionUpdate:"設定を変更する権限がありません",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:"エントリーの削除に失敗しました",material:"材料",spoolWeight:"スプール重量",color:"色",updateSpoolWeight:"スプール重量を更新",filamentUpdated:"フィラメントを更新しました",filamentUpdateFailed:"フィラメントの更新に失敗しました",filamentUpdateInvalid:"フィラメントデータが無効です",keepExistingSpoolWeight:"既存スプールの旧重量を保持",keepExistingSpoolWeightDesc:"このフィラメントタイプで既に作成されたスプールは旧風袋重量を保持します。新しいスプールは更新後の値を使用します。",applyToAllSpools:"全スプールに適用",applyToAllSpoolsDesc:"このフィラメントタイプの全重量計算に新しい風袋重量が即座に適用されます。"},colorCatalog:{title:"カラーカタログ",description:"メーカー/素材別のフィラメントカラー。スプール追加時の自動カラー検索に使用されます。",searchColors:"カラーを検索...",allManufacturers:"すべてのメーカー",addNewColor:"新しいカラーを追加",manufacturer:"メーカー",colorName:"カラー名",hex:"16進数",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:"米国 (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)",cameraSnapshotUrl:"スナップショットURL(任意)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"通知サムネイル、終了写真、レイヤータイムラプスフレーム、プレート検出に使用される単一フレームURL。タイムラプスとプレート検出はそれぞれプリンターごとのトグルが必要 — このURLはアクティブ時の画像ソースに過ぎません。上記のライブストリームから取得する場合は空のままにします。go2rtc(/api/frame.jpeg)や専用スナップショットエンドポイントを持つIPカメラに便利です。",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でアップデート:",updateViaHomeAssistant:"アップデートはHome Assistant Supervisorによって管理されます。Home Assistantの設定→アドオン→Bambuddyを開いて新しいバージョンをインストールしてください。",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:"プロバイダーが削除されました。",refreshIcon:"アイコンを再取得",removeIcon:"アイコンを削除",iconRefreshed:"アイコンを更新しました。",iconRemoved:"アイコンを削除しました。",iconFetchFailed:"プロバイダーURLからアイコンを取得できませんでした。",deleteTitle:"プロバイダーを削除",deleteMessage:'"{{name}}"を削除しますか?リンクされたすべてのユーザーアカウントが切断されます。',form:{name:"表示名",issuerUrl:"発行者URL",clientId:"クライアントID",clientSecret:"クライアントシークレット",scopes:"スコープ",iconUrl:"アイコンURL (任意)",enabled:"有効",autoCreate:"ユーザーを自動作成",autoCreateDesc:"初回ログイン時にローカルアカウントを自動的に作成します。",autoLink:"既存アカウントを自動リンク",autoLinkDesc:"初回ログイン時にメールアドレスで既存のローカルアカウントにリンクします。",secretHint:"空白のままで現在のものを維持",secretPlaceholder:"新しいシークレット",emailClaim:"メールクレーム",emailClaimDesc:"メールIDとして使用するJWTクレーム。Azure Entra IDには'preferred_username'または'upn'を使用(email_verifiedを送信しない)。信頼できるクレーム名のみ使用してください。",emailClaimPlaceholder:"メール",emailClaimCustomClaimAutoLinkWarning:"カスタムクレームは、値がテナント管理されている場合(Azure Entra IDのupn / preferred_usernameなど)にのみ自動リンクに安全です。IdPがユーザーにこのクレームの自己宣言を許可している場合は、自動リンクを有効にしないでください。",requireEmailVerified:"メール確認を要求",requireEmailVerifiedDesc:"プロバイダーが確認済みとしてマークした場合にのみメールクレームを受け入れます。",requireEmailVerifiedWarning:"警告:確認なしでメールが受け入れられます。信頼できるプロバイダーのみで使用してください。",requireEmailVerifiedAutoLink:"この設定を変更するには、まず自動リンクを無効にしてください。",defaultGroup:"デフォルトグループ",defaultGroupDesc:"自動作成ユーザーに割り当てられるグループ。未設定の場合はViewersにフォールバックします。",defaultGroupViewersFallback:"Viewers(デフォルト)"}},encryption:{title:"MFA暗号化ステータス",enabledFromEnv:"保存時の暗号化が有効(MFA_ENCRYPTION_KEY環境変数のキー)",enabledFromFile:"保存時の暗号化が有効(データディレクトリから読み込んだキー)",enabledGenerated:"保存時の暗号化が自動生成キーで有効",notConfigured:"保存時の暗号化が設定されていません",notConfiguredDesc:"TOTPシークレットとOIDCのclient_secretsは平文で保存されています。MFA_ENCRYPTION_KEYを設定するか、書き込み可能なデータディレクトリでBambuddyを再起動して自動生成してください。",allEncrypted:"すべてのMFAシークレットは保存時に暗号化されています。",legacyRowsLabel:"レガシー平文行",encryptedRowsLabel:"暗号化された行",legacyRowsWarning:"{{count}}件のレガシー平文行を検出。OIDCプロバイダーを再保存するか、ユーザーの認証アプリを再登録して暗号化ストレージへ移行してください。",backupHint:"自動生成キーは DATA_DIR/.mfa_encryption_key に保存され、ローカルバックアップZIPに含まれます。バックアップを安全に保管するか、MFA_ENCRYPTION_KEYを明示的に設定してください。",decryptionBrokenTitle:"暗号化キーが見つかりません",decryptionBrokenError:"{{count}}件の暗号化レコードを復号できません。暗号化キーが見つかりません。以前のMFA_ENCRYPTION_KEYまたはDATA_DIR/.mfa_encryption_keyを復元してください。",migrationErrorWarning:"{{count}} 件のレガシー行を起動時に再暗号化できませんでした。サーバーログを確認し、Bambuddy を再起動して再試行してください。"}},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:'"{{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:"ログイン中...",rememberMe:"ログイン状態を保持する",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:"無効なコードです。もう一度お試しください。"},resetPassword:{title:"新しいパスワードを設定",subtitle:"下のフィールドに新しいパスワードを入力して確認してください。",newPassword:"新しいパスワード",newPasswordPlaceholder:"8文字以上",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"新しいパスワードを再入力",saving:"保存中…",submit:"新しいパスワードを設定",backToLogin:"ログインに戻る",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは8文字以上で入力してください",resetFailed:"パスワードのリセットに失敗しました。リンクが期限切れの可能性があります。"}},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:"チャンバーライト切替",unavailable:"カメラは利用できません",diagnose:{button:"診断",modalTitle:"カメラ診断",running:"診断を実行中...",runFailed:"診断を実行できませんでした: {{error}}",retry:"再実行",stage:{tcp_reachable:"ネットワーク到達性",first_frame:"フレーム取得",live_stream_active:"ライブストリーム動作中"},summary:{all_ok:"カメラは正常に動作しています。診断のすべての段階が成功しました。",live_stream_active_healthy:"カメラは現在新しいフレームを配信しています — テストは不要です。",printer_unreachable:"プリンターに到達できません。IPアドレス、ネットワーク接続、プリンターの電源が入っていることを確認してください。",camera_port_closed:"プリンターには到達できますが、カメラポートが閉じています。プリンター設定でLANのみモードと開発者モードが有効になっていることを確認してください。",no_frame:"カメラに接続できましたがフレームを受信できませんでした。再試行するか、プリンター設定でカメラが有効になっていることを確認してください。",unknown_failure:"カメラ診断が不明な理由で失敗しました。詳細はサポートログを確認してください。"},meta:{protocol:"プロトコル",port:"ポート",profile:"プロファイル"}}},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文字以上必要です",ldapProvisioned:"LDAPユーザー「{{username}}」をプロビジョニング"},modal:{createUser:"ユーザーを作成",editUser:"ユーザーを編集",cancel:"キャンセル",creating:"作成中...",saving:"保存中...",saveChanges:"変更を保存",advancedAuthSubtitle:"高度な認証を使用",tabsAriaLabel:"ユーザーソース",localTab:"ローカル",ldapTab:"LDAP",ldapSearchLabel:"ディレクトリを検索",ldapSearchPlaceholder:"ユーザー名、名前、またはメールアドレスを入力...",ldapMinChars:"検索するには2文字以上入力してください",ldapTypeToSearch:"LDAPディレクトリを検索するには入力を開始",ldapSearching:"ディレクトリを検索中...",ldapNoResults:"ディレクトリに一致するユーザーがいません",ldapSearchError:"ディレクトリ検索に失敗。LDAPサーバーの状態を確認してください。",ldapAlreadyProvisioned:"プロビジョニング済み",ldapSelectedLabel:"選択中",ldapProvision:"ユーザーをプロビジョニング",ldapProvisioning:"プロビジョニング中...",ldapErrorProvision:"プロビジョニングに失敗。LDAPサーバーの状態を確認して再試行してください。"},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:"Bambuddy ログイン",subtitle:"アカウントにサインイン",email:"メールアドレス",password:"パスワード",region:"リージョン",regionGlobal:"グローバル",regionChina:"中国",verificationCode:"認証コード",totpCode:"認証アプリコード",checkEmail:"メール ({{email}}) に届いた6桁のコードを入力してください",enterTotpHint:"認証アプリの6桁のコードを入力してください",accessToken:"アクセストークン",accessTokenHint:"Bambu Cloud のアクセストークンを貼り付けてください。中国リージョンのアカウントはこの方法のみ利用可能です(電話番号認証のためメールログイン不可)。トークンの取得方法は MakerWorld の Cookie から(Wiki を参照)。",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}} 件中 {{showing}} 件のプリセットを表示",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:"アップロード失敗",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:"テキスト折り返しを無効化",collapse:"折りたたむ",collapseFoldersByDefault:"フォルダをデフォルトで折りたたむ",expandFoldersByDefault:"フォルダをデフォルトで展開する",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:"印刷する権限がありません",noPermissionSlice:"ファイルをスライスする権限がありません",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:"プロジェクト名",description:"説明",noProjects:"プロジェクトはまだありません",noProjectsFiltered:"{{status}}のプロジェクトはありません",noProjectsFilteredHelp:"{{status}}のプロジェクトがありません。ステータスが変更されるとここに表示されます。",createFirst:"最初のプロジェクトを作成して、関連する印刷の整理、進捗管理、ビルドの管理を始めましょう。",createFirstButton:"最初のプロジェクトを作成",create:"作成",files:"ファイル",prints:"印刷",plates:"プレート",parts:"パーツ",lastModified:"最終更新日",deleteConfirm:"このプロジェクトを削除しますか?アーカイブとキューアイテムはリンク解除されますが、削除されません。",addFiles:"ファイルを追加",removeFile:"ファイルを削除",viewDetails:"詳細を表示",namePlaceholder:"プロジェクト名",descriptionPlaceholder:"プロジェクトの説明(任意)",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"URLはhttp://またはhttps://で始まる必要があります",openExternalUrl:"プロジェクトのURLを開く",coverImageLabel:"カバー画像",coverImageAlt:"プロジェクトのカバー画像",coverImageUpload:"アップロード",coverImageReplace:"置き換える",coverImageRemove:"削除",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:"{{percent}}% 完了",remaining:"残り {{count}} 件"},stats:{printJobs:"印刷ジョブ",total:"合計",failed:"失敗 {{count}} 件",partsPrinted:"印刷済みパーツ {{count}} 件",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:"印刷中 {{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:"ファイルにエクスポート"},slice:{title:"モデルをスライス",action:"スライス",slicing:"スライス中…",printer:"プリンタープロファイル",process:"プロセスプロファイル",filament:"フィラメントプロファイル",filamentSlot:"フィラメント {{index}}({{type}})",selectPreset:"— プリセットを選択 —",loadingPresets:"プリセットを読み込み中…",analyzingPlateFilaments:"プレートのフィラメントを分析中…",analyzingPlateFilamentsHint:"このプレートが使用するAMSスロットを検出するためにプレビュースライスを実行中。キャッシュ後は再オープンが即座になります。",previewToast:"{{name}}を分析中 – {{elapsed}}",previewWithProgress:"{{name}}を分析中 – {{stage}} ({{percent}}%) – {{elapsed}}",notUsedByPlate:"— このプレートでは使用しない",noPresetsForSlot:"プリセットなし",presetsLoadFailed:"プリセットの読み込みに失敗。先に設定 → プロファイルからインポートしてください。",allPresetsRequired:"すべてのプリセットを選択する必要があります",bundle:"スライサーバンドル",bundleNone:"— なし(プリセットを個別に選択)—",bundleAllRequired:"バンドルのプロセスとすべてのフィラメントスロットを選択してください",enqueuing:"スライスジョブを送信中…",queued:"待機中…",failed:"スライスに失敗。サイドカーのログを確認してください。",startedToast:"バックグラウンドで{{name}}をスライス中…",queuedToast:"待機中: {{name}} – {{elapsed}}",runningToast:"{{name}}をスライス中 – {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",completedToast:"{{name}}をスライス済み",failedToast:"{{name}}のスライスに失敗: {{detail}}",tier:{local:"インポート済み",cloud:"クラウド",standard:"標準"},cloud:{notAuthenticated:"Bambu Cloudにサインイン(設定 → プロファイル → クラウド)してクラウドプリセットを表示。",expired:"Bambu Cloudセッションの有効期限切れ – クラウドプリセットを更新するには再ログインしてください。",unreachable:"Bambu Cloudに接続できません。ローカルと標準のプリセットは引き続き使用できます。"},bedType:{label:"ビルドプレート",auto:"自動(プロセスプリセットを使用)",coolPlate:"クールプレート",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},spoolman:{title:"Spoolman連携",enabled:"Spoolman有効",url:"Spoolman URL",connected:"接続中",disconnected:"未接続",testConnection:"接続テスト",sync:"同期",syncing:"同期中...",lastSync:"最終同期",linkToSpoolman:"Spoolmanに連携",openInSpoolman:"Spoolmanで開く",unlinkSpool:"スプールのリンクを解除",unlinkConfirmTitle:"スプールの割り当てを解除しますか?",unlinkConfirmMessage:"このスロットからスプールが削除されます。スプール自体のデータは変更されません。",selectSpool:"スプールを選択",noUnlinkedSpools:"割り当てられていないスプールがありません",linkSuccess:"スプールが正常に割り当てられました",linkFailed:"スプールの割り当てに失敗しました",unlinkSuccess:"スプールの割り当てが正常に解除されました",unlinkFailed:"スプールの割り当て解除に失敗しました",linkedSpool:"割り当て済みスプール",spoolId:"スプールID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"残り",disableWeightSync:"AMS推定重量同期を無効化",disableWeightSyncDesc:"AMS推定値から残量を更新しません。AMSの割合ベースの推定よりもSpoolmanの使用量追跡を優先する場合に使用してください。新しいスプールは引き続きAMS推定値を初期重量として使用します。",reportPartialUsage:"失敗した印刷の部分使用量を報告",reportPartialUsageDesc:"印刷が失敗またはキャンセルされた場合、レイヤー進捗に基づいてその時点までの推定フィラメント使用量を報告します。"},inventory:{title:"スプール在庫管理",subtitle:"スプールを管理",spoolmanMixedContentTitle:"Spoolman を HTTPS で読み込めません — ブラウザが混在コンテンツをブロックしています",spoolmanMixedContentBody:"Bambuddy はリバースプロキシ経由で HTTPS 配信されていますが、Spoolman の URL は HTTP のままです。ブラウザはセキュリティ上の理由で混在コンテンツをブロックするため、埋め込みの Spoolman UI を表示できません。Spoolman も HTTPS でアクセスできる必要があります。",spoolmanMixedContentFixReverseProxy:"Spoolman を Bambuddy と同じリバースプロキシ(Traefik / Nginx / Caddy)の後ろに HTTPS で配置し、設定で Spoolman URL を新しい HTTPS アドレスに更新してください。",spoolmanMixedContentFixOpenNewTab:"回避策として Spoolman を新しいタブで HTTP として開くことができます — 混在コンテンツのルールは埋め込みフレームのみに適用され、独立したタブは問題なく動作します。",spoolmanOpenInNewTab:"Spoolman を新しいタブで開く",labels:{title:"スプールラベルを印刷",selectedCount:"{{count}}件選択中",pickSpools:"ラベルを印刷するスプールを選択:",searchPlaceholder:"名前、ブランド、#IDで検索",filterByMaterial:"素材:",allMaterials:"すべて",selectVisible:"表示中をすべて選択 ({{count}})",deselectVisible:"表示中を選択解除",clearAll:"すべてクリア",noSpoolsToShow:"表示するスプールはありません。フィルターを調整して再試行してください。",noMatches:"現在の検索またはフィルターに一致するスプールはありません。",printOne:"このスプールのラベルを印刷",printLabels:"ラベルを印刷…",bulkTitle:"現在表示中の{{count}}件からラベルを印刷するスプールを選択",noSpoolsTitle:"ラベル付けするスプールなし",error:"ラベルを生成できませんでした: {{msg}}",sortBy:{label:"並べ替え:",id:"ID順",color:"色順"},templates:{amsHolderSmall:{label:"AMS ホルダー — 小 (74 × 33 mm)",hint:"1ページにつき1枚;MakerWorld モデル 752566 (AMS フィラメントラベルホルダー) の印刷可能なラベルに対応します。"},amsHolderLarge:{label:"AMS ホルダー — 大 (75 × 55 mm)",hint:"1ページにつき1枚;AMS フィラメントラベルホルダーのカード紙挿入バージョンに対応します。色見本、ブランド、素材、ID、QR コードを表示できる広さです。"},box40x30:{label:"ボックスラベル (40 × 30 mm)",hint:"1ページに1枚。DK/Brother の一般的なロールサイズで、フィラメント袋や保管箱のラベルに適しています。"},box:{label:"Box label (62 × 29 mm)",hint:"1ページに1ラベル、Brother PT/QLおよびDymoの小さなラベル用サイズ。"},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"EUシート規格、A4ページに21枚のラベル。"},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"米国シート規格、Letterページに30枚のラベル。"}}},addSpool:"スプールを追加",editSpool:"スプールを編集",copySpool:"スプールをコピー",material:"素材",selectMaterial:"素材を選択...",subtype:"サブタイプ",brand:"ブランド",searchBrand:"ブランドを検索...",useCustomBrand:"「{{brand}}」を使用",useCustomMaterial:"カスタム素材を使用: {{material}}",colorName:"色名",colorNamePlaceholder:"ジェイドホワイト、ファイアレッド...",color:"色",hexColor:"HEXカラー",pickColor:"カスタムカラーを選択",labelWeight:"表示重量",coreWeight:"空スプール重量",searchSpoolWeight:"スプール重量を検索...",weightUsed:"使用量",currentWeight:"残量",measuredWeight:"計測重量",spoolName:"スプール",costPerKg:"kgあたりのコスト",storageLocation:"保管場所",storageLocationPlaceholder:"例:棚A、引き出し1",openInInventory:"インベントリで開く",measuredWeightError:"計測重量は{{min}}gから{{max}}gの間で入力してください。",slicerFilament:"スライサーフィラメント",slicerFilamentName:"スライサープリセット名",slicerPreset:"スライサープリセット",searchPresets:"フィラメントプリセットを検索...",selectedPreset:"選択済み",noPresetsFound:"プリセットが見つかりません",tempOverrides:"温度オーバーライド",note:"メモ",notePlaceholder:"このスプールに関する追加メモ...",category:"カテゴリ",categoryPlaceholder:"例:本番、試作、クライアントA",categoryNone:"カテゴリなし",storageLocationNone:"保管場所未設定",lowStockThresholdOverride:"在庫低下のしきい値(このスプール)",lowStockThresholdOverrideHelp:"空欄の場合、グローバル設定({{global}}%)を使用します。",clearRfid:"RFIDタグをクリア",rfidCleared:"RFIDタグをクリアしました",archive:"アーカイブ",restore:"復元",noSpools:"スプールがありません。最初のスプールを追加してください。",noAvailableSpools:"利用可能なスプールがありません。インベントリにスプールを追加するか、別のスロットからスプールの割り当てを解除してください。",kProfiles:"Kプロファイル",addKProfile:"Kプロファイルを追加",assignSpool:"スプールを割り当て",unassignSpool:"割り当て解除",assignSuccess:"スプールを割り当て、AMSスロットを設定しました",assignFailed:"スプールの割り当てに失敗しました",selectSpool:"このスロットに割り当てるスプールを選択",assigned:"割り当て済み",assigning:"割り当て中...",searchSpools:"スプールを検索...",showAllSpools:"すべてのスプールを表示",spoolmanSpools:"Spoolman スプール",allMaterials:"すべての素材",filterByBrand:"ブランドで絞り込み...",showArchived:"アーカイブ済みを表示",quickAdd:"クイック追加(在庫)",quantity:"数量",stock:"在庫",configured:"設定済み",spoolsCreated:"{{count}}本のスプールを作成しました",spoolsPartiallyCreated:"{{total}}本中{{created}}本のスプールを作成しました(一部失敗)",spoolCreated:"スプールを作成しました",spoolUpdated:"スプールを更新しました",spoolDeleted:"スプールを削除しました",deepLinkSpoolNotFound:"スプールが見つかりません",deepLinkFetchFailed:"スプールを読み込めませんでした — もう一度お試しください",spoolArchived:"スプールをアーカイブしました",spoolRestored:"スプールを復元しました",kProfileSaveFailed:"Kプロファイル設定を保存できませんでした",syncWeightSpoolNotFound:"スプールが見つかりません — 削除された可能性があります",syncWeightSpoolmanUnreachable:"Spoolmanに接続できません — 後でもう一度お試しください",syncWeightFailed:"重量の同期に失敗しました",spoolmanUnreachable:"Spoolmanに接続できません — 後でもう一度お試しください",deleteSpoolNotFound:"スプールが見つかりません — すでに削除された可能性があります",deleteFailed:"スプールを削除できませんでした",archiveSpoolNotFound:"スプールが見つかりません — すでに削除された可能性があります",archiveFailed:"スプールをアーカイブできませんでした",restoreSpoolNotFound:"スプールが見つかりません — すでに削除された可能性があります",restoreFailed:"スプールを復元できませんでした",saveFailed:"変更を保存できませんでした",tagClearFailed:"タグを削除できませんでした",deleteConfirm:"このスプールを削除しますか?この操作は元に戻せません。",archiveConfirm:"このスプールをアーカイブしますか?",advancedSettings:"詳細設定",filamentInfoTab:"フィラメント情報",paProfileTab:"PAプロファイル",filamentInfo:"フィラメント",additional:"追加情報",loadingPresets:"クラウドプリセットを読み込み中...",cloudConnected:"クラウド接続済み",cloudNotConnected:"クラウド未接続(デフォルト使用)",recentColors:"最近",searchColors:"色を検索...",searchResults:"検索結果",allColors:"すべての色",commonColors:"一般的な色",showLess:"少なく表示",showAll:"すべて表示",noColorsFound:"一致する色がありません",noResults:"結果なし",extraColorsLabel:"追加の色",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"2〜8個の16進数ストップをカンマで区切って貼り付けます。グラデーションとして表示されます。",extraColorsInvalid:"無効な16進数を無視: {{tokens}}",colorEffectLabel:"エフェクト",colorEffect:{none:"なし",sparkle:"スパークル",wood:"ウッド",marble:"マーブル",glow:"グロー",matte:"マット",silk:"シルク",galaxy:"ギャラクシー",rainbow:"レインボー",metal:"メタル",translucent:"半透明",gradient:"グラデーション",dualColor:"デュアルカラー",triColor:"トリカラー",multicolor:"マルチカラー"},selectMaterialFirst:"フィラメント情報タブで素材を選択してください。",noPrintersConfigured:"プリンターが設定されていません。プリンターを追加してください。",matchingFilter:"フィルター",anyBrand:"すべてのブランド",anyVariant:"すべてのバリアント",autoSelect:"自動選択",matches:"件一致",match:"件一致",noMatches:"一致なし",connected:"接続済み",offline:"オフライン",printerOffline:"プリンターがオフラインです。接続してキャリブレーションプロファイルを表示してください。",noKProfilesMatch:"選択したフィラメントに一致するKプロファイルがありません。",leftNozzle:"左ノズル",rightNozzle:"右ノズル",profilesSelected:"キャリブレーションプロファイル選択済み",totalInventory:"在庫合計",totalConsumed:"総消費量",byMaterial:"素材別",inPrinter:"プリンター内",lowStock:"残量少",sinceTracking:"追跡開始以降",resetUsage:"使用量を0にリセット",resetUsageTooltip:"このスプールの消費量カウンタを0にする",resetUsageConfirm:"このスプールの消費量カウンタを0にリセットしますか?以降の印刷は再びゼロからカウントされます。スプール自体、残量計算、設定は変更されません。",resetAllUsage:"全スプールの使用量をリセット",resetAllUsageTooltip:"すべてのスプールの消費量カウンタを0にする",resetAllUsageConfirm:"{{count}}件すべてのスプール(アーカイブ済みを含む)の消費量カウンタを0にリセットしますか?「累計消費量」の値がクリアされ、以降の印刷はゼロからカウントされます。スプール自体と残量は変更されません。",usageReset:"スプールの使用量を0にリセットしました",allUsageReset:"{{count}}件のスプールをリセットしました",resetUsageFailed:"スプールの使用量リセットに失敗しました",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:"(在庫)",lowStockThresholdError:"しきい値は0.1から99.9の間でなければなりません",assignMismatchTitle:"材料の不一致",assignMismatchMessage:"選択したスプールの材料「{{spoolMaterial}}」は、{{location}} のトレイ材料「{{trayMaterial}}」と一致しません。割り当てますか?",assignMismatchConfirm:"強制的に割り当て",assignPartialMismatchMessage:"スプールの材料「{{spoolMaterial}}」は「{{trayMaterial}}」に似ていますが、{{location}} と完全には一致しません。続行しますか?",assignProfileMismatchMessage:"スプールのプロファイル「{{spoolProfile}}」は {{location}} のトレイプロファイル「{{trayProfile}}」と一致しません。続行しますか?",spoolmanFilamentCatalog:"Spoolmanフィラメントカタログ",pickFromSpoolmanCatalog:"Spoolmanカタログから選択…",spoolmanFilamentSelected:"Spoolmanカタログからフィラメントを選択しました",spoolmanFilamentUnlinked:"フィラメントカタログのリンクを解除しました",noSpoolmanFilaments:"Spoolmanカタログにフィラメントが見つかりません",spoolmanFilamentColorSwatch:"フィラメントの色",spoolWeightManagedBySpoolman:"空スプールの重量はSpoolmanでフィラメントタイプごとに管理されています",spoolmanCatalogLoadFailed:"Spoolmanのフィラメントカタログを読み込めませんでした"},timelapse:{title:"タイムラプス",create:"タイムラプスを作成",download:"ダウンロード",delete:"削除",preview:"プレビュー",frameRate:"フレームレート",quality:"品質",processing:"バックアップファイルを処理中...",noTimelapses:"利用可能なタイムラプスがありません"},ams:{title:"AMS",slot:"スロット",empty:"<空>",emptySlot:"空のスロット",slotEmpty:"空",emptySlotReset:"スプール未割当",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:"プリンター開始を段階的に",staggerGroupSize:"グループサイズ",staggerInterval:"間隔(分)",staggerPreview:"{{printers}}台のプリンター → {{size}}台ずつ{{groups}}グループ、{{interval}}分ごとに開始",staggerLastGroup:"最終グループ: {{count}}",staggerTotal:"合計: {{minutes}}分",staggerToPrinters:"{{count}}台のプリンターに段階的に送信",gcodeInjection:"自動印刷G-codeを挿入"},backup:{includesEncryptionKey:"ローカルバックアップにはMFA暗号化キーファイル(DATA_DIR/.mfa_encryption_key)が含まれ、バックアップZIPは自己完結型です。ZIPを機密扱いしてください — ファイルを持つ人は誰でも内部のOIDCクライアントシークレットとTOTPシークレットを復号できます。",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リポジトリに自動的に同期し、バックアップとバージョン履歴を保持します。",repoIsPrivate:"リポジトリはプライベートです — バックアップしても安全です。",repoIsPublicWarning:"リポジトリが公開(PUBLIC)です。Bambuddyのバックアップには MQTT 認証情報、Home Assistant トークン、Prometheus トークン、Bambu Cloud のメールアドレス、K-プロファイル経由のプリンタアクセスコードが含まれます。プロバイダー側でリポジトリをプライベートに変更するまで保存はブロックされます。",repoVisibilityUnknown:"リポジトリの公開設定を確認できませんでした。Bambuddy はプライベートと確認できないリポジトリへのバックアップを拒否します。保存はブロックされます。",repositoryUrl:"リポジトリURL",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"安全でないHTTPを許可",allowInsecureHttpHint:"TLSなしのプライベートネットワーク上のセルフホストインスタンスに対して有効化",personalAccessToken:"個人アクセストークン",tokenSaved:"(保存済み)",enterNewToken:"新しいトークンを入力して更新",tokenHint:"Contents読み書き権限を持つきめ細かいトークン",branch:"ブランチ",provider:"Gitプロバイダー",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"スケジュールされたバックアップ",scheduledBackupDescription:"スケジュールに基づいてバックアップスナップショットを自動作成。出力ディレクトリはNASや外部ストレージにマウント可能。",frequency:"頻度",backupTime:"時間",retention:"保持期間",retentionDescription:"保持するバックアップ数",outputPath:"出力パス",outputPathPlaceholder:"デフォルト: {{path}}",outputPathDescription:"デフォルトの場所を使用する場合は空白のまま",runNow:"今すぐ実行",backupFiles:"バックアップファイル",noScheduledBackups:"バックアップなし",deleteBackup:"削除",deleteBackupConfirm:"このバックアップファイルを削除しますか?",backupRunning:"バックアップ中...",scheduledBackupComplete:"バックアップが正常に完了しました",scheduledBackupFailed:"バックアップに失敗",nextBackup:"次回バックアップ",backupSize:"サイズ",utc:"UTC",defaultPathLabel:"デフォルト:",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}} 件中 {{count}} 件のプロファイルをインポートしました",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:"キューに追加されたときに自動的に印刷を開始します。オフの場合、手動ディスパッチを待ちます。"},queueForceColorMatch:{title:"色の一致を強制",description:"正確なフィラメントタイプと色がロードされていないプリンターへの送信を拒否します。デフォルトはオフ — これがないと、キューはモデルのみのマッチングを使用し、間違った色がロードされたプリンターを選ぶ可能性があります。"},tailscaleDisabled:{title:"Tailscale統合",description:"このVPがTailscale経由で公開されていることをマークするには有効にしてください。スライサーに貼り付けるIPがわかるよう、ホストのTailscaleアドレスを表示します。CAインポート手順は変更されません — このトグルは証明書に影響しません。"},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:"設定の更新に失敗しました",copyFailed:"コピーに失敗しました — テキストを手動で選択してください",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}}」を削除してもよろしいですか?このプリンターのすべてのサービスが停止されます。"},archiveNameSource:{title:"アーカイブ名のソース",description:"仮想プリンター経由でファイルが到着したときに、新しいアーカイブをどのように命名するかを選択します。「メタデータ」は3MFに埋め込まれたスライサータイトル(デフォルト)を使用します。「ファイル名」はBambu StudioがFTPで送信したファイル名を使用します — 「プリンターに送信」ダイアログでジョブ名を変更した場合に便利です。",metadata:"メタデータ",filename:"ファイル名"}},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:"ワンショットではなく印刷間で有効のまま維持",autoOffAfterDrying:"乾燥完了後に自動オフ",autoOffAfterDryingDescription:"AMSの乾燥が完了したらオフにする",delayAfterDryingMinutes:"乾燥後の遅延(分)",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")。トピックが生の数値を送信する場合は空のままにしてください。
  19. 乗数: mW→Wは0.001、kW→Wは1000を使用。`,mqttEnergyHint:`JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。
  20. 乗数: Wh→kWhは0.001、MWh→kWhは1000を使用。`,mqttStateHint:`JSONパスはJSONペイロードから値を抽出します。生の値の場合は空のままにしてください。
  21. ON値: "ON"を意味する正確な文字列。自動検出(ON、true、1)の場合は空のままにしてください。`,restControl:"コントロール",restOnUrl:"オンURL",restOffUrl:"オフURL",restOnBody:"ONリクエスト本文",restOffBody:"OFFリクエスト本文",restMethod:"HTTPメソッド",restHeaders:"Custom Headers (JSON)",restStatusUrl:"ステータスURL",restStatusPath:"状態JSONパス",restStatusOnValue:"ON値",restPowerUrl:"電力URL",restPowerPath:"電力JSONパス",restPowerMultiplier:"電力乗数",restEnergyUrl:"エネルギーURL",restEnergyPath:"電力量JSONパス",restEnergyMultiplier:"エネルギー乗数",restUrlRequired:"RESTプラグには少なくとも1つのURL(ONまたはOFF)が必要",restHeadersHint:'例: {"Authorization": "Bearer your-token"}',restBodyHint:'例:ON, {"state": "on"}',restStatusHint:"現在の状態を取得するURL",restPathHint:"例: state または data.power.status",restPowerUrlHint:"電力データ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyUrlHint:"エネルギーデータ用の個別URL(空欄の場合はステータスURLを使用)",restEnergyHint:"各値は個別のURLを使用するか、ステータスURLにフォールバックできます。乗数で単位変換が可能です(例:WhからkWhへの変換は0.001)。",testConnection:"接続テスト",connectionSuccess:"接続成功",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の温度がしきい値を超過",inventoryAlerts:"在庫アラート",stockReorderAlert:"発注アラート",stockReorderAlertDescription:"SKUが発注点に達しました",stockBreakAlert:"在庫切れアラート",stockBreakAlertDescription:"入荷前に在庫が枯渇する見込みです",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:"(印刷完了後)",eventPriority:{sectionTitle:"ntfy 優先度",helpNtfy:"有効な各イベントに優先度を選択してください。ntfy はこれを使って通知の挙動(音、表示、プッシュ動作)を切り替えます。ここで設定していないレベルは ntfy サーバーのデフォルトを使用します。",min:"最小",low:"低",default:"デフォルト",high:"高",urgent:"緊急"},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:"16進: #{{hex}}",resetting:"リセット中...",resetSlot:"スロットをリセット",cancel:"キャンセル",configuring:"設定中...",configureSlot:"スロットを設定"},githubBackup:{title:"Gitバックアップ",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:"現在のスプール",plateReady:"プレート準備完了: {{name}}",plateReadyLabel:"片付け待ちプレート",plateClearAction:"片付け",plateClearedToast:"プレートを片付け済みにしました",plateClearFailed:"プレートを片付け済みにできませんでした"},modal:{spoolDetected:"スプール検出",assignToAms:"AMSに割り当て",syncWeight:"重量同期",weightSynced:"同期完了!",syncing:"同期中...",newTagDetected:"新しいタグを検出",addToInventory:"インベントリに追加",assignToAmsTitle:"AMSに割り当て",selectSlot:"スロットを選択",assign:"割り当て",assigning:"割り当て中...",assignSuccess:"割り当て完了!",assignPendingInsert:"割り当てました。スプールを挿入したときにスロットが設定されます。",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:"ベータ版を含む",systemConfig:"バックエンドと認証",backendUrl:"BambuddyバックエンドURL",apiToken:"APIトークン",apiTokenPlaceholder:"APIトークンを入力",saveConfig:"設定を保存",systemQueued:"設定をキューに追加しました。",systemFieldsRequired:"バックエンドURLは必須です。",nfcDiagnostic:"NFC診断",scaleDiagnostic:"スケール診断",readTagDiagnostic:"タグ読み取り診断",testNfc:"リーダーをテスト",testScale:"精度をテスト",testReadTag:"タグを読み取り"},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:"スプールの作成に失敗しました",incompleteDataWarning:"不完全なSpoolmanデータでタグを書き込みました"},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でカメラスナップショットを取得します。MLAPIコンテナがBambuddyに到達できるよう、一般設定で外部URLを設定してください。",perPrinterTitle:"監視対象プリンター",perPrinterHint:"検出サービスが監視するプリンターを選択します。",monitorAll:"接続されているすべてのプリンターを監視",statusTitle:"ステータス",serviceRunning:"サービス稼働中",thresholds:"低 / 高しきい値",activePrinters:"アクティブな印刷",noActivePrints:"現在、実行中の印刷はありません。",historyTitle:"最近の検出",noHistory:"まだ検出はありません。"},makerworld:{title:"MakerWorld",description:"MakerWorld モデルの URL を貼り付けると、Bambu Handy アプリを開かなくても Bambuddy から直接インポート・印刷できます。",pasteUrlHeader:"MakerWorld からインポート",pasteUrlPlaceholder:"https://makerworld.com/en/models/… または任意の MakerWorld リンク",resolveButton:"読み込む",signInRequiredTitle:"ダウンロードには Bambu Cloud へのサインインが必要です",signInRequiredBody:"モデルの詳細は匿名で閲覧できますが、3MF ファイルをダウンロードするには Bambu Cloud アカウントが必要です。",openCloudSettings:"Cloud 設定を開く",untitledModel:"無題のモデル",byCreator:"作成者: {{name}}",downloadsCount:"ダウンロード数: {{count}}",licensePrefix:"ライセンス",alreadyImported:"ライブラリに登録済み",openOnMakerworld:"MakerWorld で開く",alreadyInLibrary:"このモデルはすでにライブラリにあります — ファイルマネージャー → MakerWorld で確認できます",importSuccess:"{{filename}} をインポートしました — ファイルマネージャー → MakerWorld に保存済み",platesHeader:"プレート ({{count}})",plateDefaultName:"プレート {{n}}",materialCount:"フィラメント {{count}} 本",amsRequired:"AMS が必要",slicedFor:"{{printer}}用にスライス済み",alsoCompatible:"互換性ありとも記録: {{printers}}",importToLibrary:"保存",sliceIn:"保存して {{slicer}} でスライス",disclaimer:"MakerWorld 連携はコミュニティで文書化された API エンドポイントを使用しています。Bambuddy は MakerWorld または Bambu Lab との提携・承認関係はありません。",lastImportSuccess:"ライブラリにインポートしました",lastImportAlreadyInLibrary:"既にライブラリに存在します",viewInLibrary:"ファイルマネージャーで表示",openInBambuStudio:"Bambu Studio で開く",openInOrcaSlicer:"OrcaSlicer で開く",importTo:"ファイルマネージャーへのインポート先",recentImportsHeader:"最近のインポート",phaseResolving:"解決中",phaseDownloading:"ダウンロード中",folderAuto:"MakerWorld (デフォルト)",importAll:"すべてインポート",importAllProgress:"インポート中 {{current}}/{{total}}",openGallery:"画像ギャラリーを開く",galleryPrev:"前の画像",galleryNext:"次の画像",deleteImport:"ライブラリから削除",importDeleting:"削除中…",importDeleted:"ライブラリから削除しました",confirmDelete:"{{filename}} をライブラリから削除しますか?ローカルファイルは削除されますが、MakerWorld から再インポートできます。",errors:{resolveFailed:"この MakerWorld URL を解決できませんでした。",downloadFailed:"ダウンロードに失敗しました。もう一度お試しください。",deleteFailed:"ライブラリからファイルを削除できませんでした。"}},gcodeViewer:{back:"戻る",backToArchives:"印刷アーカイブに戻る",backToFiles:"ファイル管理に戻る"},libraryTrash:{title:"ゴミ箱",headerButton:"ゴミ箱",headerTooltip:"ゴミ箱に移動したファイルを表示",backToFiles:"ファイルマネージャーに戻る",subtitleAdmin:"削除されたファイルは {{days}} 日間ゴミ箱に残り、その後自動的に削除されます。このビューには全ユーザーのゴミ箱が表示されます。",subtitleUser:"削除されたファイルは {{days}} 日間ゴミ箱に残り、その後自動的に削除されます。",loading:"ゴミ箱を読み込み中…",loadError:"ゴミ箱を読み込めませんでした。",empty:"ゴミ箱は空です。",summary:"{{count}} 件 · {{size}}",emptyTrash:"ゴミ箱を空にする",restore:"復元",purgeNow:"今すぐ削除",autoPurgeIn:"{{when}} に自動削除",days:"日",retentionLabel:"自動削除までの期間",selectAll:"すべて選択",selectOne:"{{filename}} を選択",selectionCount:"{{count}} 件選択中",bulkRestore:"選択したものを復元",bulkPurge:"選択したものを削除",col:{filename:"ファイル",folder:"フォルダ",size:"サイズ",deleted:"ゴミ箱に移動",autoPurge:"自動削除",owner:"所有者",actions:"操作"},confirm:{purgeTitle:"完全に削除しますか?",purgeBody:"{{filename}} はディスクから削除され、復元できません。",emptyTitle:"ゴミ箱を空にしますか?",emptyBody:"{{count}} 件のファイルすべてがディスクから削除されます。この操作は取り消せません。",bulkPurgeTitle:"選択したファイルを完全に削除しますか?",bulkPurgeBody:"選択した {{count}} 件のファイルがディスクから削除され、復元できません。",cta:"完全に削除"},toast:{restored:"ファイルを復元しました。",restoreFailed:"ファイルを復元できませんでした。",purged:"ファイルを完全に削除しました。",purgeFailed:"ファイルを削除できませんでした。",emptied:"ゴミ箱から {{count}} 件のファイルを削除しました。",emptyFailed:"ゴミ箱を空にできませんでした。",retentionSaved:"自動削除を {{days}} 日に設定しました。",retentionFailed:"保持期間の設定を保存できませんでした。",bulkRestored:"{{count}} 件のファイルを復元しました。",bulkPurged:"{{count}} 件のファイルを削除しました。"}},libraryPurge:{title:"古いファイルを一括削除",headerButton:"古いファイル削除",headerTooltip:"古いファイルをまとめてゴミ箱に移動",description:"指定した期間より古いファイルはゴミ箱に移動されます。外部フォルダはスキップされます。自動削除までの間、ゴミ箱から復元できます。",ageLabel:"次より古いファイルを移動",days:"日",includeNeverPrinted:"一度も印刷していないファイルも含める",effectsTitle:"「削除」をクリックすると何が起こるか",effect1:"一致するファイルはゴミ箱に移動されます。ディスクからはまだ削除されません。",effect2:"保持期間が過ぎるまで、いつでもゴミ箱から復元できます。",effect3:"保持期間が過ぎると、ゴミ箱クリーナーがディスクから完全に削除します。",effect4:"外部(リンク済み)フォルダー内のファイルはスキップされます — Bambuddyは所有していないバイトを削除しません。",previewLoading:"対象ファイル数を確認中…",previewFailed:"プレビューを取得できませんでした。",previewSummary:"{{count}} 件 · {{size}} がゴミ箱に移動されます",andMore:"…ほか {{count}} 件",warning:"ファイルはソフト削除されます — 保持期間が終了するまでゴミ箱から復元できます。",confirmCta:"{{count}} 件をゴミ箱へ移動",purging:"ゴミ箱へ移動中…",toast:{success:"{{count}} 件のファイルをゴミ箱に移動しました。",failed:"ファイルを削除できませんでした。"}},libraryAutoPurge:{enableLabel:"古いファイルを自動で一括削除",enableDescription:"管理者の一括削除を 1 日 1 回実行します。ファイルはまずゴミ箱に移動され、すぐには削除されません。",ageLabel:"次より古いファイルを自動削除",ageDescription:"最短 7 日、最長 10 年。手動の「古いファイル削除」ボタンと同じ期間ルールを使用します。",days:"日",includeNeverPrinted:"一度も印刷していないファイルも含める",saveFailed:"自動削除の設定を保存できませんでした。"},archivePurge:{headerButton:"古いものを削除",headerTooltip:"古いアーカイブを一括削除",title:"古いアーカイブを削除",description:"古い印刷履歴をクリア。各アーカイブは最新の印刷完了に基づいてエイジングされます — アーカイブを再印刷するとエイジがリセットされるため、現在使用中の作業が削除されることはありません。",ageLabel:"印刷されていないアーカイブを削除(過去",days:"日",effectsTitle:"「削除」をクリックすると何が起こるか",effect1:"一致するアーカイブはリストから非表示になり、ファイル(3MF、サムネイル、タイムラプス、ソース3MF、F3D、写真)はディスクから削除されます。",effect2:"アーカイブのレコードはデータベースに残るため、Quick Stats のフィラメント/時間/コスト/エネルギーの寄与は保持されます — 個別アーカイブ削除の既定動作と同じです。",effect3:"下の「統計からも削除」を有効にすると、Quick Stats の寄与も破棄されます(個別アーカイブ削除のオプションと同等)。この操作は取り消せません。",effect4:"アーカイブを再印刷するとエイジクロックがリセットされるため、まだ使用中のアーカイブは安全です。",purgeStatsLabel:"統計からも削除",purgeStatsHint:"一致するアーカイブを Quick Stats(フィラメント、時間、コスト、エネルギー)からも削除します。チェックしない場合、Quick Stats は寄与を保持し、ファイルのみがディスクから消えます。",previewLoading:"一致するアーカイブの数を確認中…",previewFailed:"削除のプレビューを表示できませんでした。",previewSummary:"{{count}}件のアーカイブ · {{size}}が削除されます",andMore:"…他に{{count}}件",warning:"ファイルはディスクから削除され、元に戻せません。続行する前に、保持したいものをダウンロードまたはお気に入りに追加してください。",confirmCta:"{{count}}件のアーカイブを削除",purging:"削除中…",toast:{success:"{{count}}件のアーカイブを削除しました。",failed:"アーカイブを削除できませんでした。"}},archiveAutoPurge:{enableLabel:"古いアーカイブを自動削除",enableDescription:"1日1回、しきい値内に印刷されていないアーカイブをリストから非表示にし、ファイルをディスクから削除します。再印刷するとタイマーがリセットされます。",ageLabel:"印刷されていないアーカイブを自動削除(過去",ageDescription:"最小7日、最大10年。最新の印刷完了に基づきます — 再印刷するとエイジがリセットされます。3MF、サムネイル、タイムラプス、ソース3MF、F3D、写真を削除します。",days:"日",purgeStatsLabel:"統計からも削除",purgeStatsDescription:"有効にすると、毎日のスイーパーが削除した各アーカイブを Quick Stats(フィラメント、時間、コスト、エネルギー)からも除外します。既定はオフ — Quick Stats は寄与を保持し、ファイルのみがディスクから消えます。",runNow:"アーカイブを今すぐ削除",saveFailed:"自動削除設定を保存できませんでした。"},cameraTokens:{title:"カメラAPIトークン",navTitle:"カメラAPIトークン",description:"Home Assistant、Frigate、キオスク、その他安定したURLが必要なツールにカメラストリームを埋め込むための長期トークン。各トークンはカメラストリーム専用で、いつでも取り消し可能。",loading:"読み込み中…",confirmRevoke:{title:"このトークンを取り消しますか?",body:"「{{name}}」を使用しているデバイスは直ちにアクセスできなくなります。元に戻せません。",cancel:"キャンセル",confirm:"取り消し"},create:{title:"新しいトークンを作成",nameLabel:"トークン名",namePlaceholder:"例:Home Assistant",daysLabel:"有効期限までの日数",submit:"作成",hint:"最大有効期間は365日。トークン値は作成時に一度だけ表示されます — 今すぐコピーしてください。"},created:{title:"トークンを作成しました – 今すぐコピー",warning:"このトークンが表示されるのは今回限りです。このダイアログを閉じると二度と表示できません。",copy:"コピー",dismiss:"保存しました"},list:{myTitle:"マイトークン",allTitle:"全ユーザー(管理者ビュー)",empty:"トークンはまだありません。",name:"名前",owner:"所有者",prefix:"プレフィックス",created:"作成",expires:"有効期限",lastUsed:"最終使用",revoke:"取り消し",expired:"期限切れ"},toast:{created:"トークンを作成しました",createFailed:"トークンの作成に失敗",revoked:"トークンを取り消しました",revokeFailed:"トークンの取り消しに失敗",loadFailed:"トークンの読み込みに失敗",copied:"クリップボードにコピー",copyFailed:"コピーに失敗 – 手動で選択してコピー"}},forecast:{title:"在庫予測",noSpools:"アクティブなスプールが見つかりません。予測データを表示するには、在庫にスプールを追加してください。",noUsageData:"使用データがありません — 在庫のタイムラインを予測できません。",sku:"SKU",material:"素材",stock:"在庫",dailyRate:"レート",daysLeft:"残り日数",emptyBy:"在庫切れ予定日",reorderBy:"発注期限",actions:"操作",trend:"トレンド",estimated:"推定",noData:"データなし",timeframe:"期間",chartTitle:"在庫予測 — 上位5素材",dashedLinesROP:"破線 = 発注点",stockLevel:"在庫量",reorderPoint:"発注点",safetyMargin:"安全余裕",trendLegend:"トレンド(履歴ベース、95%サービスレベル)",estimatedLegend:"推定(重量差分)",noDataLegend:"データなし",ropLabel:"発注点",ssLabel:"安全在庫",safetyStockLegend:"安全在庫",stockArrivalLegend:"入荷",stockoutLegend:"品切れ",alertCount_one:"{{count}}件の警告",alertCount_other:"{{count}}件の警告",order:"注文",globalLeadTime:"グローバルリードタイム",globalLeadTimeHint:"グローバルリードタイムの下限 — 全SKUの発注点計算に使用",save:"保存",cancel:"キャンセル",settingsSaved:"設定を保存しました",failedSaveSettings:"設定の保存に失敗しました",globalLeadTimeSaved:"グローバルリードタイムを保存しました",skuLeadTimeOverride:"SKUリードタイム上書き",skuLeadTimeHint:"0 = グローバルリードタイムを使用。このSKUを上書きするには0より大きい値を設定。",safetyMarginLabel:"安全余裕",effectiveLeadTime:"実効リードタイム",effectiveLeadTimeHint:"max(グローバル {{global}}日, SKU {{sku}}日)",reorderPointHint:"d̄ × LT + safety margin — 在庫がこのレベルに達したら発注",safetyMarginHint:"統計的安全在庫 (z=1.65 × σ × √LT) + ユーザー定義バッファ",safetyMarginHintDays:"統計的安全在庫に加算されるバッファ。{{approx}}",safetyMarginHintDaysApprox:" ≈ 現在のペースで{{g}}g。",safetyMarginHintG:"統計的安全在庫に加算される固定重量バッファ。{{approx}}",safetyMarginHintGApprox:" ≈ 現在のペースで{{days}}日。",individualSpools:"個別スプール",labelWeight:"ラベル",spoolCount_one:"{{count}}個のスプール",spoolCount_other:"{{count}}個のスプール",stockBreakRisk:"在庫切れリスク",stockBreakBefore:"補充前の在庫切れ",stockBreakDetail:"残り{{days}}日、リードタイム{{lt}}日。",reorderNow:"今すぐ発注",reorderTriggerPassed:"発注トリガー日 {{date}} が経過しました。",shoppingList:"購入リスト",shoppingListItems_one:"({{count}}件)",shoppingListItems_other:"({{count}}件)",shoppingListEmpty:"購入リストは空です。行のカートアイコンをクリックしてアイテムを追加してください。",addToCart:"購入リストに追加",alertsSnoozed:"このSKUのアラートをミュート",alertsEnabled:"このSKUのアラートを有効にする",addedToCart:"買い物リストに追加しました",failedAddItem:"アイテムの追加に失敗しました",listView:"リスト",logisticsView:"ロジスティクス",qty:"数量",weight:"重量",leadTime:"リードタイム",expectedRestock:"入荷予定日",status:"ステータス",note:"メモ",pending:"保留中",purchased:"発注済み",received:"受領済み",markPurchased:"発注済みとしてマーク",markReceived:"受領済みとしてマーク — スプールを在庫に追加",resetToPending:"保留中にリセット",remove:"削除",clearAll:"すべてクリア",downloadCsv:"CSV",addToCartTitle:"買い物リストに追加",byQuantity:"数量で",byDuration:"期間で",numberOfSpools:"スプール数",lastHowManyDays:"何日間持つべきですか?",noUsageQty:"使用データなし — 数量を1に設定しました。",noteOptional:"メモ(任意)",notePlaceholder:"例:プロジェクトX用、緊急…",addNSpools_one:"{{count}}個のスプールを追加",addNSpools_other:"{{count}}個のスプールを追加",onArrival:"入荷時",stockBreakIn:"{{days}}日後に在庫切れ。",stockRunsOutBefore:"リードタイム{{lt}}日が経過する前に在庫が枯渇します。",atRate:"{{rate}}g/日のペースでは",moreSpools_one:"あと{{count}}個のスプール",moreSpools_other:"あと{{count}}個のスプール",bridgeGap:"が不足を補うために必要です。",noReadAccess:"在庫予測を閲覧する権限がありません。",noWriteAccess:"予測設定を変更する権限がありません。"}},rpe={nav:{printers:"Stampanti",archives:"Archivi",queue:"Coda di stampa",stats:"Statistiche",profiles:"Profili",maintenance:"Manutenzione",projects:"Progetti",inventory:"Filamento",files:"File",makerworld:"MakerWorld",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",errorLoading:"Errore di caricamento",retry:"Riprova",success:"Successo",warning:"Avviso",enabled:"Abilitato",disabled:"Disabilitato",yes:"Si",no:"No",on:"On",off:"Spento",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"},toolbar:{filters:"Filtri",view:"Vista",actions:"Azioni"},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:"Telecamera",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",connectionFailedNotAdded:"Impossibile connettersi alla stampante. Verifica IP, numero di serie e codice di accesso e conferma che la modalità solo LAN sia attiva. La stampante non è stata aggiunta.",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",loadInitiated:"Caricamento filamento…",unloadInitiated:"Scaricamento filamento…",failedToLoad:"Caricamento filamento fallito",failedToUnload:"Scaricamento filamento fallito"},connection:{connected:"Connesso",offline:"Offline"},plateStatus:{markCleared:"Segna il piatto come liberato",cleared:"Piatto libero",notCleared:"Piatto non libero",inUse:"Piatto in uso"},queue:{inQueue:"{{count}} stampa in coda",inQueue_plural:"{{count}} stampe in coda"},controls:"Controlli",rfid:{reread:"Rileggi RFID"},ams:{load:"Carica",unload:"Scarica"},bedJog:{title:"Muovi il piano di stampa",bed:"Piano",step:"Passo (mm)",up:"Sposta piano su",down:"Sposta piano giù",disabledWhilePrinting:"Disabilitato durante la stampa",notHomedTitle:"Stampante non azzerata",notHomedMessage:"La stampante non è stata azzerata dall'ultima stampa. Esegui prima l'azzeramento automatico per un posizionamento sicuro (parcheggia la testa di stampa, poi azzera X, Y e Z), oppure muovi comunque — i finecorsa software verranno ignorati.",homeZ:"Azzeramento automatico",moveAnyway:"Muovi comunque",homingStarted:"Azzeramento automatico in corso…"},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",haToggleTitle:'Commuta "{{name}}"',haToggleMessage:"Commutare l'entità Home Assistant {{entity}}? Questo potrebbe spegnere l'alimentazione se attualmente è accesa.",haToggleWarning:`AVVISO: "{{name}}" sta stampando! La commutazione di {{entity}} potrebbe togliere l'alimentazione e interrompere la stampa. Continuare?`,haToggleButton:"Commuta"},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.",availableVersions:"Versioni disponibili",usable:"Utilizzabile",unavailable:"Non disponibile",installed:"Installato",newerBadge:"più recente",olderBadge:"più vecchio",currentBadge:"attuale"},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:"Codice QR",viewPhotos:"Vedi foto",viewPhotosCount:"Vedi foto ({{count}})",projectPage:"Pagina progetto",addToFavorites:"Aggiungi ai preferiti",removeFromFavorites:"Rimuovi dai preferiti",edit:"Modifica",printLog:"Registro stampe",goToProject:"Vai al progetto: {{name}}",addToProject:"Aggiungi al progetto",removeFromProject:"Rimuovi dal progetto",loading:"Caricamento...",noProjectsAvailable:"Nessun progetto disponibile",searchProjects:"Cerca progetti…",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"},platePicker:{title:"Seleziona la piastra da visualizzare",hint:"Questo archivio contiene più piastre. Scegline una da aprire nel visualizzatore GCode.",plateLabel:"Piastra {{index}}",objectCount:"{{count}} oggetto",objectCount_plural:"{{count}} oggetti",noGcode:"Questo archivio non contiene G-code generato da visualizzare. Aprilo prima in Bambu Studio per sezionarlo."},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}}",runsBadge:"{{count}} stampe",runsBadgeTitle:"{{count}} stampe in totale — {{successful}} riuscite, {{failed}} fallite. Fai clic per vedere il registro completo.",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"},runLog:{title:"Registro stampe",modalTitle:"Registro stampe — {{name}}",modalTitleFallback:"questo archivio",empty:"Nessun evento di stampa ancora registrato per questo archivio.",col:{date:"Data",status:"Stato",duration:"Durata",filament:"Filamento",cost:"Costo"},status:{completed:"Completata",failed:"Fallita",cancelled:"Annullata",stopped:"Interrotta",skipped:"Saltata",printing:"In stampa"}},modal:{deleteArchive:"Elimina Archivio",deleteConfirm:'Sei sicuro di eliminare "{{name}}"? Questa azione non può essere annullata.',deleteButton:"Elimina",deletePurgeStats:"Rimuovi anche questa stampa dalle Quick Stats (filamento, tempo, costo, energia)",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",clearPlateSuccess:"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…",awaitingPrinter:"In attesa della stampante…",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:"Statistiche",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:"Flusso",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",security:"Sicurezza",spoolbuddy:"SpoolBuddy"},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.",advanced:"Avanzate",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",spoolmanAmsSyncButton:"Sincronizza i pesi Spoolman dall'AMS",spoolmanAmsSyncTitle:"Sincronizza i pesi delle bobine Spoolman dall'AMS",spoolmanAmsSyncMessage:"Questo aggiornerà i pesi di tutte le bobine Spoolman in base ai valori di riempimento AMS correnti delle stampanti connesse. Le stampanti devono essere online.",spoolmanAmsSyncing:"Sincronizzazione...",spoolmanAmsSyncSuccess:"{{synced}} bobina/e sincronizzata/e, {{skipped}} saltata/e",spoolmanAmsSyncError:"Impossibile sincronizzare i pesi Spoolman dall'AMS",spoolmanAmsSyncErrorUnreachable:"Sincronizzazione fallita (Spoolman non raggiungibile)",spoolmanAmsSyncErrorNotConfigured:"Sincronizzazione fallita (Spoolman non configurato)",spoolmanNotConfigured:"Spoolman non configurato",spoolmanFilamentCatalogTitle:"Catalogo filamenti Spoolman",spoolmanFilamentCatalogDesc:"Nomi dei filamenti e pesi tara dalla tua istanza Spoolman. Nome e peso bobina sono modificabili qui; tutte le altre proprietà sono gestite direttamente in Spoolman.",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:"Registro",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",cloudAccess:"Consenti accesso cloud",cloudAccessDescription:"Legge i preset e i filamenti Bambu Cloud per tuo conto. Richiede l'accesso a Bambu Cloud.",cloudBadge:"Cloud",updateEnergyCost:"Aggiorna prezzo elettricità",updateEnergyCostDescription:"Consenti a questa chiave di inviare in POST un nuovo prezzo elettricità per kWh a /settings/electricity-price. Utile per automazioni Home Assistant a tariffa dinamica (Tibber, Octopus, ecc.). Questo è l'unico campo di impostazioni scrivibile via API key.",energyCostBadge:"Energia",legacyKey:"Legacy",legacyKeyTooltip:"Creato prima della proprietà per utente; ricreare per accesso cloud",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:"Avvio scaglionato",staggeredStartDescription:"Dimensione gruppo e intervallo predefiniti per scaglionare avvii di batch multi-stampante. Sovrascrivibili per batch nella finestra di stampa.",plateClear:"Conferma piatto libero",requirePlateClear:"Richiedi conferma piatto libero",requirePlateClearDescription:'Quando questa opzione è abilitata, lo scheduler attende una conferma per stampante che il piatto sia libero prima di avviare le stampe in coda su stampanti con lavori completati. Disabilitandola vengono nascosti anche il badge di stato del piatto e il pulsante "Segna il piatto come liberato" sulle schede stampante.',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:"Dimensione gruppo",staggerGroupSizeHelp:"Stampanti da avviare simultaneamente per gruppo",staggerInterval:"Intervallo (minuti)",staggerIntervalHelp:"Ritardo tra l'avvio di ogni gruppo",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:"Amministratore",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",passwordRequirements:"Almeno 8 caratteri, con una maiuscola, una minuscola, una cifra e un carattere speciale.",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",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev hanno bug CLI noti che bloccano lo slicing di molti 3MF creati da Bambu — vedi le issue upstream #12426 (segfault su file multi-estrusore dipinti) e #13386 (rifiuto della validazione rigorosa dei range di parametri). Bambu Studio è raccomandato finché non arrivano le correzioni upstream.",useSlicerApi:"Usa Slicer API",useSlicerApiDescription:'Se attivo, le azioni "Slice" aprono il modale slicer integrato e chiamano il sidecar slicer-API. Se disattivo (predefinito), inoltrano al slicer desktop tramite schema URI.',slicerCard:"Slicer",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"URL del container sidecar slicer-API. Lascia vuoto per usare le variabili d'ambiente SLICER_API_URL / BAMBU_STUDIO_API_URL.",slicerBundles:{title:"Bundle slicer",description:'Importa un Printer Preset Bundle (.bbscfg) esportato da BambuStudio (File → Esporta → Esporta bundle preset → "Printer preset bundle"). Una volta importato, le richieste di slicing possono scegliere preset dal bundle per nome senza ricaricare il triplet di profili JSON.',uploadButton:"Carica bundle",uploading:"Caricamento…",loading:"Caricamento bundle…",empty:"Nessun bundle importato ancora.",summary:"{{processCount}} processo · {{filamentCount}} preset filamento",delete:"Elimina",uploadSuccess:"{{name}} importato",uploadError:"Caricamento bundle fallito: {{message}}",deleteSuccess:"Bundle rimosso",deleteError:"Eliminazione bundle fallita: {{message}}",confirmDeleteTitle:"Rimuovere questo bundle?",confirmDeleteMessage:'Le richieste di slicing che fanno riferimento a "{{name}}" falliranno fino al re-import del bundle.'},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 8 caratteri",passwordNeedsUppercase:"La password deve contenere almeno una lettera maiuscola",passwordNeedsLowercase:"La password deve contenere almeno una lettera minuscola",passwordNeedsDigit:"La password deve contenere almeno una cifra",passwordNeedsSpecial:"La password deve contenere almeno un carattere speciale",enterGroupName:"Inserisci un nome gruppo",settingsSaved:"Impostazioni salvate",noPermissionUpdate:"Non hai il permesso di modificare le impostazioni",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",material:"Materiale",spoolWeight:"Peso bobina",color:"Colore",updateSpoolWeight:"Aggiorna peso bobina",filamentUpdated:"Filamento aggiornato",filamentUpdateFailed:"Aggiornamento filamento non riuscito",filamentUpdateInvalid:"Dati filamento non validi",keepExistingSpoolWeight:"Mantieni vecchio peso per le bobine esistenti",keepExistingSpoolWeightDesc:"Le bobine già create con questo tipo di filamento mantengono il vecchio peso tara. Le nuove bobine usano il valore aggiornato.",applyToAllSpools:"Applica a tutte le bobine",applyToAllSpoolsDesc:"Tutti i calcoli del peso per questo tipo di filamento usano immediatamente il nuovo peso tara."},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)",cameraSnapshotUrl:"URL istantanea (facoltativo)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"URL singolo frame usato per miniature di notifica, foto di fine, frame del layer timelapse e rilevamento del piano. Timelapse e rilevamento del piano richiedono ciascuno il proprio toggle per stampante — questo URL è solo la sorgente immagine che usano quando attivi. Lascia vuoto per acquisire dallo stream live sopra. Utile per go2rtc (/api/frame.jpeg) e telecamere IP con endpoint snapshot dedicato.",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:",updateViaHomeAssistant:"Gli aggiornamenti sono gestiti dal Supervisor di Home Assistant. Apri Impostazioni → Add-on → Bambuddy in Home Assistant per installare la nuova versione.",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.",refreshIcon:"Aggiorna icona",removeIcon:"Rimuovi icona",iconRefreshed:"Icona aggiornata.",iconRemoved:"Icona rimossa.",iconFetchFailed:"Impossibile recuperare l'icona dall'URL del provider.",deleteTitle:"Elimina provider",deleteMessage:'Eliminare "{{name}}"? Tutti gli account collegati verranno disconnessi.',form:{name:"Nome visualizzato",issuerUrl:"URL emittente",clientId:"ID client",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",emailClaim:"Claim email",emailClaimDesc:"Claim JWT usato come identità email. Usare 'preferred_username' o 'upn' per Azure Entra ID (che non invia email_verified). Usare solo nomi di claim affidabili.",emailClaimPlaceholder:"e-mail",emailClaimCustomClaimAutoLinkWarning:"I claim personalizzati sono sicuri per il collegamento automatico solo se il valore è gestito dal tenant (es. Azure Entra ID upn / preferred_username). Non abilitare il collegamento automatico se il tuo IdP consente agli utenti di auto-assegnare questo claim.",requireEmailVerified:"Richiedi verifica email",requireEmailVerifiedDesc:"Accetta il claim email solo se il provider lo contrassegna come verificato.",requireEmailVerifiedWarning:"Attenzione: l'email sarà accettata senza verifica. Usare solo con provider affidabili.",requireEmailVerifiedAutoLink:"Disabilitare prima il collegamento automatico per modificare questa impostazione.",defaultGroup:"Gruppo predefinito",defaultGroupDesc:"Gruppo assegnato agli utenti creati automaticamente. Ritorno a Viewers se non impostato.",defaultGroupViewersFallback:"Viewers (predefinito)"}},encryption:{title:"Stato crittografia MFA",enabledFromEnv:"Crittografia a riposo abilitata (chiave dalla variabile d'ambiente MFA_ENCRYPTION_KEY)",enabledFromFile:"Crittografia a riposo abilitata (chiave caricata dalla directory dei dati)",enabledGenerated:"Crittografia a riposo abilitata con chiave auto-generata",notConfigured:"Crittografia a riposo non configurata",notConfiguredDesc:"I segreti TOTP e i client_secrets OIDC sono memorizzati in chiaro. Imposta MFA_ENCRYPTION_KEY o riavvia Bambuddy con una directory dati scrivibile per generarne uno automaticamente.",allEncrypted:"Tutti i segreti MFA sono crittografati a riposo.",legacyRowsLabel:"Righe legacy in chiaro",encryptedRowsLabel:"Righe crittografate",legacyRowsWarning:"Rilevate {{count}} righe legacy in chiaro. Salva di nuovo il provider OIDC o re-iscrivi l'app authenticator dell'utente per migrare allo storage crittografato.",backupHint:"La chiave generata automaticamente è memorizzata in DATA_DIR/.mfa_encryption_key ed è inclusa nei backup locali ZIP. Mantieni sicuri i tuoi backup o imposta MFA_ENCRYPTION_KEY esplicitamente.",decryptionBrokenTitle:"Chiave di crittografia mancante",decryptionBrokenError:"{{count}} record crittografati non possono essere decifrati perché la chiave di crittografia non è più disponibile. Ripristina il precedente MFA_ENCRYPTION_KEY o DATA_DIR/.mfa_encryption_key per recuperare.",migrationErrorWarning:"{{count}} riga/righe legacy non sono state ricifrate all'avvio. Controlla i log del server e riavvia Bambuddy per riprovare."},spoolbuddy:{infoTitle:"Dispositivi SpoolBuddy",infoBody:"I kiosk SpoolBuddy si registrano automaticamente tramite heartbeat. Annulla la registrazione qui se un dispositivo non è più in uso o se un duplicato obsoleto è rimasto dopo un crash del daemon.",duplicatesTitle:"{{count}} dispositivi registrati",duplicatesBody:"Solo il primo dispositivo registrato viene utilizzato dall'interfaccia kiosk. Se uno di questi è un duplicato obsoleto da un crash, annulla la sua registrazione — un dispositivo online si ri-registrerà al prossimo heartbeat.",empty:"Nessun dispositivo SpoolBuddy registrato.",online:"Online",offline:"Offline",unregister:"Annulla registrazione",unregisterSuccess:"Dispositivo deregistrato",unregisterError:"Deregistrazione non riuscita",confirmTitle:"Annullare la registrazione del dispositivo SpoolBuddy?",confirmBody:'Questo rimuoverà "{{hostname}}" ({{deviceId}}) dal database. Se il dispositivo è online, si ri-registrerà al prossimo heartbeat.',ipAddress:"Indirizzo IP",firmware:"Firmware",lastSeen:"Ultimo rilevamento",daemonUptime:"Uptime del daemon",systemUptime:"Uptime sistema",never:"mai",nfc:"NFC",scale:"Bilancia",cpuTemp:"Temp. CPU",memory:"Memoria",disk:"Disco",update:"Aggiorna",updateConfirmTitle:"Aggiornare il daemon Spoolbuddy?",updateConfirmBody:`Avviare un aggiornamento software su "{{hostname}}"? Il daemon si riavvierà al termine dell'aggiornamento.`,restartBrowser:"Riavvia browser",restartBrowserConfirmTitle:"Riavviare il browser del kiosk?",restartBrowserConfirmBody:'Riavviare il browser del kiosk su "{{hostname}}"? Il display si oscurerà brevemente.',restartDaemon:"Riavvia daemon",restartDaemonConfirmTitle:"Riavviare il daemon Spoolbuddy?",restartDaemonConfirmBody:'Riavviare il daemon Spoolbuddy su "{{hostname}}"? Il dispositivo sarà offline per alcuni secondi.',reboot:"Riavvia",rebootConfirmTitle:"Riavviare il dispositivo?",rebootConfirmBody:'Riavviare "{{hostname}}"? Il dispositivo sarà offline per circa un minuto.',shutdown:"Spegni",shutdownConfirmTitle:"Spegnere il dispositivo?",shutdownConfirmBody:'Spegnere "{{hostname}}"? Sarà necessario un accesso fisico per riaccenderlo.',commandConfirm:"Conferma",commandQueued:"Comando in coda",commandError:"Invio comando non riuscito"}},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:"Argomento",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...",rememberMe:"Ricordami",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."},resetPassword:{title:"Imposta nuova password",subtitle:"Inserisci e conferma la nuova password qui sotto.",newPassword:"Nuova password",newPasswordPlaceholder:"Almeno 8 caratteri",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Ripeti la nuova password",saving:"Salvataggio…",submit:"Imposta nuova password",backToLogin:"Torna al login",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve avere almeno 8 caratteri",resetFailed:"Reimpostazione non riuscita. Il link potrebbe essere scaduto."}},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:"Istantanea",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:"Reimposta zoom",recording:"Registrazione",startRecording:"Avvia registrazione",stopRecording:"Ferma registrazione",chamberLight:"Accendi/Spegni luce camera",unavailable:"Telecamera non disponibile",diagnose:{button:"Diagnostica",modalTitle:"Diagnostica telecamera",running:"Diagnostica in corso...",runFailed:"Impossibile eseguire la diagnostica: {{error}}",retry:"Riesegui",stage:{tcp_reachable:"Raggiungibilità di rete",first_frame:"Acquisizione frame",live_stream_active:"Stream live attivo"},summary:{all_ok:"La telecamera funziona. La diagnostica ha completato tutte le fasi con successo.",live_stream_active_healthy:"La telecamera sta trasmettendo con frame recenti — nessun test necessario.",printer_unreachable:"La stampante non è raggiungibile. Verifica l'indirizzo IP, la connessione di rete e che la stampante sia accesa.",camera_port_closed:"La stampante risponde ma la porta della telecamera è chiusa. Assicurati che la modalità LAN e la modalità sviluppatore siano attive nelle impostazioni della stampante.",no_frame:"Connessione alla telecamera riuscita ma nessun frame ricevuto. Riprova o verifica che la telecamera sia abilitata nelle impostazioni della stampante.",unknown_failure:"Diagnostica della telecamera fallita per motivo sconosciuto. Controlla il log di supporto per i dettagli."},meta:{protocol:"Protocollo",port:"Porta",profile:"Profilo"}}},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:"Amministratore",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",ldapProvisioned:'Utente LDAP "{{username}}" provisionato'},modal:{createUser:"Crea utente",editUser:"Modifica utente",cancel:"Annulla",creating:"Creazione...",saving:"Salvataggio...",saveChanges:"Salva modifiche",advancedAuthSubtitle:"con autenticazione avanzata",tabsAriaLabel:"Origine utente",localTab:"Locale",ldapTab:"LDAP",ldapSearchLabel:"Cerca nella directory",ldapSearchPlaceholder:"Digita un nome utente, nome o e-mail...",ldapMinChars:"Digita almeno 2 caratteri per cercare",ldapTypeToSearch:"Inizia a digitare per cercare nella directory LDAP",ldapSearching:"Ricerca nella directory...",ldapNoResults:"Nessun utente corrispondente nella directory",ldapSearchError:"Ricerca nella directory fallita. Verifica lo stato del server LDAP.",ldapAlreadyProvisioned:"Già provisionato",ldapSelectedLabel:"Selezionato",ldapProvision:"Provisiona utente",ldapProvisioning:"Provisioning...",ldapErrorProvision:"Provisioning fallito. Verifica lo stato del server LDAP e riprova."},form:{username:"Nome utente",usernamePlaceholder:"Inserisci nome utente",email:"E-mail",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:"Profili K"},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:"E-mail",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:"Token di accesso",accessTokenHint:"Incolla il tuo access token Bambu Cloud. Gli account della regione Cina devono usare questa via (vincolati al numero di telefono — login via e-mail non disponibile). Il wiki spiega come recuperare il token dai cookie di MakerWorld.",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",collapse:"Comprimi",collapseFoldersByDefault:"Comprimi le cartelle per impostazione predefinita",expandFoldersByDefault:"Espandi le cartelle per impostazione predefinita",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",noPermissionSlice:"Non hai il permesso di sezionare i file",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...",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"L'URL deve iniziare con http:// o https://",openExternalUrl:"Apri URL del progetto",coverImageLabel:"Immagine di copertina",coverImageAlt:"Immagine di copertina del progetto",coverImageUpload:"Carica",coverImageReplace:"Sostituisci",coverImageRemove:"Rimuovi",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:"Fattore K",temperature:"Temperatura",noFilaments:"Nessun filamento in libreria",deleteConfirm:"Sei sicuro di voler eliminare questo filamento?",importFromPrinter:"Importa da stampante",exportToFile:"Esporta su file"},slice:{title:"Slicing modello",action:"Slice",slicing:"Slicing…",printer:"Profilo stampante",process:"Profilo processo",filament:"Profilo filamento",filamentSlot:"Filamento {{index}} ({{type}})",selectPreset:"— Seleziona un preset —",loadingPresets:"Caricamento preset…",analyzingPlateFilaments:"Analisi filamenti del piano…",analyzingPlateFilamentsHint:"Slicing di anteprima per scoprire quali slot AMS usa questo piano. In cache dopo — la riapertura è istantanea.",previewToast:"Analisi di {{name}} – {{elapsed}}",previewWithProgress:"Analisi di {{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",notUsedByPlate:"— non usato da questo piano",noPresetsForSlot:"Nessun preset disponibile",presetsLoadFailed:"Caricamento preset fallito. Apri Impostazioni → Profili per importarli prima.",allPresetsRequired:"Tutti i preset devono essere selezionati",bundle:"Bundle slicer",bundleNone:"— Nessuno (scegli i preset singolarmente) —",bundleAllRequired:"Devi scegliere il processo del bundle e ogni slot filamento",enqueuing:"Invio lavoro di slicing…",queued:"In coda…",failed:"Slicing fallito. Controlla i log del sidecar.",startedToast:"Slicing di {{name}} in background…",queuedToast:"In coda: {{name}} – {{elapsed}}",runningToast:"Slicing {{name}} – {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",completedToast:"{{name}} sezionato",failedToast:"Slicing di {{name}} fallito: {{detail}}",tier:{local:"Importato",cloud:"Cloud",standard:"Standard"},cloud:{notAuthenticated:"Accedi a Bambu Cloud (Impostazioni → Profili → Cloud) per vedere i preset cloud.",expired:"Sessione Bambu Cloud scaduta – accedi di nuovo per aggiornare i preset cloud.",unreachable:"Bambu Cloud non è raggiungibile. I preset locali e standard funzionano ancora."},bedType:{label:"Piano di stampa",auto:"Auto (usa preset di processo)",coolPlate:"Cool Plate",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},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:"Rimuovere bobina?",unlinkConfirmMessage:"Questo rimuoverà la bobina da questo slot. I dati della bobina stessa rimarranno invariati.",selectSpool:"Seleziona bobina",noUnlinkedSpools:"Nessuna bobina disponibile",linkSuccess:"Bobina assegnata con successo",linkFailed:"Impossibile assegnare la bobina",unlinkSuccess:"Bobina rimossa con successo",unlinkFailed:"Impossibile rimuovere la bobina",linkedSpool:"Bobina assegnata",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",subtitle:"Gestisci le tue bobine",spoolmanMixedContentTitle:"Spoolman non può essere caricato tramite HTTPS — contenuto misto bloccato dal browser",spoolmanMixedContentBody:"Bambuddy viene servito tramite HTTPS (dietro il tuo reverse proxy), ma l'URL di Spoolman è ancora HTTP. I browser bloccano il contenuto misto per motivi di sicurezza, quindi l'interfaccia Spoolman incorporata non può essere visualizzata. Anche Spoolman deve essere raggiungibile via HTTPS.",spoolmanMixedContentFixReverseProxy:"Metti Spoolman dietro lo stesso reverse proxy di Bambuddy (Traefik / Nginx / Caddy) in HTTPS, poi aggiorna l'URL di Spoolman nelle Impostazioni con il nuovo indirizzo HTTPS.",spoolmanMixedContentFixOpenNewTab:"Come alternativa, apri Spoolman in una nuova scheda via HTTP — le regole sul contenuto misto si applicano solo ai frame incorporati, una scheda autonoma funziona.",spoolmanOpenInNewTab:"Apri Spoolman in una nuova scheda",labels:{title:"Stampa etichette bobine",selectedCount:"{{count}} selezionato",pickSpools:"Scegli per quali bobine stampare le etichette:",searchPlaceholder:"Cerca per nome, marca o #ID",filterByMaterial:"Materiale:",allMaterials:"Tutto",selectVisible:"Seleziona tutti visibili ({{count}})",deselectVisible:"Deseleziona visibili",clearAll:"Cancella tutto",noSpoolsToShow:"Nessuna bobina da mostrare. Modifica il filtro e riprova.",noMatches:"Nessuna bobina corrisponde alla ricerca o al filtro corrente.",printOne:"Stampa etichetta per questa bobina",printLabels:"Stampa etichette…",bulkTitle:"Scegli le bobine da etichettare tra le {{count}} mostrate",noSpoolsTitle:"Nessuna bobina da etichettare",error:"Impossibile generare etichette: {{msg}}",sortBy:{label:"Ordina:",id:"Per ID",color:"Per colore"},templates:{amsHolderSmall:{label:"Supporto AMS — piccolo (74 × 33 mm)",hint:"Un'etichetta per pagina; corrisponde all'etichetta stampabile del modello MakerWorld 752566 (Porta-etichette filamento AMS)."},amsHolderLarge:{label:"Supporto AMS — grande (75 × 55 mm)",hint:"Un'etichetta per pagina; si adatta alla variante cartoncino del porta-etichette filamento AMS. Spazio sufficiente per campione colore, marca, materiale, ID e codice QR."},box40x30:{label:"Etichetta scatola (40 × 30 mm)",hint:"Una etichetta per pagina; misura comune DK/Brother, ideale per etichette di sacchetti filamento e contenitori."},box:{label:"Box label (62 × 29 mm)",hint:"Una etichetta per pagina; dimensionata per Brother PT/QL e piccole etichette Dymo."},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"Foglio formato UE; 21 etichette per pagina A4."},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"Foglio formato US; 30 etichette per pagina Letter."}}},addSpool:"Aggiungi Bobina",editSpool:"Modifica Bobina",copySpool:"Copia 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:"Bianco Giada, Rosso Fuoco...",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",storageLocation:"Posizione di archiviazione",storageLocationPlaceholder:"es. Scaffale A, Cassetto 1",openInInventory:"Apri nell'inventario",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...",category:"Categoria",categoryPlaceholder:"es. Produzione, Prototipo, Cliente A",categoryNone:"Senza categoria",storageLocationNone:"Nessuna posizione impostata",lowStockThresholdOverride:"Soglia scorte basse (questa bobina)",lowStockThresholdOverrideHelp:"Lascia vuoto per usare la soglia globale ({{global}}%).",clearRfid:"Cancella tag RFID",rfidCleared:"Tag RFID cancellato",archive:"Archivia",restore:"Ripristina",noSpools:"Ancora nessuna bobina. Aggiungi la tua prima bobina per iniziare.",noAvailableSpools:"Nessuna bobina disponibile. Aggiungi una bobina al tuo inventario o rimuovine l'assegnazione da un altro slot.",kProfiles:"Profili K",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",spoolmanSpools:"Bobine Spoolman",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",spoolsPartiallyCreated:"{{created}} di {{total}} bobine create (alcune non riuscite)",spoolCreated:"Bobina creata",spoolUpdated:"Bobina aggiornata",spoolDeleted:"Bobina eliminata",deepLinkSpoolNotFound:"Bobina non trovata",deepLinkFetchFailed:"Impossibile caricare la bobina — riprova",spoolArchived:"Bobina archiviata",spoolRestored:"Bobina ripristinata",kProfileSaveFailed:"Impossibile salvare le impostazioni del profilo K",syncWeightSpoolNotFound:"Bobina non trovata — potrebbe essere stata eliminata",syncWeightSpoolmanUnreachable:"Spoolman non è raggiungibile — riprovare più tardi",syncWeightFailed:"Sincronizzazione del peso non riuscita",spoolmanUnreachable:"Spoolman non è raggiungibile — riprovare più tardi",deleteSpoolNotFound:"Bobina non trovata — potrebbe essere già stata eliminata",deleteFailed:"Impossibile eliminare la bobina",archiveSpoolNotFound:"Bobina non trovata — potrebbe essere già stata eliminata",archiveFailed:"Impossibile archiviare la bobina",restoreSpoolNotFound:"Bobina non trovata — potrebbe essere già stata eliminata",restoreFailed:"Impossibile ripristinare la bobina",saveFailed:"Impossibile salvare le modifiche",tagClearFailed:"Impossibile cancellare il tag",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",extraColorsLabel:"Colori extra",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"Incolla da 2 a 8 stop hex, separati da virgole. Visualizzato come sfumatura.",extraColorsInvalid:"Hex non validi ignorati: {{tokens}}",colorEffectLabel:"Effetto",colorEffect:{none:"Nessuno",sparkle:"Scintillante",wood:"Legno",marble:"Marmo",glow:"Bagliore",matte:"Opaco",silk:"Silk",galaxy:"Galassia",rainbow:"Arcobaleno",metal:"Metallo",translucent:"Traslucido",gradient:"Sfumatura",dualColor:"Bicolore",triColor:"Tricolore",multicolor:"Multicolore"},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",resetUsage:"Azzera utilizzo",resetUsageTooltip:"Azzera il contatore di grammi consumati per questa bobina",resetUsageConfirm:"Azzerare il contatore di grammi consumati di questa bobina? Le stampe future ripartiranno da zero. La bobina, il calcolo del peso rimanente e le impostazioni non vengono modificati.",resetAllUsage:"Azzera utilizzo di tutte le bobine",resetAllUsageTooltip:"Azzera il contatore di grammi consumati su ogni bobina",resetAllUsageConfirm:'Azzerare il contatore di grammi consumati su tutte le {{count}} bobine (incluse quelle archiviate)? La statistica "Totale Consumato" verrà azzerata e le stampe future ripartiranno da zero. Bobine e pesi rimanenti restano invariati.',usageReset:"Utilizzo della bobina azzerato",allUsageReset:"{{count}} bobina/e azzerata/e",resetUsageFailed:"Impossibile azzerare l'utilizzo della bobina",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?',spoolmanFilamentCatalog:"Catalogo filamenti Spoolman",pickFromSpoolmanCatalog:"Scegli dal catalogo Spoolman…",spoolmanFilamentSelected:"Filamento selezionato dal catalogo Spoolman",spoolmanFilamentUnlinked:"Collegamento al catalogo filamenti rimosso",noSpoolmanFilaments:"Nessun filamento trovato nel catalogo Spoolman",spoolmanFilamentColorSwatch:"Colore del filamento",spoolWeightManagedBySpoolman:"Il peso della bobina vuota è gestito per tipo di filamento in Spoolman",spoolmanCatalogLoadFailed:"Impossibile caricare il catalogo Spoolman"},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",slotEmpty:"Vuoto",emptySlotReset:"Nessuna bobina assegnata",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:"Fattore K",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:"Scaglionare avvii",staggerGroupSize:"Dimensione gruppo",staggerInterval:"Intervallo (min)",staggerPreview:"{{printers}} stampanti → {{groups}} gruppi di {{size}}, avvio ogni {{interval}} min",staggerLastGroup:"ultimo gruppo: {{count}}",staggerTotal:"totale: {{minutes}} min",staggerToPrinters:"Scagliona a {{count}} stampanti",gcodeInjection:"Inietta G-code auto-stampa"},backup:{includesEncryptionKey:"I backup locali includono il file della chiave di crittografia MFA (DATA_DIR/.mfa_encryption_key), quindi un backup ZIP è autonomo. Tratta lo ZIP come sensibile — chiunque abbia il file può decifrare i client secret OIDC e i segreti TOTP contenuti.",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.",repoIsPrivate:"Il repository è privato — è sicuro effettuare il backup.",repoIsPublicWarning:"Il repository è PUBBLICO. I backup di Bambuddy includono credenziali MQTT, token di Home Assistant, token di Prometheus, la tua e-mail Bambu Cloud e i codici di accesso alle stampanti tramite K-profile. Il salvataggio è bloccato finché non rendi privato il repository nelle impostazioni del tuo provider.",repoVisibilityUnknown:"Impossibile determinare la visibilità del repository. Bambuddy rifiuta di eseguire backup su qualsiasi target non confermato come privato; il salvataggio sarà bloccato.",repositoryUrl:"URL del repository",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"Consenti HTTP non sicuro",allowInsecureHttpHint:"Abilita per istanze self-hosted su reti private senza TLS",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",provider:"Provider Git",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"Backup pianificati",scheduledBackupDescription:"Crea automaticamente snapshot di backup secondo una pianificazione. La directory di output può essere montata su un NAS o storage esterno.",frequency:"Frequenza",backupTime:"Tempo",retention:"Conservazione",retentionDescription:"Numero di backup da conservare",outputPath:"Percorso di output",outputPathPlaceholder:"Predefinito: {{path}}",outputPathDescription:"Lasciare vuoto per la posizione predefinita",runNow:"Esegui ora",backupFiles:"File di backup",noScheduledBackups:"Nessun backup ancora",deleteBackup:"Elimina",deleteBackupConfirm:"Eliminare questo file di backup?",backupRunning:"Backup in corso...",scheduledBackupComplete:"Backup completato con successo",scheduledBackupFailed:"Backup fallito",nextBackup:"Prossimo backup",backupSize:"Dimensione",utc:"UTC",defaultPathLabel:"Predefinito:",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:"Deformazione",stringing:"Filamento",underExtrusion:"Sotto-estrusione",powerFailure:"Mancanza corrente",userCancelled:"Annullato dall'utente",other:"Altro"},statuses:{completed:"Completato",failed:"Fallito",aborted:"Annullato",printing:"In stampa"}},kProfiles:{title:"Profili K",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:"Valore K",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:"Alto flusso",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."},queueForceColorMatch:{title:"Forza corrispondenza colori",description:"Rifiuta di inviare a una stampante che non ha esattamente il tipo di filamento e il colore caricato. Disattivato per impostazione predefinita — senza questo, la coda usa solo la corrispondenza per modello e potrebbe scegliere una stampante con il colore sbagliato."},tailscaleDisabled:{title:"Integrazione Tailscale",description:"Abilita per contrassegnare questo VP come esposto tramite Tailscale. Mostra l'indirizzo Tailscale dell'host così sai quale IP incollare nello slicer. Il passo di importazione CA è invariato — questo toggle non ha effetto sui certificati."},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",copyFailed:"Copia non riuscita — seleziona il testo manualmente",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.'},archiveNameSource:{title:"Origine nome archivio",description:'Scegli come vengono nominati i nuovi archivi quando i file arrivano tramite la stampante virtuale. "Metadati" utilizza il titolo incorporato nello slicer dal 3MF (default). "Nome file" utilizza il nome che Bambu Studio ha inviato via FTP — utile se hai rinominato il job nella finestra "invia a stampante".',metadata:"Metadati",filename:"Nome file"}},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:"Alle {{time}}",scheduleOff:"Spento {{time}}",on:"On",off:"Spento",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",autoOffAfterDrying:"Spegni dopo asciugatura",autoOffAfterDryingDescription:"Spegni al termine dell'asciugatura AMS",delayAfterDryingMinutes:"Ritardo dopo asciugatura (minuti)",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:"Argomento",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.
  22. 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.
  23. 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.
  24. Valore ON: la stringa esatta che significa "ON". Lascia vuoto per rilevamento auto (ON, true, 1).`,restControl:"Controllo",restOnUrl:"URL accensione",restOffUrl:"URL spegnimento",restOnBody:"Corpo richiesta ON",restOffBody:"Corpo richiesta OFF",restMethod:"Metodo HTTP",restHeaders:"Custom Headers (JSON)",restStatusUrl:"URL stato",restStatusPath:"Percorso JSON stato",restStatusOnValue:"Valore ON",restPowerUrl:"URL potenza",restPowerPath:"Percorso JSON potenza",restPowerMultiplier:"Moltiplicatore potenza",restEnergyUrl:"URL energia",restEnergyPath:"Percorso JSON energia",restEnergyMultiplier:"Moltiplicatore energia",restUrlRequired:"È richiesto almeno un URL (ON o OFF) per le prese REST",restHeadersHint:'es. {"Authorization": "Bearer your-token"}',restBodyHint:'es. ON, {"state": "on"}',restStatusHint:"URL per recuperare lo stato attuale",restPathHint:"es. state o 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:"Testa connessione",connectionSuccess:"Connessione riuscita",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:"E-mail",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",inventoryAlerts:"Avvisi di inventario",stockReorderAlert:"Avviso di riordino",stockReorderAlertDescription:"Il SKU ha raggiunto il punto di riordino",stockBreakAlert:"Avviso di esaurimento scorte",stockBreakAlertDescription:"Le scorte si esauriranno prima dell'arrivo del rifornimento",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)",eventPriority:{sectionTitle:"Priorità ntfy",helpNtfy:"Scegli una priorità per ogni evento abilitato. ntfy le usa per intensificare gli avvisi (suono, visibilità, comportamento push). I livelli non impostati qui usano l'impostazione predefinita del server ntfy.",min:"Min.",low:"Bassa",default:"Predefinita",high:"Alta",urgent:"Urgente"},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 Git",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:"Etichetta",grossWeight:"Peso lordo",spoolSize:"Dimensione bobina",close:"Chiudi",currentSpool:"Bobina attuale",plateReady:"Piatto pronto: {{name}}",plateReadyLabel:"Piatti da liberare",plateClearAction:"Libera",plateClearedToast:"Piatto contrassegnato come liberato",plateClearFailed:"Impossibile contrassegnare il piatto come liberato"},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!",assignPendingInsert:"Assegnato. Lo slot verrà configurato all'inserimento della bobina.",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/D",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",systemConfig:"Backend & autenticazione",backendUrl:"URL backend Bambuddy",apiToken:"Token API",apiTokenPlaceholder:"Inserisci token API",saveConfig:"Salva configurazione",systemQueued:"Configurazione in coda.",systemFieldsRequired:"L'URL del backend è obbligatorio.",nfcDiagnostic:"Diagnostica NFC",scaleDiagnostic:"Diagnostica bilancia",readTagDiagnostic:"Diagnostica lettura tag",testNfc:"Test lettore",testScale:"Test precisione",testReadTag:"Leggi tag"},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",incompleteDataWarning:"Tag scritto con dati Spoolman incompleti"},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:"Schermata",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'istantanea della telecamera tramite URL. Imposta l'URL esterno nelle impostazioni generali in modo che il container API ML 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."},makerworld:{title:"MakerWorld",description:"Incolla un URL di un modello MakerWorld per importarlo e stamparlo direttamente da Bambuddy — senza passare dall'app Bambu Handy.",pasteUrlHeader:"Importa da MakerWorld",pasteUrlPlaceholder:"https://makerworld.com/en/models/… o incolla qualsiasi link MakerWorld",resolveButton:"Risolvi",signInRequiredTitle:"Accesso Bambu Cloud richiesto per scaricare",signInRequiredBody:"Puoi consultare i dettagli del modello in modo anonimo, ma MakerWorld richiede un account Bambu Cloud per scaricare i file 3MF.",openCloudSettings:"Apri impostazioni Cloud",untitledModel:"Modello senza titolo",byCreator:"di {{name}}",downloadsCount:"{{count}} download",licensePrefix:"Licenza",alreadyImported:"Già nella libreria",openOnMakerworld:"Apri su MakerWorld",alreadyInLibrary:"Questo modello è già nella tua libreria — lo trovi in Gestione file → MakerWorld",importSuccess:"{{filename}} importato — salvato in Gestione file → MakerWorld",platesHeader:"Piatti ({{count}})",plateDefaultName:"Piatto {{n}}",materialCount:"{{count}} filamenti",amsRequired:"AMS richiesto",slicedFor:"Sezionato per {{printer}}",alsoCompatible:"Anche contrassegnato come compatibile: {{printers}}",importToLibrary:"Salva",sliceIn:"Salva e affetta in {{slicer}}",disclaimer:"L'integrazione MakerWorld utilizza endpoint API documentati dalla community. Bambuddy non è affiliato né approvato da MakerWorld o Bambu Lab.",lastImportSuccess:"Importato nella tua libreria",lastImportAlreadyInLibrary:"Già nella tua libreria",viewInLibrary:"Visualizza in Gestione file",openInBambuStudio:"Apri in Bambu Studio",openInOrcaSlicer:"Apri in OrcaSlicer",importTo:"Importa in Gestione file",recentImportsHeader:"Importazioni recenti",phaseResolving:"Risoluzione",phaseDownloading:"Download",folderAuto:"MakerWorld (predefinita)",importAll:"Importa tutto",importAllProgress:"Importazione {{current}}/{{total}}",openGallery:"Apri galleria immagini",galleryPrev:"Immagine precedente",galleryNext:"Immagine successiva",deleteImport:"Rimuovi dalla libreria",importDeleting:"Rimozione…",importDeleted:"Rimosso dalla libreria",confirmDelete:"Rimuovere {{filename}} dalla libreria? Il file locale verrà eliminato, ma il piatto può essere re-importato da MakerWorld.",errors:{resolveFailed:"Impossibile risolvere questo URL MakerWorld.",downloadFailed:"Download non riuscito. Riprova.",deleteFailed:"Impossibile rimuovere il file dalla libreria."}},gcodeViewer:{back:"Indietro",backToArchives:"Torna agli archivi di stampa",backToFiles:"Torna al gestore file"},libraryTrash:{title:"Cestino",headerButton:"Cestino",headerTooltip:"Visualizza i file spostati nel cestino",backToFiles:"Torna al gestore file",subtitleAdmin:"I file eliminati restano qui per {{days}} giorni, poi vengono rimossi automaticamente. Questa vista mostra il cestino di tutti gli utenti.",subtitleUser:"I file eliminati restano qui per {{days}} giorni, poi vengono rimossi automaticamente.",loading:"Caricamento del cestino…",loadError:"Impossibile caricare il cestino.",empty:"Il cestino è vuoto.",summary:"{{count}} file · {{size}}",emptyTrash:"Svuota cestino",restore:"Ripristina",purgeNow:"Elimina ora",autoPurgeIn:"Eliminazione automatica tra {{when}}",days:"giorni",retentionLabel:"Elimina automaticamente dopo",selectAll:"Seleziona tutto",selectOne:"Seleziona {{filename}}",selectionCount:"{{count}} selezionati",bulkRestore:"Ripristina selezionati",bulkPurge:"Elimina selezionati",col:{filename:"File",folder:"Cartella",size:"Dimensione",deleted:"Spostato nel cestino",autoPurge:"Eliminazione auto.",owner:"Proprietario",actions:"Azioni"},confirm:{purgeTitle:"Eliminare definitivamente?",purgeBody:"{{filename}} verrà eliminato dal disco e non potrà essere ripristinato.",emptyTitle:"Svuotare il cestino?",emptyBody:"Tutti i {{count}} file verranno eliminati dal disco. Azione non annullabile.",bulkPurgeTitle:"Eliminare definitivamente i file selezionati?",bulkPurgeBody:"I {{count}} file selezionati verranno eliminati dal disco e non potranno essere ripristinati.",cta:"Elimina definitivamente"},toast:{restored:"File ripristinato.",restoreFailed:"Impossibile ripristinare il file.",purged:"File eliminato definitivamente.",purgeFailed:"Impossibile eliminare il file.",emptied:"{{count}} file eliminati dal cestino.",emptyFailed:"Impossibile svuotare il cestino.",retentionSaved:"Eliminazione automatica impostata su {{days}} giorni.",retentionFailed:"Impossibile salvare l'impostazione di conservazione.",bulkRestored:"{{count}} file ripristinati.",bulkPurged:"{{count}} file eliminati."}},libraryPurge:{title:"Elimina file vecchi",headerButton:"Elimina vecchi",headerTooltip:"Sposta in blocco i file vecchi nel cestino",description:"I file più vecchi della soglia verranno spostati nel cestino. Le cartelle esterne vengono ignorate. Puoi ripristinarli dal cestino prima dell'eliminazione automatica.",ageLabel:"Sposta i file più vecchi di",days:"giorni",includeNeverPrinted:"Includi i file mai stampati",effectsTitle:"Cosa succede quando fai clic su Pulisci",effect1:"I file corrispondenti vengono spostati nel cestino — non sono ancora eliminati dal disco.",effect2:"Puoi ripristinarli dal cestino in qualsiasi momento fino alla scadenza del periodo di conservazione.",effect3:"Dopo il periodo di conservazione, lo spazzino del cestino li rimuove definitivamente.",effect4:"I file in cartelle esterne (collegate) vengono saltati — Bambuddy non elimina mai dati che non possiede.",previewLoading:"Verifica quanti file corrispondono…",previewFailed:"Impossibile mostrare l'anteprima.",previewSummary:"{{count}} file · {{size}} verrebbero spostati nel cestino",andMore:"…e altri {{count}}",warning:"I file vengono eliminati in modo soft — puoi ripristinarli dal cestino fino alla scadenza del periodo di conservazione.",confirmCta:"Sposta {{count}} nel cestino",purging:"Spostamento nel cestino…",toast:{success:"{{count}} file spostati nel cestino.",failed:"Impossibile eliminare i file."}},libraryAutoPurge:{enableLabel:"Elimina automaticamente i file vecchi",enableDescription:"Esegue l'eliminazione amministrativa una volta al giorno. I file finiscono prima nel cestino — non vengono eliminati immediatamente.",ageLabel:"Elimina automaticamente i file più vecchi di",ageDescription:"Minimo 7 giorni, massimo 10 anni. Usa la stessa regola di età del pulsante Elimina manuale.",days:"giorni",includeNeverPrinted:"Includi i file mai stampati",saveFailed:"Impossibile salvare le impostazioni di eliminazione automatica."},archivePurge:{headerButton:"Elimina vecchi",headerTooltip:"Eliminazione massiva vecchi archivi",title:"Elimina vecchi archivi",description:"Cancella la vecchia cronologia di stampa. Ogni archivio invecchia in base alla sua ultima stampa completata — ristampare azzera l'età, quindi il lavoro attivo non viene mai eliminato.",ageLabel:"Elimina archivi non stampati negli ultimi",days:"giorni",effectsTitle:"Cosa succede quando fai clic su Pulisci",effect1:"Ogni archivio corrispondente viene nascosto dagli elenchi e i suoi file vengono rimossi dal disco (3MF, miniatura, timelapse, 3MF sorgente, F3D, foto).",effect2:"La riga dell'archivio rimane nel database, così le Quick Stats conservano il contributo di filamento, tempo, costo ed energia — come il comportamento predefinito dell'eliminazione singola.",effect3:"Spunta «Rimuovi anche dalle statistiche» qui sotto per eliminare anche il contributo dalle Quick Stats (equivalente all'opzione dell'eliminazione singola). Questo percorso è irreversibile.",effect4:"Ristampare un archivio azzera il suo conteggio dell'età, quindi gli archivi attivi sono al sicuro.",purgeStatsLabel:"Rimuovi anche dalle statistiche",purgeStatsHint:"Rimuove gli archivi selezionati dalle Quick Stats (filamento, tempo, costo, energia). Senza questa opzione le Quick Stats conservano ogni contributo e solo i file vengono cancellati.",previewLoading:"Verifica del numero di archivi corrispondenti…",previewFailed:"Impossibile visualizzare l'anteprima della pulizia.",previewSummary:"{{count}} archivi · {{size}} verrebbero rimossi",andMore:"…e altri {{count}}",warning:"I file vengono rimossi dal disco e non possono essere ripristinati. Scarica o aggiungi ai preferiti tutto ciò che vuoi conservare prima di continuare.",confirmCta:"Rimuovi {{count}} archivio(i)",purging:"Rimozione…",toast:{success:"{{count}} archivio(i) rimosso.",failed:"Impossibile eliminare gli archivi."}},archiveAutoPurge:{enableLabel:"Elimina auto. vecchi archivi",enableDescription:"Una volta al giorno nasconde dagli elenchi gli archivi non stampati entro la soglia e rimuove i loro file dal disco. Ristampare azzera il timer.",ageLabel:"Eliminazione auto. di archivi non stampati negli ultimi",ageDescription:"Minimo 7 giorni, massimo 10 anni. Basato sull'ultima stampa completata — ristampare azzera l'età. Rimuove 3MF, miniatura, timelapse, 3MF sorgente, F3D e foto.",days:"giorni",purgeStatsLabel:"Rimuovi anche dalle statistiche",purgeStatsDescription:"Quando abilitato, lo sweeper giornaliero elimina anche il contributo di ogni archivio purgato dalle Quick Stats (filamento, tempo, costo, energia). Disabilitato per impostazione predefinita — le Quick Stats mantengono il contributo e solo i file vengono cancellati.",runNow:"Elimina archivi ora",saveFailed:"Impossibile salvare le impostazioni di pulizia automatica."},cameraTokens:{title:"Token API telecamera",navTitle:"Token API telecamera",description:"Token a lunga durata per incorporare lo stream della telecamera in Home Assistant, Frigate, chioschi o qualsiasi altro strumento che richieda un URL stabile. Ogni token è limitato allo stream della telecamera e può essere revocato in qualsiasi momento.",loading:"Caricamento…",confirmRevoke:{title:"Revocare questo token?",body:`Qualsiasi dispositivo che usa "{{name}}" perderà l'accesso immediatamente. Non può essere annullato.`,cancel:"Annulla",confirm:"Revoca"},create:{title:"Crea nuovo token",nameLabel:"Nome token",namePlaceholder:"es. Home Assistant",daysLabel:"Giorni alla scadenza",submit:"Crea",hint:"Durata massima 365 giorni. Il valore del token viene mostrato solo alla creazione — copialo ora."},created:{title:"Token creato – copialo ora",warning:"Questa è l'unica volta in cui questo token sarà visibile. Dopo la chiusura di questa finestra non potrai più visualizzarlo.",copy:"Copia",dismiss:"L'ho salvato"},list:{myTitle:"I miei token",allTitle:"Tutti gli utenti (vista admin)",empty:"Nessun token ancora.",name:"Nome",owner:"Proprietario",prefix:"Prefisso",created:"Creato",expires:"Scade",lastUsed:"Ultimo uso",revoke:"Revoca",expired:"Scaduto"},toast:{created:"Token creato",createFailed:"Creazione token fallita",revoked:"Token revocato",revokeFailed:"Revoca token fallita",loadFailed:"Caricamento token fallito",copied:"Copiato negli appunti",copyFailed:"Copia non riuscita – seleziona e copia manualmente"}},forecast:{title:"Previsione scorte",noSpools:"Nessuna bobina attiva trovata. Aggiungi bobine al tuo inventario per vedere i dati di previsione.",noUsageData:"Nessun dato di utilizzo disponibile — impossibile proiettare la timeline delle scorte.",sku:"SKU",material:"Materiale",stock:"Scorte",dailyRate:"Tasso",daysLeft:"Giorni rimanenti",emptyBy:"Esaurimento previsto",reorderBy:"Riordinare entro",actions:"Azioni",trend:"Tendenza",estimated:"Stim.",noData:"Nessun dato",timeframe:"Periodo",chartTitle:"Stock proiettato — Top 5 materiali",dashedLinesROP:"Linee tratteggiate = punti di riordino",stockLevel:"Livello scorte",reorderPoint:"Punto di riordino",safetyMargin:"Margine di sicurezza",trendLegend:"Tendenza (basata su storico, livello servizio 95%)",estimatedLegend:"Stimata (delta peso)",noDataLegend:"Nessun dato",ropLabel:"PR",ssLabel:"SS",safetyStockLegend:"Scorta di sicurezza",stockArrivalLegend:"Arrivo merce",stockoutLegend:"Esaurimento scorte",alertCount_one:"{{count}} avviso",alertCount_other:"{{count}} avvisi",order:"Ordina",globalLeadTime:"Lead time globale",globalLeadTimeHint:"Lead time globale minimo — usato nel calcolo del punto di riordino per tutti gli SKU",save:"Salva",cancel:"Annulla",settingsSaved:"Impostazioni salvate",failedSaveSettings:"Impossibile salvare le impostazioni",globalLeadTimeSaved:"Lead time globale salvato",skuLeadTimeOverride:"Override lead time SKU",skuLeadTimeHint:"0 = usa lead time globale. Imposta >0 per sovrascrivere per questo SKU.",safetyMarginLabel:"Margine di sicurezza",effectiveLeadTime:"Lead time effettivo",effectiveLeadTimeHint:"max(globale {{global}}g, SKU {{sku}}g)",reorderPointHint:"d̄ × LT + safety margin — ordina quando le scorte raggiungono questo livello",safetyMarginHint:"Scorta di sicurezza statistica (z=1,65 × σ × √LT) + buffer definito dall'utente",safetyMarginHintDays:"Buffer aggiunto sulla scorta di sicurezza statistica.{{approx}}",safetyMarginHintDaysApprox:" ≈ {{g}}g al tasso attuale.",safetyMarginHintG:"Buffer di peso fisso aggiunto sulla scorta di sicurezza statistica.{{approx}}",safetyMarginHintGApprox:" ≈ {{days}}g al tasso attuale.",individualSpools:"Bobine singole",labelWeight:"Etichetta",spoolCount_one:"{{count}} bobina",spoolCount_other:"{{count}} bobine",stockBreakRisk:"Rischio di rottura scorte",stockBreakBefore:"Rottura scorte prima del rifornimento",stockBreakDetail:"{{days}}g rimanenti, lead time {{lt}}g.",reorderNow:"Riordina ora",reorderTriggerPassed:"La data di attivazione {{date}} è passata.",shoppingList:"Lista della spesa",shoppingListItems_one:"({{count}} articolo)",shoppingListItems_other:"({{count}} articoli)",shoppingListEmpty:"La lista della spesa è vuota. Clicca sull'icona del carrello in qualsiasi riga per aggiungere articoli.",addToCart:"Aggiungi alla lista della spesa",alertsSnoozed:"Silenzia avvisi per questo SKU",alertsEnabled:"Riattiva avvisi per questo SKU",addedToCart:"Aggiunto alla lista della spesa",failedAddItem:"Impossibile aggiungere l'articolo",listView:"Lista",logisticsView:"Logistica",qty:"Qtà",weight:"Peso",leadTime:"Lead time",expectedRestock:"Rifornimento previsto",status:"Stato",note:"Nota",pending:"In attesa",purchased:"Acquistato",received:"Ricevuto",markPurchased:"Segna come acquistato",markReceived:"Segna come ricevuto — aggiunge bobine all'inventario",resetToPending:"Ripristina in attesa",remove:"Rimuovi",clearAll:"Cancella tutto",downloadCsv:"CSV",addToCartTitle:"Aggiungi alla lista della spesa",byQuantity:"Per quantità",byDuration:"Per durata",numberOfSpools:"Numero di bobine",lastHowManyDays:"Per quanti giorni deve durare?",noUsageQty:"Nessun dato di utilizzo — quantità impostata a 1.",noteOptional:"Nota (opzionale)",notePlaceholder:"es. per il progetto X, urgente…",addNSpools_one:"Aggiungi {{count}} bobina",addNSpools_other:"Aggiungi {{count}} bobine",onArrival:"All'arrivo",stockBreakIn:"Rottura scorte tra {{days}}g.",stockRunsOutBefore:"Le scorte si esauriscono prima dello scadere del lead time di {{lt}}g.",atRate:"A {{rate}}g/giorno hai bisogno di",moreSpools_one:"{{count}} bobina in più",moreSpools_other:"{{count}} bobine in più",bridgeGap:"per colmare il divario.",noReadAccess:"Non hai il permesso di visualizzare le previsioni di inventario.",noWriteAccess:"Non hai il permesso di modificare le impostazioni di previsione."}},ape={nav:{printers:"Impressoras",archives:"Arquivos",queue:"Fila de impressão",stats:"Estatísticas",profiles:"Perfis",maintenance:"Manutenção",projects:"Projetos",inventory:"Inventário",files:"Gerenciador de Arquivos",makerworld:"MakerWorld",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",errorLoading:"Erro ao carregar",retry:"Tentar novamente",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"},toolbar:{filters:"Filtros",view:"Visualização",actions:"Ações"},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:"Número de série",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",connectionFailedNotAdded:"Não foi possível conectar à impressora. Verifique o IP, o número de série e o código de acesso, e confirme que o modo somente LAN está ativado. A impressora não foi adicionada.",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",loadInitiated:"Carregando filamento…",unloadInitiated:"Descarregando filamento…",failedToLoad:"Falha ao carregar filamento",failedToUnload:"Falha ao descarregar filamento"},connection:{connected:"Conectado",offline:"Offline"},plateStatus:{markCleared:"Marcar placa como liberada",cleared:"Placa liberada",notCleared:"Placa não liberada",inUse:"Placa em uso"},queue:{inQueue:"{{count}} impressão na fila",inQueue_plural:"{{count}} impressões na fila"},controls:"Controles",rfid:{reread:"Releitura de RFID"},ams:{load:"Carregar",unload:"Descarregar"},bedJog:{title:"Mover a mesa de impressão",bed:"Mesa",step:"Passo (mm)",up:"Mover mesa para cima",down:"Mover mesa para baixo",disabledWhilePrinting:"Desativado durante a impressão",notHomedTitle:"Impressora não referenciada",notHomedMessage:"A impressora não foi referenciada desde a última impressão. Execute a referência automática primeiro para um posicionamento seguro (estaciona o cabeçote, depois referencia X, Y e Z), ou mova assim mesmo — os fins de curso de software serão ignorados.",homeZ:"Referência automática",moveAnyway:"Mover assim mesmo",homingStarted:"Referenciando impressora automaticamente…"},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",haToggleTitle:'Alternar "{{name}}"',haToggleMessage:"Alternar a entidade Home Assistant {{entity}}? Isso pode desligar a energia se estiver ligada no momento.",haToggleWarning:'AVISO: "{{name}}" está imprimindo no momento! Alternar {{entity}} pode cortar a energia e interromper a impressão. Continuar?',haToggleButton:"Alternar"},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.",availableVersions:"Versões disponíveis",usable:"Utilizável",unavailable:"Indisponível",installed:"Instalada",newerBadge:"mais recente",olderBadge:"mais antiga",currentBadge:"atual"},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",printLog:"Histórico de impressões",goToProject:"Ir para o projeto: {{name}}",addToProject:"Adicionar ao projeto",removeFromProject:"Remover do projeto",loading:"Carregando...",noProjectsAvailable:"Nenhum projeto disponível",searchProjects:"Pesquisar projetos…",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"},platePicker:{title:"Selecione a placa para visualizar",hint:"Este arquivo contém várias placas. Escolha uma para abrir no visualizador GCode.",plateLabel:"Placa {{index}}",objectCount:"{{count}} objeto",objectCount_plural:"{{count}} objetos",noGcode:"Este arquivo não contém G-code fatiado para visualizar. Abra-o no Bambu Studio para fatiar primeiro."},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}}",runsBadge:"{{count}} impressões",runsBadgeTitle:"{{count}} impressões no total — {{successful}} bem-sucedidas, {{failed}} com falha. Clique para ver o histórico completo.",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"},runLog:{title:"Histórico de impressões",modalTitle:"Histórico de impressões — {{name}}",modalTitleFallback:"este arquivo",empty:"Nenhum evento de impressão registrado para este arquivo ainda.",col:{date:"Data",status:"Status",duration:"Duração",filament:"Filamento",cost:"Custo"},status:{completed:"Concluída",failed:"Falhou",cancelled:"Cancelada",stopped:"Interrompida",skipped:"Ignorada",printing:"Imprimindo"}},modal:{deleteArchive:"Excluir Arquivo",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"? Esta ação não pode ser desfeita.',deleteButton:"Excluir",deletePurgeStats:"Remover também esta impressão das Quick Stats (filamento, tempo, custo, energia)",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:"Etiquetas",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",clearPlateSuccess:"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:"Arquivo desconhecido",unknownPrinter:"Impressora desconhecida",startingPrints:"Iniciando impressões",progressSummary:"{{complete}}/{{total}} concluídos • Despachados: {{dispatched}} • Processando: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dispensar notificação de despacho",cancelDispatchJob:"Cancelar despacho",cancel:"Cancelar",cancelling:"Cancelando…",awaitingPrinter:"Aguardando impressora…",status:{dispatched:"Despachado",processing:"Processando",completed:"Concluído",failed:"Falhou",cancelled:"Cancelado"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Despacho cancelado",cancelFailed:"Falha ao cancelar despacho",completeWithFailures:"Despacho em segundo plano concluído: {{completed}} sucesso(s), {{failed}} falha(s)",completeSuccess:"Despacho em segundo plano concluído: {{completed}} sucesso(s)",printStartedRemaining:"{{completed}} impressão(ões) iniciada(s), {{remaining}} enviando..."}},stats:{title:"Estatísticas",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:"Ícone",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:"Fluxo",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",security:"Segurança",spoolbuddy:"SpoolBuddy"},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.",advanced:"Avançado",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",spoolmanAmsSyncButton:"Sincronizar pesos do Spoolman pelo AMS",spoolmanAmsSyncTitle:"Sincronizar pesos dos rolos Spoolman pelo AMS",spoolmanAmsSyncMessage:"Isso atualizará os pesos de todos os rolos Spoolman com base nos valores atuais de % restante do AMS das impressoras conectadas. As impressoras devem estar online.",spoolmanAmsSyncing:"Sincronizando...",spoolmanAmsSyncSuccess:"{{synced}} rolo(s) Spoolman sincronizado(s), {{skipped}} ignorado(s)",spoolmanAmsSyncError:"Falha ao sincronizar pesos do Spoolman pelo AMS",spoolmanAmsSyncErrorUnreachable:"Falha na sincronização (Spoolman inacessível)",spoolmanAmsSyncErrorNotConfigured:"Falha na sincronização (Spoolman não configurado)",spoolmanNotConfigured:"Spoolman não configurado",spoolmanFilamentCatalogTitle:"Catálogo de filamentos Spoolman",spoolmanFilamentCatalogDesc:"Nomes de filamentos e pesos tara da sua instância Spoolman. Nome e peso do carretel são editáveis aqui; todas as outras propriedades são gerenciadas diretamente no Spoolman.",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",cloudAccess:"Permitir acesso à nuvem",cloudAccessDescription:"Lê predefinições e filamentos do Bambu Cloud em seu nome. Requer login no Bambu Cloud.",cloudBadge:"Nuvem",updateEnergyCost:"Atualizar preço da eletricidade",updateEnergyCostDescription:"Permitir que esta chave envie POST de um novo preço por kWh para /settings/electricity-price. Útil para automações de tarifa dinâmica do Home Assistant (Tibber, Octopus, etc.). Este é o único campo de configuração gravável via API key.",energyCostBadge:"Energia",legacyKey:"Legado",legacyKeyTooltip:"Criado antes da propriedade por usuário; recrie para acesso à nuvem",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:"Início escalonado",staggeredStartDescription:"Tamanho de grupo e intervalo padrão ao escalonar inícios de lotes multi-impressora. Pode ser sobrescrito por lote no modal de impressão.",plateClear:"Confirmação de placa livre",requirePlateClear:"Exigir confirmação de placa livre",requirePlateClearDescription:'Quando ativado, o agendador aguarda uma confirmação de placa livre por impressora antes de iniciar impressões na fila em impressoras com trabalhos concluídos. Desativar isso também oculta o indicador de status da placa e o botão "Marcar placa como liberada" nos cartões das impressoras.',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:"Tamanho do grupo",staggerGroupSizeHelp:"Impressoras para iniciar simultaneamente por grupo",staggerInterval:"Intervalo (minutos)",staggerIntervalHelp:"Atraso entre o início de cada grupo",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",passwordRequirements:"Pelo menos 8 caracteres, com uma maiúscula, uma minúscula, um dígito e um caractere especial.",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",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev têm bugs CLI conhecidos que bloqueiam o fatiamento de muitos 3MFs criados pela Bambu — veja issues upstream #12426 (segfault em arquivos multi-extrusor pintados) e #13386 (rejeição de validação estrita de intervalos de parâmetros). Bambu Studio é recomendado até as correções upstream chegarem.",useSlicerApi:"Usar API do fatiador",useSlicerApiDescription:'Quando ativo, as ações "Slice" abrem o modal do fatiador interno e chamam o sidecar slicer-API. Quando inativo (padrão), redirecionam ao fatiador desktop via esquema URI.',slicerCard:"Fatiador",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"URL do contêiner sidecar slicer-API. Deixe em branco para usar SLICER_API_URL / BAMBU_STUDIO_API_URL.",slicerBundles:{title:"Bundles do fatiador",description:'Importe um Printer Preset Bundle (.bbscfg) exportado do BambuStudio (Arquivo → Exportar → Exportar Bundle de Predefinições → "Printer preset bundle"). Após importado, solicitações de fatiamento podem escolher predefinições do bundle por nome sem re-enviar o triplet de perfis JSON.',uploadButton:"Enviar bundle",uploading:"Enviando…",loading:"Carregando bundles…",empty:"Nenhum bundle importado ainda.",summary:"{{processCount}} processo · {{filamentCount}} predefinições de filamento",delete:"Excluir",uploadSuccess:"{{name}} importado",uploadError:"Falha ao enviar bundle: {{message}}",deleteSuccess:"Bundle removido",deleteError:"Falha ao excluir bundle: {{message}}",confirmDeleteTitle:"Remover este bundle?",confirmDeleteMessage:'Solicitações de fatiamento referenciando "{{name}}" falharão até o bundle ser reimportado.'},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 8 caracteres",passwordNeedsUppercase:"A senha deve conter pelo menos uma letra maiúscula",passwordNeedsLowercase:"A senha deve conter pelo menos uma letra minúscula",passwordNeedsDigit:"A senha deve conter pelo menos um dígito",passwordNeedsSpecial:"A senha deve conter pelo menos um caractere especial",enterGroupName:"Por favor, insira um nome de grupo",settingsSaved:"Configurações salvas",noPermissionUpdate:"Você não tem permissão para alterar as configurações",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",material:"Material",spoolWeight:"Peso do carretel",color:"Cor",updateSpoolWeight:"Atualizar peso do carretel",filamentUpdated:"Filamento atualizado",filamentUpdateFailed:"Falha ao atualizar filamento",filamentUpdateInvalid:"Dados de filamento inválidos",keepExistingSpoolWeight:"Manter peso antigo para carretéis existentes",keepExistingSpoolWeightDesc:"Os carretéis já criados com este tipo de filamento mantêm o peso tara antigo. Novos carretéis usam o valor atualizado.",applyToAllSpools:"Aplicar a todos os carretéis",applyToAllSpoolsDesc:"Todos os cálculos de peso para este tipo de filamento usam imediatamente o novo peso tara."},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)",cameraSnapshotUrl:"URL de captura (opcional)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"URL de frame único usado para miniaturas de notificação, fotos de finalização, frames do timelapse por camada e detecção de mesa. Timelapse e detecção de mesa requerem cada um seu próprio toggle por impressora — esta URL é apenas a fonte de imagem que eles usam quando ativos. Deixe em branco para capturar do stream ao vivo acima. Útil para go2rtc (/api/frame.jpeg) e câmeras IP com endpoint de captura dedicado.",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:",updateViaHomeAssistant:"As atualizações são gerenciadas pelo Supervisor do Home Assistant. Abra Configurações → Complementos → Bambuddy no Home Assistant para instalar a nova versão.",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.",refreshIcon:"Atualizar ícone",removeIcon:"Remover ícone",iconRefreshed:"Ícone atualizado.",iconRemoved:"Ícone removido.",iconFetchFailed:"Não foi possível obter o ícone da URL do provedor.",deleteTitle:"Excluir provedor",deleteMessage:'Excluir "{{name}}"? Todas as contas vinculadas serão desconectadas.',form:{name:"Nome de exibição",issuerUrl:"URL do emissor",clientId:"ID do cliente",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",emailClaim:"Claim de e-mail",emailClaimDesc:"Claim JWT usado como identidade de e-mail. Use 'preferred_username' ou 'upn' para Azure Entra ID (que não envia email_verified). Use apenas nomes de claim confiáveis.",emailClaimPlaceholder:"e-mail",emailClaimCustomClaimAutoLinkWarning:"Claims personalizadas são seguras para vinculação automática apenas quando o valor é administrado pelo tenant (ex. Azure Entra ID upn / preferred_username). Não ative a vinculação automática se seu IdP permite que usuários auto-declarem essa claim.",requireEmailVerified:"Exigir e-mail verificado",requireEmailVerifiedDesc:"Aceitar o claim de e-mail apenas quando o provedor o marcar como verificado.",requireEmailVerifiedWarning:"Aviso: o e-mail será aceito sem verificação. Use apenas com provedores confiáveis.",requireEmailVerifiedAutoLink:"Desabilite o vínculo automático primeiro para alterar esta configuração.",defaultGroup:"Grupo padrão",defaultGroupDesc:"Grupo atribuído aos usuários criados automaticamente. Retorna a Viewers se não definido.",defaultGroupViewersFallback:"Viewers (padrão)"}},encryption:{title:"Status de criptografia MFA",enabledFromEnv:"Criptografia em repouso ativa (chave da variável de ambiente MFA_ENCRYPTION_KEY)",enabledFromFile:"Criptografia em repouso ativa (chave do diretório de dados)",enabledGenerated:"Criptografia em repouso ativa com chave auto-gerada",notConfigured:"Criptografia em repouso não configurada",notConfiguredDesc:"Os segredos TOTP e client_secrets OIDC são armazenados em texto plano. Defina MFA_ENCRYPTION_KEY ou reinicie o Bambuddy com um diretório de dados gravável para gerar automaticamente.",allEncrypted:"Todos os segredos MFA são criptografados em repouso.",legacyRowsLabel:"Linhas legadas em texto plano",encryptedRowsLabel:"Linhas criptografadas",legacyRowsWarning:"{{count}} linha(s) legada(s) em texto plano detectada(s). Salve novamente o provedor OIDC ou registre novamente o autenticador do usuário para migrar ao armazenamento criptografado.",backupHint:"A chave auto-gerada é armazenada em DATA_DIR/.mfa_encryption_key e incluída em ZIPs de backup locais. Mantenha seus backups seguros ou defina MFA_ENCRYPTION_KEY explicitamente.",decryptionBrokenTitle:"Chave de criptografia ausente",decryptionBrokenError:"{{count}} registro(s) criptografado(s) não podem ser descriptografados pois a chave de criptografia não está mais disponível. Restaure o MFA_ENCRYPTION_KEY anterior ou DATA_DIR/.mfa_encryption_key para recuperar.",migrationErrorWarning:"{{count}} linha(s) antiga(s) não puderam ser recriptografadas na inicialização. Verifique os logs do servidor e reinicie o Bambuddy para tentar novamente."},spoolbuddy:{infoTitle:"Dispositivos SpoolBuddy",infoBody:"Os kiosks SpoolBuddy se registram automaticamente via heartbeat. Cancele o registro de um dispositivo aqui se não estiver mais em uso ou se um duplicado obsoleto foi deixado por uma falha do daemon.",duplicatesTitle:"{{count}} dispositivos registrados",duplicatesBody:"Apenas o primeiro dispositivo registrado é usado pela interface do kiosk. Se algum destes for um duplicado obsoleto após uma falha, cancele seu registro — um dispositivo online se registrará novamente no próximo heartbeat.",empty:"Nenhum dispositivo SpoolBuddy registrado ainda.",online:"Online",offline:"Offline",unregister:"Cancelar registro",unregisterSuccess:"Dispositivo removido",unregisterError:"Falha ao cancelar registro",confirmTitle:"Cancelar registro do dispositivo SpoolBuddy?",confirmBody:'Isso removerá "{{hostname}}" ({{deviceId}}) do banco de dados. Se o dispositivo estiver online, ele se registrará novamente no próximo heartbeat.',ipAddress:"Endereço IP",firmware:"Firmware",lastSeen:"Visto pela última vez",daemonUptime:"Tempo ativo do daemon",systemUptime:"Tempo ativo do sistema",never:"nunca",nfc:"NFC",scale:"Balança",cpuTemp:"Temp. CPU",memory:"Memória",disk:"Disco",update:"Atualizar",updateConfirmTitle:"Atualizar daemon do Spoolbuddy?",updateConfirmBody:'Iniciar uma atualização de software em "{{hostname}}"? O daemon será reiniciado após a aplicação.',restartBrowser:"Reiniciar navegador",restartBrowserConfirmTitle:"Reiniciar o navegador do kiosk?",restartBrowserConfirmBody:'Reiniciar o navegador do kiosk em "{{hostname}}"? A tela ficará em branco brevemente.',restartDaemon:"Reiniciar daemon",restartDaemonConfirmTitle:"Reiniciar daemon do Spoolbuddy?",restartDaemonConfirmBody:'Reiniciar o daemon do Spoolbuddy em "{{hostname}}"? O dispositivo ficará offline por alguns segundos.',reboot:"Reiniciar",rebootConfirmTitle:"Reiniciar o dispositivo?",rebootConfirmBody:'Reiniciar "{{hostname}}"? O dispositivo ficará offline por cerca de um minuto.',shutdown:"Desligar",shutdownConfirmTitle:"Desligar o dispositivo?",shutdownConfirmBody:'Desligar "{{hostname}}"? Será necessário acesso físico para ligá-lo novamente.',commandConfirm:"Confirmar",commandQueued:"Comando enfileirado",commandError:"Falha ao enviar comando"}},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:"Login Bambuddy",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...",rememberMe:"Lembrar de mim",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",unavailable:"Câmera indisponível",diagnose:{button:"Diagnóstico",modalTitle:"Diagnóstico da câmera",running:"Executando diagnóstico...",runFailed:"Não foi possível executar o diagnóstico: {{error}}",retry:"Executar novamente",stage:{tcp_reachable:"Conectividade de rede",first_frame:"Captura de frame",live_stream_active:"Transmissão ao vivo ativa"},summary:{all_ok:"A câmera está funcionando. O diagnóstico concluiu todas as etapas com sucesso.",live_stream_active_healthy:"A câmera está transmitindo com frames recentes — nenhum teste necessário.",printer_unreachable:"Impressora inacessível. Verifique o endereço IP, a conexão de rede e se a impressora está ligada.",camera_port_closed:"A impressora responde mas a porta da câmera está fechada. Verifique se o modo LAN e o modo desenvolvedor estão ativados nas configurações da impressora.",no_frame:"Conexão com a câmera estabelecida mas nenhum frame recebido. Tente novamente ou verifique se a câmera está habilitada nas configurações da impressora.",unknown_failure:"Diagnóstico da câmera falhou por motivo desconhecido. Consulte o log de suporte para mais detalhes."},meta:{protocol:"Protocolo",port:"Porta",profile:"Perfil"}}},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:"Administrador",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",ldapProvisioned:'Usuário LDAP "{{username}}" provisionado'},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",tabsAriaLabel:"Fonte do usuário",localTab:"Local",ldapTab:"LDAP",ldapSearchLabel:"Pesquisar diretório",ldapSearchPlaceholder:"Digite um nome de usuário, nome ou e-mail...",ldapMinChars:"Digite ao menos 2 caracteres para pesquisar",ldapTypeToSearch:"Comece a digitar para pesquisar o diretório LDAP",ldapSearching:"Pesquisando diretório...",ldapNoResults:"Nenhum usuário correspondente no diretório",ldapSearchError:"Falha na pesquisa do diretório. Verifique o status do servidor LDAP.",ldapAlreadyProvisioned:"Já provisionado",ldapSelectedLabel:"Selecionado",ldapProvision:"Provisionar usuário",ldapProvisioning:"Provisionando...",ldapErrorProvision:"Falha no provisionamento. Verifique o status do servidor LDAP e tente novamente."},form:{username:"Nome de Usuário",usernamePlaceholder:"Insira o nome de usuário",email:"E-mail",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:"Sobreposição de stream",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:"E-mail",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 da Bambu Cloud. Contas da região China precisam usar este caminho (vinculadas ao celular — login por e-mail indisponível). Veja no wiki como obter o token dos cookies do MakerWorld.",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",collapse:"Recolher",collapseFoldersByDefault:"Recolher pastas por padrão",expandFoldersByDefault:"Expandir pastas por padrão",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",noPermissionSlice:"Você não tem permissão para fatiar arquivos",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...",urlLabel:"URL",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"A URL deve começar com http:// ou https://",openExternalUrl:"Abrir URL do projeto",coverImageLabel:"Imagem de capa",coverImageAlt:"Imagem de capa do projeto",coverImageUpload:"Enviar",coverImageReplace:"Substituir",coverImageRemove:"Remover",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:"Registros",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"},slice:{title:"Fatiar modelo",action:"Fatiar",slicing:"Fatiando…",printer:"Perfil de impressora",process:"Perfil de processo",filament:"Perfil de filamento",filamentSlot:"Filamento {{index}} ({{type}})",selectPreset:"— Selecione uma predefinição —",loadingPresets:"Carregando predefinições…",analyzingPlateFilaments:"Analisando filamentos da mesa…",analyzingPlateFilamentsHint:"Executando uma fatia de pré-visualização para descobrir quais slots AMS esta mesa usa. Cacheado depois — reabrir é instantâneo.",previewToast:"Analisando {{name}} – {{elapsed}}",previewWithProgress:"Analisando {{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",notUsedByPlate:"— não usado por esta mesa",noPresetsForSlot:"Nenhuma predefinição disponível",presetsLoadFailed:"Falha ao carregar predefinições. Abra Configurações → Perfis para importá-las primeiro.",allPresetsRequired:"Todas as predefinições devem ser selecionadas",bundle:"Pacote do fatiador",bundleNone:"— Nenhum (escolher predefinições individualmente) —",bundleAllRequired:"O processo do pacote e cada slot de filamento devem ser escolhidos",enqueuing:"Enviando trabalho de fatiamento…",queued:"Na fila…",failed:"Falha ao fatiar. Verifique os logs do sidecar.",startedToast:"Fatiando {{name}} em segundo plano…",queuedToast:"Na fila: {{name}} – {{elapsed}}",runningToast:"Fatiando {{name}} – {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",completedToast:"{{name}} fatiado",failedToast:"Falha ao fatiar {{name}}: {{detail}}",tier:{local:"Importado",cloud:"Nuvem",standard:"Padrão"},cloud:{notAuthenticated:"Faça login no Bambu Cloud (Configurações → Perfis → Nuvem) para ver as predefinições.",expired:"Sessão do Bambu Cloud expirou – faça login novamente para atualizar as predefinições.",unreachable:"Bambu Cloud está inacessível agora. Predefinições locais e padrão ainda funcionam."},bedType:{label:"Mesa de impressão",auto:"Auto (usar predefinição de processo)",coolPlate:"Cool Plate",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},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:"Remover atribuição do carretel?",unlinkConfirmMessage:"Isso removerá o carretel deste slot. Os dados do próprio carretel permanecerão inalterados.",selectSpool:"Selecionar Carretel",noUnlinkedSpools:"Nenhum carretel não atribuído disponível",linkSuccess:"Carretel atribuído com sucesso",linkFailed:"Falha ao atribuir carretel",unlinkSuccess:"Atribuição do carretel removida com sucesso",unlinkFailed:"Falha ao remover atribuição do carretel",linkedSpool:"Carretel atribuído",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",subtitle:"Gerencie seus carretéis",spoolmanMixedContentTitle:"Spoolman não pode carregar em HTTPS — conteúdo misto bloqueado pelo navegador",spoolmanMixedContentBody:"O Bambuddy é servido via HTTPS (pelo seu reverse proxy), mas a URL do Spoolman ainda é HTTP. Os navegadores bloqueiam conteúdo misto por segurança, então a interface embutida do Spoolman não consegue carregar. O Spoolman também precisa estar acessível via HTTPS.",spoolmanMixedContentFixReverseProxy:"Coloque o Spoolman atrás do mesmo reverse proxy do Bambuddy (Traefik / Nginx / Caddy) com HTTPS e atualize a URL do Spoolman em Configurações com o novo endereço HTTPS.",spoolmanMixedContentFixOpenNewTab:"Como alternativa, abra o Spoolman em uma nova aba via HTTP — as regras de conteúdo misto só se aplicam a frames embutidos, uma aba independente funciona normalmente.",spoolmanOpenInNewTab:"Abrir Spoolman em nova aba",labels:{title:"Imprimir etiquetas de bobinas",selectedCount:"{{count}} selecionado",pickSpools:"Escolha para quais bobinas imprimir etiquetas:",searchPlaceholder:"Buscar por nome, marca ou #ID",filterByMaterial:"Material:",allMaterials:"Tudo",selectVisible:"Selecionar todos visíveis ({{count}})",deselectVisible:"Desmarcar visíveis",clearAll:"Limpar tudo",noSpoolsToShow:"Nenhuma bobina para mostrar. Ajuste o filtro e tente novamente.",noMatches:"Nenhuma bobina corresponde à pesquisa ou filtro atual.",printOne:"Imprimir etiqueta desta bobina",printLabels:"Imprimir etiquetas…",bulkTitle:"Escolha bobinas para etiquetar entre as {{count}} exibidas",noSpoolsTitle:"Nenhuma bobina para rotular",error:"Não foi possível gerar etiquetas: {{msg}}",sortBy:{label:"Ordenar:",id:"Por ID",color:"Por cor"},templates:{amsHolderSmall:{label:"Suporte AMS — pequeno (74 × 33 mm)",hint:"Uma etiqueta por página; corresponde à etiqueta imprimível do modelo MakerWorld 752566 (Suporte de etiquetas de filamento AMS)."},amsHolderLarge:{label:"Suporte AMS — grande (75 × 55 mm)",hint:"Uma etiqueta por página; encaixa na variante com inserto em cartão do Suporte de etiquetas de filamento AMS. Espaço suficiente para amostra de cor, marca, material, ID e QR code."},box40x30:{label:"Etiqueta de caixa (40 × 30 mm)",hint:"Uma etiqueta por página; tamanho comum de rolo DK/Brother, ideal para etiquetar sacos de filamento e caixas de armazenamento."},box:{label:"Box label (62 × 29 mm)",hint:"Uma etiqueta por página; tamanho para Brother PT/QL e etiquetas pequenas Dymo."},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"Formato de folha UE; 21 etiquetas por página A4."},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"Formato de folha US; 30 etiquetas por página Letter."}}},addSpool:"Adicionar Carretel",editSpool:"Editar Carretel",copySpool:"Copiar 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:"Branco Jade, Vermelho Fogo...",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",storageLocation:"Local de armazenamento",storageLocationPlaceholder:"ex. Prateleira A, Gaveta 1",openInInventory:"Abrir no inventário",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...",category:"Categoria",categoryPlaceholder:"ex. Produção, Protótipo, Cliente A",categoryNone:"Sem categoria",storageLocationNone:"Sem local definido",lowStockThresholdOverride:"Limite de estoque baixo (este carretel)",lowStockThresholdOverrideHelp:"Deixe em branco para usar o limite global ({{global}}%).",clearRfid:"Limpar tag RFID",rfidCleared:"Tag RFID limpa",archive:"Arquivar",restore:"Restaurar",noSpools:"Nenhum carretel ainda. Adicione seu primeiro carretel para começar.",noAvailableSpools:"Nenhum carretel disponível. Adicione um carretel ao seu inventário ou desatribua um de outro slot 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",spoolmanSpools:"Bobinas Spoolman",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",spoolsPartiallyCreated:"{{created}} de {{total}} carretéis criados (alguns falharam)",spoolCreated:"Carretel criado",spoolUpdated:"Carretel atualizado",spoolDeleted:"Carretel excluído",deepLinkSpoolNotFound:"Carretel não encontrado",deepLinkFetchFailed:"Não foi possível carregar o carretel — tente novamente",spoolArchived:"Carretel arquivado",spoolRestored:"Carretel restaurado",kProfileSaveFailed:"Não foi possível salvar as configurações do perfil K",syncWeightSpoolNotFound:"Carretel não encontrado — pode ter sido excluído",syncWeightSpoolmanUnreachable:"Spoolman está inacessível — tente novamente mais tarde",syncWeightFailed:"Falha ao sincronizar o peso",spoolmanUnreachable:"Spoolman está inacessível — tente novamente mais tarde",deleteSpoolNotFound:"Carretel não encontrado — pode já ter sido excluído",deleteFailed:"Falha ao excluir carretel",archiveSpoolNotFound:"Carretel não encontrado — pode já ter sido excluído",archiveFailed:"Falha ao arquivar carretel",restoreSpoolNotFound:"Carretel não encontrado — pode já ter sido excluído",restoreFailed:"Falha ao restaurar carretel",saveFailed:"Falha ao salvar as alterações",tagClearFailed:"Falha ao limpar a tag",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",extraColorsLabel:"Cores extras",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"Cole 2 a 8 paradas hex, separadas por vírgulas. Renderizado como gradiente.",extraColorsInvalid:"Hex inválidos ignorados: {{tokens}}",colorEffectLabel:"Efeito",colorEffect:{none:"Nenhum",sparkle:"Brilho",wood:"Madeira",marble:"Mármore",glow:"Brilho",matte:"Fosco",silk:"Silk",galaxy:"Galáxia",rainbow:"Arco-íris",metal:"Metal",translucent:"Translúcido",gradient:"Gradiente",dualColor:"Dupla cor",triColor:"Tricolor",multicolor:"Multicolor"},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",resetUsage:"Zerar uso",resetUsageTooltip:"Zerar o contador de gramas consumidas desta bobina",resetUsageConfirm:"Zerar o contador de gramas consumidas desta bobina? As impressões futuras voltarão a contar do zero. A bobina em si, o cálculo do peso restante e as configurações não são alterados.",resetAllUsage:"Zerar uso de todas as bobinas",resetAllUsageTooltip:"Zerar o contador de gramas consumidas em todas as bobinas",resetAllUsageConfirm:'Zerar o contador de gramas consumidas nas {{count}} bobinas (incluindo as arquivadas)? Isso limpa o "Total Consumido" para que as impressões futuras contem do zero. Bobinas e pesos restantes não são alterados.',usageReset:"Uso da bobina zerado",allUsageReset:"{{count}} bobina(s) zerada(s)",resetUsageFailed:"Falha ao zerar o uso da bobina",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?',spoolmanFilamentCatalog:"Catálogo de filamentos Spoolman",pickFromSpoolmanCatalog:"Escolher do catálogo Spoolman…",spoolmanFilamentSelected:"Filamento selecionado do catálogo Spoolman",spoolmanFilamentUnlinked:"Vínculo com o catálogo de filamentos removido",noSpoolmanFilaments:"Nenhum filamento encontrado no catálogo Spoolman",spoolmanFilamentColorSwatch:"Cor do filamento",spoolWeightManagedBySpoolman:"O peso do carretel vazio é gerenciado por tipo de filamento no Spoolman",spoolmanCatalogLoadFailed:"Falha ao carregar catálogo de filamentos do Spoolman"},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",slotEmpty:"Vazio",emptySlotReset:"Nenhum carretel atribuído",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:"Escalonar inícios",staggerGroupSize:"Tamanho do grupo",staggerInterval:"Intervalo (min)",staggerPreview:"{{printers}} impressoras → {{groups}} grupos de {{size}}, iniciando a cada {{interval}} min",staggerLastGroup:"último grupo: {{count}}",staggerTotal:"total: {{minutes}} min",staggerToPrinters:"Escalonar para {{count}} impressoras",gcodeInjection:"Injetar G-code de auto-impressão"},backup:{includesEncryptionKey:"Backups locais incluem o arquivo da chave de criptografia MFA (DATA_DIR/.mfa_encryption_key), então o backup ZIP é autossuficiente. Trate o ZIP como sensível — quem tiver o arquivo pode descriptografar os client secrets OIDC e os segredos TOTP armazenados.",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:"Backup automático",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.",repoIsPrivate:"O repositório é privado — seguro para backup.",repoIsPublicWarning:"O repositório está PÚBLICO. Os backups do Bambuddy incluem credenciais MQTT, tokens do Home Assistant, tokens do Prometheus, seu e-mail do Bambu Cloud e os códigos de acesso das impressoras via K-profiles. Salvar está bloqueado até que você torne o repositório privado nas configurações do seu provedor.",repoVisibilityUnknown:"Não foi possível determinar a visibilidade do repositório. O Bambuddy se recusa a fazer backup em qualquer destino não confirmado como privado; salvar será bloqueado.",repositoryUrl:"URL do repositório",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"Permitir HTTP inseguro",allowInsecureHttpHint:"Ativar para instâncias auto-hospedadas em redes privadas sem TLS",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",provider:"Provedor Git",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"Tomadas inteligentes",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:"Backups agendados",scheduledBackupDescription:"Cria automaticamente snapshots de backup conforme agendamento. O diretório de saída pode ser montado em um NAS ou armazenamento externo.",frequency:"Frequência",backupTime:"Tempo",retention:"Retenção",retentionDescription:"Número de backups a manter",outputPath:"Caminho de saída",outputPathPlaceholder:"Padrão: {{path}}",outputPathDescription:"Deixe em branco para o local padrão",runNow:"Executar agora",backupFiles:"Arquivos de backup",noScheduledBackups:"Sem backups ainda",deleteBackup:"Excluir",deleteBackupConfirm:"Excluir este arquivo de backup?",backupRunning:"Backup em andamento...",scheduledBackupComplete:"Backup concluído com sucesso",scheduledBackupFailed:"Falha no backup",nextBackup:"Próximo backup",backupSize:"Tamanho",utc:"UTC",defaultPathLabel:"Padrão:",categories:{settings:"Configurações",notification_providers:"Provedores de notificação",notification_templates:"Modelos de notificação",smart_plugs:"Tomadas inteligentes",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:"Etiquetas",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:"Etiquetas",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:"Empenamento",stringing:"Fios",underExtrusion:"Subextrusão",powerFailure:"Falha de energia",userCancelled:"Cancelado pelo usuário",other:"Outro"},statuses:{completed:"Concluído",failed:"Falhou",aborted:"Cancelado",printing:"Imprimindo"}},kProfiles:{title:"Perfis K",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."},queueForceColorMatch:{title:"Forçar correspondência de cor",description:"Recusa enviar para uma impressora que não tenha exatamente o tipo e cor de filamento carregados. Desativado por padrão — sem isto, a fila usa apenas correspondência por modelo e pode escolher uma impressora com a cor errada carregada."},tailscaleDisabled:{title:"Integração Tailscale",description:"Ative para marcar este VP como exposto via Tailscale. Mostra o endereço Tailscale do host para você saber qual IP colar no fatiador. A etapa de importação CA é inalterada — este toggle não afeta certificados."},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",copyFailed:"Falha ao copiar — selecione o texto manualmente",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.'},archiveNameSource:{title:"Origem do nome do arquivo",description:'Escolha como os novos arquivos são nomeados quando chegam pela impressora virtual. "Metadados" usa o título embutido pelo slicer no 3MF (padrão). "Nome do arquivo" usa o nome que o Bambu Studio enviou via FTP — útil se você renomeou o job no diálogo "enviar para impressora".',metadata:"Metadados",filename:"Nome do arquivo"}},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:"Administrador",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",autoOffAfterDrying:"Desligar Após Secagem",autoOffAfterDryingDescription:"Desligar quando a secagem do AMS terminar",delayAfterDryingMinutes:"Atraso após secagem (minutos)",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.
  25. 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.
  26. 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.
  27. Valor ON: a string exata que significa "ON". Deixe vazio para detecção automática (ON, true, 1).`,restControl:"Controle",restOnUrl:"URL para ligar",restOffUrl:"URL para desligar",restOnBody:"Corpo da requisição ON",restOffBody:"Corpo da requisição OFF",restMethod:"Método HTTP",restHeaders:"Custom Headers (JSON)",restStatusUrl:"URL de status",restStatusPath:"Caminho JSON de estado",restStatusOnValue:"Valor ON",restPowerUrl:"URL de potência",restPowerPath:"Caminho JSON de energia",restPowerMultiplier:"Multiplicador de potência",restEnergyUrl:"URL de energia",restEnergyPath:"Caminho JSON de energia",restEnergyMultiplier:"Multiplicador de energia",restUrlRequired:"Ao menos uma URL (ON ou OFF) é necessária para tomadas REST",restHeadersHint:'ex. {"Authorization": "Bearer your-token"}',restBodyHint:'ex. ON, {"state": "on"}',restStatusHint:"URL para consultar o estado atual",restPathHint:"ex. state ou 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:"Testar conexão",connectionSuccess:"Conexão bem-sucedida",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",inventoryAlerts:"Alertas de Estoque",stockReorderAlert:"Alerta de Reposição",stockReorderAlertDescription:"O SKU atingiu seu ponto de reposição",stockBreakAlert:"Alerta de Ruptura de Estoque",stockBreakAlertDescription:"O estoque se esgotará antes da chegada do reabastecimento",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)",eventPriority:{sectionTitle:"Prioridade ntfy",helpNtfy:"Escolha uma prioridade para cada evento habilitado. O ntfy usa isso para escalar alertas (som, visibilidade, comportamento push). Níveis não definidos aqui usam o padrão do servidor ntfy.",min:"Mín",low:"Baixa",default:"Padrão",high:"Alta",urgent:"Urgente"},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:"Perfis K",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 Git",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:"Etiqueta",grossWeight:"Peso bruto",spoolSize:"Tamanho do carretel",close:"Fechar",currentSpool:"Carretel Atual",plateReady:"Mesa pronta: {{name}}",plateReadyLabel:"Mesas para liberar",plateClearAction:"Liberar",plateClearedToast:"Mesa marcada como limpa",plateClearFailed:"Não foi possível marcar a mesa como limpa"},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!",assignPendingInsert:"Atribuído. O slot será configurado quando você inserir o carretel.",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/D",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",systemConfig:"Backend e autenticação",backendUrl:"URL do backend Bambuddy",apiToken:"Token de API",apiTokenPlaceholder:"Insira o token de API",saveConfig:"Salvar configuração",systemQueued:"Configuração enfileirada.",systemFieldsRequired:"URL do backend é obrigatória.",nfcDiagnostic:"Diagnóstico NFC",scaleDiagnostic:"Diagnóstico da balança",readTagDiagnostic:"Diagnóstico de leitura de tag",testNfc:"Testar leitor",testScale:"Testar precisão",testReadTag:"Ler tag"},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",incompleteDataWarning:"Tag gravada com dados Spoolman incompletos"},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 definida.",externalUrlHint:"A API ML busca a captura 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."},makerworld:{title:"MakerWorld",description:"Cole uma URL de modelo do MakerWorld para importar e imprimir diretamente do Bambuddy — sem precisar abrir o app Bambu Handy.",pasteUrlHeader:"Importar do MakerWorld",pasteUrlPlaceholder:"https://makerworld.com/en/models/… ou cole qualquer link do MakerWorld",resolveButton:"Resolver",signInRequiredTitle:"Login no Bambu Cloud necessário para baixar",signInRequiredBody:"Você pode navegar pelos detalhes do modelo anonimamente, mas o MakerWorld exige uma conta Bambu Cloud para baixar arquivos 3MF.",openCloudSettings:"Abrir configurações do Cloud",untitledModel:"Modelo sem título",byCreator:"por {{name}}",downloadsCount:"{{count}} downloads",licensePrefix:"Licença",alreadyImported:"Já na biblioteca",openOnMakerworld:"Abrir no MakerWorld",alreadyInLibrary:"Este modelo já está na sua biblioteca — encontre-o em Gerenciador de Arquivos → MakerWorld",importSuccess:"{{filename}} importado — salvo em Gerenciador de Arquivos → MakerWorld",platesHeader:"Placas ({{count}})",plateDefaultName:"Placa {{n}}",materialCount:"{{count}} filamentos",amsRequired:"AMS necessário",slicedFor:"Fatiado para {{printer}}",alsoCompatible:"Também marcado como compatível: {{printers}}",importToLibrary:"Salvar",sliceIn:"Salvar e fatiar no {{slicer}}",disclaimer:"A integração com o MakerWorld usa endpoints de API documentados pela comunidade. Bambuddy não é afiliado nem endossado pelo MakerWorld ou pela Bambu Lab.",lastImportSuccess:"Importado para sua biblioteca",lastImportAlreadyInLibrary:"Já na sua biblioteca",viewInLibrary:"Ver no Gerenciador de Arquivos",openInBambuStudio:"Abrir no Bambu Studio",openInOrcaSlicer:"Abrir no OrcaSlicer",importTo:"Importar para o Gerenciador de Arquivos",recentImportsHeader:"Importações recentes",phaseResolving:"Resolvendo",phaseDownloading:"Baixando",folderAuto:"MakerWorld (padrão)",importAll:"Importar tudo",importAllProgress:"Importando {{current}}/{{total}}",openGallery:"Abrir galeria de imagens",galleryPrev:"Imagem anterior",galleryNext:"Próxima imagem",deleteImport:"Remover da biblioteca",importDeleting:"Removendo…",importDeleted:"Removido da biblioteca",confirmDelete:"Remover {{filename}} da biblioteca? O arquivo local será excluído, mas a placa pode ser reimportada do MakerWorld.",errors:{resolveFailed:"Não foi possível resolver essa URL do MakerWorld.",downloadFailed:"Falha no download. Tente novamente.",deleteFailed:"Não foi possível remover o arquivo da biblioteca."}},gcodeViewer:{back:"Voltar",backToArchives:"Voltar para os arquivos de impressão",backToFiles:"Voltar para o gerenciador de arquivos"},libraryTrash:{title:"Lixeira",headerButton:"Lixeira",headerTooltip:"Ver arquivos movidos para a lixeira",backToFiles:"Voltar ao gerenciador de arquivos",subtitleAdmin:"Arquivos excluídos ficam aqui por {{days}} dias e depois são removidos automaticamente. Esta visualização mostra a lixeira de todos os usuários.",subtitleUser:"Arquivos excluídos ficam aqui por {{days}} dias e depois são removidos automaticamente.",loading:"Carregando a lixeira…",loadError:"Não foi possível carregar a lixeira.",empty:"A lixeira está vazia.",summary:"{{count}} arquivos · {{size}}",emptyTrash:"Esvaziar lixeira",restore:"Restaurar",purgeNow:"Excluir agora",autoPurgeIn:"Exclusão automática em {{when}}",days:"dias",retentionLabel:"Excluir automaticamente após",selectAll:"Selecionar todos",selectOne:"Selecionar {{filename}}",selectionCount:"{{count}} selecionado(s)",bulkRestore:"Restaurar selecionados",bulkPurge:"Excluir selecionados",col:{filename:"Arquivo",folder:"Pasta",size:"Tamanho",deleted:"Movido para a lixeira",autoPurge:"Exclusão auto.",owner:"Proprietário",actions:"Ações"},confirm:{purgeTitle:"Excluir permanentemente?",purgeBody:"{{filename}} será excluído do disco e não poderá ser restaurado.",emptyTitle:"Esvaziar a lixeira?",emptyBody:"Todos os {{count}} arquivos serão excluídos do disco. Esta ação não pode ser desfeita.",bulkPurgeTitle:"Excluir permanentemente os arquivos selecionados?",bulkPurgeBody:"Os {{count}} arquivos selecionados serão excluídos do disco e não poderão ser restaurados.",cta:"Excluir permanentemente"},toast:{restored:"Arquivo restaurado.",restoreFailed:"Não foi possível restaurar o arquivo.",purged:"Arquivo excluído permanentemente.",purgeFailed:"Não foi possível excluir o arquivo.",emptied:"{{count}} arquivo(s) excluído(s) da lixeira.",emptyFailed:"Não foi possível esvaziar a lixeira.",retentionSaved:"Exclusão automática definida para {{days}} dias.",retentionFailed:"Não foi possível salvar a configuração de retenção.",bulkRestored:"{{count}} arquivo(s) restaurado(s).",bulkPurged:"{{count}} arquivo(s) excluído(s)."}},libraryPurge:{title:"Limpar arquivos antigos",headerButton:"Limpar antigos",headerTooltip:"Mover arquivos antigos em massa para a lixeira",description:"Arquivos mais antigos que o limite serão movidos para a lixeira. Pastas externas são ignoradas. Você pode restaurar da lixeira antes da exclusão automática.",ageLabel:"Mover arquivos mais antigos que",days:"dias",includeNeverPrinted:"Incluir arquivos que nunca foram impressos",effectsTitle:"O que acontece quando você clica em Limpar",effect1:"Os arquivos correspondentes são movidos para a Lixeira — ainda não são excluídos do disco.",effect2:"Você pode restaurá-los da Lixeira a qualquer momento até o fim do período de retenção.",effect3:"Após o período de retenção, o coletor da lixeira os remove permanentemente.",effect4:"Arquivos em pastas externas (vinculadas) são ignorados — Bambuddy nunca exclui bytes que não possui.",previewLoading:"Verificando quantos arquivos correspondem…",previewFailed:"Não foi possível pré-visualizar a limpeza.",previewSummary:"{{count}} arquivos · {{size}} seriam movidos para a lixeira",andMore:"…e mais {{count}}",warning:"Os arquivos são excluídos de forma suave — você pode restaurá-los da lixeira até o fim do período de retenção.",confirmCta:"Mover {{count}} para a lixeira",purging:"Movendo para a lixeira…",toast:{success:"{{count}} arquivo(s) movido(s) para a lixeira.",failed:"Não foi possível limpar os arquivos."}},libraryAutoPurge:{enableLabel:"Limpar arquivos antigos automaticamente",enableDescription:"Executa a limpeza administrativa uma vez por dia. Os arquivos vão primeiro para a lixeira — não são excluídos imediatamente.",ageLabel:"Limpar automaticamente arquivos mais antigos que",ageDescription:"Mínimo 7 dias, máximo 10 anos. Usa a mesma regra de idade do botão Limpar manual.",days:"dias",includeNeverPrinted:"Incluir arquivos que nunca foram impressos",saveFailed:"Não foi possível salvar as configurações de limpeza automática."},archivePurge:{headerButton:"Limpar antigos",headerTooltip:"Excluir arquivos antigos em massa",title:"Limpar arquivos antigos",description:"Limpa o histórico de impressão antigo. Cada arquivo envelhece pela última conclusão de impressão — reimprimir reinicia a idade, então trabalho ativo nunca é removido.",ageLabel:"Excluir arquivos não impressos nos últimos",days:"dias",effectsTitle:"O que acontece quando você clica em Limpar",effect1:"Cada arquivo correspondente é ocultado das listagens e seus arquivos são removidos do disco (3MF, miniatura, timelapse, 3MF de origem, F3D, fotos).",effect2:"A linha do arquivo permanece no banco de dados para que o Quick Stats mantenha a contribuição de filamento, tempo, custo e energia — mesmo comportamento padrão da exclusão individual.",effect3:'Marque "Remover também das estatísticas" abaixo para descartar também a contribuição do Quick Stats (equivalente à opção da exclusão individual). Esse caminho é irreversível.',effect4:"Reimprimir um arquivo reinicia seu cronômetro de idade, então arquivos ativos estão protegidos.",purgeStatsLabel:"Remover também das estatísticas",purgeStatsHint:"Remove os arquivos correspondentes do Quick Stats (filamento, tempo, custo, energia). Sem essa opção, o Quick Stats mantém cada contribuição e apenas os arquivos saem do disco.",previewLoading:"Verificando quantos arquivos correspondem…",previewFailed:"Não foi possível visualizar a limpeza.",previewSummary:"{{count}} arquivos · {{size}} seriam removidos",andMore:"…e mais {{count}}",warning:"Os arquivos são removidos do disco e não podem ser restaurados. Baixe ou favorite o que quiser manter antes de continuar.",confirmCta:"Remover {{count}} arquivo(s)",purging:"Removendo…",toast:{success:"{{count}} arquivo(s) removido(s).",failed:"Não foi possível limpar os arquivos."}},archiveAutoPurge:{enableLabel:"Limpar arquivos antigos auto.",enableDescription:"Uma vez por dia oculta das listagens os arquivos não impressos dentro do limite e remove seus arquivos do disco. Reimprimir reinicia o cronômetro.",ageLabel:"Exclusão auto. de arquivos não impressos nos últimos",ageDescription:"Mínimo 7 dias, máximo 10 anos. Baseado na última conclusão de impressão — reimprimir reinicia a idade. Remove 3MF, miniatura, timelapse, 3MF de origem, F3D e fotos.",days:"dias",purgeStatsLabel:"Remover também das estatísticas",purgeStatsDescription:"Quando ativada, a varredura diária também descarta a contribuição de cada arquivo limpo do Quick Stats (filamento, tempo, custo, energia). Desativada por padrão — o Quick Stats mantém a contribuição e apenas os arquivos saem do disco.",runNow:"Limpar arquivos agora",saveFailed:"Não foi possível salvar as configurações de limpeza automática."},cameraTokens:{title:"Tokens da API de câmera",navTitle:"Tokens da API de câmera",description:"Tokens de longa duração para incorporar o stream da câmera no Home Assistant, Frigate, quiosques ou qualquer outra ferramenta que precise de URL estável. Cada token é apenas para stream de câmera e pode ser revogado a qualquer momento.",loading:"Carregando…",confirmRevoke:{title:"Revogar este token?",body:'Qualquer dispositivo usando "{{name}}" perderá acesso imediatamente. Isso não pode ser desfeito.',cancel:"Cancelar",confirm:"Revogar"},create:{title:"Criar novo token",nameLabel:"Nome do token",namePlaceholder:"ex. Home Assistant",daysLabel:"Dias até expirar",submit:"Criar",hint:"Tempo de vida máximo 365 dias. O valor do token é exibido apenas na criação — copie agora."},created:{title:"Token criado – copie agora",warning:"Esta é a única vez que este token será visível. Após fechar este diálogo, você nunca poderá vê-lo novamente.",copy:"Copiar",dismiss:"Eu salvei"},list:{myTitle:"Meus tokens",allTitle:"Todos os usuários (visão admin)",empty:"Nenhum token ainda.",name:"Nome",owner:"Proprietário",prefix:"Prefixo",created:"Criado",expires:"Expira",lastUsed:"Último uso",revoke:"Revogar",expired:"Expirado"},toast:{created:"Token criado",createFailed:"Falha ao criar token",revoked:"Token revogado",revokeFailed:"Falha ao revogar token",loadFailed:"Falha ao carregar tokens",copied:"Copiado para a área de transferência",copyFailed:"Falha ao copiar – selecione e copie manualmente"}},forecast:{title:"Previsão de Estoque",noSpools:"Nenhum carretel ativo encontrado. Adicione carretéis ao seu inventário para ver os dados de previsão.",noUsageData:"Nenhum dado de uso disponível — não é possível projetar a linha do tempo do estoque.",sku:"SKU",material:"Material",stock:"Estoque",dailyRate:"Taxa",daysLeft:"Dias Restantes",emptyBy:"Esgota em",reorderBy:"Reabastecer até",actions:"Ações",trend:"Tendência",estimated:"Est.",noData:"Sem dados",timeframe:"Período",chartTitle:"Estoque projetado — Top 5 materiais",dashedLinesROP:"Linhas tracejadas = pontos de reposição",stockLevel:"Nível de Estoque",reorderPoint:"Ponto de Reposição",safetyMargin:"Margem de Segurança",trendLegend:"Tendência (baseada em histórico, nível de serviço 95%)",estimatedLegend:"Estimado (delta de peso)",noDataLegend:"Sem dados",ropLabel:"PR",ssLabel:"SE",safetyStockLegend:"Estoque de segurança",stockArrivalLegend:"Chegada do estoque",stockoutLegend:"Ruptura de estoque",alertCount_one:"{{count}} alerta",alertCount_other:"{{count}} alertas",order:"Pedir",globalLeadTime:"Lead time global",globalLeadTimeHint:"Lead time global mínimo — usado no cálculo do ponto de reposição para todos os SKUs",save:"Salvar",cancel:"Cancelar",settingsSaved:"Configurações salvas",failedSaveSettings:"Falha ao salvar configurações",globalLeadTimeSaved:"Prazo global salvo",skuLeadTimeOverride:"Override de Lead Time do SKU",skuLeadTimeHint:"0 = usar lead time global. Defina >0 para substituir para este SKU.",safetyMarginLabel:"Margem de Segurança",effectiveLeadTime:"Lead Time Efetivo",effectiveLeadTimeHint:"máx(global {{global}}d, SKU {{sku}}d)",reorderPointHint:"d̄ × LT + safety margin — peça quando o estoque atingir este nível",safetyMarginHint:"Estoque de segurança estatístico (z=1,65 × σ × √LT) + buffer definido pelo usuário",safetyMarginHintDays:"Buffer adicionado ao estoque de segurança estatístico.{{approx}}",safetyMarginHintDaysApprox:" ≈ {{g}}g na taxa atual.",safetyMarginHintG:"Buffer de peso fixo adicionado ao estoque de segurança estatístico.{{approx}}",safetyMarginHintGApprox:" ≈ {{days}}d na taxa atual.",individualSpools:"Carretéis individuais",labelWeight:"Etiqueta",spoolCount_one:"{{count}} carretel",spoolCount_other:"{{count}} carretéis",stockBreakRisk:"Risco de ruptura de estoque",stockBreakBefore:"Ruptura de estoque antes do reabastecimento",stockBreakDetail:"{{days}}d restantes, lead time {{lt}}d.",reorderNow:"Reabastecer agora",reorderTriggerPassed:"A data de acionamento {{date}} já passou.",shoppingList:"Lista de Compras",shoppingListItems_one:"({{count}} item)",shoppingListItems_other:"({{count}} itens)",shoppingListEmpty:"A lista de compras está vazia. Clique no ícone do carrinho em qualquer linha para adicionar itens.",addToCart:"Adicionar à lista de compras",alertsSnoozed:"Silenciar alertas para este SKU",alertsEnabled:"Ativar alertas para este SKU",addedToCart:"Adicionado à lista de compras",failedAddItem:"Falha ao adicionar item",listView:"Lista",logisticsView:"Logística",qty:"Qtd",weight:"Peso",leadTime:"Prazo de entrega",expectedRestock:"Reabastecimento Previsto",status:"Status",note:"Nota",pending:"Pendente",purchased:"Comprado",received:"Recebido",markPurchased:"Marcar como comprado",markReceived:"Marcar como recebido — adiciona carretéis ao estoque",resetToPending:"Redefinir para pendente",remove:"Remover",clearAll:"Limpar tudo",downloadCsv:"CSV",addToCartTitle:"Adicionar à lista de compras",byQuantity:"Por quantidade",byDuration:"Por duração",numberOfSpools:"Número de carretéis",lastHowManyDays:"Por quantos dias deve durar?",noUsageQty:"Sem dados de uso — quantidade definida como 1.",noteOptional:"Observação (opcional)",notePlaceholder:"ex. para o projeto X, urgente…",addNSpools_one:"Adicionar {{count}} carretel",addNSpools_other:"Adicionar {{count}} carretéis",onArrival:"Na Chegada",stockBreakIn:"Ruptura de estoque em {{days}}d.",stockRunsOutBefore:"O estoque se esgota antes do lead time de {{lt}}d decorrer.",atRate:"A {{rate}}g/dia você precisa de",moreSpools_one:"{{count}} carretel a mais",moreSpools_other:"{{count}} carretéis a mais",bridgeGap:"para cobrir a lacuna.",noReadAccess:"Você não tem permissão para visualizar previsões de inventário.",noWriteAccess:"Você não tem permissão para modificar as configurações de previsão."}},ipe={nav:{printers:"打印机",archives:"归档",queue:"打印队列",stats:"统计",profiles:"配置文件",maintenance:"维护",projects:"项目",inventory:"耗材",files:"文件管理器",makerworld:"MakerWorld",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:"错误",errorLoading:"加载错误",retry:"重试",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:"所有位置"},toolbar:{filters:"筛选",view:"视图",actions:"操作"},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:"添加打印机失败",connectionFailedNotAdded:"无法连接到打印机。请检查 IP 地址、序列号和访问码,并确认已启用仅局域网(LAN-only)模式。该打印机未被添加。",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 重新读取",loadInitiated:"加载耗材中…",unloadInitiated:"卸载耗材中…",failedToLoad:"加载耗材失败",failedToUnload:"卸载耗材失败"},connection:{connected:"已连接",offline:"离线"},plateStatus:{markCleared:"将打印板标记为已清理",cleared:"打印板已清理",notCleared:"打印板未清理",inUse:"打印板使用中"},queue:{inQueue:"队列中有 {{count}} 个打印任务",inQueue_plural:"队列中有 {{count}} 个打印任务"},controls:"控制",rfid:{reread:"重新读取 RFID"},ams:{load:"加载",unload:"卸载"},bedJog:{title:"移动热床",bed:"热床",step:"步长 (mm)",up:"热床上移",down:"热床下移",disabledWhilePrinting:"打印中已禁用",notHomedTitle:"打印机未归零",notHomedMessage:"打印机自上次打印以来尚未归零。请先执行自动归零以确保安全定位(先停放喷头,然后归零 X、Y 和 Z),或者直接移动 — 软限位将被绕过。",homeZ:"自动归零",moveAnyway:"强制移动",homingStarted:"打印机自动归零中…"},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:"关机",haToggleTitle:'切换"{{name}}"',haToggleMessage:"切换 Home Assistant 实体 {{entity}}?如果当前为开启状态,可能会关闭电源。",haToggleWarning:'警告:"{{name}}"正在打印中!切换 {{entity}} 可能会切断电源并中断打印。是否继续?',haToggleButton:"切换"},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:"固件已上传!请在打印机屏幕上触发更新。",availableVersions:"可用版本",usable:"可用",unavailable:"不可用",installed:"已安装",newerBadge:"较新",olderBadge:"较旧",currentBadge:"当前"},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:"编辑",printLog:"打印记录",goToProject:"前往项目:{{name}}",addToProject:"添加到项目",removeFromProject:"从项目中移除",loading:"加载中...",noProjectsAvailable:"无可用项目",searchProjects:"搜索项目…",select:"选择",deselect:"取消选择",delete:"删除"},permission:{noReprint:"您没有重新打印此归档的权限",noAddToQueue:"您没有添加到队列的权限",noUpdateArchives:"您没有更新归档的权限",noUploadFiles:"您没有上传文件的权限",noDownload:"您没有下载归档的权限",noCopyLink:"您没有复制下载链接的权限",noDelete:"您没有删除此归档的权限",noCreate:"您没有创建归档的权限"},platePicker:{title:"选择要预览的打印板",hint:"此存档包含多个打印板。选择一个在 GCode 查看器中打开。",plateLabel:"打印板 {{index}}",objectCount:"{{count}} 个对象",objectCount_plural:"{{count}} 个对象",noGcode:"此存档没有可预览的已切片 G 代码。请先在 Bambu Studio 中打开并切片。"},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}}",runsBadge:"{{count}} 次打印",runsBadgeTitle:"共 {{count}} 次打印 — 成功 {{successful}} 次,失败 {{failed}} 次。点击查看完整打印记录。",estimated:"预计:{{time}}",actual:"实际:{{time}}",accuracy:"准确度:{{percent}}%",filament:"{{weight}} 克",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:"删除"},runLog:{title:"打印记录",modalTitle:"打印记录 — {{name}}",modalTitleFallback:"此归档",empty:"此归档尚未记录任何打印事件。",col:{date:"日期",status:"状态",duration:"时长",filament:"耗材",cost:"成本"},status:{completed:"已完成",failed:"失败",cancelled:"已取消",stopped:"已停止",skipped:"已跳过",printing:"打印中"}},modal:{deleteArchive:"删除归档",deleteConfirm:'确定要删除"{{name}}"吗?此操作无法撤销。',deleteButton:"删除",deletePurgeStats:"同时从快速统计中删除此打印(耗材、时间、成本、能耗)",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:"队列中的下一个",clearPlateSuccess:"打印板已清理 — 准备进行下一个打印",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:"取消中…",awaitingPrinter:"等待打印机…",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:"虚拟打印机",spoolbuddy:"SpoolBuddy",failureDetection:"故障检测",users:"身份验证",backup:"备份",emailAuth:"邮箱认证",ldap:"LDAP",twoFa:"双因素认证",oidc:"SSO / OIDC",security:"安全"},spoolbuddy:{infoTitle:"SpoolBuddy 设备",infoBody:"SpoolBuddy kiosk 通过心跳自动注册。如果设备不再使用,或守护进程崩溃遗留了陈旧的重复项,可在此注销。",duplicatesTitle:"已注册 {{count}} 台设备",duplicatesBody:"kiosk 界面只使用最先注册的设备。如果其中有因崩溃遗留的陈旧重复项,请注销它——在线设备会在下次心跳时重新注册自己。",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:"磁盘",update:"更新",updateConfirmTitle:"更新 SpoolBuddy 守护进程?",updateConfirmBody:'对 "{{hostname}}" 触发软件更新?更新完成后守护进程将重启。',restartBrowser:"重启浏览器",restartBrowserConfirmTitle:"重启 kiosk 浏览器?",restartBrowserConfirmBody:'在 "{{hostname}}" 上重启 kiosk 浏览器?显示将短暂黑屏。',restartDaemon:"重启守护进程",restartDaemonConfirmTitle:"重启 SpoolBuddy 守护进程?",restartDaemonConfirmBody:'在 "{{hostname}}" 上重启 SpoolBuddy 守护进程?设备将离线几秒钟。',reboot:"重启",rebootConfirmTitle:"重启设备?",rebootConfirmBody:'重启 "{{hostname}}"?设备将离线约一分钟。',shutdown:"关机",shutdownConfirmTitle:"关闭设备?",shutdownConfirmBody:'关闭 "{{hostname}}"?您需要物理访问才能重新开机。',commandConfirm:"确认",commandQueued:"命令已加入队列",commandError:"发送命令失败"},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})。",advanced:"高级",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 同步重量失败",spoolmanAmsSyncButton:"从 AMS 同步 Spoolman 重量",spoolmanAmsSyncTitle:"从 AMS 同步 Spoolman 耗材重量",spoolmanAmsSyncMessage:"这将根据已连接打印机的当前 AMS 剩余百分比值更新所有 Spoolman 耗材重量。打印机必须在线。",spoolmanAmsSyncing:"同步中...",spoolmanAmsSyncSuccess:"已同步 {{synced}} 个 Spoolman 耗材,跳过 {{skipped}} 个",spoolmanAmsSyncError:"从 AMS 同步 Spoolman 重量失败",spoolmanAmsSyncErrorUnreachable:"同步失败(Spoolman 不可访问)",spoolmanAmsSyncErrorNotConfigured:"同步失败(Spoolman 未配置)",spoolmanNotConfigured:"Spoolman 未配置",spoolmanFilamentCatalogTitle:"Spoolman 耗材目录",spoolmanFilamentCatalogDesc:"来自 Spoolman 的耗材名称和皮重。名称和线轴重量可在此处编辑;其他属性请直接在 Spoolman 中管理。",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:"暂停、继续和停止打印",cloudAccess:"允许云端访问",cloudAccessDescription:"代表您读取 Bambu Cloud 预设和耗材。需要登录 Bambu Cloud。",cloudBadge:"云端",updateEnergyCost:"更新电价",updateEnergyCostDescription:"允许此密钥向 /settings/electricity-price POST 新的每千瓦时电价。适用于 Home Assistant 动态电价自动化(Tibber、Octopus 等)。这是唯一可通过 API 密钥写入的设置字段。",energyCostBadge:"能耗",legacyKey:"传统",legacyKeyTooltip:"在按用户所有权之前创建;需重建以使用云端访问",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:"错峰启动",staggeredStartDescription:"错峰启动多台打印机批次时的默认组大小和间隔。可在打印对话框中按批次覆盖。",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:"组大小",staggerGroupSizeHelp:"每组同时启动的打印机数量",staggerInterval:"间隔(分钟)",staggerIntervalHelp:"每组启动之间的延迟",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:"输入密码",passwordRequirements:"至少 8 个字符,包含一个大写、一个小写、一个数字和一个特殊字符。",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:"选择要用于打开文件的切片软件",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev 存在已知 CLI 错误,无法切片许多 Bambu 创建的 3MF — 见上游 issue #12426(绘制的多挤出机文件 segfault)和 #13386(参数范围严格验证拒绝)。在上游修复发布之前,推荐使用 Bambu Studio。",useSlicerApi:"使用切片器 API",useSlicerApiDescription:"开启时,「切片」操作打开应用内切片器模态并调用 slicer-API sidecar。关闭时(默认),通过 URI 方案交给桌面切片器。",slicerCard:"切片器",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"slicer-API sidecar 容器的 URL。留空以使用 SLICER_API_URL / BAMBU_STUDIO_API_URL 环境变量默认值。",slicerBundles:{title:"切片器捆绑包",description:'导入从 BambuStudio 导出的 Printer Preset Bundle (.bbscfg)(文件 → 导出 → 导出预设捆绑包 → "Printer preset bundle")。导入后,切片请求可以按名称从捆绑包中选择预设,无需重新上传 JSON 配置三元组。',uploadButton:"上传捆绑包",uploading:"上传中…",loading:"加载捆绑包中…",empty:"尚未导入捆绑包。",summary:"{{processCount}} 个工艺 · {{filamentCount}} 个耗材预设",delete:"删除",uploadSuccess:"已导入 {{name}}",uploadError:"上传捆绑包失败:{{message}}",deleteSuccess:"捆绑包已移除",deleteError:"删除捆绑包失败:{{message}}",confirmDeleteTitle:"移除此捆绑包?",confirmDeleteMessage:"引用「{{name}}」的切片请求将失败,直到捆绑包重新导入。"},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:"密码至少需要 8 个字符",passwordNeedsUppercase:"密码必须至少包含一个大写字母",passwordNeedsLowercase:"密码必须至少包含一个小写字母",passwordNeedsDigit:"密码必须至少包含一个数字",passwordNeedsSpecial:"密码必须至少包含一个特殊字符",enterGroupName:"请输入组名称",settingsSaved:"设置已保存",noPermissionUpdate:"您没有权限更改设置",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:"删除条目失败",material:"材料",spoolWeight:"线轴重量",color:"颜色",updateSpoolWeight:"更新线轴重量",filamentUpdated:"耗材已更新",filamentUpdateFailed:"更新耗材失败",filamentUpdateInvalid:"耗材数据无效",keepExistingSpoolWeight:"保留现有线轴的旧重量",keepExistingSpoolWeightDesc:"已使用此耗材类型创建的线轴保留旧的皮重。新线轴使用更新后的值。",applyToAllSpools:"应用到所有线轴",applyToAllSpoolsDesc:"此耗材类型的所有重量计算立即使用新的皮重。"},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)",cameraSnapshotUrl:"快照 URL(可选)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"用于通知缩略图、完成照片、层延时摄影帧和打印板检测的单帧 URL。延时摄影和打印板检测各自需要自己的每打印机开关 — 此 URL 只是它们激活时拉取的图像源。留空以从上方实时流捕获。适用于 go2rtc(/api/frame.jpeg)和具有专用快照端点的 IP 摄像头。",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 更新:",updateViaHomeAssistant:"更新由 Home Assistant Supervisor 管理。请在 Home Assistant 中打开 设置 → 加载项 → Bambuddy 以安装新版本。",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:"提供商已删除。",refreshIcon:"刷新图标",removeIcon:"移除图标",iconRefreshed:"图标已刷新。",iconRemoved:"图标已移除。",iconFetchFailed:"无法从提供商 URL 获取图标。",deleteTitle:"删除提供商",deleteMessage:'删除"{{name}}"?所有关联账户将断开连接。',form:{name:"显示名称",issuerUrl:"颁发者 URL",clientId:"客户端 ID",clientSecret:"客户端密钥",scopes:"作用域",iconUrl:"图标 URL(可选)",enabled:"已启用",autoCreate:"自动创建用户",autoCreateDesc:"首次登录时自动创建本地账户。",autoLink:"自动关联已有账户",autoLinkDesc:"首次登录时通过邮箱匹配现有本地账户并自动关联。",secretHint:"留空以保留当前",secretPlaceholder:"新密钥",emailClaim:"邮箱声明",emailClaimDesc:"用作邮箱身份的 JWT 声明。Azure Entra ID 请使用 'preferred_username' 或 'upn'(不发送 email_verified)。仅使用可信的声明名称。",emailClaimPlaceholder:"邮箱",emailClaimCustomClaimAutoLinkWarning:"自定义声明仅在值由租户管理时(例如 Azure Entra ID 的 upn / preferred_username)对自动关联安全。如果您的 IdP 允许用户自我声明此声明,请勿启用自动关联。",requireEmailVerified:"要求邮箱已验证",requireEmailVerifiedDesc:"仅在提供商将邮箱声明标记为已验证时才接受。",requireEmailVerifiedWarning:"警告:将在未经验证的情况下接受邮箱。仅对受信任的提供商使用。",requireEmailVerifiedAutoLink:"请先禁用自动关联以更改此设置。",defaultGroup:"默认组",defaultGroupDesc:"自动创建用户时分配的组。未设置时回退到 Viewers。",defaultGroupViewersFallback:"Viewers(默认)"}},encryption:{title:"MFA 加密状态",enabledFromEnv:"已启用静态加密(密钥来自 MFA_ENCRYPTION_KEY 环境变量)",enabledFromFile:"已启用静态加密(密钥从数据目录加载)",enabledGenerated:"使用自动生成的密钥启用静态加密",notConfigured:"未配置静态加密",notConfiguredDesc:"TOTP 密钥和 OIDC client_secrets 以明文存储。请设置 MFA_ENCRYPTION_KEY 或使用可写数据目录重启 Bambuddy 以自动生成。",allEncrypted:"所有 MFA 密钥均已静态加密。",legacyRowsLabel:"旧版明文行",encryptedRowsLabel:"已加密行",legacyRowsWarning:"检测到 {{count}} 个旧版明文行。请重新保存 OIDC 提供商或重新注册用户的身份验证器应用,以迁移到加密存储。",backupHint:"自动生成的密钥存储在 DATA_DIR/.mfa_encryption_key 中,并包含在本地备份 ZIP 中。请保护备份安全或显式设置 MFA_ENCRYPTION_KEY。",decryptionBrokenTitle:"加密密钥缺失",decryptionBrokenError:"无法解密 {{count}} 条加密记录,因为加密密钥不再可用。请恢复以前的 MFA_ENCRYPTION_KEY 或 DATA_DIR/.mfa_encryption_key 以恢复访问。",migrationErrorWarning:"{{count}} 行旧数据在启动时未能重新加密。请检查服务器日志并重启 Bambuddy 以重试。"}},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:"登录中...",rememberMe:"记住我",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:"知道了",resetPassword:{title:"设置新密码",subtitle:"请在下方输入并确认您的新密码。",newPassword:"新密码",newPasswordPlaceholder:"至少 8 个字符",confirmPassword:"确认密码",confirmPasswordPlaceholder:"重复输入新密码",saving:"保存中…",submit:"设置新密码",backToLogin:"返回登录",passwordsDoNotMatch:"密码不匹配",passwordTooShort:"密码至少需要 8 个字符",resetFailed:"密码重置失败。链接可能已过期。"},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:"切换腔室灯",unavailable:"摄像头不可用",diagnose:{button:"诊断",modalTitle:"摄像头诊断",running:"正在运行诊断...",runFailed:"无法运行诊断: {{error}}",retry:"重新运行",stage:{tcp_reachable:"网络可达性",first_frame:"画面捕获",live_stream_active:"直播流正在进行"},summary:{all_ok:"摄像头工作正常。诊断已成功完成所有阶段。",live_stream_active_healthy:"摄像头正在传输最新画面 — 无需测试。",printer_unreachable:"无法访问打印机。请检查 IP 地址、网络连接以及打印机是否已开机。",camera_port_closed:"打印机可访问,但摄像头端口已关闭。请确保打印机设置中已启用仅 LAN 模式和开发者模式。",no_frame:"已连接到摄像头,但未收到画面。请重试或检查打印机设置中摄像头是否已启用。",unknown_failure:"摄像头诊断因未知原因失败。请查看支持日志了解详情。"},meta:{protocol:"协议",port:"端口",profile:"配置"}}},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 个字符",ldapProvisioned:"已创建 LDAP 用户「{{username}}」"},modal:{createUser:"创建用户",editUser:"编辑用户",cancel:"取消",creating:"创建中...",saving:"保存中...",saveChanges:"保存更改",advancedAuthSubtitle:"使用高级认证",tabsAriaLabel:"用户来源",localTab:"本地",ldapTab:"LDAP",ldapSearchLabel:"搜索目录",ldapSearchPlaceholder:"输入用户名、姓名或电子邮件...",ldapMinChars:"输入至少 2 个字符以搜索",ldapTypeToSearch:"开始输入以搜索 LDAP 目录",ldapSearching:"搜索目录中...",ldapNoResults:"目录中没有匹配的用户",ldapSearchError:"目录搜索失败。请检查 LDAP 服务器状态。",ldapAlreadyProvisioned:"已创建",ldapSelectedLabel:"已选",ldapProvision:"创建用户",ldapProvisioning:"创建中...",ldapErrorProvision:"创建失败。请检查 LDAP 服务器状态后重试。"},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:"粘贴您的拓竹云访问令牌。中国大陆账号(绑定手机号、无邮箱登录)只能使用此方式登录。可从 MakerWorld 浏览器 Cookie 中获取令牌,详见 Wiki。",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:"上传失败",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:"禁用文本换行",collapse:"折叠",collapseFoldersByDefault:"默认折叠文件夹",expandFoldersByDefault:"默认展开文件夹",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:"您没有打印的权限",noPermissionSlice:"您没有切片文件的权限",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:"可选描述...",urlLabel:"网址",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"网址必须以 http:// 或 https:// 开头",openExternalUrl:"打开项目网址",coverImageLabel:"封面图片",coverImageAlt:"项目封面图片",coverImageUpload:"上传",coverImageReplace:"替换",coverImageRemove:"移除",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:"导出到文件"},slice:{title:"切片模型",action:"切片",slicing:"切片中…",printer:"打印机配置",process:"工艺配置",filament:"耗材配置",filamentSlot:"耗材 {{index}}({{type}})",selectPreset:"— 选择预设 —",loadingPresets:"加载预设中…",analyzingPlateFilaments:"分析打印板耗材中…",analyzingPlateFilamentsHint:"正在运行预览切片以发现此打印板使用的 AMS 插槽。之后会缓存 — 重新打开是即时的。",previewToast:"分析 {{name}} — {{elapsed}}",previewWithProgress:"分析 {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",notUsedByPlate:"— 此打印板未使用",noPresetsForSlot:"无可用预设",presetsLoadFailed:"加载预设失败。请先打开设置 → 配置文件以导入。",allPresetsRequired:"必须选择所有预设",bundle:"切片器套装",bundleNone:"— 无(单独选择预设)—",bundleAllRequired:"必须选择套装的工艺和每个耗材槽",enqueuing:"提交切片任务中…",queued:"已排队…",failed:"切片失败。请检查切片器 sidecar 日志。",startedToast:"在后台切片 {{name}}…",queuedToast:"已排队:{{name}} — {{elapsed}}",runningToast:"切片 {{name}} — {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",completedToast:"已切片 {{name}}",failedToast:"切片 {{name}} 失败:{{detail}}",tier:{local:"已导入",cloud:"云端",standard:"标准"},cloud:{notAuthenticated:"登录 Bambu Cloud(设置 → 配置文件 → 云端)以查看云端预设。",expired:"Bambu Cloud 会话已过期 — 请重新登录以刷新云端预设。",unreachable:"目前无法访问 Bambu Cloud。本地和标准预设仍可使用。"},bedType:{label:"打印板",auto:"自动(使用工艺预设)",coolPlate:"冷板",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},spoolman:{title:"Spoolman 集成",enabled:"Spoolman 已启用",url:"Spoolman URL",connected:"已连接",disconnected:"未连接",testConnection:"测试连接",sync:"同步",syncing:"同步中...",lastSync:"上次同步",linkToSpoolman:"链接到 Spoolman",openInSpoolman:"在 Spoolman 中打开",unlinkSpool:"取消链接耗材",unlinkConfirmTitle:"取消分配料盘?",unlinkConfirmMessage:"这将从此插槽中移除料盘。料盘本身的数据将保持不变。",selectSpool:"选择耗材",noUnlinkedSpools:"无未分配的料盘",linkSuccess:"料盘分配成功",linkFailed:"料盘分配失败",unlinkSuccess:"料盘取消分配成功",unlinkFailed:"料盘取消分配失败",linkedSpool:"已分配料盘",spoolId:"耗材 ID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"剩余",disableWeightSync:"禁用 AMS 估计重量同步",disableWeightSyncDesc:"不从 AMS 估计值更新剩余容量。如果您更喜欢 Spoolman 的用量追踪而非 AMS 百分比估计,请使用此选项。新耗材仍将使用 AMS 估计值作为初始重量。",reportPartialUsage:"报告失败打印的部分用量",reportPartialUsageDesc:"当打印失败或被取消时,根据层进度报告估计的耗材使用量。"},inventory:{title:"耗材库存",subtitle:"管理您的料盘",spoolmanMixedContentTitle:"Spoolman 无法通过 HTTPS 加载 — 浏览器已阻止混合内容",spoolmanMixedContentBody:"Bambuddy 通过您的反向代理以 HTTPS 提供服务,但您的 Spoolman 地址仍为 HTTP。出于安全考虑,浏览器会阻止混合内容,因此嵌入式 Spoolman 界面无法加载。Spoolman 也必须通过 HTTPS 访问。",spoolmanMixedContentFixReverseProxy:"请将 Spoolman 置于与 Bambuddy 相同的反向代理(Traefik / Nginx / Caddy)之后并启用 HTTPS,然后在设置中将 Spoolman URL 更新为新的 HTTPS 地址。",spoolmanMixedContentFixOpenNewTab:"作为变通方案,可在新标签页中通过 HTTP 打开 Spoolman — 混合内容规则仅适用于嵌入式框架,独立标签页仍可正常使用。",spoolmanOpenInNewTab:"在新标签页中打开 Spoolman",labels:{title:"打印线材标签",selectedCount:"已选 {{count}} 项",pickSpools:"选择要打印标签的线材:",searchPlaceholder:"按名称、品牌或 #ID 搜索",filterByMaterial:"材料:",allMaterials:"全部",selectVisible:"选择所有可见 ({{count}})",deselectVisible:"取消选择可见",clearAll:"全部清除",noSpoolsToShow:"没有要显示的线材。请调整筛选条件后重试。",noMatches:"没有线材符合当前搜索或筛选。",printOne:"打印此线材的标签",printLabels:"打印标签…",bulkTitle:"从当前显示的 {{count}} 个线材中选择要打印标签的",noSpoolsTitle:"没有要打标签的线材",error:"无法生成标签:{{msg}}",sortBy:{label:"排序:",id:"按 ID",color:"按颜色"},templates:{amsHolderSmall:{label:"AMS 支架 — 小 (74 × 33 mm)",hint:"每页一个标签;适配 MakerWorld 模型 752566 (AMS 耗材标签支架) 中可打印的标签。"},amsHolderLarge:{label:"AMS 支架 — 大 (75 × 55 mm)",hint:"每页一个标签;适配 AMS 耗材标签支架的卡片插入款。空间充足,可放置色板、品牌、材料、ID 与二维码。"},box40x30:{label:"盒标签 (40 × 30 mm)",hint:"每页一张;常见的 DK/Brother 卷尺寸,适合给耗材袋和储物盒贴标签。"},box:{label:"Box label (62 × 29 mm)",hint:"每页一个标签;适配 Brother PT/QL 和 Dymo 小标签。"},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"欧洲规格纸张;每张 A4 页 21 个标签。"},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"美国规格纸张;每张 Letter 页 30 个标签。"}}},addSpool:"添加耗材",editSpool:"编辑耗材",copySpool:"复制耗材",material:"材料",selectMaterial:"选择材料...",subtype:"子类型",brand:"品牌",searchBrand:"搜索品牌...",useCustomBrand:'使用"{{brand}}"',useCustomMaterial:"使用自定义材料:{{material}}",colorName:"颜色名称",colorNamePlaceholder:"翡翠白、烈焰红...",color:"颜色",hexColor:"十六进制颜色",pickColor:"选择自定义颜色",labelWeight:"标签重量",coreWeight:"空盘重量",searchSpoolWeight:"搜索耗材重量...",weightUsed:"已使用",currentWeight:"剩余重量",measuredWeight:"称量重量",spoolName:"线轴",costPerKg:"每公斤成本",storageLocation:"存放位置",storageLocationPlaceholder:"例如:货架A,抽屉1",openInInventory:"在库存中查看",measuredWeightError:"称量重量必须在 {{min}}g 到 {{max}}g 之间。",slicerFilament:"切片耗材",slicerFilamentName:"切片预设名称",slicerPreset:"切片预设",searchPresets:"搜索耗材预设...",selectedPreset:"已选择",noPresetsFound:"未找到预设",tempOverrides:"温度覆盖",note:"备注",notePlaceholder:"关于此耗材的任何备注...",category:"类别",categoryPlaceholder:"例如:生产、原型、客户A",categoryNone:"未分类",storageLocationNone:"未设置位置",lowStockThresholdOverride:"低库存阈值(此料盘)",lowStockThresholdOverrideHelp:"留空以使用全局阈值({{global}}%)。",clearRfid:"清除 RFID 标签",rfidCleared:"RFID 标签已清除",archive:"归档",restore:"恢复",noSpools:"暂无耗材。添加您的第一个耗材开始使用。",noAvailableSpools:"没有可用的耗材。请先向库存中添加耗材,或从其他槽位取消分配一个耗材。",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:"显示所有耗材",spoolmanSpools:"Spoolman 线轴",allMaterials:"所有材料",filterByBrand:"按品牌筛选...",showArchived:"显示已归档",quickAdd:"快速添加(库存)",quantity:"数量",stock:"库存",configured:"已配置",spoolsCreated:"已创建 {{count}} 个耗材",spoolsPartiallyCreated:"已创建 {{created}} / {{total}} 个耗材(部分失败)",spoolCreated:"耗材已创建",spoolUpdated:"耗材已更新",spoolDeleted:"耗材已删除",deepLinkSpoolNotFound:"未找到耗材",deepLinkFetchFailed:"无法加载耗材 — 请重试",spoolArchived:"耗材已归档",spoolRestored:"耗材已恢复",kProfileSaveFailed:"K值配置文件设置无法保存",syncWeightSpoolNotFound:"未找到耗材 — 可能已被删除",syncWeightSpoolmanUnreachable:"Spoolman 无法访问 — 请稍后再试",syncWeightFailed:"重量同步失败",spoolmanUnreachable:"Spoolman 无法访问 — 请稍后再试",deleteSpoolNotFound:"未找到耗材 — 可能已被删除",deleteFailed:"删除耗材失败",archiveSpoolNotFound:"未找到耗材 — 可能已被删除",archiveFailed:"归档耗材失败",restoreSpoolNotFound:"未找到耗材 — 可能已被删除",restoreFailed:"恢复耗材失败",saveFailed:"保存更改失败",tagClearFailed:"清除标签失败",deleteConfirm:"确定要删除此耗材吗?此操作无法撤销。",archiveConfirm:"确定要归档此耗材吗?",advancedSettings:"高级设置",filamentInfoTab:"耗材信息",paProfileTab:"PA 配置",filamentInfo:"耗材",additional:"附加",loadingPresets:"加载云端预设中...",cloudConnected:"云端已连接",cloudNotConnected:"云端未连接(使用默认值)",recentColors:"最近",searchColors:"搜索颜色...",searchResults:"搜索结果",allColors:"所有颜色",commonColors:"常用颜色",showLess:"显示更少",showAll:"显示全部",noColorsFound:"没有颜色匹配您的搜索",noResults:"未找到匹配项",extraColorsLabel:"附加颜色",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"粘贴 2 到 8 个十六进制色值,以逗号分隔。将渲染为渐变。",extraColorsInvalid:"已忽略无效的十六进制值:{{tokens}}",colorEffectLabel:"效果",colorEffect:{none:"无",sparkle:"闪光",wood:"木纹",marble:"大理石",glow:"夜光",matte:"哑光",silk:"丝光",galaxy:"星空",rainbow:"彩虹",metal:"金属",translucent:"半透明",gradient:"渐变",dualColor:"双色",triColor:"三色",multicolor:"多色"},selectMaterialFirst:"请先在耗材信息选项卡中选择材料。",noPrintersConfigured:"未配置打印机。添加打印机以使用 PA 配置。",matchingFilter:"匹配",anyBrand:"任何品牌",anyVariant:"任何变体",autoSelect:"自动选择",matches:"匹配",match:"匹配",noMatches:"无匹配",connected:"已连接",offline:"离线",printerOffline:"打印机离线。连接后查看校准配置。",noKProfilesMatch:"没有 K 值配置匹配所选耗材。",leftNozzle:"左喷嘴",rightNozzle:"右喷嘴",profilesSelected:"个校准配置已选择",totalInventory:"总库存",totalConsumed:"总消耗",byMaterial:"按材料",inPrinter:"在打印机中",lowStock:"库存不足",sinceTracking:"自开始追踪",resetUsage:"将用量重置为 0",resetUsageTooltip:"将此料盘的已消耗克数计数器清零",resetUsageConfirm:"将此料盘的已消耗克数计数器重置为 0?后续打印将从零开始计数。料盘本身、剩余重量计算和您的设置不会改变。",resetAllUsage:"重置所有料盘的用量",resetAllUsageTooltip:"将每个料盘的已消耗克数计数器清零",resetAllUsageConfirm:'将全部 {{count}} 个料盘(含已归档)的已消耗克数计数器重置为 0?这将清空"累计消耗"统计值,后续打印从零开始计数。料盘和剩余重量不会改变。',usageReset:"料盘用量已重置为 0",allUsageReset:"已重置 {{count}} 个料盘",resetUsageFailed:"重置料盘用量失败",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 之间",spoolmanFilamentCatalog:"Spoolman 耗材目录",pickFromSpoolmanCatalog:"从 Spoolman 目录选择…",spoolmanFilamentSelected:"已从 Spoolman 目录选择耗材",spoolmanFilamentUnlinked:"已解除耗材目录关联",noSpoolmanFilaments:"Spoolman 目录中未找到耗材",spoolmanFilamentColorSwatch:"耗材颜色",spoolWeightManagedBySpoolman:"空线轴重量在 Spoolman 中按耗材类型管理",spoolmanCatalogLoadFailed:"无法加载 Spoolman 耗材目录"},timelapse:{title:"延时摄影",create:"创建延时摄影",download:"下载",delete:"删除",preview:"预览",frameRate:"帧率",quality:"质量",processing:"处理中...",noTimelapses:"无可用延时摄影"},ams:{title:"AMS",slot:"槽位",empty:"空",emptySlot:"空槽位",slotEmpty:"空",emptySlotReset:"未分配料盘",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:"错峰启动打印机",staggerGroupSize:"组大小",staggerInterval:"间隔(分钟)",staggerPreview:"{{printers}} 台打印机 → {{groups}} 个 {{size}} 台的组,每 {{interval}} 分钟启动一次",staggerLastGroup:"最后一组:{{count}}",staggerTotal:"共 {{minutes}} 分钟",staggerToPrinters:"分批发送到 {{count}} 台打印机",gcodeInjection:"注入自动打印G-code"},backup:{includesEncryptionKey:"本地备份包含 MFA 加密密钥文件(DATA_DIR/.mfa_encryption_key),因此备份 ZIP 是自包含的。请将 ZIP 视为敏感文件 — 任何拥有该文件的人都可以解密内部存储的 OIDC 客户端密钥和 TOTP 密钥。",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 仓库以进行备份和版本历史记录。",repoIsPrivate:"仓库为私有 — 可以安全备份。",repoIsPublicWarning:"仓库为公开(PUBLIC)。Bambuddy 备份包含 MQTT 凭据、Home Assistant 令牌、Prometheus 令牌、您的 Bambu Cloud 邮箱以及通过 K-profile 暴露的打印机访问代码。在您于提供商设置中将仓库改为私有之前,保存将被阻止。",repoVisibilityUnknown:"无法确定仓库的可见性。Bambuddy 拒绝向任何未确认为私有的目标进行备份;保存将被阻止。",repositoryUrl:"仓库 URL",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"允许不安全的 HTTP",allowInsecureHttpHint:"为无 TLS 的私有网络自托管实例启用",personalAccessToken:"个人访问令牌",tokenSaved:"(已保存)",enterNewToken:"输入新令牌以更新",tokenHint:"具有内容读写权限的细粒度令牌",branch:"分支",provider:"Git 提供商",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"定时备份",scheduledBackupDescription:"按计划自动创建备份快照。输出目录可以挂载到 NAS 或外部存储。",frequency:"频率",backupTime:"时间",retention:"保留",retentionDescription:"保留备份数量",outputPath:"输出路径",outputPathPlaceholder:"默认:{{path}}",outputPathDescription:"留空以使用默认位置",runNow:"立即运行",backupFiles:"备份文件",noScheduledBackups:"暂无备份",deleteBackup:"删除",deleteBackupConfirm:"删除此备份文件?",backupRunning:"备份中...",scheduledBackupComplete:"备份成功完成",scheduledBackupFailed:"备份失败",nextBackup:"下次备份",backupSize:"大小",utc:"UTC",defaultPathLabel:"默认:",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:"添加到队列时自动开始打印。关闭后,打印任务等待手动派发。"},queueForceColorMatch:{title:"强制颜色匹配",description:"拒绝派发到没有完全相同耗材类型和颜色的打印机。默认关闭 — 不启用时,队列仅按型号匹配,可能选到颜色错误的打印机。"},tailscaleDisabled:{title:"Tailscale 集成",description:"启用以将此 VP 标记为通过 Tailscale 公开。显示主机的 Tailscale 地址,以便您知道要粘贴到切片器中的 IP。CA 导入步骤保持不变 — 此开关对证书无影响。"},setupRequired:{title:"需要设置",description:"虚拟打印机功能需要额外的系统配置才能工作。包括端口转发、防火墙规则和平台特定设置。",readGuide:"启用前请阅读设置指南"},archiveNameSource:{title:"存档名称来源",description:'选择通过虚拟打印机接收文件时新存档的命名方式。"元数据"使用 3MF 中嵌入的切片标题(默认)。"文件名"使用 Bambu Studio 通过 FTP 发送的文件名 — 当您在"发送到打印机"对话框中重命名作业时非常有用。',metadata:"元数据",filename:"文件名"},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:"更新设置失败",copyFailed:"复制失败 — 请手动选中文本",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:"在打印之间保持启用而非一次性",autoOffAfterDrying:"干燥完成后自动关闭",autoOffAfterDryingDescription:"AMS 干燥完成后关闭",delayAfterDryingMinutes:"干燥后延迟(分钟)",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")。如果主题发布原始数值,请留空。
  28. 乘数:mW→W使用0.001,kW→W使用1000。`,mqttEnergyHint:`JSON路径从JSON负载中提取值。原始值请留空。
  29. 乘数:Wh→kWh使用0.001,MWh→kWh使用1000。`,mqttStateHint:`JSON路径从JSON负载中提取值。原始值请留空。
  30. ON值:表示"ON"的确切字符串。留空以自动检测(ON、true、1)。`,restControl:"控制",restOnUrl:"开启 URL",restOffUrl:"关闭 URL",restOnBody:"开启请求体",restOffBody:"关闭请求体",restMethod:"HTTP 方法",restHeaders:"Custom Headers (JSON)",restStatusUrl:"状态 URL",restStatusPath:"状态 JSON 路径",restStatusOnValue:"开启值",restPowerUrl:"功率URL",restPowerPath:"功率 JSON 路径",restPowerMultiplier:"功率乘数",restEnergyUrl:"能耗URL",restEnergyPath:"能耗 JSON 路径",restEnergyMultiplier:"能耗乘数",restUrlRequired:"REST 插座至少需要一个 URL(ON 或 OFF)",restHeadersHint:'例如 {"Authorization": "Bearer your-token"}',restBodyHint:'例如 ON, {"state": "on"}',restStatusHint:"轮询当前状态的 URL",restPathHint:"例如 state 或 data.power.status",restPowerUrlHint:"功率数据的独立URL(留空则使用状态URL)",restEnergyUrlHint:"能耗数据的独立URL(留空则使用状态URL)",restEnergyHint:"每个值可以使用独立的URL,或回退到状态URL。使用乘数进行单位转换(例如:0.001 将 Wh 转换为 kWh)。",testConnection:"测试连接",connectionSuccess:"连接成功",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 温度超过阈值",inventoryAlerts:"库存警报",stockReorderAlert:"补货警报",stockReorderAlertDescription:"SKU 已达到补货点",stockBreakAlert:"断货警报",stockBreakAlertDescription:"库存将在补货到达前耗尽",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:"(打印完成后)",eventPriority:{sectionTitle:"ntfy 优先级",helpNtfy:"为每个已启用的事件选择优先级。ntfy 使用它来升级提醒(声音、可见性、推送行为)。此处未设置的级别将使用 ntfy 服务器默认值。",min:"最低",low:"低",default:"默认",high:"高",urgent:"紧急"},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:"Git 备份",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:"当前耗材",plateReady:"热床就绪: {{name}}",plateReadyLabel:"待清理的热床",plateClearAction:"清理",plateClearedToast:"已将热床标记为已清理",plateClearFailed:"无法将热床标记为已清理"},modal:{spoolDetected:"检测到耗材",assignToAms:"分配到 AMS",syncWeight:"同步重量",weightSynced:"已同步!",syncing:"同步中...",newTagDetected:"检测到新标签",addToInventory:"添加到库存",assignToAmsTitle:"分配到 AMS",selectSlot:"选择槽位",assign:"分配",assigning:"分配中...",assignSuccess:"已分配!",assignPendingInsert:"已分配。插入耗材后将配置槽位。",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:"运行时间",systemConfig:"后端与认证",backendUrl:"Bambuddy 后端 URL",apiToken:"API 令牌",apiTokenPlaceholder:"输入 API 令牌",saveConfig:"保存配置",systemQueued:"配置已加入队列。",nfcDiagnostic:"NFC 诊断",scaleDiagnostic:"秤诊断",readTagDiagnostic:"读取标签诊断",testNfc:"测试读卡器",testScale:"测试精度",testReadTag:"读取标签",systemFieldsRequired:"后端 URL 为必填项。",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:"创建耗材失败",incompleteDataWarning:"已使用不完整的Spoolman数据写入标签"},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:"暂无检测记录。"},makerworld:{title:"MakerWorld",description:"粘贴 MakerWorld 模型链接,即可直接在 Bambuddy 中导入并打印 —— 无需切换到 Bambu Handy 应用。",pasteUrlHeader:"从 MakerWorld 导入",pasteUrlPlaceholder:"https://makerworld.com/en/models/… 或粘贴任意 MakerWorld 链接",resolveButton:"解析",signInRequiredTitle:"下载需要登录 Bambu Cloud",signInRequiredBody:"您可以匿名浏览模型详情,但下载 3MF 文件需要 Bambu Cloud 账户。",openCloudSettings:"打开云设置",untitledModel:"无标题模型",byCreator:"作者: {{name}}",downloadsCount:"{{count}} 次下载",licensePrefix:"许可协议",alreadyImported:"已在资料库中",openOnMakerworld:"在 MakerWorld 中打开",alreadyInLibrary:"此模型已在您的资料库中 —— 可在文件管理器 → MakerWorld 中找到",importSuccess:"已导入 {{filename}} —— 已保存到文件管理器 → MakerWorld",platesHeader:"打印板 ({{count}})",plateDefaultName:"打印板 {{n}}",materialCount:"{{count}} 种耗材",amsRequired:"需要 AMS",slicedFor:"为 {{printer}} 切片",alsoCompatible:"还标记为兼容:{{printers}}",importToLibrary:"保存",sliceIn:"保存并在 {{slicer}} 中切片",disclaimer:"MakerWorld 集成使用由社区记录的 API 接口。Bambuddy 与 MakerWorld 或 Bambu Lab 没有从属或认可关系。",lastImportSuccess:"已导入到您的资料库",lastImportAlreadyInLibrary:"已存在于您的资料库中",viewInLibrary:"在文件管理器中查看",openInBambuStudio:"在 Bambu Studio 中打开",openInOrcaSlicer:"在 OrcaSlicer 中打开",importTo:"导入到文件管理器",recentImportsHeader:"最近导入",phaseResolving:"解析中",phaseDownloading:"下载中",folderAuto:"MakerWorld (默认)",importAll:"全部导入",importAllProgress:"正在导入 {{current}}/{{total}}",openGallery:"打开图片库",galleryPrev:"上一张",galleryNext:"下一张",deleteImport:"从资料库中移除",importDeleting:"正在移除…",importDeleted:"已从资料库中移除",confirmDelete:"从资料库中移除 {{filename}}?本地文件将被删除,但可以从 MakerWorld 重新导入。",errors:{resolveFailed:"无法解析该 MakerWorld 链接。",downloadFailed:"下载失败。请重试。",deleteFailed:"无法从资料库中移除文件。"}},gcodeViewer:{back:"返回",backToArchives:"返回打印归档",backToFiles:"返回文件管理器"},libraryTrash:{title:"回收站",headerButton:"回收站",headerTooltip:"查看已移至回收站的文件",backToFiles:"返回文件管理器",subtitleAdmin:"已删除的文件会在回收站保留 {{days}} 天,之后自动删除。此视图显示所有用户的回收站。",subtitleUser:"已删除的文件会在回收站保留 {{days}} 天,之后自动删除。",loading:"正在加载回收站…",loadError:"无法加载回收站。",empty:"回收站为空。",summary:"{{count}} 个文件 · {{size}}",emptyTrash:"清空回收站",restore:"还原",purgeNow:"立即删除",autoPurgeIn:"将于 {{when}} 自动删除",days:"天",retentionLabel:"自动删除时间",selectAll:"全选",selectOne:"选择 {{filename}}",selectionCount:"已选择 {{count}} 项",bulkRestore:"还原所选",bulkPurge:"删除所选",col:{filename:"文件",folder:"文件夹",size:"大小",deleted:"移入回收站",autoPurge:"自动删除",owner:"所有者",actions:"操作"},confirm:{purgeTitle:"永久删除?",purgeBody:"{{filename}} 将从磁盘中删除,无法恢复。",emptyTitle:"清空回收站?",emptyBody:"全部 {{count}} 个文件将从磁盘中删除。此操作无法撤消。",bulkPurgeTitle:"永久删除所选文件?",bulkPurgeBody:"所选的 {{count}} 个文件将从磁盘中删除,无法恢复。",cta:"永久删除"},toast:{restored:"文件已还原。",restoreFailed:"无法还原文件。",purged:"文件已永久删除。",purgeFailed:"无法删除文件。",emptied:"已从回收站删除 {{count}} 个文件。",emptyFailed:"无法清空回收站。",retentionSaved:"自动删除已设置为 {{days}} 天。",retentionFailed:"无法保存保留设置。",bulkRestored:"已还原 {{count}} 个文件。",bulkPurged:"已删除 {{count}} 个文件。"}},libraryPurge:{title:"清理旧文件",headerButton:"清理旧文件",headerTooltip:"批量将旧文件移至回收站",description:"早于所选阈值的文件将被移至回收站。外部文件夹会被跳过。在自动删除之前,您可以从回收站还原文件。",ageLabel:"移动早于以下天数的文件",days:"天",includeNeverPrinted:"包括从未打印过的文件",effectsTitle:"点击清除时会发生什么",effect1:"匹配的文件移至回收站 — 尚未从磁盘删除。",effect2:"在保留期到期之前,您可以随时从回收站恢复。",effect3:"保留期满后,回收站清理器将它们从磁盘永久删除。",effect4:"外部(链接)文件夹中的文件将被跳过 — Bambuddy 从不删除不属于自己的字节。",previewLoading:"正在检查匹配的文件数量…",previewFailed:"无法预览清理结果。",previewSummary:"{{count}} 个文件 · {{size}} 将被移至回收站",andMore:"…还有 {{count}} 个",warning:"文件将被软删除——在保留期结束前,您可以从回收站还原它们。",confirmCta:"将 {{count}} 个移至回收站",purging:"正在移至回收站…",toast:{success:"已将 {{count}} 个文件移至回收站。",failed:"无法清理文件。"}},libraryAutoPurge:{enableLabel:"自动清理旧文件",enableDescription:"每天执行一次管理员清理。文件会先进入回收站——不会立即删除。",ageLabel:"自动清理早于以下天数的文件",ageDescription:"最少 7 天,最多 10 年。使用与手动「清理旧文件」按钮相同的时间规则。",days:"天",includeNeverPrinted:"包括从未打印过的文件",saveFailed:"无法保存自动清理设置。"},archivePurge:{headerButton:"清除旧条目",headerTooltip:"批量删除旧归档",title:"清除旧归档",description:"清除旧的打印历史。每个归档按其最近一次打印完成时间老化 — 重新打印归档会刷新其年龄,因此活跃工作永远不会被清除。",ageLabel:"删除最近未打印的归档:",days:"天",effectsTitle:"点击清除时会发生什么",effect1:"每个匹配的归档将从列表中隐藏,其磁盘文件(3MF、缩略图、延时摄影、源 3MF、F3D、照片)也将被删除。",effect2:"数据库中的归档记录将被保留,因此 Quick Stats 仍可计入耗材、时间、成本和能耗的贡献 — 与单条删除的默认行为一致。",effect3:'勾选下方"同时从统计中移除"可一并清除 Quick Stats 中的贡献(与单条删除选项等同)。该操作不可撤销。',effect4:"重新打印归档会刷新其使用计时器,因此仍在使用的归档不会被清除。",purgeStatsLabel:"同时从统计中移除",purgeStatsHint:"从 Quick Stats(耗材、时间、成本、能耗)中移除匹配的归档。不勾选时,Quick Stats 保留所有贡献,仅文件从磁盘删除。",previewLoading:"检查匹配的归档数量…",previewFailed:"无法预览清除。",previewSummary:"将移除 {{count}} 个归档 · {{size}}",andMore:"…还有 {{count}} 个",warning:"文件将从磁盘删除且无法恢复。继续前请下载或收藏您想保留的内容。",confirmCta:"移除 {{count}} 个归档",purging:"移除中…",toast:{success:"已移除 {{count}} 个归档。",failed:"无法清除归档。"}},archiveAutoPurge:{enableLabel:"自动清除旧归档",enableDescription:"每天一次,将阈值内未打印的归档从列表中隐藏,并从磁盘中删除其文件。重新打印会重置计时器。",ageLabel:"自动删除最近未打印的归档:",ageDescription:"最少 7 天,最多 10 年。基于最近一次打印完成 — 重新打印会刷新年龄。删除 3MF、缩略图、延时摄影、源 3MF、F3D 和照片。",days:"天",purgeStatsLabel:"同时从统计中移除",purgeStatsDescription:"启用后,每日清理任务还会将每个被清除的归档从 Quick Stats(耗材、时间、成本、能耗)中移除。默认关闭 — Quick Stats 保留贡献,仅文件从磁盘删除。",runNow:"立即清除归档",saveFailed:"无法保存自动清除设置。"},cameraTokens:{title:"摄像头 API 令牌",navTitle:"摄像头 API 令牌",description:"长期令牌,用于将摄像头流嵌入 Home Assistant、Frigate、信息亭或其他需要稳定 URL 的工具。每个令牌仅限摄像头流,可随时撤销。",loading:"加载中…",confirmRevoke:{title:"撤销此令牌?",body:"使用「{{name}}」的任何设备将立即失去访问权限。此操作无法撤销。",cancel:"取消",confirm:"撤销"},create:{title:"创建新令牌",nameLabel:"令牌名称",namePlaceholder:"例如 Home Assistant",daysLabel:"过期天数",submit:"创建",hint:"最大有效期 365 天。令牌值仅在创建时显示一次 — 请立即复制。"},created:{title:"令牌已创建 — 立即复制",warning:"这是此令牌唯一一次可见。关闭此对话框后您将无法再次查看。",copy:"复制",dismiss:"我已保存"},list:{myTitle:"我的令牌",allTitle:"所有用户(管理员视图)",empty:"暂无令牌。",name:"名称",owner:"所有者",prefix:"前缀",created:"创建时间",expires:"过期时间",lastUsed:"最近使用",revoke:"撤销",expired:"已过期"},toast:{created:"令牌已创建",createFailed:"创建令牌失败",revoked:"令牌已撤销",revokeFailed:"撤销令牌失败",loadFailed:"加载令牌失败",copied:"已复制到剪贴板",copyFailed:"复制失败 — 手动选择并复制"}},forecast:{title:"库存预测",noSpools:"未找到活跃的料卷。请将料卷添加到库存中以查看预测数据。",noUsageData:"无可用使用数据 — 无法预测库存时间线。",sku:"SKU",material:"材料",stock:"库存",dailyRate:"消耗率",daysLeft:"剩余天数",emptyBy:"耗尽日期",reorderBy:"补货截止日",actions:"操作",trend:"趋势",estimated:"估算",noData:"无数据",timeframe:"时间范围",chartTitle:"库存预测 — 前5种材料",dashedLinesROP:"虚线 = 再订货点",stockLevel:"库存量",reorderPoint:"再订购点",safetyMargin:"安全余量",trendLegend:"趋势(基于历史,95%服务水平)",estimatedLegend:"估算(重量差值)",noDataLegend:"无数据",ropLabel:"再订货点",ssLabel:"安全库存",safetyStockLegend:"安全库存",stockArrivalLegend:"到货",stockoutLegend:"断货",alertCount_one:"{{count}}条警告",alertCount_other:"{{count}}条警告",order:"订购",globalLeadTime:"全局交货期",globalLeadTimeHint:"全局交货期下限 — 用于所有 SKU 的再订购点计算",save:"保存",cancel:"取消",settingsSaved:"设置已保存",failedSaveSettings:"保存设置失败",globalLeadTimeSaved:"全局提前期已保存",skuLeadTimeOverride:"SKU 交货期覆盖",skuLeadTimeHint:"0 = 使用全局交货期。设置 >0 以覆盖此 SKU。",safetyMarginLabel:"安全余量",effectiveLeadTime:"有效交货期",effectiveLeadTimeHint:"max(全局 {{global}}天, SKU {{sku}}天)",reorderPointHint:"d̄ × LT + safety margin — 当库存降至此水平时下单",safetyMarginHint:"统计安全库存 (z=1.65 × σ × √LT) + 用户自定义缓冲",safetyMarginHintDays:"在统计安全库存基础上额外增加的缓冲。{{approx}}",safetyMarginHintDaysApprox:" ≈ 按当前速率 {{g}}g。",safetyMarginHintG:"在统计安全库存基础上增加的固定重量缓冲。{{approx}}",safetyMarginHintGApprox:" ≈ 按当前速率 {{days}}天。",individualSpools:"单个料卷",labelWeight:"标注重量",spoolCount_one:"{{count}}个线轴",spoolCount_other:"{{count}}个线轴",stockBreakRisk:"断货风险",stockBreakBefore:"补货前库存断档",stockBreakDetail:"剩余 {{days}} 天,交货期 {{lt}} 天。",reorderNow:"立即补货",reorderTriggerPassed:"触发日期 {{date}} 已过。",shoppingList:"购物清单",shoppingListItems_one:"({{count}}项)",shoppingListItems_other:"({{count}}项)",shoppingListEmpty:"购物清单为空。点击任意行的购物车图标以添加商品。",addToCart:"添加到购物清单",alertsSnoozed:"静音此SKU的提醒",alertsEnabled:"启用此SKU的提醒",addedToCart:"已添加到购物清单",failedAddItem:"添加项目失败",listView:"列表",logisticsView:"物流",qty:"数量",weight:"重量",leadTime:"交货期",expectedRestock:"预计补货日期",status:"状态",note:"备注",pending:"待处理",purchased:"已购买",received:"已收货",markPurchased:"标记为已购买",markReceived:"标记为已收货 — 将料卷添加到库存",resetToPending:"重置为待处理",remove:"移除",clearAll:"清空",downloadCsv:"CSV",addToCartTitle:"添加到购物清单",byQuantity:"按数量",byDuration:"按时长",numberOfSpools:"线轴数量",lastHowManyDays:"需要持续多少天?",noUsageQty:"无使用数据 — 数量已设为1。",noteOptional:"备注(可选)",notePlaceholder:"例如:用于项目X,紧急…",addNSpools_one:"添加{{count}}个线轴",addNSpools_other:"添加{{count}}个线轴",onArrival:"到货时",stockBreakIn:"{{days}} 天后断货。",stockRunsOutBefore:"库存在 {{lt}} 天交货期结束前耗尽。",atRate:"按 {{rate}}g/天的速度,您需要",moreSpools_one:"再{{count}}个线轴",moreSpools_other:"再{{count}}个线轴",bridgeGap:"来弥补缺口。",noReadAccess:"您没有查看库存预测的权限。",noWriteAccess:"您没有修改预测设置的权限。"}},spe={nav:{printers:"印表機",archives:"歸檔",queue:"列印佇列",stats:"統計",profiles:"設定檔案",maintenance:"維護",projects:"專案",inventory:"耗材",files:"檔案管理器",makerworld:"MakerWorld",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:"錯誤",errorLoading:"載入錯誤",retry:"重試",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:"所有位置"},toolbar:{filters:"篩選",view:"檢視",actions:"操作"},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:"Wi-Fi 訊號",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:"新增印表機失敗",connectionFailedNotAdded:"無法連線到印表機。請檢查 IP 位址、序號和存取碼,並確認已啟用僅區域網路(LAN-only)模式。該印表機未被新增。",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 重新讀取",loadInitiated:"載入耗材中…",unloadInitiated:"卸載耗材中…",failedToLoad:"載入耗材失敗",failedToUnload:"卸載耗材失敗"},connection:{connected:"已連線",offline:"離線"},plateStatus:{markCleared:"將列印板標記為已清理",cleared:"列印板已清理",notCleared:"列印板未清理",inUse:"列印板使用中"},queue:{inQueue:"佇列中有 {{count}} 個列印任務",inQueue_plural:"佇列中有 {{count}} 個列印任務"},controls:"控制",rfid:{reread:"重新讀取 RFID"},ams:{load:"載入",unload:"卸載"},bedJog:{title:"移動熱床",bed:"熱床",step:"步長 (mm)",up:"熱床上移",down:"熱床下移",disabledWhilePrinting:"列印中已停用",notHomedTitle:"印表機未歸零",notHomedMessage:"印表機自上次列印以來尚未歸零。請先執行自動歸零以確保安全定位(先停放噴頭,然後歸零 X、Y 和 Z),或者直接移動 — 軟限位將被繞過。",homeZ:"自動歸零",moveAnyway:"強制移動",homingStarted:"印表機自動歸零中…"},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:"關機",haToggleTitle:'切換"{{name}}"',haToggleMessage:"切換 Home Assistant 實體 {{entity}}?如果目前為開啟狀態,可能會關閉電源。",haToggleWarning:'警告:"{{name}}"正在列印中!切換 {{entity}} 可能會切斷電源並中斷列印。是否繼續?',haToggleButton:"切換"},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:"韌體已上傳!請在印表機螢幕上觸發更新。",availableVersions:"可用版本",usable:"可用",unavailable:"不可用",installed:"已安裝",newerBadge:"較新",olderBadge:"較舊",currentBadge:"目前"},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:"QR 碼",viewPhotos:"檢視照片",viewPhotosCount:"檢視照片 ({{count}})",projectPage:"專案頁面",addToFavorites:"新增到收藏",removeFromFavorites:"從收藏中移除",edit:"編輯",printLog:"列印記錄",goToProject:"前往專案:{{name}}",addToProject:"新增到專案",removeFromProject:"從專案中移除",loading:"載入中...",noProjectsAvailable:"無可用專案",searchProjects:"搜尋專案…",select:"選擇",deselect:"取消選擇",delete:"刪除"},permission:{noReprint:"您沒有重新列印此歸檔的權限",noAddToQueue:"您沒有新增到佇列的權限",noUpdateArchives:"您沒有更新歸檔的權限",noUploadFiles:"您沒有上傳檔案的權限",noDownload:"您沒有下載歸檔的權限",noCopyLink:"您沒有複製下載連結的權限",noDelete:"您沒有刪除此歸檔的權限",noCreate:"您沒有建立歸檔的權限"},platePicker:{title:"選擇要預覽的列印板",hint:"此存檔包含多個列印板。選擇一個在 GCode 檢視器中開啟。",plateLabel:"列印板 {{index}}",objectCount:"{{count}} 個物件",objectCount_plural:"{{count}} 個物件",noGcode:"此存檔沒有可預覽的已切片 G 代碼。請先在 Bambu Studio 中開啟並切片。"},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}}",runsBadge:"{{count}} 次列印",runsBadgeTitle:"共 {{count}} 次列印 — 成功 {{successful}} 次,失敗 {{failed}} 次。點擊查看完整列印記錄。",estimated:"預計:{{time}}",actual:"實際:{{time}}",accuracy:"準確度:{{percent}}%",filament:"{{weight}} 克",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:"刪除"},runLog:{title:"列印記錄",modalTitle:"列印記錄 — {{name}}",modalTitleFallback:"此歸檔",empty:"此歸檔尚未記錄任何列印事件。",col:{date:"日期",status:"狀態",duration:"時長",filament:"耗材",cost:"成本"},status:{completed:"已完成",failed:"失敗",cancelled:"已取消",stopped:"已停止",skipped:"已略過",printing:"列印中"}},modal:{deleteArchive:"刪除歸檔",deleteConfirm:'確定要刪除"{{name}}"嗎?此操作無法復原。',deleteButton:"刪除",deletePurgeStats:"同時從快速統計中刪除此列印(耗材、時間、成本、能耗)",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:"佇列中的下一個",clearPlateSuccess:"列印板已清理 — 準備進行下一個列印",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:"取消中…",awaitingPrinter:"等待印表機…",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:"虛擬印表機",spoolbuddy:"SpoolBuddy",failureDetection:"故障檢測",users:"身份驗證",backup:"備份",emailAuth:"信箱認證",ldap:"LDAP",twoFa:"雙因素認證",oidc:"SSO / OIDC",security:"安全"},spoolbuddy:{infoTitle:"SpoolBuddy 裝置",infoBody:"SpoolBuddy kiosk 透過心跳自動註冊。如果裝置不再使用,或守護程式當機遺留了過時的重複項,可在此取消註冊。",duplicatesTitle:"已註冊 {{count}} 台裝置",duplicatesBody:"kiosk 介面只使用最先註冊的裝置。如果其中有因當機遺留的過時重複項,請取消註冊它——線上裝置會在下次心跳時重新註冊自己。",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:"磁碟",update:"更新",updateConfirmTitle:"更新 SpoolBuddy 守護程式?",updateConfirmBody:'對 "{{hostname}}" 觸發軟體更新?更新完成後守護程式將重新啟動。',restartBrowser:"重新啟動瀏覽器",restartBrowserConfirmTitle:"重新啟動 kiosk 瀏覽器?",restartBrowserConfirmBody:'在 "{{hostname}}" 上重新啟動 kiosk 瀏覽器?顯示將短暫黑屏。',restartDaemon:"重新啟動守護程式",restartDaemonConfirmTitle:"重新啟動 SpoolBuddy 守護程式?",restartDaemonConfirmBody:'在 "{{hostname}}" 上重新啟動 SpoolBuddy 守護程式?裝置將離線幾秒鐘。',reboot:"重新開機",rebootConfirmTitle:"重新開機?",rebootConfirmBody:'重新開機 "{{hostname}}"?裝置將離線約一分鐘。',shutdown:"關機",shutdownConfirmTitle:"關閉裝置?",shutdownConfirmBody:'關閉 "{{hostname}}"?您需要實體存取才能重新開機。',commandConfirm:"確認",commandQueued:"命令已加入佇列",commandError:"傳送命令失敗"},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})。",advanced:"進階",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 同步重量失敗",spoolmanAmsSyncButton:"從 AMS 同步 Spoolman 重量",spoolmanAmsSyncTitle:"從 AMS 同步 Spoolman 耗材重量",spoolmanAmsSyncMessage:"這將根據已連線印表機的目前 AMS 剩餘百分比值更新所有 Spoolman 耗材重量。印表機必須線上。",spoolmanAmsSyncing:"同步中...",spoolmanAmsSyncSuccess:"已同步 {{synced}} 個 Spoolman 耗材,跳過 {{skipped}} 個",spoolmanAmsSyncError:"從 AMS 同步 Spoolman 重量失敗",spoolmanAmsSyncErrorUnreachable:"同步失敗(Spoolman 無法存取)",spoolmanAmsSyncErrorNotConfigured:"同步失敗(Spoolman 未設定)",spoolmanNotConfigured:"Spoolman 未設定",spoolmanFilamentCatalogTitle:"Spoolman 耗材目錄",spoolmanFilamentCatalogDesc:"來自 Spoolman 的耗材名稱和皮重。名稱和線軸重量可在此處編輯;其他屬性請直接在 Spoolman 中管理。",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:"暫停、繼續和停止列印",cloudAccess:"允許雲端存取",cloudAccessDescription:"代表您讀取 Bambu Cloud 預設和耗材。需要登入 Bambu Cloud。",cloudBadge:"雲端",updateEnergyCost:"更新電價",updateEnergyCostDescription:"允許此金鑰向 /settings/electricity-price POST 新的每千瓦時電價。適用於 Home Assistant 動態電價自動化(Tibber、Octopus 等)。這是唯一可透過 API 金鑰寫入的設定欄位。",energyCostBadge:"能耗",legacyKey:"舊版",legacyKeyTooltip:"在按使用者所有權之前建立;需重建以使用雲端存取",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:"錯開啟動",staggeredStartDescription:"多台印表機批次啟動時的預設群組大小與間隔。可在列印對話框中逐批覆寫。",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:"群組大小",staggerGroupSizeHelp:"每個群組要同時啟動的印表機數量",staggerInterval:"間隔(分鐘)",staggerIntervalHelp:"每個群組啟動之間的延遲",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:"輸入密碼",passwordRequirements:"至少 8 個字元,包含一個大寫、一個小寫、一個數字和一個特殊字元。",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:"選擇要用於開啟檔案的切片軟體",orcaslicerKnownIssuesWarning:"OrcaSlicer 2.3.2 / 2.4.0-dev 存在已知 CLI 錯誤,無法切片許多 Bambu 建立的 3MF — 見上游 issue #12426(繪製的多擠出機檔案 segfault)和 #13386(參數範圍嚴格驗證拒絕)。在上游修復發布之前,推薦使用 Bambu Studio。",useSlicerApi:"使用切片器 API",useSlicerApiDescription:"開啟時,「切片」操作開啟應用程式內切片器對話框並呼叫 slicer-API sidecar。關閉時(預設),透過 URI 方案交給桌面切片器。",slicerCard:"切片器",orcaslicerApiUrl:"OrcaSlicer sidecar URL",bambuStudioApiUrl:"Bambu Studio sidecar URL",slicerApiUrlDescription:"slicer-API sidecar 容器的 URL。留空以使用 SLICER_API_URL / BAMBU_STUDIO_API_URL 環境變數預設值。",slicerBundles:{title:"切片器捆綁包",description:'匯入從 BambuStudio 匯出的 Printer Preset Bundle (.bbscfg)(檔案 → 匯出 → 匯出預設捆綁包 → "Printer preset bundle")。匯入後,切片請求可以按名稱從捆綁包中選擇預設,無需重新上傳 JSON 設定三元組。',uploadButton:"上傳捆綁包",uploading:"上傳中…",loading:"載入捆綁包中…",empty:"尚未匯入捆綁包。",summary:"{{processCount}} 個製程 · {{filamentCount}} 個耗材預設",delete:"刪除",uploadSuccess:"已匯入 {{name}}",uploadError:"上傳捆綁包失敗:{{message}}",deleteSuccess:"捆綁包已移除",deleteError:"刪除捆綁包失敗:{{message}}",confirmDeleteTitle:"移除此捆綁包?",confirmDeleteMessage:"引用「{{name}}」的切片請求將失敗,直到捆綁包重新匯入。"},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:"密碼至少需要 8 個字元",passwordNeedsUppercase:"密碼必須至少包含一個大寫字母",passwordNeedsLowercase:"密碼必須至少包含一個小寫字母",passwordNeedsDigit:"密碼必須至少包含一個數字",passwordNeedsSpecial:"密碼必須至少包含一個特殊字元",enterGroupName:"請輸入群組名稱",settingsSaved:"設定已儲存",noPermissionUpdate:"您沒有權限變更設定",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:"刪除條目失敗",material:"材料",spoolWeight:"線軸重量",color:"顏色",updateSpoolWeight:"更新線軸重量",filamentUpdated:"耗材已更新",filamentUpdateFailed:"更新耗材失敗",filamentUpdateInvalid:"耗材資料無效",keepExistingSpoolWeight:"保留現有線軸的舊重量",keepExistingSpoolWeightDesc:"已使用此耗材類型建立的線軸保留舊的皮重。新線軸使用更新後的值。",applyToAllSpools:"套用至所有線軸",applyToAllSpoolsDesc:"此耗材類型的所有重量計算立即使用新的皮重。"},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)",cameraSnapshotUrl:"快照 URL(選用)",cameraSnapshotUrlPlaceholder:"http://192.168.1.61:1984/api/frame.jpeg?src=printer",cameraSnapshotUrlHelp:"用於通知縮圖、完成照片、層縮時攝影影格和列印板偵測的單一影格 URL。縮時攝影和列印板偵測各自需要自己的每印表機切換 — 此 URL 只是它們啟用時拉取的影像來源。留空以從上方即時串流擷取。適用於 go2rtc(/api/frame.jpeg)和具有專用快照端點的 IP 攝影機。",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 更新:",updateViaHomeAssistant:"更新由 Home Assistant Supervisor 管理。請在 Home Assistant 中開啟 設定 → 附加元件 → Bambuddy 以安裝新版本。",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:"將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:"身份驗證器 App (TOTP)",totpDesc:"使用 Google Authenticator、Aegis 或 Authy 等 App。",emailOtpTitle:"郵件 OTP",emailOtpDesc:"登入時向 {{email}} 傳送一次性驗證碼。",emailOtpNoEmail:"請先為帳戶新增信箱地址以啟用此方式。",addEmailFirst:"您的帳戶沒有信箱地址,請聯絡管理員新增。",setupTotp:"設定身份驗證器 App",setupAuthApp:"設定身份驗證器 App",setupInstructions:"使用身份驗證器 App 掃描QR Code,然後輸入驗證碼確認。",manualEntry:"無法掃描?請手動輸入此金鑰:",scannedContinue:"已掃描 — 繼續",enterCodeToConfirm:"請輸入身份驗證器 App 中的6位驗證碼以確認設定。",activate:"啟用",disableTotp:"停用身份驗證器",disableConfirmHint:"請輸入有效的 TOTP 碼或備用碼來停用身份驗證器。",totpDisabled:"身份驗證器 App 已停用。",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:"提供者已刪除。",refreshIcon:"重新整理圖示",removeIcon:"移除圖示",iconRefreshed:"圖示已重新整理。",iconRemoved:"圖示已移除。",iconFetchFailed:"無法從提供者 URL 取得圖示。",deleteTitle:"刪除提供者",deleteMessage:'刪除"{{name}}"?所有連結帳戶將斷開連線。',form:{name:"顯示名稱",issuerUrl:"頒發者 URL",clientId:"客戶端 ID",clientSecret:"客戶端金鑰",scopes:"作用域",iconUrl:"圖示 URL(可選)",enabled:"已啟用",autoCreate:"自動建立使用者",autoCreateDesc:"首次登入時自動建立本機帳戶。",autoLink:"自動連結已有帳戶",autoLinkDesc:"首次登入時透過信箱匹配現有本機帳戶並自動連結。",emailClaim:"電子郵件聲明",emailClaimDesc:"用作電子郵件身份的 JWT 聲明。Azure Entra ID 請使用 'preferred_username' 或 'upn'(不發送 email_verified)。僅使用可信的聲明名稱。",emailClaimPlaceholder:"電子郵件",emailClaimCustomClaimAutoLinkWarning:"自訂宣告僅在值由租用戶管理時(例如 Azure Entra ID 的 upn / preferred_username)對自動關聯安全。如果您的 IdP 允許使用者自我宣告此宣告,請勿啟用自動關聯。",requireEmailVerified:"要求電子郵件已驗證",requireEmailVerifiedDesc:"僅在提供商將電子郵件聲明標記為已驗證時才接受。",requireEmailVerifiedWarning:"警告:將在未經驗證的情況下接受電子郵件。僅對受信任的提供商使用。",requireEmailVerifiedAutoLink:"請先停用自動連結以變更此設定。",secretHint:"留空以保留目前",secretPlaceholder:"新金鑰",defaultGroup:"預設群組",defaultGroupDesc:"自動建立使用者時分配的群組。未設定時回退到 Viewers。",defaultGroupViewersFallback:"Viewers(預設)"}},encryption:{title:"MFA 加密狀態",enabledFromEnv:"已啟用靜態加密(金鑰來自 MFA_ENCRYPTION_KEY 環境變數)",enabledFromFile:"已啟用靜態加密(金鑰從資料目錄載入)",enabledGenerated:"使用自動產生的金鑰啟用靜態加密",notConfigured:"未設定靜態加密",notConfiguredDesc:"TOTP 機密和 OIDC client_secrets 以明文儲存。請設定 MFA_ENCRYPTION_KEY 或使用可寫資料目錄重新啟動 Bambuddy 以自動產生。",allEncrypted:"所有 MFA 機密皆已靜態加密。",legacyRowsLabel:"舊版明文列",encryptedRowsLabel:"已加密列",legacyRowsWarning:"偵測到 {{count}} 個舊版明文列。請重新儲存 OIDC 供應商或重新註冊使用者的身份驗證器應用程式,以遷移到加密儲存。",backupHint:"自動產生的金鑰儲存在 DATA_DIR/.mfa_encryption_key 中,並包含在本機備份 ZIP 中。請保護備份安全或顯式設定 MFA_ENCRYPTION_KEY。",decryptionBrokenTitle:"加密金鑰遺失",decryptionBrokenError:"無法解密 {{count}} 條加密記錄,因為加密金鑰不再可用。請還原先前的 MFA_ENCRYPTION_KEY 或 DATA_DIR/.mfa_encryption_key 以恢復存取。",migrationErrorWarning:"{{count}} 行舊資料在啟動時未能重新加密。請檢查伺服器日誌並重新啟動 Bambuddy 以重試。"}},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:"登入中...",rememberMe:"記住我",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:"知道了",resetPassword:{title:"設定新密碼",subtitle:"請在下方輸入並確認您的新密碼。",newPassword:"新密碼",newPasswordPlaceholder:"至少 8 個字元",confirmPassword:"確認密碼",confirmPasswordPlaceholder:"重複輸入新密碼",saving:"儲存中…",submit:"設定新密碼",backToLogin:"回到登入",passwordsDoNotMatch:"密碼不符",passwordTooShort:"密碼至少需要 8 個字元",resetFailed:"密碼重設失敗。連結可能已過期。"},twoFA:{title:"兩步驗證",subtitle:"您的帳戶已啟用兩步驗證。請在下方輸入驗證碼。",methodAuthenticator:"身份驗證器 App",methodEmail:"信箱驗證碼",methodBackup:"備用恢復碼",instructionsTotp:"請開啟您的身份驗證器 App,輸入 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:"切換腔室燈",unavailable:"攝影機無法使用",diagnose:{button:"診斷",modalTitle:"攝影機診斷",running:"正在執行診斷...",runFailed:"無法執行診斷: {{error}}",retry:"重新執行",stage:{tcp_reachable:"網路可達性",first_frame:"畫面擷取",live_stream_active:"直播串流進行中"},summary:{all_ok:"攝影機運作正常。診斷已成功完成所有階段。",live_stream_active_healthy:"攝影機正在傳輸最新畫面 — 無需測試。",printer_unreachable:"無法存取印表機。請檢查 IP 位址、網路連線以及印表機是否已開機。",camera_port_closed:"印表機可存取,但攝影機連接埠已關閉。請確認印表機設定中已啟用僅 LAN 模式與開發者模式。",no_frame:"已連線到攝影機,但未收到畫面。請重試或檢查印表機設定中攝影機是否已啟用。",unknown_failure:"攝影機診斷因不明原因失敗。請查看支援日誌了解詳情。"},meta:{protocol:"協定",port:"連接埠",profile:"設定檔"}}},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 個字元",ldapProvisioned:"已建立 LDAP 使用者「{{username}}」"},modal:{createUser:"建立使用者",editUser:"編輯使用者",cancel:"取消",creating:"建立中...",saving:"儲存中...",saveChanges:"儲存更改",advancedAuthSubtitle:"使用進階認證",tabsAriaLabel:"使用者來源",localTab:"本機",ldapTab:"LDAP",ldapSearchLabel:"搜尋目錄",ldapSearchPlaceholder:"輸入使用者名稱、姓名或電子郵件...",ldapMinChars:"輸入至少 2 個字元以搜尋",ldapTypeToSearch:"開始輸入以搜尋 LDAP 目錄",ldapSearching:"搜尋目錄中...",ldapNoResults:"目錄中沒有符合的使用者",ldapSearchError:"目錄搜尋失敗。請檢查 LDAP 伺服器狀態。",ldapAlreadyProvisioned:"已建立",ldapSelectedLabel:"已選",ldapProvision:"建立使用者",ldapProvisioning:"建立中...",ldapErrorProvision:"建立失敗。請檢查 LDAP 伺服器狀態後重試。"},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:"輸入驗證器 App 中的 6 位驗證碼",accessToken:"存取權杖",accessTokenHint:"貼上您的拓竹雲端存取權杖。中國大陸帳號(綁定手機號碼、無 Email 登入)僅能使用此方式登入。可從 MakerWorld 瀏覽器 Cookie 取得權杖,詳見 Wiki。",back:"返回",loginButton:"登入",verifyButton:"驗證",setTokenButton:"設定權杖",useToken:"改用存取權杖",useEmail:"改用信箱登入",toast:{loggedIn:"登入成功",codeSent:"驗證碼已傳送到您的信箱",enterTotp:"輸入驗證器 App 中的程式碼",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:"上傳失敗",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:"停用文字換行",collapse:"折疊",collapseFoldersByDefault:"預設折疊資料夾",expandFoldersByDefault:"預設展開資料夾",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:"您沒有列印的權限",noPermissionSlice:"您沒有切片檔案的權限",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 構建",urlLabel:"網址",urlPlaceholder:"https://makerworld.com/...",urlInvalid:"網址必須以 http:// 或 https:// 開頭",openExternalUrl:"開啟專案網址",coverImageLabel:"封面圖片",coverImageAlt:"專案封面圖片",coverImageUpload:"上傳",coverImageReplace:"替換",coverImageRemove:"移除",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:"匯出到檔案"},slice:{title:"切片模型",action:"切片",slicing:"切片中…",printer:"印表機設定檔",process:"製程設定檔",filament:"耗材設定檔",filamentSlot:"耗材 {{index}}({{type}})",selectPreset:"— 選擇預設 —",loadingPresets:"載入預設中…",analyzingPlateFilaments:"分析列印板耗材中…",analyzingPlateFilamentsHint:"正在執行預覽切片以發現此列印板使用的 AMS 插槽。之後會快取 — 重新開啟是即時的。",previewToast:"分析 {{name}} — {{elapsed}}",previewWithProgress:"分析 {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",notUsedByPlate:"— 此列印板未使用",noPresetsForSlot:"無可用預設",presetsLoadFailed:"載入預設失敗。請先開啟設定 → 設定檔以匯入。",allPresetsRequired:"必須選擇所有預設",bundle:"切片器套裝",bundleNone:"— 無(單獨選擇預設)—",bundleAllRequired:"必須選擇套裝的製程和每個耗材槽",enqueuing:"提交切片任務中…",queued:"已排隊…",failed:"切片失敗。請檢查切片器 sidecar 日誌。",startedToast:"在背景切片 {{name}}…",queuedToast:"已排隊:{{name}} — {{elapsed}}",runningToast:"切片 {{name}} — {{elapsed}}",runningWithProgress:"{{name}} – {{stage}} ({{percent}}%) – {{elapsed}}",completedToast:"已切片 {{name}}",failedToast:"切片 {{name}} 失敗:{{detail}}",tier:{local:"已匯入",cloud:"雲端",standard:"標準"},cloud:{notAuthenticated:"登入 Bambu Cloud(設定 → 設定檔 → 雲端)以查看雲端預設。",expired:"Bambu Cloud 工作階段已過期 — 請重新登入以重新整理雲端預設。",unreachable:"目前無法存取 Bambu Cloud。本機和標準預設仍可使用。"},bedType:{label:"列印板",auto:"自動(使用製程預設)",coolPlate:"冷板",coolPlateSuperTack:"Cool Plate SuperTack",engineering:"Engineering Plate",highTemp:"High Temp Plate",texturedPEI:"Textured PEI Plate",smoothPEI:"Smooth PEI Plate"}},spoolman:{title:"Spoolman 整合",enabled:"Spoolman 已啟用",url:"Spoolman URL",connected:"已連線",disconnected:"未連線",testConnection:"測試連線",sync:"同步",syncing:"同步中...",lastSync:"上次同步",linkToSpoolman:"連結到 Spoolman",openInSpoolman:"在 Spoolman 中開啟",unlinkSpool:"取消連結耗材",unlinkConfirmTitle:"取消指派料盤?",unlinkConfirmMessage:"這將從此插槽中移除料盤。料盤本身的資料將保持不變。",selectSpool:"選擇耗材",noUnlinkedSpools:"無未指派的料盤",linkSuccess:"料盤指派成功",linkFailed:"料盤指派失敗",unlinkSuccess:"料盤取消指派成功",unlinkFailed:"料盤取消指派失敗",linkedSpool:"已指派料盤",spoolId:"耗材 ID",fillSourceLabel:"(Spoolman)",weight:"重量",remaining:"剩餘",disableWeightSync:"停用 AMS 估計重量同步",disableWeightSyncDesc:"不從 AMS 估計值更新剩餘容量。如果您更喜歡 Spoolman 的用量追蹤而非 AMS 百分比估計,請使用此選項。新耗材仍將使用 AMS 估計值作為初始重量。",reportPartialUsage:"報告失敗列印的部分用量",reportPartialUsageDesc:"當列印失敗或被取消時,根據層進度報告估計的耗材使用量。"},inventory:{title:"耗材庫存",subtitle:"管理您的料盤",spoolmanMixedContentTitle:"Spoolman 無法透過 HTTPS 載入 — 瀏覽器已封鎖混合內容",spoolmanMixedContentBody:"Bambuddy 透過您的反向代理以 HTTPS 提供服務,但您的 Spoolman 位址仍為 HTTP。基於安全考量,瀏覽器會封鎖混合內容,因此內嵌的 Spoolman 介面無法載入。Spoolman 也必須可透過 HTTPS 存取。",spoolmanMixedContentFixReverseProxy:"請將 Spoolman 置於與 Bambuddy 相同的反向代理(Traefik / Nginx / Caddy)之後並啟用 HTTPS,然後在設定中將 Spoolman URL 更新為新的 HTTPS 位址。",spoolmanMixedContentFixOpenNewTab:"作為替代方案,可在新分頁以 HTTP 開啟 Spoolman — 混合內容規則僅適用於內嵌框架,獨立分頁仍可正常運作。",spoolmanOpenInNewTab:"在新分頁開啟 Spoolman",labels:{title:"列印線材標籤",selectedCount:"已選 {{count}} 項",pickSpools:"選擇要列印標籤的線材:",searchPlaceholder:"按名稱、品牌或 #ID 搜尋",filterByMaterial:"材料:",allMaterials:"全部",selectVisible:"選擇所有可見 ({{count}})",deselectVisible:"取消選擇可見",clearAll:"全部清除",noSpoolsToShow:"沒有要顯示的線材。請調整篩選條件後重試。",noMatches:"沒有線材符合目前搜尋或篩選。",printOne:"列印此線材的標籤",printLabels:"列印標籤…",bulkTitle:"從目前顯示的 {{count}} 個線材中選擇要列印標籤的",noSpoolsTitle:"沒有要貼標籤的線材",error:"無法產生標籤:{{msg}}",sortBy:{label:"排序:",id:"按 ID",color:"按顏色"},templates:{amsHolderSmall:{label:"AMS 支架 — 小 (74 × 33 mm)",hint:"每頁一個標籤;對應 MakerWorld 模型 752566 (AMS 耗材標籤支架) 中可列印的標籤。"},amsHolderLarge:{label:"AMS 支架 — 大 (75 × 55 mm)",hint:"每頁一個標籤;對應 AMS 耗材標籤支架的紙卡插入款。空間足夠放置色塊、品牌、材質、ID 與 QR 碼。"},box40x30:{label:"盒標籤 (40 × 30 mm)",hint:"每頁一張;常見的 DK/Brother 捲尺寸,適合用於耗材袋與儲物盒標籤。"},box:{label:"Box label (62 × 29 mm)",hint:"每頁一個標籤;適配 Brother PT/QL 和 Dymo 小標籤。"},averyL7160:{label:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",hint:"歐洲規格紙張;每張 A4 頁 21 個標籤。"},avery5160:{label:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",hint:"美國規格紙張;每張 Letter 頁 30 個標籤。"}}},addSpool:"新增耗材",editSpool:"編輯耗材",copySpool:"複製耗材",material:"材料",selectMaterial:"選擇材料...",subtype:"子類型",brand:"品牌",searchBrand:"搜尋品牌...",useCustomBrand:'使用"{{brand}}"',useCustomMaterial:"使用自訂材料:{{material}}",colorName:"顏色名稱",colorNamePlaceholder:"翡翠白、烈焰紅...",color:"顏色",hexColor:"十六進位顏色",pickColor:"選擇自訂顏色",labelWeight:"標籤重量",coreWeight:"空盤重量",searchSpoolWeight:"搜尋耗材重量...",weightUsed:"已使用",currentWeight:"剩餘重量",measuredWeight:"稱量重量",spoolName:"料盤",costPerKg:"每公斤成本",storageLocation:"存放位置",storageLocationPlaceholder:"例如:貨架A,抽屜1",openInInventory:"在庫存中查看",measuredWeightError:"稱量重量必須在 {{min}}g 到 {{max}}g 之間。",slicerFilament:"切片耗材",slicerFilamentName:"切片預設名稱",slicerPreset:"切片預設",searchPresets:"搜尋耗材預設...",selectedPreset:"已選擇",noPresetsFound:"未找到預設",tempOverrides:"溫度覆蓋",note:"備註",notePlaceholder:"關於此耗材的任何備註...",category:"類別",categoryPlaceholder:"例如:生產、原型、客戶A",categoryNone:"未分類",storageLocationNone:"未設定位置",lowStockThresholdOverride:"低庫存閾值(此料盤)",lowStockThresholdOverrideHelp:"留空以使用全域閾值({{global}}%)。",clearRfid:"清除 RFID 標籤",rfidCleared:"RFID 標籤已清除",archive:"歸檔",restore:"恢復",noSpools:"尚無耗材。新增您的第一個耗材開始使用。",noAvailableSpools:"沒有可用的耗材。請先向庫存中新增耗材,或從其他槽位取消指派一個耗材。",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:"顯示所有耗材",spoolmanSpools:"Spoolman 線軸",allMaterials:"所有材料",filterByBrand:"按品牌篩選...",showArchived:"顯示已歸檔",quickAdd:"快速新增(庫存)",quantity:"數量",stock:"庫存",configured:"已設定",spoolsCreated:"已建立 {{count}} 個耗材",spoolsPartiallyCreated:"已建立 {{created}} / {{total}} 個耗材(部分失敗)",spoolCreated:"耗材已建立",spoolUpdated:"耗材已更新",spoolDeleted:"耗材已刪除",deepLinkSpoolNotFound:"找不到耗材",deepLinkFetchFailed:"無法載入耗材 — 請重試",spoolArchived:"耗材已歸檔",spoolRestored:"耗材已恢復",kProfileSaveFailed:"K值設定檔設定無法儲存",syncWeightSpoolNotFound:"找不到耗材 — 可能已被刪除",syncWeightSpoolmanUnreachable:"Spoolman 無法存取 — 請稍後再試",syncWeightFailed:"重量同步失敗",spoolmanUnreachable:"Spoolman 無法存取 — 請稍後再試",deleteSpoolNotFound:"找不到耗材 — 可能已被刪除",deleteFailed:"刪除耗材失敗",archiveSpoolNotFound:"找不到耗材 — 可能已被刪除",archiveFailed:"歸檔耗材失敗",restoreSpoolNotFound:"找不到耗材 — 可能已被刪除",restoreFailed:"恢復耗材失敗",saveFailed:"儲存變更失敗",tagClearFailed:"清除標籤失敗",deleteConfirm:"確定要刪除此耗材嗎?此操作無法復原。",archiveConfirm:"確定要歸檔此耗材嗎?",advancedSettings:"進階設定",filamentInfoTab:"耗材資訊",paProfileTab:"PA 設定",filamentInfo:"耗材",additional:"附加",loadingPresets:"載入雲端預設中...",cloudConnected:"雲端已連線",cloudNotConnected:"雲端未連線(使用預設值)",recentColors:"最近",searchColors:"搜尋顏色...",searchResults:"搜尋結果",allColors:"所有顏色",commonColors:"常用顏色",showLess:"顯示更少",showAll:"顯示全部",noColorsFound:"沒有顏色匹配您的搜尋",noResults:"未找到匹配項",extraColorsLabel:"附加顏色",extraColorsPlaceholder:"EC984C,#6CD4BC,A66EB9,D87694",extraColorsHint:"貼上 2 至 8 個十六進位色值,以逗號分隔。將以漸層方式呈現。",extraColorsInvalid:"已略過無效的十六進位值:{{tokens}}",colorEffectLabel:"效果",colorEffect:{none:"無",sparkle:"閃光",wood:"木紋",marble:"大理石",glow:"夜光",matte:"霧面",silk:"絲光",galaxy:"星空",rainbow:"彩虹",metal:"金屬",translucent:"半透明",gradient:"漸層",dualColor:"雙色",triColor:"三色",multicolor:"多色"},selectMaterialFirst:"請先在耗材資訊分頁中選擇材料。",noPrintersConfigured:"未設定印表機。新增印表機以使用 PA 設定。",matchingFilter:"匹配",anyBrand:"任何品牌",anyVariant:"任何變體",autoSelect:"自動選擇",matches:"匹配",match:"匹配",noMatches:"無匹配",connected:"已連線",offline:"離線",printerOffline:"印表機離線。連線後檢視校準設定。",noKProfilesMatch:"沒有 K 值設定匹配所選耗材。",leftNozzle:"左噴嘴",rightNozzle:"右噴嘴",profilesSelected:"個校準設定已選擇",totalInventory:"總庫存",totalConsumed:"總消耗",byMaterial:"按材料",inPrinter:"在印表機中",lowStock:"庫存不足",sinceTracking:"自開始追蹤",resetUsage:"將用量重置為 0",resetUsageTooltip:"將此料盤的已消耗克數計數器歸零",resetUsageConfirm:"將此料盤的已消耗克數計數器重置為 0?後續列印將從零開始計算。料盤本身、剩餘重量計算與您的設定均不會變更。",resetAllUsage:"重置所有料盤的用量",resetAllUsageTooltip:"將每個料盤的已消耗克數計數器歸零",resetAllUsageConfirm:"將全部 {{count}} 個料盤(含已封存)的已消耗克數計數器重置為 0?這將清空「累計消耗」統計值,後續列印從零開始計算。料盤與剩餘重量不會變更。",usageReset:"料盤用量已重置為 0",allUsageReset:"已重置 {{count}} 個料盤",resetUsageFailed:"重置料盤用量失敗",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 之間",spoolmanFilamentCatalog:"Spoolman 耗材目錄",pickFromSpoolmanCatalog:"從 Spoolman 目錄選擇…",spoolmanFilamentSelected:"已從 Spoolman 目錄選擇耗材",spoolmanFilamentUnlinked:"已解除耗材目錄關聯",noSpoolmanFilaments:"Spoolman 目錄中未找到耗材",spoolmanFilamentColorSwatch:"耗材顏色",spoolWeightManagedBySpoolman:"空線軸重量在 Spoolman 中按耗材類型管理",spoolmanCatalogLoadFailed:"無法載入 Spoolman 耗材目錄"},timelapse:{title:"縮時攝影",create:"建立縮時攝影",download:"下載",delete:"刪除",preview:"預覽",frameRate:"幀率",quality:"品質",processing:"處理中...",noTimelapses:"無可用縮時攝影"},ams:{title:"AMS",slot:"槽位",empty:"空",emptySlot:"空槽位",slotEmpty:"空",emptySlotReset:"未指派線材",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:"錯開印表機啟動",staggerGroupSize:"群組大小",staggerInterval:"間隔(分鐘)",staggerPreview:"{{printers}} 台印表機 → 分成 {{groups}} 組,每組 {{size}} 台,每 {{interval}} 分鐘啟動一組",staggerLastGroup:"最後一組:{{count}}",staggerTotal:"總計:{{minutes}} 分鐘",staggerToPrinters:"分批傳送到 {{count}} 臺印表機",gcodeInjection:"注入自動列印G-code"},backup:{includesEncryptionKey:"本機備份包含 MFA 加密金鑰檔案(DATA_DIR/.mfa_encryption_key),因此備份 ZIP 是自包含的。請將 ZIP 視為敏感檔案 — 任何擁有該檔案的人都可以解密內部儲存的 OIDC 用戶端機密和 TOTP 機密。",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:"需要雲端登入",githubDescription:"自動將您的設定檔案同步到私有 GitHub 倉庫以進行備份和版本歷史紀錄。",repoIsPrivate:"儲存庫為私有 — 可安全備份。",repoIsPublicWarning:"儲存庫為公開(PUBLIC)。Bambuddy 備份包含 MQTT 認證、Home Assistant 權杖、Prometheus 權杖、您的 Bambu Cloud 電子郵件,以及透過 K-profile 暴露的印表機存取碼。在您於服務商設定中將儲存庫改為私有之前,儲存將被阻擋。",repoVisibilityUnknown:"無法確認儲存庫的可見性。Bambuddy 拒絕向任何未確認為私有的目標進行備份;儲存將被阻擋。",repositoryUrl:"倉庫 URL",repoUrlPlaceholderGitHub:"https://github.com/username/repo-name",repoUrlPlaceholderGitea:"https://gitea.example.com/username/repo-name",repoUrlPlaceholderForgejo:"https://forgejo.example.com/username/repo-name",repoUrlPlaceholderGitLab:"https://gitlab.com/username/repo-name",allowInsecureHttp:"允許不安全的 HTTP",allowInsecureHttpHint:"為無 TLS 的私人網路自托管執行個體啟用",personalAccessToken:"個人存取權杖",tokenSaved:"(已儲存)",enterNewToken:"輸入新權杖以更新",tokenHint:"具有內容讀寫權限的細粒度權杖",branch:"分支",provider:"Git 供應商",providerGitHub:"GitHub",providerGitLab:"GitLab",providerGitea:"Gitea",providerForgejo:"Forgejo",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:"排程備份",scheduledBackupDescription:"依排程自動建立備份快照。輸出目錄可掛載到 NAS 或外部儲存。",frequency:"頻率",backupTime:"時間",retention:"保留",retentionDescription:"保留的備份數量",outputPath:"輸出路徑",outputPathPlaceholder:"預設:{{path}}",outputPathDescription:"留空以使用預設位置",runNow:"立即執行",backupFiles:"備份檔案",noScheduledBackups:"尚無備份",deleteBackup:"刪除",deleteBackupConfirm:"要刪除此備份檔案嗎?",backupRunning:"備份進行中…",scheduledBackupComplete:"備份已成功完成",scheduledBackupFailed:"備份失敗",nextBackup:"下次備份",backupSize:"大小",utc:"UTC",defaultPathLabel:"預設:",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:"新增到佇列時自動開始列印。關閉後,列印任務等待手動派發。"},queueForceColorMatch:{title:"強制顏色匹配",description:"拒絕派發到沒有完全相同耗材類型和顏色的印表機。預設關閉 — 不啟用時,佇列僅按型號匹配,可能選到顏色錯誤的印表機。"},tailscaleDisabled:{title:"Tailscale 整合",description:"啟用以將此 VP 標記為透過 Tailscale 公開。顯示主機的 Tailscale 位址,以便您知道要貼上到切片器中的 IP。CA 匯入步驟保持不變 — 此切換對憑證無影響。"},setupRequired:{title:"需要設定",description:"虛擬印表機功能需要額外的系統設定才能工作。包括埠轉發、防火牆規則和平臺特定設定。",readGuide:"啟用前請閱讀設定指南"},archiveNameSource:{title:"存檔名稱來源",description:'選擇透過虛擬印表機接收檔案時新存檔的命名方式。"元資料"使用 3MF 中嵌入的切片標題(預設)。"檔名"使用 Bambu Studio 透過 FTP 傳送的檔案名稱 — 當您在"傳送到印表機"對話方塊中重新命名工作時非常有用。',metadata:"元資料",filename:"檔名"},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:"更新設定失敗",copyFailed:"複製失敗 — 請手動選取文字",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:"在列印之間保持啟用而非一次性",autoOffAfterDrying:"乾燥完成後自動關閉",autoOffAfterDryingDescription:"AMS 乾燥完成後關閉",delayAfterDryingMinutes:"乾燥後延遲(分鐘)",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")。如果主題發布原始數值,請留空。
  31. 乘數:mW→W使用0.001,kW→W使用1000。`,mqttEnergyHint:`JSON路徑從JSON負載中提取值。原始值請留空。
  32. 乘數:Wh→kWh使用0.001,MWh→kWh使用1000。`,mqttStateHint:`JSON路徑從JSON負載中提取值。原始值請留空。
  33. ON值:表示"ON"的確切字串。留空以自動檢測(ON、true、1)。`,restControl:"控制",restOnUrl:"開啟 URL",restOffUrl:"關閉 URL",restOnBody:"開啟請求內容",restOffBody:"關閉請求內容",restMethod:"HTTP 方法",restHeaders:"自訂標頭(JSON)",restStatusUrl:"狀態 URL",restStatusPath:"狀態 JSON 路徑",restStatusOnValue:"ON 值",restPowerUrl:"功率URL",restPowerPath:"功率 JSON 路徑",restPowerMultiplier:"功率乘數",restEnergyUrl:"能耗URL",restEnergyPath:"能耗 JSON 路徑",restEnergyMultiplier:"能耗乘數",restUrlRequired:"REST 插座至少需要一個 URL(ON 或 OFF)",restHeadersHint:'例如:{"Authorization": "Bearer your-token"}',restBodyHint:'例如:ON、{"state": "on"}',restStatusHint:"用於輪詢目前狀態的 URL",restPathHint:"例如:state 或 data.power.status",restPowerUrlHint:"功率資料的獨立URL(留空則使用狀態URL)",restEnergyUrlHint:"能耗資料的獨立URL(留空則使用狀態URL)",restEnergyHint:"每個值可以使用獨立的URL,或回退到狀態 URL。使用乘數進行單位轉換(例如:0.001 將 Wh 轉換為 kWh)。",testConnection:"測試連線",connectionSuccess:"連線成功",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 溫度超過閾值",inventoryAlerts:"庫存警報",stockReorderAlert:"補貨警報",stockReorderAlertDescription:"SKU 已達到補貨點",stockBreakAlert:"斷貨警報",stockBreakAlertDescription:"庫存將在補貨到達前耗盡",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:"(列印完成後)",eventPriority:{sectionTitle:"ntfy 優先級",helpNtfy:"為每個已啟用的事件選擇優先級。ntfy 使用它來升級提醒(聲音、可見性、推播行為)。此處未設定的級別將使用 ntfy 伺服器預設值。",min:"最低",low:"低",default:"預設",high:"高",urgent:"緊急"},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:"Git 備份",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:"目前耗材",plateReady:"熱床就緒: {{name}}",plateReadyLabel:"待清理的熱床",plateClearAction:"清理",plateClearedToast:"已將熱床標記為已清理",plateClearFailed:"無法將熱床標記為已清理"},modal:{spoolDetected:"偵測到耗材",assignToAms:"分配到 AMS",syncWeight:"同步重量",weightSynced:"已同步!",syncing:"同步中...",newTagDetected:"偵測到新標籤",addToInventory:"新增到庫存",assignToAmsTitle:"分配到 AMS",selectSlot:"選擇槽位",assign:"分配",assigning:"分配中...",assignSuccess:"已分配!",assignPendingInsert:"已分配。插入耗材後將設定槽位。",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:"執行時間",systemConfig:"後端與認證",backendUrl:"Bambuddy 後端 URL",apiToken:"API 權杖",apiTokenPlaceholder:"輸入 API 權杖",saveConfig:"儲存設定",systemQueued:"設定已加入佇列。",nfcDiagnostic:"NFC 診斷",scaleDiagnostic:"磅秤診斷",readTagDiagnostic:"讀取標籤診斷",testNfc:"測試讀卡器",testScale:"測試精度",testReadTag:"讀取標籤",systemFieldsRequired:"後端 URL 為必填項。",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:"建立耗材失敗",incompleteDataWarning:"已使用不完整的Spoolman資料寫入標籤"},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:"尚無檢測紀錄。"},makerworld:{title:"MakerWorld",description:"貼上 MakerWorld 模型連結,即可直接在 Bambuddy 中匯入並列印 —— 無需切換至 Bambu Handy 應用程式。",pasteUrlHeader:"從 MakerWorld 匯入",pasteUrlPlaceholder:"https://makerworld.com/en/models/… 或貼上任意 MakerWorld 連結",resolveButton:"解析",signInRequiredTitle:"下載需要登入 Bambu Cloud",signInRequiredBody:"您可以匿名瀏覽模型詳情,但下載 3MF 檔案需要 Bambu Cloud 帳戶。",openCloudSettings:"開啟雲端設定",untitledModel:"無標題模型",byCreator:"作者: {{name}}",downloadsCount:"{{count}} 次下載",licensePrefix:"授權條款",alreadyImported:"已在資料庫中",openOnMakerworld:"在 MakerWorld 中開啟",alreadyInLibrary:"此模型已在您的資料庫中 —— 可在檔案管理員 → MakerWorld 中找到",importSuccess:"已匯入 {{filename}} —— 已儲存至檔案管理員 → MakerWorld",platesHeader:"列印板 ({{count}})",plateDefaultName:"列印板 {{n}}",materialCount:"{{count}} 種耗材",amsRequired:"需要 AMS",slicedFor:"為 {{printer}} 切片",alsoCompatible:"還標記為相容:{{printers}}",importToLibrary:"儲存",sliceIn:"儲存並在 {{slicer}} 中切片",disclaimer:"MakerWorld 整合使用由社群記錄的 API 介面。Bambuddy 與 MakerWorld 或 Bambu Lab 無從屬或認可關係。",lastImportSuccess:"已匯入您的資料庫",lastImportAlreadyInLibrary:"已存在於您的資料庫中",viewInLibrary:"在檔案管理員中查看",openInBambuStudio:"在 Bambu Studio 中開啟",openInOrcaSlicer:"在 OrcaSlicer 中開啟",importTo:"匯入至檔案管理員",recentImportsHeader:"最近匯入",phaseResolving:"解析中",phaseDownloading:"下載中",folderAuto:"MakerWorld (預設)",importAll:"全部匯入",importAllProgress:"正在匯入 {{current}}/{{total}}",openGallery:"開啟圖片庫",galleryPrev:"上一張",galleryNext:"下一張",deleteImport:"從資料庫中移除",importDeleting:"正在移除…",importDeleted:"已從資料庫中移除",confirmDelete:"從資料庫中移除 {{filename}}?本機檔案將被刪除,但可以從 MakerWorld 重新匯入。",errors:{resolveFailed:"無法解析該 MakerWorld 連結。",downloadFailed:"下載失敗。請重試。",deleteFailed:"無法從資料庫中移除檔案。"}},gcodeViewer:{back:"返回",backToArchives:"返回列印歸檔",backToFiles:"返回檔案管理器"},libraryTrash:{title:"資源回收筒",headerButton:"資源回收筒",headerTooltip:"檢視已移至資源回收筒的檔案",backToFiles:"返回檔案管理員",subtitleAdmin:"已刪除的檔案會在資源回收筒保留 {{days}} 天,之後自動刪除。此檢視顯示所有使用者的資源回收筒。",subtitleUser:"已刪除的檔案會在資源回收筒保留 {{days}} 天,之後自動刪除。",loading:"正在載入資源回收筒…",loadError:"無法載入資源回收筒。",empty:"資源回收筒是空的。",summary:"{{count}} 個檔案 · {{size}}",emptyTrash:"清空資源回收筒",restore:"還原",purgeNow:"立即刪除",autoPurgeIn:"將於 {{when}} 自動刪除",days:"天",retentionLabel:"自動刪除時間",selectAll:"全選",selectOne:"選擇 {{filename}}",selectionCount:"已選擇 {{count}} 項",bulkRestore:"還原所選",bulkPurge:"刪除所選",col:{filename:"檔案",folder:"資料夾",size:"大小",deleted:"移入資源回收筒",autoPurge:"自動刪除",owner:"擁有者",actions:"操作"},confirm:{purgeTitle:"永久刪除?",purgeBody:"{{filename}} 將從磁碟中刪除,無法還原。",emptyTitle:"清空資源回收筒?",emptyBody:"全部 {{count}} 個檔案將從磁碟中刪除。此操作無法復原。",bulkPurgeTitle:"永久刪除所選檔案?",bulkPurgeBody:"所選的 {{count}} 個檔案將從磁碟中刪除,無法還原。",cta:"永久刪除"},toast:{restored:"檔案已還原。",restoreFailed:"無法還原檔案。",purged:"檔案已永久刪除。",purgeFailed:"無法刪除檔案。",emptied:"已從資源回收筒刪除 {{count}} 個檔案。",emptyFailed:"無法清空資源回收筒。",retentionSaved:"自動刪除已設定為 {{days}} 天。",retentionFailed:"無法儲存保留設定。",bulkRestored:"已還原 {{count}} 個檔案。",bulkPurged:"已刪除 {{count}} 個檔案。"}},libraryPurge:{title:"清理舊檔案",headerButton:"清理舊檔案",headerTooltip:"批次將舊檔案移至資源回收筒",description:"早於所選時間的檔案將被移至資源回收筒。外部資料夾會被略過。在自動刪除之前,您可以從資源回收筒還原檔案。",ageLabel:"移動早於以下天數的檔案",days:"天",includeNeverPrinted:"包括從未列印過的檔案",effectsTitle:"點擊清除時會發生什麼",effect1:"符合的檔案移至回收筒 — 尚未從磁碟刪除。",effect2:"在保留期到期之前,您可以隨時從回收筒復原。",effect3:"保留期滿後,回收筒清理器將它們從磁碟永久刪除。",effect4:"外部(連結)資料夾中的檔案將被略過 — Bambuddy 從不刪除不屬於自己的位元組。",previewLoading:"正在檢查符合的檔案數量…",previewFailed:"無法預覽清理結果。",previewSummary:"{{count}} 個檔案 · {{size}} 將被移至資源回收筒",andMore:"…還有 {{count}} 個",warning:"檔案將被軟刪除——在保留期結束前,您可以從資源回收筒還原它們。",confirmCta:"將 {{count}} 個移至資源回收筒",purging:"正在移至資源回收筒…",toast:{success:"已將 {{count}} 個檔案移至資源回收筒。",failed:"無法清理檔案。"}},libraryAutoPurge:{enableLabel:"自動清理舊檔案",enableDescription:"每天執行一次管理員清理。檔案會先進入資源回收筒——不會立即刪除。",ageLabel:"自動清理早於以下天數的檔案",ageDescription:"最少 7 天,最多 10 年。使用與手動「清理舊檔案」按鈕相同的時間規則。",days:"天",includeNeverPrinted:"包括從未列印過的檔案",saveFailed:"無法儲存自動清理設定。"},archivePurge:{headerButton:"清除舊條目",headerTooltip:"批次刪除舊歸檔",title:"清除舊歸檔",description:"清除舊的列印歷史。每個歸檔按其最近一次列印完成時間老化 — 重新列印歸檔會重新整理其年齡,因此活躍工作永遠不會被清除。",ageLabel:"刪除最近未列印的歸檔:",days:"天",effectsTitle:"點擊清除時會發生什麼",effect1:"每個符合的歸檔將從清單中隱藏,其磁碟檔案(3MF、縮圖、縮時攝影、原始 3MF、F3D、照片)也會被刪除。",effect2:"資料庫中的歸檔記錄會保留,因此 Quick Stats 仍可計入耗材、時間、成本與能耗的貢獻 — 與單筆刪除的預設行為一致。",effect3:"勾選下方「同時從統計中移除」,可一併清除 Quick Stats 中的貢獻(等同單筆刪除選項)。此操作無法復原。",effect4:"重新列印歸檔會重新整理其使用計時器,因此仍在使用的歸檔不會被清除。",purgeStatsLabel:"同時從統計中移除",purgeStatsHint:"從 Quick Stats(耗材、時間、成本、能耗)中移除符合的歸檔。未勾選時,Quick Stats 會保留所有貢獻,僅檔案從磁碟刪除。",previewLoading:"檢查符合的歸檔數量…",previewFailed:"無法預覽清除。",previewSummary:"將移除 {{count}} 個歸檔 · {{size}}",andMore:"…還有 {{count}} 個",warning:"檔案會從磁碟刪除且無法復原。繼續前請下載或收藏您想保留的內容。",confirmCta:"移除 {{count}} 個歸檔",purging:"移除中…",toast:{success:"已移除 {{count}} 個歸檔。",failed:"無法清除歸檔。"}},archiveAutoPurge:{enableLabel:"自動清除舊歸檔",enableDescription:"每天一次,將閾值內未列印的歸檔從清單中隱藏,並從磁碟中刪除其檔案。重新列印會重設計時器。",ageLabel:"自動刪除最近未列印的歸檔:",ageDescription:"最少 7 天,最多 10 年。基於最近一次列印完成 — 重新列印會重新整理年齡。刪除 3MF、縮圖、縮時攝影、原始 3MF、F3D 與照片。",days:"天",purgeStatsLabel:"同時從統計中移除",purgeStatsDescription:"啟用後,每日清理任務還會將每個被清除的歸檔從 Quick Stats(耗材、時間、成本、能耗)中移除。預設關閉 — Quick Stats 會保留貢獻,僅檔案從磁碟刪除。",runNow:"立即清除歸檔",saveFailed:"無法儲存自動清除設定。"},cameraTokens:{title:"攝影機 API 權杖",navTitle:"攝影機 API 權杖",description:"長期權杖,用於將攝影機串流嵌入 Home Assistant、Frigate、資訊站或其他需要穩定 URL 的工具。每個權杖僅限攝影機串流,可隨時撤銷。",loading:"載入中…",confirmRevoke:{title:"撤銷此權杖?",body:"使用「{{name}}」的任何裝置將立即失去存取權限。此操作無法復原。",cancel:"取消",confirm:"撤銷"},create:{title:"建立新權杖",nameLabel:"權杖名稱",namePlaceholder:"例如 Home Assistant",daysLabel:"到期天數",submit:"建立",hint:"最大有效期 365 天。權杖值僅在建立時顯示一次 — 請立即複製。"},created:{title:"權杖已建立 — 立即複製",warning:"這是此權杖唯一一次可見。關閉此對話框後您將無法再次查看。",copy:"複製",dismiss:"我已儲存"},list:{myTitle:"我的權杖",allTitle:"所有使用者(管理員視圖)",empty:"尚無權杖。",name:"名稱",owner:"擁有者",prefix:"前綴",created:"建立時間",expires:"到期時間",lastUsed:"最近使用",revoke:"撤銷",expired:"已過期"},toast:{created:"權杖已建立",createFailed:"建立權杖失敗",revoked:"權杖已撤銷",revokeFailed:"撤銷權杖失敗",loadFailed:"載入權杖失敗",copied:"已複製到剪貼簿",copyFailed:"複製失敗 — 手動選擇並複製"}},forecast:{title:"庫存預測",noSpools:"未找到活躍的料卷。請將料卷新增至庫存以查看預測資料。",noUsageData:"無可用使用資料 — 無法預測庫存時間線。",sku:"SKU",material:"材料",stock:"庫存",dailyRate:"消耗率",daysLeft:"剩餘天數",emptyBy:"耗盡日期",reorderBy:"補貨截止日",actions:"操作",trend:"趨勢",estimated:"估算",noData:"無資料",timeframe:"時間範圍",chartTitle:"庫存預測 — 前5種材料",dashedLinesROP:"虛線 = 再訂貨點",stockLevel:"庫存量",reorderPoint:"再訂購點",safetyMargin:"安全餘量",trendLegend:"趨勢(基於歷史,95%服務水準)",estimatedLegend:"估算(重量差值)",noDataLegend:"無資料",ropLabel:"再訂貨點",ssLabel:"安全庫存",safetyStockLegend:"安全庫存",stockArrivalLegend:"到貨",stockoutLegend:"斷貨",alertCount_one:"{{count}}條警告",alertCount_other:"{{count}}條警告",order:"訂購",globalLeadTime:"全域交貨期",globalLeadTimeHint:"全域交貨期下限 — 用於所有 SKU 的再訂購點計算",save:"儲存",cancel:"取消",settingsSaved:"設定已儲存",failedSaveSettings:"儲存設定失敗",globalLeadTimeSaved:"全域提前期已儲存",skuLeadTimeOverride:"SKU 交貨期覆蓋",skuLeadTimeHint:"0 = 使用全域交貨期。設定 >0 以覆蓋此 SKU。",safetyMarginLabel:"安全餘量",effectiveLeadTime:"有效交貨期",effectiveLeadTimeHint:"max(全域 {{global}}天, SKU {{sku}}天)",reorderPointHint:"d̄ × LT + safety margin — 當庫存降至此水準時下單",safetyMarginHint:"統計安全庫存 (z=1.65 × σ × √LT) + 使用者自訂緩衝",safetyMarginHintDays:"在統計安全庫存基礎上額外增加的緩衝。{{approx}}",safetyMarginHintDaysApprox:" ≈ 按當前速率 {{g}}g。",safetyMarginHintG:"在統計安全庫存基礎上增加的固定重量緩衝。{{approx}}",safetyMarginHintGApprox:" ≈ 按當前速率 {{days}}天。",individualSpools:"單個料卷",labelWeight:"標示重量",spoolCount_one:"{{count}}個線軸",spoolCount_other:"{{count}}個線軸",stockBreakRisk:"斷貨風險",stockBreakBefore:"補貨前庫存斷檔",stockBreakDetail:"剩餘 {{days}} 天,交貨期 {{lt}} 天。",reorderNow:"立即補貨",reorderTriggerPassed:"觸發日期 {{date}} 已過。",shoppingList:"購物清單",shoppingListItems_one:"({{count}}項)",shoppingListItems_other:"({{count}}項)",shoppingListEmpty:"購物清單為空。點擊任意列的購物車圖示以新增商品。",addToCart:"新增至購物清單",alertsSnoozed:"靜音此SKU的提醒",alertsEnabled:"啟用此SKU的提醒",addedToCart:"已新增至購物清單",failedAddItem:"新增項目失敗",listView:"列表",logisticsView:"物流",qty:"數量",weight:"重量",leadTime:"交貨期",expectedRestock:"預計補貨日期",status:"狀態",note:"備註",pending:"待處理",purchased:"已購買",received:"已收貨",markPurchased:"標記為已購買",markReceived:"標記為已收貨 — 將料卷新增至庫存",resetToPending:"重置為待處理",remove:"移除",clearAll:"清空",downloadCsv:"CSV",addToCartTitle:"新增至購物清單",byQuantity:"依數量",byDuration:"依時長",numberOfSpools:"線軸數量",lastHowManyDays:"需要持續多少天?",noUsageQty:"無使用資料 — 數量已設為1。",noteOptional:"備註(選填)",notePlaceholder:"例如:用於專案X,緊急…",addNSpools_one:"新增{{count}}個線軸",addNSpools_other:"新增{{count}}個線軸",onArrival:"到貨時",stockBreakIn:"{{days}} 天後斷貨。",stockRunsOutBefore:"庫存在 {{lt}} 天交貨期結束前耗盡。",atRate:"按 {{rate}}g/天的速度,您需要",moreSpools_one:"再{{count}}個線軸",moreSpools_other:"再{{count}}個線軸",bridgeGap:"來彌補缺口。",noReadAccess:"您沒有查看庫存預測的權限。",noWriteAccess:"您沒有修改預測設定的權限。"}},ope={en:{translation:Jme},de:{translation:epe},fr:{translation:tpe},ja:{translation:npe},it:{translation:rpe},"pt-BR":{translation:ape},"zh-CN":{translation:ipe},"zh-TW":{translation:spe}};Ao.use(XX).use(Mme).init({resources:ope,fallbackLng:"en",supportedLngs:["en","de","fr","ja","it","pt-BR","zh-CN","zh-TW"],detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:"bambutrack_language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!1}});const Q8=[{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:"简体中文"},{code:"zh-TW",name:"Chinese (Traditional)",nativeName:"繁體中文"}];var Y8="popstate";function lpe(t={}){function e(a,i){let{pathname:s,search:o,hash:l}=a.location;return DF("",{pathname:s,search:o,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(a,i){return typeof i=="string"?i:Tw(i)}return dpe(e,n,null,t)}function za(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function vc(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function cpe(){return Math.random().toString(36).substring(2,10)}function X8(t,e){return{usr:t.state,key:t.key,idx:e}}function DF(t,e,n=null,a){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof e=="string"?$y(e):e,state:n,key:e&&e.key||a||cpe()}}function Tw({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 $y(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substring(n),t=t.substring(0,n));let a=t.indexOf("?");a>=0&&(e.search=t.substring(a),t=t.substring(0,a)),t&&(e.pathname=t)}return e}function dpe(t,e,n,a={}){let{window:i=document.defaultView,v5Compat:s=!1}=a,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 b=u(),x=b==null?null:b-d;d=b,c&&c({action:l,location:w.location,delta:x})}function p(b,x){l="PUSH";let S=DF(w.location,b,x);d=u()+1;let k=X8(S,d),C=w.createHref(S);try{o.pushState(k,"",C)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;i.location.assign(C)}s&&c&&c({action:l,location:w.location,delta:1})}function f(b,x){l="REPLACE";let S=DF(w.location,b,x);d=u();let k=X8(S,d),C=w.createHref(S);o.replaceState(k,"",C),s&&c&&c({action:l,location:w.location,delta:0})}function g(b){return upe(b)}let w={get action(){return l},get location(){return t(i,o)},listen(b){if(c)throw new Error("A history only accepts one active listener");return i.addEventListener(Y8,m),c=b,()=>{i.removeEventListener(Y8,m),c=null}},createHref(b){return e(i,b)},createURL:g,encodeLocation(b){let x=g(b);return{pathname:x.pathname,search:x.search,hash:x.hash}},push:p,replace:f,go(b){return o.go(b)}};return w}function upe(t,e=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),za(n,"No window.location.(origin|href) available to create URL");let a=typeof t=="string"?t:Tw(t);return a=a.replace(/ $/,"%20"),!e&&a.startsWith("//")&&(a=n+a),new URL(a,n)}function ZX(t,e,n="/"){return mpe(t,e,n,!1)}function mpe(t,e,n,a){let i=typeof e=="string"?$y(e):e,s=Hm(i.pathname||"/",n);if(s==null)return null;let o=JX(t);ppe(o);let l=null;for(let c=0;l==null&&c<o.length;++c){let d=kpe(s);l=Spe(o[c],d,a)}return l}function JX(t,e=[],n=[],a="",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(a)&&c)return;za(u.relativePath.startsWith(a),`Absolute route path "${u.relativePath}" nested under path "${a}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),u.relativePath=u.relativePath.slice(a.length)}let m=Em([a,u.relativePath]),p=n.concat(u);o.children&&o.children.length>0&&(za(o.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${m}".`),JX(o.children,e,p,m,c)),!(o.path==null&&!o.index)&&e.push({path:m,score:vpe(m,o.index),routesMeta:p})};return t.forEach((o,l)=>{if(o.path===""||!o.path?.includes("?"))s(o,l);else for(let c of eZ(o.path))s(o,l,!0,c)}),e}function eZ(t){let e=t.split("/");if(e.length===0)return[];let[n,...a]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(a.length===0)return i?[s,""]:[s];let o=eZ(a.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 ppe(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:wpe(e.routesMeta.map(a=>a.childrenIndex),n.routesMeta.map(a=>a.childrenIndex)))}var hpe=/^:[\w-]+$/,fpe=3,gpe=2,bpe=1,xpe=10,ype=-2,Z8=t=>t==="*";function vpe(t,e){let n=t.split("/"),a=n.length;return n.some(Z8)&&(a+=ype),e&&(a+=gpe),n.filter(i=>!Z8(i)).reduce((i,s)=>i+(hpe.test(s)?fpe:s===""?bpe:xpe),a)}function wpe(t,e){return t.length===e.length&&t.slice(0,-1).every((a,i)=>a===e[i])?t[t.length-1]-e[e.length-1]:0}function Spe(t,e,n=!1){let{routesMeta:a}=t,i={},s="/",o=[];for(let l=0;l<a.length;++l){let c=a[l],d=l===a.length-1,u=s==="/"?e:e.slice(s.length)||"/",m=QN({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},u),p=c.route;if(!m&&d&&n&&!a[a.length-1].route.index&&(m=QN({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},u)),!m)return null;Object.assign(i,m.params),o.push({params:i,pathname:Em([s,m.pathname]),pathnameBase:Tpe(Em([s,m.pathnameBase])),route:p}),m.pathnameBase!=="/"&&(s=Em([s,m.pathnameBase]))}return o}function QN(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,a]=_pe(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:a.reduce((d,{paramName:u,isOptional:m},p)=>{if(u==="*"){let g=l[p]||"";o=s.slice(0,s.length-g.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 _pe(t,e=!1,n=!0){vc(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 a=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,c)=>(a.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(a.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),a]}function kpe(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return vc(!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 Hm(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,a=t.charAt(n);return a&&a!=="/"?null:t.slice(n)||"/"}var Npe=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Cpe(t,e="/"){let{pathname:n,search:a="",hash:i=""}=typeof t=="string"?$y(t):t,s;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?s=J8(n.substring(1),"/"):s=J8(n,e)):s=e,{pathname:s,search:Ape(a),hash:jpe(i)}}function J8(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 aE(t,e,n,a){return`Cannot include a '${t}' character in a manually specified \`to.${e}\` field [${JSON.stringify(a)}]. 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 Ppe(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function aO(t){let e=Ppe(t);return e.map((n,a)=>a===e.length-1?n.pathname:n.pathnameBase)}function iO(t,e,n,a=!1){let i;typeof t=="string"?i=$y(t):(i={...t},za(!i.pathname||!i.pathname.includes("?"),aE("?","pathname","search",i)),za(!i.pathname||!i.pathname.includes("#"),aE("#","pathname","hash",i)),za(!i.search||!i.search.includes("#"),aE("#","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(!a&&o.startsWith("..")){let p=o.split("/");for(;p[0]==="..";)p.shift(),m-=1;i.pathname=p.join("/")}l=m>=0?e[m]:"/"}let c=Cpe(i,l),d=o&&o!=="/"&&o.endsWith("/"),u=(s||o===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}var Em=t=>t.join("/").replace(/\/\/+/g,"/"),Tpe=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),Ape=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,jpe=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,Mpe=class{constructor(t,e,n,a=!1){this.status=t,this.statusText=e||"",this.internal=a,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Epe(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function Dpe(t){return t.map(e=>e.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var tZ=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function nZ(t,e){let n=t;if(typeof n!="string"||!Npe.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let a=n,i=!1;if(tZ)try{let s=new URL(window.location.href),o=n.startsWith("//")?new URL(s.protocol+n):new URL(n),l=Hm(o.pathname,e);o.origin===s.origin&&l!=null?n=l+o.search+o.hash:i=!0}catch{vc(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:a,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var rZ=["POST","PUT","PATCH","DELETE"];new Set(rZ);var Fpe=["GET",...rZ];new Set(Fpe);var Vy=y.createContext(null);Vy.displayName="DataRouter";var vT=y.createContext(null);vT.displayName="DataRouterState";var Lpe=y.createContext(!1),aZ=y.createContext({isTransitioning:!1});aZ.displayName="ViewTransition";var Rpe=y.createContext(new Map);Rpe.displayName="Fetchers";var Ipe=y.createContext(null);Ipe.displayName="Await";var jl=y.createContext(null);jl.displayName="Navigation";var kS=y.createContext(null);kS.displayName="Location";var Ac=y.createContext({outlet:null,matches:[],isDataRoute:!1});Ac.displayName="Route";var sO=y.createContext(null);sO.displayName="RouteError";var iZ="REACT_ROUTER_ERROR",Ope="REDIRECT",zpe="ROUTE_ERROR_RESPONSE";function Upe(t){if(t.startsWith(`${iZ}:${Ope}:{`))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 Bpe(t){if(t.startsWith(`${iZ}:${zpe}:{`))try{let e=JSON.parse(t.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new Mpe(e.status,e.statusText,e.data)}catch{}}function Hpe(t,{relative:e}={}){za(Gy(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:a}=y.useContext(jl),{hash:i,pathname:s,search:o}=CS(t,{relative:e}),l=s;return n!=="/"&&(l=s==="/"?n:Em([n,s])),a.createHref({pathname:l,search:o,hash:i})}function Gy(){return y.useContext(kS)!=null}function bd(){return za(Gy(),"useLocation() may be used only in the context of a <Router> component."),y.useContext(kS).location}var sZ="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function oZ(t){y.useContext(jl).static||y.useLayoutEffect(t)}function ji(){let{isDataRoute:t}=y.useContext(Ac);return t?nhe():qpe()}function qpe(){za(Gy(),"useNavigate() may be used only in the context of a <Router> component.");let t=y.useContext(Vy),{basename:e,navigator:n}=y.useContext(jl),{matches:a}=y.useContext(Ac),{pathname:i}=bd(),s=JSON.stringify(aO(a)),o=y.useRef(!1);return oZ(()=>{o.current=!0}),y.useCallback((c,d={})=>{if(vc(o.current,sZ),!o.current)return;if(typeof c=="number"){n.go(c);return}let u=iO(c,JSON.parse(s),i,d.relative==="path");t==null&&e!=="/"&&(u.pathname=u.pathname==="/"?e:Em([e,u.pathname])),(d.replace?n.replace:n.push)(u,d.state,d)},[e,n,s,i,t])}var lZ=y.createContext(null);function Wy(){return y.useContext(lZ)}function $pe(t){let e=y.useContext(Ac).outlet;return y.useMemo(()=>e&&y.createElement(lZ.Provider,{value:t},e),[e,t])}function NS(){let{matches:t}=y.useContext(Ac),e=t[t.length-1];return e?e.params:{}}function CS(t,{relative:e}={}){let{matches:n}=y.useContext(Ac),{pathname:a}=bd(),i=JSON.stringify(aO(n));return y.useMemo(()=>iO(t,JSON.parse(i),a,e==="path"),[t,i,a,e])}function Vpe(t,e){return cZ(t,e)}function cZ(t,e,n,a,i){za(Gy(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=y.useContext(jl),{matches:o}=y.useContext(Ac),l=o[o.length-1],c=l?l.params:{},d=l?l.pathname:"/",u=l?l.pathnameBase:"/",m=l&&l.route;{let S=m&&m.path||"";uZ(d,!m||S.endsWith("*")||S.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${d}" (under <Route path="${S}">) 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.
  34. Please change the parent <Route path="${S}"> to <Route path="${S==="/"?"*":`${S}/*`}">.`)}let p=bd(),f;if(e){let S=typeof e=="string"?$y(e):e;za(u==="/"||S.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 "${S.pathname}" was given in the \`location\` prop.`),f=S}else f=p;let g=f.pathname||"/",w=g;if(u!=="/"){let S=u.replace(/^\//,"").split("/");w="/"+g.replace(/^\//,"").split("/").slice(S.length).join("/")}let b=ZX(t,{pathname:w});vc(m||b!=null,`No routes matched location "${f.pathname}${f.search}${f.hash}" `),vc(b==null||b[b.length-1].route.element!==void 0||b[b.length-1].route.Component!==void 0||b[b.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 x=Ype(b&&b.map(S=>Object.assign({},S,{params:Object.assign({},c,S.params),pathname:Em([u,s.encodeLocation?s.encodeLocation(S.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathname]),pathnameBase:S.pathnameBase==="/"?u:Em([u,s.encodeLocation?s.encodeLocation(S.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathnameBase])})),o,n,a,i);return e&&x?y.createElement(kS.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...f},navigationType:"POP"}},x):x}function Gpe(){let t=the(),e=Epe(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,a="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:a},s={padding:"2px 4px",backgroundColor:a},o=null;return console.error("Error handled by React Router default ErrorBoundary:",t),o=y.createElement(y.Fragment,null,y.createElement("p",null,"💿 Hey developer 👋"),y.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",y.createElement("code",{style:s},"ErrorBoundary")," or"," ",y.createElement("code",{style:s},"errorElement")," prop on your route.")),y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},e),n?y.createElement("pre",{style:i},n):null,o)}var Wpe=y.createElement(Gpe,null),dZ=class extends y.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=Bpe(t.digest);n&&(t=n)}let e=t!==void 0?y.createElement(Ac.Provider,{value:this.props.routeContext},y.createElement(sO.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?y.createElement(Kpe,{error:t},e):e}};dZ.contextType=Lpe;var iE=new WeakMap;function Kpe({children:t,error:e}){let{basename:n}=y.useContext(jl);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let a=Upe(e.digest);if(a){let i=iE.get(e);if(i)throw i;let s=nZ(a.location,n);if(tZ&&!iE.get(e))if(s.isExternal||a.reloadDocument)window.location.href=s.absoluteURL||s.to;else{const o=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(s.to,{replace:a.replace}));throw iE.set(e,o),o}return y.createElement("meta",{httpEquiv:"refresh",content:`0;url=${s.absoluteURL||s.to}`})}}return t}function Qpe({routeContext:t,match:e,children:n}){let a=y.useContext(Vy);return a&&a.static&&a.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=e.route.id),y.createElement(Ac.Provider,{value:t},n)}function Ype(t,e=[],n=null,a=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);za(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,g=m.route.loader&&!p.hasOwnProperty(m.route.id)&&(!f||f[m.route.id]===void 0);if(m.route.lazy||g){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}let d=n&&a?(u,m)=>{a(u,{location:n.location,params:n.matches?.[0]?.params??{},unstable_pattern:Dpe(n.matches),errorInfo:m})}:void 0;return s.reduceRight((u,m,p)=>{let f,g=!1,w=null,b=null;n&&(f=o&&m.route.id?o[m.route.id]:void 0,w=m.route.errorElement||Wpe,l&&(c<0&&p===0?(uZ("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),g=!0,b=null):c===p&&(g=!0,b=m.route.hydrateFallbackElement||null)));let x=e.concat(s.slice(0,p+1)),S=()=>{let k;return f?k=w:g?k=b:m.route.Component?k=y.createElement(m.route.Component,null):m.route.element?k=m.route.element:k=u,y.createElement(Qpe,{match:m,routeContext:{outlet:u,matches:x,isDataRoute:n!=null},children:k})};return n&&(m.route.ErrorBoundary||m.route.errorElement||p===0)?y.createElement(dZ,{location:n.location,revalidation:n.revalidation,component:w,error:f,children:S(),routeContext:{outlet:null,matches:x,isDataRoute:!0},onError:d}):S()},null)}function oO(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Xpe(t){let e=y.useContext(Vy);return za(e,oO(t)),e}function Zpe(t){let e=y.useContext(vT);return za(e,oO(t)),e}function Jpe(t){let e=y.useContext(Ac);return za(e,oO(t)),e}function lO(t){let e=Jpe(t),n=e.matches[e.matches.length-1];return za(n.route.id,`${t} can only be used on routes that contain a unique "id"`),n.route.id}function ehe(){return lO("useRouteId")}function the(){let t=y.useContext(sO),e=Zpe("useRouteError"),n=lO("useRouteError");return t!==void 0?t:e.errors?.[n]}function nhe(){let{router:t}=Xpe("useNavigate"),e=lO("useNavigate"),n=y.useRef(!1);return oZ(()=>{n.current=!0}),y.useCallback(async(i,s={})=>{vc(n.current,sZ),n.current&&(typeof i=="number"?await t.navigate(i):await t.navigate(i,{fromRouteId:e,...s}))},[t,e])}var e6={};function uZ(t,e,n){!e&&!e6[t]&&(e6[t]=!0,vc(!1,n))}y.memo(rhe);function rhe({routes:t,future:e,state:n,onError:a}){return cZ(t,void 0,n,a,e)}function hg({to:t,replace:e,state:n,relative:a}){za(Gy(),"<Navigate> may be used only in the context of a <Router> component.");let{static:i}=y.useContext(jl);vc(!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}=y.useContext(Ac),{pathname:o}=bd(),l=ji(),c=iO(t,aO(s),o,a==="path"),d=JSON.stringify(c);return y.useEffect(()=>{l(JSON.parse(d),{replace:e,state:n,relative:a})},[l,d,a,e,n]),null}function mZ(t){return $pe(t.context)}function Pr(t){za(!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 ahe({basename:t="/",children:e=null,location:n,navigationType:a="POP",navigator:i,static:s=!1,unstable_useTransitions:o}){za(!Gy(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=t.replace(/^\/*/,"/"),c=y.useMemo(()=>({basename:l,navigator:i,static:s,unstable_useTransitions:o,future:{}}),[l,i,s,o]);typeof n=="string"&&(n=$y(n));let{pathname:d="/",search:u="",hash:m="",state:p=null,key:f="default"}=n,g=y.useMemo(()=>{let w=Hm(d,l);return w==null?null:{location:{pathname:w,search:u,hash:m,state:p,key:f},navigationType:a}},[l,d,u,m,p,f,a]);return vc(g!=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.`),g==null?null:y.createElement(jl.Provider,{value:c},y.createElement(kS.Provider,{children:e,value:g}))}function ihe({children:t,location:e}){return Vpe(FF(t),e)}function FF(t,e=[]){let n=[];return y.Children.forEach(t,(a,i)=>{if(!y.isValidElement(a))return;let s=[...e,i];if(a.type===y.Fragment){n.push.apply(n,FF(a.props.children,s));return}za(a.type===Pr,`[${typeof a.type=="string"?a.type:a.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),za(!a.props.index||!a.props.children,"An index route cannot have child routes.");let o={id:a.props.id||s.join("-"),caseSensitive:a.props.caseSensitive,element:a.props.element,Component:a.props.Component,index:a.props.index,path:a.props.path,middleware:a.props.middleware,loader:a.props.loader,action:a.props.action,hydrateFallbackElement:a.props.hydrateFallbackElement,HydrateFallback:a.props.HydrateFallback,errorElement:a.props.errorElement,ErrorBoundary:a.props.ErrorBoundary,hasErrorBoundary:a.props.hasErrorBoundary===!0||a.props.ErrorBoundary!=null||a.props.errorElement!=null,shouldRevalidate:a.props.shouldRevalidate,handle:a.props.handle,lazy:a.props.lazy};a.props.children&&(o.children=FF(a.props.children,s)),n.push(o)}),n}var bN="get",xN="application/x-www-form-urlencoded";function wT(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function she(t){return wT(t)&&t.tagName.toLowerCase()==="button"}function ohe(t){return wT(t)&&t.tagName.toLowerCase()==="form"}function lhe(t){return wT(t)&&t.tagName.toLowerCase()==="input"}function che(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function dhe(t,e){return t.button===0&&(!e||e==="_self")&&!che(t)}function LF(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let a=t[n];return e.concat(Array.isArray(a)?a.map(i=>[n,i]):[[n,a]])},[]))}function uhe(t,e){let n=LF(t);return e&&e.forEach((a,i)=>{n.has(i)||e.getAll(i).forEach(s=>{n.append(i,s)})}),n}var Nk=null;function mhe(){if(Nk===null)try{new FormData(document.createElement("form"),0),Nk=!1}catch{Nk=!0}return Nk}var phe=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function sE(t){return t!=null&&!phe.has(t)?(vc(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${xN}"`),null):t}function hhe(t,e){let n,a,i,s,o;if(ohe(t)){let l=t.getAttribute("action");a=l?Hm(l,e):null,n=t.getAttribute("method")||bN,i=sE(t.getAttribute("enctype"))||xN,s=new FormData(t)}else if(she(t)||lhe(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(a=c?Hm(c,e):null,n=t.getAttribute("formmethod")||l.getAttribute("method")||bN,i=sE(t.getAttribute("formenctype"))||sE(l.getAttribute("enctype"))||xN,s=new FormData(l,t),!mhe()){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(wT(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=bN,a=null,i=xN,o=t}return s&&i==="text/plain"&&(o=s,s=void 0),{action:a,method:n.toLowerCase(),encType:i,formData:s,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function cO(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function fhe(t,e,n,a){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}_.${a}`:i.pathname=`${i.pathname}.${a}`:i.pathname==="/"?i.pathname=`_root.${a}`:e&&Hm(i.pathname,e)==="/"?i.pathname=`${e.replace(/\/$/,"")}/_root.${a}`:i.pathname=`${i.pathname.replace(/\/$/,"")}.${a}`,i}async function ghe(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 bhe(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 xhe(t,e,n){let a=await Promise.all(t.map(async i=>{let s=e.routes[i.route.id];if(s){let o=await ghe(s,n);return o.links?o.links():[]}return[]}));return She(a.flat(1).filter(bhe).filter(i=>i.rel==="stylesheet"||i.rel==="preload").map(i=>i.rel==="stylesheet"?{...i,rel:"prefetch",as:"style"}:{...i,rel:"prefetch"}))}function t6(t,e,n,a,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=a.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 yhe(t,e,{includeHydrateFallback:n}={}){return vhe(t.map(a=>{let i=e.routes[a.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 vhe(t){return[...new Set(t)]}function whe(t){let e={},n=Object.keys(t).sort();for(let a of n)e[a]=t[a];return e}function She(t,e){let n=new Set;return new Set(e),t.reduce((a,i)=>{let s=JSON.stringify(whe(i));return n.has(s)||(n.add(s),a.push({key:s,link:i})),a},[])}function pZ(){let t=y.useContext(Vy);return cO(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function _he(){let t=y.useContext(vT);return cO(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var dO=y.createContext(void 0);dO.displayName="FrameworkContext";function hZ(){let t=y.useContext(dO);return cO(t,"You must render this element inside a <HydratedRouter> element"),t}function khe(t,e){let n=y.useContext(dO),[a,i]=y.useState(!1),[s,o]=y.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:u,onTouchStart:m}=e,p=y.useRef(null);y.useEffect(()=>{if(t==="render"&&o(!0),t==="viewport"){let w=x=>{x.forEach(S=>{o(S.isIntersecting)})},b=new IntersectionObserver(w,{threshold:.5});return p.current&&b.observe(p.current),()=>{b.disconnect()}}},[t]),y.useEffect(()=>{if(a){let w=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(w)}}},[a]);let f=()=>{i(!0)},g=()=>{i(!1),o(!1)};return n?t!=="intent"?[s,p,{}]:[s,p,{onFocus:Jv(l,f),onBlur:Jv(c,g),onMouseEnter:Jv(d,f),onMouseLeave:Jv(u,g),onTouchStart:Jv(m,f)}]:[!1,p,{}]}function Jv(t,e){return n=>{t&&t(n),n.defaultPrevented||e(n)}}function Nhe({page:t,...e}){let{router:n}=pZ(),a=y.useMemo(()=>ZX(n.routes,t,n.basename),[n.routes,t,n.basename]);return a?y.createElement(Phe,{page:t,matches:a,...e}):null}function Che(t){let{manifest:e,routeModules:n}=hZ(),[a,i]=y.useState([]);return y.useEffect(()=>{let s=!1;return xhe(t,e,n).then(o=>{s||i(o)}),()=>{s=!0}},[t,e,n]),a}function Phe({page:t,matches:e,...n}){let a=bd(),{future:i,manifest:s,routeModules:o}=hZ(),{basename:l}=pZ(),{loaderData:c,matches:d}=_he(),u=y.useMemo(()=>t6(t,e,d,s,a,"data"),[t,e,d,s,a]),m=y.useMemo(()=>t6(t,e,d,s,a,"assets"),[t,e,d,s,a]),p=y.useMemo(()=>{if(t===a.pathname+a.search+a.hash)return[];let w=new Set,b=!1;if(e.forEach(S=>{let k=s.routes[S.route.id];!k||!k.hasLoader||(!u.some(C=>C.route.id===S.route.id)&&S.route.id in c&&o[S.route.id]?.shouldRevalidate||k.hasClientLoader?b=!0:w.add(S.route.id))}),w.size===0)return[];let x=fhe(t,l,i.unstable_trailingSlashAwareDataRequests,"data");return b&&w.size>0&&x.searchParams.set("_routes",e.filter(S=>w.has(S.route.id)).map(S=>S.route.id).join(",")),[x.pathname+x.search]},[l,i.unstable_trailingSlashAwareDataRequests,c,a,s,u,e,t,o]),f=y.useMemo(()=>yhe(m,s),[m,s]),g=Che(m);return y.createElement(y.Fragment,null,p.map(w=>y.createElement("link",{key:w,rel:"prefetch",as:"fetch",href:w,...n})),f.map(w=>y.createElement("link",{key:w,rel:"modulepreload",href:w,...n})),g.map(({key:w,link:b})=>y.createElement("link",{key:w,nonce:n.nonce,...b,crossOrigin:b.crossOrigin??n.crossOrigin})))}function The(...t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var Ahe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Ahe&&(window.__reactRouterVersion="7.13.0")}catch{}function jhe({basename:t,children:e,unstable_useTransitions:n,window:a}){let i=y.useRef();i.current==null&&(i.current=lpe({window:a,v5Compat:!0}));let s=i.current,[o,l]=y.useState({action:s.action,location:s.location}),c=y.useCallback(d=>{n===!1?l(d):y.startTransition(()=>l(d))},[n]);return y.useLayoutEffect(()=>s.listen(c),[s,c]),y.createElement(ahe,{basename:t,children:e,location:o.location,navigationType:o.action,navigator:s,unstable_useTransitions:n})}var fZ=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Es=y.forwardRef(function({onClick:e,discover:n="render",prefetch:a="none",relative:i,reloadDocument:s,replace:o,state:l,target:c,to:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},g){let{basename:w,unstable_useTransitions:b}=y.useContext(jl),x=typeof d=="string"&&fZ.test(d),S=nZ(d,w);d=S.to;let k=Hpe(d,{relative:i}),[C,P,T]=khe(a,f),A=Dhe(d,{replace:o,state:l,target:c,preventScrollReset:u,relative:i,viewTransition:m,unstable_defaultShouldRevalidate:p,unstable_useTransitions:b});function F(M){e&&e(M),M.defaultPrevented||A(M)}let _=y.createElement("a",{...f,...T,href:S.absoluteURL||k,onClick:S.isExternal||s?e:F,ref:The(g,P),target:c,"data-discover":!x&&n==="render"?"true":void 0});return C&&!x?y.createElement(y.Fragment,null,_,y.createElement(Nhe,{page:k})):_});Es.displayName="Link";var Vx=y.forwardRef(function({"aria-current":e="page",caseSensitive:n=!1,className:a="",end:i=!1,style:s,to:o,viewTransition:l,children:c,...d},u){let m=CS(o,{relative:d.relative}),p=bd(),f=y.useContext(vT),{navigator:g,basename:w}=y.useContext(jl),b=f!=null&&Ohe(m)&&l===!0,x=g.encodeLocation?g.encodeLocation(m).pathname:m.pathname,S=p.pathname,k=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;n||(S=S.toLowerCase(),k=k?k.toLowerCase():null,x=x.toLowerCase()),k&&w&&(k=Hm(k,w)||k);const C=x!=="/"&&x.endsWith("/")?x.length-1:x.length;let P=S===x||!i&&S.startsWith(x)&&S.charAt(C)==="/",T=k!=null&&(k===x||!i&&k.startsWith(x)&&k.charAt(x.length)==="/"),A={isActive:P,isPending:T,isTransitioning:b},F=P?e:void 0,_;typeof a=="function"?_=a(A):_=[a,P?"active":null,T?"pending":null,b?"transitioning":null].filter(Boolean).join(" ");let M=typeof s=="function"?s(A):s;return y.createElement(Es,{...d,"aria-current":F,className:_,ref:u,style:M,to:o,viewTransition:l},typeof c=="function"?c(A):c)});Vx.displayName="NavLink";var Mhe=y.forwardRef(({discover:t="render",fetcherKey:e,navigate:n,reloadDocument:a,replace:i,state:s,method:o=bN,action:l,onSubmit:c,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p,...f},g)=>{let{unstable_useTransitions:w}=y.useContext(jl),b=Rhe(),x=Ihe(l,{relative:d}),S=o.toLowerCase()==="get"?"get":"post",k=typeof l=="string"&&fZ.test(l),C=P=>{if(c&&c(P),P.defaultPrevented)return;P.preventDefault();let T=P.nativeEvent.submitter,A=T?.getAttribute("formmethod")||o,F=()=>b(T||P.currentTarget,{fetcherKey:e,method:A,navigate:n,replace:i,state:s,relative:d,preventScrollReset:u,viewTransition:m,unstable_defaultShouldRevalidate:p});w&&n!==!1?y.startTransition(()=>F()):F()};return y.createElement("form",{ref:g,method:S,action:x,onSubmit:a?c:C,...f,"data-discover":!k&&t==="render"?"true":void 0})});Mhe.displayName="Form";function Ehe(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function gZ(t){let e=y.useContext(Vy);return za(e,Ehe(t)),e}function Dhe(t,{target:e,replace:n,state:a,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l,unstable_useTransitions:c}={}){let d=ji(),u=bd(),m=CS(t,{relative:s});return y.useCallback(p=>{if(dhe(p,e)){p.preventDefault();let f=n!==void 0?n:Tw(u)===Tw(m),g=()=>d(t,{replace:f,state:a,preventScrollReset:i,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l});c?y.startTransition(()=>g()):g()}},[u,d,m,n,a,e,t,i,s,o,l,c])}function nb(t){vc(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=y.useRef(LF(t)),n=y.useRef(!1),a=bd(),i=y.useMemo(()=>uhe(a.search,n.current?null:e.current),[a.search]),s=ji(),o=y.useCallback((l,c)=>{const d=LF(typeof l=="function"?l(new URLSearchParams(i)):l);n.current=!0,s("?"+d,c)},[s,i]);return[i,o]}var Fhe=0,Lhe=()=>`__${String(++Fhe)}__`;function Rhe(){let{router:t}=gZ("useSubmit"),{basename:e}=y.useContext(jl),n=ehe(),a=t.fetch,i=t.navigate;return y.useCallback(async(s,o={})=>{let{action:l,method:c,encType:d,formData:u,body:m}=hhe(s,e);if(o.navigate===!1){let p=o.fetcherKey||Lhe();await a(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})},[a,i,e,n])}function Ihe(t,{relative:e}={}){let{basename:n}=y.useContext(jl),a=y.useContext(Ac);za(a,"useFormAction must be used inside a RouteContext");let[i]=a.matches.slice(-1),s={...CS(t||".",{relative:e})},o=bd();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:Em([n,s.pathname])),Tw(s)}function Ohe(t,{relative:e}={}){let n=y.useContext(aZ);za(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:a}=gZ("useViewTransitionState"),i=CS(t,{relative:e});if(!n.isTransitioning)return!1;let s=Hm(n.currentLocation.pathname,a)||n.currentLocation.pathname,o=Hm(n.nextLocation.pathname,a)||n.nextLocation.pathname;return QN(i.pathname,o)!=null||QN(i.pathname,s)!=null}var cc=BX();const zhe=Tc(cc);var rb=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(){}},Uhe={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Bhe=class{#t=Uhe;#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)}},ag=new Bhe;function Hhe(t){setTimeout(t,0)}var Tg=typeof window>"u"||"Deno"in globalThis;function Xs(){}function qhe(t,e){return typeof t=="function"?t(e):t}function RF(t){return typeof t=="number"&&t>=0&&t!==1/0}function bZ(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Nh(t,e){return typeof t=="function"?t(e):t}function ec(t,e){return typeof t=="function"?t(e):t}function n6(t,e){const{type:n="all",exact:a,fetchStatus:i,predicate:s,queryKey:o,stale:l}=t;if(o){if(a){if(e.queryHash!==uO(o,e.options))return!1}else if(!Aw(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 r6(t,e){const{exact:n,status:a,predicate:i,mutationKey:s}=t;if(s){if(!e.options.mutationKey)return!1;if(n){if(Ag(e.options.mutationKey)!==Ag(s))return!1}else if(!Aw(e.options.mutationKey,s))return!1}return!(a&&e.state.status!==a||i&&!i(e))}function uO(t,e){return(e?.queryKeyHashFn||Ag)(t)}function Ag(t){return JSON.stringify(t,(e,n)=>IF(n)?Object.keys(n).sort().reduce((a,i)=>(a[i]=n[i],a),{}):n)}function Aw(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>Aw(t[n],e[n])):!1}var $he=Object.prototype.hasOwnProperty;function mO(t,e,n=0){if(t===e)return t;if(n>500)return e;const a=a6(t)&&a6(e);if(!a&&!(IF(t)&&IF(e)))return e;const s=(a?t:Object.keys(t)).length,o=a?e:Object.keys(e),l=o.length,c=a?new Array(l):{};let d=0;for(let u=0;u<l;u++){const m=a?u:o[u],p=t[m],f=e[m];if(p===f){c[m]=p,(a?u<s:$he.call(t,m))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){c[m]=f;continue}const g=mO(p,f,n+1);c[m]=g,g===p&&d++}return s===l&&d===s?t:c}function jw(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 a6(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function IF(t){if(!i6(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!i6(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function i6(t){return Object.prototype.toString.call(t)==="[object Object]"}function Vhe(t){return new Promise(e=>{ag.setTimeout(e,t)})}function OF(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?mO(t,e):e}function Ghe(t,e,n=0){const a=[...t,e];return n&&a.length>n?a.slice(1):a}function Whe(t,e,n=0){const a=[e,...t];return n&&a.length>n?a.slice(0,-1):a}var pO=Symbol();function xZ(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===pO?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function hO(t,e){return typeof t=="function"?t(...e):!!t}function Khe(t,e,n){let a=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??=e(),a||(a=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),t}var Qhe=class extends rb{#t;#e;#n;constructor(){super(),this.#n=t=>{if(!Tg&&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"}},fO=new Qhe;function zF(){let t,e;const n=new Promise((i,s)=>{t=i,e=s});n.status="pending",n.catch(()=>{});function a(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{a({status:"fulfilled",value:i}),t(i)},n.reject=i=>{a({status:"rejected",reason:i}),e(i)},n}var Yhe=Hhe;function Xhe(){let t=[],e=0,n=l=>{l()},a=l=>{l()},i=Yhe;const s=l=>{e?t.push(l):i(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&i(()=>{a(()=>{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=>{a=l},setScheduler:l=>{i=l}}}var ai=Xhe(),Zhe=class extends rb{#t=!0;#e;#n;constructor(){super(),this.#n=t=>{if(!Tg&&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}},YN=new Zhe;function Jhe(t){return Math.min(1e3*2**t,3e4)}function yZ(t){return(t??"online")==="online"?YN.isOnline():!0}var UF=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function vZ(t){let e=!1,n=0,a;const i=zF(),s=()=>i.status!=="pending",o=w=>{if(!s()){const b=new UF(w);p(b),t.onCancel?.(b)}},l=()=>{e=!0},c=()=>{e=!1},d=()=>fO.isFocused()&&(t.networkMode==="always"||YN.isOnline())&&t.canRun(),u=()=>yZ(t.networkMode)&&t.canRun(),m=w=>{s()||(a?.(),i.resolve(w))},p=w=>{s()||(a?.(),i.reject(w))},f=()=>new Promise(w=>{a=b=>{(s()||d())&&w(b)},t.onPause?.()}).then(()=>{a=void 0,s()||t.onContinue?.()}),g=()=>{if(s())return;let w;const b=n===0?t.initialPromise:void 0;try{w=b??t.fn()}catch(x){w=Promise.reject(x)}Promise.resolve(w).then(m).catch(x=>{if(s())return;const S=t.retry??(Tg?0:3),k=t.retryDelay??Jhe,C=typeof k=="function"?k(n,x):k,P=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,x);if(e||!P){p(x);return}n++,t.onFail?.(n,x),Vhe(C).then(()=>d()?void 0:f()).then(()=>{e?p(x):g()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(a?.(),i),cancelRetry:l,continueRetry:c,canStart:u,start:()=>(u()?g():f().then(g),i)}}var wZ=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),RF(this.gcTime)&&(this.#t=ag.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Tg?1/0:300*1e3))}clearGcTimeout(){this.#t&&(ag.clearTimeout(this.#t),this.#t=void 0)}},efe=class extends wZ{#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=o6(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=o6(this.options);e.data!==void 0&&(this.setState(s6(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){const n=OF(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(Xs).catch(Xs):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(t=>ec(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===pO||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Nh(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:!bZ(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,a=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{const l=xZ(this.options,e),d=(()=>{const u={client:this.#a,queryKey:this.queryKey,meta:this.meta};return a(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 a(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=vZ({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof UF&&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 UF){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,...SZ(n.data,this.options),fetchMeta:t.meta??null};case"success":const a={...n,...s6(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#e=t.manual?a:void 0,a;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),ai.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function SZ(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:yZ(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function s6(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function o6(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,a=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var gO=class extends rb{constructor(t,e){super(),this.options=e,this.#t=t,this.#s=null,this.#o=zF(),this.bindMethods(),this.setOptions(e)}#t;#e=void 0;#n=void 0;#a=void 0;#r;#i;#o;#s;#h;#u;#m;#c;#d;#l;#p=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),l6(this.#e,this.options)?this.#f():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return BF(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return BF(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 ec(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&&!jw(this.options,e)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const a=this.hasListeners();a&&c6(this.#e,n,this.options,e)&&this.#f(),this.updateResult(),a&&(this.#e!==n||ec(this.options.enabled,this.#e)!==ec(e.enabled,this.#e)||Nh(this.options.staleTime,this.#e)!==Nh(e.staleTime,this.#e))&&this.#g();const i=this.#b();a&&(this.#e!==n||ec(this.options.enabled,this.#e)!==ec(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 nfe(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,a)=>(this.trackProp(a),e?.(a),a==="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,a))})}trackProp(t){this.#p.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(Xs)),e}#g(){this.#v();const t=Nh(this.options.staleTime,this.#e);if(Tg||this.#a.isStale||!RF(t))return;const n=bZ(this.#a.dataUpdatedAt,t)+1;this.#c=ag.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,!(Tg||ec(this.options.enabled,this.#e)===!1||!RF(this.#l)||this.#l===0)&&(this.#d=ag.setInterval(()=>{(this.options.refetchIntervalInBackground||fO.isFocused())&&this.#f()},this.#l))}#y(){this.#g(),this.#x(this.#b())}#v(){this.#c&&(ag.clearTimeout(this.#c),this.#c=void 0)}#w(){this.#d&&(ag.clearInterval(this.#d),this.#d=void 0)}createResult(t,e){const n=this.#e,a=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(),_=!F&&l6(t,e),M=F&&c6(t,n,e,a);(_||M)&&(u={...u,...SZ(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:w}=u;p=u.data;let b=!1;if(e.placeholderData!==void 0&&p===void 0&&w==="pending"){let F;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(F=i.data,b=!0):F=typeof e.placeholderData=="function"?e.placeholderData(this.#m?.state.data,this.#m):e.placeholderData,F!==void 0&&(w="success",p=OF(i?.data,F,e),m=!0)}if(e.select&&p!==void 0&&!b)if(i&&p===s?.data&&e.select===this.#h)p=this.#u;else try{this.#h=e.select,p=e.select(p),p=OF(i?.data,p,e),this.#u=p,this.#s=null}catch(F){this.#s=F}this.#s&&(f=this.#s,p=this.#u,g=Date.now(),w="error");const x=u.fetchStatus==="fetching",S=w==="pending",k=w==="error",C=S&&x,P=p!==void 0,A={status:w,fetchStatus:u.fetchStatus,isPending:S,isSuccess:w==="success",isError:k,isInitialLoading:C,isLoading:C,data:p,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:g,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:x,isRefetching:x&&!S,isLoadingError:k&&!P,isPaused:u.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:k&&P,isStale:bO(t,e),refetch:this.refetch,promise:this.#o,isEnabled:ec(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const F=A.data!==void 0,_=A.status==="error"&&!F,M=z=>{_?z.reject(A.error):F&&z.resolve(A.data)},H=()=>{const z=this.#o=A.promise=zF();M(z)},I=this.#o;switch(I.status){case"pending":t.queryHash===n.queryHash&&M(I);break;case"fulfilled":(_||A.data!==I.value)&&H();break;case"rejected":(!_||A.error!==I.reason)&&H();break}}return A}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),jw(e,t))return;this.#a=e;const n=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!this.#p.size)return!0;const s=new Set(i??this.#p);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){ai.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#a)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function tfe(t,e){return ec(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function l6(t,e){return tfe(t,e)||t.state.data!==void 0&&BF(t,e,e.refetchOnMount)}function BF(t,e,n){if(ec(e.enabled,t)!==!1&&Nh(e.staleTime,t)!=="static"){const a=typeof n=="function"?n(t):n;return a==="always"||a!==!1&&bO(t,e)}return!1}function c6(t,e,n,a){return(t!==e||ec(a.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&bO(t,n)}function bO(t,e){return ec(e.enabled,t)!==!1&&t.isStaleByTime(Nh(e.staleTime,t))}function nfe(t,e){return!jw(t.getCurrentResult(),e)}function d6(t){return{onFetch:(e,n)=>{const a=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=g=>{Khe(g,()=>e.signal,()=>u=!0)},p=xZ(e.options,e.fetchOptions),f=async(g,w,b)=>{if(u)return Promise.reject();if(w==null&&g.pages.length)return Promise.resolve(g);const S=(()=>{const T={client:e.client,queryKey:e.queryKey,pageParam:w,direction:b?"backward":"forward",meta:e.options.meta};return m(T),T})(),k=await p(S),{maxPages:C}=e.options,P=b?Whe:Ghe;return{pages:P(g.pages,k,C),pageParams:P(g.pageParams,w,C)}};if(i&&s.length){const g=i==="backward",w=g?rfe:u6,b={pages:s,pageParams:o},x=w(a,b);l=await f(b,x,g)}else{const g=t??s.length;do{const w=c===0?o[0]??a.initialPageParam:u6(a,l);if(c>0&&w==null)break;l=await f(l,w),c++}while(c<g)}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 u6(t,{pages:e,pageParams:n}){const a=e.length-1;return e.length>0?t.getNextPageParam(e[a],e,n[a],n):void 0}function rfe(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}var afe=class extends wZ{#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||_Z(),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=vZ({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 a=this.state.status==="pending",i=!this.#a.canStart();try{if(a)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),ai.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function _Z(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ife=class extends rb{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 a=new afe({client:t,mutationCache:this,mutationId:++this.#n,options:t.defaultMutationOptions(e),state:n});return this.add(a),a}add(t){this.#t.add(t);const e=Ck(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=Ck(t);if(typeof e=="string"){const n=this.#e.get(e);if(n)if(n.length>1){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}else n[0]===t&&this.#e.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){const e=Ck(t);if(typeof e=="string"){const a=this.#e.get(e)?.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){const e=Ck(t);return typeof e=="string"?this.#e.get(e)?.find(a=>a!==t&&a.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ai.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=>r6(e,n))}findAll(t={}){return this.getAll().filter(e=>r6(t,e))}notify(t){ai.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){const t=this.getAll().filter(e=>e.state.isPaused);return ai.batch(()=>Promise.all(t.map(e=>e.continue().catch(Xs))))}};function Ck(t){return t.options.scope?.id}var sfe=class extends rb{#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),jw(this.options,n)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&Ag(n.mutationKey)!==Ag(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??_Z();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){ai.batch(()=>{if(this.#a&&this.hasListeners()){const n=this.#e.variables,a=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,a,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(e.data,null,n,a,i)}catch(s){Promise.reject(s)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,n,a,i)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(void 0,e.error,n,a,i)}catch(s){Promise.reject(s)}}}this.listeners.forEach(n=>{n(this.#e)})})}};function m6(t,e){const n=new Set(e);return t.filter(a=>!n.has(a))}function ofe(t,e,n){const a=t.slice(0);return a[e]=n,a}var lfe=class extends rb{#t;#e;#n;#a;#r;#i;#o;#s;#h;#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,ai.batch(()=>{const n=this.#r,a=this.#d(this.#n);a.forEach(u=>u.observer.setOptions(u.defaultedQueryOptions));const i=a.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||!jw(u,p)});!c&&!d||(c&&(this.#u=a,this.#r=i),this.#e=s,this.hasListeners()&&(c&&(m6(n,i).forEach(u=>{u.destroy()}),m6(i,n).forEach(u=>{u.subscribe(m=>{this.#l(u,m)})})),this.#p()))})}getCurrentResult(){return this.#e}getQueries(){return this.#r.map(t=>t.getCurrentQuery())}getObservers(){return this.#r}getOptimisticResult(t,e){const n=this.#d(t),a=n.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions)),i=n.map(s=>s.defaultedQueryOptions.queryHash);return[a,s=>this.#c(s??a,e,i),()=>this.#m(a,n)]}#m(t,e){return e.map((n,a)=>{const i=t[a];return n.defaultedQueryOptions.notifyOnChangeProps?i:n.observer.trackResult(i,s=>{e.forEach(o=>{o.observer.trackProp(s)})})})}#c(t,e,n){if(e){const a=this.#h,i=n!==void 0&&a!==void 0&&(a.length!==n.length||n.some((s,o)=>s!==a[o]));return(!this.#i||this.#e!==this.#s||i||e!==this.#o)&&(this.#o=e,this.#s=this.#e,n!==void 0&&(this.#h=n),this.#i=mO(this.#i,e(t))),this.#i}return t}#d(t){const e=new Map;this.#r.forEach(a=>{const i=a.options.queryHash;if(!i)return;const s=e.get(i);s?s.push(a):e.set(i,[a])});const n=[];return t.forEach(a=>{const i=this.#t.defaultQueryOptions(a),o=e.get(i.queryHash)?.shift()??new gO(this.#t,i);n.push({defaultedQueryOptions:i,observer:o})}),n}#l(t,e){const n=this.#r.indexOf(t);n!==-1&&(this.#e=ofe(this.#e,n,e),this.#p())}#p(){if(this.hasListeners()){const t=this.#i,e=this.#m(this.#e,this.#u),n=this.#c(e,this.#a?.combine);t!==n&&ai.batch(()=>{this.listeners.forEach(a=>{a(this.#e)})})}}},cfe=class extends rb{constructor(t={}){super(),this.config=t,this.#t=new Map}#t;build(t,e,n){const a=e.queryKey,i=e.queryHash??uO(a,e);let s=this.get(i);return s||(s=new efe({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(e),state:n,defaultOptions:t.getQueryDefaults(a)}),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(){ai.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=>n6(e,n))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter(n=>n6(t,n)):e}notify(t){ai.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){ai.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){ai.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},dfe=class{#t;#e;#n;#a;#r;#i;#o;#s;constructor(t={}){this.#t=t.queryCache||new cfe,this.#e=t.mutationCache||new ife,this.#n=t.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=fO.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=YN.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),a=n.state.data;return a===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(Nh(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(a))}getQueriesData(t){return this.#t.findAll(t).map(({queryKey:e,state:n})=>{const a=n.data;return[e,a]})}setQueryData(t,e,n){const a=this.defaultQueryOptions({queryKey:t}),s=this.#t.get(a.queryHash)?.state.data,o=qhe(e,s);if(o!==void 0)return this.#t.build(this,a).setData(o,{...n,manual:!0})}setQueriesData(t,e,n){return ai.batch(()=>this.#t.findAll(t).map(({queryKey:a})=>[a,this.setQueryData(a,e,n)]))}getQueryState(t){const e=this.defaultQueryOptions({queryKey:t});return this.#t.get(e.queryHash)?.state}removeQueries(t){const e=this.#t;ai.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=this.#t;return ai.batch(()=>(n.findAll(t).forEach(a=>{a.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},a=ai.batch(()=>this.#t.findAll(t).map(i=>i.cancel(n)));return Promise.all(a).then(Xs).catch(Xs)}invalidateQueries(t,e={}){return ai.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},a=ai.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(Xs)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(a).then(Xs)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=this.#t.build(this,e);return n.isStaleByTime(Nh(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Xs).catch(Xs)}fetchInfiniteQuery(t){return t.behavior=d6(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Xs).catch(Xs)}ensureInfiniteQueryData(t){return t.behavior=d6(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return YN.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(Ag(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#a.values()],n={};return e.forEach(a=>{Aw(t,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(t,e){this.#r.set(Ag(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#r.values()],n={};return e.forEach(a=>{Aw(t,a.mutationKey)&&Object.assign(n,a.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=uO(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===pO&&(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()}},kZ=y.createContext(void 0),tn=t=>{const e=y.useContext(kZ);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},ufe=({client:t,children:e})=>(y.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),r.jsx(kZ.Provider,{value:t,children:e})),NZ=y.createContext(!1),CZ=()=>y.useContext(NZ);NZ.Provider;function mfe(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var pfe=y.createContext(mfe()),PZ=()=>y.useContext(pfe),TZ=(t,e,n)=>{const a=n?.state.error&&typeof t.throwOnError=="function"?hO(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||a)&&(e.isReset()||(t.retryOnMount=!1))},AZ=t=>{y.useEffect(()=>{t.clearReset()},[t])},jZ=({result:t,errorResetBoundary:e,throwOnError:n,query:a,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&a&&(i&&t.data===void 0||hO(n,[t.error,a])),MZ=t=>{if(t.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),a=t.staleTime;t.staleTime=typeof a=="function"?(...i)=>n(a(...i)):n(a),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},EZ=(t,e)=>t.isLoading&&t.isFetching&&!e,HF=(t,e)=>t?.suspense&&e.isPending,XN=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function rf({queries:t,...e},n){const a=tn(),i=CZ(),s=PZ(),o=y.useMemo(()=>t.map(w=>{const b=a.defaultQueryOptions(w);return b._optimisticResults=i?"isRestoring":"optimistic",b}),[t,a,i]);o.forEach(w=>{MZ(w);const b=a.getQueryCache().get(w.queryHash);TZ(w,s,b)}),AZ(s);const[l]=y.useState(()=>new lfe(a,o,e)),[c,d,u]=l.getOptimisticResult(o,e.combine),m=!i&&e.subscribed!==!1;y.useSyncExternalStore(y.useCallback(w=>m?l.subscribe(ai.batchCalls(w)):Xs,[l,m]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),y.useEffect(()=>{l.setQueries(o,e)},[o,e,l]);const f=c.some((w,b)=>HF(o[b],w))?c.flatMap((w,b)=>{const x=o[b];if(x){const S=new gO(a,x);if(HF(x,w))return XN(x,S,s);EZ(w,i)&&XN(x,S,s)}return[]}):[];if(f.length>0)throw Promise.all(f);const g=c.find((w,b)=>{const x=o[b];return x&&jZ({result:w,errorResetBoundary:s,throwOnError:x.throwOnError,query:a.getQueryCache().get(x.queryHash),suspense:x.suspense})});if(g?.error)throw g.error;return d(u())}function hfe(t,e,n){const a=CZ(),i=PZ(),s=tn(),o=s.defaultQueryOptions(t);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=s.getQueryCache().get(o.queryHash);o._optimisticResults=a?"isRestoring":"optimistic",MZ(o),TZ(o,i,l),AZ(i);const c=!s.getQueryCache().get(o.queryHash),[d]=y.useState(()=>new e(s,o)),u=d.getOptimisticResult(o),m=!a&&t.subscribed!==!1;if(y.useSyncExternalStore(y.useCallback(p=>{const f=m?d.subscribe(ai.batchCalls(p)):Xs;return d.updateResult(),f},[d,m]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),y.useEffect(()=>{d.setOptions(o)},[o,d]),HF(o,u))throw XN(o,d,i);if(jZ({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&&!Tg&&EZ(u,a)&&(c?XN(o,d,i):l?.promise)?.catch(Xs).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?u:d.trackResult(u)}function Xe(t,e){return hfe(t,gO)}function lt(t,e){const n=tn(),[a]=y.useState(()=>new sfe(n,t));y.useEffect(()=>{a.setOptions(t)},[a,t]);const i=y.useSyncExternalStore(y.useCallback(o=>a.subscribe(ai.batchCalls(o)),[a]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),s=y.useCallback((o,l)=>{a.mutate(o,l).catch(Xs)},[a]);if(i.error&&hO(a.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:s,mutateAsync:i.mutate}}const ffe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),gfe=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,a)=>a?a.toUpperCase():n.toLowerCase()),p6=t=>{const e=gfe(t);return e.charAt(0).toUpperCase()+e.slice(1)},DZ=(...t)=>t.filter((e,n,a)=>!!e&&e.trim()!==""&&a.indexOf(e)===n).join(" ").trim(),bfe=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var xfe={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 yfe=y.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:s,iconNode:o,...l},c)=>y.createElement("svg",{ref:c,...xfe,width:e,height:e,stroke:t,strokeWidth:a?Number(n)*24/Number(e):n,className:DZ("lucide",i),...!s&&!bfe(l)&&{"aria-hidden":"true"},...l},[...o.map(([d,u])=>y.createElement(d,u)),...Array.isArray(s)?s:[s]]));const gt=(t,e)=>{const n=y.forwardRef(({className:a,...i},s)=>y.createElement(yfe,{ref:s,iconNode:e,className:DZ(`lucide-${ffe(p6(t))}`,`lucide-${t}`,a),...i}));return n.displayName=p6(t),n};const vfe=[["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"}]],wfe=gt("air-vent",vfe);const Sfe=[["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"}]],eo=gt("archive",Sfe);const _fe=[["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"}]],kfe=gt("arrow-down-wide-narrow",_fe);const Nfe=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],qh=gt("arrow-down",Nfe);const Cfe=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ST=gt("arrow-left",Cfe);const Pfe=[["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"}]],qF=gt("arrow-right-left",Pfe);const Tfe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],ZN=gt("arrow-right",Tfe);const Afe=[["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"}]],_T=gt("arrow-up-down",Afe);const jfe=[["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"}]],Mfe=gt("arrow-up-narrow-wide",jfe);const Efe=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],qm=gt("arrow-up",Efe);const Dfe=[["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"}]],Ffe=gt("beaker",Dfe);const Lfe=[["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"}]],FZ=gt("bell-off",Lfe);const Rfe=[["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"}]],Ch=gt("bell",Rfe);const Ife=[["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"}]],Ofe=gt("bold",Ife);const zfe=[["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"}]],Ufe=gt("book",zfe);const Bfe=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Hfe=gt("bookmark",Bfe);const qfe=[["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"}]],Si=gt("box",qfe);const $fe=[["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"}]],LZ=gt("briefcase",$fe);const Vfe=[["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"}]],gy=gt("bug",Vfe);const Gfe=[["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"}]],xO=gt("cable",Gfe);const Wfe=[["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"}]],Kfe=gt("calculator",Wfe);const Qfe=[["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"}]],Yfe=gt("calendar-days",Qfe);const Xfe=[["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"}]],Zfe=gt("calendar-plus",Xfe);const Jfe=[["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"}]],wa=gt("calendar",Jfe);const ege=[["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"}]],by=gt("camera",ege);const tge=[["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"}]],RZ=gt("chart-column",tge);const nge=[["path",{d:"M5 21v-6",key:"1hz6c0"}],["path",{d:"M12 21V3",key:"1lcnhd"}],["path",{d:"M19 21V9",key:"unv183"}]],rge=gt("chart-no-axes-column",nge);const age=[["path",{d:"M6 5h12",key:"fvfigv"}],["path",{d:"M4 12h10",key:"oujl3d"}],["path",{d:"M12 19h8",key:"baeox8"}]],ige=gt("chart-no-axes-gantt",age);const sge=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ar=gt("check",sge);const oge=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ln=gt("chevron-down",oge);const lge=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],qa=gt("chevron-right",lge);const cge=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Xo=gt("chevron-left",cge);const dge=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Zo=gt("chevron-up",dge);const uge=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],yO=gt("chevrons-left",uge);const mge=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],vO=gt("chevrons-right",mge);const pge=[["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"}]],Ha=gt("circle-alert",pge);const hge=[["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"}]],oE=gt("circle-arrow-up",hge);const fge=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],xr=gt("circle-check-big",fge);const gge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],yl=gt("circle-check",gge);const bge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],xge=gt("circle-dot",bge);const yge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],vge=gt("circle-minus",yge);const wge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Sge=gt("circle-stop",wge);const _ge=[["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"}]],$r=gt("circle-x",_ge);const kge=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Mw=gt("circle",kge);const Nge=[["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"}]],Cge=gt("clipboard-list",Nge);const Pge=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Zn=gt("clock",Pge);const Tge=[["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"}]],$F=gt("cloud-off",Tge);const Age=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],$h=gt("cloud",Age);const jge=[["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"}]],Mge=gt("code-xml",jge);const Ege=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Ky=gt("code",Ege);const Dge=[["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"}]],Fge=gt("coffee",Dge);const Lge=[["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"}]],Rge=gt("coins",Lge);const Ige=[["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"}]],uu=gt("cog",Ige);const Oge=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],zge=gt("columns-2",Oge);const Uge=[["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"}]],Bge=gt("compass",Uge);const Hge=[["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"}]],Ti=gt("copy",Hge);const qge=[["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"}]],F0=gt("cpu",qge);const $ge=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Vge=gt("credit-card",$ge);const Gge=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]],Wge=gt("cylinder",Gge);const Kge=[["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"}]],dc=gt("database",Kge);const Qge=[["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"}]],Yge=gt("disc-3",Qge);const Xge=[["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"}]],JN=gt("dollar-sign",Xge);const Zge=[["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"}]],Jge=gt("door-closed",Zge);const ebe=[["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"}]],tbe=gt("door-open",ebe);const nbe=[["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"}]],Zr=gt("download",nbe);const rbe=[["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"}]],kT=gt("droplet",rbe);const abe=[["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"}]],wO=gt("droplets",abe);const ibe=[["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"}]],vm=gt("ellipsis-vertical",ibe);const sbe=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],obe=gt("ellipsis",sbe);const lbe=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]],lE=gt("equal",lbe);const cbe=[["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"}]],SO=gt("eraser",cbe);const dbe=[["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"}]],zr=gt("external-link",dbe);const ube=[["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"}]],ab=gt("eye-off",ube);const mbe=[["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"}]],Cl=gt("eye",mbe);const pbe=[["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"}]],IZ=gt("fan",pbe);const hbe=[["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"}]],Ph=gt("file-box",hbe);const fbe=[["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"}]],eC=gt("file-code",fbe);const gbe=[["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"}]],bbe=gt("file-exclamation-point",gbe);const xbe=[["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"}]],tC=gt("file-spreadsheet",xbe);const ybe=[["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"}]],Rs=gt("file-text",ybe);const vbe=[["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"}]],NT=gt("file",vbe);const wbe=[["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"}]],Th=gt("film",wbe);const Sbe=[["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"}]],pm=gt("flame",Sbe);const _be=[["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"}]],kbe=gt("folder-archive",_be);const Nbe=[["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"}]],to=gt("folder-kanban",Nbe);const Cbe=[["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"}]],Pl=gt("folder-open",Cbe);const Pbe=[["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"}]],Tbe=gt("folder-plus",Pbe);const Abe=[["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"}]],nC=gt("folder-symlink",Abe);const jbe=[["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"}]],Mbe=gt("folder-tree",jbe);const Ebe=[["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"}]],OZ=gt("folder",Ebe);const Dbe=[["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"}]],Fbe=gt("fullscreen",Dbe);const Lbe=[["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"}]],PS=gt("funnel",Lbe);const Rbe=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],TS=gt("gauge",Rbe);const Ibe=[["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"}]],Obe=gt("gift",Ibe);const zbe=[["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"}]],zZ=gt("git-branch",zbe);const Ube=[["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"}]],ey=gt("git-compare",Ube);const Bbe=[["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"}]],VF=gt("github",Bbe);const Hbe=[["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"}]],Js=gt("globe",Hbe);const qbe=[["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"}]],Ah=gt("grip-vertical",qbe);const $be=[["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"}]],Vbe=gt("group",$be);const Gbe=[["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"}]],UZ=gt("hand",Gbe);const Wbe=[["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"}]],ib=gt("hard-drive",Wbe);const Kbe=[["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"}]],Qbe=gt("hash",Kbe);const Ybe=[["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"}]],Xbe=gt("headphones",Ybe);const Zbe=[["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"}]],Jbe=gt("heart",Zbe);const exe=[["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"}]],Vh=gt("history",exe);const txe=[["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"}]],AS=gt("house",txe);const nxe=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]],rxe=gt("image-off",nxe);const axe=[["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"}]],mu=gt("image",axe);const ixe=[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",key:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]],sxe=gt("images",ixe);const oxe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],_i=gt("info",oxe);const lxe=[["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"}]],cxe=gt("italic",lxe);const dxe=[["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"}]],bo=gt("key",dxe);const uxe=[["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"}]],GF=gt("keyboard",uxe);const mxe=[["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"}]],ca=gt("layers",mxe);const pxe=[["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"}]],jS=gt("layout-grid",pxe);const hxe=[["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"}]],fxe=gt("link-2-off",hxe);const gxe=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],jh=gt("link-2",gxe);const bxe=[["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"}]],Qy=gt("link",bxe);const xxe=[["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"}]],Ew=gt("list-ordered",xxe);const yxe=[["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"}]],WF=gt("list-todo",yxe);const vxe=[["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"}]],MS=gt("list",vxe);const wxe=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ft=gt("loader-circle",wxe);const Sxe=[["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"}]],X0=gt("lock-open",Sxe);const _xe=[["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"}]],rc=gt("lock",_xe);const kxe=[["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"}]],Z0=gt("log-in",kxe);const Nxe=[["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"}]],ty=gt("log-out",Nxe);const Cxe=[["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"}]],$m=gt("mail",Cxe);const Pxe=[["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"}]],Txe=gt("map",Pxe);const Axe=[["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"}]],CT=gt("maximize-2",Axe);const jxe=[["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"}]],Mxe=gt("maximize",jxe);const Exe=[["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"}]],Dxe=gt("memory-stick",Exe);const Fxe=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Lxe=gt("menu",Fxe);const Rxe=[["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"}]],_O=gt("minimize-2",Rxe);const Ixe=[["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"}]],BZ=gt("minimize",Ixe);const Oxe=[["path",{d:"M5 12h14",key:"1ays0h"}]],rC=gt("minus",Oxe);const zxe=[["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"}]],kO=gt("monitor",zxe);const Uxe=[["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"}]],aC=gt("moon",Uxe);const Bxe=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Hxe=gt("move-right",Bxe);const qxe=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]],$xe=gt("move-vertical",qxe);const Vxe=[["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"}]],KF=gt("music",Vxe);const Gxe=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 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 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],Wxe=gt("package-check",Gxe);const Kxe=[["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"}]],Vr=gt("package",Kxe);const Qxe=[["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"}]],ES=gt("palette",Qxe);const Yxe=[["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"}]],DS=gt("pause",Yxe);const Xxe=[["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"}]],jg=gt("pen-line",Xxe);const Zxe=[["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"}]],uc=gt("pen",Zxe);const Jxe=[["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"}]],mi=gt("pencil",Jxe);const eye=[["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"}]],tye=gt("phone",eye);const nye=[["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"}]],hs=gt("play",nye);const rye=[["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"}]],hc=gt("plug",rye);const aye=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],er=gt("plus",aye);const iye=[["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"}]],FS=gt("power-off",iye);const sye=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],_u=gt("power",sye);const oye=[["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"}]],hr=gt("printer",oye);const lye=[["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"}]],HZ=gt("qr-code",lye);const cye=[["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"}]],NO=gt("radio",cye);const dye=[["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"}]],tr=gt("refresh-cw",dye);const uye=[["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"}]],fs=gt("rotate-ccw",uye);const mye=[["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"}]],Dw=gt("rotate-cw",mye);const pye=[["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"}]],hye=gt("ruler",pye);const fye=[["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"}]],ds=gt("save",fye);const gye=[["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"}]],qZ=gt("scale",gye);const bye=[["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"}]],$Z=gt("scan-eye",bye);const xye=[["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"}]],iC=gt("scan-search",xye);const yye=[["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"}]],vye=gt("scissors",yye);const wye=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],yr=gt("search",wye);const Sye=[["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"}]],LS=gt("send",Sye);const _ye=[["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"}]],Gf=gt("server",_ye);const kye=[["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"}]],pu=gt("settings-2",kye);const Nye=[["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"}]],xy=gt("settings",Nye);const Cye=[["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"}]],Pye=gt("shield-alert",Cye);const Tye=[["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"}]],Fw=gt("shield-check",Tye);const Aye=[["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"}]],QF=gt("shield-off",Aye);const jye=[["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"}]],hl=gt("shield",jye);const Mye=[["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"}]],sb=gt("shopping-cart",Mye);const Eye=[["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"}]],VZ=gt("signal",Eye);const Dye=[["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"}]],Fye=gt("skip-back",Dye);const Lye=[["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"}]],PT=gt("skip-forward",Lye);const Rye=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],Iye=gt("sliders-horizontal",Rye);const Oye=[["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"}]],h6=gt("sliders-vertical",Oye);const zye=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],YF=gt("smartphone",zye);const Uye=[["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"}]],Bye=gt("snail",Uye);const Hye=[["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"}]],f6=gt("snowflake",Hye);const qye=[["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"}]],Mg=gt("sparkles",qye);const $ye=[["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"}]],gs=gt("square-check-big",$ye);const Vye=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]],Gye=gt("square-minus",Vye);const Wye=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ro=gt("square",Wye);const Kye=[["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"}]],Eg=gt("star",Kye);const Qye=[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]],GZ=gt("stethoscope",Qye);const Yye=[["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"}]],WZ=gt("sticky-note",Yye);const Xye=[["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"}]],g6=gt("sun",Xye);const Zye=[["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"}]],Jye=gt("table-properties",Zye);const eve=[["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"}]],Vm=gt("tag",eve);const tve=[["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"}]],KZ=gt("target",tve);const nve=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],QZ=gt("terminal",nve);const rve=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],ave=gt("text-align-center",rve);const ive=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],sve=gt("text-align-end",ive);const ove=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],lve=gt("text-align-start",ove);const cve=[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]],RS=gt("thermometer",cve);const dve=[["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"}]],Zd=gt("timer",dve);const uve=[["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"}]],en=gt("trash-2",uve);const mve=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],IS=gt("trending-down",mve);const pve=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],sC=gt("trending-up",pve);const hve=[["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"}]],Nn=gt("triangle-alert",hve);const fve=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],gve=gt("underline",fve);const bve=[["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"}]],ou=gt("unlink",bve);const xve=[["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"}]],_a=gt("upload",xve);const yve=[["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"}]],Gm=gt("user",yve);const vve=[["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"}]],bm=gt("users",vve);const wve=[["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"}]],oC=gt("video",wve);const Sve=[["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"}]],_ve=gt("volume-2",Sve);const kve=[["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"}]],Nve=gt("volume-x",kve);const Cve=[["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"}]],YZ=gt("wand-sparkles",Cve);const Pve=[["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"}]],XZ=gt("weight",Pve);const Tve=[["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"}]],hu=gt("wifi-off",Tve);const Ave=[["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"}]],Mh=gt("wifi",Ave);const jve=[["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"}]],ZZ=gt("wind",jve);const Mve=[["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"}]],Gh=gt("wrench",Mve);const Eve=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Vt=gt("x",Eve);const Dve=[["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"}]],CO=gt("zoom-in",Dve);const Fve=[["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"}]],wc=gt("zap",Fve);const Lve=[["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"}]],PO=gt("zoom-out",Lve),kn="/api/v1";class rs extends Error{status;code;constructor(e,n,a=null){super(e),this.name="ApiError",this.status=n,this.code=a}}let Sn=sessionStorage.getItem("auth_token")??localStorage.getItem("auth_token");function eh(t,e="session"){Sn=t;try{t?sessionStorage.setItem("auth_token",t):sessionStorage.removeItem("auth_token")}catch(n){console.warn("setAuthToken: sessionStorage unavailable, token kept in-memory only",n)}try{t?e==="persistent"&&localStorage.setItem("auth_token",t):localStorage.removeItem("auth_token")}catch(n){console.warn("setAuthToken: localStorage operation failed",n)}}function Wm(){return Sn}let lC=null;function b6(t){lC=t}function JZ(){return lC}function La(t){if(!lC)return t;const e=t.includes("?")?"&":"?";return`${t}${e}token=${encodeURIComponent(lC)}`}function Wf(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}function Rve(t){const e=t.replace(/[/\\?#]/g,"_");return e.toLowerCase().endsWith(".3mf")?e:`${e}.3mf`}async function Pe(t,e={}){const n={"Content-Type":"application/json",...e.headers};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}${t}`,{...e,cache:"no-store",credentials:"include",headers:n});if(!a.ok){const o=(await a.json().catch(()=>({}))).detail;let l,c=null;throw typeof o=="string"?l=o:Array.isArray(o)?l=o.map(u=>(u.msg??"").replace(/^Value error,\s*/i,"")).filter(Boolean).join("; ")||JSON.stringify(o)||`HTTP ${a.status}`:o&&typeof o=="object"?(c=typeof o.code=="string"?o.code:null,l=typeof o.message=="string"?o.message:`HTTP ${a.status}`):l=`HTTP ${a.status}`,a.status===401&&["Could not validate credentials","Token has expired","User not found or inactive","Invalid API key","API key has expired"].some(u=>l.includes(u))&&eh(null),new rs(l,a.status,c)}const i=a.headers.get("content-length");if(!(a.status===204||i==="0"))return await a.json()}const ae={getAuthStatus:()=>Pe("/auth/status"),setupAuth:t=>Pe("/auth/setup",{method:"POST",body:JSON.stringify(t)}),login:t=>Pe("/auth/login",{method:"POST",body:JSON.stringify(t)}),logout:()=>Pe("/auth/logout",{method:"POST"}),getCurrentUser:()=>Pe("/auth/me"),disableAuth:()=>Pe("/auth/disable",{method:"POST"}),testSMTP:t=>Pe("/auth/smtp/test",{method:"POST",body:JSON.stringify(t)}),getSMTPSettings:()=>Pe("/auth/smtp"),saveSMTPSettings:t=>Pe("/auth/smtp",{method:"POST",body:JSON.stringify(t)}),enableAdvancedAuth:()=>Pe("/auth/advanced-auth/enable",{method:"POST"}),disableAdvancedAuth:()=>Pe("/auth/advanced-auth/disable",{method:"POST"}),getAdvancedAuthStatus:()=>Pe("/auth/advanced-auth/status"),getLDAPStatus:()=>Pe("/auth/ldap/status"),getEncryptionStatus:()=>Pe("/auth/encryption-status"),testLDAP:()=>Pe("/auth/ldap/test",{method:"POST"}),searchLDAPDirectory:t=>Pe(`/auth/ldap/search?q=${encodeURIComponent(t)}`),provisionLDAPUser:t=>Pe("/auth/ldap/provision",{method:"POST",body:JSON.stringify({username:t})}),forgotPassword:t=>Pe("/auth/forgot-password",{method:"POST",body:JSON.stringify(t)}),forgotPasswordConfirm:(t,e)=>Pe("/auth/forgot-password/confirm",{method:"POST",body:JSON.stringify({token:t,new_password:e})}),resetUserPassword:t=>Pe("/auth/reset-password",{method:"POST",body:JSON.stringify(t)}),get2FAStatus:()=>Pe("/auth/2fa/status"),setupTOTP:()=>Pe("/auth/2fa/totp/setup",{method:"POST"}),enableTOTP:t=>Pe("/auth/2fa/totp/enable",{method:"POST",body:JSON.stringify({code:t})}),disableTOTP:t=>Pe("/auth/2fa/totp/disable",{method:"POST",body:JSON.stringify({code:t})}),regenerateBackupCodes:t=>Pe("/auth/2fa/totp/regenerate-backup-codes",{method:"POST",body:JSON.stringify({code:t})}),enableEmailOTP:()=>Pe("/auth/2fa/email/enable",{method:"POST"}),confirmEnableEmailOTP:(t,e)=>Pe("/auth/2fa/email/enable/confirm",{method:"POST",body:JSON.stringify({setup_token:t,code:e})}),disableEmailOTP:t=>Pe("/auth/2fa/email/disable",{method:"POST",body:JSON.stringify({password:t})}),sendEmailOTP:t=>Pe("/auth/2fa/email/send",{method:"POST",body:JSON.stringify({pre_auth_token:t})}),verify2FA:t=>Pe("/auth/2fa/verify",{method:"POST",body:JSON.stringify(t)}),admin2FADisable:t=>Pe(`/auth/2fa/admin/${t}`,{method:"DELETE"}),getOIDCProviders:()=>Pe("/auth/oidc/providers"),getOIDCProvidersAll:()=>Pe("/auth/oidc/providers/all"),createOIDCProvider:t=>Pe("/auth/oidc/providers",{method:"POST",body:JSON.stringify(t)}),updateOIDCProvider:(t,e)=>Pe(`/auth/oidc/providers/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteOIDCProvider:t=>Pe(`/auth/oidc/providers/${t}`,{method:"DELETE"}),oidcProviderIconUrl:t=>`/api/v1/auth/oidc/providers/${t}/icon`,deleteOIDCProviderIcon:t=>Pe(`/auth/oidc/providers/${t}/icon`,{method:"DELETE"}),refreshOIDCProviderIcon:t=>Pe(`/auth/oidc/providers/${t}/icon/refresh`,{method:"POST"}),getOIDCAuthorizeUrl:t=>Pe(`/auth/oidc/authorize/${t}`),exchangeOIDCToken:t=>Pe("/auth/oidc/exchange",{method:"POST",body:JSON.stringify({oidc_token:t})}),getOIDCLinks:()=>Pe("/auth/oidc/links"),deleteOIDCLink:t=>Pe(`/auth/oidc/links/${t}`,{method:"DELETE"}),getUsers:()=>Pe("/users/"),getUser:t=>Pe(`/users/${t}`),createUser:t=>Pe("/users/",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>Pe(`/users/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:(t,e=!1)=>Pe(`/users/${t}?delete_items=${e}`,{method:"DELETE"}),getUserItemsCount:t=>Pe(`/users/${t}/items-count`),changePassword:(t,e)=>Pe("/users/me/change-password",{method:"POST",body:JSON.stringify({current_password:t,new_password:e})}),getUserEmailPreferences:()=>Pe("/user-notifications/preferences"),updateUserEmailPreferences:t=>Pe("/user-notifications/preferences",{method:"PUT",body:JSON.stringify(t)}),getPermissions:()=>Pe("/groups/permissions"),getGroups:()=>Pe("/groups/"),getGroup:t=>Pe(`/groups/${t}`),createGroup:t=>Pe("/groups/",{method:"POST",body:JSON.stringify(t)}),updateGroup:(t,e)=>Pe(`/groups/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteGroup:t=>Pe(`/groups/${t}`,{method:"DELETE"}),addUserToGroup:(t,e)=>Pe(`/groups/${t}/users/${e}`,{method:"POST"}),removeUserFromGroup:(t,e)=>Pe(`/groups/${t}/users/${e}`,{method:"DELETE"}),getPrinters:()=>Pe("/printers/"),getPrinter:t=>Pe(`/printers/${t}`),createPrinter:t=>Pe("/printers/",{method:"POST",body:JSON.stringify(t)}),updatePrinter:(t,e)=>Pe(`/printers/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deletePrinter:(t,e=!0)=>Pe(`/printers/${t}?delete_archives=${e}`,{method:"DELETE"}),getDeveloperModeWarnings:()=>Pe("/printers/developer-mode-warnings"),getAvailableFilaments:(t,e)=>{const n=new URLSearchParams({model:t});return e&&n.set("location",e),Pe(`/printers/available-filaments?${n}`)},getPrinterStatus:t=>Pe(`/printers/${t}/status`),refreshPrinterStatus:t=>Pe(`/printers/${t}/refresh-status`,{method:"POST"}),connectPrinter:t=>Pe(`/printers/${t}/connect`,{method:"POST"}),disconnectPrinter:t=>Pe(`/printers/${t}/disconnect`,{method:"POST"}),testExternalCamera:(t,e,n)=>Pe(`/printers/${t}/camera/external/test?url=${encodeURIComponent(e)}&camera_type=${encodeURIComponent(n)}`,{method:"POST"}),stopPrint:t=>Pe(`/printers/${t}/print/stop`,{method:"POST"}),pausePrint:t=>Pe(`/printers/${t}/print/pause`,{method:"POST"}),resumePrint:t=>Pe(`/printers/${t}/print/resume`,{method:"POST"}),clearPlate:t=>Pe(`/printers/${t}/clear-plate`,{method:"POST"}),getCurrentPrintUser:t=>Pe(`/printers/${t}/current-print-user`),setPrintSpeed:(t,e)=>Pe(`/printers/${t}/print-speed?mode=${e}`,{method:"POST"}),setAirductMode:(t,e)=>Pe(`/printers/${t}/airduct-mode?mode=${e}`,{method:"POST"}),bedJog:(t,e,n=!1)=>Pe(`/printers/${t}/bed-jog?distance=${e}&force=${n}`,{method:"POST"}),homeAxes:(t,e="z")=>Pe(`/printers/${t}/home-axes?axes=${e}`,{method:"POST"}),setChamberLight:(t,e)=>Pe(`/printers/${t}/chamber-light?on=${e}`,{method:"POST"}),startDrying:(t,e,n,a,i="",s=!1)=>Pe(`/printers/${t}/drying/start?ams_id=${e}&temp=${n}&duration=${a}&filament=${encodeURIComponent(i)}&rotate_tray=${s}`,{method:"POST"}),stopDrying:(t,e)=>Pe(`/printers/${t}/drying/stop?ams_id=${e}`,{method:"POST"}),getPrintableObjects:t=>Pe(`/printers/${t}/print/objects`),skipObjects:(t,e)=>Pe(`/printers/${t}/print/skip-objects`,{method:"POST",body:JSON.stringify(e)}),clearHMSErrors:t=>Pe(`/printers/${t}/hms/clear`,{method:"POST"}),refreshAmsSlot:(t,e,n)=>Pe(`/printers/${t}/ams/${e}/slot/${n}/refresh`,{method:"POST"}),loadAmsTray:(t,e)=>Pe(`/printers/${t}/ams/load?tray_id=${e}`,{method:"POST"}),unloadAms:t=>Pe(`/printers/${t}/ams/unload`,{method:"POST"}),enableMQTTLogging:t=>Pe(`/printers/${t}/logging/enable`,{method:"POST"}),disableMQTTLogging:t=>Pe(`/printers/${t}/logging/disable`,{method:"POST"}),getMQTTLogs:t=>Pe(`/printers/${t}/logging`),clearMQTTLogs:t=>Pe(`/printers/${t}/logging`,{method:"DELETE"}),getPrinterFiles:(t,e="/")=>Pe(`/printers/${t}/files?path=${encodeURIComponent(e)}`),getPrinterFileDownloadUrl:(t,e)=>`${kn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,getPrinterFileGcodeUrl:(t,e)=>`${kn}/printers/${t}/files/gcode?path=${encodeURIComponent(e)}`,getPrinterFilePlates:(t,e)=>Pe(`/printers/${t}/files/plates?path=${encodeURIComponent(e)}`),getPrinterFilePlateThumbnail:(t,e,n)=>La(`${kn}/printers/${t}/files/plate-thumbnail/${e}?path=${encodeURIComponent(n)}`),downloadPrinterFile:async(t,e)=>{const n={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,{headers:n});if(!a.ok){const d=await a.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${a.status}`)}const i=a.headers.get("Content-Disposition"),s=Wf(i)||e.split("/").pop()||"download",o=await a.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"};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/printers/${t}/files/download-zip`,{method:"POST",headers:n,body:JSON.stringify({paths:e})});if(!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${a.status}`)}return a.blob()},deletePrinterFile:(t,e)=>Pe(`/printers/${t}/files?path=${encodeURIComponent(e)}`,{method:"DELETE"}),getPrinterStorage:t=>Pe(`/printers/${t}/storage`),getArchives:(t,e,n=1e4,a=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(a)),i&&o.set("date_from",i),s&&o.set("date_to",s),Pe(`/archives/?${o}`)},getArchivesSlim:(t,e,n)=>{const a=new URLSearchParams;t&&a.set("date_from",t),e&&a.set("date_to",e),n!==void 0&&a.set("created_by_id",String(n));const i=a.toString();return Pe(`/archives/slim${i?`?${i}`:""}`)},getArchive:t=>Pe(`/archives/${t}`),getArchiveRuns:t=>Pe(`/archives/${t}/runs`),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)),Pe(`/archives/search?${n}`)},rebuildSearchIndex:()=>Pe("/archives/search/rebuild-index",{method:"POST"}),updateArchive:(t,e)=>Pe(`/archives/${t}`,{method:"PATCH",body:JSON.stringify(e)}),toggleFavorite:t=>Pe(`/archives/${t}/favorite`,{method:"POST"}),deleteArchive:(t,e=!1)=>Pe(`/archives/${t}${e?"?purge_stats=true":""}`,{method:"DELETE"}),previewArchivePurge:(t,e=!1)=>Pe(`/archives/purge/preview?older_than_days=${t}&purge_stats=${e}`),executeArchivePurge:(t,e=!1)=>Pe("/archives/purge",{method:"POST",body:JSON.stringify({older_than_days:t,purge_stats:e})}),getArchivePurgeSettings:()=>Pe("/archives/purge/settings"),updateArchivePurgeSettings:t=>Pe("/archives/purge/settings",{method:"PUT",body:JSON.stringify(t)}),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 Pe(`/archives/stats${n?`?${n}`:""}`)},getTags:()=>Pe("/archives/tags"),renameTag:(t,e)=>Pe(`/archives/tags/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({new_name:e})}),deleteTag:t=>Pe(`/archives/tags/${encodeURIComponent(t)}`,{method:"DELETE"}),recalculateCosts:()=>Pe("/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 Pe(`/archives/analysis/failures${n?`?${n}`:""}`)},compareArchives:t=>Pe(`/archives/compare?archive_ids=${t.join(",")}`),findSimilarArchives:(t,e=10)=>Pe(`/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={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/archives/export?${e}`,{headers:n});if(!a.ok){const l=await a.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${a.status}`)}const i=a.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 a.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={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/archives/stats/export?${e}`,{headers:n});if(!a.ok){const l=await a.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${a.status}`)}const i=a.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 a.blob(),filename:s}},getArchiveDuplicates:t=>Pe(`/archives/${t}/duplicates`),backfillContentHashes:()=>Pe("/archives/backfill-hashes",{method:"POST"}),getArchiveThumbnail:t=>La(`${kn}/archives/${t}/thumbnail?v=${Date.now()}`),getArchivePlateThumbnail:(t,e)=>La(`${kn}/archives/${t}/plate-thumbnail/${e}`),getArchiveDownload:t=>`${kn}/archives/${t}/download`,downloadArchive:async(t,e)=>{const n={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/archives/${t}/download`,{headers:n});if(!a.ok){const d=await a.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${a.status}`)}const i=a.headers.get("Content-Disposition"),s=Wf(i)||e||`archive_${t}.3mf`,o=await a.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=>`${kn}/archives/${t}/gcode`,getArchivePlatePreview:t=>La(`${kn}/archives/${t}/plate-preview`),getArchiveTimelapse:t=>La(`${kn}/archives/${t}/timelapse?v=${Date.now()}`),scanArchiveTimelapse:t=>Pe(`/archives/${t}/timelapse/scan`,{method:"POST"}),selectArchiveTimelapse:(t,e)=>Pe(`/archives/${t}/timelapse/select?filename=${encodeURIComponent(e)}`,{method:"POST"}),deleteArchiveTimelapse:t=>Pe(`/archives/${t}/timelapse`,{method:"DELETE"}),uploadArchiveTimelapse:async(t,e)=>{const n=new FormData;n.append("file",e);const a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/archives/${t}/timelapse/upload`,{method:"POST",headers:a,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},getTimelapseInfo:t=>Pe(`/archives/${t}/timelapse/info`),getTimelapseThumbnails:(t,e=10)=>Pe(`/archives/${t}/timelapse/thumbnails?count=${e}`),processTimelapse:async(t,e,n)=>{const a=new FormData;a.append("trim_start",String(e.trimStart??0)),e.trimEnd!==void 0&&a.append("trim_end",String(e.trimEnd)),a.append("speed",String(e.speed??1)),a.append("save_mode",e.saveMode),e.outputFilename&&a.append("output_filename",e.outputFilename),n&&a.append("audio",n);const i={};Sn&&(i.Authorization=`Bearer ${Sn}`);const s=await fetch(`${kn}/archives/${t}/timelapse/process`,{method:"POST",headers:i,body:a});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},getArchivePhotoUrl:(t,e)=>La(`${kn}/archives/${t}/photos/${encodeURIComponent(e)}`),uploadArchivePhoto:async(t,e)=>{const n=new FormData;n.append("file",e);const a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/archives/${t}/photos`,{headers:a,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)=>Pe(`/archives/${t}/photos/${encodeURIComponent(e)}`,{method:"DELETE"}),getSource3mfDownloadUrl:t=>`${kn}/archives/${t}/source`,downloadSource3mf:async t=>{const e={};Sn&&(e.Authorization=`Bearer ${Sn}`);const n=await fetch(`${kn}/archives/${t}/source`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const a=n.headers.get("Content-Disposition"),i=Wf(a)||`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`${kn}/archives/${t}/source/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createSourceSlicerToken:t=>Pe(`/archives/${t}/source-slicer-token`,{method:"POST"}),getSourceSlicerDownloadUrl:(t,e,n)=>{const a=n.replace(/[/\\?#]/g,"_");return`${kn}/archives/${t}/source-dl/${e}/${encodeURIComponent(a.endsWith(".3mf")?a:a+".3mf")}`},uploadSource3mf:async(t,e)=>{const n=new FormData;n.append("file",e);const a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/archives/${t}/source`,{method:"POST",headers:a,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteSource3mf:t=>Pe(`/archives/${t}/source`,{method:"DELETE"}),getF3dDownloadUrl:t=>`${kn}/archives/${t}/f3d`,downloadF3d:async t=>{const e={};Sn&&(e.Authorization=`Bearer ${Sn}`);const n=await fetch(`${kn}/archives/${t}/f3d`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const a=n.headers.get("Content-Disposition"),i=Wf(a)||`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 a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/archives/${t}/f3d`,{method:"POST",headers:a,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteF3d:t=>Pe(`/archives/${t}/f3d`,{method:"DELETE"}),getArchiveQRCodeUrl:(t,e=200)=>La(`${kn}/archives/${t}/qrcode?size=${e}`),getArchiveCapabilities:t=>Pe(`/archives/${t}/capabilities`),getArchiveProjectPage:t=>Pe(`/archives/${t}/project-page`),updateArchiveProjectPage:(t,e)=>Pe(`/archives/${t}/project-page`,{method:"PATCH",body:JSON.stringify(e)}),getArchiveProjectImageUrl:(t,e)=>La(`${kn}/archives/${t}/project-image/${encodeURIComponent(e)}`),getArchiveForSlicer:(t,e)=>{const n=e.replace(/[/\\?#]/g,"_");return`${kn}/archives/${t}/file/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`},createArchiveSlicerToken:t=>Pe(`/archives/${t}/slicer-token`,{method:"POST"}),getArchiveSlicerDownloadUrl:(t,e,n)=>{const a=n.replace(/[/\\?#]/g,"_");return`${kn}/archives/${t}/dl/${e}/${encodeURIComponent(a.endsWith(".3mf")?a:a+".3mf")}`},getArchivePlates:t=>Pe(`/archives/${t}/plates`),getArchiveFilamentRequirements:(t,e,n,a)=>{const i=new URLSearchParams;return e!==void 0&&i.set("plate_id",String(e)),n&&i.set("request_id",n),a&&(i.set("bundle_id",a.bundle_id),i.set("printer_name",a.printer_name),i.set("process_name",a.process_name),i.set("filament_names",a.filament_names.join(";"))),Pe(`/archives/${t}/filament-requirements${i.toString()?`?${i}`:""}`)},reprintArchive:(t,e,n)=>Pe(`/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 a=e?`${kn}/archives/upload?printer_id=${e}`:`${kn}/archives/upload`,i={};Sn&&(i.Authorization=`Bearer ${Sn}`);const s=await fetch(a,{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 a=e?`${kn}/archives/upload-bulk?printer_id=${e}`:`${kn}/archives/upload-bulk`,i={};Sn&&(i.Authorization=`Bearer ${Sn}`);const s=await fetch(a,{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)),Pe(`/print-log/?${e}`)},getPrintLogThumbnail:t=>La(`${kn}/print-log/${t}/thumbnail`),clearPrintLog:()=>Pe("/print-log/",{method:"DELETE"}),getSettings:()=>Pe("/settings/"),getDefaultSidebarOrder:()=>Pe("/settings/default-sidebar-order"),getUiPreferences:()=>Pe("/settings/ui-preferences"),updateSettings:t=>Pe("/settings/",{method:"PUT",body:JSON.stringify(t)}),getMQTTStatus:()=>Pe("/settings/mqtt/status"),resetSettings:()=>Pe("/settings/reset",{method:"POST"}),exportBackup:async()=>{const t=`${kn}/settings/backup`,e={};Sn&&(e.Authorization=`Bearer ${Sn}`);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 a=n.headers.get("Content-Disposition");let i="bambuddy-backup.zip";if(a){const o=a.match(/filename=([^;]+)/);o&&(i=o[1].trim().replace(/^"(.*)"$/,"$1"))}return{blob:await n.blob(),filename:i}},importBackup:async t=>{const e=new FormData;e.append("file",t);const n=`${kn}/settings/restore`,a={};return Sn&&(a.Authorization=`Bearer ${Sn}`),(await fetch(n,{method:"POST",headers:a,body:e})).json()},checkFfmpeg:()=>Pe("/settings/check-ffmpeg"),getNetworkInterfaces:()=>Pe("/settings/network-interfaces"),getCloudStatus:()=>Pe("/cloud/status"),cloudLogin:(t,e,n="global")=>Pe("/cloud/login",{method:"POST",body:JSON.stringify({email:t,password:e,region:n})}),cloudVerify:(t,e,n,a="global")=>Pe("/cloud/verify",{method:"POST",body:JSON.stringify({email:t,code:e,tfa_key:n,region:a})}),cloudSetToken:(t,e="global")=>Pe("/cloud/token",{method:"POST",body:JSON.stringify({access_token:t,region:e})}),cloudLogout:()=>Pe("/cloud/logout",{method:"POST"}),getCloudSettings:(t="02.04.00.70")=>Pe(`/cloud/settings?version=${t}`),getBuiltinFilaments:()=>Pe("/cloud/builtin-filaments"),getFilamentIdMap:()=>Pe("/cloud/filament-id-map"),getMakerworldStatus:()=>Pe("/makerworld/status"),resolveMakerworldUrl:t=>Pe("/makerworld/resolve",{method:"POST",body:JSON.stringify({url:t})}),getMakerworldRecentImports:(t=10)=>Pe(`/makerworld/recent-imports?limit=${t}`),importMakerworldInstance:(t,e,n,a)=>Pe("/makerworld/import",{method:"POST",body:JSON.stringify({model_id:t,instance_id:e??null,profile_id:n??null,folder_id:a??null})}),getCloudSettingDetail:t=>Pe(`/cloud/settings/${t}`),createCloudSetting:t=>Pe("/cloud/settings",{method:"POST",body:JSON.stringify(t)}),updateCloudSetting:(t,e)=>Pe(`/cloud/settings/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCloudSetting:t=>Pe(`/cloud/settings/${t}`,{method:"DELETE"}),getCloudDevices:()=>Pe("/cloud/devices"),getCloudFields:t=>Pe(`/cloud/fields/${t}`),getAllCloudFields:()=>Pe("/cloud/fields"),getFilamentInfo:t=>Pe("/cloud/filament-info",{method:"POST",body:JSON.stringify(t)}),getSmartPlugs:()=>Pe("/smart-plugs/"),getSmartPlug:t=>Pe(`/smart-plugs/${t}`),getSmartPlugByPrinter:t=>Pe(`/smart-plugs/by-printer/${t}`),getScriptPlugsByPrinter:t=>Pe(`/smart-plugs/by-printer/${t}/scripts`),createSmartPlug:t=>Pe("/smart-plugs/",{method:"POST",body:JSON.stringify(t)}),updateSmartPlug:(t,e)=>Pe(`/smart-plugs/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSmartPlug:t=>Pe(`/smart-plugs/${t}`,{method:"DELETE"}),controlSmartPlug:(t,e)=>Pe(`/smart-plugs/${t}/control`,{method:"POST",body:JSON.stringify({action:e})}),getSmartPlugStatus:t=>Pe(`/smart-plugs/${t}/status`),testSmartPlugConnection:(t,e,n)=>Pe("/smart-plugs/test-connection",{method:"POST",body:JSON.stringify({ip_address:t,username:e,password:n})}),startTasmotaScan:()=>Pe("/smart-plugs/discover/scan",{method:"POST"}),getTasmotaScanStatus:()=>Pe("/smart-plugs/discover/status"),stopTasmotaScan:()=>Pe("/smart-plugs/discover/stop",{method:"POST"}),getDiscoveredTasmotaDevices:()=>Pe("/smart-plugs/discover/devices"),testHAConnection:(t,e)=>Pe("/smart-plugs/ha/test-connection",{method:"POST",body:JSON.stringify({url:t,token:e})}),getHAEntities:t=>{const e=t?`?search=${encodeURIComponent(t)}`:"";return Pe(`/smart-plugs/ha/entities${e}`)},getHASensorEntities:()=>Pe("/smart-plugs/ha/sensors"),testRESTConnection:(t,e="GET",n)=>Pe("/smart-plugs/rest/test-connection",{method:"POST",body:JSON.stringify({url:t,method:e,headers:n})}),getQueue:(t,e,n)=>{const a=new URLSearchParams;return t&&a.set("printer_id",String(t)),e&&a.set("status",e),n&&a.set("target_model",n),Pe(`/queue/?${a}`)},getQueueItem:t=>Pe(`/queue/${t}`),addToQueue:t=>Pe("/queue/",{method:"POST",body:JSON.stringify(t)}),updateQueueItem:(t,e)=>Pe(`/queue/${t}`,{method:"PATCH",body:JSON.stringify(e)}),removeFromQueue:t=>Pe(`/queue/${t}`,{method:"DELETE"}),reorderQueue:t=>Pe("/queue/reorder",{method:"POST",body:JSON.stringify({items:t})}),cancelQueueItem:t=>Pe(`/queue/${t}/cancel`,{method:"POST"}),stopQueueItem:t=>Pe(`/queue/${t}/stop`,{method:"POST"}),startQueueItem:t=>Pe(`/queue/${t}/start`,{method:"POST"}),bulkUpdateQueue:t=>Pe("/queue/bulk",{method:"PATCH",body:JSON.stringify(t)}),getBatches:t=>{const e=t?`?status=${t}`:"";return Pe(`/queue/batches${e}`)},getBatch:t=>Pe(`/queue/batches/${t}`),cancelBatch:t=>Pe(`/queue/batches/${t}`,{method:"DELETE"}),getKProfiles:(t,e="0.4")=>Pe(`/printers/${t}/kprofiles/?nozzle_diameter=${e}`),setKProfile:(t,e)=>Pe(`/printers/${t}/kprofiles/`,{method:"POST",body:JSON.stringify(e)}),deleteKProfile:(t,e)=>Pe(`/printers/${t}/kprofiles/`,{method:"DELETE",body:JSON.stringify(e)}),setKProfilesBatch:(t,e)=>Pe(`/printers/${t}/kprofiles/batch`,{method:"POST",body:JSON.stringify(e)}),getKProfileNotes:t=>Pe(`/printers/${t}/kprofiles/notes`),setKProfileNote:(t,e,n)=>Pe(`/printers/${t}/kprofiles/notes`,{method:"PUT",body:JSON.stringify({setting_id:e,note:n})}),deleteKProfileNote:(t,e)=>Pe(`/printers/${t}/kprofiles/notes/${encodeURIComponent(e)}`,{method:"DELETE"}),getSlotPresets:t=>Pe(`/printers/${t}/slot-presets`),getSlotPreset:(t,e,n)=>Pe(`/printers/${t}/slot-presets/${e}/${n}`),saveSlotPreset:(t,e,n,a,i,s="cloud")=>Pe(`/printers/${t}/slot-presets/${e}/${n}?preset_id=${encodeURIComponent(a)}&preset_name=${encodeURIComponent(i)}&preset_source=${encodeURIComponent(s)}`,{method:"PUT"}),deleteSlotPreset:(t,e,n)=>Pe(`/printers/${t}/slot-presets/${e}/${n}`,{method:"DELETE"}),getAmsLabels:t=>Pe(`/printers/${t}/ams-labels`),saveAmsLabel:(t,e,n,a="")=>Pe(`/printers/${t}/ams-labels/${e}`,{method:"PUT",body:JSON.stringify({label:n,ams_serial:a})}),deleteAmsLabel:(t,e,n="")=>Pe(`/printers/${t}/ams-labels/${e}?ams_serial=${encodeURIComponent(n)}`,{method:"DELETE"}),configureAmsSlot:(t,e,n,a)=>{const i=new URLSearchParams({tray_info_idx:a.tray_info_idx,tray_type:a.tray_type,tray_sub_brands:a.tray_sub_brands,tray_color:a.tray_color,nozzle_temp_min:a.nozzle_temp_min.toString(),nozzle_temp_max:a.nozzle_temp_max.toString(),cali_idx:a.cali_idx.toString(),nozzle_diameter:a.nozzle_diameter});return a.setting_id&&i.set("setting_id",a.setting_id),a.kprofile_filament_id&&i.set("kprofile_filament_id",a.kprofile_filament_id),a.kprofile_setting_id&&i.set("kprofile_setting_id",a.kprofile_setting_id),a.k_value!==void 0&&a.k_value>0&&i.set("k_value",a.k_value.toString()),Pe(`/printers/${t}/slots/${e}/${n}/configure?${i}`,{method:"POST"})},resetAmsSlot:(t,e,n)=>Pe(`/printers/${t}/ams/${e}/tray/${n}/reset`,{method:"POST"}),listFilaments:()=>Pe("/filament-catalog/"),getFilament:t=>Pe(`/filament-catalog/${t}`),getFilamentsByType:t=>Pe(`/filament-catalog/by-type/${t}`),getNotificationProviders:()=>Pe("/notifications/"),getNotificationProvider:t=>Pe(`/notifications/${t}`),createNotificationProvider:t=>Pe("/notifications/",{method:"POST",body:JSON.stringify(t)}),updateNotificationProvider:(t,e)=>Pe(`/notifications/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteNotificationProvider:t=>Pe(`/notifications/${t}`,{method:"DELETE"}),testNotificationProvider:t=>Pe(`/notifications/${t}/test`,{method:"POST"}),testNotificationConfig:t=>Pe("/notifications/test-config",{method:"POST",body:JSON.stringify(t)}),testAllNotificationProviders:()=>Pe("/notifications/test-all",{method:"POST"}),getNotificationTemplates:()=>Pe("/notification-templates"),getNotificationTemplate:t=>Pe(`/notification-templates/${t}`),updateNotificationTemplate:(t,e)=>Pe(`/notification-templates/${t}`,{method:"PUT",body:JSON.stringify(e)}),resetNotificationTemplate:t=>Pe(`/notification-templates/${t}/reset`,{method:"POST"}),getTemplateVariables:()=>Pe("/notification-templates/variables"),previewTemplate:t=>Pe("/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)),Pe(`/notifications/logs?${e}`)},getNotificationLogStats:(t=7)=>Pe(`/notifications/logs/stats?days=${t}`),clearNotificationLogs:(t=30)=>Pe(`/notifications/logs?older_than_days=${t}`,{method:"DELETE"}),getSpoolmanStatus:()=>Pe("/spoolman/status"),connectSpoolman:()=>Pe("/spoolman/connect",{method:"POST"}),disconnectSpoolman:()=>Pe("/spoolman/disconnect",{method:"POST"}),syncPrinterAms:t=>Pe(`/spoolman/sync/${t}`,{method:"POST"}),syncAllPrintersAms:()=>Pe("/spoolman/sync-all",{method:"POST"}),getSpoolmanSpools:()=>Pe("/spoolman/spools"),getSpoolmanFilaments:()=>Pe("/spoolman/filaments"),getSpoolmanInventoryFilaments:()=>Pe("/spoolman/inventory/filaments"),patchSpoolmanFilament:(t,e)=>Pe(`/spoolman/inventory/filaments/${t}`,{method:"PATCH",body:JSON.stringify(e)}),getUnlinkedSpools:()=>Pe("/spoolman/spools/unlinked"),getLinkedSpools:()=>Pe("/spoolman/spools/linked"),linkSpool:(t,e)=>Pe(`/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=>Pe(`/spoolman/spools/${t}/unlink`,{method:"POST"}),getSpoolmanSettings:()=>Pe("/settings/spoolman"),updateSpoolmanSettings:t=>Pe("/settings/spoolman",{method:"PUT",body:JSON.stringify(t)}),getSpools:(t=!1)=>Pe(`/inventory/spools?include_archived=${t}`),getSpool:t=>Pe(`/inventory/spools/${t}`),createSpool:t=>Pe("/inventory/spools",{method:"POST",body:JSON.stringify(t)}),bulkCreateSpools:(t,e)=>Pe("/inventory/spools/bulk",{method:"POST",body:JSON.stringify({spool:t,quantity:e})}),updateSpool:(t,e)=>Pe(`/inventory/spools/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSpool:t=>Pe(`/inventory/spools/${t}`,{method:"DELETE"}),archiveSpool:t=>Pe(`/inventory/spools/${t}/archive`,{method:"POST"}),restoreSpool:t=>Pe(`/inventory/spools/${t}/restore`,{method:"POST"}),resetSpoolUsage:t=>Pe(`/inventory/spools/${t}/reset-usage`,{method:"POST"}),bulkResetSpoolUsage:t=>Pe("/inventory/spools/reset-usage-bulk",{method:"POST",body:JSON.stringify({spool_ids:t})}),getSpoolKProfiles:t=>Pe(`/inventory/spools/${t}/k-profiles`),saveSpoolKProfiles:(t,e)=>Pe(`/inventory/spools/${t}/k-profiles`,{method:"PUT",body:JSON.stringify(e)}),getAssignments:t=>Pe(`/inventory/assignments${t?`?printer_id=${t}`:""}`),assignSpool:t=>Pe("/inventory/assignments",{method:"POST",body:JSON.stringify(t)}),unassignSpool:(t,e,n)=>Pe(`/inventory/assignments/${t}/${e}/${n}`,{method:"DELETE"}),printSpoolLabels:async t=>{const e={"Content-Type":"application/json"};Sn&&(e.Authorization=`Bearer ${Sn}`);const n=await fetch(`${kn}/inventory/labels`,{method:"POST",headers:e,body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({}));throw new Error(a.detail||`HTTP ${n.status}`)}return n.blob()},printSpoolmanSpoolLabels:async t=>{const e={"Content-Type":"application/json"};Sn&&(e.Authorization=`Bearer ${Sn}`);const n=await fetch(`${kn}/spoolman/labels`,{method:"POST",headers:e,body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({}));throw new Error(a.detail||`HTTP ${n.status}`)}return n.blob()},getSpoolCatalog:()=>Pe("/inventory/catalog"),addCatalogEntry:t=>Pe("/inventory/catalog",{method:"POST",body:JSON.stringify(t)}),updateCatalogEntry:(t,e)=>Pe(`/inventory/catalog/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCatalogEntry:t=>Pe(`/inventory/catalog/${t}`,{method:"DELETE"}),bulkDeleteCatalogEntries:t=>Pe("/inventory/catalog/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetSpoolCatalog:()=>Pe("/inventory/catalog/reset",{method:"POST"}),getColorCatalog:()=>Pe("/inventory/colors"),getColorNameMap:()=>Pe("/inventory/colors/map"),addColorEntry:t=>Pe("/inventory/colors",{method:"POST",body:JSON.stringify(t)}),updateColorEntry:(t,e)=>Pe(`/inventory/colors/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteColorEntry:t=>Pe(`/inventory/colors/${t}`,{method:"DELETE"}),bulkDeleteColorEntries:t=>Pe("/inventory/colors/bulk-delete",{method:"POST",body:JSON.stringify({ids:t})}),resetColorCatalog:()=>Pe("/inventory/colors/reset",{method:"POST"}),lookupColor:(t,e,n)=>Pe(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(t)}&color_name=${encodeURIComponent(e)}${n?`&material=${encodeURIComponent(n)}`:""}`),searchColors:(t,e)=>Pe(`/inventory/colors/search?${t?`manufacturer=${encodeURIComponent(t)}`:""}${t&&e?"&":""}${e?`material=${encodeURIComponent(e)}`:""}`),linkTagToSpool:(t,e)=>Pe(`/inventory/spools/${t}/link-tag`,{method:"PATCH",body:JSON.stringify(e)}),getSpoolUsageHistory:(t,e=50)=>Pe(`/inventory/spools/${t}/usage?limit=${e}`),getAllUsageHistory:(t=100,e)=>Pe(`/inventory/usage?limit=${t}${e?`&printer_id=${e}`:""}`),clearSpoolUsageHistory:t=>Pe(`/inventory/spools/${t}/usage`,{method:"DELETE"}),syncWeightsFromAms:()=>Pe("/inventory/sync-ams-weights",{method:"POST"}),getSkuSettings:()=>Pe("/inventory/sku-settings"),upsertSkuSettings:t=>Pe("/inventory/sku-settings",{method:"POST",body:JSON.stringify(t)}),getShoppingList:()=>Pe("/inventory/shopping-list"),addToShoppingList:t=>Pe("/inventory/shopping-list",{method:"POST",body:JSON.stringify(t)}),removeFromShoppingList:t=>Pe(`/inventory/shopping-list/${t}`,{method:"DELETE"}),clearShoppingList:()=>Pe("/inventory/shopping-list",{method:"DELETE"}),updateShoppingListStatus:(t,e)=>Pe(`/inventory/shopping-list/${t}/status`,{method:"PATCH",body:JSON.stringify({status:e})}),getFilamentPresets:()=>Pe("/cloud/filaments"),getSpoolmanInventorySpools:(t=!1)=>Pe(`/spoolman/inventory/spools?include_archived=${t}`),getSpoolmanInventorySpool:t=>Pe(`/spoolman/inventory/spools/${t}`),createSpoolmanInventorySpool:t=>Pe("/spoolman/inventory/spools",{method:"POST",body:JSON.stringify(t)}),bulkCreateSpoolmanInventorySpools:(t,e)=>Pe("/spoolman/inventory/spools/bulk",{method:"POST",body:JSON.stringify({spool:t,quantity:e})}),updateSpoolmanInventorySpool:(t,e)=>Pe(`/spoolman/inventory/spools/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSpoolmanInventorySpool:t=>Pe(`/spoolman/inventory/spools/${t}`,{method:"DELETE"}),archiveSpoolmanInventorySpool:t=>Pe(`/spoolman/inventory/spools/${t}/archive`,{method:"POST"}),restoreSpoolmanInventorySpool:t=>Pe(`/spoolman/inventory/spools/${t}/restore`,{method:"POST"}),resetSpoolmanInventorySpoolUsage:t=>Pe(`/spoolman/inventory/spools/${t}/reset-usage`,{method:"POST"}),bulkResetSpoolmanInventorySpoolUsage:t=>Pe("/spoolman/inventory/spools/reset-usage-bulk",{method:"POST",body:JSON.stringify({spool_ids:t})}),linkTagToSpoolmanSpool:(t,e)=>Pe(`/spoolman/inventory/spools/${t}/tag`,{method:"PATCH",body:JSON.stringify(e)}),syncSpoolmanSpoolWeight:(t,e)=>Pe(`/spoolman/inventory/spools/${t}/weight`,{method:"PATCH",body:JSON.stringify({weight_grams:e})}),assignSpoolmanSlot:t=>Pe("/spoolman/inventory/slot-assignments",{method:"POST",body:JSON.stringify(t)}),unassignSpoolmanSlot:t=>Pe(`/spoolman/inventory/slot-assignments/${t}`,{method:"DELETE"}),getSpoolmanSlotAssignment:(t,e,n)=>Pe(`/spoolman/inventory/slot-assignments?printer_id=${t}&ams_id=${e}&tray_id=${n}`),getSpoolmanSlotAssignments:t=>Pe(t!==void 0?`/spoolman/inventory/slot-assignments/all?printer_id=${t}`:"/spoolman/inventory/slot-assignments/all"),syncSpoolmanAmsWeights:()=>Pe("/spoolman/inventory/sync-ams-weights",{method:"POST"}),getSpoolmanKProfiles:t=>Pe(`/spoolman/inventory/spools/${t}/k-profiles`),saveSpoolmanKProfiles:(t,e)=>Pe(`/spoolman/inventory/spools/${t}/k-profiles`,{method:"PUT",body:JSON.stringify(e)}),getVersion:()=>Pe("/updates/version"),checkForUpdates:()=>Pe("/updates/check"),applyUpdate:()=>Pe("/updates/apply",{method:"POST"}),getUpdateStatus:()=>Pe("/updates/status"),getMaintenanceTypes:()=>Pe("/maintenance/types"),createMaintenanceType:t=>Pe("/maintenance/types",{method:"POST",body:JSON.stringify(t)}),updateMaintenanceType:(t,e)=>Pe(`/maintenance/types/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteMaintenanceType:t=>Pe(`/maintenance/types/${t}`,{method:"DELETE"}),restoreDefaultMaintenanceTypes:()=>Pe("/maintenance/types/restore-defaults",{method:"POST"}),getMaintenanceOverview:()=>Pe("/maintenance/overview"),getPrinterMaintenance:t=>Pe(`/maintenance/printers/${t}`),updateMaintenanceItem:(t,e)=>Pe(`/maintenance/items/${t}`,{method:"PATCH",body:JSON.stringify(e)}),performMaintenance:(t,e)=>Pe(`/maintenance/items/${t}/perform`,{method:"POST",body:JSON.stringify({notes:e})}),getMaintenanceHistory:t=>Pe(`/maintenance/items/${t}/history`),getMaintenanceSummary:()=>Pe("/maintenance/summary"),setPrinterHours:(t,e)=>Pe(`/maintenance/printers/${t}/hours?total_hours=${e}`,{method:"PATCH"}),assignMaintenanceType:(t,e)=>Pe(`/maintenance/printers/${t}/assign/${e}`,{method:"POST"}),removeMaintenanceItem:t=>Pe(`/maintenance/items/${t}`,{method:"DELETE"}),getCameraStreamToken:()=>Pe("/printers/camera/stream-token",{method:"POST"}),createLongLivedCameraToken:t=>Pe("/auth/tokens",{method:"POST",body:JSON.stringify({...t,scope:"camera_stream"})}),listMyLongLivedCameraTokens:()=>Pe("/auth/tokens"),listAllLongLivedCameraTokens:()=>Pe("/auth/tokens/all"),listLongLivedCameraTokensForUser:t=>Pe(`/auth/tokens?user_id=${t}`),revokeLongLivedCameraToken:t=>Pe(`/auth/tokens/${t}`,{method:"DELETE"}),getCameraStreamUrl:(t,e=10)=>La(`${kn}/printers/${t}/camera/stream?fps=${e}`),getCameraSnapshotUrl:t=>La(`${kn}/printers/${t}/camera/snapshot`),testCameraConnection:t=>Pe(`/printers/${t}/camera/test`),getCameraStatus:t=>Pe(`/printers/${t}/camera/status`),diagnoseCamera:t=>Pe(`/printers/${t}/camera/diagnose`,{method:"POST"}),checkPlateEmpty:(t,e)=>{const n=new URLSearchParams;return e?.useExternal!==void 0&&n.set("use_external",String(e.useExternal)),n.set("include_debug_image",String(e?.includeDebugImage??!1)),Pe(`/printers/${t}/camera/check-plate?${n.toString()}`)},getPlateDetectionStatus:t=>Pe(`/printers/${t}/camera/plate-detection/status`),calibratePlateDetection:(t,e)=>{const n=new URLSearchParams;return e?.label&&n.set("label",e.label),e?.useExternal!==void 0&&n.set("use_external",String(e.useExternal)),Pe(`/printers/${t}/camera/plate-detection/calibrate?${n.toString()}`,{method:"POST"})},deletePlateCalibration:t=>Pe(`/printers/${t}/camera/plate-detection/calibrate`,{method:"DELETE"}),getPlateReferences:t=>Pe(`/printers/${t}/camera/plate-detection/references`),getPlateReferenceThumbnailUrl:(t,e)=>La(`${kn}/printers/${t}/camera/plate-detection/references/${e}/thumbnail`),updatePlateReferenceLabel:(t,e,n)=>{const a=new URLSearchParams;return a.set("label",n),Pe(`/printers/${t}/camera/plate-detection/references/${e}?${a.toString()}`,{method:"PUT"})},deletePlateReference:(t,e)=>Pe(`/printers/${t}/camera/plate-detection/references/${e}`,{method:"DELETE"}),getExternalLinks:()=>Pe("/external-links/"),getExternalLink:t=>Pe(`/external-links/${t}`),createExternalLink:t=>Pe("/external-links/",{method:"POST",body:JSON.stringify(t)}),updateExternalLink:(t,e)=>Pe(`/external-links/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteExternalLink:t=>Pe(`/external-links/${t}`,{method:"DELETE"}),reorderExternalLinks:t=>Pe("/external-links/reorder",{method:"PUT",body:JSON.stringify({ids:t})}),uploadExternalLinkIcon:async(t,e)=>{const n=new FormData;n.append("file",e);const a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/external-links/${t}/icon`,{method:"POST",headers:a,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteExternalLinkIcon:t=>Pe(`/external-links/${t}/icon`,{method:"DELETE"}),getExternalLinkIconUrl:t=>La(`${kn}/external-links/${t}/icon`),getProjects:t=>{const e=new URLSearchParams;return t&&e.set("status",t),Pe(`/projects/?${e}`)},getProject:t=>Pe(`/projects/${t}`),createProject:t=>Pe("/projects/",{method:"POST",body:JSON.stringify(t)}),updateProject:(t,e)=>Pe(`/projects/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>Pe(`/projects/${t}`,{method:"DELETE"}),getProjectArchives:(t,e=100,n=0)=>Pe(`/projects/${t}/archives?limit=${e}&offset=${n}`),addArchivesToProject:(t,e)=>Pe(`/projects/${t}/add-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),removeArchivesFromProject:(t,e)=>Pe(`/projects/${t}/remove-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),addQueueItemsToProject:(t,e)=>Pe(`/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 a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/projects/${t}/attachments`,{method:"POST",headers:a,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)=>`${kn}/projects/${t}/attachments/${encodeURIComponent(e)}`,deleteProjectAttachment:(t,e)=>Pe(`/projects/${t}/attachments/${encodeURIComponent(e)}`,{method:"DELETE"}),getProjectCoverImageUrl:t=>La(`${kn}/projects/${t}/cover-image`),uploadProjectCoverImage:async(t,e)=>{const n=new FormData;n.append("file",e);const a={};Sn&&(a.Authorization=`Bearer ${Sn}`);const i=await fetch(`${kn}/projects/${t}/cover-image`,{method:"POST",headers:a,body:n});if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${i.status}`)}return i.json()},deleteProjectCoverImage:t=>Pe(`/projects/${t}/cover-image`,{method:"DELETE"}),getProjectBOM:t=>Pe(`/projects/${t}/bom`),createBOMItem:(t,e)=>Pe(`/projects/${t}/bom`,{method:"POST",body:JSON.stringify(e)}),updateBOMItem:(t,e,n)=>Pe(`/projects/${t}/bom/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteBOMItem:(t,e)=>Pe(`/projects/${t}/bom/${e}`,{method:"DELETE"}),getTemplates:()=>Pe("/projects/templates/"),createTemplateFromProject:t=>Pe(`/projects/${t}/create-template`,{method:"POST"}),createProjectFromTemplate:(t,e)=>Pe(`/projects/from-template/${t}${e?`?name=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getProjectTimeline:(t,e=50)=>Pe(`/projects/${t}/timeline?limit=${e}`),exportProjectJson:t=>Pe(`/projects/${t}/export?format=json`),importProject:t=>Pe("/projects/import",{method:"POST",body:JSON.stringify(t)}),importProjectFile:async t=>{const e=new FormData;e.append("file",t);const n={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/projects/import/file`,{method:"POST",headers:n,body:e});if(!a.ok){const i=await a.json().catch(()=>({}));throw new Error(i.detail||`HTTP ${a.status}`)}return a.json()},exportProjectZip:async t=>{const e={};Sn&&(e.Authorization=`Bearer ${Sn}`);const n=await fetch(`${kn}/projects/${t}/export`,{headers:e});if(!n.ok){const o=await n.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${n.status}`)}const a=n.headers.get("Content-Disposition"),i=Wf(a)||`project_${t}.zip`;return{blob:await n.blob(),filename:i}},getAPIKeys:()=>Pe("/api-keys/"),createAPIKey:t=>Pe("/api-keys/",{method:"POST",body:JSON.stringify(t)}),updateAPIKey:(t,e)=>Pe(`/api-keys/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteAPIKey:t=>Pe(`/api-keys/${t}`,{method:"DELETE"}),getAMSHistory:(t,e,n=24)=>Pe(`/ams-history/${t}/${e}?hours=${n}`),getSystemInfo:()=>Pe("/system/info"),getStorageUsage:t=>{const e=new URLSearchParams;t?.refresh&&e.set("refresh","true");const n=e.toString();return Pe(`/system/storage-usage${n?`?${n}`:""}`)},getLibraryFolders:()=>Pe("/library/folders"),createLibraryFolder:t=>Pe("/library/folders",{method:"POST",body:JSON.stringify(t)}),updateLibraryFolder:(t,e)=>Pe(`/library/folders/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFolder:t=>Pe(`/library/folders/${t}`,{method:"DELETE"}),createExternalFolder:t=>Pe("/library/folders/external",{method:"POST",body:JSON.stringify(t)}),scanExternalFolder:t=>Pe(`/library/folders/${t}/scan`,{method:"POST"}),getLibraryFoldersByProject:t=>Pe(`/library/folders/by-project/${t}`),getLibraryFoldersByArchive:t=>Pe(`/library/folders/by-archive/${t}`),getLibraryFiles:(t,e=!0,n)=>{const a=new URLSearchParams;return t!=null&&a.set("folder_id",String(t)),n!==void 0&&a.set("project_id",String(n)),a.set("include_root",String(e)),Pe(`/library/files?${a}`)},getLibraryFile:t=>Pe(`/library/files/${t}`),uploadLibraryFile:async(t,e,n=!0)=>{const a=new FormData;a.append("file",t);const i=new URLSearchParams;e&&i.set("folder_id",String(e)),i.set("generate_stl_thumbnails",String(n));const s={};Sn&&(s.Authorization=`Bearer ${Sn}`);const o=await fetch(`${kn}/library/files?${i}`,{method:"POST",headers:s,body:a});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,a=!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(a)),o.set("generate_stl_thumbnails",String(i));const l={};Sn&&(l.Authorization=`Bearer ${Sn}`);const c=await fetch(`${kn}/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)=>Pe(`/library/files/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFile:t=>Pe(`/library/files/${t}`,{method:"DELETE"}),previewLibraryPurge:(t,e=!0)=>Pe(`/library/purge/preview?older_than_days=${t}&include_never_printed=${e}`),executeLibraryPurge:(t,e=!0)=>Pe("/library/purge",{method:"POST",body:JSON.stringify({older_than_days:t,include_never_printed:e})}),listLibraryTrash:(t=100,e=0)=>Pe(`/library/trash?limit=${t}&offset=${e}`),restoreLibraryTrash:t=>Pe(`/library/trash/${t}/restore`,{method:"POST"}),hardDeleteLibraryTrash:t=>Pe(`/library/trash/${t}`,{method:"DELETE"}),emptyLibraryTrash:()=>Pe("/library/trash",{method:"DELETE"}),getLibraryTrashSettings:()=>Pe("/library/trash/settings"),updateLibraryTrashSettings:t=>Pe("/library/trash/settings",{method:"PUT",body:JSON.stringify(t)}),getLibraryFileDownloadUrl:t=>`${kn}/library/files/${t}/download`,createLibrarySlicerToken:t=>Pe(`/library/files/${t}/slicer-token`,{method:"POST"}),getLibrarySlicerDownloadUrl:(t,e,n)=>`${kn}/library/files/${t}/dl/${e}/${encodeURIComponent(Rve(n))}`,downloadLibraryFile:async(t,e)=>{const n={};Sn&&(n.Authorization=`Bearer ${Sn}`);const a=await fetch(`${kn}/library/files/${t}/download`,{headers:n});if(!a.ok){const d=await a.json().catch(()=>({}));throw new Error(d.detail||`HTTP ${a.status}`)}const i=a.headers.get("Content-Disposition"),s=Wf(i)||e||`file_${t}`,o=await a.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=>La(`${kn}/library/files/${t}/thumbnail`),getLibraryFilePlateThumbnail:(t,e)=>La(`${kn}/library/files/${t}/plate-thumbnail/${e}`),getLibraryFileGcodeUrl:t=>`${kn}/library/files/${t}/gcode`,moveLibraryFiles:(t,e)=>Pe("/library/files/move",{method:"POST",body:JSON.stringify({file_ids:t,folder_id:e})}),bulkDeleteLibrary:(t,e)=>Pe("/library/bulk-delete",{method:"POST",body:JSON.stringify({file_ids:t,folder_ids:e})}),getLibraryStats:()=>Pe("/library/stats"),batchGenerateStlThumbnails:t=>Pe("/library/generate-stl-thumbnails",{method:"POST",body:JSON.stringify(t)}),addLibraryFilesToQueue:t=>Pe("/library/files/add-to-queue",{method:"POST",body:JSON.stringify({file_ids:t})}),printLibraryFile:(t,e,n)=>Pe(`/library/files/${t}/print?printer_id=${e}`,{method:"POST",body:n?JSON.stringify(n):void 0}),cancelBackgroundDispatchJob:t=>Pe(`/background-dispatch/${t}`,{method:"DELETE"}),getLibraryFilePlates:t=>Pe(`/library/files/${t}/plates`),getLibraryFileFilamentRequirements:(t,e,n,a)=>{const i=new URLSearchParams;return e!==void 0&&i.set("plate_id",String(e)),n&&i.set("request_id",n),a&&(i.set("bundle_id",a.bundle_id),i.set("printer_name",a.printer_name),i.set("process_name",a.process_name),i.set("filament_names",a.filament_names.join(";"))),Pe(`/library/files/${t}/filament-requirements${i.toString()?`?${i}`:""}`)},getPreviewSliceProgress:async t=>{try{return await Pe(`/slicer/preview-progress/${encodeURIComponent(t)}`)}catch{return null}},getGitHubBackupConfig:()=>Pe("/github-backup/config"),saveGitHubBackupConfig:t=>Pe("/github-backup/config",{method:"POST",body:JSON.stringify(t)}),updateGitHubBackupConfig:t=>Pe("/github-backup/config",{method:"PATCH",body:JSON.stringify(t)}),deleteGitHubBackupConfig:()=>Pe("/github-backup/config",{method:"DELETE"}),testGitHubConnection:(t,e,n="github")=>Pe(`/github-backup/test?repo_url=${encodeURIComponent(t)}&token=${encodeURIComponent(e)}&provider=${encodeURIComponent(n)}`,{method:"POST"}),testGitHubStoredConnection:()=>Pe("/github-backup/test-stored",{method:"POST"}),triggerGitHubBackup:()=>Pe("/github-backup/run",{method:"POST"}),getGitHubBackupStatus:()=>Pe("/github-backup/status"),getGitHubBackupLogs:(t=50)=>Pe(`/github-backup/logs?limit=${t}`),clearGitHubBackupLogs:(t=10)=>Pe(`/github-backup/logs?keep_last=${t}`,{method:"DELETE"}),getLocalBackupStatus:()=>Pe("/local-backup/status"),triggerLocalBackup:()=>Pe("/local-backup/run",{method:"POST"}),getLocalBackups:()=>Pe("/local-backup/backups"),downloadLocalBackup:async t=>{const e=await fetch(`${kn}/local-backup/backups/${encodeURIComponent(t)}/download`,{headers:Sn?{Authorization:`Bearer ${Sn}`}:{}});if(!e.ok)throw new Error("Download failed");return{blob:await e.blob(),filename:t}},restoreLocalBackup:t=>Pe(`/local-backup/backups/${encodeURIComponent(t)}/restore`,{method:"POST"}),deleteLocalBackup:t=>Pe(`/local-backup/backups/${encodeURIComponent(t)}`,{method:"DELETE"}),getObicoStatus:()=>Pe("/obico/status"),testObicoConnection:t=>Pe("/obico/test-connection",{method:"POST",body:JSON.stringify({url:t})}),sliceLibraryFile:(t,e)=>Pe(`/library/files/${t}/slice`,{method:"POST",body:JSON.stringify(e)}),sliceArchive:(t,e)=>Pe(`/archives/${t}/slice`,{method:"POST",body:JSON.stringify(e)}),getSliceJob:t=>Pe(`/slice-jobs/${t}`),getSlicerPresets:()=>Pe("/slicer/presets"),listSlicerBundles:()=>Pe("/slicer/bundles"),importSlicerBundle:t=>{const e=new FormData;return e.append("file",t),fetch(`${kn}/slicer/bundles`,{method:"POST",headers:Sn?{Authorization:`Bearer ${Sn}`}:{},body:e}).then(async n=>{if(!n.ok){const a=await n.json().catch(()=>({}));throw new Error(a.detail||`HTTP ${n.status}`)}return n.json()})},deleteSlicerBundle:t=>Pe(`/slicer/bundles/${encodeURIComponent(t)}`,{method:"DELETE"}),getLocalPresets:()=>Pe("/local-presets/"),getLocalPresetDetail:t=>Pe(`/local-presets/${t}`),importLocalPresets:t=>fetch(`${kn}/local-presets/import`,{method:"POST",headers:Sn?{Authorization:`Bearer ${Sn}`}:{},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=>Pe("/local-presets/",{method:"POST",body:JSON.stringify(t)}),updateLocalPreset:(t,e)=>Pe(`/local-presets/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLocalPreset:t=>Pe(`/local-presets/${t}`,{method:"DELETE"}),refreshBaseProfileCache:()=>Pe("/local-presets/base-cache/refresh",{method:"POST"})},Fd={getInfo:()=>Pe("/discovery/info"),getStatus:()=>Pe("/discovery/status"),startDiscovery:(t=10)=>Pe(`/discovery/start?duration=${t}`,{method:"POST"}),stopDiscovery:()=>Pe("/discovery/stop",{method:"POST"}),getDiscoveredPrinters:()=>Pe("/discovery/printers"),startSubnetScan:(t,e=1)=>Pe("/discovery/scan",{method:"POST",body:JSON.stringify({subnet:t,timeout:e})}),getScanStatus:()=>Pe("/discovery/scan/status"),stopSubnetScan:()=>Pe("/discovery/scan/stop",{method:"POST"})},XF={getSettings:()=>Pe("/settings/virtual-printer"),getModels:()=>Pe("/settings/virtual-printer/models"),updateSettings:t=>{const e=new URLSearchParams;return t.enabled!==void 0&&e.set("enabled",String(t.enabled)),t.access_code!==void 0&&e.set("access_code",t.access_code),t.mode!==void 0&&e.set("mode",t.mode),t.model!==void 0&&e.set("model",t.model),t.target_printer_id!==void 0&&e.set("target_printer_id",String(t.target_printer_id)),t.remote_interface_ip!==void 0&&e.set("remote_interface_ip",t.remote_interface_ip),t.tailscale_disabled!==void 0&&e.set("tailscale_disabled",String(t.tailscale_disabled)),t.archive_name_source!==void 0&&e.set("archive_name_source",t.archive_name_source),Pe(`/settings/virtual-printer?${e.toString()}`,{method:"PUT"})}},J0={list:()=>Pe("/virtual-printers"),get:t=>Pe(`/virtual-printers/${t}`),create:t=>Pe("/virtual-printers",{method:"POST",body:JSON.stringify(t)}),update:(t,e)=>Pe(`/virtual-printers/${t}`,{method:"PUT",body:JSON.stringify(e)}),remove:t=>Pe(`/virtual-printers/${t}`,{method:"DELETE"}),getTailscaleStatus:()=>Pe("/virtual-printers/tailscale-status")},Ox={list:()=>Pe("/pending-uploads/"),getCount:()=>Pe("/pending-uploads/count"),get:t=>Pe(`/pending-uploads/${t}`),archive:(t,e)=>Pe(`/pending-uploads/${t}/archive`,{method:"POST",body:JSON.stringify(e||{})}),discard:t=>Pe(`/pending-uploads/${t}`,{method:"DELETE"}),archiveAll:()=>Pe("/pending-uploads/archive-all",{method:"POST"}),discardAll:()=>Pe("/pending-uploads/discard-all",{method:"DELETE"})},yN={checkUpdates:()=>Pe("/firmware/updates"),checkPrinterUpdate:t=>Pe(`/firmware/updates/${t}`),prepareUpload:(t,e)=>Pe(`/firmware/updates/${t}/prepare${e?`?version=${encodeURIComponent(e)}`:""}`),startUpload:(t,e)=>Pe(`/firmware/updates/${t}/upload${e?`?version=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getUploadStatus:t=>Pe(`/firmware/updates/${t}/upload/status`)},ny={getDebugLoggingState:()=>Pe("/support/debug-logging"),setDebugLogging:t=>Pe("/support/debug-logging",{method:"POST",body:JSON.stringify({enabled:t})}),downloadSupportBundle:async()=>{const t={};Sn&&(t.Authorization=`Bearer ${Sn}`);const e=await fetch(`${kn}/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"),a=Wf(n)||"bambuddy-support.zip",i=await e.blob(),s=window.URL.createObjectURL(i),o=document.createElement("a");o.href=s,o.download=a,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 Pe(`/support/logs${n?`?${n}`:""}`)},clearLogs:()=>Pe("/support/logs",{method:"DELETE"})},Jr={getDevices:()=>Pe("/spoolbuddy/devices"),deleteDevice:t=>Pe(`/spoolbuddy/devices/${t}`,{method:"DELETE"}),tare:t=>Pe(`/spoolbuddy/devices/${t}/calibration/tare`,{method:"POST",body:"{}"}),getCalibration:t=>Pe(`/spoolbuddy/devices/${t}/calibration`),setCalibrationFactor:(t,e,n,a)=>Pe(`/spoolbuddy/devices/${t}/calibration/set-factor`,{method:"POST",body:JSON.stringify({known_weight_grams:e,raw_adc:n,tare_raw_adc:a})}),updateSpoolWeight:(t,e)=>Pe("/spoolbuddy/scale/update-spool-weight",{method:"POST",body:JSON.stringify({spool_id:t,weight_grams:e})}),updateDisplay:(t,e,n)=>Pe(`/spoolbuddy/devices/${t}/display`,{method:"PUT",body:JSON.stringify({brightness:e,blank_timeout:n})}),updateSystemConfig:(t,e,n)=>Pe(`/spoolbuddy/devices/${t}/system/config`,{method:"POST",body:JSON.stringify({backend_url:e,...n?{api_key:n}:{}})}),checkDaemonUpdate:t=>Pe(`/spoolbuddy/devices/${t}/update-check`),triggerUpdate:t=>Pe(`/spoolbuddy/devices/${t}/update`,{method:"POST",body:"{}"}),getSSHPublicKey:()=>Pe("/spoolbuddy/ssh/public-key"),writeTag:(t,e)=>Pe("/spoolbuddy/nfc/write-tag",{method:"POST",body:JSON.stringify({device_id:t,spool_id:e})}),cancelWrite:t=>Pe(`/spoolbuddy/devices/${t}/cancel-write`,{method:"POST",body:"{}"}),systemCommand:(t,e)=>Pe(`/spoolbuddy/devices/${t}/system/command`,{method:"POST",body:JSON.stringify({command:e})}),queueDiagnostics:(t,e)=>Pe(`/spoolbuddy/diagnostics/${t}/run?diagnostic=${e}`,{method:"POST",body:"{}"}),getDiagnosticResult:(t,e)=>Pe(`/spoolbuddy/diagnostics/${t}/result?diagnostic=${e}`,{method:"GET"})},cE={submit:t=>Pe("/bug-report/submit",{method:"POST",body:JSON.stringify(t)}),startLogging:()=>Pe("/bug-report/start-logging",{method:"POST"}),stopLogging:t=>Pe(`/bug-report/stop-logging?was_debug=${t}`,{method:"POST"})},eJ=y.createContext(void 0);function Ive({children:t}){const[e,n]=y.useState(()=>{const A=localStorage.getItem("theme-mode"),F=localStorage.getItem("theme");return A||F||"dark"}),[a,i]=y.useState(()=>localStorage.getItem("dark-style")||"vibrant"),[s,o]=y.useState(()=>localStorage.getItem("dark-background")||"cool"),[l,c]=y.useState(()=>localStorage.getItem("dark-accent")||"green"),[d,u]=y.useState(()=>localStorage.getItem("light-style")||"classic"),[m,p]=y.useState(()=>localStorage.getItem("light-background")||"neutral"),[f,g]=y.useState(()=>localStorage.getItem("light-accent")||"green");y.useEffect(()=>{ae.getSettings().then(A=>{A.dark_style&&(i(A.dark_style),localStorage.setItem("dark-style",A.dark_style)),A.dark_background&&(o(A.dark_background),localStorage.setItem("dark-background",A.dark_background)),A.dark_accent&&(c(A.dark_accent),localStorage.setItem("dark-accent",A.dark_accent)),A.light_style&&(u(A.light_style),localStorage.setItem("light-style",A.light_style)),A.light_background&&(p(A.light_background),localStorage.setItem("light-background",A.light_background)),A.light_accent&&(g(A.light_accent),localStorage.setItem("light-accent",A.light_accent))}).catch(()=>{})},[]),y.useEffect(()=>{const A=document.documentElement;A.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"?(A.classList.add("dark"),A.classList.add(`style-${a}`),A.classList.add(`bg-${s}`),A.classList.add(`accent-${l}`)):(A.classList.add(`style-${d}`),A.classList.add(`bg-${m}`),A.classList.add(`accent-${f}`)),localStorage.setItem("theme-mode",e),localStorage.removeItem("theme")},[e,a,s,l,d,m,f]);const w=()=>n(A=>A==="dark"?"light":"dark"),b=A=>n(A),x=A=>{i(A),localStorage.setItem("dark-style",A),ae.updateSettings({dark_style:A}).catch(()=>{})},S=A=>{o(A),localStorage.setItem("dark-background",A),ae.updateSettings({dark_background:A}).catch(()=>{})},k=A=>{c(A),localStorage.setItem("dark-accent",A),ae.updateSettings({dark_accent:A}).catch(()=>{})},C=A=>{u(A),localStorage.setItem("light-style",A),ae.updateSettings({light_style:A}).catch(()=>{})},P=A=>{p(A),localStorage.setItem("light-background",A),ae.updateSettings({light_background:A}).catch(()=>{})},T=A=>{g(A),localStorage.setItem("light-accent",A),ae.updateSettings({light_accent:A}).catch(()=>{})};return r.jsx(eJ.Provider,{value:{mode:e,darkStyle:a,darkBackground:s,darkAccent:l,lightStyle:d,lightBackground:m,lightAccent:f,toggleMode:w,setMode:b,setDarkStyle:x,setDarkBackground:S,setDarkAccent:k,setLightStyle:C,setLightBackground:P,setLightAccent:T},children:t})}function ob(){const t=y.useContext(eJ);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const TO=y.createContext("normal");function Ove({density:t,children:e}){return r.jsx(TO.Provider,{value:t,children:e})}function At({children:t,className:e="",onClick:n,onContextMenu:a,...i}){return r.jsx("div",{className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary card-shadow ${e}`,onClick:n,onContextMenu:a,...i,children:t})}function fn({children:t,className:e="",dense:n}){const a=y.useContext(TO)==="dense",s=n??a?"px-4 py-2.5":"px-6 py-4";return r.jsx("div",{className:`${s} border-b border-bambu-dark-tertiary ${e}`,children:t})}function Et({children:t,className:e="",dense:n}){const a=y.useContext(TO)==="dense",s=n??a?"p-4":"p-6";return r.jsx("div",{className:`${s} ${e}`,children:t})}function zve(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 x6({children:t}){return r.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 Uve({onClose:t,navItems:e,sidebarItems:n}){const{t:a}=_t(),i=zve(n,e,a);return y.useEffect(()=>{const s=o=>{o.key==="Escape"&&t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:r.jsx(At,{className:"w-full max-w-md",onClick:s=>s.stopPropagation(),children:r.jsxs(Et,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(GF,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Keyboard Shortcuts"})]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4 space-y-6 max-h-[60vh] overflow-y-auto",children:i.map(s=>r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:s.category}),r.jsx("div",{className:"space-y-2",children:s.items.map(o=>r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-white text-sm flex items-center gap-1.5",children:[o.description,o.isExternal&&r.jsx(zr,{className:"w-3 h-3 text-bambu-gray"})]}),r.jsx("div",{className:"flex gap-1",children:o.keys.map(l=>r.jsx(x6,{children:l},l))})]},o.description))})]},s.category))}),r.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("p",{className:"text-xs text-bambu-gray text-center",children:["Press ",r.jsx(x6,{children:"Esc"})," or click outside to close"]})})]})})})}function je({variant:t="primary",size:e="md",className:n="",children:a,...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 r.jsx("button",{className:`${s} ${o[t]} ${l[e]} ${n}`,...i,children:a})}function wn({title:t,message:e,confirmText:n,cancelText:a,cancelVariant:i,cardClassName:s,overlayZIndex:o,variant:l="default",isLoading:c=!1,loadingText:d,children:u,onConfirm:m,onCancel:p}){const{t:f}=_t(),g=n??f("common.confirm"),w=a??f("common.cancel"),b=d??f("common.loading");y.useEffect(()=>{const k=C=>{C.key==="Escape"&&!c&&p()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[p,c]);const S={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"}}[l];return r.jsx("div",{className:`fixed inset-0 bg-black/50 flex items-center justify-center p-4 ${o??"z-50"}`,onClick:c?void 0:p,children:r.jsx(At,{className:`w-full max-w-md ${s??""}`,onClick:k=>k.stopPropagation(),children:r.jsxs(Et,{className:"p-6",children:[r.jsxs("div",{className:"flex items-start gap-4",children:[r.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${S.icon}`,children:r.jsx(Nn,{className:"w-6 h-6"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t}),r.jsx("p",{className:"text-bambu-gray text-sm whitespace-pre-line",children:e}),u&&r.jsx("div",{className:"mt-4",children:u})]})]}),r.jsxs("div",{className:"flex gap-3 mt-6",children:[r.jsx(je,{variant:i??"secondary",onClick:p,className:"flex-1",disabled:c,children:w}),r.jsx(je,{onClick:m,className:`flex-1 ${S.button}`,disabled:c,children:c?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),b]}):g})]})]})})})}function Bve({plug:t}){const e=tn(),[n,a]=y.useState(null),{data:i,isLoading:s}=Xe({queryKey:["smart-plug-status",t.id],queryFn:()=>ae.getSmartPlugStatus(t.id),refetchInterval:1e4}),o=lt({mutationFn:f=>ae.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),a(null))};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between py-2 px-3 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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?r.jsx(NO,{className:`w-4 h-4 ${d?"text-teal-400":"text-red-400"}`}):r.jsx(hc,{className:`w-4 h-4 ${d?l?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white font-medium",children:t.name}),r.jsx("div",{className:"flex items-center gap-1 text-xs",children:s?r.jsx(ft,{className:"w-3 h-3 text-bambu-gray animate-spin"}):m?d?r.jsxs(r.Fragment,{children:[r.jsx(wc,{className:"w-3 h-3 text-teal-400"}),r.jsxs("span",{className:"text-teal-400",children:[Math.round(i?.energy?.power??0),"W"]}),r.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),r.jsx(Cl,{className:"w-3 h-3 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:"Monitor"})]}):r.jsxs(r.Fragment,{children:[r.jsx(hu,{className:"w-3 h-3 text-status-error"}),r.jsx("span",{className:"text-status-error",children:"Waiting"})]}):d?r.jsxs(r.Fragment,{children:[r.jsx(Mh,{className:"w-3 h-3 text-status-ok"}),r.jsx("span",{className:l?"text-status-ok":"text-bambu-gray",children:i?.state||"Unknown"}),i?.energy?.power!==null&&i?.energy?.power!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),r.jsx(wc,{className:"w-3 h-3 text-yellow-400"}),r.jsxs("span",{className:"text-yellow-400",children:[Math.round(i.energy.power),"W"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx(hu,{className:"w-3 h-3 text-status-error"}),r.jsx("span",{className:"text-status-error",children:"Offline"})]})})]})]}),!m&&r.jsxs("div",{className:"flex gap-1",children:[r.jsx("button",{onClick:()=>a("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?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(_u,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>a("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?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(FS,{className:"w-4 h-4"})})]})]}),n&&r.jsx(wn,{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:()=>a(null)})]})}function y6({onClose:t}){const{t:e}=_t(),{data:n,isLoading:a}=Xe({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),i=n?.filter(s=>s.show_in_switchbar)||[];return r.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:[r.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary",children:r.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[r.jsx(hc,{className:"w-4 h-4 text-bambu-green"}),"Smart Switches"]})}),r.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:a?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"})}):i.length===0?r.jsxs("div",{className:"text-center py-6 px-4",children:[r.jsx(hc,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:e("smartPlugs.noSwitchesInSwitchbar")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:e("smartPlugs.enableSwitchbarHint")})]}):r.jsx("div",{className:"space-y-1",children:i.map(s=>r.jsx(Bve,{plug:s},s.id))})})]})}const tJ=[{name:"globe",icon:Js},{name:"link",icon:Qy},{name:"external-link",icon:zr},{name:"book",icon:Ufe},{name:"file-text",icon:Rs},{name:"home",icon:AS},{name:"star",icon:Eg},{name:"heart",icon:Jbe},{name:"bookmark",icon:Hfe},{name:"shopping-cart",icon:sb},{name:"music",icon:KF},{name:"video",icon:oC},{name:"image",icon:mu},{name:"camera",icon:by},{name:"map",icon:Txe},{name:"compass",icon:Bge},{name:"coffee",icon:Fge},{name:"gift",icon:Obe},{name:"wrench",icon:Gh},{name:"zap",icon:wc},{name:"cloud",icon:$h},{name:"database",icon:dc},{name:"folder",icon:OZ},{name:"mail",icon:$m},{name:"phone",icon:tye},{name:"user",icon:Gm},{name:"users",icon:bm},{name:"server",icon:Gf},{name:"terminal",icon:QZ},{name:"code",icon:Ky}];function TT(t){return tJ.find(n=>n.name===t)?.icon||Qy}function Hve({value:t,onChange:e}){const[n,a]=y.useState(!1),i=TT(t);return r.jsxs("div",{className:"relative",children:[r.jsxs("button",{type:"button",onClick:()=>a(!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:[r.jsx(i,{className:"w-5 h-5"}),r.jsx("span",{className:"text-sm text-bambu-gray flex-1 text-left",children:t})]}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>a(!1)}),r.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:r.jsx("div",{className:"grid grid-cols-5 gap-1 p-2",children:tJ.map(({name:s,icon:o})=>r.jsx("button",{type:"button",onClick:()=>{e(s),a(!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:r.jsx(o,{className:"w-5 h-5"})},s))})})]})]})}const v6=1144;function qve(){const[t,e]=y.useState(()=>typeof window<"u"?window.innerWidth<v6:!1);return y.useEffect(()=>{const n=window.matchMedia(`(max-width: ${v6-1}px)`),a=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[]),t}let AO={},nJ=0;const ZF=new Set;function $ve(t){const e={};for(const[n,a]of Object.entries(t)){if(!n||!a)continue;const i=n.replace("#","").toLowerCase().slice(0,6);i.length===6&&(e[i]=a)}AO=e,nJ+=1;for(const n of Array.from(ZF))n()}function Vve(t){return ZF.add(t),()=>{ZF.delete(t)}}function w6(){return nJ}function S6(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),a=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,a,i)/255,o=Math.min(n,a,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=a/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 fc(t){if(!t)return S6(t);const e=t.replace("#","").toLowerCase().substring(0,6),n=AO[e];return n||S6(t)}function AT(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(),a=AO[n];if(a)return a}return null}function jO(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),a=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(a,16)}, ${i})`}function rJ(t){if(!t||t.length<6)return!1;const e=t.replace("#",""),n=parseInt(e.slice(0,2),16),a=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);return(.299*n+.587*a+.114*i)/255>.6}function aJ(){return y.useSyncExternalStore(Vve,w6,w6)}const iJ=y.createContext(void 0);function Gve({children:t}){const[e,n]=y.useState(null),[a,i]=y.useState(!1),[s,o]=y.useState(!1),[l,c]=y.useState(!0),d=y.useRef(!1),u=y.useRef(!0),m=async()=>{try{const A=new URLSearchParams(window.location.search),F=A.get("token");if(F){eh(F,"session"),A.delete("token");const M=A.toString(),H=window.location.pathname+(M?`?${M}`:"")+window.location.hash;window.history.replaceState({},"",H)}const _=await ae.getAuthStatus();if(!u.current)return;if(i(_.auth_enabled),o(_.requires_setup),_.auth_enabled){const M=Wm();if(M)try{const H=await ae.getCurrentUser();if(!u.current)return;n(H),F&&M===F&&eh(F,"persistent")}catch{if(eh(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)}};y.useEffect(()=>(u.current=!0,m(),()=>{u.current=!1}),[]),y.useEffect(()=>{if(!l&&s&&!a){const A=window.location.pathname;A!=="/setup"&&!A.startsWith("/camera/")&&!d.current&&(d.current=!0,window.location.href="/setup")}else s||(d.current=!1)},[l,s,a]);const p=async(A,F,_="session")=>{const M=await ae.login({username:A,password:F});return!M.requires_2fa&&M.access_token&&(eh(M.access_token,_),await m()),M},f=(A,F,_="session")=>{eh(A,_),n(F),i(!0)},g=()=>{eh(null),n(null),ae.logout().catch(()=>{}),window.location.href="/login"},w=async()=>{if(a&&Wm())try{const A=await ae.getCurrentUser();u.current&&n(A)}catch{eh(null),u.current&&n(null)}},b=async()=>{await m()},x=y.useMemo(()=>new Set(e?.permissions??[]),[e?.permissions]),S=y.useMemo(()=>a?e?.is_admin??!1:!0,[a,e?.is_admin]),k=y.useCallback(A=>!a||S?!0:x.has(A),[a,S,x]),C=y.useCallback((...A)=>!a||S?!0:A.some(F=>x.has(F)),[a,S,x]),P=y.useCallback((...A)=>!a||S?!0:A.every(F=>x.has(F)),[a,S,x]),T=y.useCallback((A,F,_)=>{if(!a||S)return!0;const M=`${A}:${F}_all`,H=`${A}:${F}_own`;return x.has(M)?!0:x.has(H)?_==null?!1:_===e?.id:!1},[a,S,x,e?.id]);return r.jsx(iJ.Provider,{value:{user:e,authEnabled:a,requiresSetup:s,loading:l,isAdmin:S,login:p,loginWithToken:f,logout:g,refreshUser:w,refreshAuth:b,hasPermission:k,hasAnyPermission:C,hasAllPermissions:P,canModify:T},children:t})}function dr(){const t=y.useContext(iJ);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}function ls(t){if(!Number.isFinite(t)||t<=0)return"0 B";const e=["B","KB","MB","GB","TB"],n=1024,a=Math.floor(Math.log(t)/Math.log(n)),i=t/Math.pow(n,a);return a===0?`${i} ${e[a]}`:`${i.toFixed(1)} ${e[a]}`}const sJ=y.createContext(void 0);function on(){const t=y.useContext(sJ);if(!t)throw new Error("useToast must be used within a ToastProvider");return t}const _6={success:r.jsx(xr,{className:"w-5 h-5 text-green-400"}),error:r.jsx($r,{className:"w-5 h-5 text-red-400"}),warning:r.jsx(Ha,{className:"w-5 h-5 text-yellow-400"}),info:r.jsx(_i,{className:"w-5 h-5 text-blue-400"}),loading:r.jsx(ft,{className:"w-5 h-5 text-bambu-green animate-spin"})},Wve={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 Kve({children:t}){const{t:e}=_t(),[n,a]=y.useState([]),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(new Set),u=y.useRef(new Map),m="background-dispatch",p=y.useRef(null),f=y.useRef(!0);y.useEffect(()=>{f.current=!0;const S=u.current;return()=>{f.current=!1,S.forEach(k=>clearTimeout(k)),S.clear()}},[]);const g=y.useCallback((S,k="success")=>{if(!f.current)return;const C=Math.random().toString(36).substr(2,9);a(T=>[...T,{id:C,message:S,type:k}]);const P=setTimeout(()=>{f.current&&(a(T=>T.filter(A=>A.id!==C)),u.current.delete(C))},3e3);u.current.set(C,P)},[]),w=y.useCallback((S,k,C="info")=>{f.current&&a(P=>P.find(A=>A.id===S)?P.map(A=>A.id===S?{...A,message:k,type:C,persistent:!0}:A):[...P,{id:S,message:k,type:C,persistent:!0}])},[]),b=y.useCallback(S=>{if(!f.current)return;const k=u.current.get(S);k&&(clearTimeout(k),u.current.delete(S)),a(C=>C.filter(P=>P.id!==S))},[]),x=y.useCallback(async S=>{d(k=>{const C=new Set(k);return C.add(S),C});try{const k=await ae.cancelBackgroundDispatchJob(S);g(k.status==="cancelling"?e("backgroundDispatch.toast.cancellingUpload"):e("backgroundDispatch.toast.cancelled"),"info")}catch(k){const C=k instanceof Error?k.message:e("backgroundDispatch.toast.cancelFailed");g(C,"error")}finally{d(k=>{const C=new Set(k);return C.delete(S),C})}},[g,e]);return y.useEffect(()=>{const S=(P,T,A)=>{const F=P.findIndex(M=>M.jobId===T);if(F===-1)return[...P,{jobId:T,...A}];const _=[...P];return _[F]={..._[F],...A},_},k=P=>{switch(P){case"failed":return 0;case"processing":return 1;case"dispatched":return 2;case"completed":return 3;case"cancelled":return 4}},C=P=>{const T=P.detail||{},A=T.total??0,F=T.dispatched??0,_=T.processing??0,M=T.completed??0,H=T.failed??0,I=F+_>0,z=A>0&&M+H>=A&&!I,L=T.recent_event?.status;if(L==="completed"&&M>0){const Z=`first-complete:${M}:${H}`;if(p.current!==Z){p.current=Z;const ne=A-M-H,Y=ne>0?e("backgroundDispatch.toast.printStartedRemaining",{completed:M,remaining:ne}):H>0?e("backgroundDispatch.toast.completeWithFailures",{completed:M,failed:H}):e("backgroundDispatch.toast.completeSuccess",{completed:M});a(oe=>{const Q={id:m,message:Y,type:H>0?"warning":"success",persistent:!0};return oe.find(pe=>pe.id===m)?oe.map(pe=>pe.id===m?Q:pe):[...oe,Q]});const ce=u.current.get(m);ce&&clearTimeout(ce);const ue=setTimeout(()=>{f.current&&(a(oe=>oe.filter(Q=>Q.id!==m)),u.current.delete(m),p.current=null)},3e3);u.current.set(m,ue)}return}if(I){p.current=null,a(Z=>{const Y=Z.find($=>$.id===m)?.dispatchData?.jobs||[],ce=(T.dispatched_jobs||[]).map($=>({jobId:$.job_id,sourceName:$.source_name||e("backgroundDispatch.unknownFile"),printerName:$.printer_name||e("backgroundDispatch.unknownPrinter"),status:"dispatched"})),oe=(T.active_jobs&&T.active_jobs.length>0?T.active_jobs:T.active_job?.job_id?[T.active_job]:[]).filter($=>typeof $.job_id=="number").map($=>({jobId:$.job_id,sourceName:$.source_name||e("backgroundDispatch.unknownFile"),printerName:$.printer_name||e("backgroundDispatch.unknownPrinter"),status:"processing",message:$.message,uploadBytes:$.upload_bytes,uploadTotalBytes:$.upload_total_bytes,uploadProgressPct:$.upload_progress_pct})),Q=new Set([...ce,...oe].map($=>$.jobId)),le=Y.filter($=>!Q.has($.jobId)&&["completed","failed","cancelled"].includes($.status));let pe=[...ce,...oe,...le];if(T.recent_event?.job_id&&T.recent_event?.status){const $=T.recent_event.status,J=$==="cancelled"?"cancelled":$==="cancelling"?"processing":$,j=T.recent_event.source_name||e("backgroundDispatch.unknownFile"),E=T.recent_event.printer_name||e("backgroundDispatch.unknownPrinter");pe=S(pe,T.recent_event.job_id,{status:J,sourceName:j,printerName:E,message:T.recent_event.message})}oe.forEach($=>{pe=S(pe,$.jobId,{status:"processing",sourceName:$.sourceName,printerName:$.printerName,message:$.message,uploadBytes:$.uploadBytes,uploadTotalBytes:$.uploadTotalBytes,uploadProgressPct:$.uploadProgressPct})});const he={total:A,dispatched:F,processing:_,completed:M,failed:H,jobs:[...pe].sort(($,J)=>{const j=k($.status)-k(J.status);return j!==0?j:$.jobId-J.jobId})};return Z.find($=>$.id===m)?Z.map($=>$.id===m?{...$,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:he}:$):[...Z,{id:m,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:he}]});return}if(z){const Z=`${M}:${H}`;if(p.current===Z)return;p.current=Z;const ne=H>0?e("backgroundDispatch.toast.completeWithFailures",{completed:M,failed:H}):e("backgroundDispatch.toast.completeSuccess",{completed:M});a(ue=>{const oe={id:m,message:ne,type:H>0?"warning":"success",persistent:!0};return ue.find(le=>le.id===m)?ue.map(le=>le.id===m?oe:le):[...ue,oe]});const Y=u.current.get(m);Y&&clearTimeout(Y);const ce=setTimeout(()=>{a(ue=>ue.filter(oe=>oe.id!==m)),u.current.delete(m),p.current=null},3e3);u.current.set(m,ce);return}if(!I&&L&&["cancelled","failed","completed","idle"].includes(L)&&(a(Z=>Z.filter(ne=>ne.id!==m)),p.current=null),T.recent_event?.status==="idle"&&!I&&(a(Z=>Z.filter(ne=>ne.id!==m)),p.current=null),I||d(new Set),T.dispatched_jobs){const Z=new Set(T.dispatched_jobs.map(ne=>ne.job_id));d(ne=>{const Y=new Set;return ne.forEach(ce=>{Z.has(ce)&&Y.add(ce)}),Y})}};return window.addEventListener("background-dispatch",C),()=>window.removeEventListener("background-dispatch",C)},[e]),r.jsxs(sJ.Provider,{value:{showToast:g,showPersistentToast:w,dismissToast:b,setViewportSuppressed:l},children:[t,r.jsx("div",{className:`fixed bottom-4 right-20 z-[60] flex flex-col items-end gap-2 ${o?"hidden":""}`,children:n.map(S=>r.jsx("div",{className:`rounded-lg border shadow-lg backdrop-blur-sm animate-slide-in ${Wve[S.type]} ${S.dispatchData?"w-[420px] p-3":"flex items-center gap-3 px-4 py-3"}`,children:S.dispatchData?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[_6[S.type],r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm font-medium",children:e("backgroundDispatch.startingPrints")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:e("backgroundDispatch.progressSummary",{complete:S.dispatchData.completed+S.dispatchData.failed,total:S.dispatchData.total,dispatched:S.dispatchData.dispatched,processing:S.dispatchData.processing})})]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s(k=>!k),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e(i?"backgroundDispatch.expandDetails":"backgroundDispatch.collapseDetails"),children:i?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(S.id),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e("backgroundDispatch.dismissToast"),children:r.jsx(Vt,{className:"w-4 h-4"})})]})]}),!i&&r.jsx("div",{className:"mt-3 space-y-2 max-h-64 overflow-y-auto pr-1",children:S.dispatchData.jobs.map(k=>{const C={dispatched:15,processing:60,completed:100,failed:100,cancelled:100},P=k.status==="processing"&&typeof k.uploadProgressPct=="number"&&k.uploadProgressPct>=99.9,T={dispatched:"bg-bambu-gray/60",processing:"bg-bambu-green",completed:"bg-green-500",failed:"bg-red-500",cancelled:"bg-yellow-500"};return r.jsxs("div",{className:"rounded border border-white/10 bg-black/15 p-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-xs text-white truncate",title:k.sourceName,children:k.sourceName}),r.jsxs("div",{className:"flex items-center gap-2",children:[(k.status==="dispatched"||k.status==="processing")&&r.jsx("button",{onClick:()=>{x(k.jobId)},disabled:c.has(k.jobId),className:"text-[11px] text-red-300 hover:text-red-200 disabled:opacity-50 disabled:cursor-not-allowed",title:e("backgroundDispatch.cancelDispatchJob"),children:c.has(k.jobId)?e("backgroundDispatch.cancelling"):e("backgroundDispatch.cancel")}),r.jsx("span",{className:"text-[11px] uppercase tracking-wide text-bambu-gray",children:e(`backgroundDispatch.status.${k.status}`)})]})]}),r.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:k.printerName,children:k.printerName}),k.message&&r.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:k.message,children:k.message}),k.status==="processing"&&(P?r.jsx("div",{className:"text-[11px] text-bambu-gray truncate",children:e("backgroundDispatch.awaitingPrinter")}):typeof k.uploadBytes=="number"&&typeof k.uploadTotalBytes=="number"&&k.uploadTotalBytes>0?r.jsxs("div",{className:"text-[11px] text-bambu-gray truncate",children:[ls(k.uploadBytes)," / ",ls(k.uploadTotalBytes),typeof k.uploadProgressPct=="number"?` (${k.uploadProgressPct.toFixed(1)}%)`:""]}):null),r.jsx("div",{className:"mt-1 h-1.5 w-full rounded bg-white/10 overflow-hidden",children:r.jsx("div",{className:`h-full ${T[k.status]} transition-all duration-300 ${P?"animate-pulse":""}`,style:{width:`${k.status==="processing"&&typeof k.uploadProgressPct=="number"?Math.max(0,Math.min(100,k.uploadProgressPct)):C[k.status]}%`}})})]},k.jobId)})})]}):r.jsxs(r.Fragment,{children:[_6[S.type],r.jsx("span",{className:"text-white text-sm",children:S.message}),r.jsx("button",{onClick:()=>b(S.id),className:"ml-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-4 h-4"})})]})},S.id))})]})}function Qve(t="system"){const e=t==="system"?oJ():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 Yve(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 JF(t,e="system"){const n=String(t.getDate()).padStart(2,"0"),a=String(t.getMonth()+1).padStart(2,"0"),i=t.getFullYear();switch(e){case"us":return`${a}/${n}/${i}`;case"eu":return`${n}/${a}/${i}`;case"iso":return`${i}-${a}-${n}`;default:return t.toLocaleDateString()}}function k6(t,e="system"){const n=t.getHours(),a=String(t.getMinutes()).padStart(2,"0");switch(e){case"12h":{const i=n%12||12,s=n<12?"AM":"PM";return`${i}:${a} ${s}`}case"24h":return`${String(n).padStart(2,"0")}:${a}`;default:return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function Xve(t){for(const e of["/",".","-"]){const n=t.split(e);if(n.length===3)return n}return null}function oJ(){const t=new Date(2e3,11,31).toLocaleDateString();return t.startsWith("12")?"us":t.startsWith("31")?"eu":"iso"}function Zve(t,e="system"){if(!t)return null;const n=Xve(t);if(!n)return null;const a=e==="system"?oJ():e;let i,s,o;switch(a){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 Jve(t){if(!t)return null;const n=t.trim().match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);if(!n)return null;let a=parseInt(n[1],10);const i=parseInt(n[2],10),s=n[3]?.toUpperCase();return s==="PM"&&a<12&&(a+=12),s==="AM"&&a===12&&(a=0),a<0||a>23||i<0||i>59?null:{hours:a,minutes:i}}function eL(t){const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0"),i=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}-${n}-${a}T${i}:${s}`}function Lw(t,e="system"){return e==="12h"?t.hour12=!0:e==="24h"&&(t.hour12=!1),t}function Yn(t){return t?t.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(t)?new Date(t):new Date(t+"Z"):null}function Dg(t,e){const n=Yn(t);if(!n)return"";const a={year:"numeric",month:"short",day:"numeric"};return n.toLocaleDateString(void 0,e??a)}function Fg(t,e="system",n){const a=Yn(t);if(!a)return"";const s=Lw(n??{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},e);return a.toLocaleString(void 0,s)}function lJ(t,e="system",n){const i=Lw({...{hour:"2-digit",minute:"2-digit"},...n},e);return t.toLocaleTimeString([],i)}function MO(t,e="system",n){const a=new Date,i=new Date(a.getTime()+t*60*1e3),s=new Date(a);s.setHours(0,0,0,0);const o=new Date(i);o.setHours(0,0,0,0);const l=Lw({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 cs(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 Eh(t,e="system",n){if(!t)return n?.("time.unknown")??"-";const a=Yn(t);if(!a)return n?.("time.unknown")??"-";const i=new Date,s=a.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`:Fg(t,e)}function nh(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function e0e(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function dE(t){const e=typeof t=="string"?Yn(t):t;if(!e)return"";const n=e.getFullYear(),a=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${n}-${a}-${i}`}const uE=1920,t0e=.7,n0e=300;function r0e(t){return new Promise((e,n)=>{const a=new Image;a.onload=()=>{let{width:i,height:s}=a;if(i>uE||s>uE){const d=uE/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(a,0,0,i,s);const c=o.toDataURL("image/jpeg",t0e);e(c.replace(/^data:[^;]+;base64,/,""))},a.onerror=n,a.src=URL.createObjectURL(t)})}function a0e(t){const e=Math.floor(t/60),n=t%60;return`${e.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}function i0e(){const{t}=_t(),[e,n]=y.useState(!1),[a,i]=y.useState("form"),[s,o]=y.useState(""),[l,c]=y.useState(""),[d,u]=y.useState(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),[w,b]=y.useState(null),[x,S]=y.useState(""),[k,C]=y.useState(0),[P,T]=y.useState(!1),A=y.useRef(null),F=y.useRef(null),_=y.useRef(()=>{});y.useEffect(()=>{if(a!=="logging")return;if(k>=n0e){_.current();return}const oe=setTimeout(()=>C(Q=>Q+1),1e3);return()=>clearTimeout(oe)},[a,k]);const M=()=>{n(!0),i("form"),o(""),c(""),u(null),g(null),b(null),S(""),C(0),T(!1)},H=()=>{n(!1)},I=y.useCallback(async oe=>{if(oe.type.startsWith("image/"))try{const Q=await r0e(oe);u(Q)}catch{}},[]),z=y.useCallback(oe=>{const Q=oe.clipboardData?.items;if(Q){for(const le of Q)if(le.type.startsWith("image/")){const pe=le.getAsFile();pe&&I(pe);break}}},[I]),L=y.useCallback(oe=>{oe.preventDefault(),p(!0)},[]),Z=y.useCallback(oe=>{oe.preventDefault(),p(!1)},[]),ne=y.useCallback(oe=>{oe.preventDefault(),p(!1);const Q=oe.dataTransfer.files?.[0];Q&&I(Q)},[I]),Y=async()=>{if(s.trim())try{const oe=await cE.startLogging();T(oe.was_debug),C(0),i("logging")}catch(oe){S(oe instanceof Error?oe.message:t("bugReport.unexpectedError")),i("error")}},ce=async()=>{i("stopping");try{const oe=await cE.stopLogging(P);await ue(oe.logs)}catch(oe){S(oe instanceof Error?oe.message:t("bugReport.unexpectedError")),i("error")}};_.current=ce;const ue=async oe=>{i("submitting");try{const Q=await cE.submit({description:s.trim(),email:l.trim()||void 0,screenshot_base64:d||void 0,include_support_info:!0,debug_logs:oe||void 0});Q.success?(g(Q.issue_url||null),b(Q.issue_number||null),i("success")):(S(Q.message),i("error"))}catch(Q){S(Q instanceof Error?Q.message:t("bugReport.unexpectedError")),i("error")}};return r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:M,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:r.jsx(gy,{className:"w-5 h-5"})}),e&&r.jsx("div",{id:"bug-report-modal",className:"fixed bottom-20 right-4 z-50 w-full max-w-md",onPaste:z,children:r.jsxs("div",{ref:A,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:[r.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:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2",children:[r.jsx(gy,{className:"w-5 h-5 text-red-500"}),t("bugReport.title")]}),r.jsx("button",{onClick:H,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[a==="form"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:[t("bugReport.description")," *"]}),r.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.email")}),r.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"}),r.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:t("bugReport.emailPrivacy")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:t("bugReport.screenshot")}),d?r.jsxs("div",{className:"relative",children:[r.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"}),r.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:r.jsx(en,{className:"w-3 h-3"})})]}):r.jsxs("button",{type:"button",onClick:()=>F.current?.click(),onDragOver:L,onDragLeave:Z,onDrop:ne,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:[r.jsx(_a,{className:"w-5 h-5"}),r.jsx("span",{className:"text-sm",children:t("bugReport.uploadOrPaste")})]}),r.jsx("input",{ref:F,type:"file",accept:"image/*",className:"hidden",onChange:oe=>{const Q=oe.target.files?.[0];Q&&I(Q),oe.target.value=""}})]}),r.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:[r.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")}),r.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:[r.jsx("p",{className:"font-medium",children:t("bugReport.dataIncluded")}),r.jsx("p",{children:t("bugReport.dataIncludedList")}),r.jsx("p",{className:"font-medium",children:t("bugReport.dataNeverIncluded")}),r.jsx("p",{children:t("bugReport.dataNeverIncludedList")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.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")}),r.jsx("button",{onClick:Y,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")})]})]}),a==="logging"&&r.jsxs("div",{className:"py-6 space-y-6",children:[r.jsxs("div",{className:"space-y-3 px-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(yl,{className:"w-5 h-5 text-green-500 flex-shrink-0"}),r.jsx("span",{className:"text-sm text-green-700 dark:text-green-400",children:t("bugReport.stepEnableLogging")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"relative flex h-5 w-5 flex-shrink-0 items-center justify-center",children:[r.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),r.jsx("span",{className:"relative inline-flex rounded-full h-3 w-3 bg-blue-500"})]}),r.jsx("span",{className:"text-sm font-medium text-blue-700 dark:text-blue-300",children:t("bugReport.stepReproduce")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Mw,{className:"w-5 h-5 text-gray-300 dark:text-gray-600 flex-shrink-0"}),r.jsx("span",{className:"text-sm text-gray-400 dark:text-gray-500",children:t("bugReport.stepStopLogging")})]})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("p",{className:"text-3xl font-mono text-blue-500",children:a0e(k)}),r.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:t("bugReport.maxDuration",{minutes:5})})]}),r.jsx("div",{className:"flex justify-center",children:r.jsx("button",{onClick:ce,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")})})]}),(a==="stopping"||a==="submitting")&&r.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[r.jsx(ft,{className:"w-8 h-8 animate-spin text-blue-500"}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t(a==="stopping"?"bugReport.stoppingLogs":"bugReport.submitting")})]}),a==="success"&&r.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[r.jsx(xr,{className:"w-12 h-12 text-green-500"}),r.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.thankYou")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("bugReport.submitted")}),f&&r.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-500 hover:text-blue-600 underline",children:[t("bugReport.viewIssue")," #",w]}),r.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")})]}),a==="error"&&r.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[r.jsx(Ha,{className:"w-12 h-12 text-red-500"}),r.jsx("p",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:t("bugReport.submitFailed")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center",children:x}),r.jsxs("div",{className:"flex gap-2 mt-4",children:[r.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")}),r.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 wm=[{id:"printers",to:"/",icon:hr,labelKey:"nav.printers"},{id:"inventory",to:"/inventory",icon:Yge,labelKey:"nav.inventory"},{id:"archives",to:"/archives",icon:eo,labelKey:"nav.archives"},{id:"queue",to:"/queue",icon:Ew,labelKey:"nav.queue"},{id:"projects",to:"/projects",icon:to,labelKey:"nav.projects"},{id:"files",to:"/files",icon:Pl,labelKey:"nav.files"},{id:"makerworld",to:"/makerworld",icon:Js,labelKey:"nav.makerworld"},{id:"profiles",to:"/profiles",icon:$h,labelKey:"nav.profiles"},{id:"maintenance",to:"/maintenance",icon:Gh,labelKey:"nav.maintenance"},{id:"stats",to:"/stats",icon:RZ,labelKey:"nav.stats"},{id:"notifications",to:"/notifications",icon:Ch,labelKey:"nav.notifications"},{id:"settings",to:"/settings",icon:xy,labelKey:"nav.settings"}];function s0e(){const t=localStorage.getItem("sidebarOrder");if(t)try{return JSON.parse(t)}catch{return wm.map(e=>e.id)}return wm.map(e=>e.id)}function N6(t){localStorage.setItem("sidebarOrder",JSON.stringify(t))}function Pk(t){return t.startsWith("ext-")}function cJ(){return localStorage.getItem("defaultView")||"/"}function o0e(t){localStorage.setItem("defaultView",t)}function l0e(){const t=ji(),e=bd(),{mode:n,toggleMode:a}=ob(),{t:i}=_t(),s=qve();aJ();const{user:o,authEnabled:l,logout:c,hasPermission:d}=dr(),{showToast:u}=on(),[m,p]=y.useState(!1),[f,g]=y.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[w,b]=y.useState(!1),[x,S]=y.useState(()=>localStorage.getItem("sidebarExpanded")!=="false"),[k,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,M]=y.useState(s0e),[H,I]=y.useState(null),[z,L]=y.useState(null),Z=y.useRef(!1),[ne,Y]=y.useState(()=>sessionStorage.getItem("dismissedUpdateVersion")),[ce,ue]=y.useState(null),{data:oe}=Xe({queryKey:["version"],queryFn:ae.getVersion,staleTime:1/0}),{data:Q}=Xe({queryKey:["settings"],queryFn:ae.getSettings,staleTime:300*1e3}),{data:le}=Xe({queryKey:["default-sidebar-order"],queryFn:ae.getDefaultSidebarOrder,staleTime:300*1e3});y.useEffect(()=>{const ge=le?.default_sidebar_order;if(!ge||l&&!o)return;const Me=o?`sidebarDefaultApplied_${o.id}`:"sidebarDefaultApplied";if(!localStorage.getItem(Me))try{const Be=JSON.parse(ge),Fe=Array.isArray(Be)?Be:Be.order;if(!Array.isArray(Fe)||Fe.length===0)return;const Oe=new Set(wm.map(We=>We.id)),Re=Fe.filter(We=>typeof We=="string"&&(Oe.has(We)||Pk(We)));Re.length>0&&(M(Re),N6(Re),localStorage.setItem(Me,"1"))}catch(Be){console.error("Failed to apply default sidebar order:",Be)}},[le?.default_sidebar_order,M,o,l]);const{data:pe}=Xe({queryKey:["advancedAuthStatus"],queryFn:ae.getAdvancedAuthStatus,staleTime:300*1e3,enabled:l}),{data:he}=Xe({queryKey:["updateCheck"],queryFn:ae.checkForUpdates,enabled:Q?.check_updates!==!1,staleTime:3600*1e3,refetchInterval:3600*1e3}),{data:we}=Xe({queryKey:["external-links"],queryFn:ae.getExternalLinks}),{data:$}=Xe({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs,staleTime:30*1e3}),J=$?.some(ge=>ge.show_in_switchbar)??!1,{data:j}=Xe({queryKey:["debugLogging"],queryFn:ny.getDebugLoggingState,staleTime:60*1e3,refetchInterval:60*1e3}),{data:E}=Xe({queryKey:["developer-mode-warnings"],queryFn:ae.getDeveloperModeWarnings,staleTime:10*1e3,refetchInterval:30*1e3,refetchOnWindowFocus:!0}),{data:B}=Xe({queryKey:["queue","pending"],queryFn:()=>ae.getQueue(void 0,"pending"),staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),W=B?.length??0,{data:O}=Xe({queryKey:["pending-uploads","count"],queryFn:Ox.getCount,staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),ie=O?.count??0,U=y.useMemo(()=>{const ge=new Set;return B?.forEach(Me=>{Me.printer_id&&ge.add(Me.printer_id)}),Array.from(ge)},[B]),K=rf({queries:U.map(ge=>({queryKey:["printerStatus",ge],queryFn:()=>ae.getPrinterStatus(ge),staleTime:30*1e3}))}).some(ge=>{const Me=ge.data;return Me?!!Me.awaiting_plate_clear:!1}),[X,se]=y.useState(null);y.useEffect(()=>{if(!j?.enabled||!j.enabled_at){se(null);return}const ge=Yn(j.enabled_at)?.getTime()??Date.now(),Me=()=>{se(Math.floor((Date.now()-ge)/1e3))};Me();const Be=setInterval(Me,1e3);return()=>clearInterval(Be)},[j?.enabled,j?.enabled_at]);const te=y.useMemo(()=>new Map(wm.map(ge=>[ge.id,ge])),[]),fe=y.useMemo(()=>new Map((we||[]).map(ge=>[`ext-${ge.id}`,ge])),[we]),de=(()=>{const ge=[],Me=new Set,Be={archives:"archives:read",queue:"queue:read",stats:"stats:read",profiles:"kprofiles:read",maintenance:"maintenance:read",projects:"projects:read",inventory:"inventory:read",files:"library:read",makerworld:"makerworld:view",settings:"settings:read",notifications:"notifications:user_email"},Fe=Oe=>!!(l&&Oe in Be&&!d(Be[Oe])||Oe==="notifications"&&(!l||!pe?.advanced_auth_enabled||Q?.user_notifications_enabled===!1));for(const Oe of _)Fe(Oe)||(te.has(Oe)||fe.has(Oe))&&(ge.push(Oe),Me.add(Oe));for(const Oe of wm)Fe(Oe.id)||Me.has(Oe.id)||(ge.push(Oe.id),Me.add(Oe.id));for(const Oe of we||[]){const Re=`ext-${Oe.id}`;Me.has(Re)||(ge.push(Re),Me.add(Re))}return ge})(),me=(ge,Me)=>{I(Me),ge.dataTransfer.effectAllowed="move",ge.dataTransfer.setData("text/plain",Me)},q=(ge,Me)=>{ge.preventDefault(),ge.dataTransfer.dropEffect="move",L(Me)},R=()=>{L(null)},re=(ge,Me)=>{if(ge.preventDefault(),H===null||H===Me){I(null),L(null);return}const Be=[...de],Fe=Be.indexOf(H),Oe=Be.indexOf(Me);if(Fe===-1||Oe===-1){I(null),L(null);return}Be.splice(Fe,1),Be.splice(Oe,0,H),M(Be),N6(Be),I(null),L(null)},be=()=>{I(null),L(null)},ye=he?.update_available&&he.latest_version&&he.latest_version!==ne&&!he.is_ha_addon,_e=()=>{he?.latest_version&&(sessionStorage.setItem("dismissedUpdateVersion",he.latest_version),Y(he.latest_version))};y.useEffect(()=>{if(!Z.current&&e.pathname==="/"){const ge=cJ();ge!=="/"&&(Z.current=!0,t(ge,{replace:!0}))}},[e.pathname,t]),y.useEffect(()=>{localStorage.setItem("sidebarExpanded",String(x))},[x]),y.useEffect(()=>{s&&C(!1)},[e.pathname,s]),y.useEffect(()=>{const ge=Me=>{if(!d("printers:control"))return;const Be=Me.detail;ue({printer_id:Be.printer_id,printer_name:Be.printer_name,message:Be.message})};return window.addEventListener("plate-not-empty",ge),()=>window.removeEventListener("plate-not-empty",ge)},[d]);const xe=y.useCallback(ge=>{const Me=ge.target;if(!(Me.tagName==="INPUT"||Me.tagName==="TEXTAREA"||Me.isContentEditable)&&!ge.metaKey&&!ge.ctrlKey&&!ge.altKey){const Be=parseInt(ge.key);if(Be>=1&&Be<=de.length&&Be<=9){const Fe=de[Be-1];if(ge.preventDefault(),Pk(Fe)){const Oe=fe.get(Fe);if(Oe?.open_in_new_tab)window.open(Oe.url,"_blank","noopener,noreferrer");else{const Re=Fe.replace("ext-","");t(`/external/${Re}`)}}else{const Oe=te.get(Fe);Oe&&t(Oe.to)}return}switch(ge.key){case"?":ge.preventDefault(),T(!0);break;case"Escape":T(!1);break}}},[t,de,te,fe]);return y.useEffect(()=>(document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)),[xe]),r.jsxs("div",{className:"flex min-h-screen",children:[s&&r.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:[r.jsx("button",{onClick:()=>C(!0),className:"p-2 -ml-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors","aria-label":"Open menu",children:r.jsx(Lxe,{className:"w-6 h-6 text-white"})}),r.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-8 ml-3"})]}),s&&k&&r.jsx("div",{className:"fixed inset-0 bg-black/60 z-40 transition-opacity",onClick:()=>C(!1)}),r.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 ${k?"translate-x-0":"-translate-x-full"}`:`fixed inset-y-0 left-0 z-30 ${x?"w-64":"w-16"}`}`,children:[r.jsx("div",{className:`border-b border-bambu-dark-tertiary flex items-center justify-center ${s||x?"p-4":"p-2"}`,children:r.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:s||x?"h-16 w-auto":"h-8 w-8 object-cover object-left"})}),r.jsx("nav",{className:"flex-1 p-2 overflow-y-auto",children:r.jsx("ul",{className:"space-y-2",children:de.map(ge=>{if(Pk(ge)){const Be=fe.get(ge);if(!Be)return null;const Fe=Be.custom_icon?null:TT(Be.icon);return r.jsx("li",{draggable:!0,onDragStart:Oe=>me(Oe,ge),onDragOver:Oe=>q(Oe,ge),onDragLeave:R,onDrop:Oe=>re(Oe,ge),onDragEnd:be,className:`relative ${H===ge?"opacity-50":""} ${z===ge&&H!==ge?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:Be.open_in_new_tab?r.jsxs("a",{href:Be.url,target:"_blank",rel:"noopener noreferrer",className:`flex items-center ${s||x?"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&&!x?Be.name:void 0,children:[x&&!s&&r.jsx(Ah,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Be.custom_icon?r.jsx("img",{src:ae.getExternalLinkIconUrl(Be.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Fe&&r.jsx(Fe,{className:"w-5 h-5 flex-shrink-0"}),(s||x)&&r.jsx("span",{children:Be.name})]}):r.jsxs(Vx,{to:`/external/${Be.id}`,className:({isActive:Oe})=>`flex items-center ${s||x?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Oe?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!x?Be.name:void 0,children:[x&&!s&&r.jsx(Ah,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),Be.custom_icon?r.jsx("img",{src:ae.getExternalLinkIconUrl(Be.id),alt:"",className:"w-5 h-5 flex-shrink-0"}):Fe&&r.jsx(Fe,{className:"w-5 h-5 flex-shrink-0"}),(s||x)&&r.jsx("span",{children:Be.name})]})},ge)}else{const Be=te.get(ge);if(!Be)return null;const{to:Fe,icon:Oe,labelKey:Re}=Be,We=ge==="queue"&&W>0,ze=ge==="archives"&&ie>0,st=We?W:ze?ie:0,Ee=We||ze,it=ge==="printers"&&K;return r.jsx("li",{draggable:!0,onDragStart:Ce=>me(Ce,ge),onDragOver:Ce=>q(Ce,ge),onDragLeave:R,onDrop:Ce=>re(Ce,ge),onDragEnd:be,className:`relative ${H===ge?"opacity-50":""} ${z===ge&&H!==ge?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:r.jsxs(Vx,{to:Fe,className:({isActive:Ce})=>`flex items-center ${s||x?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Ce?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!x?i(Re):void 0,children:[x&&!s&&r.jsx(Ah,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),r.jsxs("div",{className:"relative",children:[r.jsx(Oe,{className:"w-5 h-5 flex-shrink-0"}),it&&r.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"}),Ee&&r.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 ${ze?"bg-blue-500 text-white":"bg-yellow-500 text-black"}`,children:st>99?"99+":st})]}),(s||x)&&r.jsx("span",{children:i(Re)})]})},ge)}})})}),!s&&r.jsx("button",{onClick:()=>S(!x),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(x?"nav.collapseSidebar":"nav.expandSidebar"),children:x?r.jsx(Xo,{className:"w-5 h-5"}):r.jsx(qa,{className:"w-5 h-5"})}),r.jsx("div",{className:"flex-shrink-0 p-2 border-t border-bambu-dark-tertiary",children:s||x?r.jsxs("div",{className:"flex flex-col gap-2 px-2",children:[r.jsxs("div",{className:"flex items-center justify-center gap-1 flex-wrap",children:[J&&r.jsxs("div",{className:"relative",children:[r.jsx("button",{onMouseEnter:()=>F(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${A?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:r.jsx(hc,{className:"w-5 h-5"})}),A&&r.jsx(y6,{onClose:()=>F(!1)})]}),d("system:read")?r.jsx(Vx,{to:"/system",className:({isActive:ge})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ge?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:r.jsx(_i,{className:"w-5 h-5"})}):r.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:r.jsx(_i,{className:"w-5 h-5"})}),r.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:r.jsx(VF,{className:"w-5 h-5"})}),r.jsx("button",{onClick:()=>T(!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:r.jsx(GF,{className:"w-5 h-5"})}),r.jsx("button",{onClick:a,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"?r.jsx(g6,{className:"w-5 h-5"}):r.jsx(aC,{className:"w-5 h-5"})}),l&&o&&r.jsxs(r.Fragment,{children:[r.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:r.jsx(bo,{className:"w-5 h-5"})}),r.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:r.jsx(ty,{className:"w-5 h-5"})})]})]}),r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:["v",oe?.version||"..."]}),he?.update_available&&r.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:he.latest_version}),children:[r.jsx(oE,{className:"w-4 h-4"}),r.jsx("span",{children:i("nav.update")})]})]})]}):r.jsxs("div",{className:"flex flex-col items-center gap-1 overflow-y-auto max-h-[50vh]",children:[he?.update_available&&r.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:he.latest_version}),children:r.jsx(oE,{className:"w-5 h-5"})}),J&&r.jsxs("div",{className:"relative",children:[r.jsx("button",{onMouseEnter:()=>F(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${A?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:r.jsx(hc,{className:"w-5 h-5"})}),A&&r.jsx(y6,{onClose:()=>F(!1)})]}),d("system:read")?r.jsx(Vx,{to:"/system",className:({isActive:ge})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${ge?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:i("nav.system"),children:r.jsx(_i,{className:"w-5 h-5"})}):r.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:r.jsx(_i,{className:"w-5 h-5"})}),r.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:r.jsx(VF,{className:"w-5 h-5"})}),r.jsx("button",{onClick:()=>T(!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:r.jsx(GF,{className:"w-5 h-5"})}),r.jsx("button",{onClick:a,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"?r.jsx(g6,{className:"w-5 h-5"}):r.jsx(aC,{className:"w-5 h-5"})}),l&&o&&r.jsxs(r.Fragment,{children:[r.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:r.jsx(bo,{className:"w-5 h-5"})}),r.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:r.jsx(ty,{className:"w-5 h-5"})})]})]})})]}),r.jsxs("main",{className:`flex-1 bg-bambu-dark overflow-auto transition-all duration-300 ${s?"mt-14":x?"ml-64":"ml-16"}`,children:[j?.enabled&&r.jsx("div",{className:"bg-amber-500/20 border-b border-amber-500/30 px-4 py-2 flex items-center justify-between",children:r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(gy,{className:"w-4 h-4 text-amber-500 animate-pulse"}),r.jsxs("span",{className:"text-amber-200",children:[i("support.debugLoggingActive",{defaultValue:"Debug logging is active"}),X!==null&&r.jsxs("span",{className:"text-amber-300/70 ml-2",children:["(",Math.floor(X/60),"m ",X%60,"s)"]})]}),r.jsx("button",{onClick:()=>t("/system"),className:"text-amber-400 hover:text-amber-300 font-medium underline ml-2",children:i("support.manageLogs",{defaultValue:"Manage"})})]})}),E&&E.length>0&&r.jsx("div",{className:"bg-orange-500/20 border-b border-orange-500/30 px-4 py-2 flex items-center justify-between",children:r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Pye,{className:"w-4 h-4 text-orange-500"}),r.jsx("span",{className:"text-orange-200",children:i("printers.developerModeWarning",{names:E.map(ge=>ge.name).join(", "),defaultValue:`Developer LAN mode is not enabled on: ${E.map(ge=>ge.name).join(", ")}. Some features may not work.`})}),r.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"})})]})}),ye&&r.jsxs("div",{className:"bg-bambu-green/20 border-b border-bambu-green/30 px-4 py-2 flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(oE,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{children:i("nav.updateAvailableBanner",{version:he?.latest_version,defaultValue:`Version ${he?.latest_version} is available!`})}),r.jsx("button",{onClick:()=>t("/settings"),className:"text-bambu-green hover:text-bambu-green/80 font-medium underline",children:i("nav.viewUpdate",{defaultValue:"View update"})})]}),r.jsx("button",{onClick:_e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:i("common.dismiss",{defaultValue:"Dismiss"}),children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsx(mZ,{})]}),P&&r.jsx(Uve,{onClose:()=>T(!1),sidebarItems:de.map(ge=>{if(Pk(ge)){const Me=fe.get(ge);return Me?{type:"external",label:Me.name}:null}else{const Me=te.get(ge);return Me?{type:"nav",label:Me.labelKey,labelKey:Me.labelKey}:null}}).filter(Boolean)}),ce&&r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4",children:r.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:r.jsxs("div",{className:"p-6 text-center",children:[r.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center",children:r.jsx("svg",{className:"w-10 h-10 text-yellow-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:r.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"})})}),r.jsx("h2",{className:"text-xl font-bold text-yellow-400 mb-2",children:i("plateAlert.title")}),r.jsx("p",{className:"text-lg text-white mb-2",children:ce.printer_name}),r.jsx("p",{className:"text-bambu-gray mb-6",children:i("plateAlert.message")}),r.jsx("button",{onClick:()=>ue(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&&r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{p(!1),g({currentPassword:"",newPassword:"",confirmPassword:""})},children:r.jsxs(At,{className:"w-full max-w-md",onClick:ge=>ge.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(bo,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("changePassword.title")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{p(!1),g({currentPassword:"",newPassword:"",confirmPassword:""})},children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsxs(Et,{children:[r.jsxs("div",{className:"space-y-4",children:[r.jsx("input",{type:"text",name:"username",autoComplete:"username",value:o?.username??"",readOnly:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.currentPassword")}),r.jsx("input",{type:"password",value:f.currentPassword,onChange:ge=>g({...f,currentPassword:ge.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.newPassword")}),r.jsx("input",{type:"password",value:f.newPassword,onChange:ge=>g({...f,newPassword:ge.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("changePassword.confirmPassword")}),r.jsx("input",{type:"password",value:f.confirmPassword,onChange:ge=>g({...f,confirmPassword:ge.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&&r.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("changePassword.passwordsDoNotMatch")})]})]}),r.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{p(!1),g({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),r.jsx(je,{onClick:async()=>{if(f.newPassword!==f.confirmPassword){u(i("changePassword.passwordsDoNotMatch"),"error");return}if(f.newPassword.length<6){u(i("changePassword.passwordTooShort"),"error");return}b(!0);try{await ae.changePassword(f.currentPassword,f.newPassword),u(i("changePassword.success"),"success"),p(!1),g({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ge){const Me=ge instanceof Error?ge.message:i("changePassword.failed");u(Me,"error")}finally{b(!1)}},disabled:w||!f.currentPassword||!f.newPassword||f.newPassword!==f.confirmPassword||f.newPassword.length<6,children:w?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("changePassword.changing")]}):r.jsxs(r.Fragment,{children:[r.jsx(bo,{className:"w-4 h-4"}),i("changePassword.title")]})})]})]})]})}),r.jsx(i0e,{})]})}function c0e(t,e){const n=t.split(".").map(i=>parseInt(i,10)||0),a=e.split(".").map(i=>parseInt(i,10)||0);for(;n.length<4;)n.push(0);for(;a.length<4;)a.push(0);for(let i=0;i<4;i++)if(n[i]!==a[i])return n[i]-a[i];return 0}function C6(t,e,n,a){if(!t)return"";if(a)return`${t} — ${a}`;if(!e)return t;const i=e.match(/plate_(\d+)\.gcode/);return i&&parseInt(i[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:i[1]})}`:t}function P6(t){const{triggerRect:e,popoverWidth:n,estimatedHeight:a,viewportHeight:i=window.innerHeight,viewportWidth:s=window.innerWidth,margin:o=8,gap:l=4}=t;let c=e.bottom+l;if(c+a>i-o){const m=e.top-l-a;m>=o&&(c=m)}let u=e.right-n;return u<o?u=o:u+n>s-o&&(u=Math.max(o,s-n-o)),{top:c,left:u}}const tL={"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 d0e(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:Nn};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:Nn};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:Ha};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:_i}}}function nL(t,e){const n=t>>16&65535||(t>>8&255)<<8|t&255,a=e&65535;return`${n.toString(16).padStart(4,"0").toUpperCase()}_${a.toString(16).padStart(4,"0").toUpperCase()}`}function Dm(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,a=nL(e.attr,n);return tL[a]!==void 0})}function u0e(){return"https://wiki.bambulab.com/en/hms/home"}function m0e({printerName:t,errors:e,onClose:n,printerId:a,hasPermission:i}){const{t:s}=_t(),{showToast:o}=on(),l=lt({mutationFn:()=>ae.clearHMSErrors(a),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=nL(d.attr,u);return tL[m]!==void 0});return y.useEffect(()=>{const d=u=>{u.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Nn,{className:"w-5 h-5 text-orange-400"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),r.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(Ha,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),r.jsx("p",{children:s("hmsErrors.noErrors")})]}):r.jsx("div",{className:"space-y-3",children:c.map((d,u)=>{const{label:m,color:p,bgColor:f,Icon:g}=d0e(d.severity),w=parseInt(d.code.replace("0x",""),16)||0,b=nL(d.attr,w),x=tL[b],S=u0e(),k=b.replace("_","-");return r.jsx("div",{className:`p-4 rounded-lg ${f} border border-white/10`,children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(g,{className:`w-5 h-5 ${p} flex-shrink-0 mt-0.5`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsxs("span",{className:`font-mono text-sm ${p}`,children:["[",k,"]"]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${f} ${p}`,children:m})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:x}),r.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[r.jsx(zr,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${d.code}-${u}`)})})}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&r.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?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}const p0e=[{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 h0e({selectedIds:t,printers:e,onClose:n,onSelectAll:a,onSelectByLocation:i,onSelectByState:s,onAction:o,actionPending:l}){const{t:c}=_t(),{hasPermission:d}=dr(),u=tn(),[m,p]=y.useState(!1),[f,g]=y.useState(!1),w=Array.from(t).map(M=>({id:M,status:u.getQueryData(["printerStatus",M])})),b=w.some(({status:M})=>M?.connected&&M.state==="RUNNING"),x=w.some(({status:M})=>M?.connected&&M.state==="PAUSE"),S=b||x,k=w.some(({status:M})=>!!(M?.connected&&M.awaiting_plate_clear)),C=w.some(({status:M})=>!M?.connected||!M.hms_errors?!1:Dm(M.hms_errors).length>0),P=d("printers:control"),T=d("printers:clear_plate"),A=[...new Set(e.map(M=>M.location).filter(M=>!!M))].sort(),F={printing:0,paused:0,finished:0,idle:0,error:0,offline:0};e.forEach(M=>{const H=u.getQueryData(["printerStatus",M.id]);if(!H||!H.connected){F.offline++;return}const I=H.hms_errors?Dm(H.hms_errors).length>0:!1;switch(I&&F.error++,H.state){case"RUNNING":F.printing++;break;case"PAUSE":F.paused++;break;case"FINISH":F.finished++;break;case"FAILED":I||F.finished++;break;default:F.idle++;break}});const _={printing:c("printers.status.printing"),paused:c("printers.status.paused","Paused"),finished:c("printers.status.finished","Finished"),idle:c("printers.status.idle"),error:c("printers.status.problem"),offline:c("printers.status.offline")};return r.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:[r.jsx(je,{variant:"secondary",size:"sm",onClick:n,children:r.jsx(Vt,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-white font-medium text-sm",children:c("printers.bulk.selected",{count:t.size})}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsx(je,{variant:"secondary",size:"sm",onClick:a,children:c("printers.bulk.selectAll")}),r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>{g(!f),p(!1)},children:[c("printers.bulk.selectByState"),r.jsx(Ln,{className:`w-3 h-3 transition-transform ${f?"rotate-180":""}`})]}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.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:p0e.filter(({key:M})=>F[M]>0).map(({key:M,dot:H})=>r.jsxs("button",{onClick:()=>{s(M),g(!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:[r.jsx("div",{className:`w-2 h-2 rounded-full ${H}`}),_[M],r.jsx("span",{className:"ml-auto text-bambu-gray text-xs",children:F[M]})]},M))})]})]}),A.length>0&&r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>{p(!m),g(!1)},children:[c("printers.bulk.selectByLocation"),r.jsx(Ln,{className:`w-3 h-3 transition-transform ${m?"rotate-180":""}`})]}),m&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),r.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:A.map(M=>r.jsx("button",{onClick:()=>{i(M),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:M},M))})]})]}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsxs(je,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>o("stop"),disabled:l||!P||!S,title:P?S?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[r.jsx(ro,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.stop")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>o("pause"),disabled:l||!P||!b,title:P?b?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[r.jsx(DS,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.pause")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>o("resume"),disabled:l||!P||!x,title:P?x?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[r.jsx(hs,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.resume")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>o("clearHMS"),disabled:l||!P||!C,title:P?C?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[r.jsx(FZ,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearHMS")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>o("clearPlate"),disabled:l||!T||!k,title:T?k?void 0:c("printers.bulk.noneApplicable"):c("printers.permission.noControl"),children:[r.jsx(SO,{className:"w-3.5 h-3.5"}),c("printers.bulk.actions.clearPlate")]})]})}const EO="181",ry={ROTATE:0,DOLLY:1,PAN:2},Gx={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},f0e=0,T6=1,g0e=2,dJ=1,b0e=2,dm=3,Wh=0,Wo=1,Qd=2,Fm=0,ay=1,A6=2,j6=3,M6=4,x0e=5,Zf=100,y0e=101,v0e=102,w0e=103,S0e=104,_0e=200,k0e=201,N0e=202,C0e=203,rL=204,aL=205,P0e=206,T0e=207,A0e=208,j0e=209,M0e=210,E0e=211,D0e=212,F0e=213,L0e=214,iL=0,sL=1,oL=2,yy=3,lL=4,cL=5,dL=6,uL=7,DO=0,R0e=1,I0e=2,Dh=0,O0e=1,z0e=2,U0e=3,B0e=4,H0e=5,q0e=6,$0e=7,uJ=300,vy=301,wy=302,mL=303,pL=304,jT=306,hL=1e3,Sm=1001,fL=1002,wl=1003,V0e=1004,Tk=1005,mc=1006,mE=1007,ig=1008,fu=1009,mJ=1010,pJ=1011,Rw=1012,FO=1013,Lg=1014,_m=1015,Yy=1016,LO=1017,RO=1018,Iw=1020,hJ=35902,fJ=35899,gJ=1021,bJ=1022,ld=1023,Ow=1026,zw=1027,xJ=1028,IO=1029,OO=1030,zO=1031,UO=1033,vN=33776,wN=33777,SN=33778,_N=33779,gL=35840,bL=35841,xL=35842,yL=35843,vL=36196,wL=37492,SL=37496,_L=37808,kL=37809,NL=37810,CL=37811,PL=37812,TL=37813,AL=37814,jL=37815,ML=37816,EL=37817,DL=37818,FL=37819,LL=37820,RL=37821,IL=36492,OL=36494,zL=36495,UL=36283,BL=36284,HL=36285,qL=36286,G0e=3200,W0e=3201,yJ=0,K0e=1,uh="",fl="srgb",Sy="srgb-linear",cC="linear",aa="srgb",Yb=7680,E6=519,Q0e=512,Y0e=513,X0e=514,vJ=515,Z0e=516,J0e=517,ewe=518,twe=519,D6=35044,F6="300 es",Jd=2e3,dC=2001;function wJ(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function uC(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function nwe(){const t=uC("canvas");return t.style.display="block",t}const L6={};function R6(...t){const e="THREE."+t.shift();console.log(e,...t)}function $n(...t){const e="THREE."+t.shift();console.warn(e,...t)}function di(...t){const e="THREE."+t.shift();console.error(e,...t)}function Uw(...t){const e=t.join(" ");e in L6||(L6[e]=!0,$n(...t))}function rwe(t,e,n){return new Promise(function(a,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:a()}}setTimeout(s,n)})}let lb=class{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const a=this._listeners;a[e]===void 0&&(a[e]=[]),a[e].indexOf(n)===-1&&a[e].push(n)}hasEventListener(e,n){const a=this._listeners;return a===void 0?!1:a[e]!==void 0&&a[e].indexOf(n)!==-1}removeEventListener(e,n){const a=this._listeners;if(a===void 0)return;const i=a[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 a=n[e.type];if(a!==void 0){e.target=this;const i=a.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}};const qs=["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"],kN=Math.PI/180,$L=180/Math.PI;function OS(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,a=Math.random()*4294967295|0;return(qs[t&255]+qs[t>>8&255]+qs[t>>16&255]+qs[t>>24&255]+"-"+qs[e&255]+qs[e>>8&255]+"-"+qs[e>>16&15|64]+qs[e>>24&255]+"-"+qs[n&63|128]+qs[n>>8&255]+"-"+qs[n>>16&255]+qs[n>>24&255]+qs[a&255]+qs[a>>8&255]+qs[a>>16&255]+qs[a>>24&255]).toLowerCase()}function br(t,e,n){return Math.max(e,Math.min(n,t))}function awe(t,e){return(t%e+e)%e}function pE(t,e,n){return(1-n)*t+n*e}function e0(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 zo(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 iwe={DEG2RAD:kN};let ir=class SJ{constructor(e=0,n=0){SJ.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,a=this.y,i=e.elements;return this.x=i[0]*n+i[3]*a+i[6],this.y=i[1]*n+i[4]*a+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=br(this.x,e.x,n.x),this.y=br(this.y,e.y,n.y),this}clampScalar(e,n){return this.x=br(this.x,e,n),this.y=br(this.y,e,n),this}clampLength(e,n){const a=this.length();return this.divideScalar(a||1).multiplyScalar(br(a,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 a=this.dot(e)/n;return Math.acos(br(a,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,a=this.y-e.y;return n*n+a*a}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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,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 a=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*a-o*i+e.x,this.y=s*i+o*a+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Rg=class{constructor(e=0,n=0,a=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=a,this._w=i}static slerpFlat(e,n,a,i,s,o,l){let c=a[i+0],d=a[i+1],u=a[i+2],m=a[i+3],p=s[o+0],f=s[o+1],g=s[o+2],w=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]=g,e[n+3]=w;return}if(m!==w||c!==p||d!==f||u!==g){let b=c*p+d*f+u*g+m*w;b<0&&(p=-p,f=-f,g=-g,w=-w,b=-b);let x=1-l;if(b<.9995){const S=Math.acos(b),k=Math.sin(S);x=Math.sin(x*S)/k,l=Math.sin(l*S)/k,c=c*x+p*l,d=d*x+f*l,u=u*x+g*l,m=m*x+w*l}else{c=c*x+p*l,d=d*x+f*l,u=u*x+g*l,m=m*x+w*l;const S=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=S,d*=S,u*=S,m*=S}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,a,i,s,o){const l=a[i],c=a[i+1],d=a[i+2],u=a[i+3],m=s[o],p=s[o+1],f=s[o+2],g=s[o+3];return e[n]=l*g+u*m+c*f-d*p,e[n+1]=c*g+u*p+d*m-l*f,e[n+2]=d*g+u*f+l*p-c*m,e[n+3]=u*g-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,a,i){return this._x=e,this._y=n,this._z=a,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 a=e._x,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(a/2),u=l(i/2),m=l(s/2),p=c(a/2),f=c(i/2),g=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m-p*f*g;break;case"YXZ":this._x=p*u*m+d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m+p*f*g;break;case"ZXY":this._x=p*u*m-d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m-p*f*g;break;case"ZYX":this._x=p*u*m-d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m+p*f*g;break;case"YZX":this._x=p*u*m+d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m-p*f*g;break;case"XZY":this._x=p*u*m-d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m+p*f*g;break;default:$n("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const a=n/2,i=Math.sin(a);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(a),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,a=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=a+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(a>l&&a>m){const f=2*Math.sqrt(1+a-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-a-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-a-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 a=e.dot(n)+1;return a<1e-8?(a=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=a):(this._x=0,this._y=-e.z,this._z=e.y,this._w=a)):(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=a),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(br(this.dot(e),-1,1)))}rotateTowards(e,n){const a=this.angleTo(e);if(a===0)return this;const i=Math.min(1,n/a);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 a=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=a*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-a*d,this._z=s*u+o*d+a*c-i*l,this._w=o*u-a*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n<=0)return this;if(n>=1)return this.copy(e);let a=e._x,i=e._y,s=e._z,o=e._w,l=this.dot(e);l<0&&(a=-a,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+a*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+a*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,a){return this.copy(e).slerp(n,a)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),a=Math.random(),i=Math.sqrt(1-a),s=Math.sqrt(a);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}},Lt=class _J{constructor(e=0,n=0,a=0){_J.prototype.isVector3=!0,this.x=e,this.y=n,this.z=a}set(e,n,a){return a===void 0&&(a=this.z),this.x=e,this.y=n,this.z=a,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(I6.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(I6.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,a=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*a+s[6]*i,this.y=s[1]*n+s[4]*a+s[7]*i,this.z=s[2]*n+s[5]*a+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,a=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*a+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*a+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*a+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*a+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,a=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*a),u=2*(l*n-s*i),m=2*(s*a-o*n);return this.x=n+c*d+o*m-l*u,this.y=a+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,a=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*a+s[8]*i,this.y=s[1]*n+s[5]*a+s[9]*i,this.z=s[2]*n+s[6]*a+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=br(this.x,e.x,n.x),this.y=br(this.y,e.y,n.y),this.z=br(this.z,e.z,n.z),this}clampScalar(e,n){return this.x=br(this.x,e,n),this.y=br(this.y,e,n),this.z=br(this.z,e,n),this}clampLength(e,n){const a=this.length();return this.divideScalar(a||1).multiplyScalar(br(a,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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,this.z=e.z+(n.z-e.z)*a,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const a=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-a*c,this.z=a*l-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const a=e.dot(this)/n;return this.copy(e).multiplyScalar(a)}projectOnPlane(e){return hE.copy(this).projectOnVector(e),this.sub(hE)}reflect(e){return this.sub(hE.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 a=this.dot(e)/n;return Math.acos(br(a,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,a=this.y-e.y,i=this.z-e.z;return n*n+a*a+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,a){const i=Math.sin(n)*e;return this.x=i*Math.sin(a),this.y=Math.cos(n)*e,this.z=i*Math.cos(a),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,a){return this.x=e*Math.sin(n),this.y=a,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(),a=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=a,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,a=Math.sqrt(1-n*n);return this.x=a*Math.cos(e),this.y=n,this.z=a*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};const hE=new Lt,I6=new Rg;let lr=class kJ{constructor(e,n,a,i,s,o,l,c,d){kJ.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,a,i,s,o,l,c,d)}set(e,n,a,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]=a,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,a=e.elements;return n[0]=a[0],n[1]=a[1],n[2]=a[2],n[3]=a[3],n[4]=a[4],n[5]=a[5],n[6]=a[6],n[7]=a[7],n[8]=a[8],this}extractBasis(e,n,a){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),a.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 a=e.elements,i=n.elements,s=this.elements,o=a[0],l=a[3],c=a[6],d=a[1],u=a[4],m=a[7],p=a[2],f=a[5],g=a[8],w=i[0],b=i[3],x=i[6],S=i[1],k=i[4],C=i[7],P=i[2],T=i[5],A=i[8];return s[0]=o*w+l*S+c*P,s[3]=o*b+l*k+c*T,s[6]=o*x+l*C+c*A,s[1]=d*w+u*S+m*P,s[4]=d*b+u*k+m*T,s[7]=d*x+u*C+m*A,s[2]=p*w+f*S+g*P,s[5]=p*b+f*k+g*T,s[8]=p*x+f*C+g*A,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],a=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-a*s*u+a*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],a=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,g=n*m+a*p+i*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const w=1/g;return e[0]=m*w,e[1]=(i*d-u*a)*w,e[2]=(l*a-i*o)*w,e[3]=p*w,e[4]=(u*n-i*c)*w,e[5]=(i*s-l*n)*w,e[6]=f*w,e[7]=(a*c-d*n)*w,e[8]=(o*n-a*s)*w,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,a,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(a*c,a*d,-a*(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(fE.makeScale(e,n)),this}rotate(e){return this.premultiply(fE.makeRotation(-e)),this}translate(e,n){return this.premultiply(fE.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),a=Math.sin(e);return this.set(n,-a,0,a,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,a=e.elements;for(let i=0;i<9;i++)if(n[i]!==a[i])return!1;return!0}fromArray(e,n=0){for(let a=0;a<9;a++)this.elements[a]=e[a+n];return this}toArray(e=[],n=0){const a=this.elements;return e[n]=a[0],e[n+1]=a[1],e[n+2]=a[2],e[n+3]=a[3],e[n+4]=a[4],e[n+5]=a[5],e[n+6]=a[6],e[n+7]=a[7],e[n+8]=a[8],e}clone(){return new this.constructor().fromArray(this.elements)}};const fE=new lr,O6=new lr().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),z6=new lr().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function swe(){const t={enabled:!0,workingColorSpace:Sy,spaces:{},convert:function(i,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===aa&&(i.r=Lm(i.r),i.g=Lm(i.g),i.b=Lm(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===aa&&(i.r=iy(i.r),i.g=iy(i.g),i.b=iy(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===uh?cC: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 Uw("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return Uw("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],a=[.3127,.329];return t.define({[Sy]:{primaries:e,whitePoint:a,transfer:cC,toXYZ:O6,fromXYZ:z6,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:fl},outputColorSpaceConfig:{drawingBufferColorSpace:fl}},[fl]:{primaries:e,whitePoint:a,transfer:aa,toXYZ:O6,fromXYZ:z6,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:fl}}}),t}const Or=swe();function Lm(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function iy(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let Xb,owe=class{static getDataURL(e,n="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let a;if(e instanceof HTMLCanvasElement)a=e;else{Xb===void 0&&(Xb=uC("canvas")),Xb.width=e.width,Xb.height=e.height;const i=Xb.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),a=Xb}return a.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=uC("canvas");n.width=e.width,n.height=e.height;const a=n.getContext("2d");a.drawImage(e,0,0,e.width,e.height);const i=a.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=Lm(s[o]/255)*255;return a.putImageData(i,0,0),n}else if(e.data){const n=e.data.slice(0);for(let a=0;a<n.length;a++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[a]=Math.floor(Lm(n[a]/255)*255):n[a]=Lm(n[a]);return{data:n,width:e.width,height:e.height}}else return $n("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},lwe=0,BO=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:lwe++}),this.uuid=OS(),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 a={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(gE(i[o].image)):s.push(gE(i[o]))}else s=gE(i);a.url=s}return n||(e.images[this.uuid]=a),a}};function gE(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?owe.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:($n("Texture: Unable to serialize Texture."),{})}let cwe=0;const bE=new Lt;let xd=class NN extends lb{constructor(e=NN.DEFAULT_IMAGE,n=NN.DEFAULT_MAPPING,a=Sm,i=Sm,s=mc,o=ig,l=ld,c=fu,d=NN.DEFAULT_ANISOTROPY,u=uh){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:cwe++}),this.uuid=OS(),this.name="",this.source=new BO(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=a,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new ir(0,0),this.repeat=new ir(1,1),this.center=new ir(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new lr,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(bE).x}get height(){return this.source.getSize(bE).y}get depth(){return this.source.getSize(bE).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 a=e[n];if(a===void 0){$n(`Texture.setValues(): parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){$n(`Texture.setValues(): property '${n}' does not exist.`);continue}i&&a&&i.isVector2&&a.isVector2||i&&a&&i.isVector3&&a.isVector3||i&&a&&i.isMatrix3&&a.isMatrix3?i.copy(a):this[n]=a}}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const a={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&&(a.userData=this.userData),n||(e.textures[this.uuid]=a),a}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==uJ)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case hL:e.x=e.x-Math.floor(e.x);break;case Sm:e.x=e.x<0?0:1;break;case fL: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 hL:e.y=e.y-Math.floor(e.y);break;case Sm:e.y=e.y<0?0:1;break;case fL: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++}};xd.DEFAULT_IMAGE=null;xd.DEFAULT_MAPPING=uJ;xd.DEFAULT_ANISOTROPY=1;let wi=class NJ{constructor(e=0,n=0,a=0,i=1){NJ.prototype.isVector4=!0,this.x=e,this.y=n,this.z=a,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,a,i){return this.x=e,this.y=n,this.z=a,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,a=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*a+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*a+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*a+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*a+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,a,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],g=c[9],w=c[2],b=c[6],x=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-w)<.01&&Math.abs(g-b)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+w)<.1&&Math.abs(g+b)<.1&&Math.abs(d+f+x-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const k=(d+1)/2,C=(f+1)/2,P=(x+1)/2,T=(u+p)/4,A=(m+w)/4,F=(g+b)/4;return k>C&&k>P?k<.01?(a=0,i=.707106781,s=.707106781):(a=Math.sqrt(k),i=T/a,s=A/a):C>P?C<.01?(a=.707106781,i=0,s=.707106781):(i=Math.sqrt(C),a=T/i,s=F/i):P<.01?(a=.707106781,i=.707106781,s=0):(s=Math.sqrt(P),a=A/s,i=F/s),this.set(a,i,s,n),this}let S=Math.sqrt((b-g)*(b-g)+(m-w)*(m-w)+(p-u)*(p-u));return Math.abs(S)<.001&&(S=1),this.x=(b-g)/S,this.y=(m-w)/S,this.z=(p-u)/S,this.w=Math.acos((d+f+x-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=br(this.x,e.x,n.x),this.y=br(this.y,e.y,n.y),this.z=br(this.z,e.z,n.z),this.w=br(this.w,e.w,n.w),this}clampScalar(e,n){return this.x=br(this.x,e,n),this.y=br(this.y,e,n),this.z=br(this.z,e,n),this.w=br(this.w,e,n),this}clampLength(e,n){const a=this.length();return this.divideScalar(a||1).multiplyScalar(br(a,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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,this.z=e.z+(n.z-e.z)*a,this.w=e.w+(n.w-e.w)*a,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}},dwe=class extends lb{constructor(e=1,n=1,a={}){super(),a=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:mc,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},a),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=a.depth,this.scissor=new wi(0,0,e,n),this.scissorTest=!1,this.viewport=new wi(0,0,e,n);const i={width:e,height:n,depth:a.depth},s=new xd(i);this.textures=[];const o=a.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(a),this.depthBuffer=a.depthBuffer,this.stencilBuffer=a.stencilBuffer,this.resolveDepthBuffer=a.resolveDepthBuffer,this.resolveStencilBuffer=a.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=a.depthTexture,this.samples=a.samples,this.multiview=a.multiview}_setTextureOptions(e={}){const n={minFilter:mc,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 a=0;a<this.textures.length;a++)this.textures[a].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,a=1){if(this.width!==e||this.height!==n||this.depth!==a){this.width=e,this.height=n,this.depth=a;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=a,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,a=e.textures.length;n<a;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 BO(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"})}},Ig=class extends dwe{constructor(e=1,n=1,a={}){super(e,n,a),this.isWebGLRenderTarget=!0}},CJ=class extends xd{constructor(e=null,n=1,a=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:a,depth:i},this.magFilter=wl,this.minFilter=wl,this.wrapR=Sm,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},uwe=class extends xd{constructor(e=null,n=1,a=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:a,depth:i},this.magFilter=wl,this.minFilter=wl,this.wrapR=Sm,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Fh=class{constructor(e=new Lt(1/0,1/0,1/0),n=new Lt(-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,a=e.length;n<a;n+=3)this.expandByPoint(Kc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,a=e.count;n<a;n++)this.expandByPoint(Kc.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,a=e.length;n<a;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const a=Kc.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(a),this.max.copy(e).add(a),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 a=e.geometry;if(a!==void 0){const s=a.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,Kc):Kc.fromBufferAttribute(s,o),Kc.applyMatrix4(e.matrixWorld),this.expandByPoint(Kc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ak.copy(e.boundingBox)):(a.boundingBox===null&&a.computeBoundingBox(),Ak.copy(a.boundingBox)),Ak.applyMatrix4(e.matrixWorld),this.union(Ak)}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,Kc),Kc.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,a;return e.normal.x>0?(n=e.normal.x*this.min.x,a=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,a=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,a+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,a+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,a+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,a+=e.normal.z*this.min.z),n<=-e.constant&&a>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(t0),jk.subVectors(this.max,t0),Zb.subVectors(e.a,t0),Jb.subVectors(e.b,t0),ex.subVectors(e.c,t0),Op.subVectors(Jb,Zb),zp.subVectors(ex,Jb),Ef.subVectors(Zb,ex);let n=[0,-Op.z,Op.y,0,-zp.z,zp.y,0,-Ef.z,Ef.y,Op.z,0,-Op.x,zp.z,0,-zp.x,Ef.z,0,-Ef.x,-Op.y,Op.x,0,-zp.y,zp.x,0,-Ef.y,Ef.x,0];return!xE(n,Zb,Jb,ex,jk)||(n=[1,0,0,0,1,0,0,0,1],!xE(n,Zb,Jb,ex,jk))?!1:(Mk.crossVectors(Op,zp),n=[Mk.x,Mk.y,Mk.z],xE(n,Zb,Jb,ex,jk))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Kc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Kc).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:(Ku[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ku[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ku[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ku[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ku[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ku[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ku[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ku[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ku),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 Ku=[new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt,new Lt],Kc=new Lt,Ak=new Fh,Zb=new Lt,Jb=new Lt,ex=new Lt,Op=new Lt,zp=new Lt,Ef=new Lt,t0=new Lt,jk=new Lt,Mk=new Lt,Df=new Lt;function xE(t,e,n,a,i){for(let s=0,o=t.length-3;s<=o;s+=3){Df.fromArray(t,s);const l=i.x*Math.abs(Df.x)+i.y*Math.abs(Df.y)+i.z*Math.abs(Df.z),c=e.dot(Df),d=n.dot(Df),u=a.dot(Df);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const mwe=new Fh,n0=new Lt,yE=new Lt;let MT=class{constructor(e=new Lt,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 a=this.center;n!==void 0?a.copy(n):mwe.setFromPoints(e).getCenter(a);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,a.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 a=this.center.distanceToSquared(e);return n.copy(e),a>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;n0.subVectors(e,this.center);const n=n0.lengthSq();if(n>this.radius*this.radius){const a=Math.sqrt(n),i=(a-this.radius)*.5;this.center.addScaledVector(n0,i/a),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):(yE.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(n0.copy(e.center).add(yE)),this.expandByPoint(n0.copy(e.center).sub(yE))),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 Qu=new Lt,vE=new Lt,Ek=new Lt,Up=new Lt,wE=new Lt,Dk=new Lt,SE=new Lt;let HO=class{constructor(e=new Lt,n=new Lt(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,Qu)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const a=n.dot(this.direction);return a<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,a)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=Qu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(Qu.copy(this.origin).addScaledVector(this.direction,n),Qu.distanceToSquared(e))}distanceSqToSegment(e,n,a,i){vE.copy(e).add(n).multiplyScalar(.5),Ek.copy(n).sub(e).normalize(),Up.copy(this.origin).sub(vE);const s=e.distanceTo(n)*.5,o=-this.direction.dot(Ek),l=Up.dot(this.direction),c=-Up.dot(Ek),d=Up.lengthSq(),u=Math.abs(1-o*o);let m,p,f,g;if(u>0)if(m=o*c-l,p=o*l-c,g=s*u,m>=0)if(p>=-g)if(p<=g){const w=1/u;m*=w,p*=w,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<=-g?(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<=g?(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 a&&a.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(vE).addScaledVector(Ek,p),f}intersectSphere(e,n){Qu.subVectors(e.center,this.origin);const a=Qu.dot(this.direction),i=Qu.dot(Qu)-a*a,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),l=a-o,c=a+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 a=-(this.origin.dot(e.normal)+e.constant)/n;return a>=0?a:null}intersectPlane(e,n){const a=this.distanceToPlane(e);return a===null?null:this.at(a,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let a,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?(a=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(a=(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),a>o||s>i||((s>a||isNaN(a))&&(a=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),a>c||l>i)||((l>a||a!==a)&&(a=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(a>=0?a:i,n)}intersectsBox(e){return this.intersectBox(e,Qu)!==null}intersectTriangle(e,n,a,i,s){wE.subVectors(n,e),Dk.subVectors(a,e),SE.crossVectors(wE,Dk);let o=this.direction.dot(SE),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Up.subVectors(this.origin,e);const c=l*this.direction.dot(Dk.crossVectors(Up,Dk));if(c<0)return null;const d=l*this.direction.dot(wE.cross(Up));if(d<0||c+d>o)return null;const u=-l*Up.dot(SE);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)}},Ci=class VL{constructor(e,n,a,i,s,o,l,c,d,u,m,p,f,g,w,b){VL.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,a,i,s,o,l,c,d,u,m,p,f,g,w,b)}set(e,n,a,i,s,o,l,c,d,u,m,p,f,g,w,b){const x=this.elements;return x[0]=e,x[4]=n,x[8]=a,x[12]=i,x[1]=s,x[5]=o,x[9]=l,x[13]=c,x[2]=d,x[6]=u,x[10]=m,x[14]=p,x[3]=f,x[7]=g,x[11]=w,x[15]=b,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 VL().fromArray(this.elements)}copy(e){const n=this.elements,a=e.elements;return n[0]=a[0],n[1]=a[1],n[2]=a[2],n[3]=a[3],n[4]=a[4],n[5]=a[5],n[6]=a[6],n[7]=a[7],n[8]=a[8],n[9]=a[9],n[10]=a[10],n[11]=a[11],n[12]=a[12],n[13]=a[13],n[14]=a[14],n[15]=a[15],this}copyPosition(e){const n=this.elements,a=e.elements;return n[12]=a[12],n[13]=a[13],n[14]=a[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,a){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),a.setFromMatrixColumn(this,2),this}makeBasis(e,n,a){return this.set(e.x,n.x,a.x,0,e.y,n.y,a.y,0,e.z,n.z,a.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,a=e.elements,i=1/tx.setFromMatrixColumn(e,0).length(),s=1/tx.setFromMatrixColumn(e,1).length(),o=1/tx.setFromMatrixColumn(e,2).length();return n[0]=a[0]*i,n[1]=a[1]*i,n[2]=a[2]*i,n[3]=0,n[4]=a[4]*s,n[5]=a[5]*s,n[6]=a[6]*s,n[7]=0,n[8]=a[8]*o,n[9]=a[9]*o,n[10]=a[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,a=e.x,i=e.y,s=e.z,o=Math.cos(a),l=Math.sin(a),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,g=l*u,w=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+g*d,n[5]=p-w*d,n[9]=-l*c,n[2]=w-p*d,n[6]=g+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,g=d*u,w=d*m;n[0]=p+w*l,n[4]=g*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-g,n[6]=w+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,g=d*u,w=d*m;n[0]=p-w*l,n[4]=-o*m,n[8]=g+f*l,n[1]=f+g*l,n[5]=o*u,n[9]=w-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,g=l*u,w=l*m;n[0]=c*u,n[4]=g*d-f,n[8]=p*d+w,n[1]=c*m,n[5]=w*d+p,n[9]=f*d-g,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,g=l*c,w=l*d;n[0]=c*u,n[4]=w-p*m,n[8]=g*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+g,n[10]=p-w*m}else if(e.order==="XZY"){const p=o*c,f=o*d,g=l*c,w=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+w,n[5]=o*u,n[9]=f*m-g,n[2]=g*m-f,n[6]=l*u,n[10]=w*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(pwe,e,hwe)}lookAt(e,n,a){const i=this.elements;return dl.subVectors(e,n),dl.lengthSq()===0&&(dl.z=1),dl.normalize(),Bp.crossVectors(a,dl),Bp.lengthSq()===0&&(Math.abs(a.z)===1?dl.x+=1e-4:dl.z+=1e-4,dl.normalize(),Bp.crossVectors(a,dl)),Bp.normalize(),Fk.crossVectors(dl,Bp),i[0]=Bp.x,i[4]=Fk.x,i[8]=dl.x,i[1]=Bp.y,i[5]=Fk.y,i[9]=dl.y,i[2]=Bp.z,i[6]=Fk.z,i[10]=dl.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const a=e.elements,i=n.elements,s=this.elements,o=a[0],l=a[4],c=a[8],d=a[12],u=a[1],m=a[5],p=a[9],f=a[13],g=a[2],w=a[6],b=a[10],x=a[14],S=a[3],k=a[7],C=a[11],P=a[15],T=i[0],A=i[4],F=i[8],_=i[12],M=i[1],H=i[5],I=i[9],z=i[13],L=i[2],Z=i[6],ne=i[10],Y=i[14],ce=i[3],ue=i[7],oe=i[11],Q=i[15];return s[0]=o*T+l*M+c*L+d*ce,s[4]=o*A+l*H+c*Z+d*ue,s[8]=o*F+l*I+c*ne+d*oe,s[12]=o*_+l*z+c*Y+d*Q,s[1]=u*T+m*M+p*L+f*ce,s[5]=u*A+m*H+p*Z+f*ue,s[9]=u*F+m*I+p*ne+f*oe,s[13]=u*_+m*z+p*Y+f*Q,s[2]=g*T+w*M+b*L+x*ce,s[6]=g*A+w*H+b*Z+x*ue,s[10]=g*F+w*I+b*ne+x*oe,s[14]=g*_+w*z+b*Y+x*Q,s[3]=S*T+k*M+C*L+P*ce,s[7]=S*A+k*H+C*Z+P*ue,s[11]=S*F+k*I+C*ne+P*oe,s[15]=S*_+k*z+C*Y+P*Q,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],a=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],g=e[3],w=e[7],b=e[11],x=e[15];return g*(+s*c*m-i*d*m-s*l*p+a*d*p+i*l*f-a*c*f)+w*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+b*(+n*d*m-n*l*f-s*o*m+a*o*f+s*l*u-a*d*u)+x*(-i*l*u-n*c*m+n*l*p+i*o*m-a*o*p+a*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,a){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]=a),this}invert(){const e=this.elements,n=e[0],a=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],g=e[12],w=e[13],b=e[14],x=e[15],S=m*b*d-w*p*d+w*c*f-l*b*f-m*c*x+l*p*x,k=g*p*d-u*b*d-g*c*f+o*b*f+u*c*x-o*p*x,C=u*w*d-g*m*d+g*l*f-o*w*f-u*l*x+o*m*x,P=g*m*c-u*w*c-g*l*p+o*w*p+u*l*b-o*m*b,T=n*S+a*k+i*C+s*P;if(T===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/T;return e[0]=S*A,e[1]=(w*p*s-m*b*s-w*i*f+a*b*f+m*i*x-a*p*x)*A,e[2]=(l*b*s-w*c*s+w*i*d-a*b*d-l*i*x+a*c*x)*A,e[3]=(m*c*s-l*p*s-m*i*d+a*p*d+l*i*f-a*c*f)*A,e[4]=k*A,e[5]=(u*b*s-g*p*s+g*i*f-n*b*f-u*i*x+n*p*x)*A,e[6]=(g*c*s-o*b*s-g*i*d+n*b*d+o*i*x-n*c*x)*A,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*A,e[8]=C*A,e[9]=(g*m*s-u*w*s-g*a*f+n*w*f+u*a*x-n*m*x)*A,e[10]=(o*w*s-g*l*s+g*a*d-n*w*d-o*a*x+n*l*x)*A,e[11]=(u*l*s-o*m*s-u*a*d+n*m*d+o*a*f-n*l*f)*A,e[12]=P*A,e[13]=(u*w*i-g*m*i+g*a*p-n*w*p-u*a*b+n*m*b)*A,e[14]=(g*l*i-o*w*i-g*a*c+n*w*c+o*a*b-n*l*b)*A,e[15]=(o*m*i-u*l*i+u*a*c-n*m*c-o*a*p+n*l*p)*A,this}scale(e){const n=this.elements,a=e.x,i=e.y,s=e.z;return n[0]*=a,n[4]*=i,n[8]*=s,n[1]*=a,n[5]*=i,n[9]*=s,n[2]*=a,n[6]*=i,n[10]*=s,n[3]*=a,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],a=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,a,i))}makeTranslation(e,n,a){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,a,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),a=Math.sin(e);return this.set(1,0,0,0,0,n,-a,0,0,a,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),a=Math.sin(e);return this.set(n,0,a,0,0,1,0,0,-a,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),a=Math.sin(e);return this.set(n,-a,0,0,a,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const a=Math.cos(n),i=Math.sin(n),s=1-a,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+a,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+a,u*c-i*o,0,d*c-i*l,u*c+i*o,s*c*c+a,0,0,0,0,1),this}makeScale(e,n,a){return this.set(e,0,0,0,0,n,0,0,0,0,a,0,0,0,0,1),this}makeShear(e,n,a,i,s,o){return this.set(1,a,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,a){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,g=s*m,w=o*u,b=o*m,x=l*m,S=c*d,k=c*u,C=c*m,P=a.x,T=a.y,A=a.z;return i[0]=(1-(w+x))*P,i[1]=(f+C)*P,i[2]=(g-k)*P,i[3]=0,i[4]=(f-C)*T,i[5]=(1-(p+x))*T,i[6]=(b+S)*T,i[7]=0,i[8]=(g+k)*A,i[9]=(b-S)*A,i[10]=(1-(p+w))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,a){const i=this.elements;let s=tx.set(i[0],i[1],i[2]).length();const o=tx.set(i[4],i[5],i[6]).length(),l=tx.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],Qc.copy(this);const d=1/s,u=1/o,m=1/l;return Qc.elements[0]*=d,Qc.elements[1]*=d,Qc.elements[2]*=d,Qc.elements[4]*=u,Qc.elements[5]*=u,Qc.elements[6]*=u,Qc.elements[8]*=m,Qc.elements[9]*=m,Qc.elements[10]*=m,n.setFromRotationMatrix(Qc),a.x=s,a.y=o,a.z=l,this}makePerspective(e,n,a,i,s,o,l=Jd,c=!1){const d=this.elements,u=2*s/(n-e),m=2*s/(a-i),p=(n+e)/(n-e),f=(a+i)/(a-i);let g,w;if(c)g=s/(o-s),w=o*s/(o-s);else if(l===Jd)g=-(o+s)/(o-s),w=-2*o*s/(o-s);else if(l===dC)g=-o/(o-s),w=-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]=g,d[14]=w,d[3]=0,d[7]=0,d[11]=-1,d[15]=0,this}makeOrthographic(e,n,a,i,s,o,l=Jd,c=!1){const d=this.elements,u=2/(n-e),m=2/(a-i),p=-(n+e)/(n-e),f=-(a+i)/(a-i);let g,w;if(c)g=1/(o-s),w=o/(o-s);else if(l===Jd)g=-2/(o-s),w=-(o+s)/(o-s);else if(l===dC)g=-1/(o-s),w=-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]=g,d[14]=w,d[3]=0,d[7]=0,d[11]=0,d[15]=1,this}equals(e){const n=this.elements,a=e.elements;for(let i=0;i<16;i++)if(n[i]!==a[i])return!1;return!0}fromArray(e,n=0){for(let a=0;a<16;a++)this.elements[a]=e[a+n];return this}toArray(e=[],n=0){const a=this.elements;return e[n]=a[0],e[n+1]=a[1],e[n+2]=a[2],e[n+3]=a[3],e[n+4]=a[4],e[n+5]=a[5],e[n+6]=a[6],e[n+7]=a[7],e[n+8]=a[8],e[n+9]=a[9],e[n+10]=a[10],e[n+11]=a[11],e[n+12]=a[12],e[n+13]=a[13],e[n+14]=a[14],e[n+15]=a[15],e}};const tx=new Lt,Qc=new Ci,pwe=new Lt(0,0,0),hwe=new Lt(1,1,1),Bp=new Lt,Fk=new Lt,dl=new Lt,U6=new Ci,B6=new Rg;let Kh=class PJ{constructor(e=0,n=0,a=0,i=PJ.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=a,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,a,i=this._order){return this._x=e,this._y=n,this._z=a,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,a=!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(br(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(-br(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(br(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(-br(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(br(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(-br(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:$n("Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,a===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,a){return U6.makeRotationFromQuaternion(e),this.setFromRotationMatrix(U6,n,a)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return B6.setFromEuler(this),this.setFromQuaternion(B6,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}};Kh.DEFAULT_ORDER="XYZ";let TJ=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}},fwe=0;const H6=new Lt,nx=new Rg,Yu=new Ci,Lk=new Lt,r0=new Lt,gwe=new Lt,bwe=new Rg,q6=new Lt(1,0,0),$6=new Lt(0,1,0),V6=new Lt(0,0,1),G6={type:"added"},xwe={type:"removed"},rx={type:"childadded",child:null},_E={type:"childremoved",child:null};let Tl=class CN extends lb{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:fwe++}),this.uuid=OS(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=CN.DEFAULT_UP.clone();const e=new Lt,n=new Kh,a=new Rg,i=new Lt(1,1,1);function s(){a.setFromEuler(n,!1)}function o(){n.setFromQuaternion(a,void 0,!1)}n._onChange(s),a._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:a},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Ci},normalMatrix:{value:new lr}}),this.matrix=new Ci,this.matrixWorld=new Ci,this.matrixAutoUpdate=CN.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=CN.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new TJ,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 nx.setFromAxisAngle(e,n),this.quaternion.multiply(nx),this}rotateOnWorldAxis(e,n){return nx.setFromAxisAngle(e,n),this.quaternion.premultiply(nx),this}rotateX(e){return this.rotateOnAxis(q6,e)}rotateY(e){return this.rotateOnAxis($6,e)}rotateZ(e){return this.rotateOnAxis(V6,e)}translateOnAxis(e,n){return H6.copy(e).applyQuaternion(this.quaternion),this.position.add(H6.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(q6,e)}translateY(e){return this.translateOnAxis($6,e)}translateZ(e){return this.translateOnAxis(V6,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,a){e.isVector3?Lk.copy(e):Lk.set(e,n,a);const i=this.parent;this.updateWorldMatrix(!0,!1),r0.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Yu.lookAt(r0,Lk,this.up):Yu.lookAt(Lk,r0,this.up),this.quaternion.setFromRotationMatrix(Yu),i&&(Yu.extractRotation(i.matrixWorld),nx.setFromRotationMatrix(Yu),this.quaternion.premultiply(nx.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(di("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(G6),rx.child=e,this.dispatchEvent(rx),rx.child=null):di("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let a=0;a<arguments.length;a++)this.remove(arguments[a]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(xwe),_E.child=e,this.dispatchEvent(_E),_E.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),Yu.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Yu.multiply(e.parent.matrixWorld)),e.applyMatrix4(Yu),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(G6),rx.child=e,this.dispatchEvent(rx),rx.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 a=0,i=this.children.length;a<i;a++){const o=this.children[a].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,a=[]){this[e]===n&&a.push(this);const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,n,a);return a}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(r0,e,gwe),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(r0,bwe,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 a=0,i=n.length;a<i;a++)n[a].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let a=0,i=n.length;a<i;a++)n[a].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 a=0,i=n.length;a<i;a++)n[a].updateMatrixWorld(e)}updateWorldMatrix(e,n){const a=this.parent;if(e===!0&&a!==null&&a.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",a={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},a.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),g=o(e.nodes);l.length>0&&(a.geometries=l),c.length>0&&(a.materials=c),d.length>0&&(a.textures=d),u.length>0&&(a.images=u),m.length>0&&(a.shapes=m),p.length>0&&(a.skeletons=p),f.length>0&&(a.animations=f),g.length>0&&(a.nodes=g)}return a.object=i,a;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 a=0;a<e.children.length;a++){const i=e.children[a];this.add(i.clone())}return this}};Tl.DEFAULT_UP=new Lt(0,1,0);Tl.DEFAULT_MATRIX_AUTO_UPDATE=!0;Tl.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Yc=new Lt,Xu=new Lt,kE=new Lt,Zu=new Lt,ax=new Lt,ix=new Lt,W6=new Lt,NE=new Lt,CE=new Lt,PE=new Lt,TE=new wi,AE=new wi,jE=new wi;let a0=class zx{constructor(e=new Lt,n=new Lt,a=new Lt){this.a=e,this.b=n,this.c=a}static getNormal(e,n,a,i){i.subVectors(a,n),Yc.subVectors(e,n),i.cross(Yc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,a,i,s){Yc.subVectors(i,n),Xu.subVectors(a,n),kE.subVectors(e,n);const o=Yc.dot(Yc),l=Yc.dot(Xu),c=Yc.dot(kE),d=Xu.dot(Xu),u=Xu.dot(kE),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,g=(o*u-l*c)*p;return s.set(1-f-g,g,f)}static containsPoint(e,n,a,i){return this.getBarycoord(e,n,a,i,Zu)===null?!1:Zu.x>=0&&Zu.y>=0&&Zu.x+Zu.y<=1}static getInterpolation(e,n,a,i,s,o,l,c){return this.getBarycoord(e,n,a,i,Zu)===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,Zu.x),c.addScaledVector(o,Zu.y),c.addScaledVector(l,Zu.z),c)}static getInterpolatedAttribute(e,n,a,i,s,o){return TE.setScalar(0),AE.setScalar(0),jE.setScalar(0),TE.fromBufferAttribute(e,n),AE.fromBufferAttribute(e,a),jE.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(TE,s.x),o.addScaledVector(AE,s.y),o.addScaledVector(jE,s.z),o}static isFrontFacing(e,n,a,i){return Yc.subVectors(a,n),Xu.subVectors(e,n),Yc.cross(Xu).dot(i)<0}set(e,n,a){return this.a.copy(e),this.b.copy(n),this.c.copy(a),this}setFromPointsAndIndices(e,n,a,i){return this.a.copy(e[n]),this.b.copy(e[a]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,a,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,a),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 Yc.subVectors(this.c,this.b),Xu.subVectors(this.a,this.b),Yc.cross(Xu).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return zx.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return zx.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,a,i,s){return zx.getInterpolation(e,this.a,this.b,this.c,n,a,i,s)}containsPoint(e){return zx.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return zx.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const a=this.a,i=this.b,s=this.c;let o,l;ax.subVectors(i,a),ix.subVectors(s,a),NE.subVectors(e,a);const c=ax.dot(NE),d=ix.dot(NE);if(c<=0&&d<=0)return n.copy(a);CE.subVectors(e,i);const u=ax.dot(CE),m=ix.dot(CE);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(a).addScaledVector(ax,o);PE.subVectors(e,s);const f=ax.dot(PE),g=ix.dot(PE);if(g>=0&&f<=g)return n.copy(s);const w=f*d-c*g;if(w<=0&&d>=0&&g<=0)return l=d/(d-g),n.copy(a).addScaledVector(ix,l);const b=u*g-f*m;if(b<=0&&m-u>=0&&f-g>=0)return W6.subVectors(s,i),l=(m-u)/(m-u+(f-g)),n.copy(i).addScaledVector(W6,l);const x=1/(b+w+p);return o=w*x,l=p*x,n.copy(a).addScaledVector(ax,o).addScaledVector(ix,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}};const AJ={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},Hp={h:0,s:0,l:0},Rk={h:0,s:0,l:0};function ME(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 cr=class{constructor(e,n,a){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,a)}set(e,n,a){if(n===void 0&&a===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,a);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=fl){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Or.colorSpaceToWorking(this,n),this}setRGB(e,n,a,i=Or.workingColorSpace){return this.r=e,this.g=n,this.b=a,Or.colorSpaceToWorking(this,i),this}setHSL(e,n,a,i=Or.workingColorSpace){if(e=awe(e,1),n=br(n,0,1),a=br(a,0,1),n===0)this.r=this.g=this.b=a;else{const s=a<=.5?a*(1+n):a+n-a*n,o=2*a-s;this.r=ME(o,s,e+1/3),this.g=ME(o,s,e),this.b=ME(o,s,e-1/3)}return Or.colorSpaceToWorking(this,i),this}setStyle(e,n=fl){function a(s){s!==void 0&&parseFloat(s)<1&&$n("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 a(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 a(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 a(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:$n("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);$n("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=fl){const a=AJ[e.toLowerCase()];return a!==void 0?this.setHex(a,n):$n("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=Lm(e.r),this.g=Lm(e.g),this.b=Lm(e.b),this}copyLinearToSRGB(e){return this.r=iy(e.r),this.g=iy(e.g),this.b=iy(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=fl){return Or.workingToColorSpace($s.copy(this),e),Math.round(br($s.r*255,0,255))*65536+Math.round(br($s.g*255,0,255))*256+Math.round(br($s.b*255,0,255))}getHexString(e=fl){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=Or.workingColorSpace){Or.workingToColorSpace($s.copy(this),n);const a=$s.r,i=$s.g,s=$s.b,o=Math.max(a,i,s),l=Math.min(a,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 a:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-a)/m+2;break;case s:c=(a-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=Or.workingColorSpace){return Or.workingToColorSpace($s.copy(this),n),e.r=$s.r,e.g=$s.g,e.b=$s.b,e}getStyle(e=fl){Or.workingToColorSpace($s.copy(this),e);const n=$s.r,a=$s.g,i=$s.b;return e!==fl?`color(${e} ${n.toFixed(3)} ${a.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(a*255)},${Math.round(i*255)})`}offsetHSL(e,n,a){return this.getHSL(Hp),this.setHSL(Hp.h+e,Hp.s+n,Hp.l+a)}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,a){return this.r=e.r+(n.r-e.r)*a,this.g=e.g+(n.g-e.g)*a,this.b=e.b+(n.b-e.b)*a,this}lerpHSL(e,n){this.getHSL(Hp),e.getHSL(Rk);const a=pE(Hp.h,Rk.h,n),i=pE(Hp.s,Rk.s,n),s=pE(Hp.l,Rk.l,n);return this.setHSL(a,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,a=this.g,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*a+s[6]*i,this.g=s[1]*n+s[4]*a+s[7]*i,this.b=s[2]*n+s[5]*a+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 cr;cr.NAMES=AJ;let ywe=0,Xy=class extends lb{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ywe++}),this.uuid=OS(),this.name="",this.type="Material",this.blending=ay,this.side=Wh,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=rL,this.blendDst=aL,this.blendEquation=Zf,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new cr(0,0,0),this.blendAlpha=0,this.depthFunc=yy,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=E6,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Yb,this.stencilZFail=Yb,this.stencilZPass=Yb,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 a=e[n];if(a===void 0){$n(`Material: parameter '${n}' has value of undefined.`);continue}const i=this[n];if(i===void 0){$n(`Material: '${n}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(a):i&&i.isVector3&&a&&a.isVector3?i.copy(a):this[n]=a}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const a={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};a.uuid=this.uuid,a.type=this.type,this.name!==""&&(a.name=this.name),this.color&&this.color.isColor&&(a.color=this.color.getHex()),this.roughness!==void 0&&(a.roughness=this.roughness),this.metalness!==void 0&&(a.metalness=this.metalness),this.sheen!==void 0&&(a.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(a.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(a.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(a.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(a.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(a.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(a.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(a.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(a.shininess=this.shininess),this.clearcoat!==void 0&&(a.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(a.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(a.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(a.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(a.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,a.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(a.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(a.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(a.dispersion=this.dispersion),this.iridescence!==void 0&&(a.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(a.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(a.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(a.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(a.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(a.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(a.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(a.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(a.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(a.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(a.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(a.lightMap=this.lightMap.toJSON(e).uuid,a.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(a.aoMap=this.aoMap.toJSON(e).uuid,a.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(a.bumpMap=this.bumpMap.toJSON(e).uuid,a.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(a.normalMap=this.normalMap.toJSON(e).uuid,a.normalMapType=this.normalMapType,a.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(a.displacementMap=this.displacementMap.toJSON(e).uuid,a.displacementScale=this.displacementScale,a.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(a.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(a.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(a.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(a.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(a.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(a.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(a.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(a.combine=this.combine)),this.envMapRotation!==void 0&&(a.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(a.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(a.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(a.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(a.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(a.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(a.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(a.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(a.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(a.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(a.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(a.size=this.size),this.shadowSide!==null&&(a.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(a.sizeAttenuation=this.sizeAttenuation),this.blending!==ay&&(a.blending=this.blending),this.side!==Wh&&(a.side=this.side),this.vertexColors===!0&&(a.vertexColors=!0),this.opacity<1&&(a.opacity=this.opacity),this.transparent===!0&&(a.transparent=!0),this.blendSrc!==rL&&(a.blendSrc=this.blendSrc),this.blendDst!==aL&&(a.blendDst=this.blendDst),this.blendEquation!==Zf&&(a.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(a.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(a.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(a.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(a.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(a.blendAlpha=this.blendAlpha),this.depthFunc!==yy&&(a.depthFunc=this.depthFunc),this.depthTest===!1&&(a.depthTest=this.depthTest),this.depthWrite===!1&&(a.depthWrite=this.depthWrite),this.colorWrite===!1&&(a.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(a.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==E6&&(a.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(a.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(a.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Yb&&(a.stencilFail=this.stencilFail),this.stencilZFail!==Yb&&(a.stencilZFail=this.stencilZFail),this.stencilZPass!==Yb&&(a.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(a.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(a.rotation=this.rotation),this.polygonOffset===!0&&(a.polygonOffset=!0),this.polygonOffsetFactor!==0&&(a.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(a.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(a.linewidth=this.linewidth),this.dashSize!==void 0&&(a.dashSize=this.dashSize),this.gapSize!==void 0&&(a.gapSize=this.gapSize),this.scale!==void 0&&(a.scale=this.scale),this.dithering===!0&&(a.dithering=!0),this.alphaTest>0&&(a.alphaTest=this.alphaTest),this.alphaHash===!0&&(a.alphaHash=!0),this.alphaToCoverage===!0&&(a.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(a.premultipliedAlpha=!0),this.forceSinglePass===!0&&(a.forceSinglePass=!0),this.wireframe===!0&&(a.wireframe=!0),this.wireframeLinewidth>1&&(a.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(a.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(a.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(a.flatShading=!0),this.visible===!1&&(a.visible=!1),this.toneMapped===!1&&(a.toneMapped=!1),this.fog===!1&&(a.fog=!1),Object.keys(this.userData).length>0&&(a.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&&(a.textures=s),o.length>0&&(a.images=o)}return a}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 a=null;if(n!==null){const i=n.length;a=new Array(i);for(let s=0;s!==i;++s)a[s]=n[s].clone()}return this.clippingPlanes=a,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++}},qO=class extends Xy{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new cr(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 Kh,this.combine=DO,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 yi=new Lt,Ik=new ir;let vwe=0,wo=class{constructor(e,n,a=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:vwe++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=a,this.usage=D6,this.updateRanges=[],this.gpuType=_m,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,a){e*=this.itemSize,a*=n.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[a+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,a=this.count;n<a;n++)Ik.fromBufferAttribute(this,n),Ik.applyMatrix3(e),this.setXY(n,Ik.x,Ik.y);else if(this.itemSize===3)for(let n=0,a=this.count;n<a;n++)yi.fromBufferAttribute(this,n),yi.applyMatrix3(e),this.setXYZ(n,yi.x,yi.y,yi.z);return this}applyMatrix4(e){for(let n=0,a=this.count;n<a;n++)yi.fromBufferAttribute(this,n),yi.applyMatrix4(e),this.setXYZ(n,yi.x,yi.y,yi.z);return this}applyNormalMatrix(e){for(let n=0,a=this.count;n<a;n++)yi.fromBufferAttribute(this,n),yi.applyNormalMatrix(e),this.setXYZ(n,yi.x,yi.y,yi.z);return this}transformDirection(e){for(let n=0,a=this.count;n<a;n++)yi.fromBufferAttribute(this,n),yi.transformDirection(e),this.setXYZ(n,yi.x,yi.y,yi.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let a=this.array[e*this.itemSize+n];return this.normalized&&(a=e0(a,this.array)),a}setComponent(e,n,a){return this.normalized&&(a=zo(a,this.array)),this.array[e*this.itemSize+n]=a,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=e0(n,this.array)),n}setX(e,n){return this.normalized&&(n=zo(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=e0(n,this.array)),n}setY(e,n){return this.normalized&&(n=zo(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=e0(n,this.array)),n}setZ(e,n){return this.normalized&&(n=zo(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=e0(n,this.array)),n}setW(e,n){return this.normalized&&(n=zo(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,a){return e*=this.itemSize,this.normalized&&(n=zo(n,this.array),a=zo(a,this.array)),this.array[e+0]=n,this.array[e+1]=a,this}setXYZ(e,n,a,i){return e*=this.itemSize,this.normalized&&(n=zo(n,this.array),a=zo(a,this.array),i=zo(i,this.array)),this.array[e+0]=n,this.array[e+1]=a,this.array[e+2]=i,this}setXYZW(e,n,a,i,s){return e*=this.itemSize,this.normalized&&(n=zo(n,this.array),a=zo(a,this.array),i=zo(i,this.array),s=zo(s,this.array)),this.array[e+0]=n,this.array[e+1]=a,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!==D6&&(e.usage=this.usage),e}},jJ=class extends wo{constructor(e,n,a){super(new Uint16Array(e),n,a)}},MJ=class extends wo{constructor(e,n,a){super(new Uint32Array(e),n,a)}},Sl=class extends wo{constructor(e,n,a){super(new Float32Array(e),n,a)}},wwe=0;const Gl=new Ci,EE=new Tl,sx=new Lt,ul=new Fh,i0=new Fh,Ji=new Lt;let Sc=class EJ extends lb{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:wwe++}),this.uuid=OS(),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(wJ(e)?MJ:jJ)(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,a=0){this.groups.push({start:e,count:n,materialIndex:a})}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 a=this.attributes.normal;if(a!==void 0){const s=new lr().getNormalMatrix(e);a.applyNormalMatrix(s),a.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 Gl.makeRotationFromQuaternion(e),this.applyMatrix4(Gl),this}rotateX(e){return Gl.makeRotationX(e),this.applyMatrix4(Gl),this}rotateY(e){return Gl.makeRotationY(e),this.applyMatrix4(Gl),this}rotateZ(e){return Gl.makeRotationZ(e),this.applyMatrix4(Gl),this}translate(e,n,a){return Gl.makeTranslation(e,n,a),this.applyMatrix4(Gl),this}scale(e,n,a){return Gl.makeScale(e,n,a),this.applyMatrix4(Gl),this}lookAt(e){return EE.lookAt(e),EE.updateMatrix(),this.applyMatrix4(EE.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(sx).negate(),this.translate(sx.x,sx.y,sx.z),this}setFromPoints(e){const n=this.getAttribute("position");if(n===void 0){const a=[];for(let i=0,s=e.length;i<s;i++){const o=e[i];a.push(o.x,o.y,o.z||0)}this.setAttribute("position",new Sl(a,3))}else{const a=Math.min(e.length,n.count);for(let i=0;i<a;i++){const s=e[i];n.setXYZ(i,s.x,s.y,s.z||0)}e.length>n.count&&$n("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 Fh);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){di("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new Lt(-1/0,-1/0,-1/0),new Lt(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let a=0,i=n.length;a<i;a++){const s=n[a];ul.setFromBufferAttribute(s),this.morphTargetsRelative?(Ji.addVectors(this.boundingBox.min,ul.min),this.boundingBox.expandByPoint(Ji),Ji.addVectors(this.boundingBox.max,ul.max),this.boundingBox.expandByPoint(Ji)):(this.boundingBox.expandByPoint(ul.min),this.boundingBox.expandByPoint(ul.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&di('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 MT);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){di("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new Lt,1/0);return}if(e){const a=this.boundingSphere.center;if(ul.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];i0.setFromBufferAttribute(l),this.morphTargetsRelative?(Ji.addVectors(ul.min,i0.min),ul.expandByPoint(Ji),Ji.addVectors(ul.max,i0.max),ul.expandByPoint(Ji)):(ul.expandByPoint(i0.min),ul.expandByPoint(i0.max))}ul.getCenter(a);let i=0;for(let s=0,o=e.count;s<o;s++)Ji.fromBufferAttribute(e,s),i=Math.max(i,a.distanceToSquared(Ji));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++)Ji.fromBufferAttribute(l,d),c&&(sx.fromBufferAttribute(e,d),Ji.add(sx)),i=Math.max(i,a.distanceToSquared(Ji))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&di('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){di("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const a=n.position,i=n.normal,s=n.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new wo(new Float32Array(4*a.count),4));const o=this.getAttribute("tangent"),l=[],c=[];for(let F=0;F<a.count;F++)l[F]=new Lt,c[F]=new Lt;const d=new Lt,u=new Lt,m=new Lt,p=new ir,f=new ir,g=new ir,w=new Lt,b=new Lt;function x(F,_,M){d.fromBufferAttribute(a,F),u.fromBufferAttribute(a,_),m.fromBufferAttribute(a,M),p.fromBufferAttribute(s,F),f.fromBufferAttribute(s,_),g.fromBufferAttribute(s,M),u.sub(d),m.sub(d),f.sub(p),g.sub(p);const H=1/(f.x*g.y-g.x*f.y);isFinite(H)&&(w.copy(u).multiplyScalar(g.y).addScaledVector(m,-f.y).multiplyScalar(H),b.copy(m).multiplyScalar(f.x).addScaledVector(u,-g.x).multiplyScalar(H),l[F].add(w),l[_].add(w),l[M].add(w),c[F].add(b),c[_].add(b),c[M].add(b))}let S=this.groups;S.length===0&&(S=[{start:0,count:e.count}]);for(let F=0,_=S.length;F<_;++F){const M=S[F],H=M.start,I=M.count;for(let z=H,L=H+I;z<L;z+=3)x(e.getX(z+0),e.getX(z+1),e.getX(z+2))}const k=new Lt,C=new Lt,P=new Lt,T=new Lt;function A(F){P.fromBufferAttribute(i,F),T.copy(P);const _=l[F];k.copy(_),k.sub(P.multiplyScalar(P.dot(_))).normalize(),C.crossVectors(T,_);const H=C.dot(c[F])<0?-1:1;o.setXYZW(F,k.x,k.y,k.z,H)}for(let F=0,_=S.length;F<_;++F){const M=S[F],H=M.start,I=M.count;for(let z=H,L=H+I;z<L;z+=3)A(e.getX(z+0)),A(e.getX(z+1)),A(e.getX(z+2))}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let a=this.getAttribute("normal");if(a===void 0)a=new wo(new Float32Array(n.count*3),3),this.setAttribute("normal",a);else for(let p=0,f=a.count;p<f;p++)a.setXYZ(p,0,0,0);const i=new Lt,s=new Lt,o=new Lt,l=new Lt,c=new Lt,d=new Lt,u=new Lt,m=new Lt;if(e)for(let p=0,f=e.count;p<f;p+=3){const g=e.getX(p+0),w=e.getX(p+1),b=e.getX(p+2);i.fromBufferAttribute(n,g),s.fromBufferAttribute(n,w),o.fromBufferAttribute(n,b),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(a,g),c.fromBufferAttribute(a,w),d.fromBufferAttribute(a,b),l.add(u),c.add(u),d.add(u),a.setXYZ(g,l.x,l.y,l.z),a.setXYZ(w,c.x,c.y,c.z),a.setXYZ(b,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),a.setXYZ(p+0,u.x,u.y,u.z),a.setXYZ(p+1,u.x,u.y,u.z),a.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),a.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,a=e.count;n<a;n++)Ji.fromBufferAttribute(e,n),Ji.normalize(),e.setXYZ(n,Ji.x,Ji.y,Ji.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,g=0;for(let w=0,b=c.length;w<b;w++){l.isInterleavedBufferAttribute?f=c[w]*l.data.stride+l.offset:f=c[w]*u;for(let x=0;x<u;x++)p[g++]=d[f++]}return new wo(p,u,m)}if(this.index===null)return $n("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new EJ,a=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,a);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,a);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 a=this.attributes;for(const c in a){const d=a[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 a=e.index;a!==null&&this.setIndex(a.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 K6=new Ci,Ff=new HO,Ok=new MT,Q6=new Lt,zk=new Lt,Uk=new Lt,Bk=new Lt,DE=new Lt,Hk=new Lt,Y6=new Lt,qk=new Lt;let _c=class extends Tl{constructor(e=new Sc,n=new qO){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,a=Object.keys(n);if(a.length>0){const i=n[a[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 a=this.geometry,i=a.attributes.position,s=a.morphAttributes.position,o=a.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){Hk.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(DE.fromBufferAttribute(m,e),o?Hk.addScaledVector(DE,u):Hk.addScaledVector(DE.sub(n),u))}n.add(Hk)}return n}raycast(e,n){const a=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(a.boundingSphere===null&&a.computeBoundingSphere(),Ok.copy(a.boundingSphere),Ok.applyMatrix4(s),Ff.copy(e.ray).recast(e.near),!(Ok.containsPoint(Ff.origin)===!1&&(Ff.intersectSphere(Ok,Q6)===null||Ff.origin.distanceToSquared(Q6)>(e.far-e.near)**2))&&(K6.copy(s).invert(),Ff.copy(e.ray).applyMatrix4(K6),!(a.boundingBox!==null&&Ff.intersectsBox(a.boundingBox)===!1)&&this._computeIntersections(e,n,Ff)))}_computeIntersections(e,n,a){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 g=0,w=p.length;g<w;g++){const b=p[g],x=o[b.materialIndex],S=Math.max(b.start,f.start),k=Math.min(l.count,Math.min(b.start+b.count,f.start+f.count));for(let C=S,P=k;C<P;C+=3){const T=l.getX(C),A=l.getX(C+1),F=l.getX(C+2);i=$k(this,x,e,a,d,u,m,T,A,F),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const g=Math.max(0,f.start),w=Math.min(l.count,f.start+f.count);for(let b=g,x=w;b<x;b+=3){const S=l.getX(b),k=l.getX(b+1),C=l.getX(b+2);i=$k(this,o,e,a,d,u,m,S,k,C),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,w=p.length;g<w;g++){const b=p[g],x=o[b.materialIndex],S=Math.max(b.start,f.start),k=Math.min(c.count,Math.min(b.start+b.count,f.start+f.count));for(let C=S,P=k;C<P;C+=3){const T=C,A=C+1,F=C+2;i=$k(this,x,e,a,d,u,m,T,A,F),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const g=Math.max(0,f.start),w=Math.min(c.count,f.start+f.count);for(let b=g,x=w;b<x;b+=3){const S=b,k=b+1,C=b+2;i=$k(this,o,e,a,d,u,m,S,k,C),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}}};function Swe(t,e,n,a,i,s,o,l){let c;if(e.side===Wo?c=a.intersectTriangle(o,s,i,!0,l):c=a.intersectTriangle(i,s,o,e.side===Wh,l),c===null)return null;qk.copy(l),qk.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(qk);return d<n.near||d>n.far?null:{distance:d,point:qk.clone(),object:t}}function $k(t,e,n,a,i,s,o,l,c,d){t.getVertexPosition(l,zk),t.getVertexPosition(c,Uk),t.getVertexPosition(d,Bk);const u=Swe(t,e,n,a,zk,Uk,Bk,Y6);if(u){const m=new Lt;a0.getBarycoord(Y6,zk,Uk,Bk,m),i&&(u.uv=a0.getInterpolatedAttribute(i,l,c,d,m,new ir)),s&&(u.uv1=a0.getInterpolatedAttribute(s,l,c,d,m,new ir)),o&&(u.normal=a0.getInterpolatedAttribute(o,l,c,d,m,new Lt),u.normal.dot(a.direction)>0&&u.normal.multiplyScalar(-1));const p={a:l,b:c,c:d,normal:new Lt,materialIndex:0};a0.getNormal(zk,Uk,Bk,p.normal),u.face=p,u.barycoord=m}return u}let $O=class DJ extends Sc{constructor(e=1,n=1,a=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:a,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;g("z","y","x",-1,-1,a,n,e,o,s,0),g("z","y","x",1,-1,a,n,-e,o,s,1),g("x","z","y",1,1,e,a,n,i,o,2),g("x","z","y",1,-1,e,a,-n,i,o,3),g("x","y","z",1,-1,e,n,a,i,s,4),g("x","y","z",-1,-1,e,n,-a,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 g(w,b,x,S,k,C,P,T,A,F,_){const M=C/A,H=P/F,I=C/2,z=P/2,L=T/2,Z=A+1,ne=F+1;let Y=0,ce=0;const ue=new Lt;for(let oe=0;oe<ne;oe++){const Q=oe*H-z;for(let le=0;le<Z;le++){const pe=le*M-I;ue[w]=pe*S,ue[b]=Q*k,ue[x]=L,d.push(ue.x,ue.y,ue.z),ue[w]=0,ue[b]=0,ue[x]=T>0?1:-1,u.push(ue.x,ue.y,ue.z),m.push(le/A),m.push(1-oe/F),Y+=1}}for(let oe=0;oe<F;oe++)for(let Q=0;Q<A;Q++){const le=p+Q+Z*oe,pe=p+Q+Z*(oe+1),he=p+(Q+1)+Z*(oe+1),we=p+(Q+1)+Z*oe;c.push(le,pe,we),c.push(pe,he,we),ce+=6}l.addGroup(f,ce,_),f+=ce,p+=Y}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new DJ(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function _y(t){const e={};for(const n in t){e[n]={};for(const a in t[n]){const i=t[n][a];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?($n("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][a]=null):e[n][a]=i.clone():Array.isArray(i)?e[n][a]=i.slice():e[n][a]=i}}return e}function fo(t){const e={};for(let n=0;n<t.length;n++){const a=_y(t[n]);for(const i in a)e[i]=a[i]}return e}function _we(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function FJ(t){const e=t.getRenderTarget();return e===null?t.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Or.workingColorSpace}const kwe={clone:_y,merge:fo};var Nwe=`void main() {
  35. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  36. }`,Cwe=`void main() {
  37. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  38. }`;let Km=class extends Xy{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Nwe,this.fragmentShader=Cwe,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=_y(e.uniforms),this.uniformsGroups=_we(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 a={};for(const i in this.extensions)this.extensions[i]===!0&&(a[i]=!0);return Object.keys(a).length>0&&(n.extensions=a),n}},LJ=class extends Tl{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ci,this.projectionMatrix=new Ci,this.projectionMatrixInverse=new Ci,this.coordinateSystem=Jd,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 qp=new Lt,X6=new ir,Z6=new ir;let ac=class extends LJ{constructor(e=50,n=1,a=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=a,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=$L*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(kN*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return $L*2*Math.atan(Math.tan(kN*.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,a){qp.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(qp.x,qp.y).multiplyScalar(-e/qp.z),qp.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),a.set(qp.x,qp.y).multiplyScalar(-e/qp.z)}getViewSize(e,n){return this.getViewBounds(e,X6,Z6),n.subVectors(Z6,X6)}setViewOffset(e,n,a,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=a,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(kN*.5*this.fov)/this.zoom,a=2*n,i=this.aspect*a,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*a/d,i*=o.width/c,a*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-a,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 ox=-90,lx=1;let Pwe=class extends Tl{constructor(e,n,a){super(),this.type="CubeCamera",this.renderTarget=a,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new ac(ox,lx,e,n);i.layers=this.layers,this.add(i);const s=new ac(ox,lx,e,n);s.layers=this.layers,this.add(s);const o=new ac(ox,lx,e,n);o.layers=this.layers,this.add(o);const l=new ac(ox,lx,e,n);l.layers=this.layers,this.add(l);const c=new ac(ox,lx,e,n);c.layers=this.layers,this.add(c);const d=new ac(ox,lx,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[a,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===Jd)a.up.set(0,1,0),a.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===dC)a.up.set(0,-1,0),a.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:a,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(),g=e.xr.enabled;e.xr.enabled=!1;const w=a.texture.generateMipmaps;a.texture.generateMipmaps=!1,e.setRenderTarget(a,0,i),e.render(n,s),e.setRenderTarget(a,1,i),e.render(n,o),e.setRenderTarget(a,2,i),e.render(n,l),e.setRenderTarget(a,3,i),e.render(n,c),e.setRenderTarget(a,4,i),e.render(n,d),a.texture.generateMipmaps=w,e.setRenderTarget(a,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=g,a.texture.needsPMREMUpdate=!0}},RJ=class extends xd{constructor(e=[],n=vy,a,i,s,o,l,c,d,u){super(e,n,a,i,s,o,l,c,d,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Twe=class extends Ig{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const a={width:e,height:e,depth:1},i=[a,a,a,a,a,a];this.texture=new RJ(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 a={uniforms:{tEquirect:{value:null}},vertexShader:`
  39. varying vec3 vWorldDirection;
  40. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  41. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  42. }
  43. void main() {
  44. vWorldDirection = transformDirection( position, modelMatrix );
  45. #include <begin_vertex>
  46. #include <project_vertex>
  47. }
  48. `,fragmentShader:`
  49. uniform sampler2D tEquirect;
  50. varying vec3 vWorldDirection;
  51. #include <common>
  52. void main() {
  53. vec3 direction = normalize( vWorldDirection );
  54. vec2 sampleUV = equirectUv( direction );
  55. gl_FragColor = texture2D( tEquirect, sampleUV );
  56. }
  57. `},i=new $O(5,5,5),s=new Km({name:"CubemapFromEquirect",uniforms:_y(a.uniforms),vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,side:Wo,blending:Fm});s.uniforms.tEquirect.value=n;const o=new _c(i,s),l=n.minFilter;return n.minFilter===ig&&(n.minFilter=mc),new Pwe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n=!0,a=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,a,i);e.setRenderTarget(s)}},Wx=class extends Tl{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Awe={type:"move"};let FE=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Wx,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 Wx,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Lt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Lt),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Wx,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Lt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Lt),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 a of e.hand.values())this._getHandJoint(n,a)}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,a){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 w of e.hand.values()){const b=n.getJointPose(w,a),x=this._getHandJoint(d,w);b!==null&&(x.matrix.fromArray(b.transform.matrix),x.matrix.decompose(x.position,x.rotation,x.scale),x.matrixWorldNeedsUpdate=!0,x.jointRadius=b.radius),x.visible=b!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,g=.005;d.inputState.pinching&&p>f+g?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-g&&(d.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,a),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,a),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(Awe)))}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 a=new Wx;a.matrixAutoUpdate=!1,a.visible=!1,e.joints[n.jointName]=a,e.add(a)}return e.joints[n.jointName]}},jwe=class extends Tl{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 Kh,this.environmentIntensity=1,this.environmentRotation=new Kh,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}},Mwe=class extends xd{constructor(e=null,n=1,a=1,i,s,o,l,c,d=wl,u=wl,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:a},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};const LE=new Lt,Ewe=new Lt,Dwe=new lr;let rh=class{constructor(e=new Lt(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,a,i){return this.normal.set(e,n,a),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,a){const i=LE.subVectors(a,n).cross(Ewe.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 a=e.delta(LE),i=this.normal.dot(a);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(a,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),a=this.distanceToPoint(e.end);return n<0&&a>0||a<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 a=n||Dwe.getNormalMatrix(e),i=this.coplanarPoint(LE).applyMatrix4(e),s=this.normal.applyMatrix3(a).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 Lf=new MT,Fwe=new ir(.5,.5),Vk=new Lt;let VO=class{constructor(e=new rh,n=new rh,a=new rh,i=new rh,s=new rh,o=new rh){this.planes=[e,n,a,i,s,o]}set(e,n,a,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(a),l[3].copy(i),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let a=0;a<6;a++)n[a].copy(e.planes[a]);return this}setFromProjectionMatrix(e,n=Jd,a=!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],g=s[8],w=s[9],b=s[10],x=s[11],S=s[12],k=s[13],C=s[14],P=s[15];if(i[0].setComponents(d-o,f-u,x-g,P-S).normalize(),i[1].setComponents(d+o,f+u,x+g,P+S).normalize(),i[2].setComponents(d+l,f+m,x+w,P+k).normalize(),i[3].setComponents(d-l,f-m,x-w,P-k).normalize(),a)i[4].setComponents(c,p,b,C).normalize(),i[5].setComponents(d-c,f-p,x-b,P-C).normalize();else if(i[4].setComponents(d-c,f-p,x-b,P-C).normalize(),n===Jd)i[5].setComponents(d+c,f+p,x+b,P+C).normalize();else if(n===dC)i[5].setComponents(c,p,b,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(),Lf.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Lf.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Lf)}intersectsSprite(e){Lf.center.set(0,0,0);const n=Fwe.distanceTo(e.center);return Lf.radius=.7071067811865476+n,Lf.applyMatrix4(e.matrixWorld),this.intersectsSphere(Lf)}intersectsSphere(e){const n=this.planes,a=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(a)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let a=0;a<6;a++){const i=n[a];if(Vk.x=i.normal.x>0?e.max.x:e.min.x,Vk.y=i.normal.y>0?e.max.y:e.min.y,Vk.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Vk)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let a=0;a<6;a++)if(n[a].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},IJ=class extends Xy{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new cr(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 mC=new Lt,pC=new Lt,J6=new Ci,s0=new HO,Gk=new MT,RE=new Lt,eq=new Lt;let Lwe=class extends Tl{constructor(e=new Sc,n=new IJ){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,a=[0];for(let i=1,s=n.count;i<s;i++)mC.fromBufferAttribute(n,i-1),pC.fromBufferAttribute(n,i),a[i]=a[i-1],a[i]+=mC.distanceTo(pC);e.setAttribute("lineDistance",new Sl(a,1))}else $n("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const a=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=a.drawRange;if(a.boundingSphere===null&&a.computeBoundingSphere(),Gk.copy(a.boundingSphere),Gk.applyMatrix4(i),Gk.radius+=s,e.ray.intersectsSphere(Gk)===!1)return;J6.copy(i).invert(),s0.copy(e.ray).applyMatrix4(J6);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=this.isLineSegments?2:1,u=a.index,p=a.attributes.position;if(u!==null){const f=Math.max(0,o.start),g=Math.min(u.count,o.start+o.count);for(let w=f,b=g-1;w<b;w+=d){const x=u.getX(w),S=u.getX(w+1),k=Wk(this,e,s0,c,x,S,w);k&&n.push(k)}if(this.isLineLoop){const w=u.getX(g-1),b=u.getX(f),x=Wk(this,e,s0,c,w,b,g-1);x&&n.push(x)}}else{const f=Math.max(0,o.start),g=Math.min(p.count,o.start+o.count);for(let w=f,b=g-1;w<b;w+=d){const x=Wk(this,e,s0,c,w,w+1,w);x&&n.push(x)}if(this.isLineLoop){const w=Wk(this,e,s0,c,g-1,f,g-1);w&&n.push(w)}}}updateMorphTargets(){const n=this.geometry.morphAttributes,a=Object.keys(n);if(a.length>0){const i=n[a[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 Wk(t,e,n,a,i,s,o){const l=t.geometry.attributes.position;if(mC.fromBufferAttribute(l,i),pC.fromBufferAttribute(l,s),n.distanceSqToSegment(mC,pC,RE,eq)>a)return;RE.applyMatrix4(t.matrixWorld);const d=e.ray.origin.distanceTo(RE);if(!(d<e.near||d>e.far))return{distance:d,point:eq.clone().applyMatrix4(t.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:t}}const tq=new Lt,nq=new Lt;let Rwe=class extends Lwe{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,a=[];for(let i=0,s=n.count;i<s;i+=2)tq.fromBufferAttribute(n,i),nq.fromBufferAttribute(n,i+1),a[i]=i===0?0:a[i-1],a[i+1]=a[i]+tq.distanceTo(nq);e.setAttribute("lineDistance",new Sl(a,1))}else $n("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},OJ=class extends xd{constructor(e,n,a=Lg,i,s,o,l=wl,c=wl,d,u=Ow,m=1){if(u!==Ow&&u!==zw)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,a,d),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new BO(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 zJ extends xd{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}let GO=class UJ extends Sc{constructor(e=1,n=1,a=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:a,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(a),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],g=[],w=[],b=[];for(let x=0;x<u;x++){const S=x*p-o;for(let k=0;k<d;k++){const C=k*m-s;g.push(C,-S,0),w.push(0,0,1),b.push(k/l),b.push(1-x/c)}}for(let x=0;x<c;x++)for(let S=0;S<l;S++){const k=S+d*x,C=S+d*(x+1),P=S+1+d*(x+1),T=S+1+d*x;f.push(k,C,T),f.push(C,P,T)}this.setIndex(f),this.setAttribute("position",new Sl(g,3)),this.setAttribute("normal",new Sl(w,3)),this.setAttribute("uv",new Sl(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new UJ(e.width,e.height,e.widthSegments,e.heightSegments)}};class BJ extends Xy{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new cr(16777215),this.specular=new cr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new cr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=yJ,this.normalScale=new ir(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Kh,this.combine=DO,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 Iwe=class extends Xy{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=G0e,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}},Owe=class extends Xy{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 rq={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 zwe{constructor(e,n,a){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=a,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],g=d[m+1];if(f.global&&(f.lastIndex=0),f.test(u))return g}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 Uwe=new zwe;class WO{constructor(e){this.manager=e!==void 0?e:Uwe,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,n){const a=this;return new Promise(function(i,s){a.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}}WO.DEFAULT_MATERIAL_NAME="__DEFAULT";const Ju={};class Bwe extends Error{constructor(e,n){super(e),this.response=n}}class Hwe extends WO{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,n,a,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=rq.get(`file:${e}`);if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{n&&n(s),this.manager.itemEnd(e)},0),s;if(Ju[e]!==void 0){Ju[e].push({onLoad:n,onProgress:a,onError:i});return}Ju[e]=[],Ju[e].push({onLoad:n,onProgress:a,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&&$n("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||d.body===void 0||d.body.getReader===void 0)return d;const u=Ju[e],m=d.body.getReader(),p=d.headers.get("X-File-Size")||d.headers.get("Content-Length"),f=p?parseInt(p):0,g=f!==0;let w=0;const b=new ReadableStream({start(x){S();function S(){m.read().then(({done:k,value:C})=>{if(k)x.close();else{w+=C.byteLength;const P=new ProgressEvent("progress",{lengthComputable:g,loaded:w,total:f});for(let T=0,A=u.length;T<A;T++){const F=u[T];F.onProgress&&F.onProgress(P)}x.enqueue(C),S()}},k=>{x.error(k)})}}});return new Response(b)}else throw new Bwe(`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(g=>f.decode(g))}}}).then(d=>{rq.add(`file:${e}`,d);const u=Ju[e];delete Ju[e];for(let m=0,p=u.length;m<p;m++){const f=u[m];f.onLoad&&f.onLoad(d)}}).catch(d=>{const u=Ju[e];if(u===void 0)throw this.manager.itemError(e),d;delete Ju[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 HJ=class extends Tl{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new cr(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 IE=new Ci,aq=new Lt,iq=new Lt;let qwe=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ir(512,512),this.mapType=fu,this.map=null,this.mapPass=null,this.matrix=new Ci,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new VO,this._frameExtents=new ir(1,1),this._viewportCount=1,this._viewports=[new wi(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,a=this.matrix;aq.setFromMatrixPosition(e.matrixWorld),n.position.copy(aq),iq.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(iq),n.updateMatrixWorld(),IE.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(IE,n.coordinateSystem,n.reversedDepth),n.reversedDepth?a.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):a.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),a.multiply(IE)}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}},qJ=class extends LJ{constructor(e=-1,n=1,a=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=a,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,a,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=a,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),a=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=a-e,o=a+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 $we extends qwe{constructor(){super(new qJ(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class sq extends HJ{constructor(e,n){super(e,n),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Tl.DEFAULT_UP),this.updateMatrix(),this.target=new Tl,this.shadow=new $we}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}let Vwe=class extends HJ{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}},Gwe=class extends ac{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},oq=class{constructor(e=1,n=0,a=0){this.radius=e,this.phi=n,this.theta=a}set(e,n,a){return this.radius=e,this.phi=n,this.theta=a,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=br(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,n,a){return this.radius=Math.sqrt(e*e+n*n+a*a),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,a),this.phi=Math.acos(br(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};class Wwe extends Rwe{constructor(e=10,n=10,a=4473924,i=8947848){a=new cr(a),i=new cr(i);const s=n/2,o=e/n,l=e/2,c=[],d=[];for(let p=0,f=0,g=-l;p<=n;p++,g+=o){c.push(-l,0,g,l,0,g),c.push(g,0,-l,g,0,l);const w=p===s?a:i;w.toArray(d,f),f+=3,w.toArray(d,f),f+=3,w.toArray(d,f),f+=3,w.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 IJ({vertexColors:!0,toneMapped:!1});super(u,m),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class Kwe extends lb{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){$n("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function lq(t,e,n,a){const i=Qwe(a);switch(n){case gJ:return t*e;case xJ:return t*e/i.components*i.byteLength;case IO:return t*e/i.components*i.byteLength;case OO:return t*e*2/i.components*i.byteLength;case zO:return t*e*2/i.components*i.byteLength;case bJ:return t*e*3/i.components*i.byteLength;case ld:return t*e*4/i.components*i.byteLength;case UO:return t*e*4/i.components*i.byteLength;case vN:case wN:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case SN:case _N:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case bL:case yL:return Math.max(t,16)*Math.max(e,8)/4;case gL:case xL:return Math.max(t,8)*Math.max(e,8)/2;case vL:case wL:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case SL:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case _L:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case kL:return Math.floor((t+4)/5)*Math.floor((e+3)/4)*16;case NL:return Math.floor((t+4)/5)*Math.floor((e+4)/5)*16;case CL:return Math.floor((t+5)/6)*Math.floor((e+4)/5)*16;case PL:return Math.floor((t+5)/6)*Math.floor((e+5)/6)*16;case TL:return Math.floor((t+7)/8)*Math.floor((e+4)/5)*16;case AL:return Math.floor((t+7)/8)*Math.floor((e+5)/6)*16;case jL:return Math.floor((t+7)/8)*Math.floor((e+7)/8)*16;case ML:return Math.floor((t+9)/10)*Math.floor((e+4)/5)*16;case EL:return Math.floor((t+9)/10)*Math.floor((e+5)/6)*16;case DL:return Math.floor((t+9)/10)*Math.floor((e+7)/8)*16;case FL:return Math.floor((t+9)/10)*Math.floor((e+9)/10)*16;case LL:return Math.floor((t+11)/12)*Math.floor((e+9)/10)*16;case RL:return Math.floor((t+11)/12)*Math.floor((e+11)/12)*16;case IL:case OL:case zL:return Math.ceil(t/4)*Math.ceil(e/4)*16;case UL:case BL:return Math.ceil(t/4)*Math.ceil(e/4)*8;case HL:case qL:return Math.ceil(t/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function Qwe(t){switch(t){case fu:case mJ:return{byteLength:1,components:1};case Rw:case pJ:case Yy:return{byteLength:2,components:1};case LO:case RO:return{byteLength:2,components:4};case Lg:case FO:case _m:return{byteLength:4,components:1};case hJ:case fJ:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:EO}}));typeof window<"u"&&(window.__THREE__?$n("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=EO);function $J(){let t=null,e=!1,n=null,a=null;function i(s,o){n(s,o),a=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(a=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(a),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function Ywe(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 a(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,g)=>f.start-g.start);let p=0;for(let f=1;f<m.length;f++){const g=m[p],w=m[f];w.start<=g.start+g.count+1?g.count=Math.max(g.count,w.start+w.count-g.start):(++p,m[p]=w)}m.length=p+1;for(let f=0,g=m.length;f<g;f++){const w=m[f];t.bufferSubData(d,w.start*u.BYTES_PER_ELEMENT,u,w.start,w.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.");a(d.buffer,l,c),d.version=l.version}}return{get:i,remove:s,update:o}}var Xwe=`#ifdef USE_ALPHAHASH
  58. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  59. #endif`,Zwe=`#ifdef USE_ALPHAHASH
  60. const float ALPHA_HASH_SCALE = 0.05;
  61. float hash2D( vec2 value ) {
  62. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  63. }
  64. float hash3D( vec3 value ) {
  65. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  66. }
  67. float getAlphaHashThreshold( vec3 position ) {
  68. float maxDeriv = max(
  69. length( dFdx( position.xyz ) ),
  70. length( dFdy( position.xyz ) )
  71. );
  72. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  73. vec2 pixScales = vec2(
  74. exp2( floor( log2( pixScale ) ) ),
  75. exp2( ceil( log2( pixScale ) ) )
  76. );
  77. vec2 alpha = vec2(
  78. hash3D( floor( pixScales.x * position.xyz ) ),
  79. hash3D( floor( pixScales.y * position.xyz ) )
  80. );
  81. float lerpFactor = fract( log2( pixScale ) );
  82. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  83. float a = min( lerpFactor, 1.0 - lerpFactor );
  84. vec3 cases = vec3(
  85. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  86. ( x - 0.5 * a ) / ( 1.0 - a ),
  87. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  88. );
  89. float threshold = ( x < ( 1.0 - a ) )
  90. ? ( ( x < a ) ? cases.x : cases.y )
  91. : cases.z;
  92. return clamp( threshold , 1.0e-6, 1.0 );
  93. }
  94. #endif`,Jwe=`#ifdef USE_ALPHAMAP
  95. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  96. #endif`,eSe=`#ifdef USE_ALPHAMAP
  97. uniform sampler2D alphaMap;
  98. #endif`,tSe=`#ifdef USE_ALPHATEST
  99. #ifdef ALPHA_TO_COVERAGE
  100. diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
  101. if ( diffuseColor.a == 0.0 ) discard;
  102. #else
  103. if ( diffuseColor.a < alphaTest ) discard;
  104. #endif
  105. #endif`,nSe=`#ifdef USE_ALPHATEST
  106. uniform float alphaTest;
  107. #endif`,rSe=`#ifdef USE_AOMAP
  108. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  109. reflectedLight.indirectDiffuse *= ambientOcclusion;
  110. #if defined( USE_CLEARCOAT )
  111. clearcoatSpecularIndirect *= ambientOcclusion;
  112. #endif
  113. #if defined( USE_SHEEN )
  114. sheenSpecularIndirect *= ambientOcclusion;
  115. #endif
  116. #if defined( USE_ENVMAP ) && defined( STANDARD )
  117. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  118. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  119. #endif
  120. #endif`,aSe=`#ifdef USE_AOMAP
  121. uniform sampler2D aoMap;
  122. uniform float aoMapIntensity;
  123. #endif`,iSe=`#ifdef USE_BATCHING
  124. #if ! defined( GL_ANGLE_multi_draw )
  125. #define gl_DrawID _gl_DrawID
  126. uniform int _gl_DrawID;
  127. #endif
  128. uniform highp sampler2D batchingTexture;
  129. uniform highp usampler2D batchingIdTexture;
  130. mat4 getBatchingMatrix( const in float i ) {
  131. int size = textureSize( batchingTexture, 0 ).x;
  132. int j = int( i ) * 4;
  133. int x = j % size;
  134. int y = j / size;
  135. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  136. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  137. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  138. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  139. return mat4( v1, v2, v3, v4 );
  140. }
  141. float getIndirectIndex( const in int i ) {
  142. int size = textureSize( batchingIdTexture, 0 ).x;
  143. int x = i % size;
  144. int y = i / size;
  145. return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
  146. }
  147. #endif
  148. #ifdef USE_BATCHING_COLOR
  149. uniform sampler2D batchingColorTexture;
  150. vec3 getBatchingColor( const in float i ) {
  151. int size = textureSize( batchingColorTexture, 0 ).x;
  152. int j = int( i );
  153. int x = j % size;
  154. int y = j / size;
  155. return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
  156. }
  157. #endif`,sSe=`#ifdef USE_BATCHING
  158. mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
  159. #endif`,oSe=`vec3 transformed = vec3( position );
  160. #ifdef USE_ALPHAHASH
  161. vPosition = vec3( position );
  162. #endif`,lSe=`vec3 objectNormal = vec3( normal );
  163. #ifdef USE_TANGENT
  164. vec3 objectTangent = vec3( tangent.xyz );
  165. #endif`,cSe=`float G_BlinnPhong_Implicit( ) {
  166. return 0.25;
  167. }
  168. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  169. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  170. }
  171. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  172. vec3 halfDir = normalize( lightDir + viewDir );
  173. float dotNH = saturate( dot( normal, halfDir ) );
  174. float dotVH = saturate( dot( viewDir, halfDir ) );
  175. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  176. float G = G_BlinnPhong_Implicit( );
  177. float D = D_BlinnPhong( shininess, dotNH );
  178. return F * ( G * D );
  179. } // validated`,dSe=`#ifdef USE_IRIDESCENCE
  180. const mat3 XYZ_TO_REC709 = mat3(
  181. 3.2404542, -0.9692660, 0.0556434,
  182. -1.5371385, 1.8760108, -0.2040259,
  183. -0.4985314, 0.0415560, 1.0572252
  184. );
  185. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  186. vec3 sqrtF0 = sqrt( fresnel0 );
  187. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  188. }
  189. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  190. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  191. }
  192. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  193. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  194. }
  195. vec3 evalSensitivity( float OPD, vec3 shift ) {
  196. float phase = 2.0 * PI * OPD * 1.0e-9;
  197. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  198. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  199. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  200. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  201. 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 ) );
  202. xyz /= 1.0685e-7;
  203. vec3 rgb = XYZ_TO_REC709 * xyz;
  204. return rgb;
  205. }
  206. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  207. vec3 I;
  208. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  209. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  210. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  211. if ( cosTheta2Sq < 0.0 ) {
  212. return vec3( 1.0 );
  213. }
  214. float cosTheta2 = sqrt( cosTheta2Sq );
  215. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  216. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  217. float T121 = 1.0 - R12;
  218. float phi12 = 0.0;
  219. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  220. float phi21 = PI - phi12;
  221. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  222. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  223. vec3 phi23 = vec3( 0.0 );
  224. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  225. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  226. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  227. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  228. vec3 phi = vec3( phi21 ) + phi23;
  229. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  230. vec3 r123 = sqrt( R123 );
  231. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  232. vec3 C0 = R12 + Rs;
  233. I = C0;
  234. vec3 Cm = Rs - T121;
  235. for ( int m = 1; m <= 2; ++ m ) {
  236. Cm *= r123;
  237. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  238. I += Cm * Sm;
  239. }
  240. return max( I, vec3( 0.0 ) );
  241. }
  242. #endif`,uSe=`#ifdef USE_BUMPMAP
  243. uniform sampler2D bumpMap;
  244. uniform float bumpScale;
  245. vec2 dHdxy_fwd() {
  246. vec2 dSTdx = dFdx( vBumpMapUv );
  247. vec2 dSTdy = dFdy( vBumpMapUv );
  248. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  249. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  250. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  251. return vec2( dBx, dBy );
  252. }
  253. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  254. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  255. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  256. vec3 vN = surf_norm;
  257. vec3 R1 = cross( vSigmaY, vN );
  258. vec3 R2 = cross( vN, vSigmaX );
  259. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  260. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  261. return normalize( abs( fDet ) * surf_norm - vGrad );
  262. }
  263. #endif`,mSe=`#if NUM_CLIPPING_PLANES > 0
  264. vec4 plane;
  265. #ifdef ALPHA_TO_COVERAGE
  266. float distanceToPlane, distanceGradient;
  267. float clipOpacity = 1.0;
  268. #pragma unroll_loop_start
  269. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  270. plane = clippingPlanes[ i ];
  271. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  272. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  273. clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  274. if ( clipOpacity == 0.0 ) discard;
  275. }
  276. #pragma unroll_loop_end
  277. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  278. float unionClipOpacity = 1.0;
  279. #pragma unroll_loop_start
  280. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  281. plane = clippingPlanes[ i ];
  282. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  283. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  284. unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  285. }
  286. #pragma unroll_loop_end
  287. clipOpacity *= 1.0 - unionClipOpacity;
  288. #endif
  289. diffuseColor.a *= clipOpacity;
  290. if ( diffuseColor.a == 0.0 ) discard;
  291. #else
  292. #pragma unroll_loop_start
  293. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  294. plane = clippingPlanes[ i ];
  295. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  296. }
  297. #pragma unroll_loop_end
  298. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  299. bool clipped = true;
  300. #pragma unroll_loop_start
  301. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  302. plane = clippingPlanes[ i ];
  303. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  304. }
  305. #pragma unroll_loop_end
  306. if ( clipped ) discard;
  307. #endif
  308. #endif
  309. #endif`,pSe=`#if NUM_CLIPPING_PLANES > 0
  310. varying vec3 vClipPosition;
  311. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  312. #endif`,hSe=`#if NUM_CLIPPING_PLANES > 0
  313. varying vec3 vClipPosition;
  314. #endif`,fSe=`#if NUM_CLIPPING_PLANES > 0
  315. vClipPosition = - mvPosition.xyz;
  316. #endif`,gSe=`#if defined( USE_COLOR_ALPHA )
  317. diffuseColor *= vColor;
  318. #elif defined( USE_COLOR )
  319. diffuseColor.rgb *= vColor;
  320. #endif`,bSe=`#if defined( USE_COLOR_ALPHA )
  321. varying vec4 vColor;
  322. #elif defined( USE_COLOR )
  323. varying vec3 vColor;
  324. #endif`,xSe=`#if defined( USE_COLOR_ALPHA )
  325. varying vec4 vColor;
  326. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  327. varying vec3 vColor;
  328. #endif`,ySe=`#if defined( USE_COLOR_ALPHA )
  329. vColor = vec4( 1.0 );
  330. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  331. vColor = vec3( 1.0 );
  332. #endif
  333. #ifdef USE_COLOR
  334. vColor *= color;
  335. #endif
  336. #ifdef USE_INSTANCING_COLOR
  337. vColor.xyz *= instanceColor.xyz;
  338. #endif
  339. #ifdef USE_BATCHING_COLOR
  340. vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
  341. vColor.xyz *= batchingColor.xyz;
  342. #endif`,vSe=`#define PI 3.141592653589793
  343. #define PI2 6.283185307179586
  344. #define PI_HALF 1.5707963267948966
  345. #define RECIPROCAL_PI 0.3183098861837907
  346. #define RECIPROCAL_PI2 0.15915494309189535
  347. #define EPSILON 1e-6
  348. #ifndef saturate
  349. #define saturate( a ) clamp( a, 0.0, 1.0 )
  350. #endif
  351. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  352. float pow2( const in float x ) { return x*x; }
  353. vec3 pow2( const in vec3 x ) { return x*x; }
  354. float pow3( const in float x ) { return x*x*x; }
  355. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  356. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  357. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  358. highp float rand( const in vec2 uv ) {
  359. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  360. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  361. return fract( sin( sn ) * c );
  362. }
  363. #ifdef HIGH_PRECISION
  364. float precisionSafeLength( vec3 v ) { return length( v ); }
  365. #else
  366. float precisionSafeLength( vec3 v ) {
  367. float maxComponent = max3( abs( v ) );
  368. return length( v / maxComponent ) * maxComponent;
  369. }
  370. #endif
  371. struct IncidentLight {
  372. vec3 color;
  373. vec3 direction;
  374. bool visible;
  375. };
  376. struct ReflectedLight {
  377. vec3 directDiffuse;
  378. vec3 directSpecular;
  379. vec3 indirectDiffuse;
  380. vec3 indirectSpecular;
  381. };
  382. #ifdef USE_ALPHAHASH
  383. varying vec3 vPosition;
  384. #endif
  385. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  386. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  387. }
  388. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  389. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  390. }
  391. bool isPerspectiveMatrix( mat4 m ) {
  392. return m[ 2 ][ 3 ] == - 1.0;
  393. }
  394. vec2 equirectUv( in vec3 dir ) {
  395. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  396. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  397. return vec2( u, v );
  398. }
  399. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  400. return RECIPROCAL_PI * diffuseColor;
  401. }
  402. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  403. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  404. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  405. }
  406. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  407. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  408. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  409. } // validated`,wSe=`#ifdef ENVMAP_TYPE_CUBE_UV
  410. #define cubeUV_minMipLevel 4.0
  411. #define cubeUV_minTileSize 16.0
  412. float getFace( vec3 direction ) {
  413. vec3 absDirection = abs( direction );
  414. float face = - 1.0;
  415. if ( absDirection.x > absDirection.z ) {
  416. if ( absDirection.x > absDirection.y )
  417. face = direction.x > 0.0 ? 0.0 : 3.0;
  418. else
  419. face = direction.y > 0.0 ? 1.0 : 4.0;
  420. } else {
  421. if ( absDirection.z > absDirection.y )
  422. face = direction.z > 0.0 ? 2.0 : 5.0;
  423. else
  424. face = direction.y > 0.0 ? 1.0 : 4.0;
  425. }
  426. return face;
  427. }
  428. vec2 getUV( vec3 direction, float face ) {
  429. vec2 uv;
  430. if ( face == 0.0 ) {
  431. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  432. } else if ( face == 1.0 ) {
  433. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  434. } else if ( face == 2.0 ) {
  435. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  436. } else if ( face == 3.0 ) {
  437. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  438. } else if ( face == 4.0 ) {
  439. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  440. } else {
  441. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  442. }
  443. return 0.5 * ( uv + 1.0 );
  444. }
  445. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  446. float face = getFace( direction );
  447. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  448. mipInt = max( mipInt, cubeUV_minMipLevel );
  449. float faceSize = exp2( mipInt );
  450. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  451. if ( face > 2.0 ) {
  452. uv.y += faceSize;
  453. face -= 3.0;
  454. }
  455. uv.x += face * faceSize;
  456. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  457. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  458. uv.x *= CUBEUV_TEXEL_WIDTH;
  459. uv.y *= CUBEUV_TEXEL_HEIGHT;
  460. #ifdef texture2DGradEXT
  461. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  462. #else
  463. return texture2D( envMap, uv ).rgb;
  464. #endif
  465. }
  466. #define cubeUV_r0 1.0
  467. #define cubeUV_m0 - 2.0
  468. #define cubeUV_r1 0.8
  469. #define cubeUV_m1 - 1.0
  470. #define cubeUV_r4 0.4
  471. #define cubeUV_m4 2.0
  472. #define cubeUV_r5 0.305
  473. #define cubeUV_m5 3.0
  474. #define cubeUV_r6 0.21
  475. #define cubeUV_m6 4.0
  476. float roughnessToMip( float roughness ) {
  477. float mip = 0.0;
  478. if ( roughness >= cubeUV_r1 ) {
  479. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  480. } else if ( roughness >= cubeUV_r4 ) {
  481. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  482. } else if ( roughness >= cubeUV_r5 ) {
  483. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  484. } else if ( roughness >= cubeUV_r6 ) {
  485. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  486. } else {
  487. mip = - 2.0 * log2( 1.16 * roughness ); }
  488. return mip;
  489. }
  490. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  491. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  492. float mipF = fract( mip );
  493. float mipInt = floor( mip );
  494. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  495. if ( mipF == 0.0 ) {
  496. return vec4( color0, 1.0 );
  497. } else {
  498. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  499. return vec4( mix( color0, color1, mipF ), 1.0 );
  500. }
  501. }
  502. #endif`,SSe=`vec3 transformedNormal = objectNormal;
  503. #ifdef USE_TANGENT
  504. vec3 transformedTangent = objectTangent;
  505. #endif
  506. #ifdef USE_BATCHING
  507. mat3 bm = mat3( batchingMatrix );
  508. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  509. transformedNormal = bm * transformedNormal;
  510. #ifdef USE_TANGENT
  511. transformedTangent = bm * transformedTangent;
  512. #endif
  513. #endif
  514. #ifdef USE_INSTANCING
  515. mat3 im = mat3( instanceMatrix );
  516. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  517. transformedNormal = im * transformedNormal;
  518. #ifdef USE_TANGENT
  519. transformedTangent = im * transformedTangent;
  520. #endif
  521. #endif
  522. transformedNormal = normalMatrix * transformedNormal;
  523. #ifdef FLIP_SIDED
  524. transformedNormal = - transformedNormal;
  525. #endif
  526. #ifdef USE_TANGENT
  527. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  528. #ifdef FLIP_SIDED
  529. transformedTangent = - transformedTangent;
  530. #endif
  531. #endif`,_Se=`#ifdef USE_DISPLACEMENTMAP
  532. uniform sampler2D displacementMap;
  533. uniform float displacementScale;
  534. uniform float displacementBias;
  535. #endif`,kSe=`#ifdef USE_DISPLACEMENTMAP
  536. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  537. #endif`,NSe=`#ifdef USE_EMISSIVEMAP
  538. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  539. #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
  540. emissiveColor = sRGBTransferEOTF( emissiveColor );
  541. #endif
  542. totalEmissiveRadiance *= emissiveColor.rgb;
  543. #endif`,CSe=`#ifdef USE_EMISSIVEMAP
  544. uniform sampler2D emissiveMap;
  545. #endif`,PSe="gl_FragColor = linearToOutputTexel( gl_FragColor );",TSe=`vec4 LinearTransferOETF( in vec4 value ) {
  546. return value;
  547. }
  548. vec4 sRGBTransferEOTF( in vec4 value ) {
  549. 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 );
  550. }
  551. vec4 sRGBTransferOETF( in vec4 value ) {
  552. 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 );
  553. }`,ASe=`#ifdef USE_ENVMAP
  554. #ifdef ENV_WORLDPOS
  555. vec3 cameraToFrag;
  556. if ( isOrthographic ) {
  557. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  558. } else {
  559. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  560. }
  561. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  562. #ifdef ENVMAP_MODE_REFLECTION
  563. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  564. #else
  565. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  566. #endif
  567. #else
  568. vec3 reflectVec = vReflect;
  569. #endif
  570. #ifdef ENVMAP_TYPE_CUBE
  571. vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  572. #else
  573. vec4 envColor = vec4( 0.0 );
  574. #endif
  575. #ifdef ENVMAP_BLENDING_MULTIPLY
  576. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  577. #elif defined( ENVMAP_BLENDING_MIX )
  578. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  579. #elif defined( ENVMAP_BLENDING_ADD )
  580. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  581. #endif
  582. #endif`,jSe=`#ifdef USE_ENVMAP
  583. uniform float envMapIntensity;
  584. uniform float flipEnvMap;
  585. uniform mat3 envMapRotation;
  586. #ifdef ENVMAP_TYPE_CUBE
  587. uniform samplerCube envMap;
  588. #else
  589. uniform sampler2D envMap;
  590. #endif
  591. #endif`,MSe=`#ifdef USE_ENVMAP
  592. uniform float reflectivity;
  593. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  594. #define ENV_WORLDPOS
  595. #endif
  596. #ifdef ENV_WORLDPOS
  597. varying vec3 vWorldPosition;
  598. uniform float refractionRatio;
  599. #else
  600. varying vec3 vReflect;
  601. #endif
  602. #endif`,ESe=`#ifdef USE_ENVMAP
  603. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  604. #define ENV_WORLDPOS
  605. #endif
  606. #ifdef ENV_WORLDPOS
  607. varying vec3 vWorldPosition;
  608. #else
  609. varying vec3 vReflect;
  610. uniform float refractionRatio;
  611. #endif
  612. #endif`,DSe=`#ifdef USE_ENVMAP
  613. #ifdef ENV_WORLDPOS
  614. vWorldPosition = worldPosition.xyz;
  615. #else
  616. vec3 cameraToVertex;
  617. if ( isOrthographic ) {
  618. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  619. } else {
  620. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  621. }
  622. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  623. #ifdef ENVMAP_MODE_REFLECTION
  624. vReflect = reflect( cameraToVertex, worldNormal );
  625. #else
  626. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  627. #endif
  628. #endif
  629. #endif`,FSe=`#ifdef USE_FOG
  630. vFogDepth = - mvPosition.z;
  631. #endif`,LSe=`#ifdef USE_FOG
  632. varying float vFogDepth;
  633. #endif`,RSe=`#ifdef USE_FOG
  634. #ifdef FOG_EXP2
  635. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  636. #else
  637. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  638. #endif
  639. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  640. #endif`,ISe=`#ifdef USE_FOG
  641. uniform vec3 fogColor;
  642. varying float vFogDepth;
  643. #ifdef FOG_EXP2
  644. uniform float fogDensity;
  645. #else
  646. uniform float fogNear;
  647. uniform float fogFar;
  648. #endif
  649. #endif`,OSe=`#ifdef USE_GRADIENTMAP
  650. uniform sampler2D gradientMap;
  651. #endif
  652. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  653. float dotNL = dot( normal, lightDirection );
  654. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  655. #ifdef USE_GRADIENTMAP
  656. return vec3( texture2D( gradientMap, coord ).r );
  657. #else
  658. vec2 fw = fwidth( coord ) * 0.5;
  659. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  660. #endif
  661. }`,zSe=`#ifdef USE_LIGHTMAP
  662. uniform sampler2D lightMap;
  663. uniform float lightMapIntensity;
  664. #endif`,USe=`LambertMaterial material;
  665. material.diffuseColor = diffuseColor.rgb;
  666. material.specularStrength = specularStrength;`,BSe=`varying vec3 vViewPosition;
  667. struct LambertMaterial {
  668. vec3 diffuseColor;
  669. float specularStrength;
  670. };
  671. 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 ) {
  672. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  673. vec3 irradiance = dotNL * directLight.color;
  674. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  675. }
  676. 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 ) {
  677. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  678. }
  679. #define RE_Direct RE_Direct_Lambert
  680. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,HSe=`uniform bool receiveShadow;
  681. uniform vec3 ambientLightColor;
  682. #if defined( USE_LIGHT_PROBES )
  683. uniform vec3 lightProbe[ 9 ];
  684. #endif
  685. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  686. float x = normal.x, y = normal.y, z = normal.z;
  687. vec3 result = shCoefficients[ 0 ] * 0.886227;
  688. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  689. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  690. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  691. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  692. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  693. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  694. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  695. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  696. return result;
  697. }
  698. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  699. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  700. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  701. return irradiance;
  702. }
  703. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  704. vec3 irradiance = ambientLightColor;
  705. return irradiance;
  706. }
  707. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  708. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  709. if ( cutoffDistance > 0.0 ) {
  710. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  711. }
  712. return distanceFalloff;
  713. }
  714. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  715. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  716. }
  717. #if NUM_DIR_LIGHTS > 0
  718. struct DirectionalLight {
  719. vec3 direction;
  720. vec3 color;
  721. };
  722. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  723. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  724. light.color = directionalLight.color;
  725. light.direction = directionalLight.direction;
  726. light.visible = true;
  727. }
  728. #endif
  729. #if NUM_POINT_LIGHTS > 0
  730. struct PointLight {
  731. vec3 position;
  732. vec3 color;
  733. float distance;
  734. float decay;
  735. };
  736. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  737. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  738. vec3 lVector = pointLight.position - geometryPosition;
  739. light.direction = normalize( lVector );
  740. float lightDistance = length( lVector );
  741. light.color = pointLight.color;
  742. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  743. light.visible = ( light.color != vec3( 0.0 ) );
  744. }
  745. #endif
  746. #if NUM_SPOT_LIGHTS > 0
  747. struct SpotLight {
  748. vec3 position;
  749. vec3 direction;
  750. vec3 color;
  751. float distance;
  752. float decay;
  753. float coneCos;
  754. float penumbraCos;
  755. };
  756. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  757. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  758. vec3 lVector = spotLight.position - geometryPosition;
  759. light.direction = normalize( lVector );
  760. float angleCos = dot( light.direction, spotLight.direction );
  761. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  762. if ( spotAttenuation > 0.0 ) {
  763. float lightDistance = length( lVector );
  764. light.color = spotLight.color * spotAttenuation;
  765. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  766. light.visible = ( light.color != vec3( 0.0 ) );
  767. } else {
  768. light.color = vec3( 0.0 );
  769. light.visible = false;
  770. }
  771. }
  772. #endif
  773. #if NUM_RECT_AREA_LIGHTS > 0
  774. struct RectAreaLight {
  775. vec3 color;
  776. vec3 position;
  777. vec3 halfWidth;
  778. vec3 halfHeight;
  779. };
  780. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  781. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  782. #endif
  783. #if NUM_HEMI_LIGHTS > 0
  784. struct HemisphereLight {
  785. vec3 direction;
  786. vec3 skyColor;
  787. vec3 groundColor;
  788. };
  789. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  790. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  791. float dotNL = dot( normal, hemiLight.direction );
  792. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  793. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  794. return irradiance;
  795. }
  796. #endif`,qSe=`#ifdef USE_ENVMAP
  797. vec3 getIBLIrradiance( const in vec3 normal ) {
  798. #ifdef ENVMAP_TYPE_CUBE_UV
  799. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  800. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
  801. return PI * envMapColor.rgb * envMapIntensity;
  802. #else
  803. return vec3( 0.0 );
  804. #endif
  805. }
  806. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  807. #ifdef ENVMAP_TYPE_CUBE_UV
  808. vec3 reflectVec = reflect( - viewDir, normal );
  809. reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
  810. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  811. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
  812. return envMapColor.rgb * envMapIntensity;
  813. #else
  814. return vec3( 0.0 );
  815. #endif
  816. }
  817. #ifdef USE_ANISOTROPY
  818. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  819. #ifdef ENVMAP_TYPE_CUBE_UV
  820. vec3 bentNormal = cross( bitangent, viewDir );
  821. bentNormal = normalize( cross( bentNormal, bitangent ) );
  822. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  823. return getIBLRadiance( viewDir, bentNormal, roughness );
  824. #else
  825. return vec3( 0.0 );
  826. #endif
  827. }
  828. #endif
  829. #endif`,$Se=`ToonMaterial material;
  830. material.diffuseColor = diffuseColor.rgb;`,VSe=`varying vec3 vViewPosition;
  831. struct ToonMaterial {
  832. vec3 diffuseColor;
  833. };
  834. 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 ) {
  835. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  836. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  837. }
  838. 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 ) {
  839. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  840. }
  841. #define RE_Direct RE_Direct_Toon
  842. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,GSe=`BlinnPhongMaterial material;
  843. material.diffuseColor = diffuseColor.rgb;
  844. material.specularColor = specular;
  845. material.specularShininess = shininess;
  846. material.specularStrength = specularStrength;`,WSe=`varying vec3 vViewPosition;
  847. struct BlinnPhongMaterial {
  848. vec3 diffuseColor;
  849. vec3 specularColor;
  850. float specularShininess;
  851. float specularStrength;
  852. };
  853. 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 ) {
  854. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  855. vec3 irradiance = dotNL * directLight.color;
  856. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  857. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  858. }
  859. 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 ) {
  860. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  861. }
  862. #define RE_Direct RE_Direct_BlinnPhong
  863. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,KSe=`PhysicalMaterial material;
  864. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  865. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  866. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  867. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  868. material.roughness = min( material.roughness, 1.0 );
  869. #ifdef IOR
  870. material.ior = ior;
  871. #ifdef USE_SPECULAR
  872. float specularIntensityFactor = specularIntensity;
  873. vec3 specularColorFactor = specularColor;
  874. #ifdef USE_SPECULAR_COLORMAP
  875. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  876. #endif
  877. #ifdef USE_SPECULAR_INTENSITYMAP
  878. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  879. #endif
  880. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  881. #else
  882. float specularIntensityFactor = 1.0;
  883. vec3 specularColorFactor = vec3( 1.0 );
  884. material.specularF90 = 1.0;
  885. #endif
  886. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  887. #else
  888. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  889. material.specularF90 = 1.0;
  890. #endif
  891. #ifdef USE_CLEARCOAT
  892. material.clearcoat = clearcoat;
  893. material.clearcoatRoughness = clearcoatRoughness;
  894. material.clearcoatF0 = vec3( 0.04 );
  895. material.clearcoatF90 = 1.0;
  896. #ifdef USE_CLEARCOATMAP
  897. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  898. #endif
  899. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  900. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  901. #endif
  902. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  903. material.clearcoatRoughness += geometryRoughness;
  904. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  905. #endif
  906. #ifdef USE_DISPERSION
  907. material.dispersion = dispersion;
  908. #endif
  909. #ifdef USE_IRIDESCENCE
  910. material.iridescence = iridescence;
  911. material.iridescenceIOR = iridescenceIOR;
  912. #ifdef USE_IRIDESCENCEMAP
  913. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  914. #endif
  915. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  916. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  917. #else
  918. material.iridescenceThickness = iridescenceThicknessMaximum;
  919. #endif
  920. #endif
  921. #ifdef USE_SHEEN
  922. material.sheenColor = sheenColor;
  923. #ifdef USE_SHEEN_COLORMAP
  924. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  925. #endif
  926. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  927. #ifdef USE_SHEEN_ROUGHNESSMAP
  928. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  929. #endif
  930. #endif
  931. #ifdef USE_ANISOTROPY
  932. #ifdef USE_ANISOTROPYMAP
  933. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  934. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  935. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  936. #else
  937. vec2 anisotropyV = anisotropyVector;
  938. #endif
  939. material.anisotropy = length( anisotropyV );
  940. if( material.anisotropy == 0.0 ) {
  941. anisotropyV = vec2( 1.0, 0.0 );
  942. } else {
  943. anisotropyV /= material.anisotropy;
  944. material.anisotropy = saturate( material.anisotropy );
  945. }
  946. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  947. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  948. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  949. #endif`,QSe=`uniform sampler2D dfgLUT;
  950. struct PhysicalMaterial {
  951. vec3 diffuseColor;
  952. float roughness;
  953. vec3 specularColor;
  954. float specularF90;
  955. float dispersion;
  956. #ifdef USE_CLEARCOAT
  957. float clearcoat;
  958. float clearcoatRoughness;
  959. vec3 clearcoatF0;
  960. float clearcoatF90;
  961. #endif
  962. #ifdef USE_IRIDESCENCE
  963. float iridescence;
  964. float iridescenceIOR;
  965. float iridescenceThickness;
  966. vec3 iridescenceFresnel;
  967. vec3 iridescenceF0;
  968. #endif
  969. #ifdef USE_SHEEN
  970. vec3 sheenColor;
  971. float sheenRoughness;
  972. #endif
  973. #ifdef IOR
  974. float ior;
  975. #endif
  976. #ifdef USE_TRANSMISSION
  977. float transmission;
  978. float transmissionAlpha;
  979. float thickness;
  980. float attenuationDistance;
  981. vec3 attenuationColor;
  982. #endif
  983. #ifdef USE_ANISOTROPY
  984. float anisotropy;
  985. float alphaT;
  986. vec3 anisotropyT;
  987. vec3 anisotropyB;
  988. #endif
  989. };
  990. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  991. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  992. vec3 sheenSpecularDirect = vec3( 0.0 );
  993. vec3 sheenSpecularIndirect = vec3(0.0 );
  994. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  995. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  996. float x2 = x * x;
  997. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  998. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  999. }
  1000. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  1001. float a2 = pow2( alpha );
  1002. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  1003. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  1004. return 0.5 / max( gv + gl, EPSILON );
  1005. }
  1006. float D_GGX( const in float alpha, const in float dotNH ) {
  1007. float a2 = pow2( alpha );
  1008. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  1009. return RECIPROCAL_PI * a2 / pow2( denom );
  1010. }
  1011. #ifdef USE_ANISOTROPY
  1012. 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 ) {
  1013. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  1014. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  1015. float v = 0.5 / ( gv + gl );
  1016. return saturate(v);
  1017. }
  1018. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  1019. float a2 = alphaT * alphaB;
  1020. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  1021. highp float v2 = dot( v, v );
  1022. float w2 = a2 / v2;
  1023. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  1024. }
  1025. #endif
  1026. #ifdef USE_CLEARCOAT
  1027. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  1028. vec3 f0 = material.clearcoatF0;
  1029. float f90 = material.clearcoatF90;
  1030. float roughness = material.clearcoatRoughness;
  1031. float alpha = pow2( roughness );
  1032. vec3 halfDir = normalize( lightDir + viewDir );
  1033. float dotNL = saturate( dot( normal, lightDir ) );
  1034. float dotNV = saturate( dot( normal, viewDir ) );
  1035. float dotNH = saturate( dot( normal, halfDir ) );
  1036. float dotVH = saturate( dot( viewDir, halfDir ) );
  1037. vec3 F = F_Schlick( f0, f90, dotVH );
  1038. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1039. float D = D_GGX( alpha, dotNH );
  1040. return F * ( V * D );
  1041. }
  1042. #endif
  1043. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1044. vec3 f0 = material.specularColor;
  1045. float f90 = material.specularF90;
  1046. float roughness = material.roughness;
  1047. float alpha = pow2( roughness );
  1048. vec3 halfDir = normalize( lightDir + viewDir );
  1049. float dotNL = saturate( dot( normal, lightDir ) );
  1050. float dotNV = saturate( dot( normal, viewDir ) );
  1051. float dotNH = saturate( dot( normal, halfDir ) );
  1052. float dotVH = saturate( dot( viewDir, halfDir ) );
  1053. vec3 F = F_Schlick( f0, f90, dotVH );
  1054. #ifdef USE_IRIDESCENCE
  1055. F = mix( F, material.iridescenceFresnel, material.iridescence );
  1056. #endif
  1057. #ifdef USE_ANISOTROPY
  1058. float dotTL = dot( material.anisotropyT, lightDir );
  1059. float dotTV = dot( material.anisotropyT, viewDir );
  1060. float dotTH = dot( material.anisotropyT, halfDir );
  1061. float dotBL = dot( material.anisotropyB, lightDir );
  1062. float dotBV = dot( material.anisotropyB, viewDir );
  1063. float dotBH = dot( material.anisotropyB, halfDir );
  1064. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  1065. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  1066. #else
  1067. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1068. float D = D_GGX( alpha, dotNH );
  1069. #endif
  1070. return F * ( V * D );
  1071. }
  1072. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  1073. const float LUT_SIZE = 64.0;
  1074. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  1075. const float LUT_BIAS = 0.5 / LUT_SIZE;
  1076. float dotNV = saturate( dot( N, V ) );
  1077. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  1078. uv = uv * LUT_SCALE + LUT_BIAS;
  1079. return uv;
  1080. }
  1081. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  1082. float l = length( f );
  1083. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  1084. }
  1085. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  1086. float x = dot( v1, v2 );
  1087. float y = abs( x );
  1088. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  1089. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  1090. float v = a / b;
  1091. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  1092. return cross( v1, v2 ) * theta_sintheta;
  1093. }
  1094. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  1095. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  1096. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  1097. vec3 lightNormal = cross( v1, v2 );
  1098. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  1099. vec3 T1, T2;
  1100. T1 = normalize( V - N * dot( V, N ) );
  1101. T2 = - cross( N, T1 );
  1102. mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
  1103. vec3 coords[ 4 ];
  1104. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  1105. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  1106. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  1107. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  1108. coords[ 0 ] = normalize( coords[ 0 ] );
  1109. coords[ 1 ] = normalize( coords[ 1 ] );
  1110. coords[ 2 ] = normalize( coords[ 2 ] );
  1111. coords[ 3 ] = normalize( coords[ 3 ] );
  1112. vec3 vectorFormFactor = vec3( 0.0 );
  1113. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  1114. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  1115. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  1116. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  1117. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  1118. return vec3( result );
  1119. }
  1120. #if defined( USE_SHEEN )
  1121. float D_Charlie( float roughness, float dotNH ) {
  1122. float alpha = pow2( roughness );
  1123. float invAlpha = 1.0 / alpha;
  1124. float cos2h = dotNH * dotNH;
  1125. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  1126. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  1127. }
  1128. float V_Neubelt( float dotNV, float dotNL ) {
  1129. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  1130. }
  1131. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  1132. vec3 halfDir = normalize( lightDir + viewDir );
  1133. float dotNL = saturate( dot( normal, lightDir ) );
  1134. float dotNV = saturate( dot( normal, viewDir ) );
  1135. float dotNH = saturate( dot( normal, halfDir ) );
  1136. float D = D_Charlie( sheenRoughness, dotNH );
  1137. float V = V_Neubelt( dotNV, dotNL );
  1138. return sheenColor * ( D * V );
  1139. }
  1140. #endif
  1141. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1142. float dotNV = saturate( dot( normal, viewDir ) );
  1143. float r2 = roughness * roughness;
  1144. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  1145. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  1146. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  1147. return saturate( DG * RECIPROCAL_PI );
  1148. }
  1149. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1150. float dotNV = saturate( dot( normal, viewDir ) );
  1151. vec2 uv = vec2( roughness, dotNV );
  1152. return texture2D( dfgLUT, uv ).rg;
  1153. }
  1154. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  1155. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1156. return specularColor * fab.x + specularF90 * fab.y;
  1157. }
  1158. #ifdef USE_IRIDESCENCE
  1159. 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 ) {
  1160. #else
  1161. 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 ) {
  1162. #endif
  1163. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1164. #ifdef USE_IRIDESCENCE
  1165. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  1166. #else
  1167. vec3 Fr = specularColor;
  1168. #endif
  1169. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  1170. float Ess = fab.x + fab.y;
  1171. float Ems = 1.0 - Ess;
  1172. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  1173. singleScatter += FssEss;
  1174. multiScatter += Fms * Ems;
  1175. }
  1176. vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1177. vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
  1178. float dotNL = saturate( dot( normal, lightDir ) );
  1179. float dotNV = saturate( dot( normal, viewDir ) );
  1180. vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness );
  1181. vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness );
  1182. vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y;
  1183. vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y;
  1184. float Ess_V = dfgV.x + dfgV.y;
  1185. float Ess_L = dfgL.x + dfgL.y;
  1186. float Ems_V = 1.0 - Ess_V;
  1187. float Ems_L = 1.0 - Ess_L;
  1188. vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619;
  1189. vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON );
  1190. float compensationFactor = Ems_V * Ems_L;
  1191. vec3 multiScatter = Fms * compensationFactor;
  1192. return singleScatter + multiScatter;
  1193. }
  1194. #if NUM_RECT_AREA_LIGHTS > 0
  1195. 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 ) {
  1196. vec3 normal = geometryNormal;
  1197. vec3 viewDir = geometryViewDir;
  1198. vec3 position = geometryPosition;
  1199. vec3 lightPos = rectAreaLight.position;
  1200. vec3 halfWidth = rectAreaLight.halfWidth;
  1201. vec3 halfHeight = rectAreaLight.halfHeight;
  1202. vec3 lightColor = rectAreaLight.color;
  1203. float roughness = material.roughness;
  1204. vec3 rectCoords[ 4 ];
  1205. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  1206. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  1207. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  1208. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  1209. vec4 t1 = texture2D( ltc_1, uv );
  1210. vec4 t2 = texture2D( ltc_2, uv );
  1211. mat3 mInv = mat3(
  1212. vec3( t1.x, 0, t1.y ),
  1213. vec3( 0, 1, 0 ),
  1214. vec3( t1.z, 0, t1.w )
  1215. );
  1216. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  1217. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  1218. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  1219. }
  1220. #endif
  1221. 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 ) {
  1222. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  1223. vec3 irradiance = dotNL * directLight.color;
  1224. #ifdef USE_CLEARCOAT
  1225. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  1226. vec3 ccIrradiance = dotNLcc * directLight.color;
  1227. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  1228. #endif
  1229. #ifdef USE_SHEEN
  1230. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  1231. #endif
  1232. reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
  1233. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1234. }
  1235. 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 ) {
  1236. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1237. }
  1238. 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) {
  1239. #ifdef USE_CLEARCOAT
  1240. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  1241. #endif
  1242. #ifdef USE_SHEEN
  1243. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  1244. #endif
  1245. vec3 singleScattering = vec3( 0.0 );
  1246. vec3 multiScattering = vec3( 0.0 );
  1247. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  1248. #ifdef USE_IRIDESCENCE
  1249. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  1250. #else
  1251. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  1252. #endif
  1253. vec3 totalScattering = singleScattering + multiScattering;
  1254. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  1255. reflectedLight.indirectSpecular += radiance * singleScattering;
  1256. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  1257. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  1258. }
  1259. #define RE_Direct RE_Direct_Physical
  1260. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  1261. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  1262. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  1263. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  1264. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  1265. }`,YSe=`
  1266. vec3 geometryPosition = - vViewPosition;
  1267. vec3 geometryNormal = normal;
  1268. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  1269. vec3 geometryClearcoatNormal = vec3( 0.0 );
  1270. #ifdef USE_CLEARCOAT
  1271. geometryClearcoatNormal = clearcoatNormal;
  1272. #endif
  1273. #ifdef USE_IRIDESCENCE
  1274. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  1275. if ( material.iridescenceThickness == 0.0 ) {
  1276. material.iridescence = 0.0;
  1277. } else {
  1278. material.iridescence = saturate( material.iridescence );
  1279. }
  1280. if ( material.iridescence > 0.0 ) {
  1281. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  1282. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  1283. }
  1284. #endif
  1285. IncidentLight directLight;
  1286. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  1287. PointLight pointLight;
  1288. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  1289. PointLightShadow pointLightShadow;
  1290. #endif
  1291. #pragma unroll_loop_start
  1292. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  1293. pointLight = pointLights[ i ];
  1294. getPointLightInfo( pointLight, geometryPosition, directLight );
  1295. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  1296. pointLightShadow = pointLightShadows[ i ];
  1297. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  1298. #endif
  1299. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1300. }
  1301. #pragma unroll_loop_end
  1302. #endif
  1303. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  1304. SpotLight spotLight;
  1305. vec4 spotColor;
  1306. vec3 spotLightCoord;
  1307. bool inSpotLightMap;
  1308. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  1309. SpotLightShadow spotLightShadow;
  1310. #endif
  1311. #pragma unroll_loop_start
  1312. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  1313. spotLight = spotLights[ i ];
  1314. getSpotLightInfo( spotLight, geometryPosition, directLight );
  1315. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1316. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  1317. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1318. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  1319. #else
  1320. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1321. #endif
  1322. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  1323. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  1324. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  1325. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  1326. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  1327. #endif
  1328. #undef SPOT_LIGHT_MAP_INDEX
  1329. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1330. spotLightShadow = spotLightShadows[ i ];
  1331. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1332. #endif
  1333. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1334. }
  1335. #pragma unroll_loop_end
  1336. #endif
  1337. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  1338. DirectionalLight directionalLight;
  1339. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  1340. DirectionalLightShadow directionalLightShadow;
  1341. #endif
  1342. #pragma unroll_loop_start
  1343. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  1344. directionalLight = directionalLights[ i ];
  1345. getDirectionalLightInfo( directionalLight, directLight );
  1346. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  1347. directionalLightShadow = directionalLightShadows[ i ];
  1348. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1349. #endif
  1350. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1351. }
  1352. #pragma unroll_loop_end
  1353. #endif
  1354. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  1355. RectAreaLight rectAreaLight;
  1356. #pragma unroll_loop_start
  1357. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  1358. rectAreaLight = rectAreaLights[ i ];
  1359. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1360. }
  1361. #pragma unroll_loop_end
  1362. #endif
  1363. #if defined( RE_IndirectDiffuse )
  1364. vec3 iblIrradiance = vec3( 0.0 );
  1365. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  1366. #if defined( USE_LIGHT_PROBES )
  1367. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  1368. #endif
  1369. #if ( NUM_HEMI_LIGHTS > 0 )
  1370. #pragma unroll_loop_start
  1371. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  1372. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  1373. }
  1374. #pragma unroll_loop_end
  1375. #endif
  1376. #endif
  1377. #if defined( RE_IndirectSpecular )
  1378. vec3 radiance = vec3( 0.0 );
  1379. vec3 clearcoatRadiance = vec3( 0.0 );
  1380. #endif`,XSe=`#if defined( RE_IndirectDiffuse )
  1381. #ifdef USE_LIGHTMAP
  1382. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  1383. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  1384. irradiance += lightMapIrradiance;
  1385. #endif
  1386. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  1387. iblIrradiance += getIBLIrradiance( geometryNormal );
  1388. #endif
  1389. #endif
  1390. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  1391. #ifdef USE_ANISOTROPY
  1392. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  1393. #else
  1394. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  1395. #endif
  1396. #ifdef USE_CLEARCOAT
  1397. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  1398. #endif
  1399. #endif`,ZSe=`#if defined( RE_IndirectDiffuse )
  1400. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1401. #endif
  1402. #if defined( RE_IndirectSpecular )
  1403. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1404. #endif`,JSe=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1405. gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  1406. #endif`,e_e=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1407. uniform float logDepthBufFC;
  1408. varying float vFragDepth;
  1409. varying float vIsPerspective;
  1410. #endif`,t_e=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1411. varying float vFragDepth;
  1412. varying float vIsPerspective;
  1413. #endif`,n_e=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1414. vFragDepth = 1.0 + gl_Position.w;
  1415. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  1416. #endif`,r_e=`#ifdef USE_MAP
  1417. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  1418. #ifdef DECODE_VIDEO_TEXTURE
  1419. sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
  1420. #endif
  1421. diffuseColor *= sampledDiffuseColor;
  1422. #endif`,a_e=`#ifdef USE_MAP
  1423. uniform sampler2D map;
  1424. #endif`,i_e=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1425. #if defined( USE_POINTS_UV )
  1426. vec2 uv = vUv;
  1427. #else
  1428. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  1429. #endif
  1430. #endif
  1431. #ifdef USE_MAP
  1432. diffuseColor *= texture2D( map, uv );
  1433. #endif
  1434. #ifdef USE_ALPHAMAP
  1435. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  1436. #endif`,s_e=`#if defined( USE_POINTS_UV )
  1437. varying vec2 vUv;
  1438. #else
  1439. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1440. uniform mat3 uvTransform;
  1441. #endif
  1442. #endif
  1443. #ifdef USE_MAP
  1444. uniform sampler2D map;
  1445. #endif
  1446. #ifdef USE_ALPHAMAP
  1447. uniform sampler2D alphaMap;
  1448. #endif`,o_e=`float metalnessFactor = metalness;
  1449. #ifdef USE_METALNESSMAP
  1450. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  1451. metalnessFactor *= texelMetalness.b;
  1452. #endif`,l_e=`#ifdef USE_METALNESSMAP
  1453. uniform sampler2D metalnessMap;
  1454. #endif`,c_e=`#ifdef USE_INSTANCING_MORPH
  1455. float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1456. float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
  1457. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1458. morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
  1459. }
  1460. #endif`,d_e=`#if defined( USE_MORPHCOLORS )
  1461. vColor *= morphTargetBaseInfluence;
  1462. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1463. #if defined( USE_COLOR_ALPHA )
  1464. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  1465. #elif defined( USE_COLOR )
  1466. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  1467. #endif
  1468. }
  1469. #endif`,u_e=`#ifdef USE_MORPHNORMALS
  1470. objectNormal *= morphTargetBaseInfluence;
  1471. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1472. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  1473. }
  1474. #endif`,m_e=`#ifdef USE_MORPHTARGETS
  1475. #ifndef USE_INSTANCING_MORPH
  1476. uniform float morphTargetBaseInfluence;
  1477. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1478. #endif
  1479. uniform sampler2DArray morphTargetsTexture;
  1480. uniform ivec2 morphTargetsTextureSize;
  1481. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  1482. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  1483. int y = texelIndex / morphTargetsTextureSize.x;
  1484. int x = texelIndex - y * morphTargetsTextureSize.x;
  1485. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  1486. return texelFetch( morphTargetsTexture, morphUV, 0 );
  1487. }
  1488. #endif`,p_e=`#ifdef USE_MORPHTARGETS
  1489. transformed *= morphTargetBaseInfluence;
  1490. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1491. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  1492. }
  1493. #endif`,h_e=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  1494. #ifdef FLAT_SHADED
  1495. vec3 fdx = dFdx( vViewPosition );
  1496. vec3 fdy = dFdy( vViewPosition );
  1497. vec3 normal = normalize( cross( fdx, fdy ) );
  1498. #else
  1499. vec3 normal = normalize( vNormal );
  1500. #ifdef DOUBLE_SIDED
  1501. normal *= faceDirection;
  1502. #endif
  1503. #endif
  1504. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  1505. #ifdef USE_TANGENT
  1506. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1507. #else
  1508. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  1509. #if defined( USE_NORMALMAP )
  1510. vNormalMapUv
  1511. #elif defined( USE_CLEARCOAT_NORMALMAP )
  1512. vClearcoatNormalMapUv
  1513. #else
  1514. vUv
  1515. #endif
  1516. );
  1517. #endif
  1518. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1519. tbn[0] *= faceDirection;
  1520. tbn[1] *= faceDirection;
  1521. #endif
  1522. #endif
  1523. #ifdef USE_CLEARCOAT_NORMALMAP
  1524. #ifdef USE_TANGENT
  1525. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1526. #else
  1527. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  1528. #endif
  1529. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1530. tbn2[0] *= faceDirection;
  1531. tbn2[1] *= faceDirection;
  1532. #endif
  1533. #endif
  1534. vec3 nonPerturbedNormal = normal;`,f_e=`#ifdef USE_NORMALMAP_OBJECTSPACE
  1535. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1536. #ifdef FLIP_SIDED
  1537. normal = - normal;
  1538. #endif
  1539. #ifdef DOUBLE_SIDED
  1540. normal = normal * faceDirection;
  1541. #endif
  1542. normal = normalize( normalMatrix * normal );
  1543. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  1544. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1545. mapN.xy *= normalScale;
  1546. normal = normalize( tbn * mapN );
  1547. #elif defined( USE_BUMPMAP )
  1548. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  1549. #endif`,g_e=`#ifndef FLAT_SHADED
  1550. varying vec3 vNormal;
  1551. #ifdef USE_TANGENT
  1552. varying vec3 vTangent;
  1553. varying vec3 vBitangent;
  1554. #endif
  1555. #endif`,b_e=`#ifndef FLAT_SHADED
  1556. varying vec3 vNormal;
  1557. #ifdef USE_TANGENT
  1558. varying vec3 vTangent;
  1559. varying vec3 vBitangent;
  1560. #endif
  1561. #endif`,x_e=`#ifndef FLAT_SHADED
  1562. vNormal = normalize( transformedNormal );
  1563. #ifdef USE_TANGENT
  1564. vTangent = normalize( transformedTangent );
  1565. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  1566. #endif
  1567. #endif`,y_e=`#ifdef USE_NORMALMAP
  1568. uniform sampler2D normalMap;
  1569. uniform vec2 normalScale;
  1570. #endif
  1571. #ifdef USE_NORMALMAP_OBJECTSPACE
  1572. uniform mat3 normalMatrix;
  1573. #endif
  1574. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  1575. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  1576. vec3 q0 = dFdx( eye_pos.xyz );
  1577. vec3 q1 = dFdy( eye_pos.xyz );
  1578. vec2 st0 = dFdx( uv.st );
  1579. vec2 st1 = dFdy( uv.st );
  1580. vec3 N = surf_norm;
  1581. vec3 q1perp = cross( q1, N );
  1582. vec3 q0perp = cross( N, q0 );
  1583. vec3 T = q1perp * st0.x + q0perp * st1.x;
  1584. vec3 B = q1perp * st0.y + q0perp * st1.y;
  1585. float det = max( dot( T, T ), dot( B, B ) );
  1586. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  1587. return mat3( T * scale, B * scale, N );
  1588. }
  1589. #endif`,v_e=`#ifdef USE_CLEARCOAT
  1590. vec3 clearcoatNormal = nonPerturbedNormal;
  1591. #endif`,w_e=`#ifdef USE_CLEARCOAT_NORMALMAP
  1592. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  1593. clearcoatMapN.xy *= clearcoatNormalScale;
  1594. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  1595. #endif`,S_e=`#ifdef USE_CLEARCOATMAP
  1596. uniform sampler2D clearcoatMap;
  1597. #endif
  1598. #ifdef USE_CLEARCOAT_NORMALMAP
  1599. uniform sampler2D clearcoatNormalMap;
  1600. uniform vec2 clearcoatNormalScale;
  1601. #endif
  1602. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  1603. uniform sampler2D clearcoatRoughnessMap;
  1604. #endif`,__e=`#ifdef USE_IRIDESCENCEMAP
  1605. uniform sampler2D iridescenceMap;
  1606. #endif
  1607. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  1608. uniform sampler2D iridescenceThicknessMap;
  1609. #endif`,k_e=`#ifdef OPAQUE
  1610. diffuseColor.a = 1.0;
  1611. #endif
  1612. #ifdef USE_TRANSMISSION
  1613. diffuseColor.a *= material.transmissionAlpha;
  1614. #endif
  1615. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,N_e=`vec3 packNormalToRGB( const in vec3 normal ) {
  1616. return normalize( normal ) * 0.5 + 0.5;
  1617. }
  1618. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  1619. return 2.0 * rgb.xyz - 1.0;
  1620. }
  1621. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
  1622. const float Inv255 = 1. / 255.;
  1623. const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
  1624. const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
  1625. const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
  1626. const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
  1627. vec4 packDepthToRGBA( const in float v ) {
  1628. if( v <= 0.0 )
  1629. return vec4( 0., 0., 0., 0. );
  1630. if( v >= 1.0 )
  1631. return vec4( 1., 1., 1., 1. );
  1632. float vuf;
  1633. float af = modf( v * PackFactors.a, vuf );
  1634. float bf = modf( vuf * ShiftRight8, vuf );
  1635. float gf = modf( vuf * ShiftRight8, vuf );
  1636. return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
  1637. }
  1638. vec3 packDepthToRGB( const in float v ) {
  1639. if( v <= 0.0 )
  1640. return vec3( 0., 0., 0. );
  1641. if( v >= 1.0 )
  1642. return vec3( 1., 1., 1. );
  1643. float vuf;
  1644. float bf = modf( v * PackFactors.b, vuf );
  1645. float gf = modf( vuf * ShiftRight8, vuf );
  1646. return vec3( vuf * Inv255, gf * PackUpscale, bf );
  1647. }
  1648. vec2 packDepthToRG( const in float v ) {
  1649. if( v <= 0.0 )
  1650. return vec2( 0., 0. );
  1651. if( v >= 1.0 )
  1652. return vec2( 1., 1. );
  1653. float vuf;
  1654. float gf = modf( v * 256., vuf );
  1655. return vec2( vuf * Inv255, gf );
  1656. }
  1657. float unpackRGBAToDepth( const in vec4 v ) {
  1658. return dot( v, UnpackFactors4 );
  1659. }
  1660. float unpackRGBToDepth( const in vec3 v ) {
  1661. return dot( v, UnpackFactors3 );
  1662. }
  1663. float unpackRGToDepth( const in vec2 v ) {
  1664. return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
  1665. }
  1666. vec4 pack2HalfToRGBA( const in vec2 v ) {
  1667. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  1668. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  1669. }
  1670. vec2 unpackRGBATo2Half( const in vec4 v ) {
  1671. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  1672. }
  1673. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  1674. return ( viewZ + near ) / ( near - far );
  1675. }
  1676. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1677. return depth * ( near - far ) - near;
  1678. }
  1679. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  1680. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  1681. }
  1682. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1683. return ( near * far ) / ( ( far - near ) * depth - far );
  1684. }`,C_e=`#ifdef PREMULTIPLIED_ALPHA
  1685. gl_FragColor.rgb *= gl_FragColor.a;
  1686. #endif`,P_e=`vec4 mvPosition = vec4( transformed, 1.0 );
  1687. #ifdef USE_BATCHING
  1688. mvPosition = batchingMatrix * mvPosition;
  1689. #endif
  1690. #ifdef USE_INSTANCING
  1691. mvPosition = instanceMatrix * mvPosition;
  1692. #endif
  1693. mvPosition = modelViewMatrix * mvPosition;
  1694. gl_Position = projectionMatrix * mvPosition;`,T_e=`#ifdef DITHERING
  1695. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  1696. #endif`,A_e=`#ifdef DITHERING
  1697. vec3 dithering( vec3 color ) {
  1698. float grid_position = rand( gl_FragCoord.xy );
  1699. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  1700. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  1701. return color + dither_shift_RGB;
  1702. }
  1703. #endif`,j_e=`float roughnessFactor = roughness;
  1704. #ifdef USE_ROUGHNESSMAP
  1705. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  1706. roughnessFactor *= texelRoughness.g;
  1707. #endif`,M_e=`#ifdef USE_ROUGHNESSMAP
  1708. uniform sampler2D roughnessMap;
  1709. #endif`,E_e=`#if NUM_SPOT_LIGHT_COORDS > 0
  1710. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1711. #endif
  1712. #if NUM_SPOT_LIGHT_MAPS > 0
  1713. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  1714. #endif
  1715. #ifdef USE_SHADOWMAP
  1716. #if NUM_DIR_LIGHT_SHADOWS > 0
  1717. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  1718. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1719. struct DirectionalLightShadow {
  1720. float shadowIntensity;
  1721. float shadowBias;
  1722. float shadowNormalBias;
  1723. float shadowRadius;
  1724. vec2 shadowMapSize;
  1725. };
  1726. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1727. #endif
  1728. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1729. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  1730. struct SpotLightShadow {
  1731. float shadowIntensity;
  1732. float shadowBias;
  1733. float shadowNormalBias;
  1734. float shadowRadius;
  1735. vec2 shadowMapSize;
  1736. };
  1737. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1738. #endif
  1739. #if NUM_POINT_LIGHT_SHADOWS > 0
  1740. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  1741. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1742. struct PointLightShadow {
  1743. float shadowIntensity;
  1744. float shadowBias;
  1745. float shadowNormalBias;
  1746. float shadowRadius;
  1747. vec2 shadowMapSize;
  1748. float shadowCameraNear;
  1749. float shadowCameraFar;
  1750. };
  1751. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1752. #endif
  1753. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  1754. float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
  1755. #ifdef USE_REVERSED_DEPTH_BUFFER
  1756. return step( depth, compare );
  1757. #else
  1758. return step( compare, depth );
  1759. #endif
  1760. }
  1761. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  1762. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  1763. }
  1764. float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
  1765. float occlusion = 1.0;
  1766. vec2 distribution = texture2DDistribution( shadow, uv );
  1767. #ifdef USE_REVERSED_DEPTH_BUFFER
  1768. float hard_shadow = step( distribution.x, compare );
  1769. #else
  1770. float hard_shadow = step( compare, distribution.x );
  1771. #endif
  1772. if ( hard_shadow != 1.0 ) {
  1773. float distance = compare - distribution.x;
  1774. float variance = max( 0.00000, distribution.y * distribution.y );
  1775. 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 );
  1776. }
  1777. return occlusion;
  1778. }
  1779. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  1780. float shadow = 1.0;
  1781. shadowCoord.xyz /= shadowCoord.w;
  1782. shadowCoord.z += shadowBias;
  1783. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  1784. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  1785. if ( frustumTest ) {
  1786. #if defined( SHADOWMAP_TYPE_PCF )
  1787. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1788. float dx0 = - texelSize.x * shadowRadius;
  1789. float dy0 = - texelSize.y * shadowRadius;
  1790. float dx1 = + texelSize.x * shadowRadius;
  1791. float dy1 = + texelSize.y * shadowRadius;
  1792. float dx2 = dx0 / 2.0;
  1793. float dy2 = dy0 / 2.0;
  1794. float dx3 = dx1 / 2.0;
  1795. float dy3 = dy1 / 2.0;
  1796. shadow = (
  1797. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  1798. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  1799. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  1800. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  1801. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  1802. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  1803. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  1804. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  1805. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  1806. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  1807. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  1808. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  1809. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  1810. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  1811. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  1812. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  1813. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  1814. ) * ( 1.0 / 17.0 );
  1815. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  1816. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1817. float dx = texelSize.x;
  1818. float dy = texelSize.y;
  1819. vec2 uv = shadowCoord.xy;
  1820. vec2 f = fract( uv * shadowMapSize + 0.5 );
  1821. uv -= f * texelSize;
  1822. shadow = (
  1823. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  1824. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  1825. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  1826. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  1827. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  1828. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  1829. f.x ) +
  1830. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  1831. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  1832. f.x ) +
  1833. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  1834. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  1835. f.y ) +
  1836. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  1837. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  1838. f.y ) +
  1839. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  1840. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  1841. f.x ),
  1842. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  1843. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  1844. f.x ),
  1845. f.y )
  1846. ) * ( 1.0 / 9.0 );
  1847. #elif defined( SHADOWMAP_TYPE_VSM )
  1848. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  1849. #else
  1850. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  1851. #endif
  1852. }
  1853. return mix( 1.0, shadow, shadowIntensity );
  1854. }
  1855. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  1856. vec3 absV = abs( v );
  1857. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  1858. absV *= scaleToCube;
  1859. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  1860. vec2 planar = v.xy;
  1861. float almostATexel = 1.5 * texelSizeY;
  1862. float almostOne = 1.0 - almostATexel;
  1863. if ( absV.z >= almostOne ) {
  1864. if ( v.z > 0.0 )
  1865. planar.x = 4.0 - v.x;
  1866. } else if ( absV.x >= almostOne ) {
  1867. float signX = sign( v.x );
  1868. planar.x = v.z * signX + 2.0 * signX;
  1869. } else if ( absV.y >= almostOne ) {
  1870. float signY = sign( v.y );
  1871. planar.x = v.x + 2.0 * signY + 2.0;
  1872. planar.y = v.z * signY - 2.0;
  1873. }
  1874. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  1875. }
  1876. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  1877. float shadow = 1.0;
  1878. vec3 lightToPosition = shadowCoord.xyz;
  1879. float lightToPositionLength = length( lightToPosition );
  1880. if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
  1881. float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  1882. vec3 bd3D = normalize( lightToPosition );
  1883. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  1884. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  1885. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  1886. shadow = (
  1887. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  1888. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  1889. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  1890. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  1891. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  1892. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  1893. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  1894. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  1895. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  1896. ) * ( 1.0 / 9.0 );
  1897. #else
  1898. shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  1899. #endif
  1900. }
  1901. return mix( 1.0, shadow, shadowIntensity );
  1902. }
  1903. #endif`,D_e=`#if NUM_SPOT_LIGHT_COORDS > 0
  1904. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  1905. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1906. #endif
  1907. #ifdef USE_SHADOWMAP
  1908. #if NUM_DIR_LIGHT_SHADOWS > 0
  1909. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  1910. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1911. struct DirectionalLightShadow {
  1912. float shadowIntensity;
  1913. float shadowBias;
  1914. float shadowNormalBias;
  1915. float shadowRadius;
  1916. vec2 shadowMapSize;
  1917. };
  1918. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1919. #endif
  1920. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1921. struct SpotLightShadow {
  1922. float shadowIntensity;
  1923. float shadowBias;
  1924. float shadowNormalBias;
  1925. float shadowRadius;
  1926. vec2 shadowMapSize;
  1927. };
  1928. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1929. #endif
  1930. #if NUM_POINT_LIGHT_SHADOWS > 0
  1931. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  1932. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1933. struct PointLightShadow {
  1934. float shadowIntensity;
  1935. float shadowBias;
  1936. float shadowNormalBias;
  1937. float shadowRadius;
  1938. vec2 shadowMapSize;
  1939. float shadowCameraNear;
  1940. float shadowCameraFar;
  1941. };
  1942. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1943. #endif
  1944. #endif`,F_e=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  1945. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  1946. vec4 shadowWorldPosition;
  1947. #endif
  1948. #if defined( USE_SHADOWMAP )
  1949. #if NUM_DIR_LIGHT_SHADOWS > 0
  1950. #pragma unroll_loop_start
  1951. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1952. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  1953. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  1954. }
  1955. #pragma unroll_loop_end
  1956. #endif
  1957. #if NUM_POINT_LIGHT_SHADOWS > 0
  1958. #pragma unroll_loop_start
  1959. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  1960. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  1961. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  1962. }
  1963. #pragma unroll_loop_end
  1964. #endif
  1965. #endif
  1966. #if NUM_SPOT_LIGHT_COORDS > 0
  1967. #pragma unroll_loop_start
  1968. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  1969. shadowWorldPosition = worldPosition;
  1970. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1971. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  1972. #endif
  1973. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  1974. }
  1975. #pragma unroll_loop_end
  1976. #endif`,L_e=`float getShadowMask() {
  1977. float shadow = 1.0;
  1978. #ifdef USE_SHADOWMAP
  1979. #if NUM_DIR_LIGHT_SHADOWS > 0
  1980. DirectionalLightShadow directionalLight;
  1981. #pragma unroll_loop_start
  1982. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1983. directionalLight = directionalLightShadows[ i ];
  1984. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1985. }
  1986. #pragma unroll_loop_end
  1987. #endif
  1988. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1989. SpotLightShadow spotLight;
  1990. #pragma unroll_loop_start
  1991. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  1992. spotLight = spotLightShadows[ i ];
  1993. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1994. }
  1995. #pragma unroll_loop_end
  1996. #endif
  1997. #if NUM_POINT_LIGHT_SHADOWS > 0
  1998. PointLightShadow pointLight;
  1999. #pragma unroll_loop_start
  2000. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  2001. pointLight = pointLightShadows[ i ];
  2002. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  2003. }
  2004. #pragma unroll_loop_end
  2005. #endif
  2006. #endif
  2007. return shadow;
  2008. }`,R_e=`#ifdef USE_SKINNING
  2009. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  2010. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  2011. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  2012. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  2013. #endif`,I_e=`#ifdef USE_SKINNING
  2014. uniform mat4 bindMatrix;
  2015. uniform mat4 bindMatrixInverse;
  2016. uniform highp sampler2D boneTexture;
  2017. mat4 getBoneMatrix( const in float i ) {
  2018. int size = textureSize( boneTexture, 0 ).x;
  2019. int j = int( i ) * 4;
  2020. int x = j % size;
  2021. int y = j / size;
  2022. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  2023. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  2024. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  2025. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  2026. return mat4( v1, v2, v3, v4 );
  2027. }
  2028. #endif`,O_e=`#ifdef USE_SKINNING
  2029. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  2030. vec4 skinned = vec4( 0.0 );
  2031. skinned += boneMatX * skinVertex * skinWeight.x;
  2032. skinned += boneMatY * skinVertex * skinWeight.y;
  2033. skinned += boneMatZ * skinVertex * skinWeight.z;
  2034. skinned += boneMatW * skinVertex * skinWeight.w;
  2035. transformed = ( bindMatrixInverse * skinned ).xyz;
  2036. #endif`,z_e=`#ifdef USE_SKINNING
  2037. mat4 skinMatrix = mat4( 0.0 );
  2038. skinMatrix += skinWeight.x * boneMatX;
  2039. skinMatrix += skinWeight.y * boneMatY;
  2040. skinMatrix += skinWeight.z * boneMatZ;
  2041. skinMatrix += skinWeight.w * boneMatW;
  2042. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  2043. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  2044. #ifdef USE_TANGENT
  2045. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  2046. #endif
  2047. #endif`,U_e=`float specularStrength;
  2048. #ifdef USE_SPECULARMAP
  2049. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  2050. specularStrength = texelSpecular.r;
  2051. #else
  2052. specularStrength = 1.0;
  2053. #endif`,B_e=`#ifdef USE_SPECULARMAP
  2054. uniform sampler2D specularMap;
  2055. #endif`,H_e=`#if defined( TONE_MAPPING )
  2056. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  2057. #endif`,q_e=`#ifndef saturate
  2058. #define saturate( a ) clamp( a, 0.0, 1.0 )
  2059. #endif
  2060. uniform float toneMappingExposure;
  2061. vec3 LinearToneMapping( vec3 color ) {
  2062. return saturate( toneMappingExposure * color );
  2063. }
  2064. vec3 ReinhardToneMapping( vec3 color ) {
  2065. color *= toneMappingExposure;
  2066. return saturate( color / ( vec3( 1.0 ) + color ) );
  2067. }
  2068. vec3 CineonToneMapping( vec3 color ) {
  2069. color *= toneMappingExposure;
  2070. color = max( vec3( 0.0 ), color - 0.004 );
  2071. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  2072. }
  2073. vec3 RRTAndODTFit( vec3 v ) {
  2074. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  2075. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  2076. return a / b;
  2077. }
  2078. vec3 ACESFilmicToneMapping( vec3 color ) {
  2079. const mat3 ACESInputMat = mat3(
  2080. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  2081. vec3( 0.04823, 0.01566, 0.83777 )
  2082. );
  2083. const mat3 ACESOutputMat = mat3(
  2084. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  2085. vec3( -0.07367, -0.00605, 1.07602 )
  2086. );
  2087. color *= toneMappingExposure / 0.6;
  2088. color = ACESInputMat * color;
  2089. color = RRTAndODTFit( color );
  2090. color = ACESOutputMat * color;
  2091. return saturate( color );
  2092. }
  2093. const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
  2094. vec3( 1.6605, - 0.1246, - 0.0182 ),
  2095. vec3( - 0.5876, 1.1329, - 0.1006 ),
  2096. vec3( - 0.0728, - 0.0083, 1.1187 )
  2097. );
  2098. const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
  2099. vec3( 0.6274, 0.0691, 0.0164 ),
  2100. vec3( 0.3293, 0.9195, 0.0880 ),
  2101. vec3( 0.0433, 0.0113, 0.8956 )
  2102. );
  2103. vec3 agxDefaultContrastApprox( vec3 x ) {
  2104. vec3 x2 = x * x;
  2105. vec3 x4 = x2 * x2;
  2106. return + 15.5 * x4 * x2
  2107. - 40.14 * x4 * x
  2108. + 31.96 * x4
  2109. - 6.868 * x2 * x
  2110. + 0.4298 * x2
  2111. + 0.1191 * x
  2112. - 0.00232;
  2113. }
  2114. vec3 AgXToneMapping( vec3 color ) {
  2115. const mat3 AgXInsetMatrix = mat3(
  2116. vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
  2117. vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
  2118. vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
  2119. );
  2120. const mat3 AgXOutsetMatrix = mat3(
  2121. vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
  2122. vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
  2123. vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
  2124. );
  2125. const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
  2126. color *= toneMappingExposure;
  2127. color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
  2128. color = AgXInsetMatrix * color;
  2129. color = max( color, 1e-10 ); color = log2( color );
  2130. color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
  2131. color = clamp( color, 0.0, 1.0 );
  2132. color = agxDefaultContrastApprox( color );
  2133. color = AgXOutsetMatrix * color;
  2134. color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
  2135. color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
  2136. color = clamp( color, 0.0, 1.0 );
  2137. return color;
  2138. }
  2139. vec3 NeutralToneMapping( vec3 color ) {
  2140. const float StartCompression = 0.8 - 0.04;
  2141. const float Desaturation = 0.15;
  2142. color *= toneMappingExposure;
  2143. float x = min( color.r, min( color.g, color.b ) );
  2144. float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
  2145. color -= offset;
  2146. float peak = max( color.r, max( color.g, color.b ) );
  2147. if ( peak < StartCompression ) return color;
  2148. float d = 1. - StartCompression;
  2149. float newPeak = 1. - d * d / ( peak + d - StartCompression );
  2150. color *= newPeak / peak;
  2151. float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
  2152. return mix( color, vec3( newPeak ), g );
  2153. }
  2154. vec3 CustomToneMapping( vec3 color ) { return color; }`,$_e=`#ifdef USE_TRANSMISSION
  2155. material.transmission = transmission;
  2156. material.transmissionAlpha = 1.0;
  2157. material.thickness = thickness;
  2158. material.attenuationDistance = attenuationDistance;
  2159. material.attenuationColor = attenuationColor;
  2160. #ifdef USE_TRANSMISSIONMAP
  2161. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  2162. #endif
  2163. #ifdef USE_THICKNESSMAP
  2164. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  2165. #endif
  2166. vec3 pos = vWorldPosition;
  2167. vec3 v = normalize( cameraPosition - pos );
  2168. vec3 n = inverseTransformDirection( normal, viewMatrix );
  2169. vec4 transmitted = getIBLVolumeRefraction(
  2170. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  2171. pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
  2172. material.attenuationColor, material.attenuationDistance );
  2173. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  2174. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  2175. #endif`,V_e=`#ifdef USE_TRANSMISSION
  2176. uniform float transmission;
  2177. uniform float thickness;
  2178. uniform float attenuationDistance;
  2179. uniform vec3 attenuationColor;
  2180. #ifdef USE_TRANSMISSIONMAP
  2181. uniform sampler2D transmissionMap;
  2182. #endif
  2183. #ifdef USE_THICKNESSMAP
  2184. uniform sampler2D thicknessMap;
  2185. #endif
  2186. uniform vec2 transmissionSamplerSize;
  2187. uniform sampler2D transmissionSamplerMap;
  2188. uniform mat4 modelMatrix;
  2189. uniform mat4 projectionMatrix;
  2190. varying vec3 vWorldPosition;
  2191. float w0( float a ) {
  2192. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  2193. }
  2194. float w1( float a ) {
  2195. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  2196. }
  2197. float w2( float a ){
  2198. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  2199. }
  2200. float w3( float a ) {
  2201. return ( 1.0 / 6.0 ) * ( a * a * a );
  2202. }
  2203. float g0( float a ) {
  2204. return w0( a ) + w1( a );
  2205. }
  2206. float g1( float a ) {
  2207. return w2( a ) + w3( a );
  2208. }
  2209. float h0( float a ) {
  2210. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  2211. }
  2212. float h1( float a ) {
  2213. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  2214. }
  2215. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  2216. uv = uv * texelSize.zw + 0.5;
  2217. vec2 iuv = floor( uv );
  2218. vec2 fuv = fract( uv );
  2219. float g0x = g0( fuv.x );
  2220. float g1x = g1( fuv.x );
  2221. float h0x = h0( fuv.x );
  2222. float h1x = h1( fuv.x );
  2223. float h0y = h0( fuv.y );
  2224. float h1y = h1( fuv.y );
  2225. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2226. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2227. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2228. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2229. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  2230. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  2231. }
  2232. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  2233. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  2234. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  2235. vec2 fLodSizeInv = 1.0 / fLodSize;
  2236. vec2 cLodSizeInv = 1.0 / cLodSize;
  2237. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  2238. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  2239. return mix( fSample, cSample, fract( lod ) );
  2240. }
  2241. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  2242. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  2243. vec3 modelScale;
  2244. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  2245. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  2246. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  2247. return normalize( refractionVector ) * thickness * modelScale;
  2248. }
  2249. float applyIorToRoughness( const in float roughness, const in float ior ) {
  2250. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  2251. }
  2252. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  2253. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  2254. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  2255. }
  2256. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  2257. if ( isinf( attenuationDistance ) ) {
  2258. return vec3( 1.0 );
  2259. } else {
  2260. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  2261. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  2262. }
  2263. }
  2264. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  2265. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  2266. const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
  2267. const in vec3 attenuationColor, const in float attenuationDistance ) {
  2268. vec4 transmittedLight;
  2269. vec3 transmittance;
  2270. #ifdef USE_DISPERSION
  2271. float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
  2272. vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
  2273. for ( int i = 0; i < 3; i ++ ) {
  2274. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
  2275. vec3 refractedRayExit = position + transmissionRay;
  2276. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2277. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2278. refractionCoords += 1.0;
  2279. refractionCoords /= 2.0;
  2280. vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
  2281. transmittedLight[ i ] = transmissionSample[ i ];
  2282. transmittedLight.a += transmissionSample.a;
  2283. transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
  2284. }
  2285. transmittedLight.a /= 3.0;
  2286. #else
  2287. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  2288. vec3 refractedRayExit = position + transmissionRay;
  2289. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2290. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2291. refractionCoords += 1.0;
  2292. refractionCoords /= 2.0;
  2293. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  2294. transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  2295. #endif
  2296. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  2297. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  2298. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  2299. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  2300. }
  2301. #endif`,G_e=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2302. varying vec2 vUv;
  2303. #endif
  2304. #ifdef USE_MAP
  2305. varying vec2 vMapUv;
  2306. #endif
  2307. #ifdef USE_ALPHAMAP
  2308. varying vec2 vAlphaMapUv;
  2309. #endif
  2310. #ifdef USE_LIGHTMAP
  2311. varying vec2 vLightMapUv;
  2312. #endif
  2313. #ifdef USE_AOMAP
  2314. varying vec2 vAoMapUv;
  2315. #endif
  2316. #ifdef USE_BUMPMAP
  2317. varying vec2 vBumpMapUv;
  2318. #endif
  2319. #ifdef USE_NORMALMAP
  2320. varying vec2 vNormalMapUv;
  2321. #endif
  2322. #ifdef USE_EMISSIVEMAP
  2323. varying vec2 vEmissiveMapUv;
  2324. #endif
  2325. #ifdef USE_METALNESSMAP
  2326. varying vec2 vMetalnessMapUv;
  2327. #endif
  2328. #ifdef USE_ROUGHNESSMAP
  2329. varying vec2 vRoughnessMapUv;
  2330. #endif
  2331. #ifdef USE_ANISOTROPYMAP
  2332. varying vec2 vAnisotropyMapUv;
  2333. #endif
  2334. #ifdef USE_CLEARCOATMAP
  2335. varying vec2 vClearcoatMapUv;
  2336. #endif
  2337. #ifdef USE_CLEARCOAT_NORMALMAP
  2338. varying vec2 vClearcoatNormalMapUv;
  2339. #endif
  2340. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2341. varying vec2 vClearcoatRoughnessMapUv;
  2342. #endif
  2343. #ifdef USE_IRIDESCENCEMAP
  2344. varying vec2 vIridescenceMapUv;
  2345. #endif
  2346. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2347. varying vec2 vIridescenceThicknessMapUv;
  2348. #endif
  2349. #ifdef USE_SHEEN_COLORMAP
  2350. varying vec2 vSheenColorMapUv;
  2351. #endif
  2352. #ifdef USE_SHEEN_ROUGHNESSMAP
  2353. varying vec2 vSheenRoughnessMapUv;
  2354. #endif
  2355. #ifdef USE_SPECULARMAP
  2356. varying vec2 vSpecularMapUv;
  2357. #endif
  2358. #ifdef USE_SPECULAR_COLORMAP
  2359. varying vec2 vSpecularColorMapUv;
  2360. #endif
  2361. #ifdef USE_SPECULAR_INTENSITYMAP
  2362. varying vec2 vSpecularIntensityMapUv;
  2363. #endif
  2364. #ifdef USE_TRANSMISSIONMAP
  2365. uniform mat3 transmissionMapTransform;
  2366. varying vec2 vTransmissionMapUv;
  2367. #endif
  2368. #ifdef USE_THICKNESSMAP
  2369. uniform mat3 thicknessMapTransform;
  2370. varying vec2 vThicknessMapUv;
  2371. #endif`,W_e=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2372. varying vec2 vUv;
  2373. #endif
  2374. #ifdef USE_MAP
  2375. uniform mat3 mapTransform;
  2376. varying vec2 vMapUv;
  2377. #endif
  2378. #ifdef USE_ALPHAMAP
  2379. uniform mat3 alphaMapTransform;
  2380. varying vec2 vAlphaMapUv;
  2381. #endif
  2382. #ifdef USE_LIGHTMAP
  2383. uniform mat3 lightMapTransform;
  2384. varying vec2 vLightMapUv;
  2385. #endif
  2386. #ifdef USE_AOMAP
  2387. uniform mat3 aoMapTransform;
  2388. varying vec2 vAoMapUv;
  2389. #endif
  2390. #ifdef USE_BUMPMAP
  2391. uniform mat3 bumpMapTransform;
  2392. varying vec2 vBumpMapUv;
  2393. #endif
  2394. #ifdef USE_NORMALMAP
  2395. uniform mat3 normalMapTransform;
  2396. varying vec2 vNormalMapUv;
  2397. #endif
  2398. #ifdef USE_DISPLACEMENTMAP
  2399. uniform mat3 displacementMapTransform;
  2400. varying vec2 vDisplacementMapUv;
  2401. #endif
  2402. #ifdef USE_EMISSIVEMAP
  2403. uniform mat3 emissiveMapTransform;
  2404. varying vec2 vEmissiveMapUv;
  2405. #endif
  2406. #ifdef USE_METALNESSMAP
  2407. uniform mat3 metalnessMapTransform;
  2408. varying vec2 vMetalnessMapUv;
  2409. #endif
  2410. #ifdef USE_ROUGHNESSMAP
  2411. uniform mat3 roughnessMapTransform;
  2412. varying vec2 vRoughnessMapUv;
  2413. #endif
  2414. #ifdef USE_ANISOTROPYMAP
  2415. uniform mat3 anisotropyMapTransform;
  2416. varying vec2 vAnisotropyMapUv;
  2417. #endif
  2418. #ifdef USE_CLEARCOATMAP
  2419. uniform mat3 clearcoatMapTransform;
  2420. varying vec2 vClearcoatMapUv;
  2421. #endif
  2422. #ifdef USE_CLEARCOAT_NORMALMAP
  2423. uniform mat3 clearcoatNormalMapTransform;
  2424. varying vec2 vClearcoatNormalMapUv;
  2425. #endif
  2426. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2427. uniform mat3 clearcoatRoughnessMapTransform;
  2428. varying vec2 vClearcoatRoughnessMapUv;
  2429. #endif
  2430. #ifdef USE_SHEEN_COLORMAP
  2431. uniform mat3 sheenColorMapTransform;
  2432. varying vec2 vSheenColorMapUv;
  2433. #endif
  2434. #ifdef USE_SHEEN_ROUGHNESSMAP
  2435. uniform mat3 sheenRoughnessMapTransform;
  2436. varying vec2 vSheenRoughnessMapUv;
  2437. #endif
  2438. #ifdef USE_IRIDESCENCEMAP
  2439. uniform mat3 iridescenceMapTransform;
  2440. varying vec2 vIridescenceMapUv;
  2441. #endif
  2442. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2443. uniform mat3 iridescenceThicknessMapTransform;
  2444. varying vec2 vIridescenceThicknessMapUv;
  2445. #endif
  2446. #ifdef USE_SPECULARMAP
  2447. uniform mat3 specularMapTransform;
  2448. varying vec2 vSpecularMapUv;
  2449. #endif
  2450. #ifdef USE_SPECULAR_COLORMAP
  2451. uniform mat3 specularColorMapTransform;
  2452. varying vec2 vSpecularColorMapUv;
  2453. #endif
  2454. #ifdef USE_SPECULAR_INTENSITYMAP
  2455. uniform mat3 specularIntensityMapTransform;
  2456. varying vec2 vSpecularIntensityMapUv;
  2457. #endif
  2458. #ifdef USE_TRANSMISSIONMAP
  2459. uniform mat3 transmissionMapTransform;
  2460. varying vec2 vTransmissionMapUv;
  2461. #endif
  2462. #ifdef USE_THICKNESSMAP
  2463. uniform mat3 thicknessMapTransform;
  2464. varying vec2 vThicknessMapUv;
  2465. #endif`,K_e=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2466. vUv = vec3( uv, 1 ).xy;
  2467. #endif
  2468. #ifdef USE_MAP
  2469. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  2470. #endif
  2471. #ifdef USE_ALPHAMAP
  2472. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  2473. #endif
  2474. #ifdef USE_LIGHTMAP
  2475. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  2476. #endif
  2477. #ifdef USE_AOMAP
  2478. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  2479. #endif
  2480. #ifdef USE_BUMPMAP
  2481. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  2482. #endif
  2483. #ifdef USE_NORMALMAP
  2484. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  2485. #endif
  2486. #ifdef USE_DISPLACEMENTMAP
  2487. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  2488. #endif
  2489. #ifdef USE_EMISSIVEMAP
  2490. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  2491. #endif
  2492. #ifdef USE_METALNESSMAP
  2493. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  2494. #endif
  2495. #ifdef USE_ROUGHNESSMAP
  2496. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  2497. #endif
  2498. #ifdef USE_ANISOTROPYMAP
  2499. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  2500. #endif
  2501. #ifdef USE_CLEARCOATMAP
  2502. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  2503. #endif
  2504. #ifdef USE_CLEARCOAT_NORMALMAP
  2505. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  2506. #endif
  2507. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2508. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  2509. #endif
  2510. #ifdef USE_IRIDESCENCEMAP
  2511. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  2512. #endif
  2513. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2514. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  2515. #endif
  2516. #ifdef USE_SHEEN_COLORMAP
  2517. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  2518. #endif
  2519. #ifdef USE_SHEEN_ROUGHNESSMAP
  2520. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  2521. #endif
  2522. #ifdef USE_SPECULARMAP
  2523. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  2524. #endif
  2525. #ifdef USE_SPECULAR_COLORMAP
  2526. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  2527. #endif
  2528. #ifdef USE_SPECULAR_INTENSITYMAP
  2529. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  2530. #endif
  2531. #ifdef USE_TRANSMISSIONMAP
  2532. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  2533. #endif
  2534. #ifdef USE_THICKNESSMAP
  2535. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  2536. #endif`,Q_e=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  2537. vec4 worldPosition = vec4( transformed, 1.0 );
  2538. #ifdef USE_BATCHING
  2539. worldPosition = batchingMatrix * worldPosition;
  2540. #endif
  2541. #ifdef USE_INSTANCING
  2542. worldPosition = instanceMatrix * worldPosition;
  2543. #endif
  2544. worldPosition = modelMatrix * worldPosition;
  2545. #endif`;const Y_e=`varying vec2 vUv;
  2546. uniform mat3 uvTransform;
  2547. void main() {
  2548. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  2549. gl_Position = vec4( position.xy, 1.0, 1.0 );
  2550. }`,X_e=`uniform sampler2D t2D;
  2551. uniform float backgroundIntensity;
  2552. varying vec2 vUv;
  2553. void main() {
  2554. vec4 texColor = texture2D( t2D, vUv );
  2555. #ifdef DECODE_VIDEO_TEXTURE
  2556. 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 );
  2557. #endif
  2558. texColor.rgb *= backgroundIntensity;
  2559. gl_FragColor = texColor;
  2560. #include <tonemapping_fragment>
  2561. #include <colorspace_fragment>
  2562. }`,Z_e=`varying vec3 vWorldDirection;
  2563. #include <common>
  2564. void main() {
  2565. vWorldDirection = transformDirection( position, modelMatrix );
  2566. #include <begin_vertex>
  2567. #include <project_vertex>
  2568. gl_Position.z = gl_Position.w;
  2569. }`,J_e=`#ifdef ENVMAP_TYPE_CUBE
  2570. uniform samplerCube envMap;
  2571. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2572. uniform sampler2D envMap;
  2573. #endif
  2574. uniform float flipEnvMap;
  2575. uniform float backgroundBlurriness;
  2576. uniform float backgroundIntensity;
  2577. uniform mat3 backgroundRotation;
  2578. varying vec3 vWorldDirection;
  2579. #include <cube_uv_reflection_fragment>
  2580. void main() {
  2581. #ifdef ENVMAP_TYPE_CUBE
  2582. vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  2583. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2584. vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
  2585. #else
  2586. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  2587. #endif
  2588. texColor.rgb *= backgroundIntensity;
  2589. gl_FragColor = texColor;
  2590. #include <tonemapping_fragment>
  2591. #include <colorspace_fragment>
  2592. }`,eke=`varying vec3 vWorldDirection;
  2593. #include <common>
  2594. void main() {
  2595. vWorldDirection = transformDirection( position, modelMatrix );
  2596. #include <begin_vertex>
  2597. #include <project_vertex>
  2598. gl_Position.z = gl_Position.w;
  2599. }`,tke=`uniform samplerCube tCube;
  2600. uniform float tFlip;
  2601. uniform float opacity;
  2602. varying vec3 vWorldDirection;
  2603. void main() {
  2604. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  2605. gl_FragColor = texColor;
  2606. gl_FragColor.a *= opacity;
  2607. #include <tonemapping_fragment>
  2608. #include <colorspace_fragment>
  2609. }`,nke=`#include <common>
  2610. #include <batching_pars_vertex>
  2611. #include <uv_pars_vertex>
  2612. #include <displacementmap_pars_vertex>
  2613. #include <morphtarget_pars_vertex>
  2614. #include <skinning_pars_vertex>
  2615. #include <logdepthbuf_pars_vertex>
  2616. #include <clipping_planes_pars_vertex>
  2617. varying vec2 vHighPrecisionZW;
  2618. void main() {
  2619. #include <uv_vertex>
  2620. #include <batching_vertex>
  2621. #include <skinbase_vertex>
  2622. #include <morphinstance_vertex>
  2623. #ifdef USE_DISPLACEMENTMAP
  2624. #include <beginnormal_vertex>
  2625. #include <morphnormal_vertex>
  2626. #include <skinnormal_vertex>
  2627. #endif
  2628. #include <begin_vertex>
  2629. #include <morphtarget_vertex>
  2630. #include <skinning_vertex>
  2631. #include <displacementmap_vertex>
  2632. #include <project_vertex>
  2633. #include <logdepthbuf_vertex>
  2634. #include <clipping_planes_vertex>
  2635. vHighPrecisionZW = gl_Position.zw;
  2636. }`,rke=`#if DEPTH_PACKING == 3200
  2637. uniform float opacity;
  2638. #endif
  2639. #include <common>
  2640. #include <packing>
  2641. #include <uv_pars_fragment>
  2642. #include <map_pars_fragment>
  2643. #include <alphamap_pars_fragment>
  2644. #include <alphatest_pars_fragment>
  2645. #include <alphahash_pars_fragment>
  2646. #include <logdepthbuf_pars_fragment>
  2647. #include <clipping_planes_pars_fragment>
  2648. varying vec2 vHighPrecisionZW;
  2649. void main() {
  2650. vec4 diffuseColor = vec4( 1.0 );
  2651. #include <clipping_planes_fragment>
  2652. #if DEPTH_PACKING == 3200
  2653. diffuseColor.a = opacity;
  2654. #endif
  2655. #include <map_fragment>
  2656. #include <alphamap_fragment>
  2657. #include <alphatest_fragment>
  2658. #include <alphahash_fragment>
  2659. #include <logdepthbuf_fragment>
  2660. #ifdef USE_REVERSED_DEPTH_BUFFER
  2661. float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
  2662. #else
  2663. float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
  2664. #endif
  2665. #if DEPTH_PACKING == 3200
  2666. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  2667. #elif DEPTH_PACKING == 3201
  2668. gl_FragColor = packDepthToRGBA( fragCoordZ );
  2669. #elif DEPTH_PACKING == 3202
  2670. gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
  2671. #elif DEPTH_PACKING == 3203
  2672. gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
  2673. #endif
  2674. }`,ake=`#define DISTANCE
  2675. varying vec3 vWorldPosition;
  2676. #include <common>
  2677. #include <batching_pars_vertex>
  2678. #include <uv_pars_vertex>
  2679. #include <displacementmap_pars_vertex>
  2680. #include <morphtarget_pars_vertex>
  2681. #include <skinning_pars_vertex>
  2682. #include <clipping_planes_pars_vertex>
  2683. void main() {
  2684. #include <uv_vertex>
  2685. #include <batching_vertex>
  2686. #include <skinbase_vertex>
  2687. #include <morphinstance_vertex>
  2688. #ifdef USE_DISPLACEMENTMAP
  2689. #include <beginnormal_vertex>
  2690. #include <morphnormal_vertex>
  2691. #include <skinnormal_vertex>
  2692. #endif
  2693. #include <begin_vertex>
  2694. #include <morphtarget_vertex>
  2695. #include <skinning_vertex>
  2696. #include <displacementmap_vertex>
  2697. #include <project_vertex>
  2698. #include <worldpos_vertex>
  2699. #include <clipping_planes_vertex>
  2700. vWorldPosition = worldPosition.xyz;
  2701. }`,ike=`#define DISTANCE
  2702. uniform vec3 referencePosition;
  2703. uniform float nearDistance;
  2704. uniform float farDistance;
  2705. varying vec3 vWorldPosition;
  2706. #include <common>
  2707. #include <packing>
  2708. #include <uv_pars_fragment>
  2709. #include <map_pars_fragment>
  2710. #include <alphamap_pars_fragment>
  2711. #include <alphatest_pars_fragment>
  2712. #include <alphahash_pars_fragment>
  2713. #include <clipping_planes_pars_fragment>
  2714. void main () {
  2715. vec4 diffuseColor = vec4( 1.0 );
  2716. #include <clipping_planes_fragment>
  2717. #include <map_fragment>
  2718. #include <alphamap_fragment>
  2719. #include <alphatest_fragment>
  2720. #include <alphahash_fragment>
  2721. float dist = length( vWorldPosition - referencePosition );
  2722. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  2723. dist = saturate( dist );
  2724. gl_FragColor = packDepthToRGBA( dist );
  2725. }`,ske=`varying vec3 vWorldDirection;
  2726. #include <common>
  2727. void main() {
  2728. vWorldDirection = transformDirection( position, modelMatrix );
  2729. #include <begin_vertex>
  2730. #include <project_vertex>
  2731. }`,oke=`uniform sampler2D tEquirect;
  2732. varying vec3 vWorldDirection;
  2733. #include <common>
  2734. void main() {
  2735. vec3 direction = normalize( vWorldDirection );
  2736. vec2 sampleUV = equirectUv( direction );
  2737. gl_FragColor = texture2D( tEquirect, sampleUV );
  2738. #include <tonemapping_fragment>
  2739. #include <colorspace_fragment>
  2740. }`,lke=`uniform float scale;
  2741. attribute float lineDistance;
  2742. varying float vLineDistance;
  2743. #include <common>
  2744. #include <uv_pars_vertex>
  2745. #include <color_pars_vertex>
  2746. #include <fog_pars_vertex>
  2747. #include <morphtarget_pars_vertex>
  2748. #include <logdepthbuf_pars_vertex>
  2749. #include <clipping_planes_pars_vertex>
  2750. void main() {
  2751. vLineDistance = scale * lineDistance;
  2752. #include <uv_vertex>
  2753. #include <color_vertex>
  2754. #include <morphinstance_vertex>
  2755. #include <morphcolor_vertex>
  2756. #include <begin_vertex>
  2757. #include <morphtarget_vertex>
  2758. #include <project_vertex>
  2759. #include <logdepthbuf_vertex>
  2760. #include <clipping_planes_vertex>
  2761. #include <fog_vertex>
  2762. }`,cke=`uniform vec3 diffuse;
  2763. uniform float opacity;
  2764. uniform float dashSize;
  2765. uniform float totalSize;
  2766. varying float vLineDistance;
  2767. #include <common>
  2768. #include <color_pars_fragment>
  2769. #include <uv_pars_fragment>
  2770. #include <map_pars_fragment>
  2771. #include <fog_pars_fragment>
  2772. #include <logdepthbuf_pars_fragment>
  2773. #include <clipping_planes_pars_fragment>
  2774. void main() {
  2775. vec4 diffuseColor = vec4( diffuse, opacity );
  2776. #include <clipping_planes_fragment>
  2777. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  2778. discard;
  2779. }
  2780. vec3 outgoingLight = vec3( 0.0 );
  2781. #include <logdepthbuf_fragment>
  2782. #include <map_fragment>
  2783. #include <color_fragment>
  2784. outgoingLight = diffuseColor.rgb;
  2785. #include <opaque_fragment>
  2786. #include <tonemapping_fragment>
  2787. #include <colorspace_fragment>
  2788. #include <fog_fragment>
  2789. #include <premultiplied_alpha_fragment>
  2790. }`,dke=`#include <common>
  2791. #include <batching_pars_vertex>
  2792. #include <uv_pars_vertex>
  2793. #include <envmap_pars_vertex>
  2794. #include <color_pars_vertex>
  2795. #include <fog_pars_vertex>
  2796. #include <morphtarget_pars_vertex>
  2797. #include <skinning_pars_vertex>
  2798. #include <logdepthbuf_pars_vertex>
  2799. #include <clipping_planes_pars_vertex>
  2800. void main() {
  2801. #include <uv_vertex>
  2802. #include <color_vertex>
  2803. #include <morphinstance_vertex>
  2804. #include <morphcolor_vertex>
  2805. #include <batching_vertex>
  2806. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  2807. #include <beginnormal_vertex>
  2808. #include <morphnormal_vertex>
  2809. #include <skinbase_vertex>
  2810. #include <skinnormal_vertex>
  2811. #include <defaultnormal_vertex>
  2812. #endif
  2813. #include <begin_vertex>
  2814. #include <morphtarget_vertex>
  2815. #include <skinning_vertex>
  2816. #include <project_vertex>
  2817. #include <logdepthbuf_vertex>
  2818. #include <clipping_planes_vertex>
  2819. #include <worldpos_vertex>
  2820. #include <envmap_vertex>
  2821. #include <fog_vertex>
  2822. }`,uke=`uniform vec3 diffuse;
  2823. uniform float opacity;
  2824. #ifndef FLAT_SHADED
  2825. varying vec3 vNormal;
  2826. #endif
  2827. #include <common>
  2828. #include <dithering_pars_fragment>
  2829. #include <color_pars_fragment>
  2830. #include <uv_pars_fragment>
  2831. #include <map_pars_fragment>
  2832. #include <alphamap_pars_fragment>
  2833. #include <alphatest_pars_fragment>
  2834. #include <alphahash_pars_fragment>
  2835. #include <aomap_pars_fragment>
  2836. #include <lightmap_pars_fragment>
  2837. #include <envmap_common_pars_fragment>
  2838. #include <envmap_pars_fragment>
  2839. #include <fog_pars_fragment>
  2840. #include <specularmap_pars_fragment>
  2841. #include <logdepthbuf_pars_fragment>
  2842. #include <clipping_planes_pars_fragment>
  2843. void main() {
  2844. vec4 diffuseColor = vec4( diffuse, opacity );
  2845. #include <clipping_planes_fragment>
  2846. #include <logdepthbuf_fragment>
  2847. #include <map_fragment>
  2848. #include <color_fragment>
  2849. #include <alphamap_fragment>
  2850. #include <alphatest_fragment>
  2851. #include <alphahash_fragment>
  2852. #include <specularmap_fragment>
  2853. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2854. #ifdef USE_LIGHTMAP
  2855. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  2856. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  2857. #else
  2858. reflectedLight.indirectDiffuse += vec3( 1.0 );
  2859. #endif
  2860. #include <aomap_fragment>
  2861. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  2862. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  2863. #include <envmap_fragment>
  2864. #include <opaque_fragment>
  2865. #include <tonemapping_fragment>
  2866. #include <colorspace_fragment>
  2867. #include <fog_fragment>
  2868. #include <premultiplied_alpha_fragment>
  2869. #include <dithering_fragment>
  2870. }`,mke=`#define LAMBERT
  2871. varying vec3 vViewPosition;
  2872. #include <common>
  2873. #include <batching_pars_vertex>
  2874. #include <uv_pars_vertex>
  2875. #include <displacementmap_pars_vertex>
  2876. #include <envmap_pars_vertex>
  2877. #include <color_pars_vertex>
  2878. #include <fog_pars_vertex>
  2879. #include <normal_pars_vertex>
  2880. #include <morphtarget_pars_vertex>
  2881. #include <skinning_pars_vertex>
  2882. #include <shadowmap_pars_vertex>
  2883. #include <logdepthbuf_pars_vertex>
  2884. #include <clipping_planes_pars_vertex>
  2885. void main() {
  2886. #include <uv_vertex>
  2887. #include <color_vertex>
  2888. #include <morphinstance_vertex>
  2889. #include <morphcolor_vertex>
  2890. #include <batching_vertex>
  2891. #include <beginnormal_vertex>
  2892. #include <morphnormal_vertex>
  2893. #include <skinbase_vertex>
  2894. #include <skinnormal_vertex>
  2895. #include <defaultnormal_vertex>
  2896. #include <normal_vertex>
  2897. #include <begin_vertex>
  2898. #include <morphtarget_vertex>
  2899. #include <skinning_vertex>
  2900. #include <displacementmap_vertex>
  2901. #include <project_vertex>
  2902. #include <logdepthbuf_vertex>
  2903. #include <clipping_planes_vertex>
  2904. vViewPosition = - mvPosition.xyz;
  2905. #include <worldpos_vertex>
  2906. #include <envmap_vertex>
  2907. #include <shadowmap_vertex>
  2908. #include <fog_vertex>
  2909. }`,pke=`#define LAMBERT
  2910. uniform vec3 diffuse;
  2911. uniform vec3 emissive;
  2912. uniform float opacity;
  2913. #include <common>
  2914. #include <packing>
  2915. #include <dithering_pars_fragment>
  2916. #include <color_pars_fragment>
  2917. #include <uv_pars_fragment>
  2918. #include <map_pars_fragment>
  2919. #include <alphamap_pars_fragment>
  2920. #include <alphatest_pars_fragment>
  2921. #include <alphahash_pars_fragment>
  2922. #include <aomap_pars_fragment>
  2923. #include <lightmap_pars_fragment>
  2924. #include <emissivemap_pars_fragment>
  2925. #include <envmap_common_pars_fragment>
  2926. #include <envmap_pars_fragment>
  2927. #include <fog_pars_fragment>
  2928. #include <bsdfs>
  2929. #include <lights_pars_begin>
  2930. #include <normal_pars_fragment>
  2931. #include <lights_lambert_pars_fragment>
  2932. #include <shadowmap_pars_fragment>
  2933. #include <bumpmap_pars_fragment>
  2934. #include <normalmap_pars_fragment>
  2935. #include <specularmap_pars_fragment>
  2936. #include <logdepthbuf_pars_fragment>
  2937. #include <clipping_planes_pars_fragment>
  2938. void main() {
  2939. vec4 diffuseColor = vec4( diffuse, opacity );
  2940. #include <clipping_planes_fragment>
  2941. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2942. vec3 totalEmissiveRadiance = emissive;
  2943. #include <logdepthbuf_fragment>
  2944. #include <map_fragment>
  2945. #include <color_fragment>
  2946. #include <alphamap_fragment>
  2947. #include <alphatest_fragment>
  2948. #include <alphahash_fragment>
  2949. #include <specularmap_fragment>
  2950. #include <normal_fragment_begin>
  2951. #include <normal_fragment_maps>
  2952. #include <emissivemap_fragment>
  2953. #include <lights_lambert_fragment>
  2954. #include <lights_fragment_begin>
  2955. #include <lights_fragment_maps>
  2956. #include <lights_fragment_end>
  2957. #include <aomap_fragment>
  2958. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  2959. #include <envmap_fragment>
  2960. #include <opaque_fragment>
  2961. #include <tonemapping_fragment>
  2962. #include <colorspace_fragment>
  2963. #include <fog_fragment>
  2964. #include <premultiplied_alpha_fragment>
  2965. #include <dithering_fragment>
  2966. }`,hke=`#define MATCAP
  2967. varying vec3 vViewPosition;
  2968. #include <common>
  2969. #include <batching_pars_vertex>
  2970. #include <uv_pars_vertex>
  2971. #include <color_pars_vertex>
  2972. #include <displacementmap_pars_vertex>
  2973. #include <fog_pars_vertex>
  2974. #include <normal_pars_vertex>
  2975. #include <morphtarget_pars_vertex>
  2976. #include <skinning_pars_vertex>
  2977. #include <logdepthbuf_pars_vertex>
  2978. #include <clipping_planes_pars_vertex>
  2979. void main() {
  2980. #include <uv_vertex>
  2981. #include <color_vertex>
  2982. #include <morphinstance_vertex>
  2983. #include <morphcolor_vertex>
  2984. #include <batching_vertex>
  2985. #include <beginnormal_vertex>
  2986. #include <morphnormal_vertex>
  2987. #include <skinbase_vertex>
  2988. #include <skinnormal_vertex>
  2989. #include <defaultnormal_vertex>
  2990. #include <normal_vertex>
  2991. #include <begin_vertex>
  2992. #include <morphtarget_vertex>
  2993. #include <skinning_vertex>
  2994. #include <displacementmap_vertex>
  2995. #include <project_vertex>
  2996. #include <logdepthbuf_vertex>
  2997. #include <clipping_planes_vertex>
  2998. #include <fog_vertex>
  2999. vViewPosition = - mvPosition.xyz;
  3000. }`,fke=`#define MATCAP
  3001. uniform vec3 diffuse;
  3002. uniform float opacity;
  3003. uniform sampler2D matcap;
  3004. varying vec3 vViewPosition;
  3005. #include <common>
  3006. #include <dithering_pars_fragment>
  3007. #include <color_pars_fragment>
  3008. #include <uv_pars_fragment>
  3009. #include <map_pars_fragment>
  3010. #include <alphamap_pars_fragment>
  3011. #include <alphatest_pars_fragment>
  3012. #include <alphahash_pars_fragment>
  3013. #include <fog_pars_fragment>
  3014. #include <normal_pars_fragment>
  3015. #include <bumpmap_pars_fragment>
  3016. #include <normalmap_pars_fragment>
  3017. #include <logdepthbuf_pars_fragment>
  3018. #include <clipping_planes_pars_fragment>
  3019. void main() {
  3020. vec4 diffuseColor = vec4( diffuse, opacity );
  3021. #include <clipping_planes_fragment>
  3022. #include <logdepthbuf_fragment>
  3023. #include <map_fragment>
  3024. #include <color_fragment>
  3025. #include <alphamap_fragment>
  3026. #include <alphatest_fragment>
  3027. #include <alphahash_fragment>
  3028. #include <normal_fragment_begin>
  3029. #include <normal_fragment_maps>
  3030. vec3 viewDir = normalize( vViewPosition );
  3031. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  3032. vec3 y = cross( viewDir, x );
  3033. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  3034. #ifdef USE_MATCAP
  3035. vec4 matcapColor = texture2D( matcap, uv );
  3036. #else
  3037. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  3038. #endif
  3039. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  3040. #include <opaque_fragment>
  3041. #include <tonemapping_fragment>
  3042. #include <colorspace_fragment>
  3043. #include <fog_fragment>
  3044. #include <premultiplied_alpha_fragment>
  3045. #include <dithering_fragment>
  3046. }`,gke=`#define NORMAL
  3047. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3048. varying vec3 vViewPosition;
  3049. #endif
  3050. #include <common>
  3051. #include <batching_pars_vertex>
  3052. #include <uv_pars_vertex>
  3053. #include <displacementmap_pars_vertex>
  3054. #include <normal_pars_vertex>
  3055. #include <morphtarget_pars_vertex>
  3056. #include <skinning_pars_vertex>
  3057. #include <logdepthbuf_pars_vertex>
  3058. #include <clipping_planes_pars_vertex>
  3059. void main() {
  3060. #include <uv_vertex>
  3061. #include <batching_vertex>
  3062. #include <beginnormal_vertex>
  3063. #include <morphinstance_vertex>
  3064. #include <morphnormal_vertex>
  3065. #include <skinbase_vertex>
  3066. #include <skinnormal_vertex>
  3067. #include <defaultnormal_vertex>
  3068. #include <normal_vertex>
  3069. #include <begin_vertex>
  3070. #include <morphtarget_vertex>
  3071. #include <skinning_vertex>
  3072. #include <displacementmap_vertex>
  3073. #include <project_vertex>
  3074. #include <logdepthbuf_vertex>
  3075. #include <clipping_planes_vertex>
  3076. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3077. vViewPosition = - mvPosition.xyz;
  3078. #endif
  3079. }`,bke=`#define NORMAL
  3080. uniform float opacity;
  3081. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3082. varying vec3 vViewPosition;
  3083. #endif
  3084. #include <packing>
  3085. #include <uv_pars_fragment>
  3086. #include <normal_pars_fragment>
  3087. #include <bumpmap_pars_fragment>
  3088. #include <normalmap_pars_fragment>
  3089. #include <logdepthbuf_pars_fragment>
  3090. #include <clipping_planes_pars_fragment>
  3091. void main() {
  3092. vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
  3093. #include <clipping_planes_fragment>
  3094. #include <logdepthbuf_fragment>
  3095. #include <normal_fragment_begin>
  3096. #include <normal_fragment_maps>
  3097. gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
  3098. #ifdef OPAQUE
  3099. gl_FragColor.a = 1.0;
  3100. #endif
  3101. }`,xke=`#define PHONG
  3102. varying vec3 vViewPosition;
  3103. #include <common>
  3104. #include <batching_pars_vertex>
  3105. #include <uv_pars_vertex>
  3106. #include <displacementmap_pars_vertex>
  3107. #include <envmap_pars_vertex>
  3108. #include <color_pars_vertex>
  3109. #include <fog_pars_vertex>
  3110. #include <normal_pars_vertex>
  3111. #include <morphtarget_pars_vertex>
  3112. #include <skinning_pars_vertex>
  3113. #include <shadowmap_pars_vertex>
  3114. #include <logdepthbuf_pars_vertex>
  3115. #include <clipping_planes_pars_vertex>
  3116. void main() {
  3117. #include <uv_vertex>
  3118. #include <color_vertex>
  3119. #include <morphcolor_vertex>
  3120. #include <batching_vertex>
  3121. #include <beginnormal_vertex>
  3122. #include <morphinstance_vertex>
  3123. #include <morphnormal_vertex>
  3124. #include <skinbase_vertex>
  3125. #include <skinnormal_vertex>
  3126. #include <defaultnormal_vertex>
  3127. #include <normal_vertex>
  3128. #include <begin_vertex>
  3129. #include <morphtarget_vertex>
  3130. #include <skinning_vertex>
  3131. #include <displacementmap_vertex>
  3132. #include <project_vertex>
  3133. #include <logdepthbuf_vertex>
  3134. #include <clipping_planes_vertex>
  3135. vViewPosition = - mvPosition.xyz;
  3136. #include <worldpos_vertex>
  3137. #include <envmap_vertex>
  3138. #include <shadowmap_vertex>
  3139. #include <fog_vertex>
  3140. }`,yke=`#define PHONG
  3141. uniform vec3 diffuse;
  3142. uniform vec3 emissive;
  3143. uniform vec3 specular;
  3144. uniform float shininess;
  3145. uniform float opacity;
  3146. #include <common>
  3147. #include <packing>
  3148. #include <dithering_pars_fragment>
  3149. #include <color_pars_fragment>
  3150. #include <uv_pars_fragment>
  3151. #include <map_pars_fragment>
  3152. #include <alphamap_pars_fragment>
  3153. #include <alphatest_pars_fragment>
  3154. #include <alphahash_pars_fragment>
  3155. #include <aomap_pars_fragment>
  3156. #include <lightmap_pars_fragment>
  3157. #include <emissivemap_pars_fragment>
  3158. #include <envmap_common_pars_fragment>
  3159. #include <envmap_pars_fragment>
  3160. #include <fog_pars_fragment>
  3161. #include <bsdfs>
  3162. #include <lights_pars_begin>
  3163. #include <normal_pars_fragment>
  3164. #include <lights_phong_pars_fragment>
  3165. #include <shadowmap_pars_fragment>
  3166. #include <bumpmap_pars_fragment>
  3167. #include <normalmap_pars_fragment>
  3168. #include <specularmap_pars_fragment>
  3169. #include <logdepthbuf_pars_fragment>
  3170. #include <clipping_planes_pars_fragment>
  3171. void main() {
  3172. vec4 diffuseColor = vec4( diffuse, opacity );
  3173. #include <clipping_planes_fragment>
  3174. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3175. vec3 totalEmissiveRadiance = emissive;
  3176. #include <logdepthbuf_fragment>
  3177. #include <map_fragment>
  3178. #include <color_fragment>
  3179. #include <alphamap_fragment>
  3180. #include <alphatest_fragment>
  3181. #include <alphahash_fragment>
  3182. #include <specularmap_fragment>
  3183. #include <normal_fragment_begin>
  3184. #include <normal_fragment_maps>
  3185. #include <emissivemap_fragment>
  3186. #include <lights_phong_fragment>
  3187. #include <lights_fragment_begin>
  3188. #include <lights_fragment_maps>
  3189. #include <lights_fragment_end>
  3190. #include <aomap_fragment>
  3191. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  3192. #include <envmap_fragment>
  3193. #include <opaque_fragment>
  3194. #include <tonemapping_fragment>
  3195. #include <colorspace_fragment>
  3196. #include <fog_fragment>
  3197. #include <premultiplied_alpha_fragment>
  3198. #include <dithering_fragment>
  3199. }`,vke=`#define STANDARD
  3200. varying vec3 vViewPosition;
  3201. #ifdef USE_TRANSMISSION
  3202. varying vec3 vWorldPosition;
  3203. #endif
  3204. #include <common>
  3205. #include <batching_pars_vertex>
  3206. #include <uv_pars_vertex>
  3207. #include <displacementmap_pars_vertex>
  3208. #include <color_pars_vertex>
  3209. #include <fog_pars_vertex>
  3210. #include <normal_pars_vertex>
  3211. #include <morphtarget_pars_vertex>
  3212. #include <skinning_pars_vertex>
  3213. #include <shadowmap_pars_vertex>
  3214. #include <logdepthbuf_pars_vertex>
  3215. #include <clipping_planes_pars_vertex>
  3216. void main() {
  3217. #include <uv_vertex>
  3218. #include <color_vertex>
  3219. #include <morphinstance_vertex>
  3220. #include <morphcolor_vertex>
  3221. #include <batching_vertex>
  3222. #include <beginnormal_vertex>
  3223. #include <morphnormal_vertex>
  3224. #include <skinbase_vertex>
  3225. #include <skinnormal_vertex>
  3226. #include <defaultnormal_vertex>
  3227. #include <normal_vertex>
  3228. #include <begin_vertex>
  3229. #include <morphtarget_vertex>
  3230. #include <skinning_vertex>
  3231. #include <displacementmap_vertex>
  3232. #include <project_vertex>
  3233. #include <logdepthbuf_vertex>
  3234. #include <clipping_planes_vertex>
  3235. vViewPosition = - mvPosition.xyz;
  3236. #include <worldpos_vertex>
  3237. #include <shadowmap_vertex>
  3238. #include <fog_vertex>
  3239. #ifdef USE_TRANSMISSION
  3240. vWorldPosition = worldPosition.xyz;
  3241. #endif
  3242. }`,wke=`#define STANDARD
  3243. #ifdef PHYSICAL
  3244. #define IOR
  3245. #define USE_SPECULAR
  3246. #endif
  3247. uniform vec3 diffuse;
  3248. uniform vec3 emissive;
  3249. uniform float roughness;
  3250. uniform float metalness;
  3251. uniform float opacity;
  3252. #ifdef IOR
  3253. uniform float ior;
  3254. #endif
  3255. #ifdef USE_SPECULAR
  3256. uniform float specularIntensity;
  3257. uniform vec3 specularColor;
  3258. #ifdef USE_SPECULAR_COLORMAP
  3259. uniform sampler2D specularColorMap;
  3260. #endif
  3261. #ifdef USE_SPECULAR_INTENSITYMAP
  3262. uniform sampler2D specularIntensityMap;
  3263. #endif
  3264. #endif
  3265. #ifdef USE_CLEARCOAT
  3266. uniform float clearcoat;
  3267. uniform float clearcoatRoughness;
  3268. #endif
  3269. #ifdef USE_DISPERSION
  3270. uniform float dispersion;
  3271. #endif
  3272. #ifdef USE_IRIDESCENCE
  3273. uniform float iridescence;
  3274. uniform float iridescenceIOR;
  3275. uniform float iridescenceThicknessMinimum;
  3276. uniform float iridescenceThicknessMaximum;
  3277. #endif
  3278. #ifdef USE_SHEEN
  3279. uniform vec3 sheenColor;
  3280. uniform float sheenRoughness;
  3281. #ifdef USE_SHEEN_COLORMAP
  3282. uniform sampler2D sheenColorMap;
  3283. #endif
  3284. #ifdef USE_SHEEN_ROUGHNESSMAP
  3285. uniform sampler2D sheenRoughnessMap;
  3286. #endif
  3287. #endif
  3288. #ifdef USE_ANISOTROPY
  3289. uniform vec2 anisotropyVector;
  3290. #ifdef USE_ANISOTROPYMAP
  3291. uniform sampler2D anisotropyMap;
  3292. #endif
  3293. #endif
  3294. varying vec3 vViewPosition;
  3295. #include <common>
  3296. #include <packing>
  3297. #include <dithering_pars_fragment>
  3298. #include <color_pars_fragment>
  3299. #include <uv_pars_fragment>
  3300. #include <map_pars_fragment>
  3301. #include <alphamap_pars_fragment>
  3302. #include <alphatest_pars_fragment>
  3303. #include <alphahash_pars_fragment>
  3304. #include <aomap_pars_fragment>
  3305. #include <lightmap_pars_fragment>
  3306. #include <emissivemap_pars_fragment>
  3307. #include <iridescence_fragment>
  3308. #include <cube_uv_reflection_fragment>
  3309. #include <envmap_common_pars_fragment>
  3310. #include <envmap_physical_pars_fragment>
  3311. #include <fog_pars_fragment>
  3312. #include <lights_pars_begin>
  3313. #include <normal_pars_fragment>
  3314. #include <lights_physical_pars_fragment>
  3315. #include <transmission_pars_fragment>
  3316. #include <shadowmap_pars_fragment>
  3317. #include <bumpmap_pars_fragment>
  3318. #include <normalmap_pars_fragment>
  3319. #include <clearcoat_pars_fragment>
  3320. #include <iridescence_pars_fragment>
  3321. #include <roughnessmap_pars_fragment>
  3322. #include <metalnessmap_pars_fragment>
  3323. #include <logdepthbuf_pars_fragment>
  3324. #include <clipping_planes_pars_fragment>
  3325. void main() {
  3326. vec4 diffuseColor = vec4( diffuse, opacity );
  3327. #include <clipping_planes_fragment>
  3328. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3329. vec3 totalEmissiveRadiance = emissive;
  3330. #include <logdepthbuf_fragment>
  3331. #include <map_fragment>
  3332. #include <color_fragment>
  3333. #include <alphamap_fragment>
  3334. #include <alphatest_fragment>
  3335. #include <alphahash_fragment>
  3336. #include <roughnessmap_fragment>
  3337. #include <metalnessmap_fragment>
  3338. #include <normal_fragment_begin>
  3339. #include <normal_fragment_maps>
  3340. #include <clearcoat_normal_fragment_begin>
  3341. #include <clearcoat_normal_fragment_maps>
  3342. #include <emissivemap_fragment>
  3343. #include <lights_physical_fragment>
  3344. #include <lights_fragment_begin>
  3345. #include <lights_fragment_maps>
  3346. #include <lights_fragment_end>
  3347. #include <aomap_fragment>
  3348. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  3349. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  3350. #include <transmission_fragment>
  3351. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  3352. #ifdef USE_SHEEN
  3353. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  3354. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  3355. #endif
  3356. #ifdef USE_CLEARCOAT
  3357. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  3358. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  3359. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  3360. #endif
  3361. #include <opaque_fragment>
  3362. #include <tonemapping_fragment>
  3363. #include <colorspace_fragment>
  3364. #include <fog_fragment>
  3365. #include <premultiplied_alpha_fragment>
  3366. #include <dithering_fragment>
  3367. }`,Ske=`#define TOON
  3368. varying vec3 vViewPosition;
  3369. #include <common>
  3370. #include <batching_pars_vertex>
  3371. #include <uv_pars_vertex>
  3372. #include <displacementmap_pars_vertex>
  3373. #include <color_pars_vertex>
  3374. #include <fog_pars_vertex>
  3375. #include <normal_pars_vertex>
  3376. #include <morphtarget_pars_vertex>
  3377. #include <skinning_pars_vertex>
  3378. #include <shadowmap_pars_vertex>
  3379. #include <logdepthbuf_pars_vertex>
  3380. #include <clipping_planes_pars_vertex>
  3381. void main() {
  3382. #include <uv_vertex>
  3383. #include <color_vertex>
  3384. #include <morphinstance_vertex>
  3385. #include <morphcolor_vertex>
  3386. #include <batching_vertex>
  3387. #include <beginnormal_vertex>
  3388. #include <morphnormal_vertex>
  3389. #include <skinbase_vertex>
  3390. #include <skinnormal_vertex>
  3391. #include <defaultnormal_vertex>
  3392. #include <normal_vertex>
  3393. #include <begin_vertex>
  3394. #include <morphtarget_vertex>
  3395. #include <skinning_vertex>
  3396. #include <displacementmap_vertex>
  3397. #include <project_vertex>
  3398. #include <logdepthbuf_vertex>
  3399. #include <clipping_planes_vertex>
  3400. vViewPosition = - mvPosition.xyz;
  3401. #include <worldpos_vertex>
  3402. #include <shadowmap_vertex>
  3403. #include <fog_vertex>
  3404. }`,_ke=`#define TOON
  3405. uniform vec3 diffuse;
  3406. uniform vec3 emissive;
  3407. uniform float opacity;
  3408. #include <common>
  3409. #include <packing>
  3410. #include <dithering_pars_fragment>
  3411. #include <color_pars_fragment>
  3412. #include <uv_pars_fragment>
  3413. #include <map_pars_fragment>
  3414. #include <alphamap_pars_fragment>
  3415. #include <alphatest_pars_fragment>
  3416. #include <alphahash_pars_fragment>
  3417. #include <aomap_pars_fragment>
  3418. #include <lightmap_pars_fragment>
  3419. #include <emissivemap_pars_fragment>
  3420. #include <gradientmap_pars_fragment>
  3421. #include <fog_pars_fragment>
  3422. #include <bsdfs>
  3423. #include <lights_pars_begin>
  3424. #include <normal_pars_fragment>
  3425. #include <lights_toon_pars_fragment>
  3426. #include <shadowmap_pars_fragment>
  3427. #include <bumpmap_pars_fragment>
  3428. #include <normalmap_pars_fragment>
  3429. #include <logdepthbuf_pars_fragment>
  3430. #include <clipping_planes_pars_fragment>
  3431. void main() {
  3432. vec4 diffuseColor = vec4( diffuse, opacity );
  3433. #include <clipping_planes_fragment>
  3434. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3435. vec3 totalEmissiveRadiance = emissive;
  3436. #include <logdepthbuf_fragment>
  3437. #include <map_fragment>
  3438. #include <color_fragment>
  3439. #include <alphamap_fragment>
  3440. #include <alphatest_fragment>
  3441. #include <alphahash_fragment>
  3442. #include <normal_fragment_begin>
  3443. #include <normal_fragment_maps>
  3444. #include <emissivemap_fragment>
  3445. #include <lights_toon_fragment>
  3446. #include <lights_fragment_begin>
  3447. #include <lights_fragment_maps>
  3448. #include <lights_fragment_end>
  3449. #include <aomap_fragment>
  3450. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  3451. #include <opaque_fragment>
  3452. #include <tonemapping_fragment>
  3453. #include <colorspace_fragment>
  3454. #include <fog_fragment>
  3455. #include <premultiplied_alpha_fragment>
  3456. #include <dithering_fragment>
  3457. }`,kke=`uniform float size;
  3458. uniform float scale;
  3459. #include <common>
  3460. #include <color_pars_vertex>
  3461. #include <fog_pars_vertex>
  3462. #include <morphtarget_pars_vertex>
  3463. #include <logdepthbuf_pars_vertex>
  3464. #include <clipping_planes_pars_vertex>
  3465. #ifdef USE_POINTS_UV
  3466. varying vec2 vUv;
  3467. uniform mat3 uvTransform;
  3468. #endif
  3469. void main() {
  3470. #ifdef USE_POINTS_UV
  3471. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  3472. #endif
  3473. #include <color_vertex>
  3474. #include <morphinstance_vertex>
  3475. #include <morphcolor_vertex>
  3476. #include <begin_vertex>
  3477. #include <morphtarget_vertex>
  3478. #include <project_vertex>
  3479. gl_PointSize = size;
  3480. #ifdef USE_SIZEATTENUATION
  3481. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3482. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  3483. #endif
  3484. #include <logdepthbuf_vertex>
  3485. #include <clipping_planes_vertex>
  3486. #include <worldpos_vertex>
  3487. #include <fog_vertex>
  3488. }`,Nke=`uniform vec3 diffuse;
  3489. uniform float opacity;
  3490. #include <common>
  3491. #include <color_pars_fragment>
  3492. #include <map_particle_pars_fragment>
  3493. #include <alphatest_pars_fragment>
  3494. #include <alphahash_pars_fragment>
  3495. #include <fog_pars_fragment>
  3496. #include <logdepthbuf_pars_fragment>
  3497. #include <clipping_planes_pars_fragment>
  3498. void main() {
  3499. vec4 diffuseColor = vec4( diffuse, opacity );
  3500. #include <clipping_planes_fragment>
  3501. vec3 outgoingLight = vec3( 0.0 );
  3502. #include <logdepthbuf_fragment>
  3503. #include <map_particle_fragment>
  3504. #include <color_fragment>
  3505. #include <alphatest_fragment>
  3506. #include <alphahash_fragment>
  3507. outgoingLight = diffuseColor.rgb;
  3508. #include <opaque_fragment>
  3509. #include <tonemapping_fragment>
  3510. #include <colorspace_fragment>
  3511. #include <fog_fragment>
  3512. #include <premultiplied_alpha_fragment>
  3513. }`,Cke=`#include <common>
  3514. #include <batching_pars_vertex>
  3515. #include <fog_pars_vertex>
  3516. #include <morphtarget_pars_vertex>
  3517. #include <skinning_pars_vertex>
  3518. #include <logdepthbuf_pars_vertex>
  3519. #include <shadowmap_pars_vertex>
  3520. void main() {
  3521. #include <batching_vertex>
  3522. #include <beginnormal_vertex>
  3523. #include <morphinstance_vertex>
  3524. #include <morphnormal_vertex>
  3525. #include <skinbase_vertex>
  3526. #include <skinnormal_vertex>
  3527. #include <defaultnormal_vertex>
  3528. #include <begin_vertex>
  3529. #include <morphtarget_vertex>
  3530. #include <skinning_vertex>
  3531. #include <project_vertex>
  3532. #include <logdepthbuf_vertex>
  3533. #include <worldpos_vertex>
  3534. #include <shadowmap_vertex>
  3535. #include <fog_vertex>
  3536. }`,Pke=`uniform vec3 color;
  3537. uniform float opacity;
  3538. #include <common>
  3539. #include <packing>
  3540. #include <fog_pars_fragment>
  3541. #include <bsdfs>
  3542. #include <lights_pars_begin>
  3543. #include <logdepthbuf_pars_fragment>
  3544. #include <shadowmap_pars_fragment>
  3545. #include <shadowmask_pars_fragment>
  3546. void main() {
  3547. #include <logdepthbuf_fragment>
  3548. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  3549. #include <tonemapping_fragment>
  3550. #include <colorspace_fragment>
  3551. #include <fog_fragment>
  3552. }`,Tke=`uniform float rotation;
  3553. uniform vec2 center;
  3554. #include <common>
  3555. #include <uv_pars_vertex>
  3556. #include <fog_pars_vertex>
  3557. #include <logdepthbuf_pars_vertex>
  3558. #include <clipping_planes_pars_vertex>
  3559. void main() {
  3560. #include <uv_vertex>
  3561. vec4 mvPosition = modelViewMatrix[ 3 ];
  3562. vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
  3563. #ifndef USE_SIZEATTENUATION
  3564. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3565. if ( isPerspective ) scale *= - mvPosition.z;
  3566. #endif
  3567. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  3568. vec2 rotatedPosition;
  3569. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  3570. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  3571. mvPosition.xy += rotatedPosition;
  3572. gl_Position = projectionMatrix * mvPosition;
  3573. #include <logdepthbuf_vertex>
  3574. #include <clipping_planes_vertex>
  3575. #include <fog_vertex>
  3576. }`,Ake=`uniform vec3 diffuse;
  3577. uniform float opacity;
  3578. #include <common>
  3579. #include <uv_pars_fragment>
  3580. #include <map_pars_fragment>
  3581. #include <alphamap_pars_fragment>
  3582. #include <alphatest_pars_fragment>
  3583. #include <alphahash_pars_fragment>
  3584. #include <fog_pars_fragment>
  3585. #include <logdepthbuf_pars_fragment>
  3586. #include <clipping_planes_pars_fragment>
  3587. void main() {
  3588. vec4 diffuseColor = vec4( diffuse, opacity );
  3589. #include <clipping_planes_fragment>
  3590. vec3 outgoingLight = vec3( 0.0 );
  3591. #include <logdepthbuf_fragment>
  3592. #include <map_fragment>
  3593. #include <alphamap_fragment>
  3594. #include <alphatest_fragment>
  3595. #include <alphahash_fragment>
  3596. outgoingLight = diffuseColor.rgb;
  3597. #include <opaque_fragment>
  3598. #include <tonemapping_fragment>
  3599. #include <colorspace_fragment>
  3600. #include <fog_fragment>
  3601. }`,rr={alphahash_fragment:Xwe,alphahash_pars_fragment:Zwe,alphamap_fragment:Jwe,alphamap_pars_fragment:eSe,alphatest_fragment:tSe,alphatest_pars_fragment:nSe,aomap_fragment:rSe,aomap_pars_fragment:aSe,batching_pars_vertex:iSe,batching_vertex:sSe,begin_vertex:oSe,beginnormal_vertex:lSe,bsdfs:cSe,iridescence_fragment:dSe,bumpmap_pars_fragment:uSe,clipping_planes_fragment:mSe,clipping_planes_pars_fragment:pSe,clipping_planes_pars_vertex:hSe,clipping_planes_vertex:fSe,color_fragment:gSe,color_pars_fragment:bSe,color_pars_vertex:xSe,color_vertex:ySe,common:vSe,cube_uv_reflection_fragment:wSe,defaultnormal_vertex:SSe,displacementmap_pars_vertex:_Se,displacementmap_vertex:kSe,emissivemap_fragment:NSe,emissivemap_pars_fragment:CSe,colorspace_fragment:PSe,colorspace_pars_fragment:TSe,envmap_fragment:ASe,envmap_common_pars_fragment:jSe,envmap_pars_fragment:MSe,envmap_pars_vertex:ESe,envmap_physical_pars_fragment:qSe,envmap_vertex:DSe,fog_vertex:FSe,fog_pars_vertex:LSe,fog_fragment:RSe,fog_pars_fragment:ISe,gradientmap_pars_fragment:OSe,lightmap_pars_fragment:zSe,lights_lambert_fragment:USe,lights_lambert_pars_fragment:BSe,lights_pars_begin:HSe,lights_toon_fragment:$Se,lights_toon_pars_fragment:VSe,lights_phong_fragment:GSe,lights_phong_pars_fragment:WSe,lights_physical_fragment:KSe,lights_physical_pars_fragment:QSe,lights_fragment_begin:YSe,lights_fragment_maps:XSe,lights_fragment_end:ZSe,logdepthbuf_fragment:JSe,logdepthbuf_pars_fragment:e_e,logdepthbuf_pars_vertex:t_e,logdepthbuf_vertex:n_e,map_fragment:r_e,map_pars_fragment:a_e,map_particle_fragment:i_e,map_particle_pars_fragment:s_e,metalnessmap_fragment:o_e,metalnessmap_pars_fragment:l_e,morphinstance_vertex:c_e,morphcolor_vertex:d_e,morphnormal_vertex:u_e,morphtarget_pars_vertex:m_e,morphtarget_vertex:p_e,normal_fragment_begin:h_e,normal_fragment_maps:f_e,normal_pars_fragment:g_e,normal_pars_vertex:b_e,normal_vertex:x_e,normalmap_pars_fragment:y_e,clearcoat_normal_fragment_begin:v_e,clearcoat_normal_fragment_maps:w_e,clearcoat_pars_fragment:S_e,iridescence_pars_fragment:__e,opaque_fragment:k_e,packing:N_e,premultiplied_alpha_fragment:C_e,project_vertex:P_e,dithering_fragment:T_e,dithering_pars_fragment:A_e,roughnessmap_fragment:j_e,roughnessmap_pars_fragment:M_e,shadowmap_pars_fragment:E_e,shadowmap_pars_vertex:D_e,shadowmap_vertex:F_e,shadowmask_pars_fragment:L_e,skinbase_vertex:R_e,skinning_pars_vertex:I_e,skinning_vertex:O_e,skinnormal_vertex:z_e,specularmap_fragment:U_e,specularmap_pars_fragment:B_e,tonemapping_fragment:H_e,tonemapping_pars_fragment:q_e,transmission_fragment:$_e,transmission_pars_fragment:V_e,uv_pars_fragment:G_e,uv_pars_vertex:W_e,uv_vertex:K_e,worldpos_vertex:Q_e,background_vert:Y_e,background_frag:X_e,backgroundCube_vert:Z_e,backgroundCube_frag:J_e,cube_vert:eke,cube_frag:tke,depth_vert:nke,depth_frag:rke,distanceRGBA_vert:ake,distanceRGBA_frag:ike,equirect_vert:ske,equirect_frag:oke,linedashed_vert:lke,linedashed_frag:cke,meshbasic_vert:dke,meshbasic_frag:uke,meshlambert_vert:mke,meshlambert_frag:pke,meshmatcap_vert:hke,meshmatcap_frag:fke,meshnormal_vert:gke,meshnormal_frag:bke,meshphong_vert:xke,meshphong_frag:yke,meshphysical_vert:vke,meshphysical_frag:wke,meshtoon_vert:Ske,meshtoon_frag:_ke,points_vert:kke,points_frag:Nke,shadow_vert:Cke,shadow_frag:Pke,sprite_vert:Tke,sprite_frag:Ake},un={common:{diffuse:{value:new cr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new lr},alphaMap:{value:null},alphaMapTransform:{value:new lr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new lr}},envmap:{envMap:{value:null},envMapRotation:{value:new lr},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 lr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new lr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new lr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new lr},normalScale:{value:new ir(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new lr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new lr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new lr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new lr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new cr(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 cr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new lr},alphaTest:{value:0},uvTransform:{value:new lr}},sprite:{diffuse:{value:new cr(16777215)},opacity:{value:1},center:{value:new ir(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new lr},alphaMap:{value:null},alphaMapTransform:{value:new lr},alphaTest:{value:0}}},Wd={basic:{uniforms:fo([un.common,un.specularmap,un.envmap,un.aomap,un.lightmap,un.fog]),vertexShader:rr.meshbasic_vert,fragmentShader:rr.meshbasic_frag},lambert:{uniforms:fo([un.common,un.specularmap,un.envmap,un.aomap,un.lightmap,un.emissivemap,un.bumpmap,un.normalmap,un.displacementmap,un.fog,un.lights,{emissive:{value:new cr(0)}}]),vertexShader:rr.meshlambert_vert,fragmentShader:rr.meshlambert_frag},phong:{uniforms:fo([un.common,un.specularmap,un.envmap,un.aomap,un.lightmap,un.emissivemap,un.bumpmap,un.normalmap,un.displacementmap,un.fog,un.lights,{emissive:{value:new cr(0)},specular:{value:new cr(1118481)},shininess:{value:30}}]),vertexShader:rr.meshphong_vert,fragmentShader:rr.meshphong_frag},standard:{uniforms:fo([un.common,un.envmap,un.aomap,un.lightmap,un.emissivemap,un.bumpmap,un.normalmap,un.displacementmap,un.roughnessmap,un.metalnessmap,un.fog,un.lights,{emissive:{value:new cr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:rr.meshphysical_vert,fragmentShader:rr.meshphysical_frag},toon:{uniforms:fo([un.common,un.aomap,un.lightmap,un.emissivemap,un.bumpmap,un.normalmap,un.displacementmap,un.gradientmap,un.fog,un.lights,{emissive:{value:new cr(0)}}]),vertexShader:rr.meshtoon_vert,fragmentShader:rr.meshtoon_frag},matcap:{uniforms:fo([un.common,un.bumpmap,un.normalmap,un.displacementmap,un.fog,{matcap:{value:null}}]),vertexShader:rr.meshmatcap_vert,fragmentShader:rr.meshmatcap_frag},points:{uniforms:fo([un.points,un.fog]),vertexShader:rr.points_vert,fragmentShader:rr.points_frag},dashed:{uniforms:fo([un.common,un.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:rr.linedashed_vert,fragmentShader:rr.linedashed_frag},depth:{uniforms:fo([un.common,un.displacementmap]),vertexShader:rr.depth_vert,fragmentShader:rr.depth_frag},normal:{uniforms:fo([un.common,un.bumpmap,un.normalmap,un.displacementmap,{opacity:{value:1}}]),vertexShader:rr.meshnormal_vert,fragmentShader:rr.meshnormal_frag},sprite:{uniforms:fo([un.sprite,un.fog]),vertexShader:rr.sprite_vert,fragmentShader:rr.sprite_frag},background:{uniforms:{uvTransform:{value:new lr},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},backgroundRotation:{value:new lr}},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:fo([un.common,un.displacementmap,{referencePosition:{value:new Lt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:rr.distanceRGBA_vert,fragmentShader:rr.distanceRGBA_frag},shadow:{uniforms:fo([un.lights,un.fog,{color:{value:new cr(0)},opacity:{value:1}}]),vertexShader:rr.shadow_vert,fragmentShader:rr.shadow_frag}};Wd.physical={uniforms:fo([Wd.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new lr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new lr},clearcoatNormalScale:{value:new ir(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new lr},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new lr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new lr},sheen:{value:0},sheenColor:{value:new cr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new lr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new lr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new lr},transmissionSamplerSize:{value:new ir},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new lr},attenuationDistance:{value:0},attenuationColor:{value:new cr(0)},specularColor:{value:new cr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new lr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new lr},anisotropyVector:{value:new ir},anisotropyMap:{value:null},anisotropyMapTransform:{value:new lr}}]),vertexShader:rr.meshphysical_vert,fragmentShader:rr.meshphysical_frag};const Kk={r:0,b:0,g:0},Rf=new Kh,jke=new Ci;function Mke(t,e,n,a,i,s,o){const l=new cr(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function g(k){let C=k.isScene===!0?k.background:null;return C&&C.isTexture&&(C=(k.backgroundBlurriness>0?n:e).get(C)),C}function w(k){let C=!1;const P=g(k);P===null?x(l,c):P&&P.isColor&&(x(P,1),C=!0);const T=t.xr.getEnvironmentBlendMode();T==="additive"?a.buffers.color.setClear(0,0,0,1,o):T==="alpha-blend"&&a.buffers.color.setClear(0,0,0,0,o),(t.autoClear||C)&&(a.buffers.depth.setTest(!0),a.buffers.depth.setMask(!0),a.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function b(k,C){const P=g(C);P&&(P.isCubeTexture||P.mapping===jT)?(u===void 0&&(u=new _c(new $O(1,1,1),new Km({name:"BackgroundCubeMaterial",uniforms:_y(Wd.backgroundCube.uniforms),vertexShader:Wd.backgroundCube.vertexShader,fragmentShader:Wd.backgroundCube.fragmentShader,side:Wo,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(T,A,F){this.matrixWorld.copyPosition(F.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Rf.copy(C.backgroundRotation),Rf.x*=-1,Rf.y*=-1,Rf.z*=-1,P.isCubeTexture&&P.isRenderTargetTexture===!1&&(Rf.y*=-1,Rf.z*=-1),u.material.uniforms.envMap.value=P,u.material.uniforms.flipEnvMap.value=P.isCubeTexture&&P.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=C.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=C.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(jke.makeRotationFromEuler(Rf)),u.material.toneMapped=Or.getTransfer(P.colorSpace)!==aa,(m!==P||p!==P.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=P,p=P.version,f=t.toneMapping),u.layers.enableAll(),k.unshift(u,u.geometry,u.material,0,0,null)):P&&P.isTexture&&(d===void 0&&(d=new _c(new GO(2,2),new Km({name:"BackgroundMaterial",uniforms:_y(Wd.background.uniforms),vertexShader:Wd.background.vertexShader,fragmentShader:Wd.background.fragmentShader,side:Wh,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=P,d.material.uniforms.backgroundIntensity.value=C.backgroundIntensity,d.material.toneMapped=Or.getTransfer(P.colorSpace)!==aa,P.matrixAutoUpdate===!0&&P.updateMatrix(),d.material.uniforms.uvTransform.value.copy(P.matrix),(m!==P||p!==P.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=P,p=P.version,f=t.toneMapping),d.layers.enableAll(),k.unshift(d,d.geometry,d.material,0,0,null))}function x(k,C){k.getRGB(Kk,FJ(t)),a.buffers.color.setClear(Kk.r,Kk.g,Kk.b,C,o)}function S(){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(k,C=1){l.set(k),c=C,x(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(k){c=k,x(l,c)},render:w,addToRenderList:b,dispose:S}}function Eke(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),a={},i=p(null);let s=i,o=!1;function l(M,H,I,z,L){let Z=!1;const ne=m(z,I,H);s!==ne&&(s=ne,d(s.object)),Z=f(M,z,I,L),Z&&g(M,z,I,L),L!==null&&e.update(L,t.ELEMENT_ARRAY_BUFFER),(Z||o)&&(o=!1,C(M,H,I,z),L!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(L).buffer))}function c(){return t.createVertexArray()}function d(M){return t.bindVertexArray(M)}function u(M){return t.deleteVertexArray(M)}function m(M,H,I){const z=I.wireframe===!0;let L=a[M.id];L===void 0&&(L={},a[M.id]=L);let Z=L[H.id];Z===void 0&&(Z={},L[H.id]=Z);let ne=Z[z];return ne===void 0&&(ne=p(c()),Z[z]=ne),ne}function p(M){const H=[],I=[],z=[];for(let L=0;L<n;L++)H[L]=0,I[L]=0,z[L]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:H,enabledAttributes:I,attributeDivisors:z,object:M,attributes:{},index:null}}function f(M,H,I,z){const L=s.attributes,Z=H.attributes;let ne=0;const Y=I.getAttributes();for(const ce in Y)if(Y[ce].location>=0){const oe=L[ce];let Q=Z[ce];if(Q===void 0&&(ce==="instanceMatrix"&&M.instanceMatrix&&(Q=M.instanceMatrix),ce==="instanceColor"&&M.instanceColor&&(Q=M.instanceColor)),oe===void 0||oe.attribute!==Q||Q&&oe.data!==Q.data)return!0;ne++}return s.attributesNum!==ne||s.index!==z}function g(M,H,I,z){const L={},Z=H.attributes;let ne=0;const Y=I.getAttributes();for(const ce in Y)if(Y[ce].location>=0){let oe=Z[ce];oe===void 0&&(ce==="instanceMatrix"&&M.instanceMatrix&&(oe=M.instanceMatrix),ce==="instanceColor"&&M.instanceColor&&(oe=M.instanceColor));const Q={};Q.attribute=oe,oe&&oe.data&&(Q.data=oe.data),L[ce]=Q,ne++}s.attributes=L,s.attributesNum=ne,s.index=z}function w(){const M=s.newAttributes;for(let H=0,I=M.length;H<I;H++)M[H]=0}function b(M){x(M,0)}function x(M,H){const I=s.newAttributes,z=s.enabledAttributes,L=s.attributeDivisors;I[M]=1,z[M]===0&&(t.enableVertexAttribArray(M),z[M]=1),L[M]!==H&&(t.vertexAttribDivisor(M,H),L[M]=H)}function S(){const M=s.newAttributes,H=s.enabledAttributes;for(let I=0,z=H.length;I<z;I++)H[I]!==M[I]&&(t.disableVertexAttribArray(I),H[I]=0)}function k(M,H,I,z,L,Z,ne){ne===!0?t.vertexAttribIPointer(M,H,I,L,Z):t.vertexAttribPointer(M,H,I,z,L,Z)}function C(M,H,I,z){w();const L=z.attributes,Z=I.getAttributes(),ne=H.defaultAttributeValues;for(const Y in Z){const ce=Z[Y];if(ce.location>=0){let ue=L[Y];if(ue===void 0&&(Y==="instanceMatrix"&&M.instanceMatrix&&(ue=M.instanceMatrix),Y==="instanceColor"&&M.instanceColor&&(ue=M.instanceColor)),ue!==void 0){const oe=ue.normalized,Q=ue.itemSize,le=e.get(ue);if(le===void 0)continue;const pe=le.buffer,he=le.type,we=le.bytesPerElement,$=he===t.INT||he===t.UNSIGNED_INT||ue.gpuType===FO;if(ue.isInterleavedBufferAttribute){const J=ue.data,j=J.stride,E=ue.offset;if(J.isInstancedInterleavedBuffer){for(let B=0;B<ce.locationSize;B++)x(ce.location+B,J.meshPerAttribute);M.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=J.meshPerAttribute*J.count)}else for(let B=0;B<ce.locationSize;B++)b(ce.location+B);t.bindBuffer(t.ARRAY_BUFFER,pe);for(let B=0;B<ce.locationSize;B++)k(ce.location+B,Q/ce.locationSize,he,oe,j*we,(E+Q/ce.locationSize*B)*we,$)}else{if(ue.isInstancedBufferAttribute){for(let J=0;J<ce.locationSize;J++)x(ce.location+J,ue.meshPerAttribute);M.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=ue.meshPerAttribute*ue.count)}else for(let J=0;J<ce.locationSize;J++)b(ce.location+J);t.bindBuffer(t.ARRAY_BUFFER,pe);for(let J=0;J<ce.locationSize;J++)k(ce.location+J,Q/ce.locationSize,he,oe,Q*we,Q/ce.locationSize*J*we,$)}}else if(ne!==void 0){const oe=ne[Y];if(oe!==void 0)switch(oe.length){case 2:t.vertexAttrib2fv(ce.location,oe);break;case 3:t.vertexAttrib3fv(ce.location,oe);break;case 4:t.vertexAttrib4fv(ce.location,oe);break;default:t.vertexAttrib1fv(ce.location,oe)}}}}S()}function P(){F();for(const M in a){const H=a[M];for(const I in H){const z=H[I];for(const L in z)u(z[L].object),delete z[L];delete H[I]}delete a[M]}}function T(M){if(a[M.id]===void 0)return;const H=a[M.id];for(const I in H){const z=H[I];for(const L in z)u(z[L].object),delete z[L];delete H[I]}delete a[M.id]}function A(M){for(const H in a){const I=a[H];if(I[M.id]===void 0)continue;const z=I[M.id];for(const L in z)u(z[L].object),delete z[L];delete I[M.id]}}function F(){_(),o=!0,s!==i&&(s=i,d(s.object))}function _(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:l,reset:F,resetDefaultState:_,dispose:P,releaseStatesOfGeometry:T,releaseStatesOfProgram:A,initAttributes:w,enableAttribute:b,disableUnusedAttributes:S}}function Dke(t,e,n){let a;function i(d){a=d}function s(d,u){t.drawArrays(a,d,u),n.update(u,a,1)}function o(d,u,m){m!==0&&(t.drawArraysInstanced(a,d,u,m),n.update(u,a,m))}function l(d,u,m){if(m===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(a,d,0,u,0,m);let f=0;for(let g=0;g<m;g++)f+=u[g];n.update(f,a,1)}function c(d,u,m,p){if(m===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<d.length;g++)o(d[g],u[g],p[g]);else{f.multiDrawArraysInstancedWEBGL(a,d,0,u,0,p,0,m);let g=0;for(let w=0;w<m;w++)g+=u[w]*p[w];n.update(g,a,1)}}this.setMode=i,this.render=s,this.renderInstances=o,this.renderMultiDraw=l,this.renderMultiDrawInstances=c}function Fke(t,e,n,a){let i;function s(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");i=t.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(A){return!(A!==ld&&a.convert(A)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function l(A){const F=A===Yy&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(A!==fu&&a.convert(A)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==_m&&!F)}function c(A){if(A==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="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&&($n("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),g=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),w=t.getParameter(t.MAX_TEXTURE_SIZE),b=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),x=t.getParameter(t.MAX_VERTEX_ATTRIBS),S=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),k=t.getParameter(t.MAX_VARYING_VECTORS),C=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),P=g>0,T=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:g,maxTextureSize:w,maxCubemapSize:b,maxAttributes:x,maxVertexUniforms:S,maxVaryings:k,maxFragmentUniforms:C,vertexTextures:P,maxSamples:T}}function Lke(t){const e=this;let n=null,a=0,i=!1,s=!1;const o=new rh,l=new lr,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||a!==0||i;return i=p,a=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 g=m.clippingPlanes,w=m.clipIntersection,b=m.clipShadows,x=t.get(m);if(!i||g===null||g.length===0||s&&!b)s?u(null):d();else{const S=s?0:a,k=S*4;let C=x.clippingState||null;c.value=C,C=u(g,p,k,f);for(let P=0;P!==k;++P)C[P]=n[P];x.clippingState=C,this.numIntersection=w?this.numPlanes:0,this.numPlanes+=S}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=a>0),e.numPlanes=a,e.numIntersection=0}function u(m,p,f,g){const w=m!==null?m.length:0;let b=null;if(w!==0){if(b=c.value,g!==!0||b===null){const x=f+w*4,S=p.matrixWorldInverse;l.getNormalMatrix(S),(b===null||b.length<x)&&(b=new Float32Array(x));for(let k=0,C=f;k!==w;++k,C+=4)o.copy(m[k]).applyMatrix4(S,l),o.normal.toArray(b,C),b[C+3]=o.constant}c.value=b,c.needsUpdate=!0}return e.numPlanes=w,e.numIntersection=0,b}}function Rke(t){let e=new WeakMap;function n(o,l){return l===mL?o.mapping=vy:l===pL&&(o.mapping=wy),o}function a(o){if(o&&o.isTexture){const l=o.mapping;if(l===mL||l===pL)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 Twe(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:a,dispose:s}}const xh=4,cq=[.125,.215,.35,.446,.526,.582],Jf=20,Ike=256,o0=new qJ,dq=new cr;let OE=null,zE=0,UE=0,BE=!1;const Oke=new Lt;let uq=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,a=.1,i=100,s={}){const{size:o=256,position:l=Oke}=s;OE=this._renderer.getRenderTarget(),zE=this._renderer.getActiveCubeFace(),UE=this._renderer.getActiveMipmapLevel(),BE=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,a,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=hq(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=pq(),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(OE,zE,UE),this._renderer.xr.enabled=BE,e.scissorTest=!1,cx(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===vy||e.mapping===wy?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),OE=this._renderer.getRenderTarget(),zE=this._renderer.getActiveCubeFace(),UE=this._renderer.getActiveMipmapLevel(),BE=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const a=n||this._allocateTargets();return this._textureToCubeUV(e,a),this._applyPMREM(a),this._cleanup(a),a}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,a={magFilter:mc,minFilter:mc,generateMipmaps:!1,type:Yy,format:ld,colorSpace:Sy,depthBuffer:!1},i=mq(e,n,a);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=mq(e,n,a);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=zke(s)),this._blurMaterial=Bke(s,e,n),this._ggxMaterial=Uke(s,e,n)}return i}_compileMaterial(e){const n=new _c(new Sc,e);this._renderer.compile(n,o0)}_sceneToCubeUV(e,n,a,i,s){const c=new ac(90,1,n,a),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(dq),m.toneMapping=Dh,m.autoClear=!1,m.state.buffers.depth.getReversed()&&(m.setRenderTarget(i),m.clearDepth(),m.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new _c(new $O,new qO({name:"PMREM.Background",side:Wo,depthWrite:!1,depthTest:!1})));const w=this._backgroundBox,b=w.material;let x=!1;const S=e.background;S?S.isColor&&(b.color.copy(S),e.background=null,x=!0):(b.color.copy(dq),x=!0);for(let k=0;k<6;k++){const C=k%3;C===0?(c.up.set(0,d[k],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+u[k],s.y,s.z)):C===1?(c.up.set(0,0,d[k]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+u[k],s.z)):(c.up.set(0,d[k],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+u[k]));const P=this._cubeSize;cx(i,C*P,k>2?P:0,P,P),m.setRenderTarget(i),x&&m.render(w,c),m.render(e,c)}m.toneMapping=f,m.autoClear=p,e.background=S}_textureToCubeUV(e,n){const a=this._renderer,i=e.mapping===vy||e.mapping===wy;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=hq()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=pq());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;cx(n,0,0,3*c,2*c),a.setRenderTarget(n),a.render(o,o0)}_applyPMREM(e){const n=this._renderer,a=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=a}_applyGGXFilter(e,n,a){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,l=this._lodMeshes[a];l.material=o;const c=o.uniforms,d=a/(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:g}=this,w=this._sizeLods[a],b=3*w*(a>g-xh?a-g+xh:0),x=4*(this._cubeSize-w);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-n,cx(s,b,x,3*w,2*w),i.setRenderTarget(s),i.render(l,o0),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=g-a,cx(e,b,x,3*w,2*w),i.setRenderTarget(e),i.render(l,o0)}_blur(e,n,a,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,a,i,"latitudinal",s),this._halfBlur(o,e,a,a,i,"longitudinal",s)}_halfBlur(e,n,a,i,s,o,l){const c=this._renderer,d=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&di("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[a]-1,g=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Jf-1),w=s/g,b=isFinite(s)?1+Math.floor(u*w):Jf;b>Jf&&$n(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Jf}`);const x=[];let S=0;for(let A=0;A<Jf;++A){const F=A/w,_=Math.exp(-F*F/2);x.push(_),A===0?S+=_:A<b&&(S+=2*_)}for(let A=0;A<x.length;A++)x[A]=x[A]/S;p.envMap.value=e.texture,p.samples.value=b,p.weights.value=x,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:k}=this;p.dTheta.value=g,p.mipInt.value=k-a;const C=this._sizeLods[i],P=3*C*(i>k-xh?i-k+xh:0),T=4*(this._cubeSize-C);cx(n,P,T,3*C,2*C),c.setRenderTarget(n),c.render(m,o0)}};function zke(t){const e=[],n=[],a=[];let i=t;const s=t-xh+1+cq.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);e.push(l);let c=1/l;o>t-xh?c=cq[o-t+xh-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,g=6,w=3,b=2,x=1,S=new Float32Array(w*g*f),k=new Float32Array(b*g*f),C=new Float32Array(x*g*f);for(let T=0;T<f;T++){const A=T%3*2/3-1,F=T>2?0:-1,_=[A,F,0,A+2/3,F,0,A+2/3,F+1,0,A,F,0,A+2/3,F+1,0,A,F+1,0];S.set(_,w*g*T),k.set(p,b*g*T);const M=[T,T,T,T,T,T];C.set(M,x*g*T)}const P=new Sc;P.setAttribute("position",new wo(S,w)),P.setAttribute("uv",new wo(k,b)),P.setAttribute("faceIndex",new wo(C,x)),a.push(new _c(P,null)),i>xh&&i--}return{lodMeshes:a,sizeLods:e,sigmas:n}}function mq(t,e,n){const a=new Ig(t,e,n);return a.texture.mapping=jT,a.texture.name="PMREM.cubeUv",a.scissorTest=!0,a}function cx(t,e,n,a,i){t.viewport.set(e,n,a,i),t.scissor.set(e,n,a,i)}function Uke(t,e,n){return new Km({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Ike,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:ET(),fragmentShader:`
  3602. precision highp float;
  3603. precision highp int;
  3604. varying vec3 vOutputDirection;
  3605. uniform sampler2D envMap;
  3606. uniform float roughness;
  3607. uniform float mipInt;
  3608. #define ENVMAP_TYPE_CUBE_UV
  3609. #include <cube_uv_reflection_fragment>
  3610. #define PI 3.14159265359
  3611. // Van der Corput radical inverse
  3612. float radicalInverse_VdC(uint bits) {
  3613. bits = (bits << 16u) | (bits >> 16u);
  3614. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  3615. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  3616. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  3617. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  3618. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  3619. }
  3620. // Hammersley sequence
  3621. vec2 hammersley(uint i, uint N) {
  3622. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  3623. }
  3624. // GGX VNDF importance sampling (Eric Heitz 2018)
  3625. // "Sampling the GGX Distribution of Visible Normals"
  3626. // https://jcgt.org/published/0007/04/01/
  3627. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  3628. float alpha = roughness * roughness;
  3629. // Section 3.2: Transform view direction to hemisphere configuration
  3630. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  3631. // Section 4.1: Orthonormal basis
  3632. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  3633. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  3634. vec3 T2 = cross(Vh, T1);
  3635. // Section 4.2: Parameterization of projected area
  3636. float r = sqrt(Xi.x);
  3637. float phi = 2.0 * PI * Xi.y;
  3638. float t1 = r * cos(phi);
  3639. float t2 = r * sin(phi);
  3640. float s = 0.5 * (1.0 + Vh.z);
  3641. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  3642. // Section 4.3: Reprojection onto hemisphere
  3643. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  3644. // Section 3.4: Transform back to ellipsoid configuration
  3645. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  3646. }
  3647. void main() {
  3648. vec3 N = normalize(vOutputDirection);
  3649. vec3 V = N; // Assume view direction equals normal for pre-filtering
  3650. vec3 prefilteredColor = vec3(0.0);
  3651. float totalWeight = 0.0;
  3652. // For very low roughness, just sample the environment directly
  3653. if (roughness < 0.001) {
  3654. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  3655. return;
  3656. }
  3657. // Tangent space basis for VNDF sampling
  3658. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  3659. vec3 tangent = normalize(cross(up, N));
  3660. vec3 bitangent = cross(N, tangent);
  3661. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  3662. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  3663. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  3664. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  3665. // Transform H back to world space
  3666. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  3667. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  3668. float NdotL = max(dot(N, L), 0.0);
  3669. if(NdotL > 0.0) {
  3670. // Sample environment at fixed mip level
  3671. // VNDF importance sampling handles the distribution filtering
  3672. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  3673. // Weight by NdotL for the split-sum approximation
  3674. // VNDF PDF naturally accounts for the visible microfacet distribution
  3675. prefilteredColor += sampleColor * NdotL;
  3676. totalWeight += NdotL;
  3677. }
  3678. }
  3679. if (totalWeight > 0.0) {
  3680. prefilteredColor = prefilteredColor / totalWeight;
  3681. }
  3682. gl_FragColor = vec4(prefilteredColor, 1.0);
  3683. }
  3684. `,blending:Fm,depthTest:!1,depthWrite:!1})}function Bke(t,e,n){const a=new Float32Array(Jf),i=new Lt(0,1,0);return new Km({name:"SphericalGaussianBlur",defines:{n:Jf,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:a},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:ET(),fragmentShader:`
  3685. precision mediump float;
  3686. precision mediump int;
  3687. varying vec3 vOutputDirection;
  3688. uniform sampler2D envMap;
  3689. uniform int samples;
  3690. uniform float weights[ n ];
  3691. uniform bool latitudinal;
  3692. uniform float dTheta;
  3693. uniform float mipInt;
  3694. uniform vec3 poleAxis;
  3695. #define ENVMAP_TYPE_CUBE_UV
  3696. #include <cube_uv_reflection_fragment>
  3697. vec3 getSample( float theta, vec3 axis ) {
  3698. float cosTheta = cos( theta );
  3699. // Rodrigues' axis-angle rotation
  3700. vec3 sampleDirection = vOutputDirection * cosTheta
  3701. + cross( axis, vOutputDirection ) * sin( theta )
  3702. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  3703. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  3704. }
  3705. void main() {
  3706. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  3707. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  3708. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  3709. }
  3710. axis = normalize( axis );
  3711. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  3712. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  3713. for ( int i = 1; i < n; i++ ) {
  3714. if ( i >= samples ) {
  3715. break;
  3716. }
  3717. float theta = dTheta * float( i );
  3718. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  3719. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  3720. }
  3721. }
  3722. `,blending:Fm,depthTest:!1,depthWrite:!1})}function pq(){return new Km({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ET(),fragmentShader:`
  3723. precision mediump float;
  3724. precision mediump int;
  3725. varying vec3 vOutputDirection;
  3726. uniform sampler2D envMap;
  3727. #include <common>
  3728. void main() {
  3729. vec3 outputDirection = normalize( vOutputDirection );
  3730. vec2 uv = equirectUv( outputDirection );
  3731. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  3732. }
  3733. `,blending:Fm,depthTest:!1,depthWrite:!1})}function hq(){return new Km({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ET(),fragmentShader:`
  3734. precision mediump float;
  3735. precision mediump int;
  3736. uniform float flipEnvMap;
  3737. varying vec3 vOutputDirection;
  3738. uniform samplerCube envMap;
  3739. void main() {
  3740. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  3741. }
  3742. `,blending:Fm,depthTest:!1,depthWrite:!1})}function ET(){return`
  3743. precision mediump float;
  3744. precision mediump int;
  3745. attribute float faceIndex;
  3746. varying vec3 vOutputDirection;
  3747. // RH coordinate system; PMREM face-indexing convention
  3748. vec3 getDirection( vec2 uv, float face ) {
  3749. uv = 2.0 * uv - 1.0;
  3750. vec3 direction = vec3( uv, 1.0 );
  3751. if ( face == 0.0 ) {
  3752. direction = direction.zyx; // ( 1, v, u ) pos x
  3753. } else if ( face == 1.0 ) {
  3754. direction = direction.xzy;
  3755. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  3756. } else if ( face == 2.0 ) {
  3757. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  3758. } else if ( face == 3.0 ) {
  3759. direction = direction.zyx;
  3760. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  3761. } else if ( face == 4.0 ) {
  3762. direction = direction.xzy;
  3763. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  3764. } else if ( face == 5.0 ) {
  3765. direction.z *= -1.0; // ( u, v, -1 ) neg z
  3766. }
  3767. return direction;
  3768. }
  3769. void main() {
  3770. vOutputDirection = getDirection( uv, faceIndex );
  3771. gl_Position = vec4( position, 1.0 );
  3772. }
  3773. `}function Hke(t){let e=new WeakMap,n=null;function a(l){if(l&&l.isTexture){const c=l.mapping,d=c===mL||c===pL,u=c===vy||c===wy;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 uq(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 uq(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:a,dispose:o}}function qke(t){const e={};function n(a){if(e[a]!==void 0)return e[a];const i=t.getExtension(a);return e[a]=i,i}return{has:function(a){return n(a)!==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(a){const i=n(a);return i===null&&Uw("WebGLRenderer: "+a+" extension not supported."),i}}}function $ke(t,e,n,a){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const g in p.attributes)e.remove(p.attributes[g]);p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),a.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,g=m.attributes.position;let w=0;if(f!==null){const S=f.array;w=f.version;for(let k=0,C=S.length;k<C;k+=3){const P=S[k+0],T=S[k+1],A=S[k+2];p.push(P,T,T,A,A,P)}}else if(g!==void 0){const S=g.array;w=g.version;for(let k=0,C=S.length/3-1;k<C;k+=3){const P=k+0,T=k+1,A=k+2;p.push(P,T,T,A,A,P)}}else return;const b=new(wJ(p)?MJ:jJ)(p,1);b.version=w;const x=s.get(m);x&&e.remove(x),s.set(m,b)}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 Vke(t,e,n){let a;function i(p){a=p}let s,o;function l(p){s=p.type,o=p.bytesPerElement}function c(p,f){t.drawElements(a,f,s,p*o),n.update(f,a,1)}function d(p,f,g){g!==0&&(t.drawElementsInstanced(a,f,s,p*o,g),n.update(f,a,g))}function u(p,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(a,f,0,s,p,0,g);let b=0;for(let x=0;x<g;x++)b+=f[x];n.update(b,a,1)}function m(p,f,g,w){if(g===0)return;const b=e.get("WEBGL_multi_draw");if(b===null)for(let x=0;x<p.length;x++)d(p[x]/o,f[x],w[x]);else{b.multiDrawElementsInstancedWEBGL(a,f,0,s,p,0,w,0,g);let x=0;for(let S=0;S<g;S++)x+=f[S]*w[S];n.update(x,a,1)}}this.setMode=i,this.setIndex=l,this.render=c,this.renderInstances=d,this.renderMultiDraw=u,this.renderMultiDrawInstances=m}function Gke(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function a(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:di("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:a}}function Wke(t,e,n){const a=new WeakMap,i=new wi;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=a.get(l);if(p===void 0||p.count!==m){let M=function(){F.dispose(),a.delete(l),l.removeEventListener("dispose",M)};var f=M;p!==void 0&&p.texture.dispose();const g=l.morphAttributes.position!==void 0,w=l.morphAttributes.normal!==void 0,b=l.morphAttributes.color!==void 0,x=l.morphAttributes.position||[],S=l.morphAttributes.normal||[],k=l.morphAttributes.color||[];let C=0;g===!0&&(C=1),w===!0&&(C=2),b===!0&&(C=3);let P=l.attributes.position.count*C,T=1;P>e.maxTextureSize&&(T=Math.ceil(P/e.maxTextureSize),P=e.maxTextureSize);const A=new Float32Array(P*T*4*m),F=new CJ(A,P,T,m);F.type=_m,F.needsUpdate=!0;const _=C*4;for(let H=0;H<m;H++){const I=x[H],z=S[H],L=k[H],Z=P*T*4*H;for(let ne=0;ne<I.count;ne++){const Y=ne*_;g===!0&&(i.fromBufferAttribute(I,ne),A[Z+Y+0]=i.x,A[Z+Y+1]=i.y,A[Z+Y+2]=i.z,A[Z+Y+3]=0),w===!0&&(i.fromBufferAttribute(z,ne),A[Z+Y+4]=i.x,A[Z+Y+5]=i.y,A[Z+Y+6]=i.z,A[Z+Y+7]=0),b===!0&&(i.fromBufferAttribute(L,ne),A[Z+Y+8]=i.x,A[Z+Y+9]=i.y,A[Z+Y+10]=i.z,A[Z+Y+11]=L.itemSize===4?i.w:1)}}p={count:m,texture:F,size:new ir(P,T)},a.set(l,p),l.addEventListener("dispose",M)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(t,"morphTexture",o.morphTexture,n);else{let g=0;for(let b=0;b<d.length;b++)g+=d[b];const w=l.morphTargetsRelative?1:1-g;c.getUniforms().setValue(t,"morphTargetBaseInfluence",w),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 Kke(t,e,n,a){let i=new WeakMap;function s(c){const d=a.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 VJ=new xd,fq=new OJ(1,1),GJ=new CJ,WJ=new uwe,KJ=new RJ,gq=[],bq=[],xq=new Float32Array(16),yq=new Float32Array(9),vq=new Float32Array(4);function Zy(t,e,n){const a=t[0];if(a<=0||a>0)return t;const i=e*n;let s=gq[i];if(s===void 0&&(s=new Float32Array(i),gq[i]=s),e!==0){a.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function zi(t,e){if(t.length!==e.length)return!1;for(let n=0,a=t.length;n<a;n++)if(t[n]!==e[n])return!1;return!0}function Ui(t,e){for(let n=0,a=e.length;n<a;n++)t[n]=e[n]}function DT(t,e){let n=bq[e];n===void 0&&(n=new Int32Array(e),bq[e]=n);for(let a=0;a!==e;++a)n[a]=t.allocateTextureUnit();return n}function Qke(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function Yke(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(zi(n,e))return;t.uniform2fv(this.addr,e),Ui(n,e)}}function Xke(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(zi(n,e))return;t.uniform3fv(this.addr,e),Ui(n,e)}}function Zke(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(zi(n,e))return;t.uniform4fv(this.addr,e),Ui(n,e)}}function Jke(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(zi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),Ui(n,e)}else{if(zi(n,a))return;vq.set(a),t.uniformMatrix2fv(this.addr,!1,vq),Ui(n,a)}}function e1e(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(zi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),Ui(n,e)}else{if(zi(n,a))return;yq.set(a),t.uniformMatrix3fv(this.addr,!1,yq),Ui(n,a)}}function t1e(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(zi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),Ui(n,e)}else{if(zi(n,a))return;xq.set(a),t.uniformMatrix4fv(this.addr,!1,xq),Ui(n,a)}}function n1e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function r1e(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(zi(n,e))return;t.uniform2iv(this.addr,e),Ui(n,e)}}function a1e(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(zi(n,e))return;t.uniform3iv(this.addr,e),Ui(n,e)}}function i1e(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(zi(n,e))return;t.uniform4iv(this.addr,e),Ui(n,e)}}function s1e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function o1e(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(zi(n,e))return;t.uniform2uiv(this.addr,e),Ui(n,e)}}function l1e(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(zi(n,e))return;t.uniform3uiv(this.addr,e),Ui(n,e)}}function c1e(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(zi(n,e))return;t.uniform4uiv(this.addr,e),Ui(n,e)}}function d1e(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i);let s;this.type===t.SAMPLER_2D_SHADOW?(fq.compareFunction=vJ,s=fq):s=VJ,n.setTexture2D(e||s,i)}function u1e(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTexture3D(e||WJ,i)}function m1e(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTextureCube(e||KJ,i)}function p1e(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTexture2DArray(e||GJ,i)}function h1e(t){switch(t){case 5126:return Qke;case 35664:return Yke;case 35665:return Xke;case 35666:return Zke;case 35674:return Jke;case 35675:return e1e;case 35676:return t1e;case 5124:case 35670:return n1e;case 35667:case 35671:return r1e;case 35668:case 35672:return a1e;case 35669:case 35673:return i1e;case 5125:return s1e;case 36294:return o1e;case 36295:return l1e;case 36296:return c1e;case 35678:case 36198:case 36298:case 36306:case 35682:return d1e;case 35679:case 36299:case 36307:return u1e;case 35680:case 36300:case 36308:case 36293:return m1e;case 36289:case 36303:case 36311:case 36292:return p1e}}function f1e(t,e){t.uniform1fv(this.addr,e)}function g1e(t,e){const n=Zy(e,this.size,2);t.uniform2fv(this.addr,n)}function b1e(t,e){const n=Zy(e,this.size,3);t.uniform3fv(this.addr,n)}function x1e(t,e){const n=Zy(e,this.size,4);t.uniform4fv(this.addr,n)}function y1e(t,e){const n=Zy(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function v1e(t,e){const n=Zy(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function w1e(t,e){const n=Zy(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function S1e(t,e){t.uniform1iv(this.addr,e)}function _1e(t,e){t.uniform2iv(this.addr,e)}function k1e(t,e){t.uniform3iv(this.addr,e)}function N1e(t,e){t.uniform4iv(this.addr,e)}function C1e(t,e){t.uniform1uiv(this.addr,e)}function P1e(t,e){t.uniform2uiv(this.addr,e)}function T1e(t,e){t.uniform3uiv(this.addr,e)}function A1e(t,e){t.uniform4uiv(this.addr,e)}function j1e(t,e,n){const a=this.cache,i=e.length,s=DT(n,i);zi(a,s)||(t.uniform1iv(this.addr,s),Ui(a,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||VJ,s[o])}function M1e(t,e,n){const a=this.cache,i=e.length,s=DT(n,i);zi(a,s)||(t.uniform1iv(this.addr,s),Ui(a,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||WJ,s[o])}function E1e(t,e,n){const a=this.cache,i=e.length,s=DT(n,i);zi(a,s)||(t.uniform1iv(this.addr,s),Ui(a,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||KJ,s[o])}function D1e(t,e,n){const a=this.cache,i=e.length,s=DT(n,i);zi(a,s)||(t.uniform1iv(this.addr,s),Ui(a,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||GJ,s[o])}function F1e(t){switch(t){case 5126:return f1e;case 35664:return g1e;case 35665:return b1e;case 35666:return x1e;case 35674:return y1e;case 35675:return v1e;case 35676:return w1e;case 5124:case 35670:return S1e;case 35667:case 35671:return _1e;case 35668:case 35672:return k1e;case 35669:case 35673:return N1e;case 5125:return C1e;case 36294:return P1e;case 36295:return T1e;case 36296:return A1e;case 35678:case 36198:case 36298:case 36306:case 35682:return j1e;case 35679:case 36299:case 36307:return M1e;case 35680:case 36300:case 36308:case 36293:return E1e;case 36289:case 36303:case 36311:case 36292:return D1e}}let L1e=class{constructor(e,n,a){this.id=e,this.addr=a,this.cache=[],this.type=n.type,this.setValue=h1e(n.type)}},R1e=class{constructor(e,n,a){this.id=e,this.addr=a,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=F1e(n.type)}},I1e=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,a){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],a)}}};const HE=/(\w+)(\])?(\[|\.)?/g;function wq(t,e){t.seq.push(e),t.map[e.id]=e}function O1e(t,e,n){const a=t.name,i=a.length;for(HE.lastIndex=0;;){const s=HE.exec(a),o=HE.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){wq(n,d===void 0?new L1e(l,t,e):new R1e(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new I1e(l),wq(n,m)),n=m}}}let PN=class{constructor(e,n){this.seq=[],this.map={};const a=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<a;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);O1e(s,o,this)}}setValue(e,n,a,i){const s=this.map[n];s!==void 0&&s.setValue(e,a,i)}setOptional(e,n,a){const i=n[a];i!==void 0&&this.setValue(e,a,i)}static upload(e,n,a,i){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=a[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,i)}}static seqWithValue(e,n){const a=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&a.push(o)}return a}};function Sq(t,e,n){const a=t.createShader(e);return t.shaderSource(a,n),t.compileShader(a),a}const z1e=37297;let U1e=0;function B1e(t,e){const n=t.split(`
  3774. `),a=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;a.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return a.join(`
  3775. `)}const _q=new lr;function H1e(t){Or._getMatrix(_q,Or.workingColorSpace,t);const e=`mat3( ${_q.elements.map(n=>n.toFixed(4))} )`;switch(Or.getTransfer(t)){case cC:return[e,"LinearTransferOETF"];case aa:return[e,"sRGBTransferOETF"];default:return $n("WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function kq(t,e,n){const a=t.getShaderParameter(e,t.COMPILE_STATUS),s=(t.getShaderInfoLog(e)||"").trim();if(a&&s==="")return"";const o=/ERROR: 0:(\d+)/.exec(s);if(o){const l=parseInt(o[1]);return n.toUpperCase()+`
  3776. `+s+`
  3777. `+B1e(t.getShaderSource(e),l)}else return s}function q1e(t,e){const n=H1e(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`
  3778. `)}function $1e(t,e){let n;switch(e){case O0e:n="Linear";break;case z0e:n="Reinhard";break;case U0e:n="Cineon";break;case B0e:n="ACESFilmic";break;case q0e:n="AgX";break;case $0e:n="Neutral";break;case H0e:n="Custom";break;default:$n("WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const Qk=new Lt;function V1e(){Or.getLuminanceCoefficients(Qk);const t=Qk.x.toFixed(4),e=Qk.y.toFixed(4),n=Qk.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(`
  3779. `)}function G1e(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(L0).join(`
  3780. `)}function W1e(t){const e=[];for(const n in t){const a=t[n];a!==!1&&e.push("#define "+n+" "+a)}return e.join(`
  3781. `)}function K1e(t,e){const n={},a=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<a;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 L0(t){return t!==""}function Nq(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 Cq(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const Q1e=/^[ \t]*#include +<([\w\d./]+)>/gm;function GL(t){return t.replace(Q1e,X1e)}const Y1e=new Map;function X1e(t,e){let n=rr[e];if(n===void 0){const a=Y1e.get(e);if(a!==void 0)n=rr[a],$n('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,a);else throw new Error("Can not resolve #include <"+e+">")}return GL(n)}const Z1e=/#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 Pq(t){return t.replace(Z1e,J1e)}function J1e(t,e,n,a){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=a.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function Tq(t){let e=`precision ${t.precision} float;
  3782. precision ${t.precision} int;
  3783. precision ${t.precision} sampler2D;
  3784. precision ${t.precision} samplerCube;
  3785. precision ${t.precision} sampler3D;
  3786. precision ${t.precision} sampler2DArray;
  3787. precision ${t.precision} sampler2DShadow;
  3788. precision ${t.precision} samplerCubeShadow;
  3789. precision ${t.precision} sampler2DArrayShadow;
  3790. precision ${t.precision} isampler2D;
  3791. precision ${t.precision} isampler3D;
  3792. precision ${t.precision} isamplerCube;
  3793. precision ${t.precision} isampler2DArray;
  3794. precision ${t.precision} usampler2D;
  3795. precision ${t.precision} usampler3D;
  3796. precision ${t.precision} usamplerCube;
  3797. precision ${t.precision} usampler2DArray;
  3798. `;return t.precision==="highp"?e+=`
  3799. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  3800. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  3801. #define LOW_PRECISION`),e}function eNe(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===dJ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===b0e?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===dm&&(e="SHADOWMAP_TYPE_VSM"),e}function tNe(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case vy:case wy:e="ENVMAP_TYPE_CUBE";break;case jT:e="ENVMAP_TYPE_CUBE_UV";break}return e}function nNe(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===wy&&(e="ENVMAP_MODE_REFRACTION"),e}function rNe(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case DO:e="ENVMAP_BLENDING_MULTIPLY";break;case R0e:e="ENVMAP_BLENDING_MIX";break;case I0e:e="ENVMAP_BLENDING_ADD";break}return e}function aNe(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,a=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:a,maxMip:n}}function iNe(t,e,n,a){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=eNe(n),d=tNe(n),u=nNe(n),m=rNe(n),p=aNe(n),f=G1e(n),g=W1e(s),w=i.createProgram();let b,x,S=n.glslVersion?"#version "+n.glslVersion+`
  3802. `:"";n.isRawShaderMaterial?(b=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(L0).join(`
  3803. `),b.length>0&&(b+=`
  3804. `),x=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(L0).join(`
  3805. `),x.length>0&&(x+=`
  3806. `)):(b=[Tq(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,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",`
  3807. `].filter(L0).join(`
  3808. `),x=[Tq(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,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!==Dh?"#define TONE_MAPPING":"",n.toneMapping!==Dh?rr.tonemapping_pars_fragment:"",n.toneMapping!==Dh?$1e("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",rr.colorspace_pars_fragment,q1e("linearToOutputTexel",n.outputColorSpace),V1e(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  3809. `].filter(L0).join(`
  3810. `)),o=GL(o),o=Nq(o,n),o=Cq(o,n),l=GL(l),l=Nq(l,n),l=Cq(l,n),o=Pq(o),l=Pq(l),n.isRawShaderMaterial!==!0&&(S=`#version 300 es
  3811. `,b=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
  3812. `)+`
  3813. `+b,x=["#define varying in",n.glslVersion===F6?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===F6?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
  3814. `)+`
  3815. `+x);const k=S+b+o,C=S+x+l,P=Sq(i,i.VERTEX_SHADER,k),T=Sq(i,i.FRAGMENT_SHADER,C);i.attachShader(w,P),i.attachShader(w,T),n.index0AttributeName!==void 0?i.bindAttribLocation(w,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(w,0,"position"),i.linkProgram(w);function A(H){if(t.debug.checkShaderErrors){const I=i.getProgramInfoLog(w)||"",z=i.getShaderInfoLog(P)||"",L=i.getShaderInfoLog(T)||"",Z=I.trim(),ne=z.trim(),Y=L.trim();let ce=!0,ue=!0;if(i.getProgramParameter(w,i.LINK_STATUS)===!1)if(ce=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,w,P,T);else{const oe=kq(i,P,"vertex"),Q=kq(i,T,"fragment");di("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(w,i.VALIDATE_STATUS)+`
  3816. Material Name: `+H.name+`
  3817. Material Type: `+H.type+`
  3818. Program Info Log: `+Z+`
  3819. `+oe+`
  3820. `+Q)}else Z!==""?$n("WebGLProgram: Program Info Log:",Z):(ne===""||Y==="")&&(ue=!1);ue&&(H.diagnostics={runnable:ce,programLog:Z,vertexShader:{log:ne,prefix:b},fragmentShader:{log:Y,prefix:x}})}i.deleteShader(P),i.deleteShader(T),F=new PN(i,w),_=K1e(i,w)}let F;this.getUniforms=function(){return F===void 0&&A(this),F};let _;this.getAttributes=function(){return _===void 0&&A(this),_};let M=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return M===!1&&(M=i.getProgramParameter(w,z1e)),M},this.destroy=function(){a.releaseStatesOfProgram(this),i.deleteProgram(w),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=U1e++,this.cacheKey=e,this.usedTimes=1,this.program=w,this.vertexShader=P,this.fragmentShader=T,this}let sNe=0,oNe=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,a=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(a),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 a of n)a.usedTimes--,a.usedTimes===0&&this.shaderCache.delete(a.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 a=n.get(e);return a===void 0&&(a=new Set,n.set(e,a)),a}_getShaderStage(e){const n=this.shaderCache;let a=n.get(e);return a===void 0&&(a=new lNe(e),n.set(e,a)),a}},lNe=class{constructor(e){this.id=sNe++,this.code=e,this.usedTimes=0}};function cNe(t,e,n,a,i,s,o){const l=new TJ,c=new oNe,d=new Set,u=[],m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.precision;const g={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 w(_){return d.add(_),_===0?"uv":`uv${_}`}function b(_,M,H,I,z){const L=I.fog,Z=z.geometry,ne=_.isMeshStandardMaterial?I.environment:null,Y=(_.isMeshStandardMaterial?n:e).get(_.envMap||ne),ce=Y&&Y.mapping===jT?Y.image.height:null,ue=g[_.type];_.precision!==null&&(f=i.getMaxPrecision(_.precision),f!==_.precision&&$n("WebGLProgram.getParameters:",_.precision,"not supported, using",f,"instead."));const oe=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,Q=oe!==void 0?oe.length:0;let le=0;Z.morphAttributes.position!==void 0&&(le=1),Z.morphAttributes.normal!==void 0&&(le=2),Z.morphAttributes.color!==void 0&&(le=3);let pe,he,we,$;if(ue){const Te=Wd[ue];pe=Te.vertexShader,he=Te.fragmentShader}else pe=_.vertexShader,he=_.fragmentShader,c.update(_),we=c.getVertexShaderID(_),$=c.getFragmentShaderID(_);const J=t.getRenderTarget(),j=t.state.buffers.depth.getReversed(),E=z.isInstancedMesh===!0,B=z.isBatchedMesh===!0,W=!!_.map,O=!!_.matcap,ie=!!Y,U=!!_.aoMap,G=!!_.lightMap,K=!!_.bumpMap,X=!!_.normalMap,se=!!_.displacementMap,te=!!_.emissiveMap,fe=!!_.metalnessMap,de=!!_.roughnessMap,me=_.anisotropy>0,q=_.clearcoat>0,R=_.dispersion>0,re=_.iridescence>0,be=_.sheen>0,ye=_.transmission>0,_e=me&&!!_.anisotropyMap,xe=q&&!!_.clearcoatMap,ge=q&&!!_.clearcoatNormalMap,Me=q&&!!_.clearcoatRoughnessMap,Be=re&&!!_.iridescenceMap,Fe=re&&!!_.iridescenceThicknessMap,Oe=be&&!!_.sheenColorMap,Re=be&&!!_.sheenRoughnessMap,We=!!_.specularMap,ze=!!_.specularColorMap,st=!!_.specularIntensityMap,Ee=ye&&!!_.transmissionMap,it=ye&&!!_.thicknessMap,Ce=!!_.gradientMap,Ze=!!_.alphaMap,Ie=_.alphaTest>0,ke=!!_.alphaHash,Ve=!!_.extensions;let rt=Dh;_.toneMapped&&(J===null||J.isXRRenderTarget===!0)&&(rt=t.toneMapping);const Qe={shaderID:ue,shaderType:_.type,shaderName:_.name,vertexShader:pe,fragmentShader:he,defines:_.defines,customVertexShaderID:we,customFragmentShaderID:$,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:f,batching:B,batchingColor:B&&z._colorsTexture!==null,instancing:E,instancingColor:E&&z.instanceColor!==null,instancingMorph:E&&z.morphTexture!==null,supportsVertexTextures:p,outputColorSpace:J===null?t.outputColorSpace:J.isXRRenderTarget===!0?J.texture.colorSpace:Sy,alphaToCoverage:!!_.alphaToCoverage,map:W,matcap:O,envMap:ie,envMapMode:ie&&Y.mapping,envMapCubeUVHeight:ce,aoMap:U,lightMap:G,bumpMap:K,normalMap:X,displacementMap:p&&se,emissiveMap:te,normalMapObjectSpace:X&&_.normalMapType===K0e,normalMapTangentSpace:X&&_.normalMapType===yJ,metalnessMap:fe,roughnessMap:de,anisotropy:me,anisotropyMap:_e,clearcoat:q,clearcoatMap:xe,clearcoatNormalMap:ge,clearcoatRoughnessMap:Me,dispersion:R,iridescence:re,iridescenceMap:Be,iridescenceThicknessMap:Fe,sheen:be,sheenColorMap:Oe,sheenRoughnessMap:Re,specularMap:We,specularColorMap:ze,specularIntensityMap:st,transmission:ye,transmissionMap:Ee,thicknessMap:it,gradientMap:Ce,opaque:_.transparent===!1&&_.blending===ay&&_.alphaToCoverage===!1,alphaMap:Ze,alphaTest:Ie,alphaHash:ke,combine:_.combine,mapUv:W&&w(_.map.channel),aoMapUv:U&&w(_.aoMap.channel),lightMapUv:G&&w(_.lightMap.channel),bumpMapUv:K&&w(_.bumpMap.channel),normalMapUv:X&&w(_.normalMap.channel),displacementMapUv:se&&w(_.displacementMap.channel),emissiveMapUv:te&&w(_.emissiveMap.channel),metalnessMapUv:fe&&w(_.metalnessMap.channel),roughnessMapUv:de&&w(_.roughnessMap.channel),anisotropyMapUv:_e&&w(_.anisotropyMap.channel),clearcoatMapUv:xe&&w(_.clearcoatMap.channel),clearcoatNormalMapUv:ge&&w(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Me&&w(_.clearcoatRoughnessMap.channel),iridescenceMapUv:Be&&w(_.iridescenceMap.channel),iridescenceThicknessMapUv:Fe&&w(_.iridescenceThicknessMap.channel),sheenColorMapUv:Oe&&w(_.sheenColorMap.channel),sheenRoughnessMapUv:Re&&w(_.sheenRoughnessMap.channel),specularMapUv:We&&w(_.specularMap.channel),specularColorMapUv:ze&&w(_.specularColorMap.channel),specularIntensityMapUv:st&&w(_.specularIntensityMap.channel),transmissionMapUv:Ee&&w(_.transmissionMap.channel),thicknessMapUv:it&&w(_.thicknessMap.channel),alphaMapUv:Ze&&w(_.alphaMap.channel),vertexTangents:!!Z.attributes.tangent&&(X||me),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!Z.attributes.color&&Z.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!Z.attributes.uv&&(W||Ze),fog:!!L,useFog:_.fog===!0,fogExp2:!!L&&L.isFogExp2,flatShading:_.flatShading===!0&&_.wireframe===!1,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:m,reversedDepthBuffer:j,skinning:z.isSkinnedMesh===!0,morphTargets:Z.morphAttributes.position!==void 0,morphNormals:Z.morphAttributes.normal!==void 0,morphColors:Z.morphAttributes.color!==void 0,morphTargetsCount:Q,morphTextureStride:le,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:t.shadowMap.enabled&&H.length>0,shadowMapType:t.shadowMap.type,toneMapping:rt,decodeVideoTexture:W&&_.map.isVideoTexture===!0&&Or.getTransfer(_.map.colorSpace)===aa,decodeVideoTextureEmissive:te&&_.emissiveMap.isVideoTexture===!0&&Or.getTransfer(_.emissiveMap.colorSpace)===aa,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===Qd,flipSided:_.side===Wo,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:Ve&&_.extensions.clipCullDistance===!0&&a.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ve&&_.extensions.multiDraw===!0||B)&&a.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:a.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return Qe.vertexUv1s=d.has(1),Qe.vertexUv2s=d.has(2),Qe.vertexUv3s=d.has(3),d.clear(),Qe}function x(_){const M=[];if(_.shaderID?M.push(_.shaderID):(M.push(_.customVertexShaderID),M.push(_.customFragmentShaderID)),_.defines!==void 0)for(const H in _.defines)M.push(H),M.push(_.defines[H]);return _.isRawShaderMaterial===!1&&(S(M,_),k(M,_),M.push(t.outputColorSpace)),M.push(_.customProgramCacheKey),M.join()}function S(_,M){_.push(M.precision),_.push(M.outputColorSpace),_.push(M.envMapMode),_.push(M.envMapCubeUVHeight),_.push(M.mapUv),_.push(M.alphaMapUv),_.push(M.lightMapUv),_.push(M.aoMapUv),_.push(M.bumpMapUv),_.push(M.normalMapUv),_.push(M.displacementMapUv),_.push(M.emissiveMapUv),_.push(M.metalnessMapUv),_.push(M.roughnessMapUv),_.push(M.anisotropyMapUv),_.push(M.clearcoatMapUv),_.push(M.clearcoatNormalMapUv),_.push(M.clearcoatRoughnessMapUv),_.push(M.iridescenceMapUv),_.push(M.iridescenceThicknessMapUv),_.push(M.sheenColorMapUv),_.push(M.sheenRoughnessMapUv),_.push(M.specularMapUv),_.push(M.specularColorMapUv),_.push(M.specularIntensityMapUv),_.push(M.transmissionMapUv),_.push(M.thicknessMapUv),_.push(M.combine),_.push(M.fogExp2),_.push(M.sizeAttenuation),_.push(M.morphTargetsCount),_.push(M.morphAttributeCount),_.push(M.numDirLights),_.push(M.numPointLights),_.push(M.numSpotLights),_.push(M.numSpotLightMaps),_.push(M.numHemiLights),_.push(M.numRectAreaLights),_.push(M.numDirLightShadows),_.push(M.numPointLightShadows),_.push(M.numSpotLightShadows),_.push(M.numSpotLightShadowsWithMaps),_.push(M.numLightProbes),_.push(M.shadowMapType),_.push(M.toneMapping),_.push(M.numClippingPlanes),_.push(M.numClipIntersection),_.push(M.depthPacking)}function k(_,M){l.disableAll(),M.supportsVertexTextures&&l.enable(0),M.instancing&&l.enable(1),M.instancingColor&&l.enable(2),M.instancingMorph&&l.enable(3),M.matcap&&l.enable(4),M.envMap&&l.enable(5),M.normalMapObjectSpace&&l.enable(6),M.normalMapTangentSpace&&l.enable(7),M.clearcoat&&l.enable(8),M.iridescence&&l.enable(9),M.alphaTest&&l.enable(10),M.vertexColors&&l.enable(11),M.vertexAlphas&&l.enable(12),M.vertexUv1s&&l.enable(13),M.vertexUv2s&&l.enable(14),M.vertexUv3s&&l.enable(15),M.vertexTangents&&l.enable(16),M.anisotropy&&l.enable(17),M.alphaHash&&l.enable(18),M.batching&&l.enable(19),M.dispersion&&l.enable(20),M.batchingColor&&l.enable(21),M.gradientMap&&l.enable(22),_.push(l.mask),l.disableAll(),M.fog&&l.enable(0),M.useFog&&l.enable(1),M.flatShading&&l.enable(2),M.logarithmicDepthBuffer&&l.enable(3),M.reversedDepthBuffer&&l.enable(4),M.skinning&&l.enable(5),M.morphTargets&&l.enable(6),M.morphNormals&&l.enable(7),M.morphColors&&l.enable(8),M.premultipliedAlpha&&l.enable(9),M.shadowMapEnabled&&l.enable(10),M.doubleSided&&l.enable(11),M.flipSided&&l.enable(12),M.useDepthPacking&&l.enable(13),M.dithering&&l.enable(14),M.transmission&&l.enable(15),M.sheen&&l.enable(16),M.opaque&&l.enable(17),M.pointsUvs&&l.enable(18),M.decodeVideoTexture&&l.enable(19),M.decodeVideoTextureEmissive&&l.enable(20),M.alphaToCoverage&&l.enable(21),_.push(l.mask)}function C(_){const M=g[_.type];let H;if(M){const I=Wd[M];H=kwe.clone(I.uniforms)}else H=_.uniforms;return H}function P(_,M){let H;for(let I=0,z=u.length;I<z;I++){const L=u[I];if(L.cacheKey===M){H=L,++H.usedTimes;break}}return H===void 0&&(H=new iNe(t,M,_,s),u.push(H)),H}function T(_){if(--_.usedTimes===0){const M=u.indexOf(_);u[M]=u[u.length-1],u.pop(),_.destroy()}}function A(_){c.remove(_)}function F(){c.dispose()}return{getParameters:b,getProgramCacheKey:x,getUniforms:C,acquireProgram:P,releaseProgram:T,releaseShaderCache:A,programs:u,dispose:F}}function dNe(){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 a(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:a,update:i,dispose:s}}function uNe(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 Aq(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 jq(){const t=[];let e=0;const n=[],a=[],i=[];function s(){e=0,n.length=0,a.length=0,i.length=0}function o(m,p,f,g,w,b){let x=t[e];return x===void 0?(x={id:m.id,object:m,geometry:p,material:f,groupOrder:g,renderOrder:m.renderOrder,z:w,group:b},t[e]=x):(x.id=m.id,x.object=m,x.geometry=p,x.material=f,x.groupOrder=g,x.renderOrder=m.renderOrder,x.z=w,x.group=b),e++,x}function l(m,p,f,g,w,b){const x=o(m,p,f,g,w,b);f.transmission>0?a.push(x):f.transparent===!0?i.push(x):n.push(x)}function c(m,p,f,g,w,b){const x=o(m,p,f,g,w,b);f.transmission>0?a.unshift(x):f.transparent===!0?i.unshift(x):n.unshift(x)}function d(m,p){n.length>1&&n.sort(m||uNe),a.length>1&&a.sort(p||Aq),i.length>1&&i.sort(p||Aq)}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:a,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function mNe(){let t=new WeakMap;function e(a,i){const s=t.get(a);let o;return s===void 0?(o=new jq,t.set(a,[o])):i>=s.length?(o=new jq,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function pNe(){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 Lt,color:new cr};break;case"SpotLight":n={position:new Lt,direction:new Lt,color:new cr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Lt,color:new cr,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Lt,skyColor:new cr,groundColor:new cr};break;case"RectAreaLight":n={color:new cr,position:new Lt,halfWidth:new Lt,halfHeight:new Lt};break}return t[e.id]=n,n}}}function hNe(){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 ir};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ir};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ir,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let fNe=0;function gNe(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function bNe(t){const e=new pNe,n=hNe(),a={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let d=0;d<9;d++)a.probe.push(new Lt);const i=new Lt,s=new Ci,o=new Ci;function l(d){let u=0,m=0,p=0;for(let _=0;_<9;_++)a.probe[_].set(0,0,0);let f=0,g=0,w=0,b=0,x=0,S=0,k=0,C=0,P=0,T=0,A=0;d.sort(gNe);for(let _=0,M=d.length;_<M;_++){const H=d[_],I=H.color,z=H.intensity,L=H.distance,Z=H.shadow&&H.shadow.map?H.shadow.map.texture:null;if(H.isAmbientLight)u+=I.r*z,m+=I.g*z,p+=I.b*z;else if(H.isLightProbe){for(let ne=0;ne<9;ne++)a.probe[ne].addScaledVector(H.sh.coefficients[ne],z);A++}else if(H.isDirectionalLight){const ne=e.get(H);if(ne.color.copy(H.color).multiplyScalar(H.intensity),H.castShadow){const Y=H.shadow,ce=n.get(H);ce.shadowIntensity=Y.intensity,ce.shadowBias=Y.bias,ce.shadowNormalBias=Y.normalBias,ce.shadowRadius=Y.radius,ce.shadowMapSize=Y.mapSize,a.directionalShadow[f]=ce,a.directionalShadowMap[f]=Z,a.directionalShadowMatrix[f]=H.shadow.matrix,S++}a.directional[f]=ne,f++}else if(H.isSpotLight){const ne=e.get(H);ne.position.setFromMatrixPosition(H.matrixWorld),ne.color.copy(I).multiplyScalar(z),ne.distance=L,ne.coneCos=Math.cos(H.angle),ne.penumbraCos=Math.cos(H.angle*(1-H.penumbra)),ne.decay=H.decay,a.spot[w]=ne;const Y=H.shadow;if(H.map&&(a.spotLightMap[P]=H.map,P++,Y.updateMatrices(H),H.castShadow&&T++),a.spotLightMatrix[w]=Y.matrix,H.castShadow){const ce=n.get(H);ce.shadowIntensity=Y.intensity,ce.shadowBias=Y.bias,ce.shadowNormalBias=Y.normalBias,ce.shadowRadius=Y.radius,ce.shadowMapSize=Y.mapSize,a.spotShadow[w]=ce,a.spotShadowMap[w]=Z,C++}w++}else if(H.isRectAreaLight){const ne=e.get(H);ne.color.copy(I).multiplyScalar(z),ne.halfWidth.set(H.width*.5,0,0),ne.halfHeight.set(0,H.height*.5,0),a.rectArea[b]=ne,b++}else if(H.isPointLight){const ne=e.get(H);if(ne.color.copy(H.color).multiplyScalar(H.intensity),ne.distance=H.distance,ne.decay=H.decay,H.castShadow){const Y=H.shadow,ce=n.get(H);ce.shadowIntensity=Y.intensity,ce.shadowBias=Y.bias,ce.shadowNormalBias=Y.normalBias,ce.shadowRadius=Y.radius,ce.shadowMapSize=Y.mapSize,ce.shadowCameraNear=Y.camera.near,ce.shadowCameraFar=Y.camera.far,a.pointShadow[g]=ce,a.pointShadowMap[g]=Z,a.pointShadowMatrix[g]=H.shadow.matrix,k++}a.point[g]=ne,g++}else if(H.isHemisphereLight){const ne=e.get(H);ne.skyColor.copy(H.color).multiplyScalar(z),ne.groundColor.copy(H.groundColor).multiplyScalar(z),a.hemi[x]=ne,x++}}b>0&&(t.has("OES_texture_float_linear")===!0?(a.rectAreaLTC1=un.LTC_FLOAT_1,a.rectAreaLTC2=un.LTC_FLOAT_2):(a.rectAreaLTC1=un.LTC_HALF_1,a.rectAreaLTC2=un.LTC_HALF_2)),a.ambient[0]=u,a.ambient[1]=m,a.ambient[2]=p;const F=a.hash;(F.directionalLength!==f||F.pointLength!==g||F.spotLength!==w||F.rectAreaLength!==b||F.hemiLength!==x||F.numDirectionalShadows!==S||F.numPointShadows!==k||F.numSpotShadows!==C||F.numSpotMaps!==P||F.numLightProbes!==A)&&(a.directional.length=f,a.spot.length=w,a.rectArea.length=b,a.point.length=g,a.hemi.length=x,a.directionalShadow.length=S,a.directionalShadowMap.length=S,a.pointShadow.length=k,a.pointShadowMap.length=k,a.spotShadow.length=C,a.spotShadowMap.length=C,a.directionalShadowMatrix.length=S,a.pointShadowMatrix.length=k,a.spotLightMatrix.length=C+P-T,a.spotLightMap.length=P,a.numSpotLightShadowsWithMaps=T,a.numLightProbes=A,F.directionalLength=f,F.pointLength=g,F.spotLength=w,F.rectAreaLength=b,F.hemiLength=x,F.numDirectionalShadows=S,F.numPointShadows=k,F.numSpotShadows=C,F.numSpotMaps=P,F.numLightProbes=A,a.version=fNe++)}function c(d,u){let m=0,p=0,f=0,g=0,w=0;const b=u.matrixWorldInverse;for(let x=0,S=d.length;x<S;x++){const k=d[x];if(k.isDirectionalLight){const C=a.directional[m];C.direction.setFromMatrixPosition(k.matrixWorld),i.setFromMatrixPosition(k.target.matrixWorld),C.direction.sub(i),C.direction.transformDirection(b),m++}else if(k.isSpotLight){const C=a.spot[f];C.position.setFromMatrixPosition(k.matrixWorld),C.position.applyMatrix4(b),C.direction.setFromMatrixPosition(k.matrixWorld),i.setFromMatrixPosition(k.target.matrixWorld),C.direction.sub(i),C.direction.transformDirection(b),f++}else if(k.isRectAreaLight){const C=a.rectArea[g];C.position.setFromMatrixPosition(k.matrixWorld),C.position.applyMatrix4(b),o.identity(),s.copy(k.matrixWorld),s.premultiply(b),o.extractRotation(s),C.halfWidth.set(k.width*.5,0,0),C.halfHeight.set(0,k.height*.5,0),C.halfWidth.applyMatrix4(o),C.halfHeight.applyMatrix4(o),g++}else if(k.isPointLight){const C=a.point[p];C.position.setFromMatrixPosition(k.matrixWorld),C.position.applyMatrix4(b),p++}else if(k.isHemisphereLight){const C=a.hemi[w];C.direction.setFromMatrixPosition(k.matrixWorld),C.direction.transformDirection(b),w++}}}return{setup:l,setupView:c,state:a}}function Mq(t){const e=new bNe(t),n=[],a=[];function i(u){d.camera=u,n.length=0,a.length=0}function s(u){n.push(u)}function o(u){a.push(u)}function l(){e.setup(n)}function c(u){e.setupView(n,u)}const d={lightsArray:n,shadowsArray:a,camera:null,lights:e,transmissionRenderTarget:{}};return{init:i,state:d,setupLights:l,setupLightsView:c,pushLight:s,pushShadow:o}}function xNe(t){let e=new WeakMap;function n(i,s=0){const o=e.get(i);let l;return o===void 0?(l=new Mq(t),e.set(i,[l])):s>=o.length?(l=new Mq(t),o.push(l)):l=o[s],l}function a(){e=new WeakMap}return{get:n,dispose:a}}const yNe=`void main() {
  3821. gl_Position = vec4( position, 1.0 );
  3822. }`,vNe=`uniform sampler2D shadow_pass;
  3823. uniform vec2 resolution;
  3824. uniform float radius;
  3825. #include <packing>
  3826. void main() {
  3827. const float samples = float( VSM_SAMPLES );
  3828. float mean = 0.0;
  3829. float squared_mean = 0.0;
  3830. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  3831. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  3832. for ( float i = 0.0; i < samples; i ++ ) {
  3833. float uvOffset = uvStart + i * uvStride;
  3834. #ifdef HORIZONTAL_PASS
  3835. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  3836. mean += distribution.x;
  3837. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  3838. #else
  3839. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  3840. mean += depth;
  3841. squared_mean += depth * depth;
  3842. #endif
  3843. }
  3844. mean = mean / samples;
  3845. squared_mean = squared_mean / samples;
  3846. float std_dev = sqrt( squared_mean - mean * mean );
  3847. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  3848. }`;function wNe(t,e,n){let a=new VO;const i=new ir,s=new ir,o=new wi,l=new Iwe({depthPacking:W0e}),c=new Owe,d={},u=n.maxTextureSize,m={[Wh]:Wo,[Wo]:Wh,[Qd]:Qd},p=new Km({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ir},radius:{value:4}},vertexShader:yNe,fragmentShader:vNe}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const g=new Sc;g.setAttribute("position",new wo(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const w=new _c(g,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=dJ;let x=this.type;this.render=function(T,A,F){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||T.length===0)return;const _=t.getRenderTarget(),M=t.getActiveCubeFace(),H=t.getActiveMipmapLevel(),I=t.state;I.setBlending(Fm),I.buffers.depth.getReversed()===!0?I.buffers.color.setClear(0,0,0,0):I.buffers.color.setClear(1,1,1,1),I.buffers.depth.setTest(!0),I.setScissorTest(!1);const z=x!==dm&&this.type===dm,L=x===dm&&this.type!==dm;for(let Z=0,ne=T.length;Z<ne;Z++){const Y=T[Z],ce=Y.shadow;if(ce===void 0){$n("WebGLShadowMap:",Y,"has no shadow.");continue}if(ce.autoUpdate===!1&&ce.needsUpdate===!1)continue;i.copy(ce.mapSize);const ue=ce.getFrameExtents();if(i.multiply(ue),s.copy(ce.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/ue.x),i.x=s.x*ue.x,ce.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/ue.y),i.y=s.y*ue.y,ce.mapSize.y=s.y)),ce.map===null||z===!0||L===!0){const Q=this.type!==dm?{minFilter:wl,magFilter:wl}:{};ce.map!==null&&ce.map.dispose(),ce.map=new Ig(i.x,i.y,Q),ce.map.texture.name=Y.name+".shadowMap",ce.camera.updateProjectionMatrix()}t.setRenderTarget(ce.map),t.clear();const oe=ce.getViewportCount();for(let Q=0;Q<oe;Q++){const le=ce.getViewport(Q);o.set(s.x*le.x,s.y*le.y,s.x*le.z,s.y*le.w),I.viewport(o),ce.updateMatrices(Y,Q),a=ce.getFrustum(),C(A,F,ce.camera,Y,this.type)}ce.isPointLightShadow!==!0&&this.type===dm&&S(ce,F),ce.needsUpdate=!1}x=this.type,b.needsUpdate=!1,t.setRenderTarget(_,M,H)};function S(T,A){const F=e.update(w);p.defines.VSM_SAMPLES!==T.blurSamples&&(p.defines.VSM_SAMPLES=T.blurSamples,f.defines.VSM_SAMPLES=T.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),T.mapPass===null&&(T.mapPass=new Ig(i.x,i.y)),p.uniforms.shadow_pass.value=T.map.texture,p.uniforms.resolution.value=T.mapSize,p.uniforms.radius.value=T.radius,t.setRenderTarget(T.mapPass),t.clear(),t.renderBufferDirect(A,null,F,p,w,null),f.uniforms.shadow_pass.value=T.mapPass.texture,f.uniforms.resolution.value=T.mapSize,f.uniforms.radius.value=T.radius,t.setRenderTarget(T.map),t.clear(),t.renderBufferDirect(A,null,F,f,w,null)}function k(T,A,F,_){let M=null;const H=F.isPointLight===!0?T.customDistanceMaterial:T.customDepthMaterial;if(H!==void 0)M=H;else if(M=F.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||A.alphaToCoverage===!0){const I=M.uuid,z=A.uuid;let L=d[I];L===void 0&&(L={},d[I]=L);let Z=L[z];Z===void 0&&(Z=M.clone(),L[z]=Z,A.addEventListener("dispose",P)),M=Z}if(M.visible=A.visible,M.wireframe=A.wireframe,_===dm?M.side=A.shadowSide!==null?A.shadowSide:A.side:M.side=A.shadowSide!==null?A.shadowSide:m[A.side],M.alphaMap=A.alphaMap,M.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,M.map=A.map,M.clipShadows=A.clipShadows,M.clippingPlanes=A.clippingPlanes,M.clipIntersection=A.clipIntersection,M.displacementMap=A.displacementMap,M.displacementScale=A.displacementScale,M.displacementBias=A.displacementBias,M.wireframeLinewidth=A.wireframeLinewidth,M.linewidth=A.linewidth,F.isPointLight===!0&&M.isMeshDistanceMaterial===!0){const I=t.properties.get(M);I.light=F}return M}function C(T,A,F,_,M){if(T.visible===!1)return;if(T.layers.test(A.layers)&&(T.isMesh||T.isLine||T.isPoints)&&(T.castShadow||T.receiveShadow&&M===dm)&&(!T.frustumCulled||a.intersectsObject(T))){T.modelViewMatrix.multiplyMatrices(F.matrixWorldInverse,T.matrixWorld);const z=e.update(T),L=T.material;if(Array.isArray(L)){const Z=z.groups;for(let ne=0,Y=Z.length;ne<Y;ne++){const ce=Z[ne],ue=L[ce.materialIndex];if(ue&&ue.visible){const oe=k(T,ue,_,M);T.onBeforeShadow(t,T,A,F,z,oe,ce),t.renderBufferDirect(F,null,z,oe,T,ce),T.onAfterShadow(t,T,A,F,z,oe,ce)}}}else if(L.visible){const Z=k(T,L,_,M);T.onBeforeShadow(t,T,A,F,z,Z,null),t.renderBufferDirect(F,null,z,Z,T,null),T.onAfterShadow(t,T,A,F,z,Z,null)}}const I=T.children;for(let z=0,L=I.length;z<L;z++)C(I[z],A,F,_,M)}function P(T){T.target.removeEventListener("dispose",P);for(const F in d){const _=d[F],M=T.target.uuid;M in _&&(_[M].dispose(),delete _[M])}}}const SNe={[iL]:sL,[oL]:dL,[lL]:uL,[yy]:cL,[sL]:iL,[dL]:oL,[uL]:lL,[cL]:yy};function _Ne(t,e){function n(){let Ee=!1;const it=new wi;let Ce=null;const Ze=new wi(0,0,0,0);return{setMask:function(Ie){Ce!==Ie&&!Ee&&(t.colorMask(Ie,Ie,Ie,Ie),Ce=Ie)},setLocked:function(Ie){Ee=Ie},setClear:function(Ie,ke,Ve,rt,Qe){Qe===!0&&(Ie*=rt,ke*=rt,Ve*=rt),it.set(Ie,ke,Ve,rt),Ze.equals(it)===!1&&(t.clearColor(Ie,ke,Ve,rt),Ze.copy(it))},reset:function(){Ee=!1,Ce=null,Ze.set(-1,0,0,0)}}}function a(){let Ee=!1,it=!1,Ce=null,Ze=null,Ie=null;return{setReversed:function(ke){if(it!==ke){const Ve=e.get("EXT_clip_control");ke?Ve.clipControlEXT(Ve.LOWER_LEFT_EXT,Ve.ZERO_TO_ONE_EXT):Ve.clipControlEXT(Ve.LOWER_LEFT_EXT,Ve.NEGATIVE_ONE_TO_ONE_EXT),it=ke;const rt=Ie;Ie=null,this.setClear(rt)}},getReversed:function(){return it},setTest:function(ke){ke?J(t.DEPTH_TEST):j(t.DEPTH_TEST)},setMask:function(ke){Ce!==ke&&!Ee&&(t.depthMask(ke),Ce=ke)},setFunc:function(ke){if(it&&(ke=SNe[ke]),Ze!==ke){switch(ke){case iL:t.depthFunc(t.NEVER);break;case sL:t.depthFunc(t.ALWAYS);break;case oL:t.depthFunc(t.LESS);break;case yy:t.depthFunc(t.LEQUAL);break;case lL:t.depthFunc(t.EQUAL);break;case cL:t.depthFunc(t.GEQUAL);break;case dL:t.depthFunc(t.GREATER);break;case uL:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Ze=ke}},setLocked:function(ke){Ee=ke},setClear:function(ke){Ie!==ke&&(it&&(ke=1-ke),t.clearDepth(ke),Ie=ke)},reset:function(){Ee=!1,Ce=null,Ze=null,Ie=null,it=!1}}}function i(){let Ee=!1,it=null,Ce=null,Ze=null,Ie=null,ke=null,Ve=null,rt=null,Qe=null;return{setTest:function(Te){Ee||(Te?J(t.STENCIL_TEST):j(t.STENCIL_TEST))},setMask:function(Te){it!==Te&&!Ee&&(t.stencilMask(Te),it=Te)},setFunc:function(Te,tt,ot){(Ce!==Te||Ze!==tt||Ie!==ot)&&(t.stencilFunc(Te,tt,ot),Ce=Te,Ze=tt,Ie=ot)},setOp:function(Te,tt,ot){(ke!==Te||Ve!==tt||rt!==ot)&&(t.stencilOp(Te,tt,ot),ke=Te,Ve=tt,rt=ot)},setLocked:function(Te){Ee=Te},setClear:function(Te){Qe!==Te&&(t.clearStencil(Te),Qe=Te)},reset:function(){Ee=!1,it=null,Ce=null,Ze=null,Ie=null,ke=null,Ve=null,rt=null,Qe=null}}}const s=new n,o=new a,l=new i,c=new WeakMap,d=new WeakMap;let u={},m={},p=new WeakMap,f=[],g=null,w=!1,b=null,x=null,S=null,k=null,C=null,P=null,T=null,A=new cr(0,0,0),F=0,_=!1,M=null,H=null,I=null,z=null,L=null;const Z=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let ne=!1,Y=0;const ce=t.getParameter(t.VERSION);ce.indexOf("WebGL")!==-1?(Y=parseFloat(/^WebGL (\d)/.exec(ce)[1]),ne=Y>=1):ce.indexOf("OpenGL ES")!==-1&&(Y=parseFloat(/^OpenGL ES (\d)/.exec(ce)[1]),ne=Y>=2);let ue=null,oe={};const Q=t.getParameter(t.SCISSOR_BOX),le=t.getParameter(t.VIEWPORT),pe=new wi().fromArray(Q),he=new wi().fromArray(le);function we(Ee,it,Ce,Ze){const Ie=new Uint8Array(4),ke=t.createTexture();t.bindTexture(Ee,ke),t.texParameteri(Ee,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Ee,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Ve=0;Ve<Ce;Ve++)Ee===t.TEXTURE_3D||Ee===t.TEXTURE_2D_ARRAY?t.texImage3D(it,0,t.RGBA,1,1,Ze,0,t.RGBA,t.UNSIGNED_BYTE,Ie):t.texImage2D(it+Ve,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Ie);return ke}const $={};$[t.TEXTURE_2D]=we(t.TEXTURE_2D,t.TEXTURE_2D,1),$[t.TEXTURE_CUBE_MAP]=we(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),$[t.TEXTURE_2D_ARRAY]=we(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),$[t.TEXTURE_3D]=we(t.TEXTURE_3D,t.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),l.setClear(0),J(t.DEPTH_TEST),o.setFunc(yy),K(!1),X(T6),J(t.CULL_FACE),U(Fm);function J(Ee){u[Ee]!==!0&&(t.enable(Ee),u[Ee]=!0)}function j(Ee){u[Ee]!==!1&&(t.disable(Ee),u[Ee]=!1)}function E(Ee,it){return m[Ee]!==it?(t.bindFramebuffer(Ee,it),m[Ee]=it,Ee===t.DRAW_FRAMEBUFFER&&(m[t.FRAMEBUFFER]=it),Ee===t.FRAMEBUFFER&&(m[t.DRAW_FRAMEBUFFER]=it),!0):!1}function B(Ee,it){let Ce=f,Ze=!1;if(Ee){Ce=p.get(it),Ce===void 0&&(Ce=[],p.set(it,Ce));const Ie=Ee.textures;if(Ce.length!==Ie.length||Ce[0]!==t.COLOR_ATTACHMENT0){for(let ke=0,Ve=Ie.length;ke<Ve;ke++)Ce[ke]=t.COLOR_ATTACHMENT0+ke;Ce.length=Ie.length,Ze=!0}}else Ce[0]!==t.BACK&&(Ce[0]=t.BACK,Ze=!0);Ze&&t.drawBuffers(Ce)}function W(Ee){return g!==Ee?(t.useProgram(Ee),g=Ee,!0):!1}const O={[Zf]:t.FUNC_ADD,[y0e]:t.FUNC_SUBTRACT,[v0e]:t.FUNC_REVERSE_SUBTRACT};O[w0e]=t.MIN,O[S0e]=t.MAX;const ie={[_0e]:t.ZERO,[k0e]:t.ONE,[N0e]:t.SRC_COLOR,[rL]:t.SRC_ALPHA,[M0e]:t.SRC_ALPHA_SATURATE,[A0e]:t.DST_COLOR,[P0e]:t.DST_ALPHA,[C0e]:t.ONE_MINUS_SRC_COLOR,[aL]:t.ONE_MINUS_SRC_ALPHA,[j0e]:t.ONE_MINUS_DST_COLOR,[T0e]:t.ONE_MINUS_DST_ALPHA,[E0e]:t.CONSTANT_COLOR,[D0e]:t.ONE_MINUS_CONSTANT_COLOR,[F0e]:t.CONSTANT_ALPHA,[L0e]:t.ONE_MINUS_CONSTANT_ALPHA};function U(Ee,it,Ce,Ze,Ie,ke,Ve,rt,Qe,Te){if(Ee===Fm){w===!0&&(j(t.BLEND),w=!1);return}if(w===!1&&(J(t.BLEND),w=!0),Ee!==x0e){if(Ee!==b||Te!==_){if((x!==Zf||C!==Zf)&&(t.blendEquation(t.FUNC_ADD),x=Zf,C=Zf),Te)switch(Ee){case ay:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case A6:t.blendFunc(t.ONE,t.ONE);break;case j6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case M6:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:di("WebGLState: Invalid blending: ",Ee);break}else switch(Ee){case ay:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case A6:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case j6:di("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case M6:di("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:di("WebGLState: Invalid blending: ",Ee);break}S=null,k=null,P=null,T=null,A.set(0,0,0),F=0,b=Ee,_=Te}return}Ie=Ie||it,ke=ke||Ce,Ve=Ve||Ze,(it!==x||Ie!==C)&&(t.blendEquationSeparate(O[it],O[Ie]),x=it,C=Ie),(Ce!==S||Ze!==k||ke!==P||Ve!==T)&&(t.blendFuncSeparate(ie[Ce],ie[Ze],ie[ke],ie[Ve]),S=Ce,k=Ze,P=ke,T=Ve),(rt.equals(A)===!1||Qe!==F)&&(t.blendColor(rt.r,rt.g,rt.b,Qe),A.copy(rt),F=Qe),b=Ee,_=!1}function G(Ee,it){Ee.side===Qd?j(t.CULL_FACE):J(t.CULL_FACE);let Ce=Ee.side===Wo;it&&(Ce=!Ce),K(Ce),Ee.blending===ay&&Ee.transparent===!1?U(Fm):U(Ee.blending,Ee.blendEquation,Ee.blendSrc,Ee.blendDst,Ee.blendEquationAlpha,Ee.blendSrcAlpha,Ee.blendDstAlpha,Ee.blendColor,Ee.blendAlpha,Ee.premultipliedAlpha),o.setFunc(Ee.depthFunc),o.setTest(Ee.depthTest),o.setMask(Ee.depthWrite),s.setMask(Ee.colorWrite);const Ze=Ee.stencilWrite;l.setTest(Ze),Ze&&(l.setMask(Ee.stencilWriteMask),l.setFunc(Ee.stencilFunc,Ee.stencilRef,Ee.stencilFuncMask),l.setOp(Ee.stencilFail,Ee.stencilZFail,Ee.stencilZPass)),te(Ee.polygonOffset,Ee.polygonOffsetFactor,Ee.polygonOffsetUnits),Ee.alphaToCoverage===!0?J(t.SAMPLE_ALPHA_TO_COVERAGE):j(t.SAMPLE_ALPHA_TO_COVERAGE)}function K(Ee){M!==Ee&&(Ee?t.frontFace(t.CW):t.frontFace(t.CCW),M=Ee)}function X(Ee){Ee!==f0e?(J(t.CULL_FACE),Ee!==H&&(Ee===T6?t.cullFace(t.BACK):Ee===g0e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):j(t.CULL_FACE),H=Ee}function se(Ee){Ee!==I&&(ne&&t.lineWidth(Ee),I=Ee)}function te(Ee,it,Ce){Ee?(J(t.POLYGON_OFFSET_FILL),(z!==it||L!==Ce)&&(t.polygonOffset(it,Ce),z=it,L=Ce)):j(t.POLYGON_OFFSET_FILL)}function fe(Ee){Ee?J(t.SCISSOR_TEST):j(t.SCISSOR_TEST)}function de(Ee){Ee===void 0&&(Ee=t.TEXTURE0+Z-1),ue!==Ee&&(t.activeTexture(Ee),ue=Ee)}function me(Ee,it,Ce){Ce===void 0&&(ue===null?Ce=t.TEXTURE0+Z-1:Ce=ue);let Ze=oe[Ce];Ze===void 0&&(Ze={type:void 0,texture:void 0},oe[Ce]=Ze),(Ze.type!==Ee||Ze.texture!==it)&&(ue!==Ce&&(t.activeTexture(Ce),ue=Ce),t.bindTexture(Ee,it||$[Ee]),Ze.type=Ee,Ze.texture=it)}function q(){const Ee=oe[ue];Ee!==void 0&&Ee.type!==void 0&&(t.bindTexture(Ee.type,null),Ee.type=void 0,Ee.texture=void 0)}function R(){try{t.compressedTexImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function re(){try{t.compressedTexImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function be(){try{t.texSubImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function ye(){try{t.texSubImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function _e(){try{t.compressedTexSubImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function xe(){try{t.compressedTexSubImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function ge(){try{t.texStorage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Me(){try{t.texStorage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Be(){try{t.texImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Fe(){try{t.texImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Oe(Ee){pe.equals(Ee)===!1&&(t.scissor(Ee.x,Ee.y,Ee.z,Ee.w),pe.copy(Ee))}function Re(Ee){he.equals(Ee)===!1&&(t.viewport(Ee.x,Ee.y,Ee.z,Ee.w),he.copy(Ee))}function We(Ee,it){let Ce=d.get(it);Ce===void 0&&(Ce=new WeakMap,d.set(it,Ce));let Ze=Ce.get(Ee);Ze===void 0&&(Ze=t.getUniformBlockIndex(it,Ee.name),Ce.set(Ee,Ze))}function ze(Ee,it){const Ze=d.get(it).get(Ee);c.get(it)!==Ze&&(t.uniformBlockBinding(it,Ze,Ee.__bindingPointIndex),c.set(it,Ze))}function st(){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={},ue=null,oe={},m={},p=new WeakMap,f=[],g=null,w=!1,b=null,x=null,S=null,k=null,C=null,P=null,T=null,A=new cr(0,0,0),F=0,_=!1,M=null,H=null,I=null,z=null,L=null,pe.set(0,0,t.canvas.width,t.canvas.height),he.set(0,0,t.canvas.width,t.canvas.height),s.reset(),o.reset(),l.reset()}return{buffers:{color:s,depth:o,stencil:l},enable:J,disable:j,bindFramebuffer:E,drawBuffers:B,useProgram:W,setBlending:U,setMaterial:G,setFlipSided:K,setCullFace:X,setLineWidth:se,setPolygonOffset:te,setScissorTest:fe,activeTexture:de,bindTexture:me,unbindTexture:q,compressedTexImage2D:R,compressedTexImage3D:re,texImage2D:Be,texImage3D:Fe,updateUBOMapping:We,uniformBlockBinding:ze,texStorage2D:ge,texStorage3D:Me,texSubImage2D:be,texSubImage3D:ye,compressedTexSubImage2D:_e,compressedTexSubImage3D:xe,scissor:Oe,viewport:Re,reset:st}}function kNe(t,e,n,a,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 ir,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 g(q,R){return f?new OffscreenCanvas(q,R):uC("canvas")}function w(q,R,re){let be=1;const ye=me(q);if((ye.width>re||ye.height>re)&&(be=re/Math.max(ye.width,ye.height)),be<1)if(typeof HTMLImageElement<"u"&&q instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&q instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&q instanceof ImageBitmap||typeof VideoFrame<"u"&&q instanceof VideoFrame){const _e=Math.floor(be*ye.width),xe=Math.floor(be*ye.height);m===void 0&&(m=g(_e,xe));const ge=R?g(_e,xe):m;return ge.width=_e,ge.height=xe,ge.getContext("2d").drawImage(q,0,0,_e,xe),$n("WebGLRenderer: Texture has been resized from ("+ye.width+"x"+ye.height+") to ("+_e+"x"+xe+")."),ge}else return"data"in q&&$n("WebGLRenderer: Image in DataTexture is too big ("+ye.width+"x"+ye.height+")."),q;return q}function b(q){return q.generateMipmaps}function x(q){t.generateMipmap(q)}function S(q){return q.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:q.isWebGL3DRenderTarget?t.TEXTURE_3D:q.isWebGLArrayRenderTarget||q.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function k(q,R,re,be,ye=!1){if(q!==null){if(t[q]!==void 0)return t[q];$n("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+q+"'")}let _e=R;if(R===t.RED&&(re===t.FLOAT&&(_e=t.R32F),re===t.HALF_FLOAT&&(_e=t.R16F),re===t.UNSIGNED_BYTE&&(_e=t.R8)),R===t.RED_INTEGER&&(re===t.UNSIGNED_BYTE&&(_e=t.R8UI),re===t.UNSIGNED_SHORT&&(_e=t.R16UI),re===t.UNSIGNED_INT&&(_e=t.R32UI),re===t.BYTE&&(_e=t.R8I),re===t.SHORT&&(_e=t.R16I),re===t.INT&&(_e=t.R32I)),R===t.RG&&(re===t.FLOAT&&(_e=t.RG32F),re===t.HALF_FLOAT&&(_e=t.RG16F),re===t.UNSIGNED_BYTE&&(_e=t.RG8)),R===t.RG_INTEGER&&(re===t.UNSIGNED_BYTE&&(_e=t.RG8UI),re===t.UNSIGNED_SHORT&&(_e=t.RG16UI),re===t.UNSIGNED_INT&&(_e=t.RG32UI),re===t.BYTE&&(_e=t.RG8I),re===t.SHORT&&(_e=t.RG16I),re===t.INT&&(_e=t.RG32I)),R===t.RGB_INTEGER&&(re===t.UNSIGNED_BYTE&&(_e=t.RGB8UI),re===t.UNSIGNED_SHORT&&(_e=t.RGB16UI),re===t.UNSIGNED_INT&&(_e=t.RGB32UI),re===t.BYTE&&(_e=t.RGB8I),re===t.SHORT&&(_e=t.RGB16I),re===t.INT&&(_e=t.RGB32I)),R===t.RGBA_INTEGER&&(re===t.UNSIGNED_BYTE&&(_e=t.RGBA8UI),re===t.UNSIGNED_SHORT&&(_e=t.RGBA16UI),re===t.UNSIGNED_INT&&(_e=t.RGBA32UI),re===t.BYTE&&(_e=t.RGBA8I),re===t.SHORT&&(_e=t.RGBA16I),re===t.INT&&(_e=t.RGBA32I)),R===t.RGB&&(re===t.UNSIGNED_INT_5_9_9_9_REV&&(_e=t.RGB9_E5),re===t.UNSIGNED_INT_10F_11F_11F_REV&&(_e=t.R11F_G11F_B10F)),R===t.RGBA){const xe=ye?cC:Or.getTransfer(be);re===t.FLOAT&&(_e=t.RGBA32F),re===t.HALF_FLOAT&&(_e=t.RGBA16F),re===t.UNSIGNED_BYTE&&(_e=xe===aa?t.SRGB8_ALPHA8:t.RGBA8),re===t.UNSIGNED_SHORT_4_4_4_4&&(_e=t.RGBA4),re===t.UNSIGNED_SHORT_5_5_5_1&&(_e=t.RGB5_A1)}return(_e===t.R16F||_e===t.R32F||_e===t.RG16F||_e===t.RG32F||_e===t.RGBA16F||_e===t.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function C(q,R){let re;return q?R===null||R===Lg||R===Iw?re=t.DEPTH24_STENCIL8:R===_m?re=t.DEPTH32F_STENCIL8:R===Rw&&(re=t.DEPTH24_STENCIL8,$n("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===Lg||R===Iw?re=t.DEPTH_COMPONENT24:R===_m?re=t.DEPTH_COMPONENT32F:R===Rw&&(re=t.DEPTH_COMPONENT16),re}function P(q,R){return b(q)===!0||q.isFramebufferTexture&&q.minFilter!==wl&&q.minFilter!==mc?Math.log2(Math.max(R.width,R.height))+1:q.mipmaps!==void 0&&q.mipmaps.length>0?q.mipmaps.length:q.isCompressedTexture&&Array.isArray(q.image)?R.mipmaps.length:1}function T(q){const R=q.target;R.removeEventListener("dispose",T),F(R),R.isVideoTexture&&u.delete(R)}function A(q){const R=q.target;R.removeEventListener("dispose",A),M(R)}function F(q){const R=a.get(q);if(R.__webglInit===void 0)return;const re=q.source,be=p.get(re);if(be){const ye=be[R.__cacheKey];ye.usedTimes--,ye.usedTimes===0&&_(q),Object.keys(be).length===0&&p.delete(re)}a.remove(q)}function _(q){const R=a.get(q);t.deleteTexture(R.__webglTexture);const re=q.source,be=p.get(re);delete be[R.__cacheKey],o.memory.textures--}function M(q){const R=a.get(q);if(q.depthTexture&&(q.depthTexture.dispose(),a.remove(q.depthTexture)),q.isWebGLCubeRenderTarget)for(let be=0;be<6;be++){if(Array.isArray(R.__webglFramebuffer[be]))for(let ye=0;ye<R.__webglFramebuffer[be].length;ye++)t.deleteFramebuffer(R.__webglFramebuffer[be][ye]);else t.deleteFramebuffer(R.__webglFramebuffer[be]);R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer[be])}else{if(Array.isArray(R.__webglFramebuffer))for(let be=0;be<R.__webglFramebuffer.length;be++)t.deleteFramebuffer(R.__webglFramebuffer[be]);else t.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&t.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let be=0;be<R.__webglColorRenderbuffer.length;be++)R.__webglColorRenderbuffer[be]&&t.deleteRenderbuffer(R.__webglColorRenderbuffer[be]);R.__webglDepthRenderbuffer&&t.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const re=q.textures;for(let be=0,ye=re.length;be<ye;be++){const _e=a.get(re[be]);_e.__webglTexture&&(t.deleteTexture(_e.__webglTexture),o.memory.textures--),a.remove(re[be])}a.remove(q)}let H=0;function I(){H=0}function z(){const q=H;return q>=i.maxTextures&&$n("WebGLTextures: Trying to use "+q+" texture units while this GPU supports only "+i.maxTextures),H+=1,q}function L(q){const R=[];return R.push(q.wrapS),R.push(q.wrapT),R.push(q.wrapR||0),R.push(q.magFilter),R.push(q.minFilter),R.push(q.anisotropy),R.push(q.internalFormat),R.push(q.format),R.push(q.type),R.push(q.generateMipmaps),R.push(q.premultiplyAlpha),R.push(q.flipY),R.push(q.unpackAlignment),R.push(q.colorSpace),R.join()}function Z(q,R){const re=a.get(q);if(q.isVideoTexture&&fe(q),q.isRenderTargetTexture===!1&&q.isExternalTexture!==!0&&q.version>0&&re.__version!==q.version){const be=q.image;if(be===null)$n("WebGLRenderer: Texture marked for update but no image data found.");else if(be.complete===!1)$n("WebGLRenderer: Texture marked for update but image is incomplete");else{$(re,q,R);return}}else q.isExternalTexture&&(re.__webglTexture=q.sourceTexture?q.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,re.__webglTexture,t.TEXTURE0+R)}function ne(q,R){const re=a.get(q);if(q.isRenderTargetTexture===!1&&q.version>0&&re.__version!==q.version){$(re,q,R);return}else q.isExternalTexture&&(re.__webglTexture=q.sourceTexture?q.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,re.__webglTexture,t.TEXTURE0+R)}function Y(q,R){const re=a.get(q);if(q.isRenderTargetTexture===!1&&q.version>0&&re.__version!==q.version){$(re,q,R);return}n.bindTexture(t.TEXTURE_3D,re.__webglTexture,t.TEXTURE0+R)}function ce(q,R){const re=a.get(q);if(q.version>0&&re.__version!==q.version){J(re,q,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,re.__webglTexture,t.TEXTURE0+R)}const ue={[hL]:t.REPEAT,[Sm]:t.CLAMP_TO_EDGE,[fL]:t.MIRRORED_REPEAT},oe={[wl]:t.NEAREST,[V0e]:t.NEAREST_MIPMAP_NEAREST,[Tk]:t.NEAREST_MIPMAP_LINEAR,[mc]:t.LINEAR,[mE]:t.LINEAR_MIPMAP_NEAREST,[ig]:t.LINEAR_MIPMAP_LINEAR},Q={[Q0e]:t.NEVER,[twe]:t.ALWAYS,[Y0e]:t.LESS,[vJ]:t.LEQUAL,[X0e]:t.EQUAL,[ewe]:t.GEQUAL,[Z0e]:t.GREATER,[J0e]:t.NOTEQUAL};function le(q,R){if(R.type===_m&&e.has("OES_texture_float_linear")===!1&&(R.magFilter===mc||R.magFilter===mE||R.magFilter===Tk||R.magFilter===ig||R.minFilter===mc||R.minFilter===mE||R.minFilter===Tk||R.minFilter===ig)&&$n("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(q,t.TEXTURE_WRAP_S,ue[R.wrapS]),t.texParameteri(q,t.TEXTURE_WRAP_T,ue[R.wrapT]),(q===t.TEXTURE_3D||q===t.TEXTURE_2D_ARRAY)&&t.texParameteri(q,t.TEXTURE_WRAP_R,ue[R.wrapR]),t.texParameteri(q,t.TEXTURE_MAG_FILTER,oe[R.magFilter]),t.texParameteri(q,t.TEXTURE_MIN_FILTER,oe[R.minFilter]),R.compareFunction&&(t.texParameteri(q,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(q,t.TEXTURE_COMPARE_FUNC,Q[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===wl||R.minFilter!==Tk&&R.minFilter!==ig||R.type===_m&&e.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||a.get(R).__currentAnisotropy){const re=e.get("EXT_texture_filter_anisotropic");t.texParameterf(q,re.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),a.get(R).__currentAnisotropy=R.anisotropy}}}function pe(q,R){let re=!1;q.__webglInit===void 0&&(q.__webglInit=!0,R.addEventListener("dispose",T));const be=R.source;let ye=p.get(be);ye===void 0&&(ye={},p.set(be,ye));const _e=L(R);if(_e!==q.__cacheKey){ye[_e]===void 0&&(ye[_e]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,re=!0),ye[_e].usedTimes++;const xe=ye[q.__cacheKey];xe!==void 0&&(ye[q.__cacheKey].usedTimes--,xe.usedTimes===0&&_(R)),q.__cacheKey=_e,q.__webglTexture=ye[_e].texture}return re}function he(q,R,re){return Math.floor(Math.floor(q/re)/R)}function we(q,R,re,be){const _e=q.updateRanges;if(_e.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,R.width,R.height,re,be,R.data);else{_e.sort((Fe,Oe)=>Fe.start-Oe.start);let xe=0;for(let Fe=1;Fe<_e.length;Fe++){const Oe=_e[xe],Re=_e[Fe],We=Oe.start+Oe.count,ze=he(Re.start,R.width,4),st=he(Oe.start,R.width,4);Re.start<=We+1&&ze===st&&he(Re.start+Re.count-1,R.width,4)===ze?Oe.count=Math.max(Oe.count,Re.start+Re.count-Oe.start):(++xe,_e[xe]=Re)}_e.length=xe+1;const ge=t.getParameter(t.UNPACK_ROW_LENGTH),Me=t.getParameter(t.UNPACK_SKIP_PIXELS),Be=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,R.width);for(let Fe=0,Oe=_e.length;Fe<Oe;Fe++){const Re=_e[Fe],We=Math.floor(Re.start/4),ze=Math.ceil(Re.count/4),st=We%R.width,Ee=Math.floor(We/R.width),it=ze,Ce=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,st),t.pixelStorei(t.UNPACK_SKIP_ROWS,Ee),n.texSubImage2D(t.TEXTURE_2D,0,st,Ee,it,Ce,re,be,R.data)}q.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,ge),t.pixelStorei(t.UNPACK_SKIP_PIXELS,Me),t.pixelStorei(t.UNPACK_SKIP_ROWS,Be)}}function $(q,R,re){let be=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(be=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(be=t.TEXTURE_3D);const ye=pe(q,R),_e=R.source;n.bindTexture(be,q.__webglTexture,t.TEXTURE0+re);const xe=a.get(_e);if(_e.version!==xe.__version||ye===!0){n.activeTexture(t.TEXTURE0+re);const ge=Or.getPrimaries(Or.workingColorSpace),Me=R.colorSpace===uh?null:Or.getPrimaries(R.colorSpace),Be=R.colorSpace===uh||ge===Me?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,Be);let Fe=w(R.image,!1,i.maxTextureSize);Fe=de(R,Fe);const Oe=s.convert(R.format,R.colorSpace),Re=s.convert(R.type);let We=k(R.internalFormat,Oe,Re,R.colorSpace,R.isVideoTexture);le(be,R);let ze;const st=R.mipmaps,Ee=R.isVideoTexture!==!0,it=xe.__version===void 0||ye===!0,Ce=_e.dataReady,Ze=P(R,Fe);if(R.isDepthTexture)We=C(R.format===zw,R.type),it&&(Ee?n.texStorage2D(t.TEXTURE_2D,1,We,Fe.width,Fe.height):n.texImage2D(t.TEXTURE_2D,0,We,Fe.width,Fe.height,0,Oe,Re,null));else if(R.isDataTexture)if(st.length>0){Ee&&it&&n.texStorage2D(t.TEXTURE_2D,Ze,We,st[0].width,st[0].height);for(let Ie=0,ke=st.length;Ie<ke;Ie++)ze=st[Ie],Ee?Ce&&n.texSubImage2D(t.TEXTURE_2D,Ie,0,0,ze.width,ze.height,Oe,Re,ze.data):n.texImage2D(t.TEXTURE_2D,Ie,We,ze.width,ze.height,0,Oe,Re,ze.data);R.generateMipmaps=!1}else Ee?(it&&n.texStorage2D(t.TEXTURE_2D,Ze,We,Fe.width,Fe.height),Ce&&we(R,Fe,Oe,Re)):n.texImage2D(t.TEXTURE_2D,0,We,Fe.width,Fe.height,0,Oe,Re,Fe.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){Ee&&it&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ze,We,st[0].width,st[0].height,Fe.depth);for(let Ie=0,ke=st.length;Ie<ke;Ie++)if(ze=st[Ie],R.format!==ld)if(Oe!==null)if(Ee){if(Ce)if(R.layerUpdates.size>0){const Ve=lq(ze.width,ze.height,R.format,R.type);for(const rt of R.layerUpdates){const Qe=ze.data.subarray(rt*Ve/ze.data.BYTES_PER_ELEMENT,(rt+1)*Ve/ze.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ie,0,0,rt,ze.width,ze.height,1,Oe,Qe)}R.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ie,0,0,0,ze.width,ze.height,Fe.depth,Oe,ze.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Ie,We,ze.width,ze.height,Fe.depth,0,ze.data,0,0);else $n("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Ee?Ce&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,Ie,0,0,0,ze.width,ze.height,Fe.depth,Oe,Re,ze.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Ie,We,ze.width,ze.height,Fe.depth,0,Oe,Re,ze.data)}else{Ee&&it&&n.texStorage2D(t.TEXTURE_2D,Ze,We,st[0].width,st[0].height);for(let Ie=0,ke=st.length;Ie<ke;Ie++)ze=st[Ie],R.format!==ld?Oe!==null?Ee?Ce&&n.compressedTexSubImage2D(t.TEXTURE_2D,Ie,0,0,ze.width,ze.height,Oe,ze.data):n.compressedTexImage2D(t.TEXTURE_2D,Ie,We,ze.width,ze.height,0,ze.data):$n("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ee?Ce&&n.texSubImage2D(t.TEXTURE_2D,Ie,0,0,ze.width,ze.height,Oe,Re,ze.data):n.texImage2D(t.TEXTURE_2D,Ie,We,ze.width,ze.height,0,Oe,Re,ze.data)}else if(R.isDataArrayTexture)if(Ee){if(it&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ze,We,Fe.width,Fe.height,Fe.depth),Ce)if(R.layerUpdates.size>0){const Ie=lq(Fe.width,Fe.height,R.format,R.type);for(const ke of R.layerUpdates){const Ve=Fe.data.subarray(ke*Ie/Fe.data.BYTES_PER_ELEMENT,(ke+1)*Ie/Fe.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,ke,Fe.width,Fe.height,1,Oe,Re,Ve)}R.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Fe.width,Fe.height,Fe.depth,Oe,Re,Fe.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,We,Fe.width,Fe.height,Fe.depth,0,Oe,Re,Fe.data);else if(R.isData3DTexture)Ee?(it&&n.texStorage3D(t.TEXTURE_3D,Ze,We,Fe.width,Fe.height,Fe.depth),Ce&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Fe.width,Fe.height,Fe.depth,Oe,Re,Fe.data)):n.texImage3D(t.TEXTURE_3D,0,We,Fe.width,Fe.height,Fe.depth,0,Oe,Re,Fe.data);else if(R.isFramebufferTexture){if(it)if(Ee)n.texStorage2D(t.TEXTURE_2D,Ze,We,Fe.width,Fe.height);else{let Ie=Fe.width,ke=Fe.height;for(let Ve=0;Ve<Ze;Ve++)n.texImage2D(t.TEXTURE_2D,Ve,We,Ie,ke,0,Oe,Re,null),Ie>>=1,ke>>=1}}else if(st.length>0){if(Ee&&it){const Ie=me(st[0]);n.texStorage2D(t.TEXTURE_2D,Ze,We,Ie.width,Ie.height)}for(let Ie=0,ke=st.length;Ie<ke;Ie++)ze=st[Ie],Ee?Ce&&n.texSubImage2D(t.TEXTURE_2D,Ie,0,0,Oe,Re,ze):n.texImage2D(t.TEXTURE_2D,Ie,We,Oe,Re,ze);R.generateMipmaps=!1}else if(Ee){if(it){const Ie=me(Fe);n.texStorage2D(t.TEXTURE_2D,Ze,We,Ie.width,Ie.height)}Ce&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,Oe,Re,Fe)}else n.texImage2D(t.TEXTURE_2D,0,We,Oe,Re,Fe);b(R)&&x(be),xe.__version=_e.version,R.onUpdate&&R.onUpdate(R)}q.__version=R.version}function J(q,R,re){if(R.image.length!==6)return;const be=pe(q,R),ye=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,q.__webglTexture,t.TEXTURE0+re);const _e=a.get(ye);if(ye.version!==_e.__version||be===!0){n.activeTexture(t.TEXTURE0+re);const xe=Or.getPrimaries(Or.workingColorSpace),ge=R.colorSpace===uh?null:Or.getPrimaries(R.colorSpace),Me=R.colorSpace===uh||xe===ge?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,Me);const Be=R.isCompressedTexture||R.image[0].isCompressedTexture,Fe=R.image[0]&&R.image[0].isDataTexture,Oe=[];for(let ke=0;ke<6;ke++)!Be&&!Fe?Oe[ke]=w(R.image[ke],!0,i.maxCubemapSize):Oe[ke]=Fe?R.image[ke].image:R.image[ke],Oe[ke]=de(R,Oe[ke]);const Re=Oe[0],We=s.convert(R.format,R.colorSpace),ze=s.convert(R.type),st=k(R.internalFormat,We,ze,R.colorSpace),Ee=R.isVideoTexture!==!0,it=_e.__version===void 0||be===!0,Ce=ye.dataReady;let Ze=P(R,Re);le(t.TEXTURE_CUBE_MAP,R);let Ie;if(Be){Ee&&it&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Ze,st,Re.width,Re.height);for(let ke=0;ke<6;ke++){Ie=Oe[ke].mipmaps;for(let Ve=0;Ve<Ie.length;Ve++){const rt=Ie[Ve];R.format!==ld?We!==null?Ee?Ce&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,0,0,rt.width,rt.height,We,rt.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,st,rt.width,rt.height,0,rt.data):$n("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Ee?Ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,0,0,rt.width,rt.height,We,ze,rt.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,st,rt.width,rt.height,0,We,ze,rt.data)}}}else{if(Ie=R.mipmaps,Ee&&it){Ie.length>0&&Ze++;const ke=me(Oe[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,Ze,st,ke.width,ke.height)}for(let ke=0;ke<6;ke++)if(Fe){Ee?Ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,Oe[ke].width,Oe[ke].height,We,ze,Oe[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,st,Oe[ke].width,Oe[ke].height,0,We,ze,Oe[ke].data);for(let Ve=0;Ve<Ie.length;Ve++){const Qe=Ie[Ve].image[ke].image;Ee?Ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,0,0,Qe.width,Qe.height,We,ze,Qe.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,st,Qe.width,Qe.height,0,We,ze,Qe.data)}}else{Ee?Ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,We,ze,Oe[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,st,We,ze,Oe[ke]);for(let Ve=0;Ve<Ie.length;Ve++){const rt=Ie[Ve];Ee?Ce&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,0,0,We,ze,rt.image[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,st,We,ze,rt.image[ke])}}}b(R)&&x(t.TEXTURE_CUBE_MAP),_e.__version=ye.version,R.onUpdate&&R.onUpdate(R)}q.__version=R.version}function j(q,R,re,be,ye,_e){const xe=s.convert(re.format,re.colorSpace),ge=s.convert(re.type),Me=k(re.internalFormat,xe,ge,re.colorSpace),Be=a.get(R),Fe=a.get(re);if(Fe.__renderTarget=R,!Be.__hasExternalTextures){const Oe=Math.max(1,R.width>>_e),Re=Math.max(1,R.height>>_e);ye===t.TEXTURE_3D||ye===t.TEXTURE_2D_ARRAY?n.texImage3D(ye,_e,Me,Oe,Re,R.depth,0,xe,ge,null):n.texImage2D(ye,_e,Me,Oe,Re,0,xe,ge,null)}n.bindFramebuffer(t.FRAMEBUFFER,q),te(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,be,ye,Fe.__webglTexture,0,se(R)):(ye===t.TEXTURE_2D||ye>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&ye<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,be,ye,Fe.__webglTexture,_e),n.bindFramebuffer(t.FRAMEBUFFER,null)}function E(q,R,re){if(t.bindRenderbuffer(t.RENDERBUFFER,q),R.depthBuffer){const be=R.depthTexture,ye=be&&be.isDepthTexture?be.type:null,_e=C(R.stencilBuffer,ye),xe=R.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ge=se(R);te(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,ge,_e,R.width,R.height):re?t.renderbufferStorageMultisample(t.RENDERBUFFER,ge,_e,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,_e,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,xe,t.RENDERBUFFER,q)}else{const be=R.textures;for(let ye=0;ye<be.length;ye++){const _e=be[ye],xe=s.convert(_e.format,_e.colorSpace),ge=s.convert(_e.type),Me=k(_e.internalFormat,xe,ge,_e.colorSpace),Be=se(R);re&&te(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Be,Me,R.width,R.height):te(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Be,Me,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Me,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function B(q,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,q),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const be=a.get(R.depthTexture);be.__renderTarget=R,(!be.__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),Z(R.depthTexture,0);const ye=be.__webglTexture,_e=se(R);if(R.depthTexture.format===Ow)te(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,ye,0,_e):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,ye,0);else if(R.depthTexture.format===zw)te(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,ye,0,_e):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,ye,0);else throw new Error("Unknown depthTexture format")}function W(q){const R=a.get(q),re=q.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==q.depthTexture){const be=q.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),be){const ye=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,be.removeEventListener("dispose",ye)};be.addEventListener("dispose",ye),R.__depthDisposeCallback=ye}R.__boundDepthTexture=be}if(q.depthTexture&&!R.__autoAllocateDepthBuffer){if(re)throw new Error("target.depthTexture not supported in Cube render targets");const be=q.texture.mipmaps;be&&be.length>0?B(R.__webglFramebuffer[0],q):B(R.__webglFramebuffer,q)}else if(re){R.__webglDepthbuffer=[];for(let be=0;be<6;be++)if(n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[be]),R.__webglDepthbuffer[be]===void 0)R.__webglDepthbuffer[be]=t.createRenderbuffer(),E(R.__webglDepthbuffer[be],q,!1);else{const ye=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,_e=R.__webglDepthbuffer[be];t.bindRenderbuffer(t.RENDERBUFFER,_e),t.framebufferRenderbuffer(t.FRAMEBUFFER,ye,t.RENDERBUFFER,_e)}}else{const be=q.texture.mipmaps;if(be&&be.length>0?n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=t.createRenderbuffer(),E(R.__webglDepthbuffer,q,!1);else{const ye=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,_e=R.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,_e),t.framebufferRenderbuffer(t.FRAMEBUFFER,ye,t.RENDERBUFFER,_e)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function O(q,R,re){const be=a.get(q);R!==void 0&&j(be.__webglFramebuffer,q,q.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),re!==void 0&&W(q)}function ie(q){const R=q.texture,re=a.get(q),be=a.get(R);q.addEventListener("dispose",A);const ye=q.textures,_e=q.isWebGLCubeRenderTarget===!0,xe=ye.length>1;if(xe||(be.__webglTexture===void 0&&(be.__webglTexture=t.createTexture()),be.__version=R.version,o.memory.textures++),_e){re.__webglFramebuffer=[];for(let ge=0;ge<6;ge++)if(R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer[ge]=[];for(let Me=0;Me<R.mipmaps.length;Me++)re.__webglFramebuffer[ge][Me]=t.createFramebuffer()}else re.__webglFramebuffer[ge]=t.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer=[];for(let ge=0;ge<R.mipmaps.length;ge++)re.__webglFramebuffer[ge]=t.createFramebuffer()}else re.__webglFramebuffer=t.createFramebuffer();if(xe)for(let ge=0,Me=ye.length;ge<Me;ge++){const Be=a.get(ye[ge]);Be.__webglTexture===void 0&&(Be.__webglTexture=t.createTexture(),o.memory.textures++)}if(q.samples>0&&te(q)===!1){re.__webglMultisampledFramebuffer=t.createFramebuffer(),re.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,re.__webglMultisampledFramebuffer);for(let ge=0;ge<ye.length;ge++){const Me=ye[ge];re.__webglColorRenderbuffer[ge]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,re.__webglColorRenderbuffer[ge]);const Be=s.convert(Me.format,Me.colorSpace),Fe=s.convert(Me.type),Oe=k(Me.internalFormat,Be,Fe,Me.colorSpace,q.isXRRenderTarget===!0),Re=se(q);t.renderbufferStorageMultisample(t.RENDERBUFFER,Re,Oe,q.width,q.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+ge,t.RENDERBUFFER,re.__webglColorRenderbuffer[ge])}t.bindRenderbuffer(t.RENDERBUFFER,null),q.depthBuffer&&(re.__webglDepthRenderbuffer=t.createRenderbuffer(),E(re.__webglDepthRenderbuffer,q,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(_e){n.bindTexture(t.TEXTURE_CUBE_MAP,be.__webglTexture),le(t.TEXTURE_CUBE_MAP,R);for(let ge=0;ge<6;ge++)if(R.mipmaps&&R.mipmaps.length>0)for(let Me=0;Me<R.mipmaps.length;Me++)j(re.__webglFramebuffer[ge][Me],q,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Me);else j(re.__webglFramebuffer[ge],q,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0);b(R)&&x(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(xe){for(let ge=0,Me=ye.length;ge<Me;ge++){const Be=ye[ge],Fe=a.get(Be);let Oe=t.TEXTURE_2D;(q.isWebGL3DRenderTarget||q.isWebGLArrayRenderTarget)&&(Oe=q.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(Oe,Fe.__webglTexture),le(Oe,Be),j(re.__webglFramebuffer,q,Be,t.COLOR_ATTACHMENT0+ge,Oe,0),b(Be)&&x(Oe)}n.unbindTexture()}else{let ge=t.TEXTURE_2D;if((q.isWebGL3DRenderTarget||q.isWebGLArrayRenderTarget)&&(ge=q.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(ge,be.__webglTexture),le(ge,R),R.mipmaps&&R.mipmaps.length>0)for(let Me=0;Me<R.mipmaps.length;Me++)j(re.__webglFramebuffer[Me],q,R,t.COLOR_ATTACHMENT0,ge,Me);else j(re.__webglFramebuffer,q,R,t.COLOR_ATTACHMENT0,ge,0);b(R)&&x(ge),n.unbindTexture()}q.depthBuffer&&W(q)}function U(q){const R=q.textures;for(let re=0,be=R.length;re<be;re++){const ye=R[re];if(b(ye)){const _e=S(q),xe=a.get(ye).__webglTexture;n.bindTexture(_e,xe),x(_e),n.unbindTexture()}}}const G=[],K=[];function X(q){if(q.samples>0){if(te(q)===!1){const R=q.textures,re=q.width,be=q.height;let ye=t.COLOR_BUFFER_BIT;const _e=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,xe=a.get(q),ge=R.length>1;if(ge)for(let Be=0;Be<R.length;Be++)n.bindFramebuffer(t.FRAMEBUFFER,xe.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,xe.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,xe.__webglMultisampledFramebuffer);const Me=q.texture.mipmaps;Me&&Me.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,xe.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,xe.__webglFramebuffer);for(let Be=0;Be<R.length;Be++){if(q.resolveDepthBuffer&&(q.depthBuffer&&(ye|=t.DEPTH_BUFFER_BIT),q.stencilBuffer&&q.resolveStencilBuffer&&(ye|=t.STENCIL_BUFFER_BIT)),ge){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,xe.__webglColorRenderbuffer[Be]);const Fe=a.get(R[Be]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Fe,0)}t.blitFramebuffer(0,0,re,be,0,0,re,be,ye,t.NEAREST),c===!0&&(G.length=0,K.length=0,G.push(t.COLOR_ATTACHMENT0+Be),q.depthBuffer&&q.resolveDepthBuffer===!1&&(G.push(_e),K.push(_e),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,K)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,G))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),ge)for(let Be=0;Be<R.length;Be++){n.bindFramebuffer(t.FRAMEBUFFER,xe.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.RENDERBUFFER,xe.__webglColorRenderbuffer[Be]);const Fe=a.get(R[Be]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,xe.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.TEXTURE_2D,Fe,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,xe.__webglMultisampledFramebuffer)}else if(q.depthBuffer&&q.resolveDepthBuffer===!1&&c){const R=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[R])}}}function se(q){return Math.min(i.maxSamples,q.samples)}function te(q){const R=a.get(q);return q.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function fe(q){const R=o.render.frame;u.get(q)!==R&&(u.set(q,R),q.update())}function de(q,R){const re=q.colorSpace,be=q.format,ye=q.type;return q.isCompressedTexture===!0||q.isVideoTexture===!0||re!==Sy&&re!==uh&&(Or.getTransfer(re)===aa?(be!==ld||ye!==fu)&&$n("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):di("WebGLTextures: Unsupported texture color space:",re)),R}function me(q){return typeof HTMLImageElement<"u"&&q instanceof HTMLImageElement?(d.width=q.naturalWidth||q.width,d.height=q.naturalHeight||q.height):typeof VideoFrame<"u"&&q instanceof VideoFrame?(d.width=q.displayWidth,d.height=q.displayHeight):(d.width=q.width,d.height=q.height),d}this.allocateTextureUnit=z,this.resetTextureUnits=I,this.setTexture2D=Z,this.setTexture2DArray=ne,this.setTexture3D=Y,this.setTextureCube=ce,this.rebindTextures=O,this.setupRenderTarget=ie,this.updateRenderTargetMipmap=U,this.updateMultisampleRenderTarget=X,this.setupDepthRenderbuffer=W,this.setupFrameBufferTexture=j,this.useMultisampledRTT=te}function NNe(t,e){function n(a,i=uh){let s;const o=Or.getTransfer(i);if(a===fu)return t.UNSIGNED_BYTE;if(a===LO)return t.UNSIGNED_SHORT_4_4_4_4;if(a===RO)return t.UNSIGNED_SHORT_5_5_5_1;if(a===hJ)return t.UNSIGNED_INT_5_9_9_9_REV;if(a===fJ)return t.UNSIGNED_INT_10F_11F_11F_REV;if(a===mJ)return t.BYTE;if(a===pJ)return t.SHORT;if(a===Rw)return t.UNSIGNED_SHORT;if(a===FO)return t.INT;if(a===Lg)return t.UNSIGNED_INT;if(a===_m)return t.FLOAT;if(a===Yy)return t.HALF_FLOAT;if(a===gJ)return t.ALPHA;if(a===bJ)return t.RGB;if(a===ld)return t.RGBA;if(a===Ow)return t.DEPTH_COMPONENT;if(a===zw)return t.DEPTH_STENCIL;if(a===xJ)return t.RED;if(a===IO)return t.RED_INTEGER;if(a===OO)return t.RG;if(a===zO)return t.RG_INTEGER;if(a===UO)return t.RGBA_INTEGER;if(a===vN||a===wN||a===SN||a===_N)if(o===aa)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(a===vN)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(a===wN)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(a===SN)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(a===_N)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(a===vN)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(a===wN)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(a===SN)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(a===_N)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(a===gL||a===bL||a===xL||a===yL)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(a===gL)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(a===bL)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(a===xL)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(a===yL)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(a===vL||a===wL||a===SL)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(a===vL||a===wL)return o===aa?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(a===SL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(a===_L||a===kL||a===NL||a===CL||a===PL||a===TL||a===AL||a===jL||a===ML||a===EL||a===DL||a===FL||a===LL||a===RL)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(a===_L)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(a===kL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(a===NL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(a===CL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(a===PL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(a===TL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(a===AL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(a===jL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(a===ML)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(a===EL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(a===DL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(a===FL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(a===LL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(a===RL)return o===aa?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(a===IL||a===OL||a===zL)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(a===IL)return o===aa?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(a===OL)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(a===zL)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(a===UL||a===BL||a===HL||a===qL)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(a===UL)return s.COMPRESSED_RED_RGTC1_EXT;if(a===BL)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(a===HL)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(a===qL)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return a===Iw?t.UNSIGNED_INT_24_8:t[a]!==void 0?t[a]:null}return{convert:n}}const CNe=`
  3849. void main() {
  3850. gl_Position = vec4( position, 1.0 );
  3851. }`,PNe=`
  3852. uniform sampler2DArray depthColor;
  3853. uniform float depthWidth;
  3854. uniform float depthHeight;
  3855. void main() {
  3856. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  3857. if ( coord.x >= 1.0 ) {
  3858. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  3859. } else {
  3860. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  3861. }
  3862. }`;class TNe{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const a=new zJ(e.texture);(e.depthNear!==n.depthNear||e.depthFar!==n.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=a}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,a=new Km({vertexShader:CNe,fragmentShader:PNe,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new _c(new GO(20,20),a)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}let ANe=class extends lb{constructor(e,n){super();const a=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,g=null;const w=typeof XRWebGLBinding<"u",b=new TNe,x={},S=n.getContextAttributes();let k=null,C=null;const P=[],T=[],A=new ir;let F=null;const _=new ac;_.viewport=new wi;const M=new ac;M.viewport=new wi;const H=[_,M],I=new Gwe;let z=null,L=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function($){let J=P[$];return J===void 0&&(J=new FE,P[$]=J),J.getTargetRaySpace()},this.getControllerGrip=function($){let J=P[$];return J===void 0&&(J=new FE,P[$]=J),J.getGripSpace()},this.getHand=function($){let J=P[$];return J===void 0&&(J=new FE,P[$]=J),J.getHandSpace()};function Z($){const J=T.indexOf($.inputSource);if(J===-1)return;const j=P[J];j!==void 0&&(j.update($.inputSource,$.frame,d||o),j.dispatchEvent({type:$.type,data:$.inputSource}))}function ne(){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",ne),i.removeEventListener("inputsourceschange",Y);for(let $=0;$<P.length;$++){const J=T[$];J!==null&&(T[$]=null,P[$].disconnect(J))}z=null,L=null,b.reset();for(const $ in x)delete x[$];e.setRenderTarget(k),f=null,p=null,m=null,i=null,C=null,we.stop(),a.isPresenting=!1,e.setPixelRatio(F),e.setSize(A.width,A.height,!1),a.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function($){s=$,a.isPresenting===!0&&$n("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function($){l=$,a.isPresenting===!0&&$n("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&&w&&(m=new XRWebGLBinding(i,n)),m},this.getFrame=function(){return g},this.getSession=function(){return i},this.setSession=async function($){if(i=$,i!==null){if(k=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",ne),i.addEventListener("inputsourceschange",Y),S.xrCompatible!==!0&&await n.makeXRCompatible(),F=e.getPixelRatio(),e.getSize(A),w&&"createProjectionLayer"in XRWebGLBinding.prototype){let j=null,E=null,B=null;S.depth&&(B=S.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,j=S.stencil?zw:Ow,E=S.stencil?Iw:Lg);const W={colorFormat:n.RGBA8,depthFormat:B,scaleFactor:s};m=this.getBinding(),p=m.createProjectionLayer(W),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),C=new Ig(p.textureWidth,p.textureHeight,{format:ld,type:fu,depthTexture:new OJ(p.textureWidth,p.textureHeight,E,void 0,void 0,void 0,void 0,void 0,void 0,j),stencilBuffer:S.stencil,colorSpace:e.outputColorSpace,samples:S.antialias?4:0,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}else{const j={antialias:S.antialias,alpha:!0,depth:S.depth,stencil:S.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,j),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),C=new Ig(f.framebufferWidth,f.framebufferHeight,{format:ld,type:fu,colorSpace:e.outputColorSpace,stencilBuffer:S.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}C.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),we.setContext(i),we.start(),a.isPresenting=!0,a.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return b.getDepthTexture()};function Y($){for(let J=0;J<$.removed.length;J++){const j=$.removed[J],E=T.indexOf(j);E>=0&&(T[E]=null,P[E].disconnect(j))}for(let J=0;J<$.added.length;J++){const j=$.added[J];let E=T.indexOf(j);if(E===-1){for(let W=0;W<P.length;W++)if(W>=T.length){T.push(j),E=W;break}else if(T[W]===null){T[W]=j,E=W;break}if(E===-1)break}const B=P[E];B&&B.connect(j)}}const ce=new Lt,ue=new Lt;function oe($,J,j){ce.setFromMatrixPosition(J.matrixWorld),ue.setFromMatrixPosition(j.matrixWorld);const E=ce.distanceTo(ue),B=J.projectionMatrix.elements,W=j.projectionMatrix.elements,O=B[14]/(B[10]-1),ie=B[14]/(B[10]+1),U=(B[9]+1)/B[5],G=(B[9]-1)/B[5],K=(B[8]-1)/B[0],X=(W[8]+1)/W[0],se=O*K,te=O*X,fe=E/(-K+X),de=fe*-K;if(J.matrixWorld.decompose($.position,$.quaternion,$.scale),$.translateX(de),$.translateZ(fe),$.matrixWorld.compose($.position,$.quaternion,$.scale),$.matrixWorldInverse.copy($.matrixWorld).invert(),B[10]===-1)$.projectionMatrix.copy(J.projectionMatrix),$.projectionMatrixInverse.copy(J.projectionMatrixInverse);else{const me=O+fe,q=ie+fe,R=se-de,re=te+(E-de),be=U*ie/q*me,ye=G*ie/q*me;$.projectionMatrix.makePerspective(R,re,be,ye,me,q),$.projectionMatrixInverse.copy($.projectionMatrix).invert()}}function Q($,J){J===null?$.matrixWorld.copy($.matrix):$.matrixWorld.multiplyMatrices(J.matrixWorld,$.matrix),$.matrixWorldInverse.copy($.matrixWorld).invert()}this.updateCamera=function($){if(i===null)return;let J=$.near,j=$.far;b.texture!==null&&(b.depthNear>0&&(J=b.depthNear),b.depthFar>0&&(j=b.depthFar)),I.near=M.near=_.near=J,I.far=M.far=_.far=j,(z!==I.near||L!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),z=I.near,L=I.far),I.layers.mask=$.layers.mask|6,_.layers.mask=I.layers.mask&3,M.layers.mask=I.layers.mask&5;const E=$.parent,B=I.cameras;Q(I,E);for(let W=0;W<B.length;W++)Q(B[W],E);B.length===2?oe(I,_,M):I.projectionMatrix.copy(_.projectionMatrix),le($,I,E)};function le($,J,j){j===null?$.matrix.copy(J.matrixWorld):($.matrix.copy(j.matrixWorld),$.matrix.invert(),$.matrix.multiply(J.matrixWorld)),$.matrix.decompose($.position,$.quaternion,$.scale),$.updateMatrixWorld(!0),$.projectionMatrix.copy(J.projectionMatrix),$.projectionMatrixInverse.copy(J.projectionMatrixInverse),$.isPerspectiveCamera&&($.fov=$L*2*Math.atan(1/$.projectionMatrix.elements[5]),$.zoom=1)}this.getCamera=function(){return I},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 b.texture!==null},this.getDepthSensingMesh=function(){return b.getMesh(I)},this.getCameraTexture=function($){return x[$]};let pe=null;function he($,J){if(u=J.getViewerPose(d||o),g=J,u!==null){const j=u.views;f!==null&&(e.setRenderTargetFramebuffer(C,f.framebuffer),e.setRenderTarget(C));let E=!1;j.length!==I.cameras.length&&(I.cameras.length=0,E=!0);for(let ie=0;ie<j.length;ie++){const U=j[ie];let G=null;if(f!==null)G=f.getViewport(U);else{const X=m.getViewSubImage(p,U);G=X.viewport,ie===0&&(e.setRenderTargetTextures(C,X.colorTexture,X.depthStencilTexture),e.setRenderTarget(C))}let K=H[ie];K===void 0&&(K=new ac,K.layers.enable(ie),K.viewport=new wi,H[ie]=K),K.matrix.fromArray(U.transform.matrix),K.matrix.decompose(K.position,K.quaternion,K.scale),K.projectionMatrix.fromArray(U.projectionMatrix),K.projectionMatrixInverse.copy(K.projectionMatrix).invert(),K.viewport.set(G.x,G.y,G.width,G.height),ie===0&&(I.matrix.copy(K.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale)),E===!0&&I.cameras.push(K)}const B=i.enabledFeatures;if(B&&B.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&w){m=a.getBinding();const ie=m.getDepthInformation(j[0]);ie&&ie.isValid&&ie.texture&&b.init(ie,i.renderState)}if(B&&B.includes("camera-access")&&w){e.state.unbindTexture(),m=a.getBinding();for(let ie=0;ie<j.length;ie++){const U=j[ie].camera;if(U){let G=x[U];G||(G=new zJ,x[U]=G);const K=m.getCameraImage(U);G.sourceTexture=K}}}}for(let j=0;j<P.length;j++){const E=T[j],B=P[j];E!==null&&B!==void 0&&B.update(E,J,d||o)}pe&&pe($,J),J.detectedPlanes&&a.dispatchEvent({type:"planesdetected",data:J}),g=null}const we=new $J;we.setAnimationLoop(he),this.setAnimationLoop=function($){pe=$},this.dispose=function(){}}};const If=new Kh,jNe=new Ci;function MNe(t,e){function n(b,x){b.matrixAutoUpdate===!0&&b.updateMatrix(),x.value.copy(b.matrix)}function a(b,x){x.color.getRGB(b.fogColor.value,FJ(t)),x.isFog?(b.fogNear.value=x.near,b.fogFar.value=x.far):x.isFogExp2&&(b.fogDensity.value=x.density)}function i(b,x,S,k,C){x.isMeshBasicMaterial||x.isMeshLambertMaterial?s(b,x):x.isMeshToonMaterial?(s(b,x),m(b,x)):x.isMeshPhongMaterial?(s(b,x),u(b,x)):x.isMeshStandardMaterial?(s(b,x),p(b,x),x.isMeshPhysicalMaterial&&f(b,x,C)):x.isMeshMatcapMaterial?(s(b,x),g(b,x)):x.isMeshDepthMaterial?s(b,x):x.isMeshDistanceMaterial?(s(b,x),w(b,x)):x.isMeshNormalMaterial?s(b,x):x.isLineBasicMaterial?(o(b,x),x.isLineDashedMaterial&&l(b,x)):x.isPointsMaterial?c(b,x,S,k):x.isSpriteMaterial?d(b,x):x.isShadowMaterial?(b.color.value.copy(x.color),b.opacity.value=x.opacity):x.isShaderMaterial&&(x.uniformsNeedUpdate=!1)}function s(b,x){b.opacity.value=x.opacity,x.color&&b.diffuse.value.copy(x.color),x.emissive&&b.emissive.value.copy(x.emissive).multiplyScalar(x.emissiveIntensity),x.map&&(b.map.value=x.map,n(x.map,b.mapTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.bumpMap&&(b.bumpMap.value=x.bumpMap,n(x.bumpMap,b.bumpMapTransform),b.bumpScale.value=x.bumpScale,x.side===Wo&&(b.bumpScale.value*=-1)),x.normalMap&&(b.normalMap.value=x.normalMap,n(x.normalMap,b.normalMapTransform),b.normalScale.value.copy(x.normalScale),x.side===Wo&&b.normalScale.value.negate()),x.displacementMap&&(b.displacementMap.value=x.displacementMap,n(x.displacementMap,b.displacementMapTransform),b.displacementScale.value=x.displacementScale,b.displacementBias.value=x.displacementBias),x.emissiveMap&&(b.emissiveMap.value=x.emissiveMap,n(x.emissiveMap,b.emissiveMapTransform)),x.specularMap&&(b.specularMap.value=x.specularMap,n(x.specularMap,b.specularMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest);const S=e.get(x),k=S.envMap,C=S.envMapRotation;k&&(b.envMap.value=k,If.copy(C),If.x*=-1,If.y*=-1,If.z*=-1,k.isCubeTexture&&k.isRenderTargetTexture===!1&&(If.y*=-1,If.z*=-1),b.envMapRotation.value.setFromMatrix4(jNe.makeRotationFromEuler(If)),b.flipEnvMap.value=k.isCubeTexture&&k.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=x.reflectivity,b.ior.value=x.ior,b.refractionRatio.value=x.refractionRatio),x.lightMap&&(b.lightMap.value=x.lightMap,b.lightMapIntensity.value=x.lightMapIntensity,n(x.lightMap,b.lightMapTransform)),x.aoMap&&(b.aoMap.value=x.aoMap,b.aoMapIntensity.value=x.aoMapIntensity,n(x.aoMap,b.aoMapTransform))}function o(b,x){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,x.map&&(b.map.value=x.map,n(x.map,b.mapTransform))}function l(b,x){b.dashSize.value=x.dashSize,b.totalSize.value=x.dashSize+x.gapSize,b.scale.value=x.scale}function c(b,x,S,k){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,b.size.value=x.size*S,b.scale.value=k*.5,x.map&&(b.map.value=x.map,n(x.map,b.uvTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest)}function d(b,x){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,b.rotation.value=x.rotation,x.map&&(b.map.value=x.map,n(x.map,b.mapTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest)}function u(b,x){b.specular.value.copy(x.specular),b.shininess.value=Math.max(x.shininess,1e-4)}function m(b,x){x.gradientMap&&(b.gradientMap.value=x.gradientMap)}function p(b,x){b.metalness.value=x.metalness,x.metalnessMap&&(b.metalnessMap.value=x.metalnessMap,n(x.metalnessMap,b.metalnessMapTransform)),b.roughness.value=x.roughness,x.roughnessMap&&(b.roughnessMap.value=x.roughnessMap,n(x.roughnessMap,b.roughnessMapTransform)),x.envMap&&(b.envMapIntensity.value=x.envMapIntensity)}function f(b,x,S){b.ior.value=x.ior,x.sheen>0&&(b.sheenColor.value.copy(x.sheenColor).multiplyScalar(x.sheen),b.sheenRoughness.value=x.sheenRoughness,x.sheenColorMap&&(b.sheenColorMap.value=x.sheenColorMap,n(x.sheenColorMap,b.sheenColorMapTransform)),x.sheenRoughnessMap&&(b.sheenRoughnessMap.value=x.sheenRoughnessMap,n(x.sheenRoughnessMap,b.sheenRoughnessMapTransform))),x.clearcoat>0&&(b.clearcoat.value=x.clearcoat,b.clearcoatRoughness.value=x.clearcoatRoughness,x.clearcoatMap&&(b.clearcoatMap.value=x.clearcoatMap,n(x.clearcoatMap,b.clearcoatMapTransform)),x.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=x.clearcoatRoughnessMap,n(x.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),x.clearcoatNormalMap&&(b.clearcoatNormalMap.value=x.clearcoatNormalMap,n(x.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(x.clearcoatNormalScale),x.side===Wo&&b.clearcoatNormalScale.value.negate())),x.dispersion>0&&(b.dispersion.value=x.dispersion),x.iridescence>0&&(b.iridescence.value=x.iridescence,b.iridescenceIOR.value=x.iridescenceIOR,b.iridescenceThicknessMinimum.value=x.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=x.iridescenceThicknessRange[1],x.iridescenceMap&&(b.iridescenceMap.value=x.iridescenceMap,n(x.iridescenceMap,b.iridescenceMapTransform)),x.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=x.iridescenceThicknessMap,n(x.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),x.transmission>0&&(b.transmission.value=x.transmission,b.transmissionSamplerMap.value=S.texture,b.transmissionSamplerSize.value.set(S.width,S.height),x.transmissionMap&&(b.transmissionMap.value=x.transmissionMap,n(x.transmissionMap,b.transmissionMapTransform)),b.thickness.value=x.thickness,x.thicknessMap&&(b.thicknessMap.value=x.thicknessMap,n(x.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=x.attenuationDistance,b.attenuationColor.value.copy(x.attenuationColor)),x.anisotropy>0&&(b.anisotropyVector.value.set(x.anisotropy*Math.cos(x.anisotropyRotation),x.anisotropy*Math.sin(x.anisotropyRotation)),x.anisotropyMap&&(b.anisotropyMap.value=x.anisotropyMap,n(x.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=x.specularIntensity,b.specularColor.value.copy(x.specularColor),x.specularColorMap&&(b.specularColorMap.value=x.specularColorMap,n(x.specularColorMap,b.specularColorMapTransform)),x.specularIntensityMap&&(b.specularIntensityMap.value=x.specularIntensityMap,n(x.specularIntensityMap,b.specularIntensityMapTransform))}function g(b,x){x.matcap&&(b.matcap.value=x.matcap)}function w(b,x){const S=e.get(x).light;b.referencePosition.value.setFromMatrixPosition(S.matrixWorld),b.nearDistance.value=S.shadow.camera.near,b.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:a,refreshMaterialUniforms:i}}function ENe(t,e,n,a){let i={},s={},o=[];const l=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function c(S,k){const C=k.program;a.uniformBlockBinding(S,C)}function d(S,k){let C=i[S.id];C===void 0&&(g(S),C=u(S),i[S.id]=C,S.addEventListener("dispose",b));const P=k.program;a.updateUBOMapping(S,P);const T=e.render.frame;s[S.id]!==T&&(p(S),s[S.id]=T)}function u(S){const k=m();S.__bindingPointIndex=k;const C=t.createBuffer(),P=S.__size,T=S.usage;return t.bindBuffer(t.UNIFORM_BUFFER,C),t.bufferData(t.UNIFORM_BUFFER,P,T),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,k,C),C}function m(){for(let S=0;S<l;S++)if(o.indexOf(S)===-1)return o.push(S),S;return di("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function p(S){const k=i[S.id],C=S.uniforms,P=S.__cache;t.bindBuffer(t.UNIFORM_BUFFER,k);for(let T=0,A=C.length;T<A;T++){const F=Array.isArray(C[T])?C[T]:[C[T]];for(let _=0,M=F.length;_<M;_++){const H=F[_];if(f(H,T,_,P)===!0){const I=H.__offset,z=Array.isArray(H.value)?H.value:[H.value];let L=0;for(let Z=0;Z<z.length;Z++){const ne=z[Z],Y=w(ne);typeof ne=="number"||typeof ne=="boolean"?(H.__data[0]=ne,t.bufferSubData(t.UNIFORM_BUFFER,I+L,H.__data)):ne.isMatrix3?(H.__data[0]=ne.elements[0],H.__data[1]=ne.elements[1],H.__data[2]=ne.elements[2],H.__data[3]=0,H.__data[4]=ne.elements[3],H.__data[5]=ne.elements[4],H.__data[6]=ne.elements[5],H.__data[7]=0,H.__data[8]=ne.elements[6],H.__data[9]=ne.elements[7],H.__data[10]=ne.elements[8],H.__data[11]=0):(ne.toArray(H.__data,L),L+=Y.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,I,H.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(S,k,C,P){const T=S.value,A=k+"_"+C;if(P[A]===void 0)return typeof T=="number"||typeof T=="boolean"?P[A]=T:P[A]=T.clone(),!0;{const F=P[A];if(typeof T=="number"||typeof T=="boolean"){if(F!==T)return P[A]=T,!0}else if(F.equals(T)===!1)return F.copy(T),!0}return!1}function g(S){const k=S.uniforms;let C=0;const P=16;for(let A=0,F=k.length;A<F;A++){const _=Array.isArray(k[A])?k[A]:[k[A]];for(let M=0,H=_.length;M<H;M++){const I=_[M],z=Array.isArray(I.value)?I.value:[I.value];for(let L=0,Z=z.length;L<Z;L++){const ne=z[L],Y=w(ne),ce=C%P,ue=ce%Y.boundary,oe=ce+ue;C+=ue,oe!==0&&P-oe<Y.storage&&(C+=P-oe),I.__data=new Float32Array(Y.storage/Float32Array.BYTES_PER_ELEMENT),I.__offset=C,C+=Y.storage}}}const T=C%P;return T>0&&(C+=P-T),S.__size=C,S.__cache={},this}function w(S){const k={boundary:0,storage:0};return typeof S=="number"||typeof S=="boolean"?(k.boundary=4,k.storage=4):S.isVector2?(k.boundary=8,k.storage=8):S.isVector3||S.isColor?(k.boundary=16,k.storage=12):S.isVector4?(k.boundary=16,k.storage=16):S.isMatrix3?(k.boundary=48,k.storage=48):S.isMatrix4?(k.boundary=64,k.storage=64):S.isTexture?$n("WebGLRenderer: Texture samplers can not be part of an uniforms group."):$n("WebGLRenderer: Unsupported uniform value type.",S),k}function b(S){const k=S.target;k.removeEventListener("dispose",b);const C=o.indexOf(k.__bindingPointIndex);o.splice(C,1),t.deleteBuffer(i[k.id]),delete i[k.id],delete s[k.id]}function x(){for(const S in i)t.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:c,update:d,dispose:x}}const DNe=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 em=null;function FNe(){return em===null&&(em=new Mwe(DNe,32,32,OO,Yy),em.minFilter=mc,em.magFilter=mc,em.wrapS=Sm,em.wrapT=Sm,em.generateMipmaps=!1,em.needsUpdate=!0),em}let LNe=class{constructor(e={}){const{canvas:n=nwe(),context:a=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(a!==null){if(typeof WebGLRenderingContext<"u"&&a instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=a.getContextAttributes().alpha}else f=o;const g=new Set([UO,zO,IO]),w=new Set([fu,Lg,Rw,Iw,LO,RO]),b=new Uint32Array(4),x=new Int32Array(4);let S=null,k=null;const C=[],P=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Dh,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let A=!1;this._outputColorSpace=fl;let F=0,_=0,M=null,H=-1,I=null;const z=new wi,L=new wi;let Z=null;const ne=new cr(0);let Y=0,ce=n.width,ue=n.height,oe=1,Q=null,le=null;const pe=new wi(0,0,ce,ue),he=new wi(0,0,ce,ue);let we=!1;const $=new VO;let J=!1,j=!1;const E=new Ci,B=new Lt,W=new wi,O={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ie=!1;function U(){return M===null?oe:1}let G=a;function K(Ne,Ye){return n.getContext(Ne,Ye)}try{const Ne={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${EO}`),n.addEventListener("webglcontextlost",Ie,!1),n.addEventListener("webglcontextrestored",ke,!1),n.addEventListener("webglcontextcreationerror",Ve,!1),G===null){const Ye="webgl2";if(G=K(Ye,Ne),G===null)throw K(Ye)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(Ne){throw Ne("WebGLRenderer: "+Ne.message),Ne}let X,se,te,fe,de,me,q,R,re,be,ye,_e,xe,ge,Me,Be,Fe,Oe,Re,We,ze,st,Ee,it;function Ce(){X=new qke(G),X.init(),st=new NNe(G,X),se=new Fke(G,X,e,st),te=new _Ne(G,X),se.reversedDepthBuffer&&p&&te.buffers.depth.setReversed(!0),fe=new Gke(G),de=new dNe,me=new kNe(G,X,te,de,se,st,fe),q=new Rke(T),R=new Hke(T),re=new Ywe(G),Ee=new Eke(G,re),be=new $ke(G,re,fe,Ee),ye=new Kke(G,be,re,fe),Re=new Wke(G,se,me),Be=new Lke(de),_e=new cNe(T,q,R,X,se,Ee,Be),xe=new MNe(T,de),ge=new mNe,Me=new xNe(X),Oe=new Mke(T,q,R,te,ye,f,c),Fe=new wNe(T,ye,se),it=new ENe(G,fe,se,te),We=new Dke(G,X,fe),ze=new Vke(G,X,fe),fe.programs=_e.programs,T.capabilities=se,T.extensions=X,T.properties=de,T.renderLists=ge,T.shadowMap=Fe,T.state=te,T.info=fe}Ce();const Ze=new ANe(T,G);this.xr=Ze,this.getContext=function(){return G},this.getContextAttributes=function(){return G.getContextAttributes()},this.forceContextLoss=function(){const Ne=X.get("WEBGL_lose_context");Ne&&Ne.loseContext()},this.forceContextRestore=function(){const Ne=X.get("WEBGL_lose_context");Ne&&Ne.restoreContext()},this.getPixelRatio=function(){return oe},this.setPixelRatio=function(Ne){Ne!==void 0&&(oe=Ne,this.setSize(ce,ue,!1))},this.getSize=function(Ne){return Ne.set(ce,ue)},this.setSize=function(Ne,Ye,nt=!0){if(Ze.isPresenting){$n("WebGLRenderer: Can't change size while VR device is presenting.");return}ce=Ne,ue=Ye,n.width=Math.floor(Ne*oe),n.height=Math.floor(Ye*oe),nt===!0&&(n.style.width=Ne+"px",n.style.height=Ye+"px"),this.setViewport(0,0,Ne,Ye)},this.getDrawingBufferSize=function(Ne){return Ne.set(ce*oe,ue*oe).floor()},this.setDrawingBufferSize=function(Ne,Ye,nt){ce=Ne,ue=Ye,oe=nt,n.width=Math.floor(Ne*nt),n.height=Math.floor(Ye*nt),this.setViewport(0,0,Ne,Ye)},this.getCurrentViewport=function(Ne){return Ne.copy(z)},this.getViewport=function(Ne){return Ne.copy(pe)},this.setViewport=function(Ne,Ye,nt,at){Ne.isVector4?pe.set(Ne.x,Ne.y,Ne.z,Ne.w):pe.set(Ne,Ye,nt,at),te.viewport(z.copy(pe).multiplyScalar(oe).round())},this.getScissor=function(Ne){return Ne.copy(he)},this.setScissor=function(Ne,Ye,nt,at){Ne.isVector4?he.set(Ne.x,Ne.y,Ne.z,Ne.w):he.set(Ne,Ye,nt,at),te.scissor(L.copy(he).multiplyScalar(oe).round())},this.getScissorTest=function(){return we},this.setScissorTest=function(Ne){te.setScissorTest(we=Ne)},this.setOpaqueSort=function(Ne){Q=Ne},this.setTransparentSort=function(Ne){le=Ne},this.getClearColor=function(Ne){return Ne.copy(Oe.getClearColor())},this.setClearColor=function(){Oe.setClearColor(...arguments)},this.getClearAlpha=function(){return Oe.getClearAlpha()},this.setClearAlpha=function(){Oe.setClearAlpha(...arguments)},this.clear=function(Ne=!0,Ye=!0,nt=!0){let at=0;if(Ne){let et=!1;if(M!==null){const vt=M.texture.format;et=g.has(vt)}if(et){const vt=M.texture.type,wt=w.has(vt),Ue=Oe.getClearColor(),He=Oe.getClearAlpha(),Dt=Ue.r,Rt=Ue.g,qe=Ue.b;wt?(b[0]=Dt,b[1]=Rt,b[2]=qe,b[3]=He,G.clearBufferuiv(G.COLOR,0,b)):(x[0]=Dt,x[1]=Rt,x[2]=qe,x[3]=He,G.clearBufferiv(G.COLOR,0,x))}else at|=G.COLOR_BUFFER_BIT}Ye&&(at|=G.DEPTH_BUFFER_BIT),nt&&(at|=G.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),G.clear(at)},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",ke,!1),n.removeEventListener("webglcontextcreationerror",Ve,!1),Oe.dispose(),ge.dispose(),Me.dispose(),de.dispose(),q.dispose(),R.dispose(),ye.dispose(),Ee.dispose(),it.dispose(),_e.dispose(),Ze.dispose(),Ze.removeEventListener("sessionstart",Ut),Ze.removeEventListener("sessionend",bt),Wt.stop()};function Ie(Ne){Ne.preventDefault(),R6("WebGLRenderer: Context Lost."),A=!0}function ke(){R6("WebGLRenderer: Context Restored."),A=!1;const Ne=fe.autoReset,Ye=Fe.enabled,nt=Fe.autoUpdate,at=Fe.needsUpdate,et=Fe.type;Ce(),fe.autoReset=Ne,Fe.enabled=Ye,Fe.autoUpdate=nt,Fe.needsUpdate=at,Fe.type=et}function Ve(Ne){di("WebGLRenderer: A WebGL context could not be created. Reason: ",Ne.statusMessage)}function rt(Ne){const Ye=Ne.target;Ye.removeEventListener("dispose",rt),Qe(Ye)}function Qe(Ne){Te(Ne),de.remove(Ne)}function Te(Ne){const Ye=de.get(Ne).programs;Ye!==void 0&&(Ye.forEach(function(nt){_e.releaseProgram(nt)}),Ne.isShaderMaterial&&_e.releaseShaderCache(Ne))}this.renderBufferDirect=function(Ne,Ye,nt,at,et,vt){Ye===null&&(Ye=O);const wt=et.isMesh&&et.matrixWorld.determinant()<0,Ue=Le(Ne,Ye,nt,at,et);te.setMaterial(at,wt);let He=nt.index,Dt=1;if(at.wireframe===!0){if(He=be.getWireframeAttribute(nt),He===void 0)return;Dt=2}const Rt=nt.drawRange,qe=nt.attributes.position;let Ke=Rt.start*Dt,Bt=(Rt.start+Rt.count)*Dt;vt!==null&&(Ke=Math.max(Ke,vt.start*Dt),Bt=Math.min(Bt,(vt.start+vt.count)*Dt)),He!==null?(Ke=Math.max(Ke,0),Bt=Math.min(Bt,He.count)):qe!=null&&(Ke=Math.max(Ke,0),Bt=Math.min(Bt,qe.count));const Qt=Bt-Ke;if(Qt<0||Qt===1/0)return;Ee.setup(et,at,Ue,nt,He);let dn,nn=We;if(He!==null&&(dn=re.get(He),nn=ze,nn.setIndex(dn)),et.isMesh)at.wireframe===!0?(te.setLineWidth(at.wireframeLinewidth*U()),nn.setMode(G.LINES)):nn.setMode(G.TRIANGLES);else if(et.isLine){let rn=at.linewidth;rn===void 0&&(rn=1),te.setLineWidth(rn*U()),et.isLineSegments?nn.setMode(G.LINES):et.isLineLoop?nn.setMode(G.LINE_LOOP):nn.setMode(G.LINE_STRIP)}else et.isPoints?nn.setMode(G.POINTS):et.isSprite&&nn.setMode(G.TRIANGLES);if(et.isBatchedMesh)if(et._multiDrawInstances!==null)Uw("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),nn.renderMultiDrawInstances(et._multiDrawStarts,et._multiDrawCounts,et._multiDrawCount,et._multiDrawInstances);else if(X.get("WEBGL_multi_draw"))nn.renderMultiDraw(et._multiDrawStarts,et._multiDrawCounts,et._multiDrawCount);else{const rn=et._multiDrawStarts,yn=et._multiDrawCounts,Mn=et._multiDrawCount,or=He?re.get(He).bytesPerElement:1,Dr=de.get(at).currentProgram.getUniforms();for(let Gn=0;Gn<Mn;Gn++)Dr.setValue(G,"_gl_DrawID",Gn),nn.render(rn[Gn]/or,yn[Gn])}else if(et.isInstancedMesh)nn.renderInstances(Ke,Qt,et.count);else if(nt.isInstancedBufferGeometry){const rn=nt._maxInstanceCount!==void 0?nt._maxInstanceCount:1/0,yn=Math.min(nt.instanceCount,rn);nn.renderInstances(Ke,Qt,yn)}else nn.render(Ke,Qt)};function tt(Ne,Ye,nt){Ne.transparent===!0&&Ne.side===Qd&&Ne.forceSinglePass===!1?(Ne.side=Wo,Ne.needsUpdate=!0,Nt(Ne,Ye,nt),Ne.side=Wh,Ne.needsUpdate=!0,Nt(Ne,Ye,nt),Ne.side=Qd):Nt(Ne,Ye,nt)}this.compile=function(Ne,Ye,nt=null){nt===null&&(nt=Ne),k=Me.get(nt),k.init(Ye),P.push(k),nt.traverseVisible(function(et){et.isLight&&et.layers.test(Ye.layers)&&(k.pushLight(et),et.castShadow&&k.pushShadow(et))}),Ne!==nt&&Ne.traverseVisible(function(et){et.isLight&&et.layers.test(Ye.layers)&&(k.pushLight(et),et.castShadow&&k.pushShadow(et))}),k.setupLights();const at=new Set;return Ne.traverse(function(et){if(!(et.isMesh||et.isPoints||et.isLine||et.isSprite))return;const vt=et.material;if(vt)if(Array.isArray(vt))for(let wt=0;wt<vt.length;wt++){const Ue=vt[wt];tt(Ue,nt,et),at.add(Ue)}else tt(vt,nt,et),at.add(vt)}),k=P.pop(),at},this.compileAsync=function(Ne,Ye,nt=null){const at=this.compile(Ne,Ye,nt);return new Promise(et=>{function vt(){if(at.forEach(function(wt){de.get(wt).currentProgram.isReady()&&at.delete(wt)}),at.size===0){et(Ne);return}setTimeout(vt,10)}X.get("KHR_parallel_shader_compile")!==null?vt():setTimeout(vt,10)})};let ot=null;function Tt(Ne){ot&&ot(Ne)}function Ut(){Wt.stop()}function bt(){Wt.start()}const Wt=new $J;Wt.setAnimationLoop(Tt),typeof self<"u"&&Wt.setContext(self),this.setAnimationLoop=function(Ne){ot=Ne,Ze.setAnimationLoop(Ne),Ne===null?Wt.stop():Wt.start()},Ze.addEventListener("sessionstart",Ut),Ze.addEventListener("sessionend",bt),this.render=function(Ne,Ye){if(Ye!==void 0&&Ye.isCamera!==!0){di("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(A===!0)return;if(Ne.matrixWorldAutoUpdate===!0&&Ne.updateMatrixWorld(),Ye.parent===null&&Ye.matrixWorldAutoUpdate===!0&&Ye.updateMatrixWorld(),Ze.enabled===!0&&Ze.isPresenting===!0&&(Ze.cameraAutoUpdate===!0&&Ze.updateCamera(Ye),Ye=Ze.getCamera()),Ne.isScene===!0&&Ne.onBeforeRender(T,Ne,Ye,M),k=Me.get(Ne,P.length),k.init(Ye),P.push(k),E.multiplyMatrices(Ye.projectionMatrix,Ye.matrixWorldInverse),$.setFromProjectionMatrix(E,Jd,Ye.reversedDepth),j=this.localClippingEnabled,J=Be.init(this.clippingPlanes,j),S=ge.get(Ne,C.length),S.init(),C.push(S),Ze.enabled===!0&&Ze.isPresenting===!0){const vt=T.xr.getDepthSensingMesh();vt!==null&&Zt(vt,Ye,-1/0,T.sortObjects)}Zt(Ne,Ye,0,T.sortObjects),S.finish(),T.sortObjects===!0&&S.sort(Q,le),ie=Ze.enabled===!1||Ze.isPresenting===!1||Ze.hasDepthSensing()===!1,ie&&Oe.addToRenderList(S,Ne),this.info.render.frame++,J===!0&&Be.beginShadows();const nt=k.state.shadowsArray;Fe.render(nt,Ne,Ye),J===!0&&Be.endShadows(),this.info.autoReset===!0&&this.info.reset();const at=S.opaque,et=S.transmissive;if(k.setupLights(),Ye.isArrayCamera){const vt=Ye.cameras;if(et.length>0)for(let wt=0,Ue=vt.length;wt<Ue;wt++){const He=vt[wt];cn(at,et,Ne,He)}ie&&Oe.render(Ne);for(let wt=0,Ue=vt.length;wt<Ue;wt++){const He=vt[wt];ln(S,Ne,He,He.viewport)}}else et.length>0&&cn(at,et,Ne,Ye),ie&&Oe.render(Ne),ln(S,Ne,Ye);M!==null&&_===0&&(me.updateMultisampleRenderTarget(M),me.updateRenderTargetMipmap(M)),Ne.isScene===!0&&Ne.onAfterRender(T,Ne,Ye),Ee.resetDefaultState(),H=-1,I=null,P.pop(),P.length>0?(k=P[P.length-1],J===!0&&Be.setGlobalState(T.clippingPlanes,k.state.camera)):k=null,C.pop(),C.length>0?S=C[C.length-1]:S=null};function Zt(Ne,Ye,nt,at){if(Ne.visible===!1)return;if(Ne.layers.test(Ye.layers)){if(Ne.isGroup)nt=Ne.renderOrder;else if(Ne.isLOD)Ne.autoUpdate===!0&&Ne.update(Ye);else if(Ne.isLight)k.pushLight(Ne),Ne.castShadow&&k.pushShadow(Ne);else if(Ne.isSprite){if(!Ne.frustumCulled||$.intersectsSprite(Ne)){at&&W.setFromMatrixPosition(Ne.matrixWorld).applyMatrix4(E);const wt=ye.update(Ne),Ue=Ne.material;Ue.visible&&S.push(Ne,wt,Ue,nt,W.z,null)}}else if((Ne.isMesh||Ne.isLine||Ne.isPoints)&&(!Ne.frustumCulled||$.intersectsObject(Ne))){const wt=ye.update(Ne),Ue=Ne.material;if(at&&(Ne.boundingSphere!==void 0?(Ne.boundingSphere===null&&Ne.computeBoundingSphere(),W.copy(Ne.boundingSphere.center)):(wt.boundingSphere===null&&wt.computeBoundingSphere(),W.copy(wt.boundingSphere.center)),W.applyMatrix4(Ne.matrixWorld).applyMatrix4(E)),Array.isArray(Ue)){const He=wt.groups;for(let Dt=0,Rt=He.length;Dt<Rt;Dt++){const qe=He[Dt],Ke=Ue[qe.materialIndex];Ke&&Ke.visible&&S.push(Ne,wt,Ke,nt,W.z,qe)}}else Ue.visible&&S.push(Ne,wt,Ue,nt,W.z,null)}}const vt=Ne.children;for(let wt=0,Ue=vt.length;wt<Ue;wt++)Zt(vt[wt],Ye,nt,at)}function ln(Ne,Ye,nt,at){const{opaque:et,transmissive:vt,transparent:wt}=Ne;k.setupLightsView(nt),J===!0&&Be.setGlobalState(T.clippingPlanes,nt),at&&te.viewport(z.copy(at)),et.length>0&&ct(et,Ye,nt),vt.length>0&&ct(vt,Ye,nt),wt.length>0&&ct(wt,Ye,nt),te.buffers.depth.setTest(!0),te.buffers.depth.setMask(!0),te.buffers.color.setMask(!0),te.setPolygonOffset(!1)}function cn(Ne,Ye,nt,at){if((nt.isScene===!0?nt.overrideMaterial:null)!==null)return;k.state.transmissionRenderTarget[at.id]===void 0&&(k.state.transmissionRenderTarget[at.id]=new Ig(1,1,{generateMipmaps:!0,type:X.has("EXT_color_buffer_half_float")||X.has("EXT_color_buffer_float")?Yy:fu,minFilter:ig,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Or.workingColorSpace}));const vt=k.state.transmissionRenderTarget[at.id],wt=at.viewport||z;vt.setSize(wt.z*T.transmissionResolutionScale,wt.w*T.transmissionResolutionScale);const Ue=T.getRenderTarget(),He=T.getActiveCubeFace(),Dt=T.getActiveMipmapLevel();T.setRenderTarget(vt),T.getClearColor(ne),Y=T.getClearAlpha(),Y<1&&T.setClearColor(16777215,.5),T.clear(),ie&&Oe.render(nt);const Rt=T.toneMapping;T.toneMapping=Dh;const qe=at.viewport;if(at.viewport!==void 0&&(at.viewport=void 0),k.setupLightsView(at),J===!0&&Be.setGlobalState(T.clippingPlanes,at),ct(Ne,nt,at),me.updateMultisampleRenderTarget(vt),me.updateRenderTargetMipmap(vt),X.has("WEBGL_multisampled_render_to_texture")===!1){let Ke=!1;for(let Bt=0,Qt=Ye.length;Bt<Qt;Bt++){const dn=Ye[Bt],{object:nn,geometry:rn,material:yn,group:Mn}=dn;if(yn.side===Qd&&nn.layers.test(at.layers)){const or=yn.side;yn.side=Wo,yn.needsUpdate=!0,kt(nn,nt,at,rn,yn,Mn),yn.side=or,yn.needsUpdate=!0,Ke=!0}}Ke===!0&&(me.updateMultisampleRenderTarget(vt),me.updateRenderTargetMipmap(vt))}T.setRenderTarget(Ue,He,Dt),T.setClearColor(ne,Y),qe!==void 0&&(at.viewport=qe),T.toneMapping=Rt}function ct(Ne,Ye,nt){const at=Ye.isScene===!0?Ye.overrideMaterial:null;for(let et=0,vt=Ne.length;et<vt;et++){const wt=Ne[et],{object:Ue,geometry:He,group:Dt}=wt;let Rt=wt.material;Rt.allowOverride===!0&&at!==null&&(Rt=at),Ue.layers.test(nt.layers)&&kt(Ue,Ye,nt,He,Rt,Dt)}}function kt(Ne,Ye,nt,at,et,vt){Ne.onBeforeRender(T,Ye,nt,at,et,vt),Ne.modelViewMatrix.multiplyMatrices(nt.matrixWorldInverse,Ne.matrixWorld),Ne.normalMatrix.getNormalMatrix(Ne.modelViewMatrix),et.onBeforeRender(T,Ye,nt,at,Ne,vt),et.transparent===!0&&et.side===Qd&&et.forceSinglePass===!1?(et.side=Wo,et.needsUpdate=!0,T.renderBufferDirect(nt,Ye,at,et,Ne,vt),et.side=Wh,et.needsUpdate=!0,T.renderBufferDirect(nt,Ye,at,et,Ne,vt),et.side=Qd):T.renderBufferDirect(nt,Ye,at,et,Ne,vt),Ne.onAfterRender(T,Ye,nt,at,et,vt)}function Nt(Ne,Ye,nt){Ye.isScene!==!0&&(Ye=O);const at=de.get(Ne),et=k.state.lights,vt=k.state.shadowsArray,wt=et.state.version,Ue=_e.getParameters(Ne,et.state,vt,Ye,nt),He=_e.getProgramCacheKey(Ue);let Dt=at.programs;at.environment=Ne.isMeshStandardMaterial?Ye.environment:null,at.fog=Ye.fog,at.envMap=(Ne.isMeshStandardMaterial?R:q).get(Ne.envMap||at.environment),at.envMapRotation=at.environment!==null&&Ne.envMap===null?Ye.environmentRotation:Ne.envMapRotation,Dt===void 0&&(Ne.addEventListener("dispose",rt),Dt=new Map,at.programs=Dt);let Rt=Dt.get(He);if(Rt!==void 0){if(at.currentProgram===Rt&&at.lightsStateVersion===wt)return Ct(Ne,Ue),Rt}else Ue.uniforms=_e.getUniforms(Ne),Ne.onBeforeCompile(Ue,T),Rt=_e.acquireProgram(Ue,He),Dt.set(He,Rt),at.uniforms=Ue.uniforms;const qe=at.uniforms;return(!Ne.isShaderMaterial&&!Ne.isRawShaderMaterial||Ne.clipping===!0)&&(qe.clippingPlanes=Be.uniform),Ct(Ne,Ue),at.needsLights=Ge(Ne),at.lightsStateVersion=wt,at.needsLights&&(qe.ambientLightColor.value=et.state.ambient,qe.lightProbe.value=et.state.probe,qe.directionalLights.value=et.state.directional,qe.directionalLightShadows.value=et.state.directionalShadow,qe.spotLights.value=et.state.spot,qe.spotLightShadows.value=et.state.spotShadow,qe.rectAreaLights.value=et.state.rectArea,qe.ltc_1.value=et.state.rectAreaLTC1,qe.ltc_2.value=et.state.rectAreaLTC2,qe.pointLights.value=et.state.point,qe.pointLightShadows.value=et.state.pointShadow,qe.hemisphereLights.value=et.state.hemi,qe.directionalShadowMap.value=et.state.directionalShadowMap,qe.directionalShadowMatrix.value=et.state.directionalShadowMatrix,qe.spotShadowMap.value=et.state.spotShadowMap,qe.spotLightMatrix.value=et.state.spotLightMatrix,qe.spotLightMap.value=et.state.spotLightMap,qe.pointShadowMap.value=et.state.pointShadowMap,qe.pointShadowMatrix.value=et.state.pointShadowMatrix),at.currentProgram=Rt,at.uniformsList=null,Rt}function ut(Ne){if(Ne.uniformsList===null){const Ye=Ne.currentProgram.getUniforms();Ne.uniformsList=PN.seqWithValue(Ye.seq,Ne.uniforms)}return Ne.uniformsList}function Ct(Ne,Ye){const nt=de.get(Ne);nt.outputColorSpace=Ye.outputColorSpace,nt.batching=Ye.batching,nt.batchingColor=Ye.batchingColor,nt.instancing=Ye.instancing,nt.instancingColor=Ye.instancingColor,nt.instancingMorph=Ye.instancingMorph,nt.skinning=Ye.skinning,nt.morphTargets=Ye.morphTargets,nt.morphNormals=Ye.morphNormals,nt.morphColors=Ye.morphColors,nt.morphTargetsCount=Ye.morphTargetsCount,nt.numClippingPlanes=Ye.numClippingPlanes,nt.numIntersection=Ye.numClipIntersection,nt.vertexAlphas=Ye.vertexAlphas,nt.vertexTangents=Ye.vertexTangents,nt.toneMapping=Ye.toneMapping}function Le(Ne,Ye,nt,at,et){Ye.isScene!==!0&&(Ye=O),me.resetTextureUnits();const vt=Ye.fog,wt=at.isMeshStandardMaterial?Ye.environment:null,Ue=M===null?T.outputColorSpace:M.isXRRenderTarget===!0?M.texture.colorSpace:Sy,He=(at.isMeshStandardMaterial?R:q).get(at.envMap||wt),Dt=at.vertexColors===!0&&!!nt.attributes.color&&nt.attributes.color.itemSize===4,Rt=!!nt.attributes.tangent&&(!!at.normalMap||at.anisotropy>0),qe=!!nt.morphAttributes.position,Ke=!!nt.morphAttributes.normal,Bt=!!nt.morphAttributes.color;let Qt=Dh;at.toneMapped&&(M===null||M.isXRRenderTarget===!0)&&(Qt=T.toneMapping);const dn=nt.morphAttributes.position||nt.morphAttributes.normal||nt.morphAttributes.color,nn=dn!==void 0?dn.length:0,rn=de.get(at),yn=k.state.lights;if(J===!0&&(j===!0||Ne!==I)){const Fr=Ne===I&&at.id===H;Be.setState(at,Ne,Fr)}let Mn=!1;at.version===rn.__version?(rn.needsLights&&rn.lightsStateVersion!==yn.state.version||rn.outputColorSpace!==Ue||et.isBatchedMesh&&rn.batching===!1||!et.isBatchedMesh&&rn.batching===!0||et.isBatchedMesh&&rn.batchingColor===!0&&et.colorTexture===null||et.isBatchedMesh&&rn.batchingColor===!1&&et.colorTexture!==null||et.isInstancedMesh&&rn.instancing===!1||!et.isInstancedMesh&&rn.instancing===!0||et.isSkinnedMesh&&rn.skinning===!1||!et.isSkinnedMesh&&rn.skinning===!0||et.isInstancedMesh&&rn.instancingColor===!0&&et.instanceColor===null||et.isInstancedMesh&&rn.instancingColor===!1&&et.instanceColor!==null||et.isInstancedMesh&&rn.instancingMorph===!0&&et.morphTexture===null||et.isInstancedMesh&&rn.instancingMorph===!1&&et.morphTexture!==null||rn.envMap!==He||at.fog===!0&&rn.fog!==vt||rn.numClippingPlanes!==void 0&&(rn.numClippingPlanes!==Be.numPlanes||rn.numIntersection!==Be.numIntersection)||rn.vertexAlphas!==Dt||rn.vertexTangents!==Rt||rn.morphTargets!==qe||rn.morphNormals!==Ke||rn.morphColors!==Bt||rn.toneMapping!==Qt||rn.morphTargetsCount!==nn)&&(Mn=!0):(Mn=!0,rn.__version=at.version);let or=rn.currentProgram;Mn===!0&&(or=Nt(at,Ye,et));let Dr=!1,Gn=!1,pi=!1;const Un=or.getUniforms(),vr=rn.uniforms;if(te.useProgram(or.program)&&(Dr=!0,Gn=!0,pi=!0),at.id!==H&&(H=at.id,Gn=!0),Dr||I!==Ne){te.buffers.depth.getReversed()&&Ne.reversedDepth!==!0&&(Ne._reversedDepth=!0,Ne.updateProjectionMatrix()),Un.setValue(G,"projectionMatrix",Ne.projectionMatrix),Un.setValue(G,"viewMatrix",Ne.matrixWorldInverse);const ba=Un.map.cameraPosition;ba!==void 0&&ba.setValue(G,B.setFromMatrixPosition(Ne.matrixWorld)),se.logarithmicDepthBuffer&&Un.setValue(G,"logDepthBufFC",2/(Math.log(Ne.far+1)/Math.LN2)),(at.isMeshPhongMaterial||at.isMeshToonMaterial||at.isMeshLambertMaterial||at.isMeshBasicMaterial||at.isMeshStandardMaterial||at.isShaderMaterial)&&Un.setValue(G,"isOrthographic",Ne.isOrthographicCamera===!0),I!==Ne&&(I=Ne,Gn=!0,pi=!0)}if(et.isSkinnedMesh){Un.setOptional(G,et,"bindMatrix"),Un.setOptional(G,et,"bindMatrixInverse");const Fr=et.skeleton;Fr&&(Fr.boneTexture===null&&Fr.computeBoneTexture(),Un.setValue(G,"boneTexture",Fr.boneTexture,me))}et.isBatchedMesh&&(Un.setOptional(G,et,"batchingTexture"),Un.setValue(G,"batchingTexture",et._matricesTexture,me),Un.setOptional(G,et,"batchingIdTexture"),Un.setValue(G,"batchingIdTexture",et._indirectTexture,me),Un.setOptional(G,et,"batchingColorTexture"),et._colorsTexture!==null&&Un.setValue(G,"batchingColorTexture",et._colorsTexture,me));const ua=nt.morphAttributes;if((ua.position!==void 0||ua.normal!==void 0||ua.color!==void 0)&&Re.update(et,nt,or),(Gn||rn.receiveShadow!==et.receiveShadow)&&(rn.receiveShadow=et.receiveShadow,Un.setValue(G,"receiveShadow",et.receiveShadow)),at.isMeshGouraudMaterial&&at.envMap!==null&&(vr.envMap.value=He,vr.flipEnvMap.value=He.isCubeTexture&&He.isRenderTargetTexture===!1?-1:1),at.isMeshStandardMaterial&&at.envMap===null&&Ye.environment!==null&&(vr.envMapIntensity.value=Ye.environmentIntensity),vr.dfgLUT!==void 0&&(vr.dfgLUT.value=FNe()),Gn&&(Un.setValue(G,"toneMappingExposure",T.toneMappingExposure),rn.needsLights&&Ae(vr,pi),vt&&at.fog===!0&&xe.refreshFogUniforms(vr,vt),xe.refreshMaterialUniforms(vr,at,oe,ue,k.state.transmissionRenderTarget[Ne.id]),PN.upload(G,ut(rn),vr,me)),at.isShaderMaterial&&at.uniformsNeedUpdate===!0&&(PN.upload(G,ut(rn),vr,me),at.uniformsNeedUpdate=!1),at.isSpriteMaterial&&Un.setValue(G,"center",et.center),Un.setValue(G,"modelViewMatrix",et.modelViewMatrix),Un.setValue(G,"normalMatrix",et.normalMatrix),Un.setValue(G,"modelMatrix",et.matrixWorld),at.isShaderMaterial||at.isRawShaderMaterial){const Fr=at.uniformsGroups;for(let ba=0,Mi=Fr.length;ba<Mi;ba++){const Ki=Fr[ba];it.update(Ki,or),it.bind(Ki,or)}}return or}function Ae(Ne,Ye){Ne.ambientLightColor.needsUpdate=Ye,Ne.lightProbe.needsUpdate=Ye,Ne.directionalLights.needsUpdate=Ye,Ne.directionalLightShadows.needsUpdate=Ye,Ne.pointLights.needsUpdate=Ye,Ne.pointLightShadows.needsUpdate=Ye,Ne.spotLights.needsUpdate=Ye,Ne.spotLightShadows.needsUpdate=Ye,Ne.rectAreaLights.needsUpdate=Ye,Ne.hemisphereLights.needsUpdate=Ye}function Ge(Ne){return Ne.isMeshLambertMaterial||Ne.isMeshToonMaterial||Ne.isMeshPhongMaterial||Ne.isMeshStandardMaterial||Ne.isShadowMaterial||Ne.isShaderMaterial&&Ne.lights===!0}this.getActiveCubeFace=function(){return F},this.getActiveMipmapLevel=function(){return _},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(Ne,Ye,nt){const at=de.get(Ne);at.__autoAllocateDepthBuffer=Ne.resolveDepthBuffer===!1,at.__autoAllocateDepthBuffer===!1&&(at.__useRenderToTexture=!1),de.get(Ne.texture).__webglTexture=Ye,de.get(Ne.depthTexture).__webglTexture=at.__autoAllocateDepthBuffer?void 0:nt,at.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(Ne,Ye){const nt=de.get(Ne);nt.__webglFramebuffer=Ye,nt.__useDefaultFramebuffer=Ye===void 0};const Je=G.createFramebuffer();this.setRenderTarget=function(Ne,Ye=0,nt=0){M=Ne,F=Ye,_=nt;let at=!0,et=null,vt=!1,wt=!1;if(Ne){const He=de.get(Ne);if(He.__useDefaultFramebuffer!==void 0)te.bindFramebuffer(G.FRAMEBUFFER,null),at=!1;else if(He.__webglFramebuffer===void 0)me.setupRenderTarget(Ne);else if(He.__hasExternalTextures)me.rebindTextures(Ne,de.get(Ne.texture).__webglTexture,de.get(Ne.depthTexture).__webglTexture);else if(Ne.depthBuffer){const qe=Ne.depthTexture;if(He.__boundDepthTexture!==qe){if(qe!==null&&de.has(qe)&&(Ne.width!==qe.image.width||Ne.height!==qe.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");me.setupDepthRenderbuffer(Ne)}}const Dt=Ne.texture;(Dt.isData3DTexture||Dt.isDataArrayTexture||Dt.isCompressedArrayTexture)&&(wt=!0);const Rt=de.get(Ne).__webglFramebuffer;Ne.isWebGLCubeRenderTarget?(Array.isArray(Rt[Ye])?et=Rt[Ye][nt]:et=Rt[Ye],vt=!0):Ne.samples>0&&me.useMultisampledRTT(Ne)===!1?et=de.get(Ne).__webglMultisampledFramebuffer:Array.isArray(Rt)?et=Rt[nt]:et=Rt,z.copy(Ne.viewport),L.copy(Ne.scissor),Z=Ne.scissorTest}else z.copy(pe).multiplyScalar(oe).floor(),L.copy(he).multiplyScalar(oe).floor(),Z=we;if(nt!==0&&(et=Je),te.bindFramebuffer(G.FRAMEBUFFER,et)&&at&&te.drawBuffers(Ne,et),te.viewport(z),te.scissor(L),te.setScissorTest(Z),vt){const He=de.get(Ne.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+Ye,He.__webglTexture,nt)}else if(wt){const He=Ye;for(let Dt=0;Dt<Ne.textures.length;Dt++){const Rt=de.get(Ne.textures[Dt]);G.framebufferTextureLayer(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0+Dt,Rt.__webglTexture,nt,He)}}else if(Ne!==null&&nt!==0){const He=de.get(Ne.texture);G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,He.__webglTexture,nt)}H=-1},this.readRenderTargetPixels=function(Ne,Ye,nt,at,et,vt,wt,Ue=0){if(!(Ne&&Ne.isWebGLRenderTarget)){di("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let He=de.get(Ne).__webglFramebuffer;if(Ne.isWebGLCubeRenderTarget&&wt!==void 0&&(He=He[wt]),He){te.bindFramebuffer(G.FRAMEBUFFER,He);try{const Dt=Ne.textures[Ue],Rt=Dt.format,qe=Dt.type;if(!se.textureFormatReadable(Rt)){di("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!se.textureTypeReadable(qe)){di("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Ye>=0&&Ye<=Ne.width-at&&nt>=0&&nt<=Ne.height-et&&(Ne.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+Ue),G.readPixels(Ye,nt,at,et,st.convert(Rt),st.convert(qe),vt))}finally{const Dt=M!==null?de.get(M).__webglFramebuffer:null;te.bindFramebuffer(G.FRAMEBUFFER,Dt)}}},this.readRenderTargetPixelsAsync=async function(Ne,Ye,nt,at,et,vt,wt,Ue=0){if(!(Ne&&Ne.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let He=de.get(Ne).__webglFramebuffer;if(Ne.isWebGLCubeRenderTarget&&wt!==void 0&&(He=He[wt]),He)if(Ye>=0&&Ye<=Ne.width-at&&nt>=0&&nt<=Ne.height-et){te.bindFramebuffer(G.FRAMEBUFFER,He);const Dt=Ne.textures[Ue],Rt=Dt.format,qe=Dt.type;if(!se.textureFormatReadable(Rt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!se.textureTypeReadable(qe))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Ke=G.createBuffer();G.bindBuffer(G.PIXEL_PACK_BUFFER,Ke),G.bufferData(G.PIXEL_PACK_BUFFER,vt.byteLength,G.STREAM_READ),Ne.textures.length>1&&G.readBuffer(G.COLOR_ATTACHMENT0+Ue),G.readPixels(Ye,nt,at,et,st.convert(Rt),st.convert(qe),0);const Bt=M!==null?de.get(M).__webglFramebuffer:null;te.bindFramebuffer(G.FRAMEBUFFER,Bt);const Qt=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return G.flush(),await rwe(G,Qt,4),G.bindBuffer(G.PIXEL_PACK_BUFFER,Ke),G.getBufferSubData(G.PIXEL_PACK_BUFFER,0,vt),G.deleteBuffer(Ke),G.deleteSync(Qt),vt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(Ne,Ye=null,nt=0){const at=Math.pow(2,-nt),et=Math.floor(Ne.image.width*at),vt=Math.floor(Ne.image.height*at),wt=Ye!==null?Ye.x:0,Ue=Ye!==null?Ye.y:0;me.setTexture2D(Ne,0),G.copyTexSubImage2D(G.TEXTURE_2D,nt,0,0,wt,Ue,et,vt),te.unbindTexture()};const De=G.createFramebuffer(),mt=G.createFramebuffer();this.copyTextureToTexture=function(Ne,Ye,nt=null,at=null,et=0,vt=null){vt===null&&(et!==0?(Uw("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),vt=et,et=0):vt=0);let wt,Ue,He,Dt,Rt,qe,Ke,Bt,Qt;const dn=Ne.isCompressedTexture?Ne.mipmaps[vt]:Ne.image;if(nt!==null)wt=nt.max.x-nt.min.x,Ue=nt.max.y-nt.min.y,He=nt.isBox3?nt.max.z-nt.min.z:1,Dt=nt.min.x,Rt=nt.min.y,qe=nt.isBox3?nt.min.z:0;else{const ua=Math.pow(2,-et);wt=Math.floor(dn.width*ua),Ue=Math.floor(dn.height*ua),Ne.isDataArrayTexture?He=dn.depth:Ne.isData3DTexture?He=Math.floor(dn.depth*ua):He=1,Dt=0,Rt=0,qe=0}at!==null?(Ke=at.x,Bt=at.y,Qt=at.z):(Ke=0,Bt=0,Qt=0);const nn=st.convert(Ye.format),rn=st.convert(Ye.type);let yn;Ye.isData3DTexture?(me.setTexture3D(Ye,0),yn=G.TEXTURE_3D):Ye.isDataArrayTexture||Ye.isCompressedArrayTexture?(me.setTexture2DArray(Ye,0),yn=G.TEXTURE_2D_ARRAY):(me.setTexture2D(Ye,0),yn=G.TEXTURE_2D),G.pixelStorei(G.UNPACK_FLIP_Y_WEBGL,Ye.flipY),G.pixelStorei(G.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Ye.premultiplyAlpha),G.pixelStorei(G.UNPACK_ALIGNMENT,Ye.unpackAlignment);const Mn=G.getParameter(G.UNPACK_ROW_LENGTH),or=G.getParameter(G.UNPACK_IMAGE_HEIGHT),Dr=G.getParameter(G.UNPACK_SKIP_PIXELS),Gn=G.getParameter(G.UNPACK_SKIP_ROWS),pi=G.getParameter(G.UNPACK_SKIP_IMAGES);G.pixelStorei(G.UNPACK_ROW_LENGTH,dn.width),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,dn.height),G.pixelStorei(G.UNPACK_SKIP_PIXELS,Dt),G.pixelStorei(G.UNPACK_SKIP_ROWS,Rt),G.pixelStorei(G.UNPACK_SKIP_IMAGES,qe);const Un=Ne.isDataArrayTexture||Ne.isData3DTexture,vr=Ye.isDataArrayTexture||Ye.isData3DTexture;if(Ne.isDepthTexture){const ua=de.get(Ne),Fr=de.get(Ye),ba=de.get(ua.__renderTarget),Mi=de.get(Fr.__renderTarget);te.bindFramebuffer(G.READ_FRAMEBUFFER,ba.__webglFramebuffer),te.bindFramebuffer(G.DRAW_FRAMEBUFFER,Mi.__webglFramebuffer);for(let Ki=0;Ki<He;Ki++)Un&&(G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,de.get(Ne).__webglTexture,et,qe+Ki),G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,de.get(Ye).__webglTexture,vt,Qt+Ki)),G.blitFramebuffer(Dt,Rt,wt,Ue,Ke,Bt,wt,Ue,G.DEPTH_BUFFER_BIT,G.NEAREST);te.bindFramebuffer(G.READ_FRAMEBUFFER,null),te.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else if(et!==0||Ne.isRenderTargetTexture||de.has(Ne)){const ua=de.get(Ne),Fr=de.get(Ye);te.bindFramebuffer(G.READ_FRAMEBUFFER,De),te.bindFramebuffer(G.DRAW_FRAMEBUFFER,mt);for(let ba=0;ba<He;ba++)Un?G.framebufferTextureLayer(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,ua.__webglTexture,et,qe+ba):G.framebufferTexture2D(G.READ_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,ua.__webglTexture,et),vr?G.framebufferTextureLayer(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,Fr.__webglTexture,vt,Qt+ba):G.framebufferTexture2D(G.DRAW_FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_2D,Fr.__webglTexture,vt),et!==0?G.blitFramebuffer(Dt,Rt,wt,Ue,Ke,Bt,wt,Ue,G.COLOR_BUFFER_BIT,G.NEAREST):vr?G.copyTexSubImage3D(yn,vt,Ke,Bt,Qt+ba,Dt,Rt,wt,Ue):G.copyTexSubImage2D(yn,vt,Ke,Bt,Dt,Rt,wt,Ue);te.bindFramebuffer(G.READ_FRAMEBUFFER,null),te.bindFramebuffer(G.DRAW_FRAMEBUFFER,null)}else vr?Ne.isDataTexture||Ne.isData3DTexture?G.texSubImage3D(yn,vt,Ke,Bt,Qt,wt,Ue,He,nn,rn,dn.data):Ye.isCompressedArrayTexture?G.compressedTexSubImage3D(yn,vt,Ke,Bt,Qt,wt,Ue,He,nn,dn.data):G.texSubImage3D(yn,vt,Ke,Bt,Qt,wt,Ue,He,nn,rn,dn):Ne.isDataTexture?G.texSubImage2D(G.TEXTURE_2D,vt,Ke,Bt,wt,Ue,nn,rn,dn.data):Ne.isCompressedTexture?G.compressedTexSubImage2D(G.TEXTURE_2D,vt,Ke,Bt,dn.width,dn.height,nn,dn.data):G.texSubImage2D(G.TEXTURE_2D,vt,Ke,Bt,wt,Ue,nn,rn,dn);G.pixelStorei(G.UNPACK_ROW_LENGTH,Mn),G.pixelStorei(G.UNPACK_IMAGE_HEIGHT,or),G.pixelStorei(G.UNPACK_SKIP_PIXELS,Dr),G.pixelStorei(G.UNPACK_SKIP_ROWS,Gn),G.pixelStorei(G.UNPACK_SKIP_IMAGES,pi),vt===0&&Ye.generateMipmaps&&G.generateMipmap(yn),te.unbindTexture()},this.initRenderTarget=function(Ne){de.get(Ne).__webglFramebuffer===void 0&&me.setupRenderTarget(Ne)},this.initTexture=function(Ne){Ne.isCubeTexture?me.setTextureCube(Ne,0):Ne.isData3DTexture?me.setTexture3D(Ne,0):Ne.isDataArrayTexture||Ne.isCompressedArrayTexture?me.setTexture2DArray(Ne,0):me.setTexture2D(Ne,0),te.unbindTexture()},this.resetState=function(){F=0,_=0,M=null,te.reset(),Ee.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Jd}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=Or._getDrawingBufferColorSpace(e),n.unpackColorSpace=Or._getUnpackColorSpace()}};const Eq={type:"change"},KO={type:"start"},QJ={type:"end"},Yk=new HO,Dq=new rh,RNe=Math.cos(70*iwe.DEG2RAD),Ri=new Lt,Uo=2*Math.PI,oa={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},qE=1e-6;class INe extends Kwe{constructor(e,n=null){super(e,n),this.state=oa.NONE,this.target=new Lt,this.cursor=new Lt,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:ry.ROTATE,MIDDLE:ry.DOLLY,RIGHT:ry.PAN},this.touches={ONE:Gx.ROTATE,TWO:Gx.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new Lt,this._lastQuaternion=new Rg,this._lastTargetPosition=new Lt,this._quat=new Rg().setFromUnitVectors(e.up,new Lt(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new oq,this._sphericalDelta=new oq,this._scale=1,this._panOffset=new Lt,this._rotateStart=new ir,this._rotateEnd=new ir,this._rotateDelta=new ir,this._panStart=new ir,this._panEnd=new ir,this._panDelta=new ir,this._dollyStart=new ir,this._dollyEnd=new ir,this._dollyDelta=new ir,this._dollyDirection=new Lt,this._mouse=new ir,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=zNe.bind(this),this._onPointerDown=ONe.bind(this),this._onPointerUp=UNe.bind(this),this._onContextMenu=WNe.bind(this),this._onMouseWheel=qNe.bind(this),this._onKeyDown=$Ne.bind(this),this._onTouchStart=VNe.bind(this),this._onTouchMove=GNe.bind(this),this._onMouseDown=BNe.bind(this),this._onMouseMove=HNe.bind(this),this._interceptControlDown=KNe.bind(this),this._interceptControlUp=QNe.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(Eq),this.update(),this.state=oa.NONE}update(e=null){const n=this.object.position;Ri.copy(n).sub(this.target),Ri.applyQuaternion(this._quat),this._spherical.setFromVector3(Ri),this.autoRotate&&this.state===oa.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 a=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(a)&&isFinite(i)&&(a<-Math.PI?a+=Uo:a>Math.PI&&(a-=Uo),i<-Math.PI?i+=Uo:i>Math.PI&&(i-=Uo),a<=i?this._spherical.theta=Math.max(a,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(a+i)/2?Math.max(a,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(Ri.setFromSpherical(this._spherical),Ri.applyQuaternion(this._quatInverse),n.copy(this.target).add(Ri),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=Ri.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 Lt(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 Lt(this._mouse.x,this._mouse.y,0);d.unproject(this.object),this.object.position.sub(d).add(l),this.object.updateMatrixWorld(),o=Ri.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):(Yk.origin.copy(this.object.position),Yk.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Yk.direction))<RNe?this.object.lookAt(this.target):(Dq.setFromNormalAndCoplanarPoint(this.object.up,this.target),Yk.intersectPlane(Dq,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)>qE||8*(1-this._lastQuaternion.dot(this.object.quaternion))>qE||this._lastTargetPosition.distanceToSquared(this.target)>qE?(this.dispatchEvent(Eq),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Uo/60*this.autoRotateSpeed*e:Uo/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){Ri.setFromMatrixColumn(n,0),Ri.multiplyScalar(-e),this._panOffset.add(Ri)}_panUp(e,n){this.screenSpacePanning===!0?Ri.setFromMatrixColumn(n,1):(Ri.setFromMatrixColumn(n,0),Ri.crossVectors(this.object.up,Ri)),Ri.multiplyScalar(e),this._panOffset.add(Ri)}_pan(e,n){const a=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;Ri.copy(i).sub(this.target);let s=Ri.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/a.clientHeight,this.object.matrix),this._panUp(2*n*s/a.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/a.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/a.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 a=this.domElement.getBoundingClientRect(),i=e-a.left,s=n-a.top,o=a.width,l=a.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(Uo*this._rotateDelta.x/n.clientHeight),this._rotateUp(Uo*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(Uo*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(-Uo*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(Uo*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(-Uo*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),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._rotateStart.set(a,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panStart.set(a,i)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),a=e.pageX-n.x,i=e.pageY-n.y,s=Math.sqrt(a*a+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 a=this._getSecondPointerPosition(e),i=.5*(e.pageX+a.x),s=.5*(e.pageY+a.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Uo*this._rotateDelta.x/n.clientHeight),this._rotateUp(Uo*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),a=.5*(e.pageX+n.x),i=.5*(e.pageY+n.y);this._panEnd.set(a,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),a=e.pageX-n.x,i=e.pageY-n.y,s=Math.sqrt(a*a+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 ir,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,a={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(n){case 1:a.deltaY*=16;break;case 2:a.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(a.deltaY*=10),a}}function ONe(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 zNe(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function UNe(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(QJ),this.state=oa.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 BNe(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 ry.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=oa.DOLLY;break;case ry.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=oa.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=oa.ROTATE}break;case ry.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=oa.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=oa.PAN}break;default:this.state=oa.NONE}this.state!==oa.NONE&&this.dispatchEvent(KO)}function HNe(t){switch(this.state){case oa.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case oa.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case oa.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function qNe(t){this.enabled===!1||this.enableZoom===!1||this.state!==oa.NONE||(t.preventDefault(),this.dispatchEvent(KO),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(QJ))}function $Ne(t){this.enabled!==!1&&this._handleKeyDown(t)}function VNe(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case Gx.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=oa.TOUCH_ROTATE;break;case Gx.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=oa.TOUCH_PAN;break;default:this.state=oa.NONE}break;case 2:switch(this.touches.TWO){case Gx.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=oa.TOUCH_DOLLY_PAN;break;case Gx.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=oa.TOUCH_DOLLY_ROTATE;break;default:this.state=oa.NONE}break;default:this.state=oa.NONE}this.state!==oa.NONE&&this.dispatchEvent(KO)}function GNe(t){switch(this._trackPointer(t),this.state){case oa.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case oa.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case oa.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case oa.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=oa.NONE}}function WNe(t){this.enabled!==!1&&t.preventDefault()}function KNe(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function QNe(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function YNe(t,e=!1){const n=t[0].index!==null,a=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(!a.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!==a.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 g=0;g<f.count;++g)m.push(f.getX(g)+u);u+=t[p].attributes.position.count}c.setIndex(m)}for(const u in s){const m=Fq(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 w=0;w<o[u].length;++w)f.push(o[u][w][p]);const g=Fq(f);if(!g)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+u+" morphAttribute."),null;c.morphAttributes[u].push(g)}}return c}function Fq(t){let e,n,a,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(a===void 0&&(a=u.normalized),a!==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 wo(o,n,a);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 g=0;g<n;g++){const w=u.getComponent(p,g);l.setComponent(p+m,g,w)}}else o.set(u.array,c);c+=u.count*n}return i!==void 0&&(l.gpuType=i),l}class XNe extends WO{constructor(e){super(e)}load(e,n,a,i){const s=this,o=new Hwe(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)}},a,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 g=[115,111,108,105,100];for(let w=0;w<5;w++)if(a(g,u,w))return!1;return!0}function a(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,g,w=!1,b,x,S,k,C;for(let H=0;H<70;H++)u.getUint32(H,!1)==1129270351&&u.getUint8(H+4)==82&&u.getUint8(H+5)==61&&(w=!0,b=new Float32Array(m*3*3),x=u.getUint8(H+6)/255,S=u.getUint8(H+7)/255,k=u.getUint8(H+8)/255,C=u.getUint8(H+9)/255);const P=84,T=50,A=new Sc,F=new Float32Array(m*3*3),_=new Float32Array(m*3*3),M=new cr;for(let H=0;H<m;H++){const I=P+H*T,z=u.getFloat32(I,!0),L=u.getFloat32(I+4,!0),Z=u.getFloat32(I+8,!0);if(w){const ne=u.getUint16(I+48,!0);(ne&32768)===0?(p=(ne&31)/31,f=(ne>>5&31)/31,g=(ne>>10&31)/31):(p=x,f=S,g=k)}for(let ne=1;ne<=3;ne++){const Y=I+ne*12,ce=H*3*3+(ne-1)*3;F[ce]=u.getFloat32(Y,!0),F[ce+1]=u.getFloat32(Y+4,!0),F[ce+2]=u.getFloat32(Y+8,!0),_[ce]=z,_[ce+1]=L,_[ce+2]=Z,w&&(M.setRGB(p,f,g,fl),b[ce]=M.r,b[ce+1]=M.g,b[ce+2]=M.b)}}return A.setAttribute("position",new wo(F,3)),A.setAttribute("normal",new wo(_,3)),w&&(A.setAttribute("color",new wo(b,3)),A.hasColors=!0,A.alpha=C),A}function s(d){const u=new Sc,m=/solid([\s\S]*?)endsolid/g,p=/facet([\s\S]*?)endfacet/g,f=/solid\s(.+)/;let g=0;const w=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,b=new RegExp("vertex"+w+w+w,"g"),x=new RegExp("normal"+w+w+w,"g"),S=[],k=[],C=[],P=new Lt;let T,A=0,F=0,_=0;for(;(T=m.exec(d))!==null;){F=_;const M=T[0],H=(T=f.exec(M))!==null?T[1]:"";for(C.push(H);(T=p.exec(M))!==null;){let L=0,Z=0;const ne=T[0];for(;(T=x.exec(ne))!==null;)P.x=parseFloat(T[1]),P.y=parseFloat(T[2]),P.z=parseFloat(T[3]),Z++;for(;(T=b.exec(ne))!==null;)S.push(parseFloat(T[1]),parseFloat(T[2]),parseFloat(T[3])),k.push(P.x,P.y,P.z),L++,_++;Z!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+g),L!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+g),g++}const I=F,z=_-F;u.userData.groupNames=C,u.addGroup(I,z,A),A++}return u.setAttribute("position",new Sl(S,3)),u.setAttribute("normal",new Sl(k,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 Xk(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 $E={exports:{}};var Lq;function ZNe(){return Lq||(Lq=1,(function(t,e){(function(n){t.exports=n()})(function(){return(function n(a,i,s){function o(d,u){if(!i[d]){if(!a[d]){var m=typeof Xk=="function"&&Xk;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:{}};a[d][0].call(f.exports,function(g){var w=a[d][1][g];return o(w||g)},f,f.exports,n,a,i,s)}return i[d].exports}for(var l=typeof Xk=="function"&&Xk,c=0;c<s.length;c++)o(s[c]);return o})({1:[function(n,a,i){var s=n("./utils"),o=n("./support"),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(c){for(var d,u,m,p,f,g,w,b=[],x=0,S=c.length,k=S,C=s.getTypeOf(c)!=="string";x<c.length;)k=S-x,m=C?(d=c[x++],u=x<S?c[x++]:0,x<S?c[x++]:0):(d=c.charCodeAt(x++),u=x<S?c.charCodeAt(x++):0,x<S?c.charCodeAt(x++):0),p=d>>2,f=(3&d)<<4|u>>4,g=1<k?(15&u)<<2|m>>6:64,w=2<k?63&m:64,b.push(l.charAt(p)+l.charAt(f)+l.charAt(g)+l.charAt(w));return b.join("")},i.decode=function(c){var d,u,m,p,f,g,w=0,b=0,x="data:";if(c.substr(0,x.length)===x)throw new Error("Invalid base64 input, it looks like a data url.");var S,k=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===l.charAt(64)&&k--,c.charAt(c.length-2)===l.charAt(64)&&k--,k%1!=0)throw new Error("Invalid base64 input, bad content length.");for(S=o.uint8array?new Uint8Array(0|k):new Array(0|k);w<c.length;)d=l.indexOf(c.charAt(w++))<<2|(p=l.indexOf(c.charAt(w++)))>>4,u=(15&p)<<4|(f=l.indexOf(c.charAt(w++)))>>2,m=(3&f)<<6|(g=l.indexOf(c.charAt(w++))),S[b++]=d,f!==64&&(S[b++]=u),g!==64&&(S[b++]=m);return S}},{"./support":30,"./utils":32}],2:[function(n,a,i){var s=n("./external"),o=n("./stream/DataWorker"),l=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,m,p,f,g){this.compressedSize=u,this.uncompressedSize=m,this.crc32=p,this.compression=f,this.compressedContent=g}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)},a.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,a,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,a,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})();a.exports=function(l,c){return l!==void 0&&l.length?s.getTypeOf(l)!=="string"?(function(d,u,m,p){var f=o,g=p+m;d^=-1;for(var w=p;w<g;w++)d=d>>>8^f[255&(d^u[w])];return-1^d})(0|c,l,l.length,0):(function(d,u,m,p){var f=o,g=p+m;d^=-1;for(var w=p;w<g;w++)d=d>>>8^f[255&(d^u.charCodeAt(w))];return-1^d})(0|c,l,l.length,0):0}},{"./utils":32}],5:[function(n,a,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,a,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),a.exports={Promise:s}},{lie:37}],7:[function(n,a,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,a,i){function s(f,g){var w,b="";for(w=0;w<g;w++)b+=String.fromCharCode(255&f),f>>>=8;return b}function o(f,g,w,b,x,S){var k,C,P=f.file,T=f.compression,A=S!==d.utf8encode,F=l.transformTo("string",S(P.name)),_=l.transformTo("string",d.utf8encode(P.name)),M=P.comment,H=l.transformTo("string",S(M)),I=l.transformTo("string",d.utf8encode(M)),z=_.length!==P.name.length,L=I.length!==M.length,Z="",ne="",Y="",ce=P.dir,ue=P.date,oe={crc32:0,compressedSize:0,uncompressedSize:0};g&&!w||(oe.crc32=f.crc32,oe.compressedSize=f.compressedSize,oe.uncompressedSize=f.uncompressedSize);var Q=0;g&&(Q|=8),A||!z&&!L||(Q|=2048);var le=0,pe=0;ce&&(le|=16),x==="UNIX"?(pe=798,le|=(function(we,$){var J=we;return we||(J=$?16893:33204),(65535&J)<<16})(P.unixPermissions,ce)):(pe=20,le|=(function(we){return 63&(we||0)})(P.dosPermissions)),k=ue.getUTCHours(),k<<=6,k|=ue.getUTCMinutes(),k<<=5,k|=ue.getUTCSeconds()/2,C=ue.getUTCFullYear()-1980,C<<=4,C|=ue.getUTCMonth()+1,C<<=5,C|=ue.getUTCDate(),z&&(ne=s(1,1)+s(u(F),4)+_,Z+="up"+s(ne.length,2)+ne),L&&(Y=s(1,1)+s(u(H),4)+I,Z+="uc"+s(Y.length,2)+Y);var he="";return he+=`
  3863. \0`,he+=s(Q,2),he+=T.magic,he+=s(k,2),he+=s(C,2),he+=s(oe.crc32,4),he+=s(oe.compressedSize,4),he+=s(oe.uncompressedSize,4),he+=s(F.length,2),he+=s(Z.length,2),{fileRecord:m.LOCAL_FILE_HEADER+he+F+Z,dirRecord:m.CENTRAL_FILE_HEADER+s(pe,2)+he+s(H.length,2)+"\0\0\0\0"+s(le,4)+s(b,4)+F+Z+H}}var l=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),m=n("../signature");function p(f,g,w,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=w,this.encodeFileName=b,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 g=f.meta.percent||0,w=this.entriesCount,b=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:w?(g+100*(w-b-1))/w:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var w=o(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:w.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,w=o(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(w.dirRecord),g)this.push({data:(function(b){return m.DATA_DESCRIPTOR+s(b.crc32,4)+s(b.compressedSize,4)+s(b.uncompressedSize,4)})(f),meta:{percent:100}});else for(this.push({data:w.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var w=this.bytesWritten-f,b=(function(x,S,k,C,P){var T=l.transformTo("string",P(C));return m.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(x,2)+s(x,2)+s(S,4)+s(k,4)+s(T.length,2)+T})(this.dirRecords.length,w,f,this.zipComment,this.encodeFileName);this.push({data:b,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 g=this;return f.on("data",function(w){g.processChunk(w)}),f.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),f.on("error",function(w){g.error(w)}),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 g=this._sources;if(!c.prototype.error.call(this,f))return!1;for(var w=0;w<g.length;w++)try{g[w].error(f)}catch{}return!0},p.prototype.lock=function(){c.prototype.lock.call(this);for(var f=this._sources,g=0;g<f.length;g++)f[g].lock()},a.exports=p},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,a,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 g=(function(S,k){var C=S||k,P=s[C];if(!P)throw new Error(C+" is not a valid compression method !");return P})(f.options.compression,c.compression),w=f.options.compressionOptions||c.compressionOptions||{},b=f.dir,x=f.date;f._compressWorker(g,w).withStreamInfo("file",{name:p,dir:b,date:x,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,a,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"),a.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,a,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,g){var w=p.decompressed.getContentWorker().pipe(new d);w.on("error",function(b){g(b)}).on("end",function(){w.streamInfo.crc32!==p.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):f()}).resume()})}a.exports=function(p,f){var g=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(w){var b=new c(f);return b.load(w),b}).then(function(w){var b=[o.Promise.resolve(w)],x=w.files;if(f.checkCRC32)for(var S=0;S<x.length;S++)b.push(m(x[S]));return o.Promise.all(b)}).then(function(w){for(var b=w.shift(),x=b.files,S=0;S<x.length;S++){var k=x[S],C=k.fileNameStr,P=s.resolve(k.fileNameStr);g.file(P,k.decompressed,{binary:!0,optimizedBinaryString:!0,date:k.date,dir:k.dir,comment:k.fileCommentStr.length?k.fileCommentStr:null,unixPermissions:k.unixPermissions,dosPermissions:k.dosPermissions,createFolders:f.createFolders}),k.dir||(g.file(P).unsafeOriginalName=C)}return b.zipComment.length&&(g.comment=b.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(n,a,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)},a.exports=l},{"../stream/GenericWorker":28,"../utils":32}],13:[function(n,a,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()},a.exports=o},{"../utils":32,"readable-stream":16}],14:[function(n,a,i){a.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,a,i){function s(P,T,A){var F,_=l.getTypeOf(T),M=l.extend(A||{},u);M.date=M.date||new Date,M.compression!==null&&(M.compression=M.compression.toUpperCase()),typeof M.unixPermissions=="string"&&(M.unixPermissions=parseInt(M.unixPermissions,8)),M.unixPermissions&&16384&M.unixPermissions&&(M.dir=!0),M.dosPermissions&&16&M.dosPermissions&&(M.dir=!0),M.dir&&(P=x(P)),M.createFolders&&(F=b(P))&&S.call(this,F,!0);var H=_==="string"&&M.binary===!1&&M.base64===!1;A&&A.binary!==void 0||(M.binary=!H),(T instanceof m&&T.uncompressedSize===0||M.dir||!T||T.length===0)&&(M.base64=!1,M.binary=!0,T="",M.compression="STORE",_="string");var I=null;I=T instanceof m||T instanceof c?T:g.isNode&&g.isStream(T)?new w(P,T):l.prepareContent(P,T,M.binary,M.optimizedBinaryString,M.base64);var z=new p(P,I,M);this.files[P]=z}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"),g=n("./nodejsUtils"),w=n("./nodejs/NodejsStreamInputAdapter"),b=function(P){P.slice(-1)==="/"&&(P=P.substring(0,P.length-1));var T=P.lastIndexOf("/");return 0<T?P.substring(0,T):""},x=function(P){return P.slice(-1)!=="/"&&(P+="/"),P},S=function(P,T){return T=T!==void 0?T:u.createFolders,P=x(P),this.files[P]||s.call(this,P,null,{dir:!0,createFolders:T}),this.files[P]};function k(P){return Object.prototype.toString.call(P)==="[object RegExp]"}var C={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(P){var T,A,F;for(T in this.files)F=this.files[T],(A=T.slice(this.root.length,T.length))&&T.slice(0,this.root.length)===this.root&&P(A,F)},filter:function(P){var T=[];return this.forEach(function(A,F){P(A,F)&&T.push(F)}),T},file:function(P,T,A){if(arguments.length!==1)return P=this.root+P,s.call(this,P,T,A),this;if(k(P)){var F=P;return this.filter(function(M,H){return!H.dir&&F.test(M)})}var _=this.files[this.root+P];return _&&!_.dir?_:null},folder:function(P){if(!P)return this;if(k(P))return this.filter(function(_,M){return M.dir&&P.test(_)});var T=this.root+P,A=S.call(this,T),F=this.clone();return F.root=A.name,F},remove:function(P){P=this.root+P;var T=this.files[P];if(T||(P.slice(-1)!=="/"&&(P+="/"),T=this.files[P]),T&&!T.dir)delete this.files[P];else for(var A=this.filter(function(_,M){return M.name.slice(0,P.length)===P}),F=0;F<A.length;F++)delete this.files[A[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(P){var T,A={};try{if((A=l.extend(P||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:o.utf8encode})).type=A.type.toLowerCase(),A.compression=A.compression.toUpperCase(),A.type==="binarystring"&&(A.type="string"),!A.type)throw new Error("No output type specified.");l.checkSupport(A.type),A.platform!=="darwin"&&A.platform!=="freebsd"&&A.platform!=="linux"&&A.platform!=="sunos"||(A.platform="UNIX"),A.platform==="win32"&&(A.platform="DOS");var F=A.comment||this.comment||"";T=f.generateWorker(this,A,F)}catch(_){(T=new c("error")).error(_)}return new d(T,A.type||"string",A.mimeType)},generateAsync:function(P,T){return this.generateInternalStream(P).accumulate(T)},generateNodeStream:function(P,T){return(P=P||{}).type||(P.type="nodebuffer"),this.generateInternalStream(P).toNodejsStream(T)}};a.exports=C},{"./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,a,i){a.exports=n("stream")},{stream:void 0}],17:[function(n,a,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},a.exports=o},{"../utils":32,"./DataReader":18}],18:[function(n,a,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))}},a.exports=o},{"../utils":32}],19:[function(n,a,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},a.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,a,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},a.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,a,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},a.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,a,i){var s=n("../utils"),o=n("../support"),l=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");a.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,a,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,a,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})},a.exports=l},{"../utils":32,"./GenericWorker":28}],25:[function(n,a,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)},a.exports=l},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,a,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)},a.exports=l},{"../utils":32,"./GenericWorker":28}],27:[function(n,a,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}})},a.exports=l},{"../utils":32,"./GenericWorker":28}],28:[function(n,a,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}},a.exports=s},{}],29:[function(n,a,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(g,w){return new u.Promise(function(b,x){var S=[],k=g._internalType,C=g._outputType,P=g._mimeType;g.on("data",function(T,A){S.push(T),w&&w(A)}).on("error",function(T){S=[],x(T)}).on("end",function(){try{var T=(function(A,F,_){switch(A){case"blob":return s.newBlob(s.transformTo("arraybuffer",F),_);case"base64":return c.encode(F);default:return s.transformTo(A,F)}})(C,(function(A,F){var _,M=0,H=null,I=0;for(_=0;_<F.length;_++)I+=F[_].length;switch(A){case"string":return F.join("");case"array":return Array.prototype.concat.apply([],F);case"uint8array":for(H=new Uint8Array(I),_=0;_<F.length;_++)H.set(F[_],M),M+=F[_].length;return H;case"nodebuffer":return Buffer.concat(F);default:throw new Error("concat : unsupported type '"+A+"'")}})(k,S),P);b(T)}catch(A){x(A)}S=[]}).resume()})}function f(g,w,b){var x=w;switch(w){case"blob":case"arraybuffer":x="uint8array";break;case"base64":x="string"}try{this._internalType=x,this._outputType=w,this._mimeType=b,s.checkSupport(x),this._worker=g.pipe(new o(x)),g.lock()}catch(S){this._worker=new l("error"),this._worker.error(S)}}f.prototype={accumulate:function(g){return p(this,g)},on:function(g,w){var b=this;return g==="data"?this._worker.on(g,function(x){w.call(b,x.data,x.meta)}):this._worker.on(g,function(){s.delay(w,arguments,b)}),this},resume:function(){return s.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(g){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"},g)}},a.exports=f},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,a,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,a,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(g){var w,b,x,S,k,C=g.length,P=0;for(S=0;S<C;S++)(64512&(b=g.charCodeAt(S)))==55296&&S+1<C&&(64512&(x=g.charCodeAt(S+1)))==56320&&(b=65536+(b-55296<<10)+(x-56320),S++),P+=b<128?1:b<2048?2:b<65536?3:4;for(w=o.uint8array?new Uint8Array(P):new Array(P),S=k=0;k<P;S++)(64512&(b=g.charCodeAt(S)))==55296&&S+1<C&&(64512&(x=g.charCodeAt(S+1)))==56320&&(b=65536+(b-55296<<10)+(x-56320),S++),b<128?w[k++]=b:(b<2048?w[k++]=192|b>>>6:(b<65536?w[k++]=224|b>>>12:(w[k++]=240|b>>>18,w[k++]=128|b>>>12&63),w[k++]=128|b>>>6&63),w[k++]=128|63&b);return w})(f)},i.utf8decode=function(f){return o.nodebuffer?s.transformTo("nodebuffer",f).toString("utf-8"):(function(g){var w,b,x,S,k=g.length,C=new Array(2*k);for(w=b=0;w<k;)if((x=g[w++])<128)C[b++]=x;else if(4<(S=d[x]))C[b++]=65533,w+=S-1;else{for(x&=S===2?31:S===3?15:7;1<S&&w<k;)x=x<<6|63&g[w++],S--;1<S?C[b++]=65533:x<65536?C[b++]=x:(x-=65536,C[b++]=55296|x>>10&1023,C[b++]=56320|1023&x)}return C.length!==b&&(C.subarray?C=C.subarray(0,b):C.length=b),s.applyFromCharCode(C)})(f=s.transformTo(o.uint8array?"uint8array":"array",f))},s.inherits(m,c),m.prototype.processChunk=function(f){var g=s.transformTo(o.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var w=g;(g=new Uint8Array(w.length+this.leftOver.length)).set(this.leftOver,0),g.set(w,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var b=(function(S,k){var C;for((k=k||S.length)>S.length&&(k=S.length),C=k-1;0<=C&&(192&S[C])==128;)C--;return C<0||C===0?k:C+d[S[C]]>k?C:k})(g),x=g;b!==g.length&&(o.uint8array?(x=g.subarray(0,b),this.leftOver=g.subarray(b,g.length)):(x=g.slice(0,b),this.leftOver=g.slice(b,g.length))),this.push({data:i.utf8decode(x),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,a,i){var s=n("./support"),o=n("./base64"),l=n("./nodejsUtils"),c=n("./external");function d(w){return w}function u(w,b){for(var x=0;x<w.length;++x)b[x]=255&w.charCodeAt(x);return b}n("setimmediate"),i.newBlob=function(w,b){i.checkSupport("blob");try{return new Blob([w],{type:b})}catch{try{var x=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return x.append(w),x.getBlob(b)}catch{throw new Error("Bug : can't construct the Blob.")}}};var m={stringifyByChunk:function(w,b,x){var S=[],k=0,C=w.length;if(C<=x)return String.fromCharCode.apply(null,w);for(;k<C;)b==="array"||b==="nodebuffer"?S.push(String.fromCharCode.apply(null,w.slice(k,Math.min(k+x,C)))):S.push(String.fromCharCode.apply(null,w.subarray(k,Math.min(k+x,C)))),k+=x;return S.join("")},stringifyByChar:function(w){for(var b="",x=0;x<w.length;x++)b+=String.fromCharCode(w[x]);return b},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(w){var b=65536,x=i.getTypeOf(w),S=!0;if(x==="uint8array"?S=m.applyCanBeUsed.uint8array:x==="nodebuffer"&&(S=m.applyCanBeUsed.nodebuffer),S)for(;1<b;)try{return m.stringifyByChunk(w,x,b)}catch{b=Math.floor(b/2)}return m.stringifyByChar(w)}function f(w,b){for(var x=0;x<w.length;x++)b[x]=w[x];return b}i.applyFromCharCode=p;var g={};g.string={string:d,array:function(w){return u(w,new Array(w.length))},arraybuffer:function(w){return g.string.uint8array(w).buffer},uint8array:function(w){return u(w,new Uint8Array(w.length))},nodebuffer:function(w){return u(w,l.allocBuffer(w.length))}},g.array={string:p,array:d,arraybuffer:function(w){return new Uint8Array(w).buffer},uint8array:function(w){return new Uint8Array(w)},nodebuffer:function(w){return l.newBufferFrom(w)}},g.arraybuffer={string:function(w){return p(new Uint8Array(w))},array:function(w){return f(new Uint8Array(w),new Array(w.byteLength))},arraybuffer:d,uint8array:function(w){return new Uint8Array(w)},nodebuffer:function(w){return l.newBufferFrom(new Uint8Array(w))}},g.uint8array={string:p,array:function(w){return f(w,new Array(w.length))},arraybuffer:function(w){return w.buffer},uint8array:d,nodebuffer:function(w){return l.newBufferFrom(w)}},g.nodebuffer={string:p,array:function(w){return f(w,new Array(w.length))},arraybuffer:function(w){return g.nodebuffer.uint8array(w).buffer},uint8array:function(w){return f(w,new Uint8Array(w.length))},nodebuffer:d},i.transformTo=function(w,b){if(b=b||"",!w)return b;i.checkSupport(w);var x=i.getTypeOf(b);return g[x][w](b)},i.resolve=function(w){for(var b=w.split("/"),x=[],S=0;S<b.length;S++){var k=b[S];k==="."||k===""&&S!==0&&S!==b.length-1||(k===".."?x.pop():x.push(k))}return x.join("/")},i.getTypeOf=function(w){return typeof w=="string"?"string":Object.prototype.toString.call(w)==="[object Array]"?"array":s.nodebuffer&&l.isBuffer(w)?"nodebuffer":s.uint8array&&w instanceof Uint8Array?"uint8array":s.arraybuffer&&w instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(w){if(!s[w.toLowerCase()])throw new Error(w+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(w){var b,x,S="";for(x=0;x<(w||"").length;x++)S+="\\x"+((b=w.charCodeAt(x))<16?"0":"")+b.toString(16).toUpperCase();return S},i.delay=function(w,b,x){setImmediate(function(){w.apply(x||null,b||[])})},i.inherits=function(w,b){function x(){}x.prototype=b.prototype,w.prototype=new x},i.extend=function(){var w,b,x={};for(w=0;w<arguments.length;w++)for(b in arguments[w])Object.prototype.hasOwnProperty.call(arguments[w],b)&&x[b]===void 0&&(x[b]=arguments[w][b]);return x},i.prepareContent=function(w,b,x,S,k){return c.Promise.resolve(b).then(function(C){return s.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new c.Promise(function(P,T){var A=new FileReader;A.onload=function(F){P(F.target.result)},A.onerror=function(F){T(F.target.error)},A.readAsArrayBuffer(C)}):C}).then(function(C){var P=i.getTypeOf(C);return P?(P==="arraybuffer"?C=i.transformTo("uint8array",C):P==="string"&&(k?C=o.decode(C):x&&S!==!0&&(C=(function(T){return u(T,s.uint8array?new Uint8Array(T.length):new Array(T.length))})(C))),C):c.Promise.reject(new Error("Can't read the data of '"+w+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(n,a,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 g=this.reader.readString(4)===p;return this.reader.setIndex(f),g},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,g=this.zip64EndOfCentralSize-44;0<g;)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 g=p-f;if(0<g)this.isSignature(p,l.CENTRAL_FILE_HEADER)||(this.reader.zero=g);else if(g<0)throw new Error("Corrupted zip: missing "+Math.abs(g)+" bytes.")},prepareReader:function(m){this.reader=s(m)},load:function(m){this.prepareReader(m),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},a.exports=u},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,a,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,g){this.options=f,this.loadOptions=g}p.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(f){var g,w;if(f.skip(22),this.fileNameLength=f.readInt(2),w=f.readInt(2),this.fileName=f.readData(this.fileNameLength),f.skip(w),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((g=(function(b){for(var x in u)if(Object.prototype.hasOwnProperty.call(u,x)&&u[x].magic===b)return u[x];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,g,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 g=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(g),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 g,w,b,x=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4<x;)g=f.readInt(2),w=f.readInt(2),b=f.readData(w),this.extraFields[g]={id:g,length:w,value:b};f.setIndex(x)},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 g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var w=o.transformTo(f,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(w)}var b=this.findExtraFieldUnicodeComment();if(b!==null)this.fileCommentStr=b;else{var x=o.transformTo(f,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(x)}}},findExtraFieldUnicodePath:function(){var f=this.extraFields[28789];if(f){var g=s(f.value);return g.readInt(1)!==1||c(this.fileName)!==g.readInt(4)?null:d.utf8decode(g.readData(f.length-5))}return null},findExtraFieldUnicodeComment:function(){var f=this.extraFields[25461];if(f){var g=s(f.value);return g.readInt(1)!==1||c(this.fileComment)!==g.readInt(4)?null:d.utf8decode(g.readData(f.length-5))}return null}},a.exports=p},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,a,i){function s(g,w,b){this.name=g,this.dir=b.dir,this.date=b.date,this.comment=b.comment,this.unixPermissions=b.unixPermissions,this.dosPermissions=b.dosPermissions,this._data=w,this._dataBinary=b.binary,this.options={compression:b.compression,compressionOptions:b.compressionOptions}}var o=n("./stream/StreamHelper"),l=n("./stream/DataWorker"),c=n("./utf8"),d=n("./compressedObject"),u=n("./stream/GenericWorker");s.prototype={internalStream:function(g){var w=null,b="string";try{if(!g)throw new Error("No output type specified.");var x=(b=g.toLowerCase())==="string"||b==="text";b!=="binarystring"&&b!=="text"||(b="string"),w=this._decompressWorker();var S=!this._dataBinary;S&&!x&&(w=w.pipe(new c.Utf8EncodeWorker)),!S&&x&&(w=w.pipe(new c.Utf8DecodeWorker))}catch(k){(w=new u("error")).error(k)}return new o(w,b,"")},async:function(g,w){return this.internalStream(g).accumulate(w)},nodeStream:function(g,w){return this.internalStream(g||"nodebuffer").toNodejsStream(w)},_compressWorker:function(g,w){if(this._data instanceof d&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var b=this._decompressWorker();return this._dataBinary||(b=b.pipe(new c.Utf8EncodeWorker)),d.createWorkerFrom(b,g,w)},_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;a.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,a,i){(function(s){var o,l,c=s.MutationObserver||s.WebKitMutationObserver;if(c){var d=0,u=new c(g),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 w=s.document.createElement("script");w.onreadystatechange=function(){g(),w.onreadystatechange=null,w.parentNode.removeChild(w),w=null},s.document.documentElement.appendChild(w)}:function(){setTimeout(g,0)};else{var p=new s.MessageChannel;p.port1.onmessage=g,o=function(){p.port2.postMessage(0)}}var f=[];function g(){var w,b;l=!0;for(var x=f.length;x;){for(b=f,f=[],w=-1;++w<x;)b[w]();x=f.length}l=!1}a.exports=function(w){f.push(w)!==1||l||o()}}).call(this,typeof _k<"u"?_k:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,a,i){var s=n("immediate");function o(){}var l={},c=["REJECTED"],d=["FULFILLED"],u=["PENDING"];function m(x){if(typeof x!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,x!==o&&w(this,x)}function p(x,S,k){this.promise=x,typeof S=="function"&&(this.onFulfilled=S,this.callFulfilled=this.otherCallFulfilled),typeof k=="function"&&(this.onRejected=k,this.callRejected=this.otherCallRejected)}function f(x,S,k){s(function(){var C;try{C=S(k)}catch(P){return l.reject(x,P)}C===x?l.reject(x,new TypeError("Cannot resolve promise with itself")):l.resolve(x,C)})}function g(x){var S=x&&x.then;if(x&&(typeof x=="object"||typeof x=="function")&&typeof S=="function")return function(){S.apply(x,arguments)}}function w(x,S){var k=!1;function C(A){k||(k=!0,l.reject(x,A))}function P(A){k||(k=!0,l.resolve(x,A))}var T=b(function(){S(P,C)});T.status==="error"&&C(T.value)}function b(x,S){var k={};try{k.value=x(S),k.status="success"}catch(C){k.status="error",k.value=C}return k}(a.exports=m).prototype.finally=function(x){if(typeof x!="function")return this;var S=this.constructor;return this.then(function(k){return S.resolve(x()).then(function(){return k})},function(k){return S.resolve(x()).then(function(){throw k})})},m.prototype.catch=function(x){return this.then(null,x)},m.prototype.then=function(x,S){if(typeof x!="function"&&this.state===d||typeof S!="function"&&this.state===c)return this;var k=new this.constructor(o);return this.state!==u?f(k,this.state===d?x:S,this.outcome):this.queue.push(new p(k,x,S)),k},p.prototype.callFulfilled=function(x){l.resolve(this.promise,x)},p.prototype.otherCallFulfilled=function(x){f(this.promise,this.onFulfilled,x)},p.prototype.callRejected=function(x){l.reject(this.promise,x)},p.prototype.otherCallRejected=function(x){f(this.promise,this.onRejected,x)},l.resolve=function(x,S){var k=b(g,S);if(k.status==="error")return l.reject(x,k.value);var C=k.value;if(C)w(x,C);else{x.state=d,x.outcome=S;for(var P=-1,T=x.queue.length;++P<T;)x.queue[P].callFulfilled(S)}return x},l.reject=function(x,S){x.state=c,x.outcome=S;for(var k=-1,C=x.queue.length;++k<C;)x.queue[k].callRejected(S);return x},m.resolve=function(x){return x instanceof this?x:l.resolve(new this(o),x)},m.reject=function(x){var S=new this(o);return l.reject(S,x)},m.all=function(x){var S=this;if(Object.prototype.toString.call(x)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=x.length,C=!1;if(!k)return this.resolve([]);for(var P=new Array(k),T=0,A=-1,F=new this(o);++A<k;)_(x[A],A);return F;function _(M,H){S.resolve(M).then(function(I){P[H]=I,++T!==k||C||(C=!0,l.resolve(F,P))},function(I){C||(C=!0,l.reject(F,I))})}},m.race=function(x){var S=this;if(Object.prototype.toString.call(x)!=="[object Array]")return this.reject(new TypeError("must be an array"));var k=x.length,C=!1;if(!k)return this.resolve([]);for(var P=-1,T=new this(o);++P<k;)A=x[P],S.resolve(A).then(function(F){C||(C=!0,l.resolve(T,F))},function(F){C||(C=!0,l.reject(T,F))});var A;return T}},{immediate:36}],38:[function(n,a,i){var s={};(0,n("./lib/utils/common").assign)(s,n("./lib/deflate"),n("./lib/inflate"),n("./lib/zlib/constants")),a.exports=s},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(n,a,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,g=8;function w(x){if(!(this instanceof w))return new w(x);this.options=o.assign({level:p,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:f,to:""},x||{});var S=this.options;S.raw&&0<S.windowBits?S.windowBits=-S.windowBits:S.gzip&&0<S.windowBits&&S.windowBits<16&&(S.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var k=s.deflateInit2(this.strm,S.level,S.method,S.windowBits,S.memLevel,S.strategy);if(k!==m)throw new Error(c[k]);if(S.header&&s.deflateSetHeader(this.strm,S.header),S.dictionary){var C;if(C=typeof S.dictionary=="string"?l.string2buf(S.dictionary):u.call(S.dictionary)==="[object ArrayBuffer]"?new Uint8Array(S.dictionary):S.dictionary,(k=s.deflateSetDictionary(this.strm,C))!==m)throw new Error(c[k]);this._dict_set=!0}}function b(x,S){var k=new w(S);if(k.push(x,!0),k.err)throw k.msg||c[k.err];return k.result}w.prototype.push=function(x,S){var k,C,P=this.strm,T=this.options.chunkSize;if(this.ended)return!1;C=S===~~S?S:S===!0?4:0,typeof x=="string"?P.input=l.string2buf(x):u.call(x)==="[object ArrayBuffer]"?P.input=new Uint8Array(x):P.input=x,P.next_in=0,P.avail_in=P.input.length;do{if(P.avail_out===0&&(P.output=new o.Buf8(T),P.next_out=0,P.avail_out=T),(k=s.deflate(P,C))!==1&&k!==m)return this.onEnd(k),!(this.ended=!0);P.avail_out!==0&&(P.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(l.buf2binstring(o.shrinkBuf(P.output,P.next_out))):this.onData(o.shrinkBuf(P.output,P.next_out)))}while((0<P.avail_in||P.avail_out===0)&&k!==1);return C===4?(k=s.deflateEnd(this.strm),this.onEnd(k),this.ended=!0,k===m):C!==2||(this.onEnd(m),!(P.avail_out=0))},w.prototype.onData=function(x){this.chunks.push(x)},w.prototype.onEnd=function(x){x===m&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=x,this.msg=this.strm.msg},i.Deflate=w,i.deflate=b,i.deflateRaw=function(x,S){return(S=S||{}).raw=!0,b(x,S)},i.gzip=function(x,S){return(S=S||{}).gzip=!0,b(x,S)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,a,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(w){if(!(this instanceof f))return new f(w);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},w||{});var b=this.options;b.raw&&0<=b.windowBits&&b.windowBits<16&&(b.windowBits=-b.windowBits,b.windowBits===0&&(b.windowBits=-15)),!(0<=b.windowBits&&b.windowBits<16)||w&&w.windowBits||(b.windowBits+=32),15<b.windowBits&&b.windowBits<48&&(15&b.windowBits)==0&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new u,this.strm.avail_out=0;var x=s.inflateInit2(this.strm,b.windowBits);if(x!==c.Z_OK)throw new Error(d[x]);this.header=new m,s.inflateGetHeader(this.strm,this.header)}function g(w,b){var x=new f(b);if(x.push(w,!0),x.err)throw x.msg||d[x.err];return x.result}f.prototype.push=function(w,b){var x,S,k,C,P,T,A=this.strm,F=this.options.chunkSize,_=this.options.dictionary,M=!1;if(this.ended)return!1;S=b===~~b?b:b===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof w=="string"?A.input=l.binstring2buf(w):p.call(w)==="[object ArrayBuffer]"?A.input=new Uint8Array(w):A.input=w,A.next_in=0,A.avail_in=A.input.length;do{if(A.avail_out===0&&(A.output=new o.Buf8(F),A.next_out=0,A.avail_out=F),(x=s.inflate(A,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&_&&(T=typeof _=="string"?l.string2buf(_):p.call(_)==="[object ArrayBuffer]"?new Uint8Array(_):_,x=s.inflateSetDictionary(this.strm,T)),x===c.Z_BUF_ERROR&&M===!0&&(x=c.Z_OK,M=!1),x!==c.Z_STREAM_END&&x!==c.Z_OK)return this.onEnd(x),!(this.ended=!0);A.next_out&&(A.avail_out!==0&&x!==c.Z_STREAM_END&&(A.avail_in!==0||S!==c.Z_FINISH&&S!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(k=l.utf8border(A.output,A.next_out),C=A.next_out-k,P=l.buf2string(A.output,k),A.next_out=C,A.avail_out=F-C,C&&o.arraySet(A.output,A.output,k,C,0),this.onData(P)):this.onData(o.shrinkBuf(A.output,A.next_out)))),A.avail_in===0&&A.avail_out===0&&(M=!0)}while((0<A.avail_in||A.avail_out===0)&&x!==c.Z_STREAM_END);return x===c.Z_STREAM_END&&(S=c.Z_FINISH),S===c.Z_FINISH?(x=s.inflateEnd(this.strm),this.onEnd(x),this.ended=!0,x===c.Z_OK):S!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(A.avail_out=0))},f.prototype.onData=function(w){this.chunks.push(w)},f.prototype.onEnd=function(w){w===c.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=w,this.msg=this.strm.msg},i.Inflate=f,i.inflate=g,i.inflateRaw=function(w,b){return(b=b||{}).raw=!0,g(w,b)},i.ungzip=g},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(n,a,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,g;for(d=m=0,u=c.length;d<u;d++)m+=c[d].length;for(g=new Uint8Array(m),d=p=0,u=c.length;d<u;d++)f=c[d],g.set(f,p),p+=f.length;return g}},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,a,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="",g=0;g<p;g++)f+=String.fromCharCode(m[g]);return f}c[254]=c[254]=1,i.string2buf=function(m){var p,f,g,w,b,x=m.length,S=0;for(w=0;w<x;w++)(64512&(f=m.charCodeAt(w)))==55296&&w+1<x&&(64512&(g=m.charCodeAt(w+1)))==56320&&(f=65536+(f-55296<<10)+(g-56320),w++),S+=f<128?1:f<2048?2:f<65536?3:4;for(p=new s.Buf8(S),w=b=0;b<S;w++)(64512&(f=m.charCodeAt(w)))==55296&&w+1<x&&(64512&(g=m.charCodeAt(w+1)))==56320&&(f=65536+(f-55296<<10)+(g-56320),w++),f<128?p[b++]=f:(f<2048?p[b++]=192|f>>>6:(f<65536?p[b++]=224|f>>>12:(p[b++]=240|f>>>18,p[b++]=128|f>>>12&63),p[b++]=128|f>>>6&63),p[b++]=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,g=p.length;f<g;f++)p[f]=m.charCodeAt(f);return p},i.buf2string=function(m,p){var f,g,w,b,x=p||m.length,S=new Array(2*x);for(f=g=0;f<x;)if((w=m[f++])<128)S[g++]=w;else if(4<(b=c[w]))S[g++]=65533,f+=b-1;else{for(w&=b===2?31:b===3?15:7;1<b&&f<x;)w=w<<6|63&m[f++],b--;1<b?S[g++]=65533:w<65536?S[g++]=w:(w-=65536,S[g++]=55296|w>>10&1023,S[g++]=56320|1023&w)}return u(S,g)},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,a,i){a.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,a,i){a.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,a,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})();a.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,a,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,g=-2,w=-1,b=4,x=2,S=8,k=9,C=286,P=30,T=19,A=2*C+1,F=15,_=3,M=258,H=M+_+1,I=42,z=113,L=1,Z=2,ne=3,Y=4;function ce(U,G){return U.msg=u[G],G}function ue(U){return(U<<1)-(4<U?9:0)}function oe(U){for(var G=U.length;0<=--G;)U[G]=0}function Q(U){var G=U.state,K=G.pending;K>U.avail_out&&(K=U.avail_out),K!==0&&(o.arraySet(U.output,G.pending_buf,G.pending_out,K,U.next_out),U.next_out+=K,G.pending_out+=K,U.total_out+=K,U.avail_out-=K,G.pending-=K,G.pending===0&&(G.pending_out=0))}function le(U,G){l._tr_flush_block(U,0<=U.block_start?U.block_start:-1,U.strstart-U.block_start,G),U.block_start=U.strstart,Q(U.strm)}function pe(U,G){U.pending_buf[U.pending++]=G}function he(U,G){U.pending_buf[U.pending++]=G>>>8&255,U.pending_buf[U.pending++]=255&G}function we(U,G){var K,X,se=U.max_chain_length,te=U.strstart,fe=U.prev_length,de=U.nice_match,me=U.strstart>U.w_size-H?U.strstart-(U.w_size-H):0,q=U.window,R=U.w_mask,re=U.prev,be=U.strstart+M,ye=q[te+fe-1],_e=q[te+fe];U.prev_length>=U.good_match&&(se>>=2),de>U.lookahead&&(de=U.lookahead);do if(q[(K=G)+fe]===_e&&q[K+fe-1]===ye&&q[K]===q[te]&&q[++K]===q[te+1]){te+=2,K++;do;while(q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&q[++te]===q[++K]&&te<be);if(X=M-(be-te),te=be-M,fe<X){if(U.match_start=G,de<=(fe=X))break;ye=q[te+fe-1],_e=q[te+fe]}}while((G=re[G&R])>me&&--se!=0);return fe<=U.lookahead?fe:U.lookahead}function $(U){var G,K,X,se,te,fe,de,me,q,R,re=U.w_size;do{if(se=U.window_size-U.lookahead-U.strstart,U.strstart>=re+(re-H)){for(o.arraySet(U.window,U.window,re,re,0),U.match_start-=re,U.strstart-=re,U.block_start-=re,G=K=U.hash_size;X=U.head[--G],U.head[G]=re<=X?X-re:0,--K;);for(G=K=re;X=U.prev[--G],U.prev[G]=re<=X?X-re:0,--K;);se+=re}if(U.strm.avail_in===0)break;if(fe=U.strm,de=U.window,me=U.strstart+U.lookahead,q=se,R=void 0,R=fe.avail_in,q<R&&(R=q),K=R===0?0:(fe.avail_in-=R,o.arraySet(de,fe.input,fe.next_in,R,me),fe.state.wrap===1?fe.adler=c(fe.adler,de,R,me):fe.state.wrap===2&&(fe.adler=d(fe.adler,de,R,me)),fe.next_in+=R,fe.total_in+=R,R),U.lookahead+=K,U.lookahead+U.insert>=_)for(te=U.strstart-U.insert,U.ins_h=U.window[te],U.ins_h=(U.ins_h<<U.hash_shift^U.window[te+1])&U.hash_mask;U.insert&&(U.ins_h=(U.ins_h<<U.hash_shift^U.window[te+_-1])&U.hash_mask,U.prev[te&U.w_mask]=U.head[U.ins_h],U.head[U.ins_h]=te,te++,U.insert--,!(U.lookahead+U.insert<_)););}while(U.lookahead<H&&U.strm.avail_in!==0)}function J(U,G){for(var K,X;;){if(U.lookahead<H){if($(U),U.lookahead<H&&G===m)return L;if(U.lookahead===0)break}if(K=0,U.lookahead>=_&&(U.ins_h=(U.ins_h<<U.hash_shift^U.window[U.strstart+_-1])&U.hash_mask,K=U.prev[U.strstart&U.w_mask]=U.head[U.ins_h],U.head[U.ins_h]=U.strstart),K!==0&&U.strstart-K<=U.w_size-H&&(U.match_length=we(U,K)),U.match_length>=_)if(X=l._tr_tally(U,U.strstart-U.match_start,U.match_length-_),U.lookahead-=U.match_length,U.match_length<=U.max_lazy_match&&U.lookahead>=_){for(U.match_length--;U.strstart++,U.ins_h=(U.ins_h<<U.hash_shift^U.window[U.strstart+_-1])&U.hash_mask,K=U.prev[U.strstart&U.w_mask]=U.head[U.ins_h],U.head[U.ins_h]=U.strstart,--U.match_length!=0;);U.strstart++}else U.strstart+=U.match_length,U.match_length=0,U.ins_h=U.window[U.strstart],U.ins_h=(U.ins_h<<U.hash_shift^U.window[U.strstart+1])&U.hash_mask;else X=l._tr_tally(U,0,U.window[U.strstart]),U.lookahead--,U.strstart++;if(X&&(le(U,!1),U.strm.avail_out===0))return L}return U.insert=U.strstart<_-1?U.strstart:_-1,G===p?(le(U,!0),U.strm.avail_out===0?ne:Y):U.last_lit&&(le(U,!1),U.strm.avail_out===0)?L:Z}function j(U,G){for(var K,X,se;;){if(U.lookahead<H){if($(U),U.lookahead<H&&G===m)return L;if(U.lookahead===0)break}if(K=0,U.lookahead>=_&&(U.ins_h=(U.ins_h<<U.hash_shift^U.window[U.strstart+_-1])&U.hash_mask,K=U.prev[U.strstart&U.w_mask]=U.head[U.ins_h],U.head[U.ins_h]=U.strstart),U.prev_length=U.match_length,U.prev_match=U.match_start,U.match_length=_-1,K!==0&&U.prev_length<U.max_lazy_match&&U.strstart-K<=U.w_size-H&&(U.match_length=we(U,K),U.match_length<=5&&(U.strategy===1||U.match_length===_&&4096<U.strstart-U.match_start)&&(U.match_length=_-1)),U.prev_length>=_&&U.match_length<=U.prev_length){for(se=U.strstart+U.lookahead-_,X=l._tr_tally(U,U.strstart-1-U.prev_match,U.prev_length-_),U.lookahead-=U.prev_length-1,U.prev_length-=2;++U.strstart<=se&&(U.ins_h=(U.ins_h<<U.hash_shift^U.window[U.strstart+_-1])&U.hash_mask,K=U.prev[U.strstart&U.w_mask]=U.head[U.ins_h],U.head[U.ins_h]=U.strstart),--U.prev_length!=0;);if(U.match_available=0,U.match_length=_-1,U.strstart++,X&&(le(U,!1),U.strm.avail_out===0))return L}else if(U.match_available){if((X=l._tr_tally(U,0,U.window[U.strstart-1]))&&le(U,!1),U.strstart++,U.lookahead--,U.strm.avail_out===0)return L}else U.match_available=1,U.strstart++,U.lookahead--}return U.match_available&&(X=l._tr_tally(U,0,U.window[U.strstart-1]),U.match_available=0),U.insert=U.strstart<_-1?U.strstart:_-1,G===p?(le(U,!0),U.strm.avail_out===0?ne:Y):U.last_lit&&(le(U,!1),U.strm.avail_out===0)?L:Z}function E(U,G,K,X,se){this.good_length=U,this.max_lazy=G,this.nice_length=K,this.max_chain=X,this.func=se}function B(){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=S,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*A),this.dyn_dtree=new o.Buf16(2*(2*P+1)),this.bl_tree=new o.Buf16(2*(2*T+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*C+1),oe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new o.Buf16(2*C+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 W(U){var G;return U&&U.state?(U.total_in=U.total_out=0,U.data_type=x,(G=U.state).pending=0,G.pending_out=0,G.wrap<0&&(G.wrap=-G.wrap),G.status=G.wrap?I:z,U.adler=G.wrap===2?0:1,G.last_flush=m,l._tr_init(G),f):ce(U,g)}function O(U){var G=W(U);return G===f&&(function(K){K.window_size=2*K.w_size,oe(K.head),K.max_lazy_match=s[K.level].max_lazy,K.good_match=s[K.level].good_length,K.nice_match=s[K.level].nice_length,K.max_chain_length=s[K.level].max_chain,K.strstart=0,K.block_start=0,K.lookahead=0,K.insert=0,K.match_length=K.prev_length=_-1,K.match_available=0,K.ins_h=0})(U.state),G}function ie(U,G,K,X,se,te){if(!U)return g;var fe=1;if(G===w&&(G=6),X<0?(fe=0,X=-X):15<X&&(fe=2,X-=16),se<1||k<se||K!==S||X<8||15<X||G<0||9<G||te<0||b<te)return ce(U,g);X===8&&(X=9);var de=new B;return(U.state=de).strm=U,de.wrap=fe,de.gzhead=null,de.w_bits=X,de.w_size=1<<de.w_bits,de.w_mask=de.w_size-1,de.hash_bits=se+7,de.hash_size=1<<de.hash_bits,de.hash_mask=de.hash_size-1,de.hash_shift=~~((de.hash_bits+_-1)/_),de.window=new o.Buf8(2*de.w_size),de.head=new o.Buf16(de.hash_size),de.prev=new o.Buf16(de.w_size),de.lit_bufsize=1<<se+6,de.pending_buf_size=4*de.lit_bufsize,de.pending_buf=new o.Buf8(de.pending_buf_size),de.d_buf=1*de.lit_bufsize,de.l_buf=3*de.lit_bufsize,de.level=G,de.strategy=te,de.method=K,O(U)}s=[new E(0,0,0,0,function(U,G){var K=65535;for(K>U.pending_buf_size-5&&(K=U.pending_buf_size-5);;){if(U.lookahead<=1){if($(U),U.lookahead===0&&G===m)return L;if(U.lookahead===0)break}U.strstart+=U.lookahead,U.lookahead=0;var X=U.block_start+K;if((U.strstart===0||U.strstart>=X)&&(U.lookahead=U.strstart-X,U.strstart=X,le(U,!1),U.strm.avail_out===0)||U.strstart-U.block_start>=U.w_size-H&&(le(U,!1),U.strm.avail_out===0))return L}return U.insert=0,G===p?(le(U,!0),U.strm.avail_out===0?ne:Y):(U.strstart>U.block_start&&(le(U,!1),U.strm.avail_out),L)}),new E(4,4,8,4,J),new E(4,5,16,8,J),new E(4,6,32,32,J),new E(4,4,16,16,j),new E(8,16,32,32,j),new E(8,16,128,128,j),new E(8,32,128,256,j),new E(32,128,258,1024,j),new E(32,258,258,4096,j)],i.deflateInit=function(U,G){return ie(U,G,S,15,8,0)},i.deflateInit2=ie,i.deflateReset=O,i.deflateResetKeep=W,i.deflateSetHeader=function(U,G){return U&&U.state?U.state.wrap!==2?g:(U.state.gzhead=G,f):g},i.deflate=function(U,G){var K,X,se,te;if(!U||!U.state||5<G||G<0)return U?ce(U,g):g;if(X=U.state,!U.output||!U.input&&U.avail_in!==0||X.status===666&&G!==p)return ce(U,U.avail_out===0?-5:g);if(X.strm=U,K=X.last_flush,X.last_flush=G,X.status===I)if(X.wrap===2)U.adler=0,pe(X,31),pe(X,139),pe(X,8),X.gzhead?(pe(X,(X.gzhead.text?1:0)+(X.gzhead.hcrc?2:0)+(X.gzhead.extra?4:0)+(X.gzhead.name?8:0)+(X.gzhead.comment?16:0)),pe(X,255&X.gzhead.time),pe(X,X.gzhead.time>>8&255),pe(X,X.gzhead.time>>16&255),pe(X,X.gzhead.time>>24&255),pe(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),pe(X,255&X.gzhead.os),X.gzhead.extra&&X.gzhead.extra.length&&(pe(X,255&X.gzhead.extra.length),pe(X,X.gzhead.extra.length>>8&255)),X.gzhead.hcrc&&(U.adler=d(U.adler,X.pending_buf,X.pending,0)),X.gzindex=0,X.status=69):(pe(X,0),pe(X,0),pe(X,0),pe(X,0),pe(X,0),pe(X,X.level===9?2:2<=X.strategy||X.level<2?4:0),pe(X,3),X.status=z);else{var fe=S+(X.w_bits-8<<4)<<8;fe|=(2<=X.strategy||X.level<2?0:X.level<6?1:X.level===6?2:3)<<6,X.strstart!==0&&(fe|=32),fe+=31-fe%31,X.status=z,he(X,fe),X.strstart!==0&&(he(X,U.adler>>>16),he(X,65535&U.adler)),U.adler=1}if(X.status===69)if(X.gzhead.extra){for(se=X.pending;X.gzindex<(65535&X.gzhead.extra.length)&&(X.pending!==X.pending_buf_size||(X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),Q(U),se=X.pending,X.pending!==X.pending_buf_size));)pe(X,255&X.gzhead.extra[X.gzindex]),X.gzindex++;X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),X.gzindex===X.gzhead.extra.length&&(X.gzindex=0,X.status=73)}else X.status=73;if(X.status===73)if(X.gzhead.name){se=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),Q(U),se=X.pending,X.pending===X.pending_buf_size)){te=1;break}te=X.gzindex<X.gzhead.name.length?255&X.gzhead.name.charCodeAt(X.gzindex++):0,pe(X,te)}while(te!==0);X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),te===0&&(X.gzindex=0,X.status=91)}else X.status=91;if(X.status===91)if(X.gzhead.comment){se=X.pending;do{if(X.pending===X.pending_buf_size&&(X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),Q(U),se=X.pending,X.pending===X.pending_buf_size)){te=1;break}te=X.gzindex<X.gzhead.comment.length?255&X.gzhead.comment.charCodeAt(X.gzindex++):0,pe(X,te)}while(te!==0);X.gzhead.hcrc&&X.pending>se&&(U.adler=d(U.adler,X.pending_buf,X.pending-se,se)),te===0&&(X.status=103)}else X.status=103;if(X.status===103&&(X.gzhead.hcrc?(X.pending+2>X.pending_buf_size&&Q(U),X.pending+2<=X.pending_buf_size&&(pe(X,255&U.adler),pe(X,U.adler>>8&255),U.adler=0,X.status=z)):X.status=z),X.pending!==0){if(Q(U),U.avail_out===0)return X.last_flush=-1,f}else if(U.avail_in===0&&ue(G)<=ue(K)&&G!==p)return ce(U,-5);if(X.status===666&&U.avail_in!==0)return ce(U,-5);if(U.avail_in!==0||X.lookahead!==0||G!==m&&X.status!==666){var de=X.strategy===2?(function(me,q){for(var R;;){if(me.lookahead===0&&($(me),me.lookahead===0)){if(q===m)return L;break}if(me.match_length=0,R=l._tr_tally(me,0,me.window[me.strstart]),me.lookahead--,me.strstart++,R&&(le(me,!1),me.strm.avail_out===0))return L}return me.insert=0,q===p?(le(me,!0),me.strm.avail_out===0?ne:Y):me.last_lit&&(le(me,!1),me.strm.avail_out===0)?L:Z})(X,G):X.strategy===3?(function(me,q){for(var R,re,be,ye,_e=me.window;;){if(me.lookahead<=M){if($(me),me.lookahead<=M&&q===m)return L;if(me.lookahead===0)break}if(me.match_length=0,me.lookahead>=_&&0<me.strstart&&(re=_e[be=me.strstart-1])===_e[++be]&&re===_e[++be]&&re===_e[++be]){ye=me.strstart+M;do;while(re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&re===_e[++be]&&be<ye);me.match_length=M-(ye-be),me.match_length>me.lookahead&&(me.match_length=me.lookahead)}if(me.match_length>=_?(R=l._tr_tally(me,1,me.match_length-_),me.lookahead-=me.match_length,me.strstart+=me.match_length,me.match_length=0):(R=l._tr_tally(me,0,me.window[me.strstart]),me.lookahead--,me.strstart++),R&&(le(me,!1),me.strm.avail_out===0))return L}return me.insert=0,q===p?(le(me,!0),me.strm.avail_out===0?ne:Y):me.last_lit&&(le(me,!1),me.strm.avail_out===0)?L:Z})(X,G):s[X.level].func(X,G);if(de!==ne&&de!==Y||(X.status=666),de===L||de===ne)return U.avail_out===0&&(X.last_flush=-1),f;if(de===Z&&(G===1?l._tr_align(X):G!==5&&(l._tr_stored_block(X,0,0,!1),G===3&&(oe(X.head),X.lookahead===0&&(X.strstart=0,X.block_start=0,X.insert=0))),Q(U),U.avail_out===0))return X.last_flush=-1,f}return G!==p?f:X.wrap<=0?1:(X.wrap===2?(pe(X,255&U.adler),pe(X,U.adler>>8&255),pe(X,U.adler>>16&255),pe(X,U.adler>>24&255),pe(X,255&U.total_in),pe(X,U.total_in>>8&255),pe(X,U.total_in>>16&255),pe(X,U.total_in>>24&255)):(he(X,U.adler>>>16),he(X,65535&U.adler)),Q(U),0<X.wrap&&(X.wrap=-X.wrap),X.pending!==0?f:1)},i.deflateEnd=function(U){var G;return U&&U.state?(G=U.state.status)!==I&&G!==69&&G!==73&&G!==91&&G!==103&&G!==z&&G!==666?ce(U,g):(U.state=null,G===z?ce(U,-3):f):g},i.deflateSetDictionary=function(U,G){var K,X,se,te,fe,de,me,q,R=G.length;if(!U||!U.state||(te=(K=U.state).wrap)===2||te===1&&K.status!==I||K.lookahead)return g;for(te===1&&(U.adler=c(U.adler,G,R,0)),K.wrap=0,R>=K.w_size&&(te===0&&(oe(K.head),K.strstart=0,K.block_start=0,K.insert=0),q=new o.Buf8(K.w_size),o.arraySet(q,G,R-K.w_size,K.w_size,0),G=q,R=K.w_size),fe=U.avail_in,de=U.next_in,me=U.input,U.avail_in=R,U.next_in=0,U.input=G,$(K);K.lookahead>=_;){for(X=K.strstart,se=K.lookahead-(_-1);K.ins_h=(K.ins_h<<K.hash_shift^K.window[X+_-1])&K.hash_mask,K.prev[X&K.w_mask]=K.head[K.ins_h],K.head[K.ins_h]=X,X++,--se;);K.strstart=X,K.lookahead=_-1,$(K)}return K.strstart+=K.lookahead,K.block_start=K.strstart,K.insert=K.lookahead,K.lookahead=0,K.match_length=K.prev_length=_-1,K.match_available=0,U.next_in=de,U.input=me,U.avail_in=fe,K.wrap=te,f},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,a,i){a.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,a,i){a.exports=function(s,o){var l,c,d,u,m,p,f,g,w,b,x,S,k,C,P,T,A,F,_,M,H,I,z,L,Z;l=s.state,c=s.next_in,L=s.input,d=c+(s.avail_in-5),u=s.next_out,Z=s.output,m=u-(o-s.avail_out),p=u+(s.avail_out-257),f=l.dmax,g=l.wsize,w=l.whave,b=l.wnext,x=l.window,S=l.hold,k=l.bits,C=l.lencode,P=l.distcode,T=(1<<l.lenbits)-1,A=(1<<l.distbits)-1;e:do{k<15&&(S+=L[c++]<<k,k+=8,S+=L[c++]<<k,k+=8),F=C[S&T];t:for(;;){if(S>>>=_=F>>>24,k-=_,(_=F>>>16&255)===0)Z[u++]=65535&F;else{if(!(16&_)){if((64&_)==0){F=C[(65535&F)+(S&(1<<_)-1)];continue t}if(32&_){l.mode=12;break e}s.msg="invalid literal/length code",l.mode=30;break e}M=65535&F,(_&=15)&&(k<_&&(S+=L[c++]<<k,k+=8),M+=S&(1<<_)-1,S>>>=_,k-=_),k<15&&(S+=L[c++]<<k,k+=8,S+=L[c++]<<k,k+=8),F=P[S&A];n:for(;;){if(S>>>=_=F>>>24,k-=_,!(16&(_=F>>>16&255))){if((64&_)==0){F=P[(65535&F)+(S&(1<<_)-1)];continue n}s.msg="invalid distance code",l.mode=30;break e}if(H=65535&F,k<(_&=15)&&(S+=L[c++]<<k,(k+=8)<_&&(S+=L[c++]<<k,k+=8)),f<(H+=S&(1<<_)-1)){s.msg="invalid distance too far back",l.mode=30;break e}if(S>>>=_,k-=_,(_=u-m)<H){if(w<(_=H-_)&&l.sane){s.msg="invalid distance too far back",l.mode=30;break e}if(z=x,(I=0)===b){if(I+=g-_,_<M){for(M-=_;Z[u++]=x[I++],--_;);I=u-H,z=Z}}else if(b<_){if(I+=g+b-_,(_-=b)<M){for(M-=_;Z[u++]=x[I++],--_;);if(I=0,b<M){for(M-=_=b;Z[u++]=x[I++],--_;);I=u-H,z=Z}}}else if(I+=b-_,_<M){for(M-=_;Z[u++]=x[I++],--_;);I=u-H,z=Z}for(;2<M;)Z[u++]=z[I++],Z[u++]=z[I++],Z[u++]=z[I++],M-=3;M&&(Z[u++]=z[I++],1<M&&(Z[u++]=z[I++]))}else{for(I=u-H;Z[u++]=Z[I++],Z[u++]=Z[I++],Z[u++]=Z[I++],2<(M-=3););M&&(Z[u++]=Z[I++],1<M&&(Z[u++]=Z[I++]))}break}}break}}while(c<d&&u<p);c-=M=k>>3,S&=(1<<(k-=M<<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=S,l.bits=k}},{}],49:[function(n,a,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,g=1,w=852,b=592;function x(I){return(I>>>24&255)+(I>>>8&65280)+((65280&I)<<8)+((255&I)<<24)}function S(){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 k(I){var z;return I&&I.state?(z=I.state,I.total_in=I.total_out=z.total=0,I.msg="",z.wrap&&(I.adler=1&z.wrap),z.mode=g,z.last=0,z.havedict=0,z.dmax=32768,z.head=null,z.hold=0,z.bits=0,z.lencode=z.lendyn=new s.Buf32(w),z.distcode=z.distdyn=new s.Buf32(b),z.sane=1,z.back=-1,p):f}function C(I){var z;return I&&I.state?((z=I.state).wsize=0,z.whave=0,z.wnext=0,k(I)):f}function P(I,z){var L,Z;return I&&I.state?(Z=I.state,z<0?(L=0,z=-z):(L=1+(z>>4),z<48&&(z&=15)),z&&(z<8||15<z)?f:(Z.window!==null&&Z.wbits!==z&&(Z.window=null),Z.wrap=L,Z.wbits=z,C(I))):f}function T(I,z){var L,Z;return I?(Z=new S,(I.state=Z).window=null,(L=P(I,z))!==p&&(I.state=null),L):f}var A,F,_=!0;function M(I){if(_){var z;for(A=new s.Buf32(512),F=new s.Buf32(32),z=0;z<144;)I.lens[z++]=8;for(;z<256;)I.lens[z++]=9;for(;z<280;)I.lens[z++]=7;for(;z<288;)I.lens[z++]=8;for(d(u,I.lens,0,288,A,0,I.work,{bits:9}),z=0;z<32;)I.lens[z++]=5;d(m,I.lens,0,32,F,0,I.work,{bits:5}),_=!1}I.lencode=A,I.lenbits=9,I.distcode=F,I.distbits=5}function H(I,z,L,Z){var ne,Y=I.state;return Y.window===null&&(Y.wsize=1<<Y.wbits,Y.wnext=0,Y.whave=0,Y.window=new s.Buf8(Y.wsize)),Z>=Y.wsize?(s.arraySet(Y.window,z,L-Y.wsize,Y.wsize,0),Y.wnext=0,Y.whave=Y.wsize):(Z<(ne=Y.wsize-Y.wnext)&&(ne=Z),s.arraySet(Y.window,z,L-Z,ne,Y.wnext),(Z-=ne)?(s.arraySet(Y.window,z,L-Z,Z,0),Y.wnext=Z,Y.whave=Y.wsize):(Y.wnext+=ne,Y.wnext===Y.wsize&&(Y.wnext=0),Y.whave<Y.wsize&&(Y.whave+=ne))),0}i.inflateReset=C,i.inflateReset2=P,i.inflateResetKeep=k,i.inflateInit=function(I){return T(I,15)},i.inflateInit2=T,i.inflate=function(I,z){var L,Z,ne,Y,ce,ue,oe,Q,le,pe,he,we,$,J,j,E,B,W,O,ie,U,G,K,X,se=0,te=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(!I||!I.state||!I.output||!I.input&&I.avail_in!==0)return f;(L=I.state).mode===12&&(L.mode=13),ce=I.next_out,ne=I.output,oe=I.avail_out,Y=I.next_in,Z=I.input,ue=I.avail_in,Q=L.hold,le=L.bits,pe=ue,he=oe,G=p;e:for(;;)switch(L.mode){case g:if(L.wrap===0){L.mode=13;break}for(;le<16;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(2&L.wrap&&Q===35615){te[L.check=0]=255&Q,te[1]=Q>>>8&255,L.check=l(L.check,te,2,0),le=Q=0,L.mode=2;break}if(L.flags=0,L.head&&(L.head.done=!1),!(1&L.wrap)||(((255&Q)<<8)+(Q>>8))%31){I.msg="incorrect header check",L.mode=30;break}if((15&Q)!=8){I.msg="unknown compression method",L.mode=30;break}if(le-=4,U=8+(15&(Q>>>=4)),L.wbits===0)L.wbits=U;else if(U>L.wbits){I.msg="invalid window size",L.mode=30;break}L.dmax=1<<U,I.adler=L.check=1,L.mode=512&Q?10:12,le=Q=0;break;case 2:for(;le<16;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(L.flags=Q,(255&L.flags)!=8){I.msg="unknown compression method",L.mode=30;break}if(57344&L.flags){I.msg="unknown header flags set",L.mode=30;break}L.head&&(L.head.text=Q>>8&1),512&L.flags&&(te[0]=255&Q,te[1]=Q>>>8&255,L.check=l(L.check,te,2,0)),le=Q=0,L.mode=3;case 3:for(;le<32;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.head&&(L.head.time=Q),512&L.flags&&(te[0]=255&Q,te[1]=Q>>>8&255,te[2]=Q>>>16&255,te[3]=Q>>>24&255,L.check=l(L.check,te,4,0)),le=Q=0,L.mode=4;case 4:for(;le<16;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.head&&(L.head.xflags=255&Q,L.head.os=Q>>8),512&L.flags&&(te[0]=255&Q,te[1]=Q>>>8&255,L.check=l(L.check,te,2,0)),le=Q=0,L.mode=5;case 5:if(1024&L.flags){for(;le<16;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.length=Q,L.head&&(L.head.extra_len=Q),512&L.flags&&(te[0]=255&Q,te[1]=Q>>>8&255,L.check=l(L.check,te,2,0)),le=Q=0}else L.head&&(L.head.extra=null);L.mode=6;case 6:if(1024&L.flags&&(ue<(we=L.length)&&(we=ue),we&&(L.head&&(U=L.head.extra_len-L.length,L.head.extra||(L.head.extra=new Array(L.head.extra_len)),s.arraySet(L.head.extra,Z,Y,we,U)),512&L.flags&&(L.check=l(L.check,Z,we,Y)),ue-=we,Y+=we,L.length-=we),L.length))break e;L.length=0,L.mode=7;case 7:if(2048&L.flags){if(ue===0)break e;for(we=0;U=Z[Y+we++],L.head&&U&&L.length<65536&&(L.head.name+=String.fromCharCode(U)),U&&we<ue;);if(512&L.flags&&(L.check=l(L.check,Z,we,Y)),ue-=we,Y+=we,U)break e}else L.head&&(L.head.name=null);L.length=0,L.mode=8;case 8:if(4096&L.flags){if(ue===0)break e;for(we=0;U=Z[Y+we++],L.head&&U&&L.length<65536&&(L.head.comment+=String.fromCharCode(U)),U&&we<ue;);if(512&L.flags&&(L.check=l(L.check,Z,we,Y)),ue-=we,Y+=we,U)break e}else L.head&&(L.head.comment=null);L.mode=9;case 9:if(512&L.flags){for(;le<16;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(Q!==(65535&L.check)){I.msg="header crc mismatch",L.mode=30;break}le=Q=0}L.head&&(L.head.hcrc=L.flags>>9&1,L.head.done=!0),I.adler=L.check=0,L.mode=12;break;case 10:for(;le<32;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}I.adler=L.check=x(Q),le=Q=0,L.mode=11;case 11:if(L.havedict===0)return I.next_out=ce,I.avail_out=oe,I.next_in=Y,I.avail_in=ue,L.hold=Q,L.bits=le,2;I.adler=L.check=1,L.mode=12;case 12:if(z===5||z===6)break e;case 13:if(L.last){Q>>>=7&le,le-=7&le,L.mode=27;break}for(;le<3;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}switch(L.last=1&Q,le-=1,3&(Q>>>=1)){case 0:L.mode=14;break;case 1:if(M(L),L.mode=20,z!==6)break;Q>>>=2,le-=2;break e;case 2:L.mode=17;break;case 3:I.msg="invalid block type",L.mode=30}Q>>>=2,le-=2;break;case 14:for(Q>>>=7&le,le-=7&le;le<32;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if((65535&Q)!=(Q>>>16^65535)){I.msg="invalid stored block lengths",L.mode=30;break}if(L.length=65535&Q,le=Q=0,L.mode=15,z===6)break e;case 15:L.mode=16;case 16:if(we=L.length){if(ue<we&&(we=ue),oe<we&&(we=oe),we===0)break e;s.arraySet(ne,Z,Y,we,ce),ue-=we,Y+=we,oe-=we,ce+=we,L.length-=we;break}L.mode=12;break;case 17:for(;le<14;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(L.nlen=257+(31&Q),Q>>>=5,le-=5,L.ndist=1+(31&Q),Q>>>=5,le-=5,L.ncode=4+(15&Q),Q>>>=4,le-=4,286<L.nlen||30<L.ndist){I.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(;le<3;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.lens[fe[L.have++]]=7&Q,Q>>>=3,le-=3}for(;L.have<19;)L.lens[fe[L.have++]]=0;if(L.lencode=L.lendyn,L.lenbits=7,K={bits:L.lenbits},G=d(0,L.lens,0,19,L.lencode,0,L.work,K),L.lenbits=K.bits,G){I.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(;E=(se=L.lencode[Q&(1<<L.lenbits)-1])>>>16&255,B=65535&se,!((j=se>>>24)<=le);){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(B<16)Q>>>=j,le-=j,L.lens[L.have++]=B;else{if(B===16){for(X=j+2;le<X;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(Q>>>=j,le-=j,L.have===0){I.msg="invalid bit length repeat",L.mode=30;break}U=L.lens[L.have-1],we=3+(3&Q),Q>>>=2,le-=2}else if(B===17){for(X=j+3;le<X;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}le-=j,U=0,we=3+(7&(Q>>>=j)),Q>>>=3,le-=3}else{for(X=j+7;le<X;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}le-=j,U=0,we=11+(127&(Q>>>=j)),Q>>>=7,le-=7}if(L.have+we>L.nlen+L.ndist){I.msg="invalid bit length repeat",L.mode=30;break}for(;we--;)L.lens[L.have++]=U}}if(L.mode===30)break;if(L.lens[256]===0){I.msg="invalid code -- missing end-of-block",L.mode=30;break}if(L.lenbits=9,K={bits:L.lenbits},G=d(u,L.lens,0,L.nlen,L.lencode,0,L.work,K),L.lenbits=K.bits,G){I.msg="invalid literal/lengths set",L.mode=30;break}if(L.distbits=6,L.distcode=L.distdyn,K={bits:L.distbits},G=d(m,L.lens,L.nlen,L.ndist,L.distcode,0,L.work,K),L.distbits=K.bits,G){I.msg="invalid distances set",L.mode=30;break}if(L.mode=20,z===6)break e;case 20:L.mode=21;case 21:if(6<=ue&&258<=oe){I.next_out=ce,I.avail_out=oe,I.next_in=Y,I.avail_in=ue,L.hold=Q,L.bits=le,c(I,he),ce=I.next_out,ne=I.output,oe=I.avail_out,Y=I.next_in,Z=I.input,ue=I.avail_in,Q=L.hold,le=L.bits,L.mode===12&&(L.back=-1);break}for(L.back=0;E=(se=L.lencode[Q&(1<<L.lenbits)-1])>>>16&255,B=65535&se,!((j=se>>>24)<=le);){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(E&&(240&E)==0){for(W=j,O=E,ie=B;E=(se=L.lencode[ie+((Q&(1<<W+O)-1)>>W)])>>>16&255,B=65535&se,!(W+(j=se>>>24)<=le);){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}Q>>>=W,le-=W,L.back+=W}if(Q>>>=j,le-=j,L.back+=j,L.length=B,E===0){L.mode=26;break}if(32&E){L.back=-1,L.mode=12;break}if(64&E){I.msg="invalid literal/length code",L.mode=30;break}L.extra=15&E,L.mode=22;case 22:if(L.extra){for(X=L.extra;le<X;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.length+=Q&(1<<L.extra)-1,Q>>>=L.extra,le-=L.extra,L.back+=L.extra}L.was=L.length,L.mode=23;case 23:for(;E=(se=L.distcode[Q&(1<<L.distbits)-1])>>>16&255,B=65535&se,!((j=se>>>24)<=le);){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if((240&E)==0){for(W=j,O=E,ie=B;E=(se=L.distcode[ie+((Q&(1<<W+O)-1)>>W)])>>>16&255,B=65535&se,!(W+(j=se>>>24)<=le);){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}Q>>>=W,le-=W,L.back+=W}if(Q>>>=j,le-=j,L.back+=j,64&E){I.msg="invalid distance code",L.mode=30;break}L.offset=B,L.extra=15&E,L.mode=24;case 24:if(L.extra){for(X=L.extra;le<X;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}L.offset+=Q&(1<<L.extra)-1,Q>>>=L.extra,le-=L.extra,L.back+=L.extra}if(L.offset>L.dmax){I.msg="invalid distance too far back",L.mode=30;break}L.mode=25;case 25:if(oe===0)break e;if(we=he-oe,L.offset>we){if((we=L.offset-we)>L.whave&&L.sane){I.msg="invalid distance too far back",L.mode=30;break}$=we>L.wnext?(we-=L.wnext,L.wsize-we):L.wnext-we,we>L.length&&(we=L.length),J=L.window}else J=ne,$=ce-L.offset,we=L.length;for(oe<we&&(we=oe),oe-=we,L.length-=we;ne[ce++]=J[$++],--we;);L.length===0&&(L.mode=21);break;case 26:if(oe===0)break e;ne[ce++]=L.length,oe--,L.mode=21;break;case 27:if(L.wrap){for(;le<32;){if(ue===0)break e;ue--,Q|=Z[Y++]<<le,le+=8}if(he-=oe,I.total_out+=he,L.total+=he,he&&(I.adler=L.check=L.flags?l(L.check,ne,he,ce-he):o(L.check,ne,he,ce-he)),he=oe,(L.flags?Q:x(Q))!==L.check){I.msg="incorrect data check",L.mode=30;break}le=Q=0}L.mode=28;case 28:if(L.wrap&&L.flags){for(;le<32;){if(ue===0)break e;ue--,Q+=Z[Y++]<<le,le+=8}if(Q!==(4294967295&L.total)){I.msg="incorrect length check",L.mode=30;break}le=Q=0}L.mode=29;case 29:G=1;break e;case 30:G=-3;break e;case 31:return-4;default:return f}return I.next_out=ce,I.avail_out=oe,I.next_in=Y,I.avail_in=ue,L.hold=Q,L.bits=le,(L.wsize||he!==I.avail_out&&L.mode<30&&(L.mode<27||z!==4))&&H(I,I.output,I.next_out,he-I.avail_out)?(L.mode=31,-4):(pe-=I.avail_in,he-=I.avail_out,I.total_in+=pe,I.total_out+=he,L.total+=he,L.wrap&&he&&(I.adler=L.check=L.flags?l(L.check,ne,he,I.next_out-he):o(L.check,ne,he,I.next_out-he)),I.data_type=L.bits+(L.last?64:0)+(L.mode===12?128:0)+(L.mode===20||L.mode===15?256:0),(pe==0&&he===0||z===4)&&G===p&&(G=-5),G)},i.inflateEnd=function(I){if(!I||!I.state)return f;var z=I.state;return z.window&&(z.window=null),I.state=null,p},i.inflateGetHeader=function(I,z){var L;return I&&I.state?(2&(L=I.state).wrap)==0?f:((L.head=z).done=!1,p):f},i.inflateSetDictionary=function(I,z){var L,Z=z.length;return I&&I.state?(L=I.state).wrap!==0&&L.mode!==11?f:L.mode===11&&o(1,z,Z,0)!==L.check?-3:H(I,z,Z,Z)?(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,a,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];a.exports=function(u,m,p,f,g,w,b,x){var S,k,C,P,T,A,F,_,M,H=x.bits,I=0,z=0,L=0,Z=0,ne=0,Y=0,ce=0,ue=0,oe=0,Q=0,le=null,pe=0,he=new s.Buf16(16),we=new s.Buf16(16),$=null,J=0;for(I=0;I<=15;I++)he[I]=0;for(z=0;z<f;z++)he[m[p+z]]++;for(ne=H,Z=15;1<=Z&&he[Z]===0;Z--);if(Z<ne&&(ne=Z),Z===0)return g[w++]=20971520,g[w++]=20971520,x.bits=1,0;for(L=1;L<Z&&he[L]===0;L++);for(ne<L&&(ne=L),I=ue=1;I<=15;I++)if(ue<<=1,(ue-=he[I])<0)return-1;if(0<ue&&(u===0||Z!==1))return-1;for(we[1]=0,I=1;I<15;I++)we[I+1]=we[I]+he[I];for(z=0;z<f;z++)m[p+z]!==0&&(b[we[m[p+z]]++]=z);if(A=u===0?(le=$=b,19):u===1?(le=o,pe-=257,$=l,J-=257,256):(le=c,$=d,-1),I=L,T=w,ce=z=Q=0,C=-1,P=(oe=1<<(Y=ne))-1,u===1&&852<oe||u===2&&592<oe)return 1;for(;;){for(F=I-ce,M=b[z]<A?(_=0,b[z]):b[z]>A?(_=$[J+b[z]],le[pe+b[z]]):(_=96,0),S=1<<I-ce,L=k=1<<Y;g[T+(Q>>ce)+(k-=S)]=F<<24|_<<16|M|0,k!==0;);for(S=1<<I-1;Q&S;)S>>=1;if(S!==0?(Q&=S-1,Q+=S):Q=0,z++,--he[I]==0){if(I===Z)break;I=m[p+b[z]]}if(ne<I&&(Q&P)!==C){for(ce===0&&(ce=ne),T+=L,ue=1<<(Y=I-ce);Y+ce<Z&&!((ue-=he[Y+ce])<=0);)Y++,ue<<=1;if(oe+=1<<Y,u===1&&852<oe||u===2&&592<oe)return 1;g[C=Q&P]=ne<<24|Y<<16|T-w|0}}return Q!==0&&(g[T+Q]=I-ce<<24|64<<16|0),x.bits=ne,0}},{"../utils/common":41}],51:[function(n,a,i){a.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,a,i){var s=n("../utils/common"),o=0,l=1;function c(se){for(var te=se.length;0<=--te;)se[te]=0}var d=0,u=29,m=256,p=m+1+u,f=30,g=19,w=2*p+1,b=15,x=16,S=7,k=256,C=16,P=17,T=18,A=[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],_=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],M=[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 I=new Array(2*f);c(I);var z=new Array(512);c(z);var L=new Array(256);c(L);var Z=new Array(u);c(Z);var ne,Y,ce,ue=new Array(f);function oe(se,te,fe,de,me){this.static_tree=se,this.extra_bits=te,this.extra_base=fe,this.elems=de,this.max_length=me,this.has_stree=se&&se.length}function Q(se,te){this.dyn_tree=se,this.max_code=0,this.stat_desc=te}function le(se){return se<256?z[se]:z[256+(se>>>7)]}function pe(se,te){se.pending_buf[se.pending++]=255&te,se.pending_buf[se.pending++]=te>>>8&255}function he(se,te,fe){se.bi_valid>x-fe?(se.bi_buf|=te<<se.bi_valid&65535,pe(se,se.bi_buf),se.bi_buf=te>>x-se.bi_valid,se.bi_valid+=fe-x):(se.bi_buf|=te<<se.bi_valid&65535,se.bi_valid+=fe)}function we(se,te,fe){he(se,fe[2*te],fe[2*te+1])}function $(se,te){for(var fe=0;fe|=1&se,se>>>=1,fe<<=1,0<--te;);return fe>>>1}function J(se,te,fe){var de,me,q=new Array(b+1),R=0;for(de=1;de<=b;de++)q[de]=R=R+fe[de-1]<<1;for(me=0;me<=te;me++){var re=se[2*me+1];re!==0&&(se[2*me]=$(q[re]++,re))}}function j(se){var te;for(te=0;te<p;te++)se.dyn_ltree[2*te]=0;for(te=0;te<f;te++)se.dyn_dtree[2*te]=0;for(te=0;te<g;te++)se.bl_tree[2*te]=0;se.dyn_ltree[2*k]=1,se.opt_len=se.static_len=0,se.last_lit=se.matches=0}function E(se){8<se.bi_valid?pe(se,se.bi_buf):0<se.bi_valid&&(se.pending_buf[se.pending++]=se.bi_buf),se.bi_buf=0,se.bi_valid=0}function B(se,te,fe,de){var me=2*te,q=2*fe;return se[me]<se[q]||se[me]===se[q]&&de[te]<=de[fe]}function W(se,te,fe){for(var de=se.heap[fe],me=fe<<1;me<=se.heap_len&&(me<se.heap_len&&B(te,se.heap[me+1],se.heap[me],se.depth)&&me++,!B(te,de,se.heap[me],se.depth));)se.heap[fe]=se.heap[me],fe=me,me<<=1;se.heap[fe]=de}function O(se,te,fe){var de,me,q,R,re=0;if(se.last_lit!==0)for(;de=se.pending_buf[se.d_buf+2*re]<<8|se.pending_buf[se.d_buf+2*re+1],me=se.pending_buf[se.l_buf+re],re++,de===0?we(se,me,te):(we(se,(q=L[me])+m+1,te),(R=A[q])!==0&&he(se,me-=Z[q],R),we(se,q=le(--de),fe),(R=F[q])!==0&&he(se,de-=ue[q],R)),re<se.last_lit;);we(se,k,te)}function ie(se,te){var fe,de,me,q=te.dyn_tree,R=te.stat_desc.static_tree,re=te.stat_desc.has_stree,be=te.stat_desc.elems,ye=-1;for(se.heap_len=0,se.heap_max=w,fe=0;fe<be;fe++)q[2*fe]!==0?(se.heap[++se.heap_len]=ye=fe,se.depth[fe]=0):q[2*fe+1]=0;for(;se.heap_len<2;)q[2*(me=se.heap[++se.heap_len]=ye<2?++ye:0)]=1,se.depth[me]=0,se.opt_len--,re&&(se.static_len-=R[2*me+1]);for(te.max_code=ye,fe=se.heap_len>>1;1<=fe;fe--)W(se,q,fe);for(me=be;fe=se.heap[1],se.heap[1]=se.heap[se.heap_len--],W(se,q,1),de=se.heap[1],se.heap[--se.heap_max]=fe,se.heap[--se.heap_max]=de,q[2*me]=q[2*fe]+q[2*de],se.depth[me]=(se.depth[fe]>=se.depth[de]?se.depth[fe]:se.depth[de])+1,q[2*fe+1]=q[2*de+1]=me,se.heap[1]=me++,W(se,q,1),2<=se.heap_len;);se.heap[--se.heap_max]=se.heap[1],(function(_e,xe){var ge,Me,Be,Fe,Oe,Re,We=xe.dyn_tree,ze=xe.max_code,st=xe.stat_desc.static_tree,Ee=xe.stat_desc.has_stree,it=xe.stat_desc.extra_bits,Ce=xe.stat_desc.extra_base,Ze=xe.stat_desc.max_length,Ie=0;for(Fe=0;Fe<=b;Fe++)_e.bl_count[Fe]=0;for(We[2*_e.heap[_e.heap_max]+1]=0,ge=_e.heap_max+1;ge<w;ge++)Ze<(Fe=We[2*We[2*(Me=_e.heap[ge])+1]+1]+1)&&(Fe=Ze,Ie++),We[2*Me+1]=Fe,ze<Me||(_e.bl_count[Fe]++,Oe=0,Ce<=Me&&(Oe=it[Me-Ce]),Re=We[2*Me],_e.opt_len+=Re*(Fe+Oe),Ee&&(_e.static_len+=Re*(st[2*Me+1]+Oe)));if(Ie!==0){do{for(Fe=Ze-1;_e.bl_count[Fe]===0;)Fe--;_e.bl_count[Fe]--,_e.bl_count[Fe+1]+=2,_e.bl_count[Ze]--,Ie-=2}while(0<Ie);for(Fe=Ze;Fe!==0;Fe--)for(Me=_e.bl_count[Fe];Me!==0;)ze<(Be=_e.heap[--ge])||(We[2*Be+1]!==Fe&&(_e.opt_len+=(Fe-We[2*Be+1])*We[2*Be],We[2*Be+1]=Fe),Me--)}})(se,te),J(q,ye,se.bl_count)}function U(se,te,fe){var de,me,q=-1,R=te[1],re=0,be=7,ye=4;for(R===0&&(be=138,ye=3),te[2*(fe+1)+1]=65535,de=0;de<=fe;de++)me=R,R=te[2*(de+1)+1],++re<be&&me===R||(re<ye?se.bl_tree[2*me]+=re:me!==0?(me!==q&&se.bl_tree[2*me]++,se.bl_tree[2*C]++):re<=10?se.bl_tree[2*P]++:se.bl_tree[2*T]++,q=me,ye=(re=0)===R?(be=138,3):me===R?(be=6,3):(be=7,4))}function G(se,te,fe){var de,me,q=-1,R=te[1],re=0,be=7,ye=4;for(R===0&&(be=138,ye=3),de=0;de<=fe;de++)if(me=R,R=te[2*(de+1)+1],!(++re<be&&me===R)){if(re<ye)for(;we(se,me,se.bl_tree),--re!=0;);else me!==0?(me!==q&&(we(se,me,se.bl_tree),re--),we(se,C,se.bl_tree),he(se,re-3,2)):re<=10?(we(se,P,se.bl_tree),he(se,re-3,3)):(we(se,T,se.bl_tree),he(se,re-11,7));q=me,ye=(re=0)===R?(be=138,3):me===R?(be=6,3):(be=7,4)}}c(ue);var K=!1;function X(se,te,fe,de){he(se,(d<<1)+(de?1:0),3),(function(me,q,R,re){E(me),pe(me,R),pe(me,~R),s.arraySet(me.pending_buf,me.window,q,R,me.pending),me.pending+=R})(se,te,fe)}i._tr_init=function(se){K||((function(){var te,fe,de,me,q,R=new Array(b+1);for(me=de=0;me<u-1;me++)for(Z[me]=de,te=0;te<1<<A[me];te++)L[de++]=me;for(L[de-1]=me,me=q=0;me<16;me++)for(ue[me]=q,te=0;te<1<<F[me];te++)z[q++]=me;for(q>>=7;me<f;me++)for(ue[me]=q<<7,te=0;te<1<<F[me]-7;te++)z[256+q++]=me;for(fe=0;fe<=b;fe++)R[fe]=0;for(te=0;te<=143;)H[2*te+1]=8,te++,R[8]++;for(;te<=255;)H[2*te+1]=9,te++,R[9]++;for(;te<=279;)H[2*te+1]=7,te++,R[7]++;for(;te<=287;)H[2*te+1]=8,te++,R[8]++;for(J(H,p+1,R),te=0;te<f;te++)I[2*te+1]=5,I[2*te]=$(te,5);ne=new oe(H,A,m+1,p,b),Y=new oe(I,F,0,f,b),ce=new oe(new Array(0),_,0,g,S)})(),K=!0),se.l_desc=new Q(se.dyn_ltree,ne),se.d_desc=new Q(se.dyn_dtree,Y),se.bl_desc=new Q(se.bl_tree,ce),se.bi_buf=0,se.bi_valid=0,j(se)},i._tr_stored_block=X,i._tr_flush_block=function(se,te,fe,de){var me,q,R=0;0<se.level?(se.strm.data_type===2&&(se.strm.data_type=(function(re){var be,ye=4093624447;for(be=0;be<=31;be++,ye>>>=1)if(1&ye&&re.dyn_ltree[2*be]!==0)return o;if(re.dyn_ltree[18]!==0||re.dyn_ltree[20]!==0||re.dyn_ltree[26]!==0)return l;for(be=32;be<m;be++)if(re.dyn_ltree[2*be]!==0)return l;return o})(se)),ie(se,se.l_desc),ie(se,se.d_desc),R=(function(re){var be;for(U(re,re.dyn_ltree,re.l_desc.max_code),U(re,re.dyn_dtree,re.d_desc.max_code),ie(re,re.bl_desc),be=g-1;3<=be&&re.bl_tree[2*M[be]+1]===0;be--);return re.opt_len+=3*(be+1)+5+5+4,be})(se),me=se.opt_len+3+7>>>3,(q=se.static_len+3+7>>>3)<=me&&(me=q)):me=q=fe+5,fe+4<=me&&te!==-1?X(se,te,fe,de):se.strategy===4||q===me?(he(se,2+(de?1:0),3),O(se,H,I)):(he(se,4+(de?1:0),3),(function(re,be,ye,_e){var xe;for(he(re,be-257,5),he(re,ye-1,5),he(re,_e-4,4),xe=0;xe<_e;xe++)he(re,re.bl_tree[2*M[xe]+1],3);G(re,re.dyn_ltree,be-1),G(re,re.dyn_dtree,ye-1)})(se,se.l_desc.max_code+1,se.d_desc.max_code+1,R+1),O(se,se.dyn_ltree,se.dyn_dtree)),j(se),de&&E(se)},i._tr_tally=function(se,te,fe){return se.pending_buf[se.d_buf+2*se.last_lit]=te>>>8&255,se.pending_buf[se.d_buf+2*se.last_lit+1]=255&te,se.pending_buf[se.l_buf+se.last_lit]=255&fe,se.last_lit++,te===0?se.dyn_ltree[2*fe]++:(se.matches++,te--,se.dyn_ltree[2*(L[fe]+m+1)]++,se.dyn_dtree[2*le(te)]++),se.last_lit===se.lit_bufsize-1},i._tr_align=function(se){he(se,2,3),we(se,k,H),(function(te){te.bi_valid===16?(pe(te,te.bi_buf),te.bi_buf=0,te.bi_valid=0):8<=te.bi_valid&&(te.pending_buf[te.pending++]=255&te.bi_buf,te.bi_buf>>=8,te.bi_valid-=8)})(se)}},{"../utils/common":41}],53:[function(n,a,i){a.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,a,i){(function(s){(function(o,l){if(!o.setImmediate){var c,d,u,m,p=1,f={},g=!1,w=o.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(o);b=b&&b.setTimeout?b:o,c={}.toString.call(o.process)==="[object process]"?function(C){process.nextTick(function(){S(C)})}:(function(){if(o.postMessage&&!o.importScripts){var C=!0,P=o.onmessage;return o.onmessage=function(){C=!1},o.postMessage("","*"),o.onmessage=P,C}})()?(m="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",k,!1):o.attachEvent("onmessage",k),function(C){o.postMessage(m+C,"*")}):o.MessageChannel?((u=new MessageChannel).port1.onmessage=function(C){S(C.data)},function(C){u.port2.postMessage(C)}):w&&"onreadystatechange"in w.createElement("script")?(d=w.documentElement,function(C){var P=w.createElement("script");P.onreadystatechange=function(){S(C),P.onreadystatechange=null,d.removeChild(P),P=null},d.appendChild(P)}):function(C){setTimeout(S,0,C)},b.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var P=new Array(arguments.length-1),T=0;T<P.length;T++)P[T]=arguments[T+1];var A={callback:C,args:P};return f[p]=A,c(p),p++},b.clearImmediate=x}function x(C){delete f[C]}function S(C){if(g)setTimeout(S,0,C);else{var P=f[C];if(P){g=!0;try{(function(T){var A=T.callback,F=T.args;switch(F.length){case 0:A();break;case 1:A(F[0]);break;case 2:A(F[0],F[1]);break;case 3:A(F[0],F[1],F[2]);break;default:A.apply(l,F)}})(P)}finally{x(C),g=!1}}}}function k(C){C.source===o&&typeof C.data=="string"&&C.data.indexOf(m)===0&&S(+C.data.slice(m.length))}})(typeof self>"u"?s===void 0?this:s:self)}).call(this,typeof _k<"u"?_k:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})($E)),$E.exports}var JNe=ZNe();const eCe=Tc(JNe);function Kx(){return new Promise(t=>setTimeout(t,0))}const YJ=2e4,XJ=2e4;function tCe(t){const e=new Ci;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 Rq=tCe;async function Iq(t,e=0){const n=[],a=t.getElementsByTagName("mesh");for(let i=0;i<a.length;i++){const s=a[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")),u>0&&u%YJ===0&&await Kx()}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")),u>0&&u%XJ===0&&await Kx()}o.length>0&&l.length>0&&n.push({vertices:o,triangles:l,extruder:e})}return n}function Oq(t){const e=Array.from(t.attributes).find(a=>{const i=a.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 nCe(t){let e;try{e=await eCe.loadAsync(t)}catch{throw new Error("Unsupported file format")}const n=new Map,a=[],i=new Map,s=new Map,o=new DOMParser;async function l(k){const C=k.startsWith("/")?k.slice(1):k,P=e.files[C];if(!P)return null;const T=await P.async("string");return o.parseFromString(T,"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 k=await p.async("string"),C=o.parseFromString(k,"application/xml"),P=C.getElementsByTagName("object");for(let A=0;A<P.length;A++){const F=P[A],_=F.getAttribute("id");if(!_)continue;const M=Array.from(F.children).filter(L=>L.tagName==="metadata"&&L.getAttribute("key")==="extruder");if(M.length>0){const L=M[0].getAttribute("value");L&&c.set(_,Math.max(0,parseInt(L,10)-1))}const I=Array.from(F.children).find(L=>L.tagName==="metadata"&&L.getAttribute("key")==="name")?.getAttribute("value");I&&u.set(_,I);const z=F.getElementsByTagName("part");for(let L=0;L<z.length;L++){const Z=z[L],ne=Z.getAttribute("id");if(!ne)continue;const Y=Array.from(Z.children).filter(ce=>ce.tagName==="metadata"&&ce.getAttribute("key")==="extruder");if(Y.length>0){const ce=Y[0].getAttribute("value");ce&&d.set(`${_}:${ne}`,Math.max(0,parseInt(ce,10)-1))}}}const T=C.getElementsByTagName("plate");for(let A=0;A<T.length;A++){const F=T[A];let _=null;const M=F.getElementsByTagName("metadata");let H=0,I=0;for(let L=0;L<M.length;L++){const Z=M[L],ne=Z.getAttribute("key");if(ne==="plater_id"||ne==="plate_id"){const Y=Z.getAttribute("value");if(Y){const ce=Number.parseInt(Y,10);Number.isFinite(ce)&&(_=ce)}}else if(ne==="pos_x"){const Y=Z.getAttribute("value"),ce=Y?Number.parseFloat(Y):Number.NaN;Number.isFinite(ce)&&(H=ce)}else if(ne==="pos_y"){const Y=Z.getAttribute("value"),ce=Y?Number.parseFloat(Y):Number.NaN;Number.isFinite(ce)&&(I=ce)}}if(_==null)continue;(H!==0||I!==0)&&s.set(_,{offsetX:H,offsetY:I});const z=F.getElementsByTagName("model_instance");for(let L=0;L<z.length;L++){const ne=z[L].getElementsByTagName("metadata");for(let Y=0;Y<ne.length;Y++){const ce=ne[Y];if(ce.getAttribute("key")==="object_id"){const ue=ce.getAttribute("value");ue&&m.set(ue,_)}}}}}catch{}const f=new Map,g=Object.keys(e.files).filter(k=>k.startsWith("Metadata/plate_")&&k.endsWith(".json"));for(const k of g){const C=k.match(/^Metadata\/plate_(\d+)\.json$/);if(!C)continue;const P=Number.parseInt(C[1],10);if(Number.isFinite(P))try{const T=await e.files[k].async("string"),A=JSON.parse(T),F=A.bbox_objects??[];for(const _ of F)_?.name&&f.set(_.name,P);if(Array.isArray(A.bbox_all)&&A.bbox_all.length>=4){const[_,M,H,I]=A.bbox_all;[_,M,H,I].every(z=>Number.isFinite(z))&&i.set(P,{minX:_,minY:M,maxX:H,maxY:I})}}catch{}}const w=Object.keys(e.files).find(k=>k==="3D/3dmodel.model"||k.endsWith("/3dmodel.model"));if(!w){const k=Object.keys(e.files).find(C=>C.endsWith(".model"));if(k){const C=await l(k);if(C){const P=await Iq(C,0);P.length>0&&n.set("1",{id:"1",meshes:P,defaultExtruder:0})}}return{objects:n,buildItems:a,plateBounds:i,plateOffsets:s}}const b=await l(w);if(!b)return{objects:n,buildItems:a,plateBounds:i,plateOffsets:s};const x=b.getElementsByTagName("object");for(let k=0;k<x.length;k++){k>0&&await Kx();const C=x[k],P=C.getAttribute("id");if(!P)continue;const T=Oq(C)??m.get(P)??null;let A=c.get(P)??-1;if(A<0){const H=C.getAttribute("p:extruder")||C.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","extruder")||"1";A=Math.max(0,parseInt(H,10)-1)}const F=[],_=C.getElementsByTagName("mesh");for(let H=0;H<_.length;H++){const I=_[H],z=[],L=[],Z=I.getElementsByTagName("vertex");for(let Y=0;Y<Z.length;Y++){const ce=Z[Y];z.push(parseFloat(ce.getAttribute("x")||"0"),parseFloat(ce.getAttribute("y")||"0"),parseFloat(ce.getAttribute("z")||"0")),Y>0&&Y%YJ===0&&await Kx()}const ne=I.getElementsByTagName("triangle");for(let Y=0;Y<ne.length;Y++){const ce=ne[Y];L.push(parseInt(ce.getAttribute("v1")||"0"),parseInt(ce.getAttribute("v2")||"0"),parseInt(ce.getAttribute("v3")||"0")),Y>0&&Y%XJ===0&&await Kx()}z.length>0&&L.length>0&&F.push({vertices:z,triangles:L,extruder:A})}const M=C.getElementsByTagName("component");for(let H=0;H<M.length;H++){await Kx();const I=M[H],z=I.getAttribute("p:path")||I.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","path"),L=I.getAttribute("objectid");if(z){const Z=await l(z);if(Z){const ne=L?`${P}:${L}`:null,Y=ne?d.get(ne)??A:A,ce=await Iq(Z,Y),ue=I.getAttribute("transform"),oe=Rq(ue);for(const Q of ce)if(ue){const le=[];for(let pe=0;pe<Q.vertices.length;pe+=3){const he=new Lt(Q.vertices[pe],Q.vertices[pe+1],Q.vertices[pe+2]);he.applyMatrix4(oe),le.push(he.x,he.y,he.z)}F.push({vertices:le,triangles:Q.triangles,extruder:Q.extruder})}else F.push(Q)}}}F.length>0&&n.set(P,{id:P,meshes:F,defaultExtruder:A,plateId:T})}const S=b.getElementsByTagName("build");if(S.length>0){const k=S[0].getElementsByTagName("item");for(let C=0;C<k.length;C++){const P=k[C],T=P.getAttribute("objectid");if(!T)continue;const A=Rq(P.getAttribute("transform")),F=Oq(P),_=n.get(T)?.plateId??null,M=u.get(T),H=M?f.get(M)??null:null;a.push({objectId:T,transform:A,plateId:F??_??H??null})}}return{objects:n,buildItems:a,plateBounds:i,plateOffsets:s}}function zq(t){const e=new Sc,n=new Float32Array(t.vertices.length);for(let a=0;a<t.vertices.length;a+=3)n[a]=t.vertices[a],n[a+1]=t.vertices[a+2],n[a+2]=t.vertices[a+1];return e.setAttribute("position",new wo(n,3)),e.setIndex(t.triangles),e.computeVertexNormals(),e}function rCe(t){t.traverse(e=>{if(e instanceof _c)if(e.geometry.dispose(),Array.isArray(e.material))for(const n of e.material)n.dispose();else e.material.dispose()})}function aCe(t,e,n){const{objects:a,buildItems:i}=t,s=new Wx,o=m=>{const f=n?.[m]||"#00ae42",g=new cr(f);return new BJ({color:g,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=a.get(m.objectId);if(p)for(const f of p.meshes){const g=m.extruder??f.extruder,w=[];for(let x=0;x<f.vertices.length;x+=3){const S=new Lt(f.vertices[x],f.vertices[x+1],f.vertices[x+2]);S.applyMatrix4(m.transform),w.push(S.x,S.y,S.z)}const b=zq({vertices:w,triangles:f.triangles});l.has(g)||l.set(g,[]),l.get(g).push(b)}}else for(const m of a.values())for(const p of m.meshes){const f=p.extruder,g=zq(p);l.has(f)||l.set(f,[]),l.get(f).push(g)}for(const[m,p]of l){if(p.length===0)continue;const f=p.length===1?p[0]:YNe(p,!1);if(f){const g=o(m),w=new _c(f,g);s.add(w)}if(p.length>1)for(const g of p)g.dispose()}return s}function ZJ({url:t,fileType:e,buildVolume:n={x:256,y:256,z:256},filamentColors:a,selectedPlateId:i=null,className:s=""}){const{t:o}=_t(),l=y.useRef(null),c=y.useRef(null),d=y.useRef(null),u=y.useRef(null),m=y.useRef(null),p=y.useRef(null),f=y.useRef(null),g=y.useRef(null),[w,b]=y.useState(!0),[x,S]=y.useState(null),[k,C]=y.useState(null),[P,T]=y.useState(null);y.useEffect(()=>{if(!l.current)return;const _=l.current,M=_.clientWidth,H=_.clientHeight,I=new jwe;I.background=new cr(1710618),d.current=I;const z=new ac(45,M/H,.1,1e4);z.position.set(150,150,150),u.current=z;const L=new LNe({antialias:!0});L.setSize(M,H),L.setPixelRatio(window.devicePixelRatio),_.appendChild(L.domElement),c.current=L;const Z=new INe(z,L.domElement);Z.enableDamping=!0,Z.dampingFactor=.05,m.current=Z;const ne=new Vwe(16777215,.6);I.add(ne);const Y=new sq(16777215,.8);Y.position.set(100,100,100),I.add(Y);const ce=new sq(16777215,.4);ce.position.set(-100,50,-100),I.add(ce);const ue=Math.max(n.x,n.y),oe=Math.ceil(ue/16),Q=new Wwe(ue,oe,4473924,3355443);I.add(Q),g.current=Q;const le=new GO(n.x,n.y),pe=new qO({color:44610,transparent:!0,opacity:.15,side:Qd}),he=new _c(le,pe);he.rotation.x=-Math.PI/2,he.position.y=-.5,I.add(he),f.current=he;let we;const $=()=>{we=requestAnimationFrame($),Z.update(),L.render(I,z)};$(),b(!0),S(null),C(null),T(null);const J=(e||t.split("?")[0].split(".").pop()||"").toLowerCase(),j={},E=Wm();E&&(j.Authorization=`Bearer ${E}`),J==="stl"?fetch(t,{headers:j}).then(O=>{if(!O.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return O.arrayBuffer()}).then(O=>{const U=new XNe().parse(O);U.computeVertexNormals(),U.rotateX(-Math.PI/2),T(U)}).catch(O=>{S(O.message),b(!1)}):J==="3mf"?fetch(t,{headers:j}).then(O=>{if(!O.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return O.arrayBuffer()}).then(nCe).then(O=>{if(O.objects.size===0)throw new Error(o("modelViewer.errors.noMeshes"));C(O)}).catch(O=>{S(O.message),b(!1)}):(S(o("modelViewer.errors.unsupportedFormat")),b(!1));const B=()=>{if(!_)return;const O=_.clientWidth,ie=_.clientHeight;O===0||ie===0||(z.aspect=O/ie,z.updateProjectionMatrix(),L.setSize(O,ie))};window.addEventListener("resize",B);const W=new ResizeObserver(()=>{B()});return W.observe(_),()=>{window.removeEventListener("resize",B),W.disconnect(),cancelAnimationFrame(we),Z.dispose(),L.dispose(),_.removeChild(L.domElement),p.current=null,f.current=null,g.current=null}},[t,n,e,o]),y.useEffect(()=>{if(!d.current||!u.current||!m.current||!k&&!P)return;p.current&&(d.current.remove(p.current),rCe(p.current));const _=!!P,M=_?(()=>{const J=a?.[0]||"#00ae42",j=new BJ({color:new cr(J),shininess:30}),E=new _c(P,j),B=new Wx;return B.add(E),B})():aCe(k,i??null,a);p.current=M,d.current.add(M);const H=new Fh().setFromObject(M),I=H.getCenter(new Lt);M.position.y=-H.min.y;const z=!_&&i!=null&&k.buildItems.length>0?k.plateBounds.get(i):void 0,L=!_&&i!=null?k.plateOffsets.get(i):void 0,Z=_||k.buildItems.length===0||i!=null&&!z&&!L,ne=Z?-I.x:0,Y=Z?-I.z:0;let ce=0,ue=0;if(!_&&i!=null&&k.buildItems.length>0&&z){const J=new Fh().setFromObject(M);ce=J.min.x-z.minX,ue=J.min.z-z.minY}const oe=n.x/2,Q=n.y/2;!_&&i!=null&&k.buildItems.length>0&&z?(M.position.x=ne-ce,M.position.z=Y-ue):!_&&i!=null&&L?(M.position.x=ne+(oe-L.offsetX),M.position.z=Y+(Q-L.offsetY)):Z?(M.position.x=ne+oe,M.position.z=Y+Q):(M.position.x=ne,M.position.z=Y),f.current&&(f.current.position.x=oe,f.current.position.z=Q),g.current&&(g.current.position.x=oe,g.current.position.z=Q);const le=new Fh().setFromObject(M),pe=le.getCenter(new Lt),he=le.getSize(new Lt),$=Math.max(he.x,he.y,he.z)*1.8;u.current.position.set(pe.x+$*.7,pe.y+$*.5,pe.z+$*.7),m.current.target.copy(pe),m.current.update(),b(!1)},[k,P,i,a,n]);const A=()=>{u.current&&m.current&&(u.current.position.set(150,150,150),m.current.target.set(0,50,0),m.current.update())},F=_=>{u.current&&u.current.position.multiplyScalar(_)};return r.jsxs("div",{className:`relative ${s}`,children:[r.jsx("div",{ref:l,className:"w-full h-full min-h-[400px]"}),w&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}),x&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:r.jsx("p",{className:"text-red-400",children:x})}),!w&&!x&&r.jsxs("div",{className:"absolute bottom-4 right-4 flex gap-2",children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>F(.8),children:r.jsx(CO,{className:"w-4 h-4"})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>F(1.25),children:r.jsx(PO,{className:"w-4 h-4"})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:A,children:r.jsx(fs,{className:"w-4 h-4"})})]})]})}const FT="159",dx={ROTATE:0,DOLLY:1,PAN:2},ux={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},iCe=0,Uq=1,sCe=2,JJ=1,oCe=2,um=3,Qh=0,Ko=1,xm=2,Lh=0,sy=1,Bq=2,Hq=3,qq=4,lCe=5,eg=100,cCe=101,dCe=102,$q=103,Vq=104,uCe=200,mCe=201,pCe=202,hCe=203,WL=204,KL=205,fCe=206,gCe=207,bCe=208,xCe=209,yCe=210,vCe=211,wCe=212,SCe=213,_Ce=214,kCe=0,NCe=1,CCe=2,hC=3,PCe=4,TCe=5,ACe=6,jCe=7,QO=0,MCe=1,ECe=2,Rh=0,DCe=1,FCe=2,LCe=3,RCe=4,ICe=5,eee=300,ky=301,Ny=302,QL=303,YL=304,LT=306,XL=1e3,rd=1001,ZL=1002,js=1003,Gq=1004,VE=1005,ic=1006,OCe=1007,Bw=1008,Ih=1009,zCe=1010,UCe=1011,YO=1012,tee=1013,yh=1014,km=1015,Hw=1016,nee=1017,ree=1018,fg=1020,BCe=1021,sc=1023,HCe=1024,qCe=1025,gg=1026,Cy=1027,$Ce=1028,aee=1029,VCe=1030,iee=1031,see=1033,GE=33776,WE=33777,KE=33778,QE=33779,Wq=35840,Kq=35841,Qq=35842,Yq=35843,oee=36196,Xq=37492,Zq=37496,Jq=37808,e$=37809,t$=37810,n$=37811,r$=37812,a$=37813,i$=37814,s$=37815,o$=37816,l$=37817,c$=37818,d$=37819,u$=37820,m$=37821,YE=36492,p$=36494,h$=36495,GCe=36283,f$=36284,g$=36285,b$=36286,lee=3e3,bg=3001,WCe=3200,KCe=3201,cee=0,QCe=1,oc="",Ms="srgb",Qm="srgb-linear",XO="display-p3",RT="display-p3-linear",fC="linear",Ta="srgb",gC="rec709",bC="p3",mx=7680,x$=519,YCe=512,XCe=513,ZCe=514,dee=515,JCe=516,ePe=517,tPe=518,nPe=519,JL=35044,y$="300 es",eR=1035,eu=2e3,qw=2001;class cb{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const a=this._listeners;a[e]===void 0&&(a[e]=[]),a[e].indexOf(n)===-1&&a[e].push(n)}hasEventListener(e,n){if(this._listeners===void 0)return!1;const a=this._listeners;return a[e]!==void 0&&a[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 a=this._listeners[e.type];if(a!==void 0){e.target=this;const i=a.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}}const Vs=["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 v$=1234567;const ew=Math.PI/180,$w=180/Math.PI;function Rm(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,a=Math.random()*4294967295|0;return(Vs[t&255]+Vs[t>>8&255]+Vs[t>>16&255]+Vs[t>>24&255]+"-"+Vs[e&255]+Vs[e>>8&255]+"-"+Vs[e>>16&15|64]+Vs[e>>24&255]+"-"+Vs[n&63|128]+Vs[n>>8&255]+"-"+Vs[n>>16&255]+Vs[n>>24&255]+Vs[a&255]+Vs[a>>8&255]+Vs[a>>16&255]+Vs[a>>24&255]).toLowerCase()}function Ds(t,e,n){return Math.max(e,Math.min(n,t))}function ZO(t,e){return(t%e+e)%e}function rPe(t,e,n,a,i){return a+(t-e)*(i-a)/(n-e)}function aPe(t,e,n){return t!==e?(n-t)/(e-t):0}function tw(t,e,n){return(1-n)*t+n*e}function iPe(t,e,n,a){return tw(t,e,1-Math.exp(-n*a))}function sPe(t,e=1){return e-Math.abs(ZO(t,e*2)-e)}function oPe(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function lPe(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function cPe(t,e){return t+Math.floor(Math.random()*(e-t+1))}function dPe(t,e){return t+Math.random()*(e-t)}function uPe(t){return t*(.5-Math.random())}function mPe(t){t!==void 0&&(v$=t);let e=v$+=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 pPe(t){return t*ew}function hPe(t){return t*$w}function tR(t){return(t&t-1)===0&&t!==0}function fPe(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function xC(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function gPe(t,e,n,a,i){const s=Math.cos,o=Math.sin,l=s(n/2),c=o(n/2),d=s((e+a)/2),u=o((e+a)/2),m=s((e-a)/2),p=o((e-a)/2),f=s((a-e)/2),g=o((a-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*g,c*f,l*d);break;case"YXY":t.set(c*f,l*u,c*g,l*d);break;case"ZYZ":t.set(c*g,c*f,l*u,l*d);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Yd(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 ia(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 uee={DEG2RAD:ew,RAD2DEG:$w,generateUUID:Rm,clamp:Ds,euclideanModulo:ZO,mapLinear:rPe,inverseLerp:aPe,lerp:tw,damp:iPe,pingpong:sPe,smoothstep:oPe,smootherstep:lPe,randInt:cPe,randFloat:dPe,randFloatSpread:uPe,seededRandom:mPe,degToRad:pPe,radToDeg:hPe,isPowerOfTwo:tR,ceilPowerOfTwo:fPe,floorPowerOfTwo:xC,setQuaternionFromProperEuler:gPe,normalize:ia,denormalize:Yd};class Wn{constructor(e=0,n=0){Wn.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,a=this.y,i=e.elements;return this.x=i[0]*n+i[3]*a+i[6],this.y=i[1]*n+i[4]*a+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 a=this.length();return this.divideScalar(a||1).multiplyScalar(Math.max(e,Math.min(n,a)))}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 a=this.dot(e)/n;return Math.acos(Ds(a,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,a=this.y-e.y;return n*n+a*a}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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,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 a=Math.cos(n),i=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*a-o*i+e.x,this.y=s*i+o*a+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class pr{constructor(e,n,a,i,s,o,l,c,d){pr.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,a,i,s,o,l,c,d)}set(e,n,a,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]=a,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,a=e.elements;return n[0]=a[0],n[1]=a[1],n[2]=a[2],n[3]=a[3],n[4]=a[4],n[5]=a[5],n[6]=a[6],n[7]=a[7],n[8]=a[8],this}extractBasis(e,n,a){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),a.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 a=e.elements,i=n.elements,s=this.elements,o=a[0],l=a[3],c=a[6],d=a[1],u=a[4],m=a[7],p=a[2],f=a[5],g=a[8],w=i[0],b=i[3],x=i[6],S=i[1],k=i[4],C=i[7],P=i[2],T=i[5],A=i[8];return s[0]=o*w+l*S+c*P,s[3]=o*b+l*k+c*T,s[6]=o*x+l*C+c*A,s[1]=d*w+u*S+m*P,s[4]=d*b+u*k+m*T,s[7]=d*x+u*C+m*A,s[2]=p*w+f*S+g*P,s[5]=p*b+f*k+g*T,s[8]=p*x+f*C+g*A,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],a=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-a*s*u+a*l*c+i*s*d-i*o*c}invert(){const e=this.elements,n=e[0],a=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,g=n*m+a*p+i*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const w=1/g;return e[0]=m*w,e[1]=(i*d-u*a)*w,e[2]=(l*a-i*o)*w,e[3]=p*w,e[4]=(u*n-i*c)*w,e[5]=(i*s-l*n)*w,e[6]=f*w,e[7]=(a*c-d*n)*w,e[8]=(o*n-a*s)*w,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,a,i,s,o,l){const c=Math.cos(s),d=Math.sin(s);return this.set(a*c,a*d,-a*(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(XE.makeScale(e,n)),this}rotate(e){return this.premultiply(XE.makeRotation(-e)),this}translate(e,n){return this.premultiply(XE.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),a=Math.sin(e);return this.set(n,-a,0,a,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,a=e.elements;for(let i=0;i<9;i++)if(n[i]!==a[i])return!1;return!0}fromArray(e,n=0){for(let a=0;a<9;a++)this.elements[a]=e[a+n];return this}toArray(e=[],n=0){const a=this.elements;return e[n]=a[0],e[n+1]=a[1],e[n+2]=a[2],e[n+3]=a[3],e[n+4]=a[4],e[n+5]=a[5],e[n+6]=a[6],e[n+7]=a[7],e[n+8]=a[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const XE=new pr;function mee(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function yC(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function bPe(){const t=yC("canvas");return t.style.display="block",t}const w$={};function nw(t){t in w$||(w$[t]=!0,console.warn(t))}const S$=new pr().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),_$=new pr().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),Zk={[Qm]:{transfer:fC,primaries:gC,toReference:t=>t,fromReference:t=>t},[Ms]:{transfer:Ta,primaries:gC,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[RT]:{transfer:fC,primaries:bC,toReference:t=>t.applyMatrix3(_$),fromReference:t=>t.applyMatrix3(S$)},[XO]:{transfer:Ta,primaries:bC,toReference:t=>t.convertSRGBToLinear().applyMatrix3(_$),fromReference:t=>t.applyMatrix3(S$).convertLinearToSRGB()}},xPe=new Set([Qm,RT]),sa={enabled:!0,_workingColorSpace:Qm,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(!xPe.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 a=Zk[e].toReference,i=Zk[n].fromReference;return i(a(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 Zk[t].primaries},getTransfer:function(t){return t===oc?fC:Zk[t].transfer}};function oy(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function ZE(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let px;class pee{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{px===void 0&&(px=yC("canvas")),px.width=e.width,px.height=e.height;const a=px.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,e.width,e.height),n=px}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=yC("canvas");n.width=e.width,n.height=e.height;const a=n.getContext("2d");a.drawImage(e,0,0,e.width,e.height);const i=a.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=oy(s[o]/255)*255;return a.putImageData(i,0,0),n}else if(e.data){const n=e.data.slice(0);for(let a=0;a<n.length;a++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[a]=Math.floor(oy(n[a]/255)*255):n[a]=oy(n[a]);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 yPe=0;class hee{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:yPe++}),this.uuid=Rm(),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 a={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(JE(i[o].image)):s.push(JE(i[o]))}else s=JE(i);a.url=s}return n||(e.images[this.uuid]=a),a}}function JE(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?pee.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 vPe=0;class Qo extends cb{constructor(e=Qo.DEFAULT_IMAGE,n=Qo.DEFAULT_MAPPING,a=rd,i=rd,s=ic,o=Bw,l=sc,c=Ih,d=Qo.DEFAULT_ANISOTROPY,u=oc){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:vPe++}),this.uuid=Rm(),this.name="",this.source=new hee(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=a,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=d,this.format=l,this.internalFormat=null,this.type=c,this.offset=new Wn(0,0),this.repeat=new Wn(1,1),this.center=new Wn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new pr,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof u=="string"?this.colorSpace=u:(nw("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=u===bg?Ms:oc),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 a={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&&(a.userData=this.userData),n||(e.textures[this.uuid]=a),a}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==eee)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case XL:e.x=e.x-Math.floor(e.x);break;case rd:e.x=e.x<0?0:1;break;case ZL: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 XL:e.y=e.y-Math.floor(e.y);break;case rd:e.y=e.y<0?0:1;break;case ZL: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 nw("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Ms?bg:lee}set encoding(e){nw("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===bg?Ms:oc}}Qo.DEFAULT_IMAGE=null;Qo.DEFAULT_MAPPING=eee;Qo.DEFAULT_ANISOTROPY=1;class la{constructor(e=0,n=0,a=0,i=1){la.prototype.isVector4=!0,this.x=e,this.y=n,this.z=a,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,a,i){return this.x=e,this.y=n,this.z=a,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,a=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*a+o[8]*i+o[12]*s,this.y=o[1]*n+o[5]*a+o[9]*i+o[13]*s,this.z=o[2]*n+o[6]*a+o[10]*i+o[14]*s,this.w=o[3]*n+o[7]*a+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,a,i,s;const c=e.elements,d=c[0],u=c[4],m=c[8],p=c[1],f=c[5],g=c[9],w=c[2],b=c[6],x=c[10];if(Math.abs(u-p)<.01&&Math.abs(m-w)<.01&&Math.abs(g-b)<.01){if(Math.abs(u+p)<.1&&Math.abs(m+w)<.1&&Math.abs(g+b)<.1&&Math.abs(d+f+x-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const k=(d+1)/2,C=(f+1)/2,P=(x+1)/2,T=(u+p)/4,A=(m+w)/4,F=(g+b)/4;return k>C&&k>P?k<.01?(a=0,i=.707106781,s=.707106781):(a=Math.sqrt(k),i=T/a,s=A/a):C>P?C<.01?(a=.707106781,i=0,s=.707106781):(i=Math.sqrt(C),a=T/i,s=F/i):P<.01?(a=.707106781,i=.707106781,s=0):(s=Math.sqrt(P),a=A/s,i=F/s),this.set(a,i,s,n),this}let S=Math.sqrt((b-g)*(b-g)+(m-w)*(m-w)+(p-u)*(p-u));return Math.abs(S)<.001&&(S=1),this.x=(b-g)/S,this.y=(m-w)/S,this.z=(p-u)/S,this.w=Math.acos((d+f+x-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 a=this.length();return this.divideScalar(a||1).multiplyScalar(Math.max(e,Math.min(n,a)))}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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,this.z=e.z+(n.z-e.z)*a,this.w=e.w+(n.w-e.w)*a,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 wPe extends cb{constructor(e=1,n=1,a={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new la(0,0,e,n),this.scissorTest=!1,this.viewport=new la(0,0,e,n);const i={width:e,height:n,depth:1};a.encoding!==void 0&&(nw("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),a.colorSpace=a.encoding===bg?Ms:oc),a=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ic,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},a),this.texture=new Qo(i,a.mapping,a.wrapS,a.wrapT,a.magFilter,a.minFilter,a.format,a.type,a.anisotropy,a.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=a.generateMipmaps,this.texture.internalFormat=a.internalFormat,this.depthBuffer=a.depthBuffer,this.stencilBuffer=a.stencilBuffer,this.depthTexture=a.depthTexture,this.samples=a.samples}setSize(e,n,a=1){(this.width!==e||this.height!==n||this.depth!==a)&&(this.width=e,this.height=n,this.depth=a,this.texture.image.width=e,this.texture.image.height=n,this.texture.image.depth=a,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 hee(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 Og extends wPe{constructor(e=1,n=1,a={}){super(e,n,a),this.isWebGLRenderTarget=!0}}class fee extends Qo{constructor(e=null,n=1,a=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:a,depth:i},this.magFilter=js,this.minFilter=js,this.wrapR=rd,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class SPe extends Qo{constructor(e=null,n=1,a=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:a,depth:i},this.magFilter=js,this.minFilter=js,this.wrapR=rd,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class zg{constructor(e=0,n=0,a=0,i=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=a,this._w=i}static slerpFlat(e,n,a,i,s,o,l){let c=a[i+0],d=a[i+1],u=a[i+2],m=a[i+3];const p=s[o+0],f=s[o+1],g=s[o+2],w=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]=g,e[n+3]=w;return}if(m!==w||c!==p||d!==f||u!==g){let b=1-l;const x=c*p+d*f+u*g+m*w,S=x>=0?1:-1,k=1-x*x;if(k>Number.EPSILON){const P=Math.sqrt(k),T=Math.atan2(P,x*S);b=Math.sin(b*T)/P,l=Math.sin(l*T)/P}const C=l*S;if(c=c*b+p*C,d=d*b+f*C,u=u*b+g*C,m=m*b+w*C,b===1-l){const P=1/Math.sqrt(c*c+d*d+u*u+m*m);c*=P,d*=P,u*=P,m*=P}}e[n]=c,e[n+1]=d,e[n+2]=u,e[n+3]=m}static multiplyQuaternionsFlat(e,n,a,i,s,o){const l=a[i],c=a[i+1],d=a[i+2],u=a[i+3],m=s[o],p=s[o+1],f=s[o+2],g=s[o+3];return e[n]=l*g+u*m+c*f-d*p,e[n+1]=c*g+u*p+d*m-l*f,e[n+2]=d*g+u*f+l*p-c*m,e[n+3]=u*g-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,a,i){return this._x=e,this._y=n,this._z=a,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 a=e._x,i=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,d=l(a/2),u=l(i/2),m=l(s/2),p=c(a/2),f=c(i/2),g=c(s/2);switch(o){case"XYZ":this._x=p*u*m+d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m-p*f*g;break;case"YXZ":this._x=p*u*m+d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m+p*f*g;break;case"ZXY":this._x=p*u*m-d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m-p*f*g;break;case"ZYX":this._x=p*u*m-d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m+p*f*g;break;case"YZX":this._x=p*u*m+d*f*g,this._y=d*f*m+p*u*g,this._z=d*u*g-p*f*m,this._w=d*u*m-p*f*g;break;case"XZY":this._x=p*u*m-d*f*g,this._y=d*f*m-p*u*g,this._z=d*u*g+p*f*m,this._w=d*u*m+p*f*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n!==!1&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const a=n/2,i=Math.sin(a);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(a),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,a=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=a+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(a>l&&a>m){const f=2*Math.sqrt(1+a-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-a-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-a-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 a=e.dot(n)+1;return a<Number.EPSILON?(a=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=a):(this._x=0,this._y=-e.z,this._z=e.y,this._w=a)):(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=a),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ds(this.dot(e),-1,1)))}rotateTowards(e,n){const a=this.angleTo(e);if(a===0)return this;const i=Math.min(1,n/a);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 a=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=a*u+o*l+i*d-s*c,this._y=i*u+o*c+s*l-a*d,this._z=s*u+o*d+a*c-i*l,this._w=o*u-a*l-i*c-s*d,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const a=this._x,i=this._y,s=this._z,o=this._w;let l=o*e._w+a*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=a,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*a+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=a*m+this._x*p,this._y=i*m+this._y*p,this._z=s*m+this._z*p,this._onChangeCallback(),this}slerpQuaternions(e,n,a){return this.copy(e).slerp(n,a)}random(){const e=Math.random(),n=Math.sqrt(1-e),a=Math.sqrt(e),i=2*Math.PI*Math.random(),s=2*Math.PI*Math.random();return this.set(n*Math.cos(i),a*Math.sin(s),a*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 yt{constructor(e=0,n=0,a=0){yt.prototype.isVector3=!0,this.x=e,this.y=n,this.z=a}set(e,n,a){return a===void 0&&(a=this.z),this.x=e,this.y=n,this.z=a,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(k$.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(k$.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,a=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[3]*a+s[6]*i,this.y=s[1]*n+s[4]*a+s[7]*i,this.z=s[2]*n+s[5]*a+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,a=this.y,i=this.z,s=e.elements,o=1/(s[3]*n+s[7]*a+s[11]*i+s[15]);return this.x=(s[0]*n+s[4]*a+s[8]*i+s[12])*o,this.y=(s[1]*n+s[5]*a+s[9]*i+s[13])*o,this.z=(s[2]*n+s[6]*a+s[10]*i+s[14])*o,this}applyQuaternion(e){const n=this.x,a=this.y,i=this.z,s=e.x,o=e.y,l=e.z,c=e.w,d=2*(o*i-l*a),u=2*(l*n-s*i),m=2*(s*a-o*n);return this.x=n+c*d+o*m-l*u,this.y=a+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,a=this.y,i=this.z,s=e.elements;return this.x=s[0]*n+s[4]*a+s[8]*i,this.y=s[1]*n+s[5]*a+s[9]*i,this.z=s[2]*n+s[6]*a+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 a=this.length();return this.divideScalar(a||1).multiplyScalar(Math.max(e,Math.min(n,a)))}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,a){return this.x=e.x+(n.x-e.x)*a,this.y=e.y+(n.y-e.y)*a,this.z=e.z+(n.z-e.z)*a,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const a=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-a*c,this.z=a*l-i*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const a=e.dot(this)/n;return this.copy(e).multiplyScalar(a)}projectOnPlane(e){return e2.copy(this).projectOnVector(e),this.sub(e2)}reflect(e){return this.sub(e2.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 a=this.dot(e)/n;return Math.acos(Ds(a,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,a=this.y-e.y,i=this.z-e.z;return n*n+a*a+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,a){const i=Math.sin(n)*e;return this.x=i*Math.sin(a),this.y=Math.cos(n)*e,this.z=i*Math.cos(a),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,a){return this.x=e*Math.sin(n),this.y=a,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(),a=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=a,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,a=Math.sqrt(1-e**2);return this.x=a*Math.cos(n),this.y=a*Math.sin(n),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const e2=new yt,k$=new zg;class gc{constructor(e=new yt(1/0,1/0,1/0),n=new yt(-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,a=e.length;n<a;n+=3)this.expandByPoint(Xc.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,a=e.count;n<a;n++)this.expandByPoint(Xc.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,a=e.length;n<a;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const a=Xc.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(a),this.max.copy(e).add(a),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 a=e.geometry;if(a!==void 0){const s=a.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,Xc):Xc.fromBufferAttribute(s,o),Xc.applyMatrix4(e.matrixWorld),this.expandByPoint(Xc);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Jk.copy(e.boundingBox)):(a.boundingBox===null&&a.computeBoundingBox(),Jk.copy(a.boundingBox)),Jk.applyMatrix4(e.matrixWorld),this.union(Jk)}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,Xc),Xc.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,a;return e.normal.x>0?(n=e.normal.x*this.min.x,a=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,a=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,a+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,a+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,a+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,a+=e.normal.z*this.min.z),n<=-e.constant&&a>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(l0),e1.subVectors(this.max,l0),hx.subVectors(e.a,l0),fx.subVectors(e.b,l0),gx.subVectors(e.c,l0),$p.subVectors(fx,hx),Vp.subVectors(gx,fx),Of.subVectors(hx,gx);let n=[0,-$p.z,$p.y,0,-Vp.z,Vp.y,0,-Of.z,Of.y,$p.z,0,-$p.x,Vp.z,0,-Vp.x,Of.z,0,-Of.x,-$p.y,$p.x,0,-Vp.y,Vp.x,0,-Of.y,Of.x,0];return!t2(n,hx,fx,gx,e1)||(n=[1,0,0,0,1,0,0,0,1],!t2(n,hx,fx,gx,e1))?!1:(t1.crossVectors($p,Vp),n=[t1.x,t1.y,t1.z],t2(n,hx,fx,gx,e1))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Xc).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Xc).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:(tm[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),tm[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),tm[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),tm[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),tm[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),tm[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),tm[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),tm[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(tm),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 tm=[new yt,new yt,new yt,new yt,new yt,new yt,new yt,new yt],Xc=new yt,Jk=new gc,hx=new yt,fx=new yt,gx=new yt,$p=new yt,Vp=new yt,Of=new yt,l0=new yt,e1=new yt,t1=new yt,zf=new yt;function t2(t,e,n,a,i){for(let s=0,o=t.length-3;s<=o;s+=3){zf.fromArray(t,s);const l=i.x*Math.abs(zf.x)+i.y*Math.abs(zf.y)+i.z*Math.abs(zf.z),c=e.dot(zf),d=n.dot(zf),u=a.dot(zf);if(Math.max(-Math.max(c,d,u),Math.min(c,d,u))>l)return!1}return!0}const _Pe=new gc,c0=new yt,n2=new yt;class lu{constructor(e=new yt,n=-1){this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const a=this.center;n!==void 0?a.copy(n):_Pe.setFromPoints(e).getCenter(a);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,a.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 a=this.center.distanceToSquared(e);return n.copy(e),a>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;c0.subVectors(e,this.center);const n=c0.lengthSq();if(n>this.radius*this.radius){const a=Math.sqrt(n),i=(a-this.radius)*.5;this.center.addScaledVector(c0,i/a),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):(n2.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(c0.copy(e.center).add(n2)),this.expandByPoint(c0.copy(e.center).sub(n2))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const nm=new yt,r2=new yt,n1=new yt,Gp=new yt,a2=new yt,r1=new yt,i2=new yt;class JO{constructor(e=new yt,n=new yt(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,nm)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const a=n.dot(this.direction);return a<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,a)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=nm.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(nm.copy(this.origin).addScaledVector(this.direction,n),nm.distanceToSquared(e))}distanceSqToSegment(e,n,a,i){r2.copy(e).add(n).multiplyScalar(.5),n1.copy(n).sub(e).normalize(),Gp.copy(this.origin).sub(r2);const s=e.distanceTo(n)*.5,o=-this.direction.dot(n1),l=Gp.dot(this.direction),c=-Gp.dot(n1),d=Gp.lengthSq(),u=Math.abs(1-o*o);let m,p,f,g;if(u>0)if(m=o*c-l,p=o*l-c,g=s*u,m>=0)if(p>=-g)if(p<=g){const w=1/u;m*=w,p*=w,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<=-g?(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<=g?(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 a&&a.copy(this.origin).addScaledVector(this.direction,m),i&&i.copy(r2).addScaledVector(n1,p),f}intersectSphere(e,n){nm.subVectors(e.center,this.origin);const a=nm.dot(this.direction),i=nm.dot(nm)-a*a,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),l=a-o,c=a+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 a=-(this.origin.dot(e.normal)+e.constant)/n;return a>=0?a:null}intersectPlane(e,n){const a=this.distanceToPlane(e);return a===null?null:this.at(a,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let a,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?(a=(e.min.x-p.x)*d,i=(e.max.x-p.x)*d):(a=(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),a>o||s>i||((s>a||isNaN(a))&&(a=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),a>c||l>i)||((l>a||a!==a)&&(a=l),(c<i||i!==i)&&(i=c),i<0)?null:this.at(a>=0?a:i,n)}intersectsBox(e){return this.intersectBox(e,nm)!==null}intersectTriangle(e,n,a,i,s){a2.subVectors(n,e),r1.subVectors(a,e),i2.crossVectors(a2,r1);let o=this.direction.dot(i2),l;if(o>0){if(i)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Gp.subVectors(this.origin,e);const c=l*this.direction.dot(r1.crossVectors(Gp,r1));if(c<0)return null;const d=l*this.direction.dot(a2.cross(Gp));if(d<0||c+d>o)return null;const u=-l*Gp.dot(i2);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 Sa{constructor(e,n,a,i,s,o,l,c,d,u,m,p,f,g,w,b){Sa.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,a,i,s,o,l,c,d,u,m,p,f,g,w,b)}set(e,n,a,i,s,o,l,c,d,u,m,p,f,g,w,b){const x=this.elements;return x[0]=e,x[4]=n,x[8]=a,x[12]=i,x[1]=s,x[5]=o,x[9]=l,x[13]=c,x[2]=d,x[6]=u,x[10]=m,x[14]=p,x[3]=f,x[7]=g,x[11]=w,x[15]=b,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 Sa().fromArray(this.elements)}copy(e){const n=this.elements,a=e.elements;return n[0]=a[0],n[1]=a[1],n[2]=a[2],n[3]=a[3],n[4]=a[4],n[5]=a[5],n[6]=a[6],n[7]=a[7],n[8]=a[8],n[9]=a[9],n[10]=a[10],n[11]=a[11],n[12]=a[12],n[13]=a[13],n[14]=a[14],n[15]=a[15],this}copyPosition(e){const n=this.elements,a=e.elements;return n[12]=a[12],n[13]=a[13],n[14]=a[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,a){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),a.setFromMatrixColumn(this,2),this}makeBasis(e,n,a){return this.set(e.x,n.x,a.x,0,e.y,n.y,a.y,0,e.z,n.z,a.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,a=e.elements,i=1/bx.setFromMatrixColumn(e,0).length(),s=1/bx.setFromMatrixColumn(e,1).length(),o=1/bx.setFromMatrixColumn(e,2).length();return n[0]=a[0]*i,n[1]=a[1]*i,n[2]=a[2]*i,n[3]=0,n[4]=a[4]*s,n[5]=a[5]*s,n[6]=a[6]*s,n[7]=0,n[8]=a[8]*o,n[9]=a[9]*o,n[10]=a[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,a=e.x,i=e.y,s=e.z,o=Math.cos(a),l=Math.sin(a),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,g=l*u,w=l*m;n[0]=c*u,n[4]=-c*m,n[8]=d,n[1]=f+g*d,n[5]=p-w*d,n[9]=-l*c,n[2]=w-p*d,n[6]=g+f*d,n[10]=o*c}else if(e.order==="YXZ"){const p=c*u,f=c*m,g=d*u,w=d*m;n[0]=p+w*l,n[4]=g*l-f,n[8]=o*d,n[1]=o*m,n[5]=o*u,n[9]=-l,n[2]=f*l-g,n[6]=w+p*l,n[10]=o*c}else if(e.order==="ZXY"){const p=c*u,f=c*m,g=d*u,w=d*m;n[0]=p-w*l,n[4]=-o*m,n[8]=g+f*l,n[1]=f+g*l,n[5]=o*u,n[9]=w-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,g=l*u,w=l*m;n[0]=c*u,n[4]=g*d-f,n[8]=p*d+w,n[1]=c*m,n[5]=w*d+p,n[9]=f*d-g,n[2]=-d,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const p=o*c,f=o*d,g=l*c,w=l*d;n[0]=c*u,n[4]=w-p*m,n[8]=g*m+f,n[1]=m,n[5]=o*u,n[9]=-l*u,n[2]=-d*u,n[6]=f*m+g,n[10]=p-w*m}else if(e.order==="XZY"){const p=o*c,f=o*d,g=l*c,w=l*d;n[0]=c*u,n[4]=-m,n[8]=d*u,n[1]=p*m+w,n[5]=o*u,n[9]=f*m-g,n[2]=g*m-f,n[6]=l*u,n[10]=w*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(kPe,e,NPe)}lookAt(e,n,a){const i=this.elements;return ml.subVectors(e,n),ml.lengthSq()===0&&(ml.z=1),ml.normalize(),Wp.crossVectors(a,ml),Wp.lengthSq()===0&&(Math.abs(a.z)===1?ml.x+=1e-4:ml.z+=1e-4,ml.normalize(),Wp.crossVectors(a,ml)),Wp.normalize(),a1.crossVectors(ml,Wp),i[0]=Wp.x,i[4]=a1.x,i[8]=ml.x,i[1]=Wp.y,i[5]=a1.y,i[9]=ml.y,i[2]=Wp.z,i[6]=a1.z,i[10]=ml.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const a=e.elements,i=n.elements,s=this.elements,o=a[0],l=a[4],c=a[8],d=a[12],u=a[1],m=a[5],p=a[9],f=a[13],g=a[2],w=a[6],b=a[10],x=a[14],S=a[3],k=a[7],C=a[11],P=a[15],T=i[0],A=i[4],F=i[8],_=i[12],M=i[1],H=i[5],I=i[9],z=i[13],L=i[2],Z=i[6],ne=i[10],Y=i[14],ce=i[3],ue=i[7],oe=i[11],Q=i[15];return s[0]=o*T+l*M+c*L+d*ce,s[4]=o*A+l*H+c*Z+d*ue,s[8]=o*F+l*I+c*ne+d*oe,s[12]=o*_+l*z+c*Y+d*Q,s[1]=u*T+m*M+p*L+f*ce,s[5]=u*A+m*H+p*Z+f*ue,s[9]=u*F+m*I+p*ne+f*oe,s[13]=u*_+m*z+p*Y+f*Q,s[2]=g*T+w*M+b*L+x*ce,s[6]=g*A+w*H+b*Z+x*ue,s[10]=g*F+w*I+b*ne+x*oe,s[14]=g*_+w*z+b*Y+x*Q,s[3]=S*T+k*M+C*L+P*ce,s[7]=S*A+k*H+C*Z+P*ue,s[11]=S*F+k*I+C*ne+P*oe,s[15]=S*_+k*z+C*Y+P*Q,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],a=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],g=e[3],w=e[7],b=e[11],x=e[15];return g*(+s*c*m-i*d*m-s*l*p+a*d*p+i*l*f-a*c*f)+w*(+n*c*f-n*d*p+s*o*p-i*o*f+i*d*u-s*c*u)+b*(+n*d*m-n*l*f-s*o*m+a*o*f+s*l*u-a*d*u)+x*(-i*l*u-n*c*m+n*l*p+i*o*m-a*o*p+a*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,a){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]=a),this}invert(){const e=this.elements,n=e[0],a=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],g=e[12],w=e[13],b=e[14],x=e[15],S=m*b*d-w*p*d+w*c*f-l*b*f-m*c*x+l*p*x,k=g*p*d-u*b*d-g*c*f+o*b*f+u*c*x-o*p*x,C=u*w*d-g*m*d+g*l*f-o*w*f-u*l*x+o*m*x,P=g*m*c-u*w*c-g*l*p+o*w*p+u*l*b-o*m*b,T=n*S+a*k+i*C+s*P;if(T===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/T;return e[0]=S*A,e[1]=(w*p*s-m*b*s-w*i*f+a*b*f+m*i*x-a*p*x)*A,e[2]=(l*b*s-w*c*s+w*i*d-a*b*d-l*i*x+a*c*x)*A,e[3]=(m*c*s-l*p*s-m*i*d+a*p*d+l*i*f-a*c*f)*A,e[4]=k*A,e[5]=(u*b*s-g*p*s+g*i*f-n*b*f-u*i*x+n*p*x)*A,e[6]=(g*c*s-o*b*s-g*i*d+n*b*d+o*i*x-n*c*x)*A,e[7]=(o*p*s-u*c*s+u*i*d-n*p*d-o*i*f+n*c*f)*A,e[8]=C*A,e[9]=(g*m*s-u*w*s-g*a*f+n*w*f+u*a*x-n*m*x)*A,e[10]=(o*w*s-g*l*s+g*a*d-n*w*d-o*a*x+n*l*x)*A,e[11]=(u*l*s-o*m*s-u*a*d+n*m*d+o*a*f-n*l*f)*A,e[12]=P*A,e[13]=(u*w*i-g*m*i+g*a*p-n*w*p-u*a*b+n*m*b)*A,e[14]=(g*l*i-o*w*i-g*a*c+n*w*c+o*a*b-n*l*b)*A,e[15]=(o*m*i-u*l*i+u*a*c-n*m*c-o*a*p+n*l*p)*A,this}scale(e){const n=this.elements,a=e.x,i=e.y,s=e.z;return n[0]*=a,n[4]*=i,n[8]*=s,n[1]*=a,n[5]*=i,n[9]*=s,n[2]*=a,n[6]*=i,n[10]*=s,n[3]*=a,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],a=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,a,i))}makeTranslation(e,n,a){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,a,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),a=Math.sin(e);return this.set(1,0,0,0,0,n,-a,0,0,a,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),a=Math.sin(e);return this.set(n,0,a,0,0,1,0,0,-a,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),a=Math.sin(e);return this.set(n,-a,0,0,a,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const a=Math.cos(n),i=Math.sin(n),s=1-a,o=e.x,l=e.y,c=e.z,d=s*o,u=s*l;return this.set(d*o+a,d*l-i*c,d*c+i*l,0,d*l+i*c,u*l+a,u*c-i*o,0,d*c-i*l,u*c+i*o,s*c*c+a,0,0,0,0,1),this}makeScale(e,n,a){return this.set(e,0,0,0,0,n,0,0,0,0,a,0,0,0,0,1),this}makeShear(e,n,a,i,s,o){return this.set(1,a,s,0,e,1,o,0,n,i,1,0,0,0,0,1),this}compose(e,n,a){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,g=s*m,w=o*u,b=o*m,x=l*m,S=c*d,k=c*u,C=c*m,P=a.x,T=a.y,A=a.z;return i[0]=(1-(w+x))*P,i[1]=(f+C)*P,i[2]=(g-k)*P,i[3]=0,i[4]=(f-C)*T,i[5]=(1-(p+x))*T,i[6]=(b+S)*T,i[7]=0,i[8]=(g+k)*A,i[9]=(b-S)*A,i[10]=(1-(p+w))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,n,a){const i=this.elements;let s=bx.set(i[0],i[1],i[2]).length();const o=bx.set(i[4],i[5],i[6]).length(),l=bx.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],Zc.copy(this);const d=1/s,u=1/o,m=1/l;return Zc.elements[0]*=d,Zc.elements[1]*=d,Zc.elements[2]*=d,Zc.elements[4]*=u,Zc.elements[5]*=u,Zc.elements[6]*=u,Zc.elements[8]*=m,Zc.elements[9]*=m,Zc.elements[10]*=m,n.setFromRotationMatrix(Zc),a.x=s,a.y=o,a.z=l,this}makePerspective(e,n,a,i,s,o,l=eu){const c=this.elements,d=2*s/(n-e),u=2*s/(a-i),m=(n+e)/(n-e),p=(a+i)/(a-i);let f,g;if(l===eu)f=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(l===qw)f=-o/(o-s),g=-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]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,n,a,i,s,o,l=eu){const c=this.elements,d=1/(n-e),u=1/(a-i),m=1/(o-s),p=(n+e)*d,f=(a+i)*u;let g,w;if(l===eu)g=(o+s)*m,w=-2*m;else if(l===qw)g=s*m,w=-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]=w,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const n=this.elements,a=e.elements;for(let i=0;i<16;i++)if(n[i]!==a[i])return!1;return!0}fromArray(e,n=0){for(let a=0;a<16;a++)this.elements[a]=e[a+n];return this}toArray(e=[],n=0){const a=this.elements;return e[n]=a[0],e[n+1]=a[1],e[n+2]=a[2],e[n+3]=a[3],e[n+4]=a[4],e[n+5]=a[5],e[n+6]=a[6],e[n+7]=a[7],e[n+8]=a[8],e[n+9]=a[9],e[n+10]=a[10],e[n+11]=a[11],e[n+12]=a[12],e[n+13]=a[13],e[n+14]=a[14],e[n+15]=a[15],e}}const bx=new yt,Zc=new Sa,kPe=new yt(0,0,0),NPe=new yt(1,1,1),Wp=new yt,a1=new yt,ml=new yt,N$=new Sa,C$=new zg;class zS{constructor(e=0,n=0,a=0,i=zS.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=a,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,a,i=this._order){return this._x=e,this._y=n,this._z=a,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,a=!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(Ds(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(-Ds(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(Ds(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(-Ds(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(Ds(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(-Ds(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,a===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,a){return N$.makeRotationFromQuaternion(e),this.setFromRotationMatrix(N$,n,a)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return C$.setFromEuler(this),this.setFromQuaternion(C$,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}}zS.DEFAULT_ORDER="XYZ";class gee{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 CPe=0;const P$=new yt,xx=new zg,rm=new Sa,i1=new yt,d0=new yt,PPe=new yt,TPe=new zg,T$=new yt(1,0,0),A$=new yt(0,1,0),j$=new yt(0,0,1),APe={type:"added"},jPe={type:"removed"};class So extends cb{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:CPe++}),this.uuid=Rm(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=So.DEFAULT_UP.clone();const e=new yt,n=new zS,a=new zg,i=new yt(1,1,1);function s(){a.setFromEuler(n,!1)}function o(){n.setFromQuaternion(a,void 0,!1)}n._onChange(s),a._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:a},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Sa},normalMatrix:{value:new pr}}),this.matrix=new Sa,this.matrixWorld=new Sa,this.matrixAutoUpdate=So.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=So.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new gee,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 xx.setFromAxisAngle(e,n),this.quaternion.multiply(xx),this}rotateOnWorldAxis(e,n){return xx.setFromAxisAngle(e,n),this.quaternion.premultiply(xx),this}rotateX(e){return this.rotateOnAxis(T$,e)}rotateY(e){return this.rotateOnAxis(A$,e)}rotateZ(e){return this.rotateOnAxis(j$,e)}translateOnAxis(e,n){return P$.copy(e).applyQuaternion(this.quaternion),this.position.add(P$.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(T$,e)}translateY(e){return this.translateOnAxis(A$,e)}translateZ(e){return this.translateOnAxis(j$,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(rm.copy(this.matrixWorld).invert())}lookAt(e,n,a){e.isVector3?i1.copy(e):i1.set(e,n,a);const i=this.parent;this.updateWorldMatrix(!0,!1),d0.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?rm.lookAt(d0,i1,this.up):rm.lookAt(i1,d0,this.up),this.quaternion.setFromRotationMatrix(rm),i&&(rm.extractRotation(i.matrixWorld),xx.setFromRotationMatrix(rm),this.quaternion.premultiply(xx.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(APe)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let a=0;a<arguments.length;a++)this.remove(arguments[a]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(jPe)),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),rm.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),rm.multiply(e.parent.matrixWorld)),e.applyMatrix4(rm),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 a=0,i=this.children.length;a<i;a++){const o=this.children[a].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,a=[]){this[e]===n&&a.push(this);const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,n,a);return a}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(d0,e,PPe),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(d0,TPe,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 a=0,i=n.length;a<i;a++)n[a].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let a=0,i=n.length;a<i;a++)n[a].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 a=0,i=n.length;a<i;a++){const s=n[a];(s.matrixWorldAutoUpdate===!0||e===!0)&&s.updateMatrixWorld(e)}}updateWorldMatrix(e,n){const a=this.parent;if(e===!0&&a!==null&&a.matrixWorldAutoUpdate===!0&&a.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",a={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},a.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),g=o(e.nodes);l.length>0&&(a.geometries=l),c.length>0&&(a.materials=c),d.length>0&&(a.textures=d),u.length>0&&(a.images=u),m.length>0&&(a.shapes=m),p.length>0&&(a.skeletons=p),f.length>0&&(a.animations=f),g.length>0&&(a.nodes=g)}return a.object=i,a;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 a=0;a<e.children.length;a++){const i=e.children[a];this.add(i.clone())}return this}}So.DEFAULT_UP=new yt(0,1,0);So.DEFAULT_MATRIX_AUTO_UPDATE=!0;So.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Jc=new yt,am=new yt,s2=new yt,im=new yt,yx=new yt,vx=new yt,M$=new yt,o2=new yt,l2=new yt,c2=new yt;let s1=!1;class nd{constructor(e=new yt,n=new yt,a=new yt){this.a=e,this.b=n,this.c=a}static getNormal(e,n,a,i){i.subVectors(a,n),Jc.subVectors(e,n),i.cross(Jc);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,n,a,i,s){Jc.subVectors(i,n),am.subVectors(a,n),s2.subVectors(e,n);const o=Jc.dot(Jc),l=Jc.dot(am),c=Jc.dot(s2),d=am.dot(am),u=am.dot(s2),m=o*d-l*l;if(m===0)return s.set(-2,-1,-1);const p=1/m,f=(d*c-l*u)*p,g=(o*u-l*c)*p;return s.set(1-f-g,g,f)}static containsPoint(e,n,a,i){return this.getBarycoord(e,n,a,i,im),im.x>=0&&im.y>=0&&im.x+im.y<=1}static getUV(e,n,a,i,s,o,l,c){return s1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),s1=!0),this.getInterpolation(e,n,a,i,s,o,l,c)}static getInterpolation(e,n,a,i,s,o,l,c){return this.getBarycoord(e,n,a,i,im),c.setScalar(0),c.addScaledVector(s,im.x),c.addScaledVector(o,im.y),c.addScaledVector(l,im.z),c}static isFrontFacing(e,n,a,i){return Jc.subVectors(a,n),am.subVectors(e,n),Jc.cross(am).dot(i)<0}set(e,n,a){return this.a.copy(e),this.b.copy(n),this.c.copy(a),this}setFromPointsAndIndices(e,n,a,i){return this.a.copy(e[n]),this.b.copy(e[a]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,n,a,i){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,a),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 Jc.subVectors(this.c,this.b),am.subVectors(this.a,this.b),Jc.cross(am).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return nd.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return nd.getBarycoord(e,this.a,this.b,this.c,n)}getUV(e,n,a,i,s){return s1===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),s1=!0),nd.getInterpolation(e,this.a,this.b,this.c,n,a,i,s)}getInterpolation(e,n,a,i,s){return nd.getInterpolation(e,this.a,this.b,this.c,n,a,i,s)}containsPoint(e){return nd.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return nd.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const a=this.a,i=this.b,s=this.c;let o,l;yx.subVectors(i,a),vx.subVectors(s,a),o2.subVectors(e,a);const c=yx.dot(o2),d=vx.dot(o2);if(c<=0&&d<=0)return n.copy(a);l2.subVectors(e,i);const u=yx.dot(l2),m=vx.dot(l2);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(a).addScaledVector(yx,o);c2.subVectors(e,s);const f=yx.dot(c2),g=vx.dot(c2);if(g>=0&&f<=g)return n.copy(s);const w=f*d-c*g;if(w<=0&&d>=0&&g<=0)return l=d/(d-g),n.copy(a).addScaledVector(vx,l);const b=u*g-f*m;if(b<=0&&m-u>=0&&f-g>=0)return M$.subVectors(s,i),l=(m-u)/(m-u+(f-g)),n.copy(i).addScaledVector(M$,l);const x=1/(b+w+p);return o=w*x,l=p*x,n.copy(a).addScaledVector(yx,o).addScaledVector(vx,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const bee={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},Kp={h:0,s:0,l:0},o1={h:0,s:0,l:0};function d2(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 On=class{constructor(e,n,a){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,a)}set(e,n,a){if(n===void 0&&a===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,a);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=Ms){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,sa.toWorkingColorSpace(this,n),this}setRGB(e,n,a,i=sa.workingColorSpace){return this.r=e,this.g=n,this.b=a,sa.toWorkingColorSpace(this,i),this}setHSL(e,n,a,i=sa.workingColorSpace){if(e=ZO(e,1),n=Ds(n,0,1),a=Ds(a,0,1),n===0)this.r=this.g=this.b=a;else{const s=a<=.5?a*(1+n):a+n-a*n,o=2*a-s;this.r=d2(o,s,e+1/3),this.g=d2(o,s,e),this.b=d2(o,s,e-1/3)}return sa.toWorkingColorSpace(this,i),this}setStyle(e,n=Ms){function a(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 a(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 a(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 a(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=Ms){const a=bee[e.toLowerCase()];return a!==void 0?this.setHex(a,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=oy(e.r),this.g=oy(e.g),this.b=oy(e.b),this}copyLinearToSRGB(e){return this.r=ZE(e.r),this.g=ZE(e.g),this.b=ZE(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ms){return sa.fromWorkingColorSpace(Gs.copy(this),e),Math.round(Ds(Gs.r*255,0,255))*65536+Math.round(Ds(Gs.g*255,0,255))*256+Math.round(Ds(Gs.b*255,0,255))}getHexString(e=Ms){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=sa.workingColorSpace){sa.fromWorkingColorSpace(Gs.copy(this),n);const a=Gs.r,i=Gs.g,s=Gs.b,o=Math.max(a,i,s),l=Math.min(a,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 a:c=(i-s)/m+(i<s?6:0);break;case i:c=(s-a)/m+2;break;case s:c=(a-i)/m+4;break}c/=6}return e.h=c,e.s=d,e.l=u,e}getRGB(e,n=sa.workingColorSpace){return sa.fromWorkingColorSpace(Gs.copy(this),n),e.r=Gs.r,e.g=Gs.g,e.b=Gs.b,e}getStyle(e=Ms){sa.fromWorkingColorSpace(Gs.copy(this),e);const n=Gs.r,a=Gs.g,i=Gs.b;return e!==Ms?`color(${e} ${n.toFixed(3)} ${a.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(a*255)},${Math.round(i*255)})`}offsetHSL(e,n,a){return this.getHSL(Kp),this.setHSL(Kp.h+e,Kp.s+n,Kp.l+a)}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,a){return this.r=e.r+(n.r-e.r)*a,this.g=e.g+(n.g-e.g)*a,this.b=e.b+(n.b-e.b)*a,this}lerpHSL(e,n){this.getHSL(Kp),e.getHSL(o1);const a=tw(Kp.h,o1.h,n),i=tw(Kp.s,o1.s,n),s=tw(Kp.l,o1.l,n);return this.setHSL(a,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,a=this.g,i=this.b,s=e.elements;return this.r=s[0]*n+s[3]*a+s[6]*i,this.g=s[1]*n+s[4]*a+s[7]*i,this.b=s[2]*n+s[5]*a+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 Gs=new On;On.NAMES=bee;let MPe=0;class Jy extends cb{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:MPe++}),this.uuid=Rm(),this.name="",this.type="Material",this.blending=sy,this.side=Qh,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=WL,this.blendDst=KL,this.blendEquation=eg,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new On(0,0,0),this.blendAlpha=0,this.depthFunc=hC,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=x$,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=mx,this.stencilZFail=mx,this.stencilZPass=mx,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 a=e[n];if(a===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(a):i&&i.isVector3&&a&&a.isVector3?i.copy(a):this[n]=a}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const a={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};a.uuid=this.uuid,a.type=this.type,this.name!==""&&(a.name=this.name),this.color&&this.color.isColor&&(a.color=this.color.getHex()),this.roughness!==void 0&&(a.roughness=this.roughness),this.metalness!==void 0&&(a.metalness=this.metalness),this.sheen!==void 0&&(a.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(a.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(a.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(a.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(a.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(a.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(a.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(a.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(a.shininess=this.shininess),this.clearcoat!==void 0&&(a.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(a.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(a.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(a.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(a.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,a.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(a.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(a.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(a.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(a.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(a.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(a.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(a.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(a.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(a.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(a.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(a.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(a.lightMap=this.lightMap.toJSON(e).uuid,a.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(a.aoMap=this.aoMap.toJSON(e).uuid,a.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(a.bumpMap=this.bumpMap.toJSON(e).uuid,a.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(a.normalMap=this.normalMap.toJSON(e).uuid,a.normalMapType=this.normalMapType,a.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(a.displacementMap=this.displacementMap.toJSON(e).uuid,a.displacementScale=this.displacementScale,a.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(a.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(a.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(a.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(a.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(a.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(a.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(a.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(a.combine=this.combine)),this.envMapIntensity!==void 0&&(a.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(a.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(a.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(a.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(a.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(a.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(a.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(a.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(a.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(a.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(a.size=this.size),this.shadowSide!==null&&(a.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(a.sizeAttenuation=this.sizeAttenuation),this.blending!==sy&&(a.blending=this.blending),this.side!==Qh&&(a.side=this.side),this.vertexColors===!0&&(a.vertexColors=!0),this.opacity<1&&(a.opacity=this.opacity),this.transparent===!0&&(a.transparent=!0),this.blendSrc!==WL&&(a.blendSrc=this.blendSrc),this.blendDst!==KL&&(a.blendDst=this.blendDst),this.blendEquation!==eg&&(a.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(a.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(a.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(a.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(a.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(a.blendAlpha=this.blendAlpha),this.depthFunc!==hC&&(a.depthFunc=this.depthFunc),this.depthTest===!1&&(a.depthTest=this.depthTest),this.depthWrite===!1&&(a.depthWrite=this.depthWrite),this.colorWrite===!1&&(a.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(a.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==x$&&(a.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(a.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(a.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==mx&&(a.stencilFail=this.stencilFail),this.stencilZFail!==mx&&(a.stencilZFail=this.stencilZFail),this.stencilZPass!==mx&&(a.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(a.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(a.rotation=this.rotation),this.polygonOffset===!0&&(a.polygonOffset=!0),this.polygonOffsetFactor!==0&&(a.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(a.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(a.linewidth=this.linewidth),this.dashSize!==void 0&&(a.dashSize=this.dashSize),this.gapSize!==void 0&&(a.gapSize=this.gapSize),this.scale!==void 0&&(a.scale=this.scale),this.dithering===!0&&(a.dithering=!0),this.alphaTest>0&&(a.alphaTest=this.alphaTest),this.alphaHash===!0&&(a.alphaHash=!0),this.alphaToCoverage===!0&&(a.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(a.premultipliedAlpha=!0),this.forceSinglePass===!0&&(a.forceSinglePass=!0),this.wireframe===!0&&(a.wireframe=!0),this.wireframeLinewidth>1&&(a.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(a.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(a.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(a.flatShading=!0),this.visible===!1&&(a.visible=!1),this.toneMapped===!1&&(a.toneMapped=!1),this.fog===!1&&(a.fog=!1),Object.keys(this.userData).length>0&&(a.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&&(a.textures=s),o.length>0&&(a.images=o)}return a}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 a=null;if(n!==null){const i=n.length;a=new Array(i);for(let s=0;s!==i;++s)a[s]=n[s].clone()}return this.clippingPlanes=a,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 xee extends Jy{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new On(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=QO,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 vi=new yt,l1=new Wn;class _l{constructor(e,n,a=!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=a,this.usage=JL,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=km,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,a){e*=this.itemSize,a*=n.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=n.array[a+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,a=this.count;n<a;n++)l1.fromBufferAttribute(this,n),l1.applyMatrix3(e),this.setXY(n,l1.x,l1.y);else if(this.itemSize===3)for(let n=0,a=this.count;n<a;n++)vi.fromBufferAttribute(this,n),vi.applyMatrix3(e),this.setXYZ(n,vi.x,vi.y,vi.z);return this}applyMatrix4(e){for(let n=0,a=this.count;n<a;n++)vi.fromBufferAttribute(this,n),vi.applyMatrix4(e),this.setXYZ(n,vi.x,vi.y,vi.z);return this}applyNormalMatrix(e){for(let n=0,a=this.count;n<a;n++)vi.fromBufferAttribute(this,n),vi.applyNormalMatrix(e),this.setXYZ(n,vi.x,vi.y,vi.z);return this}transformDirection(e){for(let n=0,a=this.count;n<a;n++)vi.fromBufferAttribute(this,n),vi.transformDirection(e),this.setXYZ(n,vi.x,vi.y,vi.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let a=this.array[e*this.itemSize+n];return this.normalized&&(a=Yd(a,this.array)),a}setComponent(e,n,a){return this.normalized&&(a=ia(a,this.array)),this.array[e*this.itemSize+n]=a,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=Yd(n,this.array)),n}setX(e,n){return this.normalized&&(n=ia(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=Yd(n,this.array)),n}setY(e,n){return this.normalized&&(n=ia(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=Yd(n,this.array)),n}setZ(e,n){return this.normalized&&(n=ia(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=Yd(n,this.array)),n}setW(e,n){return this.normalized&&(n=ia(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,a){return e*=this.itemSize,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array)),this.array[e+0]=n,this.array[e+1]=a,this}setXYZ(e,n,a,i){return e*=this.itemSize,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array),i=ia(i,this.array)),this.array[e+0]=n,this.array[e+1]=a,this.array[e+2]=i,this}setXYZW(e,n,a,i,s){return e*=this.itemSize,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array),i=ia(i,this.array),s=ia(s,this.array)),this.array[e+0]=n,this.array[e+1]=a,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!==JL&&(e.usage=this.usage),e}}class yee extends _l{constructor(e,n,a){super(new Uint16Array(e),n,a)}}class vee extends _l{constructor(e,n,a){super(new Uint32Array(e),n,a)}}class ui extends _l{constructor(e,n,a){super(new Float32Array(e),n,a)}}let EPe=0;const Wl=new Sa,u2=new So,wx=new yt,pl=new gc,u0=new gc,es=new yt;class io extends cb{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:EPe++}),this.uuid=Rm(),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(mee(e)?vee:yee)(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,a=0){this.groups.push({start:e,count:n,materialIndex:a})}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 a=this.attributes.normal;if(a!==void 0){const s=new pr().getNormalMatrix(e);a.applyNormalMatrix(s),a.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 Wl.makeRotationFromQuaternion(e),this.applyMatrix4(Wl),this}rotateX(e){return Wl.makeRotationX(e),this.applyMatrix4(Wl),this}rotateY(e){return Wl.makeRotationY(e),this.applyMatrix4(Wl),this}rotateZ(e){return Wl.makeRotationZ(e),this.applyMatrix4(Wl),this}translate(e,n,a){return Wl.makeTranslation(e,n,a),this.applyMatrix4(Wl),this}scale(e,n,a){return Wl.makeScale(e,n,a),this.applyMatrix4(Wl),this}lookAt(e){return u2.lookAt(e),u2.updateMatrix(),this.applyMatrix4(u2.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(wx).negate(),this.translate(wx.x,wx.y,wx.z),this}setFromPoints(e){const n=[];for(let a=0,i=e.length;a<i;a++){const s=e[a];n.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new ui(n,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new gc);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 yt(-1/0,-1/0,-1/0),new yt(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let a=0,i=n.length;a<i;a++){const s=n[a];pl.setFromBufferAttribute(s),this.morphTargetsRelative?(es.addVectors(this.boundingBox.min,pl.min),this.boundingBox.expandByPoint(es),es.addVectors(this.boundingBox.max,pl.max),this.boundingBox.expandByPoint(es)):(this.boundingBox.expandByPoint(pl.min),this.boundingBox.expandByPoint(pl.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 lu);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 yt,1/0);return}if(e){const a=this.boundingSphere.center;if(pl.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];u0.setFromBufferAttribute(l),this.morphTargetsRelative?(es.addVectors(pl.min,u0.min),pl.expandByPoint(es),es.addVectors(pl.max,u0.max),pl.expandByPoint(es)):(pl.expandByPoint(u0.min),pl.expandByPoint(u0.max))}pl.getCenter(a);let i=0;for(let s=0,o=e.count;s<o;s++)es.fromBufferAttribute(e,s),i=Math.max(i,a.distanceToSquared(es));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++)es.fromBufferAttribute(l,d),c&&(wx.fromBufferAttribute(e,d),es.add(wx)),i=Math.max(i,a.distanceToSquared(es))}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 a=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 _l(new Float32Array(4*l),4));const c=this.getAttribute("tangent").array,d=[],u=[];for(let M=0;M<l;M++)d[M]=new yt,u[M]=new yt;const m=new yt,p=new yt,f=new yt,g=new Wn,w=new Wn,b=new Wn,x=new yt,S=new yt;function k(M,H,I){m.fromArray(i,M*3),p.fromArray(i,H*3),f.fromArray(i,I*3),g.fromArray(o,M*2),w.fromArray(o,H*2),b.fromArray(o,I*2),p.sub(m),f.sub(m),w.sub(g),b.sub(g);const z=1/(w.x*b.y-b.x*w.y);isFinite(z)&&(x.copy(p).multiplyScalar(b.y).addScaledVector(f,-w.y).multiplyScalar(z),S.copy(f).multiplyScalar(w.x).addScaledVector(p,-b.x).multiplyScalar(z),d[M].add(x),d[H].add(x),d[I].add(x),u[M].add(S),u[H].add(S),u[I].add(S))}let C=this.groups;C.length===0&&(C=[{start:0,count:a.length}]);for(let M=0,H=C.length;M<H;++M){const I=C[M],z=I.start,L=I.count;for(let Z=z,ne=z+L;Z<ne;Z+=3)k(a[Z+0],a[Z+1],a[Z+2])}const P=new yt,T=new yt,A=new yt,F=new yt;function _(M){A.fromArray(s,M*3),F.copy(A);const H=d[M];P.copy(H),P.sub(A.multiplyScalar(A.dot(H))).normalize(),T.crossVectors(F,H);const z=T.dot(u[M])<0?-1:1;c[M*4]=P.x,c[M*4+1]=P.y,c[M*4+2]=P.z,c[M*4+3]=z}for(let M=0,H=C.length;M<H;++M){const I=C[M],z=I.start,L=I.count;for(let Z=z,ne=z+L;Z<ne;Z+=3)_(a[Z+0]),_(a[Z+1]),_(a[Z+2])}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let a=this.getAttribute("normal");if(a===void 0)a=new _l(new Float32Array(n.count*3),3),this.setAttribute("normal",a);else for(let p=0,f=a.count;p<f;p++)a.setXYZ(p,0,0,0);const i=new yt,s=new yt,o=new yt,l=new yt,c=new yt,d=new yt,u=new yt,m=new yt;if(e)for(let p=0,f=e.count;p<f;p+=3){const g=e.getX(p+0),w=e.getX(p+1),b=e.getX(p+2);i.fromBufferAttribute(n,g),s.fromBufferAttribute(n,w),o.fromBufferAttribute(n,b),u.subVectors(o,s),m.subVectors(i,s),u.cross(m),l.fromBufferAttribute(a,g),c.fromBufferAttribute(a,w),d.fromBufferAttribute(a,b),l.add(u),c.add(u),d.add(u),a.setXYZ(g,l.x,l.y,l.z),a.setXYZ(w,c.x,c.y,c.z),a.setXYZ(b,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),a.setXYZ(p+0,u.x,u.y,u.z),a.setXYZ(p+1,u.x,u.y,u.z),a.setXYZ(p+2,u.x,u.y,u.z);this.normalizeNormals(),a.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,a=e.count;n<a;n++)es.fromBufferAttribute(e,n),es.normalize(),e.setXYZ(n,es.x,es.y,es.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,g=0;for(let w=0,b=c.length;w<b;w++){l.isInterleavedBufferAttribute?f=c[w]*l.data.stride+l.offset:f=c[w]*u;for(let x=0;x<u;x++)p[g++]=d[f++]}return new _l(p,u,m)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new io,a=this.index.array,i=this.attributes;for(const l in i){const c=i[l],d=e(c,a);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,a);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 a=this.attributes;for(const c in a){const d=a[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 a=e.index;a!==null&&this.setIndex(a.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 E$=new Sa,Uf=new JO,c1=new lu,D$=new yt,Sx=new yt,_x=new yt,kx=new yt,m2=new yt,d1=new yt,u1=new Wn,m1=new Wn,p1=new Wn,F$=new yt,L$=new yt,R$=new yt,h1=new yt,f1=new yt;class cd extends So{constructor(e=new io,n=new xee){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,a=Object.keys(n);if(a.length>0){const i=n[a[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 a=this.geometry,i=a.attributes.position,s=a.morphAttributes.position,o=a.morphTargetsRelative;n.fromBufferAttribute(i,e);const l=this.morphTargetInfluences;if(s&&l){d1.set(0,0,0);for(let c=0,d=s.length;c<d;c++){const u=l[c],m=s[c];u!==0&&(m2.fromBufferAttribute(m,e),o?d1.addScaledVector(m2,u):d1.addScaledVector(m2.sub(n),u))}n.add(d1)}return n}raycast(e,n){const a=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(a.boundingSphere===null&&a.computeBoundingSphere(),c1.copy(a.boundingSphere),c1.applyMatrix4(s),Uf.copy(e.ray).recast(e.near),!(c1.containsPoint(Uf.origin)===!1&&(Uf.intersectSphere(c1,D$)===null||Uf.origin.distanceToSquared(D$)>(e.far-e.near)**2))&&(E$.copy(s).invert(),Uf.copy(e.ray).applyMatrix4(E$),!(a.boundingBox!==null&&Uf.intersectsBox(a.boundingBox)===!1)&&this._computeIntersections(e,n,Uf)))}_computeIntersections(e,n,a){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 g=0,w=p.length;g<w;g++){const b=p[g],x=o[b.materialIndex],S=Math.max(b.start,f.start),k=Math.min(l.count,Math.min(b.start+b.count,f.start+f.count));for(let C=S,P=k;C<P;C+=3){const T=l.getX(C),A=l.getX(C+1),F=l.getX(C+2);i=g1(this,x,e,a,d,u,m,T,A,F),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const g=Math.max(0,f.start),w=Math.min(l.count,f.start+f.count);for(let b=g,x=w;b<x;b+=3){const S=l.getX(b),k=l.getX(b+1),C=l.getX(b+2);i=g1(this,o,e,a,d,u,m,S,k,C),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,w=p.length;g<w;g++){const b=p[g],x=o[b.materialIndex],S=Math.max(b.start,f.start),k=Math.min(c.count,Math.min(b.start+b.count,f.start+f.count));for(let C=S,P=k;C<P;C+=3){const T=C,A=C+1,F=C+2;i=g1(this,x,e,a,d,u,m,T,A,F),i&&(i.faceIndex=Math.floor(C/3),i.face.materialIndex=b.materialIndex,n.push(i))}}else{const g=Math.max(0,f.start),w=Math.min(c.count,f.start+f.count);for(let b=g,x=w;b<x;b+=3){const S=b,k=b+1,C=b+2;i=g1(this,o,e,a,d,u,m,S,k,C),i&&(i.faceIndex=Math.floor(b/3),n.push(i))}}}}function DPe(t,e,n,a,i,s,o,l){let c;if(e.side===Ko?c=a.intersectTriangle(o,s,i,!0,l):c=a.intersectTriangle(i,s,o,e.side===Qh,l),c===null)return null;f1.copy(l),f1.applyMatrix4(t.matrixWorld);const d=n.ray.origin.distanceTo(f1);return d<n.near||d>n.far?null:{distance:d,point:f1.clone(),object:t}}function g1(t,e,n,a,i,s,o,l,c,d){t.getVertexPosition(l,Sx),t.getVertexPosition(c,_x),t.getVertexPosition(d,kx);const u=DPe(t,e,n,a,Sx,_x,kx,h1);if(u){i&&(u1.fromBufferAttribute(i,l),m1.fromBufferAttribute(i,c),p1.fromBufferAttribute(i,d),u.uv=nd.getInterpolation(h1,Sx,_x,kx,u1,m1,p1,new Wn)),s&&(u1.fromBufferAttribute(s,l),m1.fromBufferAttribute(s,c),p1.fromBufferAttribute(s,d),u.uv1=nd.getInterpolation(h1,Sx,_x,kx,u1,m1,p1,new Wn),u.uv2=u.uv1),o&&(F$.fromBufferAttribute(o,l),L$.fromBufferAttribute(o,c),R$.fromBufferAttribute(o,d),u.normal=nd.getInterpolation(h1,Sx,_x,kx,F$,L$,R$,new yt),u.normal.dot(a.direction)>0&&u.normal.multiplyScalar(-1));const m={a:l,b:c,c:d,normal:new yt,materialIndex:0};nd.getNormal(Sx,_x,kx,m.normal),u.face=m}return u}class US extends io{constructor(e=1,n=1,a=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:a,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;g("z","y","x",-1,-1,a,n,e,o,s,0),g("z","y","x",1,-1,a,n,-e,o,s,1),g("x","z","y",1,1,e,a,n,i,o,2),g("x","z","y",1,-1,e,a,-n,i,o,3),g("x","y","z",1,-1,e,n,a,i,s,4),g("x","y","z",-1,-1,e,n,-a,i,s,5),this.setIndex(c),this.setAttribute("position",new ui(d,3)),this.setAttribute("normal",new ui(u,3)),this.setAttribute("uv",new ui(m,2));function g(w,b,x,S,k,C,P,T,A,F,_){const M=C/A,H=P/F,I=C/2,z=P/2,L=T/2,Z=A+1,ne=F+1;let Y=0,ce=0;const ue=new yt;for(let oe=0;oe<ne;oe++){const Q=oe*H-z;for(let le=0;le<Z;le++){const pe=le*M-I;ue[w]=pe*S,ue[b]=Q*k,ue[x]=L,d.push(ue.x,ue.y,ue.z),ue[w]=0,ue[b]=0,ue[x]=T>0?1:-1,u.push(ue.x,ue.y,ue.z),m.push(le/A),m.push(1-oe/F),Y+=1}}for(let oe=0;oe<F;oe++)for(let Q=0;Q<A;Q++){const le=p+Q+Z*oe,pe=p+Q+Z*(oe+1),he=p+(Q+1)+Z*(oe+1),we=p+(Q+1)+Z*oe;c.push(le,pe,we),c.push(pe,he,we),ce+=6}l.addGroup(f,ce,_),f+=ce,p+=Y}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new US(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Py(t){const e={};for(const n in t){e[n]={};for(const a in t[n]){const i=t[n][a];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][a]=null):e[n][a]=i.clone():Array.isArray(i)?e[n][a]=i.slice():e[n][a]=i}}return e}function go(t){const e={};for(let n=0;n<t.length;n++){const a=Py(t[n]);for(const i in a)e[i]=a[i]}return e}function FPe(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function wee(t){return t.getRenderTarget()===null?t.outputColorSpace:sa.workingColorSpace}const e4={clone:Py,merge:go};var LPe=`void main() {
  3864. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  3865. }`,RPe=`void main() {
  3866. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  3867. }`;class Yh extends Jy{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=LPe,this.fragmentShader=RPe,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=Py(e.uniforms),this.uniformsGroups=FPe(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 a={};for(const i in this.extensions)this.extensions[i]===!0&&(a[i]=!0);return Object.keys(a).length>0&&(n.extensions=a),n}}class See extends So{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Sa,this.projectionMatrix=new Sa,this.projectionMatrixInverse=new Sa,this.coordinateSystem=eu}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 gl extends See{constructor(e=50,n=1,a=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=a,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=$w*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(ew*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return $w*2*Math.atan(Math.tan(ew*.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,a,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=a,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(ew*.5*this.fov)/this.zoom,a=2*n,i=this.aspect*a,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*a/d,i*=o.width/c,a*=o.height/d}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,n,n-a,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 Nx=-90,Cx=1;class IPe extends So{constructor(e,n,a){super(),this.type="CubeCamera",this.renderTarget=a,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new gl(Nx,Cx,e,n);i.layers=this.layers,this.add(i);const s=new gl(Nx,Cx,e,n);s.layers=this.layers,this.add(s);const o=new gl(Nx,Cx,e,n);o.layers=this.layers,this.add(o);const l=new gl(Nx,Cx,e,n);l.layers=this.layers,this.add(l);const c=new gl(Nx,Cx,e,n);c.layers=this.layers,this.add(c);const d=new gl(Nx,Cx,e,n);d.layers=this.layers,this.add(d)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[a,i,s,o,l,c]=n;for(const d of n)this.remove(d);if(e===eu)a.up.set(0,1,0),a.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===qw)a.up.set(0,-1,0),a.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:a,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(),g=e.xr.enabled;e.xr.enabled=!1;const w=a.texture.generateMipmaps;a.texture.generateMipmaps=!1,e.setRenderTarget(a,0,i),e.render(n,s),e.setRenderTarget(a,1,i),e.render(n,o),e.setRenderTarget(a,2,i),e.render(n,l),e.setRenderTarget(a,3,i),e.render(n,c),e.setRenderTarget(a,4,i),e.render(n,d),a.texture.generateMipmaps=w,e.setRenderTarget(a,5,i),e.render(n,u),e.setRenderTarget(m,p,f),e.xr.enabled=g,a.texture.needsPMREMUpdate=!0}}class _ee extends Qo{constructor(e,n,a,i,s,o,l,c,d,u){e=e!==void 0?e:[],n=n!==void 0?n:ky,super(e,n,a,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 OPe extends Og{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const a={width:e,height:e,depth:1},i=[a,a,a,a,a,a];n.encoding!==void 0&&(nw("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===bg?Ms:oc),this.texture=new _ee(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:ic}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 a={uniforms:{tEquirect:{value:null}},vertexShader:`
  3868. varying vec3 vWorldDirection;
  3869. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  3870. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  3871. }
  3872. void main() {
  3873. vWorldDirection = transformDirection( position, modelMatrix );
  3874. #include <begin_vertex>
  3875. #include <project_vertex>
  3876. }
  3877. `,fragmentShader:`
  3878. uniform sampler2D tEquirect;
  3879. varying vec3 vWorldDirection;
  3880. #include <common>
  3881. void main() {
  3882. vec3 direction = normalize( vWorldDirection );
  3883. vec2 sampleUV = equirectUv( direction );
  3884. gl_FragColor = texture2D( tEquirect, sampleUV );
  3885. }
  3886. `},i=new US(5,5,5),s=new Yh({name:"CubemapFromEquirect",uniforms:Py(a.uniforms),vertexShader:a.vertexShader,fragmentShader:a.fragmentShader,side:Ko,blending:Lh});s.uniforms.tEquirect.value=n;const o=new cd(i,s),l=n.minFilter;return n.minFilter===Bw&&(n.minFilter=ic),new IPe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,a,i){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,a,i);e.setRenderTarget(s)}}const p2=new yt,zPe=new yt,UPe=new pr;class ah{constructor(e=new yt(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,a,i){return this.normal.set(e,n,a),this.constant=i,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,a){const i=p2.subVectors(a,n).cross(zPe.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 a=e.delta(p2),i=this.normal.dot(a);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(a,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),a=this.distanceToPoint(e.end);return n<0&&a>0||a<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 a=n||UPe.getNormalMatrix(e),i=this.coplanarPoint(p2).applyMatrix4(e),s=this.normal.applyMatrix3(a).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 Bf=new lu,b1=new yt;class IT{constructor(e=new ah,n=new ah,a=new ah,i=new ah,s=new ah,o=new ah){this.planes=[e,n,a,i,s,o]}set(e,n,a,i,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(a),l[3].copy(i),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let a=0;a<6;a++)n[a].copy(e.planes[a]);return this}setFromProjectionMatrix(e,n=eu){const a=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],g=i[9],w=i[10],b=i[11],x=i[12],S=i[13],k=i[14],C=i[15];if(a[0].setComponents(c-s,p-d,b-f,C-x).normalize(),a[1].setComponents(c+s,p+d,b+f,C+x).normalize(),a[2].setComponents(c+o,p+u,b+g,C+S).normalize(),a[3].setComponents(c-o,p-u,b-g,C-S).normalize(),a[4].setComponents(c-l,p-m,b-w,C-k).normalize(),n===eu)a[5].setComponents(c+l,p+m,b+w,C+k).normalize();else if(n===qw)a[5].setComponents(l,m,w,k).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Bf.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Bf.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Bf)}intersectsSprite(e){return Bf.center.set(0,0,0),Bf.radius=.7071067811865476,Bf.applyMatrix4(e.matrixWorld),this.intersectsSphere(Bf)}intersectsSphere(e){const n=this.planes,a=e.center,i=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(a)<i)return!1;return!0}intersectsBox(e){const n=this.planes;for(let a=0;a<6;a++){const i=n[a];if(b1.x=i.normal.x>0?e.max.x:e.min.x,b1.y=i.normal.y>0?e.max.y:e.min.y,b1.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(b1)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let a=0;a<6;a++)if(n[a].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function kee(){let t=null,e=!1,n=null,a=null;function i(s,o){n(s,o),a=t.requestAnimationFrame(i)}return{start:function(){e!==!0&&n!==null&&(a=t.requestAnimationFrame(i),e=!0)},stop:function(){t.cancelAnimationFrame(a),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function BPe(t,e){const n=e.isWebGL2,a=new WeakMap;function i(d,u){const m=d.array,p=d.usage,f=m.byteLength,g=t.createBuffer();t.bindBuffer(u,g),t.bufferData(u,m,p),d.onUploadCallback();let w;if(m instanceof Float32Array)w=t.FLOAT;else if(m instanceof Uint16Array)if(d.isFloat16BufferAttribute)if(n)w=t.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else w=t.UNSIGNED_SHORT;else if(m instanceof Int16Array)w=t.SHORT;else if(m instanceof Uint32Array)w=t.UNSIGNED_INT;else if(m instanceof Int32Array)w=t.INT;else if(m instanceof Int8Array)w=t.BYTE;else if(m instanceof Uint8Array)w=t.UNSIGNED_BYTE;else if(m instanceof Uint8ClampedArray)w=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+m);return{buffer:g,type:w,bytesPerElement:m.BYTES_PER_ELEMENT,version:d.version,size:f}}function s(d,u,m){const p=u.array,f=u._updateRange,g=u.updateRanges;if(t.bindBuffer(m,d),f.count===-1&&g.length===0&&t.bufferSubData(m,0,p),g.length!==0){for(let w=0,b=g.length;w<b;w++){const x=g[w];n?t.bufferSubData(m,x.start*p.BYTES_PER_ELEMENT,p,x.start,x.count):t.bufferSubData(m,x.start*p.BYTES_PER_ELEMENT,p.subarray(x.start,x.start+x.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),a.get(d)}function l(d){d.isInterleavedBufferAttribute&&(d=d.data);const u=a.get(d);u&&(t.deleteBuffer(u.buffer),a.delete(d))}function c(d,u){if(d.isGLBufferAttribute){const p=a.get(d);(!p||p.version<d.version)&&a.set(d,{buffer:d.buffer,type:d.type,bytesPerElement:d.elementSize,version:d.version});return}d.isInterleavedBufferAttribute&&(d=d.data);const m=a.get(d);if(m===void 0)a.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 t4 extends io{constructor(e=1,n=1,a=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:a,heightSegments:i};const s=e/2,o=n/2,l=Math.floor(a),c=Math.floor(i),d=l+1,u=c+1,m=e/l,p=n/c,f=[],g=[],w=[],b=[];for(let x=0;x<u;x++){const S=x*p-o;for(let k=0;k<d;k++){const C=k*m-s;g.push(C,-S,0),w.push(0,0,1),b.push(k/l),b.push(1-x/c)}}for(let x=0;x<c;x++)for(let S=0;S<l;S++){const k=S+d*x,C=S+d*(x+1),P=S+1+d*(x+1),T=S+1+d*x;f.push(k,C,T),f.push(C,P,T)}this.setIndex(f),this.setAttribute("position",new ui(g,3)),this.setAttribute("normal",new ui(w,3)),this.setAttribute("uv",new ui(b,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new t4(e.width,e.height,e.widthSegments,e.heightSegments)}}var HPe=`#ifdef USE_ALPHAHASH
  3887. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  3888. #endif`,qPe=`#ifdef USE_ALPHAHASH
  3889. const float ALPHA_HASH_SCALE = 0.05;
  3890. float hash2D( vec2 value ) {
  3891. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  3892. }
  3893. float hash3D( vec3 value ) {
  3894. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  3895. }
  3896. float getAlphaHashThreshold( vec3 position ) {
  3897. float maxDeriv = max(
  3898. length( dFdx( position.xyz ) ),
  3899. length( dFdy( position.xyz ) )
  3900. );
  3901. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  3902. vec2 pixScales = vec2(
  3903. exp2( floor( log2( pixScale ) ) ),
  3904. exp2( ceil( log2( pixScale ) ) )
  3905. );
  3906. vec2 alpha = vec2(
  3907. hash3D( floor( pixScales.x * position.xyz ) ),
  3908. hash3D( floor( pixScales.y * position.xyz ) )
  3909. );
  3910. float lerpFactor = fract( log2( pixScale ) );
  3911. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  3912. float a = min( lerpFactor, 1.0 - lerpFactor );
  3913. vec3 cases = vec3(
  3914. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  3915. ( x - 0.5 * a ) / ( 1.0 - a ),
  3916. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  3917. );
  3918. float threshold = ( x < ( 1.0 - a ) )
  3919. ? ( ( x < a ) ? cases.x : cases.y )
  3920. : cases.z;
  3921. return clamp( threshold , 1.0e-6, 1.0 );
  3922. }
  3923. #endif`,$Pe=`#ifdef USE_ALPHAMAP
  3924. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  3925. #endif`,VPe=`#ifdef USE_ALPHAMAP
  3926. uniform sampler2D alphaMap;
  3927. #endif`,GPe=`#ifdef USE_ALPHATEST
  3928. if ( diffuseColor.a < alphaTest ) discard;
  3929. #endif`,WPe=`#ifdef USE_ALPHATEST
  3930. uniform float alphaTest;
  3931. #endif`,KPe=`#ifdef USE_AOMAP
  3932. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  3933. reflectedLight.indirectDiffuse *= ambientOcclusion;
  3934. #if defined( USE_CLEARCOAT )
  3935. clearcoatSpecularIndirect *= ambientOcclusion;
  3936. #endif
  3937. #if defined( USE_SHEEN )
  3938. sheenSpecularIndirect *= ambientOcclusion;
  3939. #endif
  3940. #if defined( USE_ENVMAP ) && defined( STANDARD )
  3941. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  3942. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  3943. #endif
  3944. #endif`,QPe=`#ifdef USE_AOMAP
  3945. uniform sampler2D aoMap;
  3946. uniform float aoMapIntensity;
  3947. #endif`,YPe=`#ifdef USE_BATCHING
  3948. attribute float batchId;
  3949. uniform highp sampler2D batchingTexture;
  3950. mat4 getBatchingMatrix( const in float i ) {
  3951. int size = textureSize( batchingTexture, 0 ).x;
  3952. int j = int( i ) * 4;
  3953. int x = j % size;
  3954. int y = j / size;
  3955. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  3956. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  3957. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  3958. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  3959. return mat4( v1, v2, v3, v4 );
  3960. }
  3961. #endif`,XPe=`#ifdef USE_BATCHING
  3962. mat4 batchingMatrix = getBatchingMatrix( batchId );
  3963. #endif`,ZPe=`vec3 transformed = vec3( position );
  3964. #ifdef USE_ALPHAHASH
  3965. vPosition = vec3( position );
  3966. #endif`,JPe=`vec3 objectNormal = vec3( normal );
  3967. #ifdef USE_TANGENT
  3968. vec3 objectTangent = vec3( tangent.xyz );
  3969. #endif`,eTe=`float G_BlinnPhong_Implicit( ) {
  3970. return 0.25;
  3971. }
  3972. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  3973. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  3974. }
  3975. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  3976. vec3 halfDir = normalize( lightDir + viewDir );
  3977. float dotNH = saturate( dot( normal, halfDir ) );
  3978. float dotVH = saturate( dot( viewDir, halfDir ) );
  3979. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  3980. float G = G_BlinnPhong_Implicit( );
  3981. float D = D_BlinnPhong( shininess, dotNH );
  3982. return F * ( G * D );
  3983. } // validated`,tTe=`#ifdef USE_IRIDESCENCE
  3984. const mat3 XYZ_TO_REC709 = mat3(
  3985. 3.2404542, -0.9692660, 0.0556434,
  3986. -1.5371385, 1.8760108, -0.2040259,
  3987. -0.4985314, 0.0415560, 1.0572252
  3988. );
  3989. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  3990. vec3 sqrtF0 = sqrt( fresnel0 );
  3991. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  3992. }
  3993. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  3994. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  3995. }
  3996. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  3997. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  3998. }
  3999. vec3 evalSensitivity( float OPD, vec3 shift ) {
  4000. float phase = 2.0 * PI * OPD * 1.0e-9;
  4001. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  4002. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  4003. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  4004. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  4005. 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 ) );
  4006. xyz /= 1.0685e-7;
  4007. vec3 rgb = XYZ_TO_REC709 * xyz;
  4008. return rgb;
  4009. }
  4010. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  4011. vec3 I;
  4012. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  4013. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  4014. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  4015. if ( cosTheta2Sq < 0.0 ) {
  4016. return vec3( 1.0 );
  4017. }
  4018. float cosTheta2 = sqrt( cosTheta2Sq );
  4019. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  4020. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  4021. float T121 = 1.0 - R12;
  4022. float phi12 = 0.0;
  4023. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  4024. float phi21 = PI - phi12;
  4025. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  4026. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  4027. vec3 phi23 = vec3( 0.0 );
  4028. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  4029. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  4030. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  4031. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  4032. vec3 phi = vec3( phi21 ) + phi23;
  4033. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  4034. vec3 r123 = sqrt( R123 );
  4035. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  4036. vec3 C0 = R12 + Rs;
  4037. I = C0;
  4038. vec3 Cm = Rs - T121;
  4039. for ( int m = 1; m <= 2; ++ m ) {
  4040. Cm *= r123;
  4041. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  4042. I += Cm * Sm;
  4043. }
  4044. return max( I, vec3( 0.0 ) );
  4045. }
  4046. #endif`,nTe=`#ifdef USE_BUMPMAP
  4047. uniform sampler2D bumpMap;
  4048. uniform float bumpScale;
  4049. vec2 dHdxy_fwd() {
  4050. vec2 dSTdx = dFdx( vBumpMapUv );
  4051. vec2 dSTdy = dFdy( vBumpMapUv );
  4052. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  4053. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  4054. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  4055. return vec2( dBx, dBy );
  4056. }
  4057. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  4058. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  4059. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  4060. vec3 vN = surf_norm;
  4061. vec3 R1 = cross( vSigmaY, vN );
  4062. vec3 R2 = cross( vN, vSigmaX );
  4063. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  4064. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  4065. return normalize( abs( fDet ) * surf_norm - vGrad );
  4066. }
  4067. #endif`,rTe=`#if NUM_CLIPPING_PLANES > 0
  4068. vec4 plane;
  4069. #pragma unroll_loop_start
  4070. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  4071. plane = clippingPlanes[ i ];
  4072. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  4073. }
  4074. #pragma unroll_loop_end
  4075. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  4076. bool clipped = true;
  4077. #pragma unroll_loop_start
  4078. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  4079. plane = clippingPlanes[ i ];
  4080. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  4081. }
  4082. #pragma unroll_loop_end
  4083. if ( clipped ) discard;
  4084. #endif
  4085. #endif`,aTe=`#if NUM_CLIPPING_PLANES > 0
  4086. varying vec3 vClipPosition;
  4087. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  4088. #endif`,iTe=`#if NUM_CLIPPING_PLANES > 0
  4089. varying vec3 vClipPosition;
  4090. #endif`,sTe=`#if NUM_CLIPPING_PLANES > 0
  4091. vClipPosition = - mvPosition.xyz;
  4092. #endif`,oTe=`#if defined( USE_COLOR_ALPHA )
  4093. diffuseColor *= vColor;
  4094. #elif defined( USE_COLOR )
  4095. diffuseColor.rgb *= vColor;
  4096. #endif`,lTe=`#if defined( USE_COLOR_ALPHA )
  4097. varying vec4 vColor;
  4098. #elif defined( USE_COLOR )
  4099. varying vec3 vColor;
  4100. #endif`,cTe=`#if defined( USE_COLOR_ALPHA )
  4101. varying vec4 vColor;
  4102. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4103. varying vec3 vColor;
  4104. #endif`,dTe=`#if defined( USE_COLOR_ALPHA )
  4105. vColor = vec4( 1.0 );
  4106. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4107. vColor = vec3( 1.0 );
  4108. #endif
  4109. #ifdef USE_COLOR
  4110. vColor *= color;
  4111. #endif
  4112. #ifdef USE_INSTANCING_COLOR
  4113. vColor.xyz *= instanceColor.xyz;
  4114. #endif`,uTe=`#define PI 3.141592653589793
  4115. #define PI2 6.283185307179586
  4116. #define PI_HALF 1.5707963267948966
  4117. #define RECIPROCAL_PI 0.3183098861837907
  4118. #define RECIPROCAL_PI2 0.15915494309189535
  4119. #define EPSILON 1e-6
  4120. #ifndef saturate
  4121. #define saturate( a ) clamp( a, 0.0, 1.0 )
  4122. #endif
  4123. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  4124. float pow2( const in float x ) { return x*x; }
  4125. vec3 pow2( const in vec3 x ) { return x*x; }
  4126. float pow3( const in float x ) { return x*x*x; }
  4127. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  4128. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  4129. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  4130. highp float rand( const in vec2 uv ) {
  4131. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  4132. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  4133. return fract( sin( sn ) * c );
  4134. }
  4135. #ifdef HIGH_PRECISION
  4136. float precisionSafeLength( vec3 v ) { return length( v ); }
  4137. #else
  4138. float precisionSafeLength( vec3 v ) {
  4139. float maxComponent = max3( abs( v ) );
  4140. return length( v / maxComponent ) * maxComponent;
  4141. }
  4142. #endif
  4143. struct IncidentLight {
  4144. vec3 color;
  4145. vec3 direction;
  4146. bool visible;
  4147. };
  4148. struct ReflectedLight {
  4149. vec3 directDiffuse;
  4150. vec3 directSpecular;
  4151. vec3 indirectDiffuse;
  4152. vec3 indirectSpecular;
  4153. };
  4154. #ifdef USE_ALPHAHASH
  4155. varying vec3 vPosition;
  4156. #endif
  4157. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  4158. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  4159. }
  4160. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  4161. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  4162. }
  4163. mat3 transposeMat3( const in mat3 m ) {
  4164. mat3 tmp;
  4165. tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
  4166. tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
  4167. tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
  4168. return tmp;
  4169. }
  4170. float luminance( const in vec3 rgb ) {
  4171. const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
  4172. return dot( weights, rgb );
  4173. }
  4174. bool isPerspectiveMatrix( mat4 m ) {
  4175. return m[ 2 ][ 3 ] == - 1.0;
  4176. }
  4177. vec2 equirectUv( in vec3 dir ) {
  4178. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  4179. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  4180. return vec2( u, v );
  4181. }
  4182. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  4183. return RECIPROCAL_PI * diffuseColor;
  4184. }
  4185. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  4186. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4187. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4188. }
  4189. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  4190. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4191. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4192. } // validated`,mTe=`#ifdef ENVMAP_TYPE_CUBE_UV
  4193. #define cubeUV_minMipLevel 4.0
  4194. #define cubeUV_minTileSize 16.0
  4195. float getFace( vec3 direction ) {
  4196. vec3 absDirection = abs( direction );
  4197. float face = - 1.0;
  4198. if ( absDirection.x > absDirection.z ) {
  4199. if ( absDirection.x > absDirection.y )
  4200. face = direction.x > 0.0 ? 0.0 : 3.0;
  4201. else
  4202. face = direction.y > 0.0 ? 1.0 : 4.0;
  4203. } else {
  4204. if ( absDirection.z > absDirection.y )
  4205. face = direction.z > 0.0 ? 2.0 : 5.0;
  4206. else
  4207. face = direction.y > 0.0 ? 1.0 : 4.0;
  4208. }
  4209. return face;
  4210. }
  4211. vec2 getUV( vec3 direction, float face ) {
  4212. vec2 uv;
  4213. if ( face == 0.0 ) {
  4214. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  4215. } else if ( face == 1.0 ) {
  4216. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  4217. } else if ( face == 2.0 ) {
  4218. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  4219. } else if ( face == 3.0 ) {
  4220. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  4221. } else if ( face == 4.0 ) {
  4222. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  4223. } else {
  4224. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  4225. }
  4226. return 0.5 * ( uv + 1.0 );
  4227. }
  4228. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  4229. float face = getFace( direction );
  4230. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  4231. mipInt = max( mipInt, cubeUV_minMipLevel );
  4232. float faceSize = exp2( mipInt );
  4233. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  4234. if ( face > 2.0 ) {
  4235. uv.y += faceSize;
  4236. face -= 3.0;
  4237. }
  4238. uv.x += face * faceSize;
  4239. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  4240. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  4241. uv.x *= CUBEUV_TEXEL_WIDTH;
  4242. uv.y *= CUBEUV_TEXEL_HEIGHT;
  4243. #ifdef texture2DGradEXT
  4244. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  4245. #else
  4246. return texture2D( envMap, uv ).rgb;
  4247. #endif
  4248. }
  4249. #define cubeUV_r0 1.0
  4250. #define cubeUV_v0 0.339
  4251. #define cubeUV_m0 - 2.0
  4252. #define cubeUV_r1 0.8
  4253. #define cubeUV_v1 0.276
  4254. #define cubeUV_m1 - 1.0
  4255. #define cubeUV_r4 0.4
  4256. #define cubeUV_v4 0.046
  4257. #define cubeUV_m4 2.0
  4258. #define cubeUV_r5 0.305
  4259. #define cubeUV_v5 0.016
  4260. #define cubeUV_m5 3.0
  4261. #define cubeUV_r6 0.21
  4262. #define cubeUV_v6 0.0038
  4263. #define cubeUV_m6 4.0
  4264. float roughnessToMip( float roughness ) {
  4265. float mip = 0.0;
  4266. if ( roughness >= cubeUV_r1 ) {
  4267. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  4268. } else if ( roughness >= cubeUV_r4 ) {
  4269. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  4270. } else if ( roughness >= cubeUV_r5 ) {
  4271. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  4272. } else if ( roughness >= cubeUV_r6 ) {
  4273. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  4274. } else {
  4275. mip = - 2.0 * log2( 1.16 * roughness ); }
  4276. return mip;
  4277. }
  4278. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  4279. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  4280. float mipF = fract( mip );
  4281. float mipInt = floor( mip );
  4282. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  4283. if ( mipF == 0.0 ) {
  4284. return vec4( color0, 1.0 );
  4285. } else {
  4286. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  4287. return vec4( mix( color0, color1, mipF ), 1.0 );
  4288. }
  4289. }
  4290. #endif`,pTe=`vec3 transformedNormal = objectNormal;
  4291. #ifdef USE_TANGENT
  4292. vec3 transformedTangent = objectTangent;
  4293. #endif
  4294. #ifdef USE_BATCHING
  4295. mat3 bm = mat3( batchingMatrix );
  4296. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  4297. transformedNormal = bm * transformedNormal;
  4298. #ifdef USE_TANGENT
  4299. transformedTangent = bm * transformedTangent;
  4300. #endif
  4301. #endif
  4302. #ifdef USE_INSTANCING
  4303. mat3 im = mat3( instanceMatrix );
  4304. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  4305. transformedNormal = im * transformedNormal;
  4306. #ifdef USE_TANGENT
  4307. transformedTangent = im * transformedTangent;
  4308. #endif
  4309. #endif
  4310. transformedNormal = normalMatrix * transformedNormal;
  4311. #ifdef FLIP_SIDED
  4312. transformedNormal = - transformedNormal;
  4313. #endif
  4314. #ifdef USE_TANGENT
  4315. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  4316. #ifdef FLIP_SIDED
  4317. transformedTangent = - transformedTangent;
  4318. #endif
  4319. #endif`,hTe=`#ifdef USE_DISPLACEMENTMAP
  4320. uniform sampler2D displacementMap;
  4321. uniform float displacementScale;
  4322. uniform float displacementBias;
  4323. #endif`,fTe=`#ifdef USE_DISPLACEMENTMAP
  4324. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  4325. #endif`,gTe=`#ifdef USE_EMISSIVEMAP
  4326. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  4327. totalEmissiveRadiance *= emissiveColor.rgb;
  4328. #endif`,bTe=`#ifdef USE_EMISSIVEMAP
  4329. uniform sampler2D emissiveMap;
  4330. #endif`,xTe="gl_FragColor = linearToOutputTexel( gl_FragColor );",yTe=`
  4331. const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
  4332. vec3( 0.8224621, 0.177538, 0.0 ),
  4333. vec3( 0.0331941, 0.9668058, 0.0 ),
  4334. vec3( 0.0170827, 0.0723974, 0.9105199 )
  4335. );
  4336. const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
  4337. vec3( 1.2249401, - 0.2249404, 0.0 ),
  4338. vec3( - 0.0420569, 1.0420571, 0.0 ),
  4339. vec3( - 0.0196376, - 0.0786361, 1.0982735 )
  4340. );
  4341. vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
  4342. return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
  4343. }
  4344. vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
  4345. return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
  4346. }
  4347. vec4 LinearTransferOETF( in vec4 value ) {
  4348. return value;
  4349. }
  4350. vec4 sRGBTransferOETF( in vec4 value ) {
  4351. 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 );
  4352. }
  4353. vec4 LinearToLinear( in vec4 value ) {
  4354. return value;
  4355. }
  4356. vec4 LinearTosRGB( in vec4 value ) {
  4357. return sRGBTransferOETF( value );
  4358. }`,vTe=`#ifdef USE_ENVMAP
  4359. #ifdef ENV_WORLDPOS
  4360. vec3 cameraToFrag;
  4361. if ( isOrthographic ) {
  4362. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4363. } else {
  4364. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  4365. }
  4366. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4367. #ifdef ENVMAP_MODE_REFLECTION
  4368. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  4369. #else
  4370. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  4371. #endif
  4372. #else
  4373. vec3 reflectVec = vReflect;
  4374. #endif
  4375. #ifdef ENVMAP_TYPE_CUBE
  4376. vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  4377. #else
  4378. vec4 envColor = vec4( 0.0 );
  4379. #endif
  4380. #ifdef ENVMAP_BLENDING_MULTIPLY
  4381. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  4382. #elif defined( ENVMAP_BLENDING_MIX )
  4383. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  4384. #elif defined( ENVMAP_BLENDING_ADD )
  4385. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  4386. #endif
  4387. #endif`,wTe=`#ifdef USE_ENVMAP
  4388. uniform float envMapIntensity;
  4389. uniform float flipEnvMap;
  4390. #ifdef ENVMAP_TYPE_CUBE
  4391. uniform samplerCube envMap;
  4392. #else
  4393. uniform sampler2D envMap;
  4394. #endif
  4395. #endif`,STe=`#ifdef USE_ENVMAP
  4396. uniform float reflectivity;
  4397. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4398. #define ENV_WORLDPOS
  4399. #endif
  4400. #ifdef ENV_WORLDPOS
  4401. varying vec3 vWorldPosition;
  4402. uniform float refractionRatio;
  4403. #else
  4404. varying vec3 vReflect;
  4405. #endif
  4406. #endif`,_Te=`#ifdef USE_ENVMAP
  4407. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4408. #define ENV_WORLDPOS
  4409. #endif
  4410. #ifdef ENV_WORLDPOS
  4411. varying vec3 vWorldPosition;
  4412. #else
  4413. varying vec3 vReflect;
  4414. uniform float refractionRatio;
  4415. #endif
  4416. #endif`,kTe=`#ifdef USE_ENVMAP
  4417. #ifdef ENV_WORLDPOS
  4418. vWorldPosition = worldPosition.xyz;
  4419. #else
  4420. vec3 cameraToVertex;
  4421. if ( isOrthographic ) {
  4422. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4423. } else {
  4424. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  4425. }
  4426. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  4427. #ifdef ENVMAP_MODE_REFLECTION
  4428. vReflect = reflect( cameraToVertex, worldNormal );
  4429. #else
  4430. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  4431. #endif
  4432. #endif
  4433. #endif`,NTe=`#ifdef USE_FOG
  4434. vFogDepth = - mvPosition.z;
  4435. #endif`,CTe=`#ifdef USE_FOG
  4436. varying float vFogDepth;
  4437. #endif`,PTe=`#ifdef USE_FOG
  4438. #ifdef FOG_EXP2
  4439. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  4440. #else
  4441. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  4442. #endif
  4443. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  4444. #endif`,TTe=`#ifdef USE_FOG
  4445. uniform vec3 fogColor;
  4446. varying float vFogDepth;
  4447. #ifdef FOG_EXP2
  4448. uniform float fogDensity;
  4449. #else
  4450. uniform float fogNear;
  4451. uniform float fogFar;
  4452. #endif
  4453. #endif`,ATe=`#ifdef USE_GRADIENTMAP
  4454. uniform sampler2D gradientMap;
  4455. #endif
  4456. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  4457. float dotNL = dot( normal, lightDirection );
  4458. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  4459. #ifdef USE_GRADIENTMAP
  4460. return vec3( texture2D( gradientMap, coord ).r );
  4461. #else
  4462. vec2 fw = fwidth( coord ) * 0.5;
  4463. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  4464. #endif
  4465. }`,jTe=`#ifdef USE_LIGHTMAP
  4466. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  4467. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  4468. reflectedLight.indirectDiffuse += lightMapIrradiance;
  4469. #endif`,MTe=`#ifdef USE_LIGHTMAP
  4470. uniform sampler2D lightMap;
  4471. uniform float lightMapIntensity;
  4472. #endif`,ETe=`LambertMaterial material;
  4473. material.diffuseColor = diffuseColor.rgb;
  4474. material.specularStrength = specularStrength;`,DTe=`varying vec3 vViewPosition;
  4475. struct LambertMaterial {
  4476. vec3 diffuseColor;
  4477. float specularStrength;
  4478. };
  4479. 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 ) {
  4480. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4481. vec3 irradiance = dotNL * directLight.color;
  4482. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4483. }
  4484. 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 ) {
  4485. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4486. }
  4487. #define RE_Direct RE_Direct_Lambert
  4488. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,FTe=`uniform bool receiveShadow;
  4489. uniform vec3 ambientLightColor;
  4490. #if defined( USE_LIGHT_PROBES )
  4491. uniform vec3 lightProbe[ 9 ];
  4492. #endif
  4493. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  4494. float x = normal.x, y = normal.y, z = normal.z;
  4495. vec3 result = shCoefficients[ 0 ] * 0.886227;
  4496. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  4497. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  4498. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  4499. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  4500. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  4501. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  4502. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  4503. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  4504. return result;
  4505. }
  4506. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  4507. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4508. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  4509. return irradiance;
  4510. }
  4511. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  4512. vec3 irradiance = ambientLightColor;
  4513. return irradiance;
  4514. }
  4515. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  4516. #if defined ( LEGACY_LIGHTS )
  4517. if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
  4518. return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
  4519. }
  4520. return 1.0;
  4521. #else
  4522. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  4523. if ( cutoffDistance > 0.0 ) {
  4524. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  4525. }
  4526. return distanceFalloff;
  4527. #endif
  4528. }
  4529. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  4530. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  4531. }
  4532. #if NUM_DIR_LIGHTS > 0
  4533. struct DirectionalLight {
  4534. vec3 direction;
  4535. vec3 color;
  4536. };
  4537. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  4538. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  4539. light.color = directionalLight.color;
  4540. light.direction = directionalLight.direction;
  4541. light.visible = true;
  4542. }
  4543. #endif
  4544. #if NUM_POINT_LIGHTS > 0
  4545. struct PointLight {
  4546. vec3 position;
  4547. vec3 color;
  4548. float distance;
  4549. float decay;
  4550. };
  4551. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  4552. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4553. vec3 lVector = pointLight.position - geometryPosition;
  4554. light.direction = normalize( lVector );
  4555. float lightDistance = length( lVector );
  4556. light.color = pointLight.color;
  4557. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  4558. light.visible = ( light.color != vec3( 0.0 ) );
  4559. }
  4560. #endif
  4561. #if NUM_SPOT_LIGHTS > 0
  4562. struct SpotLight {
  4563. vec3 position;
  4564. vec3 direction;
  4565. vec3 color;
  4566. float distance;
  4567. float decay;
  4568. float coneCos;
  4569. float penumbraCos;
  4570. };
  4571. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  4572. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4573. vec3 lVector = spotLight.position - geometryPosition;
  4574. light.direction = normalize( lVector );
  4575. float angleCos = dot( light.direction, spotLight.direction );
  4576. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  4577. if ( spotAttenuation > 0.0 ) {
  4578. float lightDistance = length( lVector );
  4579. light.color = spotLight.color * spotAttenuation;
  4580. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  4581. light.visible = ( light.color != vec3( 0.0 ) );
  4582. } else {
  4583. light.color = vec3( 0.0 );
  4584. light.visible = false;
  4585. }
  4586. }
  4587. #endif
  4588. #if NUM_RECT_AREA_LIGHTS > 0
  4589. struct RectAreaLight {
  4590. vec3 color;
  4591. vec3 position;
  4592. vec3 halfWidth;
  4593. vec3 halfHeight;
  4594. };
  4595. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  4596. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  4597. #endif
  4598. #if NUM_HEMI_LIGHTS > 0
  4599. struct HemisphereLight {
  4600. vec3 direction;
  4601. vec3 skyColor;
  4602. vec3 groundColor;
  4603. };
  4604. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  4605. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  4606. float dotNL = dot( normal, hemiLight.direction );
  4607. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  4608. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  4609. return irradiance;
  4610. }
  4611. #endif`,LTe=`#ifdef USE_ENVMAP
  4612. vec3 getIBLIrradiance( const in vec3 normal ) {
  4613. #ifdef ENVMAP_TYPE_CUBE_UV
  4614. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4615. vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
  4616. return PI * envMapColor.rgb * envMapIntensity;
  4617. #else
  4618. return vec3( 0.0 );
  4619. #endif
  4620. }
  4621. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  4622. #ifdef ENVMAP_TYPE_CUBE_UV
  4623. vec3 reflectVec = reflect( - viewDir, normal );
  4624. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  4625. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  4626. vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
  4627. return envMapColor.rgb * envMapIntensity;
  4628. #else
  4629. return vec3( 0.0 );
  4630. #endif
  4631. }
  4632. #ifdef USE_ANISOTROPY
  4633. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  4634. #ifdef ENVMAP_TYPE_CUBE_UV
  4635. vec3 bentNormal = cross( bitangent, viewDir );
  4636. bentNormal = normalize( cross( bentNormal, bitangent ) );
  4637. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  4638. return getIBLRadiance( viewDir, bentNormal, roughness );
  4639. #else
  4640. return vec3( 0.0 );
  4641. #endif
  4642. }
  4643. #endif
  4644. #endif`,RTe=`ToonMaterial material;
  4645. material.diffuseColor = diffuseColor.rgb;`,ITe=`varying vec3 vViewPosition;
  4646. struct ToonMaterial {
  4647. vec3 diffuseColor;
  4648. };
  4649. 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 ) {
  4650. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  4651. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4652. }
  4653. 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 ) {
  4654. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4655. }
  4656. #define RE_Direct RE_Direct_Toon
  4657. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,OTe=`BlinnPhongMaterial material;
  4658. material.diffuseColor = diffuseColor.rgb;
  4659. material.specularColor = specular;
  4660. material.specularShininess = shininess;
  4661. material.specularStrength = specularStrength;`,zTe=`varying vec3 vViewPosition;
  4662. struct BlinnPhongMaterial {
  4663. vec3 diffuseColor;
  4664. vec3 specularColor;
  4665. float specularShininess;
  4666. float specularStrength;
  4667. };
  4668. 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 ) {
  4669. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4670. vec3 irradiance = dotNL * directLight.color;
  4671. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4672. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  4673. }
  4674. 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 ) {
  4675. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4676. }
  4677. #define RE_Direct RE_Direct_BlinnPhong
  4678. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,UTe=`PhysicalMaterial material;
  4679. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  4680. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  4681. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  4682. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  4683. material.roughness = min( material.roughness, 1.0 );
  4684. #ifdef IOR
  4685. material.ior = ior;
  4686. #ifdef USE_SPECULAR
  4687. float specularIntensityFactor = specularIntensity;
  4688. vec3 specularColorFactor = specularColor;
  4689. #ifdef USE_SPECULAR_COLORMAP
  4690. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  4691. #endif
  4692. #ifdef USE_SPECULAR_INTENSITYMAP
  4693. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  4694. #endif
  4695. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  4696. #else
  4697. float specularIntensityFactor = 1.0;
  4698. vec3 specularColorFactor = vec3( 1.0 );
  4699. material.specularF90 = 1.0;
  4700. #endif
  4701. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  4702. #else
  4703. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  4704. material.specularF90 = 1.0;
  4705. #endif
  4706. #ifdef USE_CLEARCOAT
  4707. material.clearcoat = clearcoat;
  4708. material.clearcoatRoughness = clearcoatRoughness;
  4709. material.clearcoatF0 = vec3( 0.04 );
  4710. material.clearcoatF90 = 1.0;
  4711. #ifdef USE_CLEARCOATMAP
  4712. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  4713. #endif
  4714. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  4715. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  4716. #endif
  4717. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  4718. material.clearcoatRoughness += geometryRoughness;
  4719. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  4720. #endif
  4721. #ifdef USE_IRIDESCENCE
  4722. material.iridescence = iridescence;
  4723. material.iridescenceIOR = iridescenceIOR;
  4724. #ifdef USE_IRIDESCENCEMAP
  4725. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  4726. #endif
  4727. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  4728. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  4729. #else
  4730. material.iridescenceThickness = iridescenceThicknessMaximum;
  4731. #endif
  4732. #endif
  4733. #ifdef USE_SHEEN
  4734. material.sheenColor = sheenColor;
  4735. #ifdef USE_SHEEN_COLORMAP
  4736. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  4737. #endif
  4738. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  4739. #ifdef USE_SHEEN_ROUGHNESSMAP
  4740. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  4741. #endif
  4742. #endif
  4743. #ifdef USE_ANISOTROPY
  4744. #ifdef USE_ANISOTROPYMAP
  4745. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  4746. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  4747. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  4748. #else
  4749. vec2 anisotropyV = anisotropyVector;
  4750. #endif
  4751. material.anisotropy = length( anisotropyV );
  4752. if( material.anisotropy == 0.0 ) {
  4753. anisotropyV = vec2( 1.0, 0.0 );
  4754. } else {
  4755. anisotropyV /= material.anisotropy;
  4756. material.anisotropy = saturate( material.anisotropy );
  4757. }
  4758. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  4759. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  4760. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  4761. #endif`,BTe=`struct PhysicalMaterial {
  4762. vec3 diffuseColor;
  4763. float roughness;
  4764. vec3 specularColor;
  4765. float specularF90;
  4766. #ifdef USE_CLEARCOAT
  4767. float clearcoat;
  4768. float clearcoatRoughness;
  4769. vec3 clearcoatF0;
  4770. float clearcoatF90;
  4771. #endif
  4772. #ifdef USE_IRIDESCENCE
  4773. float iridescence;
  4774. float iridescenceIOR;
  4775. float iridescenceThickness;
  4776. vec3 iridescenceFresnel;
  4777. vec3 iridescenceF0;
  4778. #endif
  4779. #ifdef USE_SHEEN
  4780. vec3 sheenColor;
  4781. float sheenRoughness;
  4782. #endif
  4783. #ifdef IOR
  4784. float ior;
  4785. #endif
  4786. #ifdef USE_TRANSMISSION
  4787. float transmission;
  4788. float transmissionAlpha;
  4789. float thickness;
  4790. float attenuationDistance;
  4791. vec3 attenuationColor;
  4792. #endif
  4793. #ifdef USE_ANISOTROPY
  4794. float anisotropy;
  4795. float alphaT;
  4796. vec3 anisotropyT;
  4797. vec3 anisotropyB;
  4798. #endif
  4799. };
  4800. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  4801. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  4802. vec3 sheenSpecularDirect = vec3( 0.0 );
  4803. vec3 sheenSpecularIndirect = vec3(0.0 );
  4804. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  4805. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  4806. float x2 = x * x;
  4807. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  4808. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  4809. }
  4810. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  4811. float a2 = pow2( alpha );
  4812. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  4813. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  4814. return 0.5 / max( gv + gl, EPSILON );
  4815. }
  4816. float D_GGX( const in float alpha, const in float dotNH ) {
  4817. float a2 = pow2( alpha );
  4818. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  4819. return RECIPROCAL_PI * a2 / pow2( denom );
  4820. }
  4821. #ifdef USE_ANISOTROPY
  4822. 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 ) {
  4823. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  4824. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  4825. float v = 0.5 / ( gv + gl );
  4826. return saturate(v);
  4827. }
  4828. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  4829. float a2 = alphaT * alphaB;
  4830. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  4831. highp float v2 = dot( v, v );
  4832. float w2 = a2 / v2;
  4833. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  4834. }
  4835. #endif
  4836. #ifdef USE_CLEARCOAT
  4837. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  4838. vec3 f0 = material.clearcoatF0;
  4839. float f90 = material.clearcoatF90;
  4840. float roughness = material.clearcoatRoughness;
  4841. float alpha = pow2( roughness );
  4842. vec3 halfDir = normalize( lightDir + viewDir );
  4843. float dotNL = saturate( dot( normal, lightDir ) );
  4844. float dotNV = saturate( dot( normal, viewDir ) );
  4845. float dotNH = saturate( dot( normal, halfDir ) );
  4846. float dotVH = saturate( dot( viewDir, halfDir ) );
  4847. vec3 F = F_Schlick( f0, f90, dotVH );
  4848. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4849. float D = D_GGX( alpha, dotNH );
  4850. return F * ( V * D );
  4851. }
  4852. #endif
  4853. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  4854. vec3 f0 = material.specularColor;
  4855. float f90 = material.specularF90;
  4856. float roughness = material.roughness;
  4857. float alpha = pow2( roughness );
  4858. vec3 halfDir = normalize( lightDir + viewDir );
  4859. float dotNL = saturate( dot( normal, lightDir ) );
  4860. float dotNV = saturate( dot( normal, viewDir ) );
  4861. float dotNH = saturate( dot( normal, halfDir ) );
  4862. float dotVH = saturate( dot( viewDir, halfDir ) );
  4863. vec3 F = F_Schlick( f0, f90, dotVH );
  4864. #ifdef USE_IRIDESCENCE
  4865. F = mix( F, material.iridescenceFresnel, material.iridescence );
  4866. #endif
  4867. #ifdef USE_ANISOTROPY
  4868. float dotTL = dot( material.anisotropyT, lightDir );
  4869. float dotTV = dot( material.anisotropyT, viewDir );
  4870. float dotTH = dot( material.anisotropyT, halfDir );
  4871. float dotBL = dot( material.anisotropyB, lightDir );
  4872. float dotBV = dot( material.anisotropyB, viewDir );
  4873. float dotBH = dot( material.anisotropyB, halfDir );
  4874. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  4875. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  4876. #else
  4877. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4878. float D = D_GGX( alpha, dotNH );
  4879. #endif
  4880. return F * ( V * D );
  4881. }
  4882. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  4883. const float LUT_SIZE = 64.0;
  4884. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  4885. const float LUT_BIAS = 0.5 / LUT_SIZE;
  4886. float dotNV = saturate( dot( N, V ) );
  4887. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  4888. uv = uv * LUT_SCALE + LUT_BIAS;
  4889. return uv;
  4890. }
  4891. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  4892. float l = length( f );
  4893. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  4894. }
  4895. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  4896. float x = dot( v1, v2 );
  4897. float y = abs( x );
  4898. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  4899. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  4900. float v = a / b;
  4901. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  4902. return cross( v1, v2 ) * theta_sintheta;
  4903. }
  4904. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  4905. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  4906. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  4907. vec3 lightNormal = cross( v1, v2 );
  4908. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  4909. vec3 T1, T2;
  4910. T1 = normalize( V - N * dot( V, N ) );
  4911. T2 = - cross( N, T1 );
  4912. mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
  4913. vec3 coords[ 4 ];
  4914. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  4915. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  4916. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  4917. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  4918. coords[ 0 ] = normalize( coords[ 0 ] );
  4919. coords[ 1 ] = normalize( coords[ 1 ] );
  4920. coords[ 2 ] = normalize( coords[ 2 ] );
  4921. coords[ 3 ] = normalize( coords[ 3 ] );
  4922. vec3 vectorFormFactor = vec3( 0.0 );
  4923. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  4924. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  4925. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  4926. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  4927. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  4928. return vec3( result );
  4929. }
  4930. #if defined( USE_SHEEN )
  4931. float D_Charlie( float roughness, float dotNH ) {
  4932. float alpha = pow2( roughness );
  4933. float invAlpha = 1.0 / alpha;
  4934. float cos2h = dotNH * dotNH;
  4935. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  4936. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  4937. }
  4938. float V_Neubelt( float dotNV, float dotNL ) {
  4939. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  4940. }
  4941. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  4942. vec3 halfDir = normalize( lightDir + viewDir );
  4943. float dotNL = saturate( dot( normal, lightDir ) );
  4944. float dotNV = saturate( dot( normal, viewDir ) );
  4945. float dotNH = saturate( dot( normal, halfDir ) );
  4946. float D = D_Charlie( sheenRoughness, dotNH );
  4947. float V = V_Neubelt( dotNV, dotNL );
  4948. return sheenColor * ( D * V );
  4949. }
  4950. #endif
  4951. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4952. float dotNV = saturate( dot( normal, viewDir ) );
  4953. float r2 = roughness * roughness;
  4954. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  4955. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  4956. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  4957. return saturate( DG * RECIPROCAL_PI );
  4958. }
  4959. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4960. float dotNV = saturate( dot( normal, viewDir ) );
  4961. const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  4962. const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  4963. vec4 r = roughness * c0 + c1;
  4964. float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
  4965. vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
  4966. return fab;
  4967. }
  4968. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  4969. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4970. return specularColor * fab.x + specularF90 * fab.y;
  4971. }
  4972. #ifdef USE_IRIDESCENCE
  4973. 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 ) {
  4974. #else
  4975. 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 ) {
  4976. #endif
  4977. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4978. #ifdef USE_IRIDESCENCE
  4979. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  4980. #else
  4981. vec3 Fr = specularColor;
  4982. #endif
  4983. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  4984. float Ess = fab.x + fab.y;
  4985. float Ems = 1.0 - Ess;
  4986. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  4987. singleScatter += FssEss;
  4988. multiScatter += Fms * Ems;
  4989. }
  4990. #if NUM_RECT_AREA_LIGHTS > 0
  4991. 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 ) {
  4992. vec3 normal = geometryNormal;
  4993. vec3 viewDir = geometryViewDir;
  4994. vec3 position = geometryPosition;
  4995. vec3 lightPos = rectAreaLight.position;
  4996. vec3 halfWidth = rectAreaLight.halfWidth;
  4997. vec3 halfHeight = rectAreaLight.halfHeight;
  4998. vec3 lightColor = rectAreaLight.color;
  4999. float roughness = material.roughness;
  5000. vec3 rectCoords[ 4 ];
  5001. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  5002. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  5003. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  5004. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  5005. vec4 t1 = texture2D( ltc_1, uv );
  5006. vec4 t2 = texture2D( ltc_2, uv );
  5007. mat3 mInv = mat3(
  5008. vec3( t1.x, 0, t1.y ),
  5009. vec3( 0, 1, 0 ),
  5010. vec3( t1.z, 0, t1.w )
  5011. );
  5012. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  5013. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  5014. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  5015. }
  5016. #endif
  5017. 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 ) {
  5018. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  5019. vec3 irradiance = dotNL * directLight.color;
  5020. #ifdef USE_CLEARCOAT
  5021. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  5022. vec3 ccIrradiance = dotNLcc * directLight.color;
  5023. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  5024. #endif
  5025. #ifdef USE_SHEEN
  5026. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  5027. #endif
  5028. reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
  5029. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5030. }
  5031. 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 ) {
  5032. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5033. }
  5034. 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) {
  5035. #ifdef USE_CLEARCOAT
  5036. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  5037. #endif
  5038. #ifdef USE_SHEEN
  5039. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  5040. #endif
  5041. vec3 singleScattering = vec3( 0.0 );
  5042. vec3 multiScattering = vec3( 0.0 );
  5043. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  5044. #ifdef USE_IRIDESCENCE
  5045. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  5046. #else
  5047. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  5048. #endif
  5049. vec3 totalScattering = singleScattering + multiScattering;
  5050. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  5051. reflectedLight.indirectSpecular += radiance * singleScattering;
  5052. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  5053. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  5054. }
  5055. #define RE_Direct RE_Direct_Physical
  5056. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  5057. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  5058. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  5059. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  5060. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  5061. }`,HTe=`
  5062. vec3 geometryPosition = - vViewPosition;
  5063. vec3 geometryNormal = normal;
  5064. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  5065. vec3 geometryClearcoatNormal = vec3( 0.0 );
  5066. #ifdef USE_CLEARCOAT
  5067. geometryClearcoatNormal = clearcoatNormal;
  5068. #endif
  5069. #ifdef USE_IRIDESCENCE
  5070. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  5071. if ( material.iridescenceThickness == 0.0 ) {
  5072. material.iridescence = 0.0;
  5073. } else {
  5074. material.iridescence = saturate( material.iridescence );
  5075. }
  5076. if ( material.iridescence > 0.0 ) {
  5077. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  5078. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  5079. }
  5080. #endif
  5081. IncidentLight directLight;
  5082. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  5083. PointLight pointLight;
  5084. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  5085. PointLightShadow pointLightShadow;
  5086. #endif
  5087. #pragma unroll_loop_start
  5088. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  5089. pointLight = pointLights[ i ];
  5090. getPointLightInfo( pointLight, geometryPosition, directLight );
  5091. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  5092. pointLightShadow = pointLightShadows[ i ];
  5093. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  5094. #endif
  5095. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5096. }
  5097. #pragma unroll_loop_end
  5098. #endif
  5099. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  5100. SpotLight spotLight;
  5101. vec4 spotColor;
  5102. vec3 spotLightCoord;
  5103. bool inSpotLightMap;
  5104. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  5105. SpotLightShadow spotLightShadow;
  5106. #endif
  5107. #pragma unroll_loop_start
  5108. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  5109. spotLight = spotLights[ i ];
  5110. getSpotLightInfo( spotLight, geometryPosition, directLight );
  5111. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5112. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  5113. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5114. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  5115. #else
  5116. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5117. #endif
  5118. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  5119. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  5120. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  5121. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  5122. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  5123. #endif
  5124. #undef SPOT_LIGHT_MAP_INDEX
  5125. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5126. spotLightShadow = spotLightShadows[ i ];
  5127. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5128. #endif
  5129. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5130. }
  5131. #pragma unroll_loop_end
  5132. #endif
  5133. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  5134. DirectionalLight directionalLight;
  5135. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  5136. DirectionalLightShadow directionalLightShadow;
  5137. #endif
  5138. #pragma unroll_loop_start
  5139. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  5140. directionalLight = directionalLights[ i ];
  5141. getDirectionalLightInfo( directionalLight, directLight );
  5142. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  5143. directionalLightShadow = directionalLightShadows[ i ];
  5144. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5145. #endif
  5146. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5147. }
  5148. #pragma unroll_loop_end
  5149. #endif
  5150. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  5151. RectAreaLight rectAreaLight;
  5152. #pragma unroll_loop_start
  5153. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  5154. rectAreaLight = rectAreaLights[ i ];
  5155. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5156. }
  5157. #pragma unroll_loop_end
  5158. #endif
  5159. #if defined( RE_IndirectDiffuse )
  5160. vec3 iblIrradiance = vec3( 0.0 );
  5161. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  5162. #if defined( USE_LIGHT_PROBES )
  5163. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  5164. #endif
  5165. #if ( NUM_HEMI_LIGHTS > 0 )
  5166. #pragma unroll_loop_start
  5167. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  5168. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  5169. }
  5170. #pragma unroll_loop_end
  5171. #endif
  5172. #endif
  5173. #if defined( RE_IndirectSpecular )
  5174. vec3 radiance = vec3( 0.0 );
  5175. vec3 clearcoatRadiance = vec3( 0.0 );
  5176. #endif`,qTe=`#if defined( RE_IndirectDiffuse )
  5177. #ifdef USE_LIGHTMAP
  5178. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  5179. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  5180. irradiance += lightMapIrradiance;
  5181. #endif
  5182. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  5183. iblIrradiance += getIBLIrradiance( geometryNormal );
  5184. #endif
  5185. #endif
  5186. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  5187. #ifdef USE_ANISOTROPY
  5188. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  5189. #else
  5190. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  5191. #endif
  5192. #ifdef USE_CLEARCOAT
  5193. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  5194. #endif
  5195. #endif`,$Te=`#if defined( RE_IndirectDiffuse )
  5196. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5197. #endif
  5198. #if defined( RE_IndirectSpecular )
  5199. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5200. #endif`,VTe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5201. gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  5202. #endif`,GTe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5203. uniform float logDepthBufFC;
  5204. varying float vFragDepth;
  5205. varying float vIsPerspective;
  5206. #endif`,WTe=`#ifdef USE_LOGDEPTHBUF
  5207. #ifdef USE_LOGDEPTHBUF_EXT
  5208. varying float vFragDepth;
  5209. varying float vIsPerspective;
  5210. #else
  5211. uniform float logDepthBufFC;
  5212. #endif
  5213. #endif`,KTe=`#ifdef USE_LOGDEPTHBUF
  5214. #ifdef USE_LOGDEPTHBUF_EXT
  5215. vFragDepth = 1.0 + gl_Position.w;
  5216. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  5217. #else
  5218. if ( isPerspectiveMatrix( projectionMatrix ) ) {
  5219. gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;
  5220. gl_Position.z *= gl_Position.w;
  5221. }
  5222. #endif
  5223. #endif`,QTe=`#ifdef USE_MAP
  5224. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  5225. #ifdef DECODE_VIDEO_TEXTURE
  5226. 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 );
  5227. #endif
  5228. diffuseColor *= sampledDiffuseColor;
  5229. #endif`,YTe=`#ifdef USE_MAP
  5230. uniform sampler2D map;
  5231. #endif`,XTe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5232. #if defined( USE_POINTS_UV )
  5233. vec2 uv = vUv;
  5234. #else
  5235. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  5236. #endif
  5237. #endif
  5238. #ifdef USE_MAP
  5239. diffuseColor *= texture2D( map, uv );
  5240. #endif
  5241. #ifdef USE_ALPHAMAP
  5242. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  5243. #endif`,ZTe=`#if defined( USE_POINTS_UV )
  5244. varying vec2 vUv;
  5245. #else
  5246. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5247. uniform mat3 uvTransform;
  5248. #endif
  5249. #endif
  5250. #ifdef USE_MAP
  5251. uniform sampler2D map;
  5252. #endif
  5253. #ifdef USE_ALPHAMAP
  5254. uniform sampler2D alphaMap;
  5255. #endif`,JTe=`float metalnessFactor = metalness;
  5256. #ifdef USE_METALNESSMAP
  5257. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  5258. metalnessFactor *= texelMetalness.b;
  5259. #endif`,eAe=`#ifdef USE_METALNESSMAP
  5260. uniform sampler2D metalnessMap;
  5261. #endif`,tAe=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )
  5262. vColor *= morphTargetBaseInfluence;
  5263. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5264. #if defined( USE_COLOR_ALPHA )
  5265. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  5266. #elif defined( USE_COLOR )
  5267. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  5268. #endif
  5269. }
  5270. #endif`,nAe=`#ifdef USE_MORPHNORMALS
  5271. objectNormal *= morphTargetBaseInfluence;
  5272. #ifdef MORPHTARGETS_TEXTURE
  5273. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5274. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  5275. }
  5276. #else
  5277. objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];
  5278. objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];
  5279. objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];
  5280. objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];
  5281. #endif
  5282. #endif`,rAe=`#ifdef USE_MORPHTARGETS
  5283. uniform float morphTargetBaseInfluence;
  5284. #ifdef MORPHTARGETS_TEXTURE
  5285. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  5286. uniform sampler2DArray morphTargetsTexture;
  5287. uniform ivec2 morphTargetsTextureSize;
  5288. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  5289. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  5290. int y = texelIndex / morphTargetsTextureSize.x;
  5291. int x = texelIndex - y * morphTargetsTextureSize.x;
  5292. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  5293. return texelFetch( morphTargetsTexture, morphUV, 0 );
  5294. }
  5295. #else
  5296. #ifndef USE_MORPHNORMALS
  5297. uniform float morphTargetInfluences[ 8 ];
  5298. #else
  5299. uniform float morphTargetInfluences[ 4 ];
  5300. #endif
  5301. #endif
  5302. #endif`,aAe=`#ifdef USE_MORPHTARGETS
  5303. transformed *= morphTargetBaseInfluence;
  5304. #ifdef MORPHTARGETS_TEXTURE
  5305. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5306. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  5307. }
  5308. #else
  5309. transformed += morphTarget0 * morphTargetInfluences[ 0 ];
  5310. transformed += morphTarget1 * morphTargetInfluences[ 1 ];
  5311. transformed += morphTarget2 * morphTargetInfluences[ 2 ];
  5312. transformed += morphTarget3 * morphTargetInfluences[ 3 ];
  5313. #ifndef USE_MORPHNORMALS
  5314. transformed += morphTarget4 * morphTargetInfluences[ 4 ];
  5315. transformed += morphTarget5 * morphTargetInfluences[ 5 ];
  5316. transformed += morphTarget6 * morphTargetInfluences[ 6 ];
  5317. transformed += morphTarget7 * morphTargetInfluences[ 7 ];
  5318. #endif
  5319. #endif
  5320. #endif`,iAe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  5321. #ifdef FLAT_SHADED
  5322. vec3 fdx = dFdx( vViewPosition );
  5323. vec3 fdy = dFdy( vViewPosition );
  5324. vec3 normal = normalize( cross( fdx, fdy ) );
  5325. #else
  5326. vec3 normal = normalize( vNormal );
  5327. #ifdef DOUBLE_SIDED
  5328. normal *= faceDirection;
  5329. #endif
  5330. #endif
  5331. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  5332. #ifdef USE_TANGENT
  5333. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5334. #else
  5335. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  5336. #if defined( USE_NORMALMAP )
  5337. vNormalMapUv
  5338. #elif defined( USE_CLEARCOAT_NORMALMAP )
  5339. vClearcoatNormalMapUv
  5340. #else
  5341. vUv
  5342. #endif
  5343. );
  5344. #endif
  5345. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5346. tbn[0] *= faceDirection;
  5347. tbn[1] *= faceDirection;
  5348. #endif
  5349. #endif
  5350. #ifdef USE_CLEARCOAT_NORMALMAP
  5351. #ifdef USE_TANGENT
  5352. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5353. #else
  5354. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  5355. #endif
  5356. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5357. tbn2[0] *= faceDirection;
  5358. tbn2[1] *= faceDirection;
  5359. #endif
  5360. #endif
  5361. vec3 nonPerturbedNormal = normal;`,sAe=`#ifdef USE_NORMALMAP_OBJECTSPACE
  5362. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5363. #ifdef FLIP_SIDED
  5364. normal = - normal;
  5365. #endif
  5366. #ifdef DOUBLE_SIDED
  5367. normal = normal * faceDirection;
  5368. #endif
  5369. normal = normalize( normalMatrix * normal );
  5370. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  5371. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5372. mapN.xy *= normalScale;
  5373. normal = normalize( tbn * mapN );
  5374. #elif defined( USE_BUMPMAP )
  5375. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  5376. #endif`,oAe=`#ifndef FLAT_SHADED
  5377. varying vec3 vNormal;
  5378. #ifdef USE_TANGENT
  5379. varying vec3 vTangent;
  5380. varying vec3 vBitangent;
  5381. #endif
  5382. #endif`,lAe=`#ifndef FLAT_SHADED
  5383. varying vec3 vNormal;
  5384. #ifdef USE_TANGENT
  5385. varying vec3 vTangent;
  5386. varying vec3 vBitangent;
  5387. #endif
  5388. #endif`,cAe=`#ifndef FLAT_SHADED
  5389. vNormal = normalize( transformedNormal );
  5390. #ifdef USE_TANGENT
  5391. vTangent = normalize( transformedTangent );
  5392. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  5393. #endif
  5394. #endif`,dAe=`#ifdef USE_NORMALMAP
  5395. uniform sampler2D normalMap;
  5396. uniform vec2 normalScale;
  5397. #endif
  5398. #ifdef USE_NORMALMAP_OBJECTSPACE
  5399. uniform mat3 normalMatrix;
  5400. #endif
  5401. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  5402. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  5403. vec3 q0 = dFdx( eye_pos.xyz );
  5404. vec3 q1 = dFdy( eye_pos.xyz );
  5405. vec2 st0 = dFdx( uv.st );
  5406. vec2 st1 = dFdy( uv.st );
  5407. vec3 N = surf_norm;
  5408. vec3 q1perp = cross( q1, N );
  5409. vec3 q0perp = cross( N, q0 );
  5410. vec3 T = q1perp * st0.x + q0perp * st1.x;
  5411. vec3 B = q1perp * st0.y + q0perp * st1.y;
  5412. float det = max( dot( T, T ), dot( B, B ) );
  5413. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  5414. return mat3( T * scale, B * scale, N );
  5415. }
  5416. #endif`,uAe=`#ifdef USE_CLEARCOAT
  5417. vec3 clearcoatNormal = nonPerturbedNormal;
  5418. #endif`,mAe=`#ifdef USE_CLEARCOAT_NORMALMAP
  5419. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  5420. clearcoatMapN.xy *= clearcoatNormalScale;
  5421. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  5422. #endif`,pAe=`#ifdef USE_CLEARCOATMAP
  5423. uniform sampler2D clearcoatMap;
  5424. #endif
  5425. #ifdef USE_CLEARCOAT_NORMALMAP
  5426. uniform sampler2D clearcoatNormalMap;
  5427. uniform vec2 clearcoatNormalScale;
  5428. #endif
  5429. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  5430. uniform sampler2D clearcoatRoughnessMap;
  5431. #endif`,hAe=`#ifdef USE_IRIDESCENCEMAP
  5432. uniform sampler2D iridescenceMap;
  5433. #endif
  5434. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  5435. uniform sampler2D iridescenceThicknessMap;
  5436. #endif`,fAe=`#ifdef OPAQUE
  5437. diffuseColor.a = 1.0;
  5438. #endif
  5439. #ifdef USE_TRANSMISSION
  5440. diffuseColor.a *= material.transmissionAlpha;
  5441. #endif
  5442. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,gAe=`vec3 packNormalToRGB( const in vec3 normal ) {
  5443. return normalize( normal ) * 0.5 + 0.5;
  5444. }
  5445. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  5446. return 2.0 * rgb.xyz - 1.0;
  5447. }
  5448. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
  5449. const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
  5450. const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
  5451. const float ShiftRight8 = 1. / 256.;
  5452. vec4 packDepthToRGBA( const in float v ) {
  5453. vec4 r = vec4( fract( v * PackFactors ), v );
  5454. r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;
  5455. }
  5456. float unpackRGBAToDepth( const in vec4 v ) {
  5457. return dot( v, UnpackFactors );
  5458. }
  5459. vec2 packDepthToRG( in highp float v ) {
  5460. return packDepthToRGBA( v ).yx;
  5461. }
  5462. float unpackRGToDepth( const in highp vec2 v ) {
  5463. return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
  5464. }
  5465. vec4 pack2HalfToRGBA( vec2 v ) {
  5466. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  5467. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  5468. }
  5469. vec2 unpackRGBATo2Half( vec4 v ) {
  5470. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  5471. }
  5472. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  5473. return ( viewZ + near ) / ( near - far );
  5474. }
  5475. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5476. return depth * ( near - far ) - near;
  5477. }
  5478. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  5479. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  5480. }
  5481. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5482. return ( near * far ) / ( ( far - near ) * depth - far );
  5483. }`,bAe=`#ifdef PREMULTIPLIED_ALPHA
  5484. gl_FragColor.rgb *= gl_FragColor.a;
  5485. #endif`,xAe=`vec4 mvPosition = vec4( transformed, 1.0 );
  5486. #ifdef USE_BATCHING
  5487. mvPosition = batchingMatrix * mvPosition;
  5488. #endif
  5489. #ifdef USE_INSTANCING
  5490. mvPosition = instanceMatrix * mvPosition;
  5491. #endif
  5492. mvPosition = modelViewMatrix * mvPosition;
  5493. gl_Position = projectionMatrix * mvPosition;`,yAe=`#ifdef DITHERING
  5494. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  5495. #endif`,vAe=`#ifdef DITHERING
  5496. vec3 dithering( vec3 color ) {
  5497. float grid_position = rand( gl_FragCoord.xy );
  5498. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  5499. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  5500. return color + dither_shift_RGB;
  5501. }
  5502. #endif`,wAe=`float roughnessFactor = roughness;
  5503. #ifdef USE_ROUGHNESSMAP
  5504. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  5505. roughnessFactor *= texelRoughness.g;
  5506. #endif`,SAe=`#ifdef USE_ROUGHNESSMAP
  5507. uniform sampler2D roughnessMap;
  5508. #endif`,_Ae=`#if NUM_SPOT_LIGHT_COORDS > 0
  5509. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5510. #endif
  5511. #if NUM_SPOT_LIGHT_MAPS > 0
  5512. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  5513. #endif
  5514. #ifdef USE_SHADOWMAP
  5515. #if NUM_DIR_LIGHT_SHADOWS > 0
  5516. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  5517. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5518. struct DirectionalLightShadow {
  5519. float shadowBias;
  5520. float shadowNormalBias;
  5521. float shadowRadius;
  5522. vec2 shadowMapSize;
  5523. };
  5524. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5525. #endif
  5526. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5527. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  5528. struct SpotLightShadow {
  5529. float shadowBias;
  5530. float shadowNormalBias;
  5531. float shadowRadius;
  5532. vec2 shadowMapSize;
  5533. };
  5534. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5535. #endif
  5536. #if NUM_POINT_LIGHT_SHADOWS > 0
  5537. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  5538. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5539. struct PointLightShadow {
  5540. float shadowBias;
  5541. float shadowNormalBias;
  5542. float shadowRadius;
  5543. vec2 shadowMapSize;
  5544. float shadowCameraNear;
  5545. float shadowCameraFar;
  5546. };
  5547. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5548. #endif
  5549. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  5550. return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
  5551. }
  5552. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  5553. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  5554. }
  5555. float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
  5556. float occlusion = 1.0;
  5557. vec2 distribution = texture2DDistribution( shadow, uv );
  5558. float hard_shadow = step( compare , distribution.x );
  5559. if (hard_shadow != 1.0 ) {
  5560. float distance = compare - distribution.x ;
  5561. float variance = max( 0.00000, distribution.y * distribution.y );
  5562. 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 );
  5563. }
  5564. return occlusion;
  5565. }
  5566. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  5567. float shadow = 1.0;
  5568. shadowCoord.xyz /= shadowCoord.w;
  5569. shadowCoord.z += shadowBias;
  5570. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  5571. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  5572. if ( frustumTest ) {
  5573. #if defined( SHADOWMAP_TYPE_PCF )
  5574. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5575. float dx0 = - texelSize.x * shadowRadius;
  5576. float dy0 = - texelSize.y * shadowRadius;
  5577. float dx1 = + texelSize.x * shadowRadius;
  5578. float dy1 = + texelSize.y * shadowRadius;
  5579. float dx2 = dx0 / 2.0;
  5580. float dy2 = dy0 / 2.0;
  5581. float dx3 = dx1 / 2.0;
  5582. float dy3 = dy1 / 2.0;
  5583. shadow = (
  5584. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  5585. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  5586. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  5587. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  5588. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  5589. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  5590. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  5591. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  5592. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  5593. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  5594. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  5595. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  5596. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  5597. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  5598. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  5599. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  5600. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  5601. ) * ( 1.0 / 17.0 );
  5602. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  5603. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5604. float dx = texelSize.x;
  5605. float dy = texelSize.y;
  5606. vec2 uv = shadowCoord.xy;
  5607. vec2 f = fract( uv * shadowMapSize + 0.5 );
  5608. uv -= f * texelSize;
  5609. shadow = (
  5610. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  5611. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  5612. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  5613. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  5614. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  5615. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  5616. f.x ) +
  5617. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  5618. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  5619. f.x ) +
  5620. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  5621. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  5622. f.y ) +
  5623. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  5624. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  5625. f.y ) +
  5626. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  5627. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  5628. f.x ),
  5629. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  5630. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  5631. f.x ),
  5632. f.y )
  5633. ) * ( 1.0 / 9.0 );
  5634. #elif defined( SHADOWMAP_TYPE_VSM )
  5635. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  5636. #else
  5637. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  5638. #endif
  5639. }
  5640. return shadow;
  5641. }
  5642. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  5643. vec3 absV = abs( v );
  5644. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  5645. absV *= scaleToCube;
  5646. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  5647. vec2 planar = v.xy;
  5648. float almostATexel = 1.5 * texelSizeY;
  5649. float almostOne = 1.0 - almostATexel;
  5650. if ( absV.z >= almostOne ) {
  5651. if ( v.z > 0.0 )
  5652. planar.x = 4.0 - v.x;
  5653. } else if ( absV.x >= almostOne ) {
  5654. float signX = sign( v.x );
  5655. planar.x = v.z * signX + 2.0 * signX;
  5656. } else if ( absV.y >= almostOne ) {
  5657. float signY = sign( v.y );
  5658. planar.x = v.x + 2.0 * signY + 2.0;
  5659. planar.y = v.z * signY - 2.0;
  5660. }
  5661. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  5662. }
  5663. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  5664. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  5665. vec3 lightToPosition = shadowCoord.xyz;
  5666. float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  5667. vec3 bd3D = normalize( lightToPosition );
  5668. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  5669. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  5670. return (
  5671. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  5672. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  5673. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  5674. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  5675. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  5676. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  5677. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  5678. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  5679. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  5680. ) * ( 1.0 / 9.0 );
  5681. #else
  5682. return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  5683. #endif
  5684. }
  5685. #endif`,kAe=`#if NUM_SPOT_LIGHT_COORDS > 0
  5686. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  5687. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5688. #endif
  5689. #ifdef USE_SHADOWMAP
  5690. #if NUM_DIR_LIGHT_SHADOWS > 0
  5691. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  5692. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5693. struct DirectionalLightShadow {
  5694. float shadowBias;
  5695. float shadowNormalBias;
  5696. float shadowRadius;
  5697. vec2 shadowMapSize;
  5698. };
  5699. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5700. #endif
  5701. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5702. struct SpotLightShadow {
  5703. float shadowBias;
  5704. float shadowNormalBias;
  5705. float shadowRadius;
  5706. vec2 shadowMapSize;
  5707. };
  5708. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5709. #endif
  5710. #if NUM_POINT_LIGHT_SHADOWS > 0
  5711. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  5712. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5713. struct PointLightShadow {
  5714. float shadowBias;
  5715. float shadowNormalBias;
  5716. float shadowRadius;
  5717. vec2 shadowMapSize;
  5718. float shadowCameraNear;
  5719. float shadowCameraFar;
  5720. };
  5721. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5722. #endif
  5723. #endif`,NAe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  5724. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  5725. vec4 shadowWorldPosition;
  5726. #endif
  5727. #if defined( USE_SHADOWMAP )
  5728. #if NUM_DIR_LIGHT_SHADOWS > 0
  5729. #pragma unroll_loop_start
  5730. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5731. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  5732. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  5733. }
  5734. #pragma unroll_loop_end
  5735. #endif
  5736. #if NUM_POINT_LIGHT_SHADOWS > 0
  5737. #pragma unroll_loop_start
  5738. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5739. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  5740. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  5741. }
  5742. #pragma unroll_loop_end
  5743. #endif
  5744. #endif
  5745. #if NUM_SPOT_LIGHT_COORDS > 0
  5746. #pragma unroll_loop_start
  5747. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  5748. shadowWorldPosition = worldPosition;
  5749. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5750. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  5751. #endif
  5752. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  5753. }
  5754. #pragma unroll_loop_end
  5755. #endif`,CAe=`float getShadowMask() {
  5756. float shadow = 1.0;
  5757. #ifdef USE_SHADOWMAP
  5758. #if NUM_DIR_LIGHT_SHADOWS > 0
  5759. DirectionalLightShadow directionalLight;
  5760. #pragma unroll_loop_start
  5761. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5762. directionalLight = directionalLightShadows[ i ];
  5763. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5764. }
  5765. #pragma unroll_loop_end
  5766. #endif
  5767. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5768. SpotLightShadow spotLight;
  5769. #pragma unroll_loop_start
  5770. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  5771. spotLight = spotLightShadows[ i ];
  5772. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5773. }
  5774. #pragma unroll_loop_end
  5775. #endif
  5776. #if NUM_POINT_LIGHT_SHADOWS > 0
  5777. PointLightShadow pointLight;
  5778. #pragma unroll_loop_start
  5779. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5780. pointLight = pointLightShadows[ i ];
  5781. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  5782. }
  5783. #pragma unroll_loop_end
  5784. #endif
  5785. #endif
  5786. return shadow;
  5787. }`,PAe=`#ifdef USE_SKINNING
  5788. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  5789. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  5790. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  5791. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  5792. #endif`,TAe=`#ifdef USE_SKINNING
  5793. uniform mat4 bindMatrix;
  5794. uniform mat4 bindMatrixInverse;
  5795. uniform highp sampler2D boneTexture;
  5796. mat4 getBoneMatrix( const in float i ) {
  5797. int size = textureSize( boneTexture, 0 ).x;
  5798. int j = int( i ) * 4;
  5799. int x = j % size;
  5800. int y = j / size;
  5801. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  5802. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  5803. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  5804. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  5805. return mat4( v1, v2, v3, v4 );
  5806. }
  5807. #endif`,AAe=`#ifdef USE_SKINNING
  5808. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  5809. vec4 skinned = vec4( 0.0 );
  5810. skinned += boneMatX * skinVertex * skinWeight.x;
  5811. skinned += boneMatY * skinVertex * skinWeight.y;
  5812. skinned += boneMatZ * skinVertex * skinWeight.z;
  5813. skinned += boneMatW * skinVertex * skinWeight.w;
  5814. transformed = ( bindMatrixInverse * skinned ).xyz;
  5815. #endif`,jAe=`#ifdef USE_SKINNING
  5816. mat4 skinMatrix = mat4( 0.0 );
  5817. skinMatrix += skinWeight.x * boneMatX;
  5818. skinMatrix += skinWeight.y * boneMatY;
  5819. skinMatrix += skinWeight.z * boneMatZ;
  5820. skinMatrix += skinWeight.w * boneMatW;
  5821. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  5822. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  5823. #ifdef USE_TANGENT
  5824. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  5825. #endif
  5826. #endif`,MAe=`float specularStrength;
  5827. #ifdef USE_SPECULARMAP
  5828. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  5829. specularStrength = texelSpecular.r;
  5830. #else
  5831. specularStrength = 1.0;
  5832. #endif`,EAe=`#ifdef USE_SPECULARMAP
  5833. uniform sampler2D specularMap;
  5834. #endif`,DAe=`#if defined( TONE_MAPPING )
  5835. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  5836. #endif`,FAe=`#ifndef saturate
  5837. #define saturate( a ) clamp( a, 0.0, 1.0 )
  5838. #endif
  5839. uniform float toneMappingExposure;
  5840. vec3 LinearToneMapping( vec3 color ) {
  5841. return saturate( toneMappingExposure * color );
  5842. }
  5843. vec3 ReinhardToneMapping( vec3 color ) {
  5844. color *= toneMappingExposure;
  5845. return saturate( color / ( vec3( 1.0 ) + color ) );
  5846. }
  5847. vec3 OptimizedCineonToneMapping( vec3 color ) {
  5848. color *= toneMappingExposure;
  5849. color = max( vec3( 0.0 ), color - 0.004 );
  5850. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  5851. }
  5852. vec3 RRTAndODTFit( vec3 v ) {
  5853. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  5854. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  5855. return a / b;
  5856. }
  5857. vec3 ACESFilmicToneMapping( vec3 color ) {
  5858. const mat3 ACESInputMat = mat3(
  5859. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  5860. vec3( 0.04823, 0.01566, 0.83777 )
  5861. );
  5862. const mat3 ACESOutputMat = mat3(
  5863. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  5864. vec3( -0.07367, -0.00605, 1.07602 )
  5865. );
  5866. color *= toneMappingExposure / 0.6;
  5867. color = ACESInputMat * color;
  5868. color = RRTAndODTFit( color );
  5869. color = ACESOutputMat * color;
  5870. return saturate( color );
  5871. }
  5872. vec3 CustomToneMapping( vec3 color ) { return color; }`,LAe=`#ifdef USE_TRANSMISSION
  5873. material.transmission = transmission;
  5874. material.transmissionAlpha = 1.0;
  5875. material.thickness = thickness;
  5876. material.attenuationDistance = attenuationDistance;
  5877. material.attenuationColor = attenuationColor;
  5878. #ifdef USE_TRANSMISSIONMAP
  5879. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  5880. #endif
  5881. #ifdef USE_THICKNESSMAP
  5882. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  5883. #endif
  5884. vec3 pos = vWorldPosition;
  5885. vec3 v = normalize( cameraPosition - pos );
  5886. vec3 n = inverseTransformDirection( normal, viewMatrix );
  5887. vec4 transmitted = getIBLVolumeRefraction(
  5888. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  5889. pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,
  5890. material.attenuationColor, material.attenuationDistance );
  5891. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  5892. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  5893. #endif`,RAe=`#ifdef USE_TRANSMISSION
  5894. uniform float transmission;
  5895. uniform float thickness;
  5896. uniform float attenuationDistance;
  5897. uniform vec3 attenuationColor;
  5898. #ifdef USE_TRANSMISSIONMAP
  5899. uniform sampler2D transmissionMap;
  5900. #endif
  5901. #ifdef USE_THICKNESSMAP
  5902. uniform sampler2D thicknessMap;
  5903. #endif
  5904. uniform vec2 transmissionSamplerSize;
  5905. uniform sampler2D transmissionSamplerMap;
  5906. uniform mat4 modelMatrix;
  5907. uniform mat4 projectionMatrix;
  5908. varying vec3 vWorldPosition;
  5909. float w0( float a ) {
  5910. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  5911. }
  5912. float w1( float a ) {
  5913. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  5914. }
  5915. float w2( float a ){
  5916. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  5917. }
  5918. float w3( float a ) {
  5919. return ( 1.0 / 6.0 ) * ( a * a * a );
  5920. }
  5921. float g0( float a ) {
  5922. return w0( a ) + w1( a );
  5923. }
  5924. float g1( float a ) {
  5925. return w2( a ) + w3( a );
  5926. }
  5927. float h0( float a ) {
  5928. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  5929. }
  5930. float h1( float a ) {
  5931. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  5932. }
  5933. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  5934. uv = uv * texelSize.zw + 0.5;
  5935. vec2 iuv = floor( uv );
  5936. vec2 fuv = fract( uv );
  5937. float g0x = g0( fuv.x );
  5938. float g1x = g1( fuv.x );
  5939. float h0x = h0( fuv.x );
  5940. float h1x = h1( fuv.x );
  5941. float h0y = h0( fuv.y );
  5942. float h1y = h1( fuv.y );
  5943. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5944. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5945. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5946. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5947. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  5948. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  5949. }
  5950. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  5951. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  5952. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  5953. vec2 fLodSizeInv = 1.0 / fLodSize;
  5954. vec2 cLodSizeInv = 1.0 / cLodSize;
  5955. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  5956. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  5957. return mix( fSample, cSample, fract( lod ) );
  5958. }
  5959. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  5960. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  5961. vec3 modelScale;
  5962. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  5963. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  5964. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  5965. return normalize( refractionVector ) * thickness * modelScale;
  5966. }
  5967. float applyIorToRoughness( const in float roughness, const in float ior ) {
  5968. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  5969. }
  5970. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  5971. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  5972. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  5973. }
  5974. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  5975. if ( isinf( attenuationDistance ) ) {
  5976. return vec3( 1.0 );
  5977. } else {
  5978. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  5979. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  5980. }
  5981. }
  5982. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  5983. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  5984. const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
  5985. const in vec3 attenuationColor, const in float attenuationDistance ) {
  5986. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  5987. vec3 refractedRayExit = position + transmissionRay;
  5988. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  5989. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  5990. refractionCoords += 1.0;
  5991. refractionCoords /= 2.0;
  5992. vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  5993. vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  5994. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  5995. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  5996. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  5997. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  5998. }
  5999. #endif`,IAe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6000. varying vec2 vUv;
  6001. #endif
  6002. #ifdef USE_MAP
  6003. varying vec2 vMapUv;
  6004. #endif
  6005. #ifdef USE_ALPHAMAP
  6006. varying vec2 vAlphaMapUv;
  6007. #endif
  6008. #ifdef USE_LIGHTMAP
  6009. varying vec2 vLightMapUv;
  6010. #endif
  6011. #ifdef USE_AOMAP
  6012. varying vec2 vAoMapUv;
  6013. #endif
  6014. #ifdef USE_BUMPMAP
  6015. varying vec2 vBumpMapUv;
  6016. #endif
  6017. #ifdef USE_NORMALMAP
  6018. varying vec2 vNormalMapUv;
  6019. #endif
  6020. #ifdef USE_EMISSIVEMAP
  6021. varying vec2 vEmissiveMapUv;
  6022. #endif
  6023. #ifdef USE_METALNESSMAP
  6024. varying vec2 vMetalnessMapUv;
  6025. #endif
  6026. #ifdef USE_ROUGHNESSMAP
  6027. varying vec2 vRoughnessMapUv;
  6028. #endif
  6029. #ifdef USE_ANISOTROPYMAP
  6030. varying vec2 vAnisotropyMapUv;
  6031. #endif
  6032. #ifdef USE_CLEARCOATMAP
  6033. varying vec2 vClearcoatMapUv;
  6034. #endif
  6035. #ifdef USE_CLEARCOAT_NORMALMAP
  6036. varying vec2 vClearcoatNormalMapUv;
  6037. #endif
  6038. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6039. varying vec2 vClearcoatRoughnessMapUv;
  6040. #endif
  6041. #ifdef USE_IRIDESCENCEMAP
  6042. varying vec2 vIridescenceMapUv;
  6043. #endif
  6044. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6045. varying vec2 vIridescenceThicknessMapUv;
  6046. #endif
  6047. #ifdef USE_SHEEN_COLORMAP
  6048. varying vec2 vSheenColorMapUv;
  6049. #endif
  6050. #ifdef USE_SHEEN_ROUGHNESSMAP
  6051. varying vec2 vSheenRoughnessMapUv;
  6052. #endif
  6053. #ifdef USE_SPECULARMAP
  6054. varying vec2 vSpecularMapUv;
  6055. #endif
  6056. #ifdef USE_SPECULAR_COLORMAP
  6057. varying vec2 vSpecularColorMapUv;
  6058. #endif
  6059. #ifdef USE_SPECULAR_INTENSITYMAP
  6060. varying vec2 vSpecularIntensityMapUv;
  6061. #endif
  6062. #ifdef USE_TRANSMISSIONMAP
  6063. uniform mat3 transmissionMapTransform;
  6064. varying vec2 vTransmissionMapUv;
  6065. #endif
  6066. #ifdef USE_THICKNESSMAP
  6067. uniform mat3 thicknessMapTransform;
  6068. varying vec2 vThicknessMapUv;
  6069. #endif`,OAe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6070. varying vec2 vUv;
  6071. #endif
  6072. #ifdef USE_MAP
  6073. uniform mat3 mapTransform;
  6074. varying vec2 vMapUv;
  6075. #endif
  6076. #ifdef USE_ALPHAMAP
  6077. uniform mat3 alphaMapTransform;
  6078. varying vec2 vAlphaMapUv;
  6079. #endif
  6080. #ifdef USE_LIGHTMAP
  6081. uniform mat3 lightMapTransform;
  6082. varying vec2 vLightMapUv;
  6083. #endif
  6084. #ifdef USE_AOMAP
  6085. uniform mat3 aoMapTransform;
  6086. varying vec2 vAoMapUv;
  6087. #endif
  6088. #ifdef USE_BUMPMAP
  6089. uniform mat3 bumpMapTransform;
  6090. varying vec2 vBumpMapUv;
  6091. #endif
  6092. #ifdef USE_NORMALMAP
  6093. uniform mat3 normalMapTransform;
  6094. varying vec2 vNormalMapUv;
  6095. #endif
  6096. #ifdef USE_DISPLACEMENTMAP
  6097. uniform mat3 displacementMapTransform;
  6098. varying vec2 vDisplacementMapUv;
  6099. #endif
  6100. #ifdef USE_EMISSIVEMAP
  6101. uniform mat3 emissiveMapTransform;
  6102. varying vec2 vEmissiveMapUv;
  6103. #endif
  6104. #ifdef USE_METALNESSMAP
  6105. uniform mat3 metalnessMapTransform;
  6106. varying vec2 vMetalnessMapUv;
  6107. #endif
  6108. #ifdef USE_ROUGHNESSMAP
  6109. uniform mat3 roughnessMapTransform;
  6110. varying vec2 vRoughnessMapUv;
  6111. #endif
  6112. #ifdef USE_ANISOTROPYMAP
  6113. uniform mat3 anisotropyMapTransform;
  6114. varying vec2 vAnisotropyMapUv;
  6115. #endif
  6116. #ifdef USE_CLEARCOATMAP
  6117. uniform mat3 clearcoatMapTransform;
  6118. varying vec2 vClearcoatMapUv;
  6119. #endif
  6120. #ifdef USE_CLEARCOAT_NORMALMAP
  6121. uniform mat3 clearcoatNormalMapTransform;
  6122. varying vec2 vClearcoatNormalMapUv;
  6123. #endif
  6124. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6125. uniform mat3 clearcoatRoughnessMapTransform;
  6126. varying vec2 vClearcoatRoughnessMapUv;
  6127. #endif
  6128. #ifdef USE_SHEEN_COLORMAP
  6129. uniform mat3 sheenColorMapTransform;
  6130. varying vec2 vSheenColorMapUv;
  6131. #endif
  6132. #ifdef USE_SHEEN_ROUGHNESSMAP
  6133. uniform mat3 sheenRoughnessMapTransform;
  6134. varying vec2 vSheenRoughnessMapUv;
  6135. #endif
  6136. #ifdef USE_IRIDESCENCEMAP
  6137. uniform mat3 iridescenceMapTransform;
  6138. varying vec2 vIridescenceMapUv;
  6139. #endif
  6140. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6141. uniform mat3 iridescenceThicknessMapTransform;
  6142. varying vec2 vIridescenceThicknessMapUv;
  6143. #endif
  6144. #ifdef USE_SPECULARMAP
  6145. uniform mat3 specularMapTransform;
  6146. varying vec2 vSpecularMapUv;
  6147. #endif
  6148. #ifdef USE_SPECULAR_COLORMAP
  6149. uniform mat3 specularColorMapTransform;
  6150. varying vec2 vSpecularColorMapUv;
  6151. #endif
  6152. #ifdef USE_SPECULAR_INTENSITYMAP
  6153. uniform mat3 specularIntensityMapTransform;
  6154. varying vec2 vSpecularIntensityMapUv;
  6155. #endif
  6156. #ifdef USE_TRANSMISSIONMAP
  6157. uniform mat3 transmissionMapTransform;
  6158. varying vec2 vTransmissionMapUv;
  6159. #endif
  6160. #ifdef USE_THICKNESSMAP
  6161. uniform mat3 thicknessMapTransform;
  6162. varying vec2 vThicknessMapUv;
  6163. #endif`,zAe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6164. vUv = vec3( uv, 1 ).xy;
  6165. #endif
  6166. #ifdef USE_MAP
  6167. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  6168. #endif
  6169. #ifdef USE_ALPHAMAP
  6170. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  6171. #endif
  6172. #ifdef USE_LIGHTMAP
  6173. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  6174. #endif
  6175. #ifdef USE_AOMAP
  6176. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  6177. #endif
  6178. #ifdef USE_BUMPMAP
  6179. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  6180. #endif
  6181. #ifdef USE_NORMALMAP
  6182. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  6183. #endif
  6184. #ifdef USE_DISPLACEMENTMAP
  6185. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  6186. #endif
  6187. #ifdef USE_EMISSIVEMAP
  6188. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  6189. #endif
  6190. #ifdef USE_METALNESSMAP
  6191. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  6192. #endif
  6193. #ifdef USE_ROUGHNESSMAP
  6194. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  6195. #endif
  6196. #ifdef USE_ANISOTROPYMAP
  6197. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  6198. #endif
  6199. #ifdef USE_CLEARCOATMAP
  6200. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  6201. #endif
  6202. #ifdef USE_CLEARCOAT_NORMALMAP
  6203. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  6204. #endif
  6205. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6206. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  6207. #endif
  6208. #ifdef USE_IRIDESCENCEMAP
  6209. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  6210. #endif
  6211. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6212. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  6213. #endif
  6214. #ifdef USE_SHEEN_COLORMAP
  6215. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  6216. #endif
  6217. #ifdef USE_SHEEN_ROUGHNESSMAP
  6218. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  6219. #endif
  6220. #ifdef USE_SPECULARMAP
  6221. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  6222. #endif
  6223. #ifdef USE_SPECULAR_COLORMAP
  6224. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  6225. #endif
  6226. #ifdef USE_SPECULAR_INTENSITYMAP
  6227. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  6228. #endif
  6229. #ifdef USE_TRANSMISSIONMAP
  6230. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  6231. #endif
  6232. #ifdef USE_THICKNESSMAP
  6233. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  6234. #endif`,UAe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  6235. vec4 worldPosition = vec4( transformed, 1.0 );
  6236. #ifdef USE_BATCHING
  6237. worldPosition = batchingMatrix * worldPosition;
  6238. #endif
  6239. #ifdef USE_INSTANCING
  6240. worldPosition = instanceMatrix * worldPosition;
  6241. #endif
  6242. worldPosition = modelMatrix * worldPosition;
  6243. #endif`;const BAe=`varying vec2 vUv;
  6244. uniform mat3 uvTransform;
  6245. void main() {
  6246. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  6247. gl_Position = vec4( position.xy, 1.0, 1.0 );
  6248. }`,HAe=`uniform sampler2D t2D;
  6249. uniform float backgroundIntensity;
  6250. varying vec2 vUv;
  6251. void main() {
  6252. vec4 texColor = texture2D( t2D, vUv );
  6253. #ifdef DECODE_VIDEO_TEXTURE
  6254. 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 );
  6255. #endif
  6256. texColor.rgb *= backgroundIntensity;
  6257. gl_FragColor = texColor;
  6258. #include <tonemapping_fragment>
  6259. #include <colorspace_fragment>
  6260. }`,qAe=`varying vec3 vWorldDirection;
  6261. #include <common>
  6262. void main() {
  6263. vWorldDirection = transformDirection( position, modelMatrix );
  6264. #include <begin_vertex>
  6265. #include <project_vertex>
  6266. gl_Position.z = gl_Position.w;
  6267. }`,$Ae=`#ifdef ENVMAP_TYPE_CUBE
  6268. uniform samplerCube envMap;
  6269. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6270. uniform sampler2D envMap;
  6271. #endif
  6272. uniform float flipEnvMap;
  6273. uniform float backgroundBlurriness;
  6274. uniform float backgroundIntensity;
  6275. varying vec3 vWorldDirection;
  6276. #include <cube_uv_reflection_fragment>
  6277. void main() {
  6278. #ifdef ENVMAP_TYPE_CUBE
  6279. vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  6280. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6281. vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );
  6282. #else
  6283. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  6284. #endif
  6285. texColor.rgb *= backgroundIntensity;
  6286. gl_FragColor = texColor;
  6287. #include <tonemapping_fragment>
  6288. #include <colorspace_fragment>
  6289. }`,VAe=`varying vec3 vWorldDirection;
  6290. #include <common>
  6291. void main() {
  6292. vWorldDirection = transformDirection( position, modelMatrix );
  6293. #include <begin_vertex>
  6294. #include <project_vertex>
  6295. gl_Position.z = gl_Position.w;
  6296. }`,GAe=`uniform samplerCube tCube;
  6297. uniform float tFlip;
  6298. uniform float opacity;
  6299. varying vec3 vWorldDirection;
  6300. void main() {
  6301. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  6302. gl_FragColor = texColor;
  6303. gl_FragColor.a *= opacity;
  6304. #include <tonemapping_fragment>
  6305. #include <colorspace_fragment>
  6306. }`,WAe=`#include <common>
  6307. #include <batching_pars_vertex>
  6308. #include <uv_pars_vertex>
  6309. #include <displacementmap_pars_vertex>
  6310. #include <morphtarget_pars_vertex>
  6311. #include <skinning_pars_vertex>
  6312. #include <logdepthbuf_pars_vertex>
  6313. #include <clipping_planes_pars_vertex>
  6314. varying vec2 vHighPrecisionZW;
  6315. void main() {
  6316. #include <uv_vertex>
  6317. #include <batching_vertex>
  6318. #include <skinbase_vertex>
  6319. #ifdef USE_DISPLACEMENTMAP
  6320. #include <beginnormal_vertex>
  6321. #include <morphnormal_vertex>
  6322. #include <skinnormal_vertex>
  6323. #endif
  6324. #include <begin_vertex>
  6325. #include <morphtarget_vertex>
  6326. #include <skinning_vertex>
  6327. #include <displacementmap_vertex>
  6328. #include <project_vertex>
  6329. #include <logdepthbuf_vertex>
  6330. #include <clipping_planes_vertex>
  6331. vHighPrecisionZW = gl_Position.zw;
  6332. }`,KAe=`#if DEPTH_PACKING == 3200
  6333. uniform float opacity;
  6334. #endif
  6335. #include <common>
  6336. #include <packing>
  6337. #include <uv_pars_fragment>
  6338. #include <map_pars_fragment>
  6339. #include <alphamap_pars_fragment>
  6340. #include <alphatest_pars_fragment>
  6341. #include <alphahash_pars_fragment>
  6342. #include <logdepthbuf_pars_fragment>
  6343. #include <clipping_planes_pars_fragment>
  6344. varying vec2 vHighPrecisionZW;
  6345. void main() {
  6346. #include <clipping_planes_fragment>
  6347. vec4 diffuseColor = vec4( 1.0 );
  6348. #if DEPTH_PACKING == 3200
  6349. diffuseColor.a = opacity;
  6350. #endif
  6351. #include <map_fragment>
  6352. #include <alphamap_fragment>
  6353. #include <alphatest_fragment>
  6354. #include <alphahash_fragment>
  6355. #include <logdepthbuf_fragment>
  6356. float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
  6357. #if DEPTH_PACKING == 3200
  6358. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  6359. #elif DEPTH_PACKING == 3201
  6360. gl_FragColor = packDepthToRGBA( fragCoordZ );
  6361. #endif
  6362. }`,QAe=`#define DISTANCE
  6363. varying vec3 vWorldPosition;
  6364. #include <common>
  6365. #include <batching_pars_vertex>
  6366. #include <uv_pars_vertex>
  6367. #include <displacementmap_pars_vertex>
  6368. #include <morphtarget_pars_vertex>
  6369. #include <skinning_pars_vertex>
  6370. #include <clipping_planes_pars_vertex>
  6371. void main() {
  6372. #include <uv_vertex>
  6373. #include <batching_vertex>
  6374. #include <skinbase_vertex>
  6375. #ifdef USE_DISPLACEMENTMAP
  6376. #include <beginnormal_vertex>
  6377. #include <morphnormal_vertex>
  6378. #include <skinnormal_vertex>
  6379. #endif
  6380. #include <begin_vertex>
  6381. #include <morphtarget_vertex>
  6382. #include <skinning_vertex>
  6383. #include <displacementmap_vertex>
  6384. #include <project_vertex>
  6385. #include <worldpos_vertex>
  6386. #include <clipping_planes_vertex>
  6387. vWorldPosition = worldPosition.xyz;
  6388. }`,YAe=`#define DISTANCE
  6389. uniform vec3 referencePosition;
  6390. uniform float nearDistance;
  6391. uniform float farDistance;
  6392. varying vec3 vWorldPosition;
  6393. #include <common>
  6394. #include <packing>
  6395. #include <uv_pars_fragment>
  6396. #include <map_pars_fragment>
  6397. #include <alphamap_pars_fragment>
  6398. #include <alphatest_pars_fragment>
  6399. #include <alphahash_pars_fragment>
  6400. #include <clipping_planes_pars_fragment>
  6401. void main () {
  6402. #include <clipping_planes_fragment>
  6403. vec4 diffuseColor = vec4( 1.0 );
  6404. #include <map_fragment>
  6405. #include <alphamap_fragment>
  6406. #include <alphatest_fragment>
  6407. #include <alphahash_fragment>
  6408. float dist = length( vWorldPosition - referencePosition );
  6409. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  6410. dist = saturate( dist );
  6411. gl_FragColor = packDepthToRGBA( dist );
  6412. }`,XAe=`varying vec3 vWorldDirection;
  6413. #include <common>
  6414. void main() {
  6415. vWorldDirection = transformDirection( position, modelMatrix );
  6416. #include <begin_vertex>
  6417. #include <project_vertex>
  6418. }`,ZAe=`uniform sampler2D tEquirect;
  6419. varying vec3 vWorldDirection;
  6420. #include <common>
  6421. void main() {
  6422. vec3 direction = normalize( vWorldDirection );
  6423. vec2 sampleUV = equirectUv( direction );
  6424. gl_FragColor = texture2D( tEquirect, sampleUV );
  6425. #include <tonemapping_fragment>
  6426. #include <colorspace_fragment>
  6427. }`,JAe=`uniform float scale;
  6428. attribute float lineDistance;
  6429. varying float vLineDistance;
  6430. #include <common>
  6431. #include <uv_pars_vertex>
  6432. #include <color_pars_vertex>
  6433. #include <fog_pars_vertex>
  6434. #include <morphtarget_pars_vertex>
  6435. #include <logdepthbuf_pars_vertex>
  6436. #include <clipping_planes_pars_vertex>
  6437. void main() {
  6438. vLineDistance = scale * lineDistance;
  6439. #include <uv_vertex>
  6440. #include <color_vertex>
  6441. #include <morphcolor_vertex>
  6442. #include <begin_vertex>
  6443. #include <morphtarget_vertex>
  6444. #include <project_vertex>
  6445. #include <logdepthbuf_vertex>
  6446. #include <clipping_planes_vertex>
  6447. #include <fog_vertex>
  6448. }`,eje=`uniform vec3 diffuse;
  6449. uniform float opacity;
  6450. uniform float dashSize;
  6451. uniform float totalSize;
  6452. varying float vLineDistance;
  6453. #include <common>
  6454. #include <color_pars_fragment>
  6455. #include <uv_pars_fragment>
  6456. #include <map_pars_fragment>
  6457. #include <fog_pars_fragment>
  6458. #include <logdepthbuf_pars_fragment>
  6459. #include <clipping_planes_pars_fragment>
  6460. void main() {
  6461. #include <clipping_planes_fragment>
  6462. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  6463. discard;
  6464. }
  6465. vec3 outgoingLight = vec3( 0.0 );
  6466. vec4 diffuseColor = vec4( diffuse, opacity );
  6467. #include <logdepthbuf_fragment>
  6468. #include <map_fragment>
  6469. #include <color_fragment>
  6470. outgoingLight = diffuseColor.rgb;
  6471. #include <opaque_fragment>
  6472. #include <tonemapping_fragment>
  6473. #include <colorspace_fragment>
  6474. #include <fog_fragment>
  6475. #include <premultiplied_alpha_fragment>
  6476. }`,tje=`#include <common>
  6477. #include <batching_pars_vertex>
  6478. #include <uv_pars_vertex>
  6479. #include <envmap_pars_vertex>
  6480. #include <color_pars_vertex>
  6481. #include <fog_pars_vertex>
  6482. #include <morphtarget_pars_vertex>
  6483. #include <skinning_pars_vertex>
  6484. #include <logdepthbuf_pars_vertex>
  6485. #include <clipping_planes_pars_vertex>
  6486. void main() {
  6487. #include <uv_vertex>
  6488. #include <color_vertex>
  6489. #include <morphcolor_vertex>
  6490. #include <batching_vertex>
  6491. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  6492. #include <beginnormal_vertex>
  6493. #include <morphnormal_vertex>
  6494. #include <skinbase_vertex>
  6495. #include <skinnormal_vertex>
  6496. #include <defaultnormal_vertex>
  6497. #endif
  6498. #include <begin_vertex>
  6499. #include <morphtarget_vertex>
  6500. #include <skinning_vertex>
  6501. #include <project_vertex>
  6502. #include <logdepthbuf_vertex>
  6503. #include <clipping_planes_vertex>
  6504. #include <worldpos_vertex>
  6505. #include <envmap_vertex>
  6506. #include <fog_vertex>
  6507. }`,nje=`uniform vec3 diffuse;
  6508. uniform float opacity;
  6509. #ifndef FLAT_SHADED
  6510. varying vec3 vNormal;
  6511. #endif
  6512. #include <common>
  6513. #include <dithering_pars_fragment>
  6514. #include <color_pars_fragment>
  6515. #include <uv_pars_fragment>
  6516. #include <map_pars_fragment>
  6517. #include <alphamap_pars_fragment>
  6518. #include <alphatest_pars_fragment>
  6519. #include <alphahash_pars_fragment>
  6520. #include <aomap_pars_fragment>
  6521. #include <lightmap_pars_fragment>
  6522. #include <envmap_common_pars_fragment>
  6523. #include <envmap_pars_fragment>
  6524. #include <fog_pars_fragment>
  6525. #include <specularmap_pars_fragment>
  6526. #include <logdepthbuf_pars_fragment>
  6527. #include <clipping_planes_pars_fragment>
  6528. void main() {
  6529. #include <clipping_planes_fragment>
  6530. vec4 diffuseColor = vec4( diffuse, opacity );
  6531. #include <logdepthbuf_fragment>
  6532. #include <map_fragment>
  6533. #include <color_fragment>
  6534. #include <alphamap_fragment>
  6535. #include <alphatest_fragment>
  6536. #include <alphahash_fragment>
  6537. #include <specularmap_fragment>
  6538. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6539. #ifdef USE_LIGHTMAP
  6540. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  6541. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  6542. #else
  6543. reflectedLight.indirectDiffuse += vec3( 1.0 );
  6544. #endif
  6545. #include <aomap_fragment>
  6546. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  6547. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  6548. #include <envmap_fragment>
  6549. #include <opaque_fragment>
  6550. #include <tonemapping_fragment>
  6551. #include <colorspace_fragment>
  6552. #include <fog_fragment>
  6553. #include <premultiplied_alpha_fragment>
  6554. #include <dithering_fragment>
  6555. }`,rje=`#define LAMBERT
  6556. varying vec3 vViewPosition;
  6557. #include <common>
  6558. #include <batching_pars_vertex>
  6559. #include <uv_pars_vertex>
  6560. #include <displacementmap_pars_vertex>
  6561. #include <envmap_pars_vertex>
  6562. #include <color_pars_vertex>
  6563. #include <fog_pars_vertex>
  6564. #include <normal_pars_vertex>
  6565. #include <morphtarget_pars_vertex>
  6566. #include <skinning_pars_vertex>
  6567. #include <shadowmap_pars_vertex>
  6568. #include <logdepthbuf_pars_vertex>
  6569. #include <clipping_planes_pars_vertex>
  6570. void main() {
  6571. #include <uv_vertex>
  6572. #include <color_vertex>
  6573. #include <morphcolor_vertex>
  6574. #include <batching_vertex>
  6575. #include <beginnormal_vertex>
  6576. #include <morphnormal_vertex>
  6577. #include <skinbase_vertex>
  6578. #include <skinnormal_vertex>
  6579. #include <defaultnormal_vertex>
  6580. #include <normal_vertex>
  6581. #include <begin_vertex>
  6582. #include <morphtarget_vertex>
  6583. #include <skinning_vertex>
  6584. #include <displacementmap_vertex>
  6585. #include <project_vertex>
  6586. #include <logdepthbuf_vertex>
  6587. #include <clipping_planes_vertex>
  6588. vViewPosition = - mvPosition.xyz;
  6589. #include <worldpos_vertex>
  6590. #include <envmap_vertex>
  6591. #include <shadowmap_vertex>
  6592. #include <fog_vertex>
  6593. }`,aje=`#define LAMBERT
  6594. uniform vec3 diffuse;
  6595. uniform vec3 emissive;
  6596. uniform float opacity;
  6597. #include <common>
  6598. #include <packing>
  6599. #include <dithering_pars_fragment>
  6600. #include <color_pars_fragment>
  6601. #include <uv_pars_fragment>
  6602. #include <map_pars_fragment>
  6603. #include <alphamap_pars_fragment>
  6604. #include <alphatest_pars_fragment>
  6605. #include <alphahash_pars_fragment>
  6606. #include <aomap_pars_fragment>
  6607. #include <lightmap_pars_fragment>
  6608. #include <emissivemap_pars_fragment>
  6609. #include <envmap_common_pars_fragment>
  6610. #include <envmap_pars_fragment>
  6611. #include <fog_pars_fragment>
  6612. #include <bsdfs>
  6613. #include <lights_pars_begin>
  6614. #include <normal_pars_fragment>
  6615. #include <lights_lambert_pars_fragment>
  6616. #include <shadowmap_pars_fragment>
  6617. #include <bumpmap_pars_fragment>
  6618. #include <normalmap_pars_fragment>
  6619. #include <specularmap_pars_fragment>
  6620. #include <logdepthbuf_pars_fragment>
  6621. #include <clipping_planes_pars_fragment>
  6622. void main() {
  6623. #include <clipping_planes_fragment>
  6624. vec4 diffuseColor = vec4( diffuse, opacity );
  6625. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6626. vec3 totalEmissiveRadiance = emissive;
  6627. #include <logdepthbuf_fragment>
  6628. #include <map_fragment>
  6629. #include <color_fragment>
  6630. #include <alphamap_fragment>
  6631. #include <alphatest_fragment>
  6632. #include <alphahash_fragment>
  6633. #include <specularmap_fragment>
  6634. #include <normal_fragment_begin>
  6635. #include <normal_fragment_maps>
  6636. #include <emissivemap_fragment>
  6637. #include <lights_lambert_fragment>
  6638. #include <lights_fragment_begin>
  6639. #include <lights_fragment_maps>
  6640. #include <lights_fragment_end>
  6641. #include <aomap_fragment>
  6642. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  6643. #include <envmap_fragment>
  6644. #include <opaque_fragment>
  6645. #include <tonemapping_fragment>
  6646. #include <colorspace_fragment>
  6647. #include <fog_fragment>
  6648. #include <premultiplied_alpha_fragment>
  6649. #include <dithering_fragment>
  6650. }`,ije=`#define MATCAP
  6651. varying vec3 vViewPosition;
  6652. #include <common>
  6653. #include <batching_pars_vertex>
  6654. #include <uv_pars_vertex>
  6655. #include <color_pars_vertex>
  6656. #include <displacementmap_pars_vertex>
  6657. #include <fog_pars_vertex>
  6658. #include <normal_pars_vertex>
  6659. #include <morphtarget_pars_vertex>
  6660. #include <skinning_pars_vertex>
  6661. #include <logdepthbuf_pars_vertex>
  6662. #include <clipping_planes_pars_vertex>
  6663. void main() {
  6664. #include <uv_vertex>
  6665. #include <color_vertex>
  6666. #include <morphcolor_vertex>
  6667. #include <batching_vertex>
  6668. #include <beginnormal_vertex>
  6669. #include <morphnormal_vertex>
  6670. #include <skinbase_vertex>
  6671. #include <skinnormal_vertex>
  6672. #include <defaultnormal_vertex>
  6673. #include <normal_vertex>
  6674. #include <begin_vertex>
  6675. #include <morphtarget_vertex>
  6676. #include <skinning_vertex>
  6677. #include <displacementmap_vertex>
  6678. #include <project_vertex>
  6679. #include <logdepthbuf_vertex>
  6680. #include <clipping_planes_vertex>
  6681. #include <fog_vertex>
  6682. vViewPosition = - mvPosition.xyz;
  6683. }`,sje=`#define MATCAP
  6684. uniform vec3 diffuse;
  6685. uniform float opacity;
  6686. uniform sampler2D matcap;
  6687. varying vec3 vViewPosition;
  6688. #include <common>
  6689. #include <dithering_pars_fragment>
  6690. #include <color_pars_fragment>
  6691. #include <uv_pars_fragment>
  6692. #include <map_pars_fragment>
  6693. #include <alphamap_pars_fragment>
  6694. #include <alphatest_pars_fragment>
  6695. #include <alphahash_pars_fragment>
  6696. #include <fog_pars_fragment>
  6697. #include <normal_pars_fragment>
  6698. #include <bumpmap_pars_fragment>
  6699. #include <normalmap_pars_fragment>
  6700. #include <logdepthbuf_pars_fragment>
  6701. #include <clipping_planes_pars_fragment>
  6702. void main() {
  6703. #include <clipping_planes_fragment>
  6704. vec4 diffuseColor = vec4( diffuse, opacity );
  6705. #include <logdepthbuf_fragment>
  6706. #include <map_fragment>
  6707. #include <color_fragment>
  6708. #include <alphamap_fragment>
  6709. #include <alphatest_fragment>
  6710. #include <alphahash_fragment>
  6711. #include <normal_fragment_begin>
  6712. #include <normal_fragment_maps>
  6713. vec3 viewDir = normalize( vViewPosition );
  6714. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  6715. vec3 y = cross( viewDir, x );
  6716. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  6717. #ifdef USE_MATCAP
  6718. vec4 matcapColor = texture2D( matcap, uv );
  6719. #else
  6720. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  6721. #endif
  6722. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  6723. #include <opaque_fragment>
  6724. #include <tonemapping_fragment>
  6725. #include <colorspace_fragment>
  6726. #include <fog_fragment>
  6727. #include <premultiplied_alpha_fragment>
  6728. #include <dithering_fragment>
  6729. }`,oje=`#define NORMAL
  6730. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6731. varying vec3 vViewPosition;
  6732. #endif
  6733. #include <common>
  6734. #include <batching_pars_vertex>
  6735. #include <uv_pars_vertex>
  6736. #include <displacementmap_pars_vertex>
  6737. #include <normal_pars_vertex>
  6738. #include <morphtarget_pars_vertex>
  6739. #include <skinning_pars_vertex>
  6740. #include <logdepthbuf_pars_vertex>
  6741. #include <clipping_planes_pars_vertex>
  6742. void main() {
  6743. #include <uv_vertex>
  6744. #include <batching_vertex>
  6745. #include <beginnormal_vertex>
  6746. #include <morphnormal_vertex>
  6747. #include <skinbase_vertex>
  6748. #include <skinnormal_vertex>
  6749. #include <defaultnormal_vertex>
  6750. #include <normal_vertex>
  6751. #include <begin_vertex>
  6752. #include <morphtarget_vertex>
  6753. #include <skinning_vertex>
  6754. #include <displacementmap_vertex>
  6755. #include <project_vertex>
  6756. #include <logdepthbuf_vertex>
  6757. #include <clipping_planes_vertex>
  6758. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6759. vViewPosition = - mvPosition.xyz;
  6760. #endif
  6761. }`,lje=`#define NORMAL
  6762. uniform float opacity;
  6763. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6764. varying vec3 vViewPosition;
  6765. #endif
  6766. #include <packing>
  6767. #include <uv_pars_fragment>
  6768. #include <normal_pars_fragment>
  6769. #include <bumpmap_pars_fragment>
  6770. #include <normalmap_pars_fragment>
  6771. #include <logdepthbuf_pars_fragment>
  6772. #include <clipping_planes_pars_fragment>
  6773. void main() {
  6774. #include <clipping_planes_fragment>
  6775. #include <logdepthbuf_fragment>
  6776. #include <normal_fragment_begin>
  6777. #include <normal_fragment_maps>
  6778. gl_FragColor = vec4( packNormalToRGB( normal ), opacity );
  6779. #ifdef OPAQUE
  6780. gl_FragColor.a = 1.0;
  6781. #endif
  6782. }`,cje=`#define PHONG
  6783. varying vec3 vViewPosition;
  6784. #include <common>
  6785. #include <batching_pars_vertex>
  6786. #include <uv_pars_vertex>
  6787. #include <displacementmap_pars_vertex>
  6788. #include <envmap_pars_vertex>
  6789. #include <color_pars_vertex>
  6790. #include <fog_pars_vertex>
  6791. #include <normal_pars_vertex>
  6792. #include <morphtarget_pars_vertex>
  6793. #include <skinning_pars_vertex>
  6794. #include <shadowmap_pars_vertex>
  6795. #include <logdepthbuf_pars_vertex>
  6796. #include <clipping_planes_pars_vertex>
  6797. void main() {
  6798. #include <uv_vertex>
  6799. #include <color_vertex>
  6800. #include <morphcolor_vertex>
  6801. #include <batching_vertex>
  6802. #include <beginnormal_vertex>
  6803. #include <morphnormal_vertex>
  6804. #include <skinbase_vertex>
  6805. #include <skinnormal_vertex>
  6806. #include <defaultnormal_vertex>
  6807. #include <normal_vertex>
  6808. #include <begin_vertex>
  6809. #include <morphtarget_vertex>
  6810. #include <skinning_vertex>
  6811. #include <displacementmap_vertex>
  6812. #include <project_vertex>
  6813. #include <logdepthbuf_vertex>
  6814. #include <clipping_planes_vertex>
  6815. vViewPosition = - mvPosition.xyz;
  6816. #include <worldpos_vertex>
  6817. #include <envmap_vertex>
  6818. #include <shadowmap_vertex>
  6819. #include <fog_vertex>
  6820. }`,dje=`#define PHONG
  6821. uniform vec3 diffuse;
  6822. uniform vec3 emissive;
  6823. uniform vec3 specular;
  6824. uniform float shininess;
  6825. uniform float opacity;
  6826. #include <common>
  6827. #include <packing>
  6828. #include <dithering_pars_fragment>
  6829. #include <color_pars_fragment>
  6830. #include <uv_pars_fragment>
  6831. #include <map_pars_fragment>
  6832. #include <alphamap_pars_fragment>
  6833. #include <alphatest_pars_fragment>
  6834. #include <alphahash_pars_fragment>
  6835. #include <aomap_pars_fragment>
  6836. #include <lightmap_pars_fragment>
  6837. #include <emissivemap_pars_fragment>
  6838. #include <envmap_common_pars_fragment>
  6839. #include <envmap_pars_fragment>
  6840. #include <fog_pars_fragment>
  6841. #include <bsdfs>
  6842. #include <lights_pars_begin>
  6843. #include <normal_pars_fragment>
  6844. #include <lights_phong_pars_fragment>
  6845. #include <shadowmap_pars_fragment>
  6846. #include <bumpmap_pars_fragment>
  6847. #include <normalmap_pars_fragment>
  6848. #include <specularmap_pars_fragment>
  6849. #include <logdepthbuf_pars_fragment>
  6850. #include <clipping_planes_pars_fragment>
  6851. void main() {
  6852. #include <clipping_planes_fragment>
  6853. vec4 diffuseColor = vec4( diffuse, opacity );
  6854. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6855. vec3 totalEmissiveRadiance = emissive;
  6856. #include <logdepthbuf_fragment>
  6857. #include <map_fragment>
  6858. #include <color_fragment>
  6859. #include <alphamap_fragment>
  6860. #include <alphatest_fragment>
  6861. #include <alphahash_fragment>
  6862. #include <specularmap_fragment>
  6863. #include <normal_fragment_begin>
  6864. #include <normal_fragment_maps>
  6865. #include <emissivemap_fragment>
  6866. #include <lights_phong_fragment>
  6867. #include <lights_fragment_begin>
  6868. #include <lights_fragment_maps>
  6869. #include <lights_fragment_end>
  6870. #include <aomap_fragment>
  6871. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  6872. #include <envmap_fragment>
  6873. #include <opaque_fragment>
  6874. #include <tonemapping_fragment>
  6875. #include <colorspace_fragment>
  6876. #include <fog_fragment>
  6877. #include <premultiplied_alpha_fragment>
  6878. #include <dithering_fragment>
  6879. }`,uje=`#define STANDARD
  6880. varying vec3 vViewPosition;
  6881. #ifdef USE_TRANSMISSION
  6882. varying vec3 vWorldPosition;
  6883. #endif
  6884. #include <common>
  6885. #include <batching_pars_vertex>
  6886. #include <uv_pars_vertex>
  6887. #include <displacementmap_pars_vertex>
  6888. #include <color_pars_vertex>
  6889. #include <fog_pars_vertex>
  6890. #include <normal_pars_vertex>
  6891. #include <morphtarget_pars_vertex>
  6892. #include <skinning_pars_vertex>
  6893. #include <shadowmap_pars_vertex>
  6894. #include <logdepthbuf_pars_vertex>
  6895. #include <clipping_planes_pars_vertex>
  6896. void main() {
  6897. #include <uv_vertex>
  6898. #include <color_vertex>
  6899. #include <morphcolor_vertex>
  6900. #include <batching_vertex>
  6901. #include <beginnormal_vertex>
  6902. #include <morphnormal_vertex>
  6903. #include <skinbase_vertex>
  6904. #include <skinnormal_vertex>
  6905. #include <defaultnormal_vertex>
  6906. #include <normal_vertex>
  6907. #include <begin_vertex>
  6908. #include <morphtarget_vertex>
  6909. #include <skinning_vertex>
  6910. #include <displacementmap_vertex>
  6911. #include <project_vertex>
  6912. #include <logdepthbuf_vertex>
  6913. #include <clipping_planes_vertex>
  6914. vViewPosition = - mvPosition.xyz;
  6915. #include <worldpos_vertex>
  6916. #include <shadowmap_vertex>
  6917. #include <fog_vertex>
  6918. #ifdef USE_TRANSMISSION
  6919. vWorldPosition = worldPosition.xyz;
  6920. #endif
  6921. }`,mje=`#define STANDARD
  6922. #ifdef PHYSICAL
  6923. #define IOR
  6924. #define USE_SPECULAR
  6925. #endif
  6926. uniform vec3 diffuse;
  6927. uniform vec3 emissive;
  6928. uniform float roughness;
  6929. uniform float metalness;
  6930. uniform float opacity;
  6931. #ifdef IOR
  6932. uniform float ior;
  6933. #endif
  6934. #ifdef USE_SPECULAR
  6935. uniform float specularIntensity;
  6936. uniform vec3 specularColor;
  6937. #ifdef USE_SPECULAR_COLORMAP
  6938. uniform sampler2D specularColorMap;
  6939. #endif
  6940. #ifdef USE_SPECULAR_INTENSITYMAP
  6941. uniform sampler2D specularIntensityMap;
  6942. #endif
  6943. #endif
  6944. #ifdef USE_CLEARCOAT
  6945. uniform float clearcoat;
  6946. uniform float clearcoatRoughness;
  6947. #endif
  6948. #ifdef USE_IRIDESCENCE
  6949. uniform float iridescence;
  6950. uniform float iridescenceIOR;
  6951. uniform float iridescenceThicknessMinimum;
  6952. uniform float iridescenceThicknessMaximum;
  6953. #endif
  6954. #ifdef USE_SHEEN
  6955. uniform vec3 sheenColor;
  6956. uniform float sheenRoughness;
  6957. #ifdef USE_SHEEN_COLORMAP
  6958. uniform sampler2D sheenColorMap;
  6959. #endif
  6960. #ifdef USE_SHEEN_ROUGHNESSMAP
  6961. uniform sampler2D sheenRoughnessMap;
  6962. #endif
  6963. #endif
  6964. #ifdef USE_ANISOTROPY
  6965. uniform vec2 anisotropyVector;
  6966. #ifdef USE_ANISOTROPYMAP
  6967. uniform sampler2D anisotropyMap;
  6968. #endif
  6969. #endif
  6970. varying vec3 vViewPosition;
  6971. #include <common>
  6972. #include <packing>
  6973. #include <dithering_pars_fragment>
  6974. #include <color_pars_fragment>
  6975. #include <uv_pars_fragment>
  6976. #include <map_pars_fragment>
  6977. #include <alphamap_pars_fragment>
  6978. #include <alphatest_pars_fragment>
  6979. #include <alphahash_pars_fragment>
  6980. #include <aomap_pars_fragment>
  6981. #include <lightmap_pars_fragment>
  6982. #include <emissivemap_pars_fragment>
  6983. #include <iridescence_fragment>
  6984. #include <cube_uv_reflection_fragment>
  6985. #include <envmap_common_pars_fragment>
  6986. #include <envmap_physical_pars_fragment>
  6987. #include <fog_pars_fragment>
  6988. #include <lights_pars_begin>
  6989. #include <normal_pars_fragment>
  6990. #include <lights_physical_pars_fragment>
  6991. #include <transmission_pars_fragment>
  6992. #include <shadowmap_pars_fragment>
  6993. #include <bumpmap_pars_fragment>
  6994. #include <normalmap_pars_fragment>
  6995. #include <clearcoat_pars_fragment>
  6996. #include <iridescence_pars_fragment>
  6997. #include <roughnessmap_pars_fragment>
  6998. #include <metalnessmap_pars_fragment>
  6999. #include <logdepthbuf_pars_fragment>
  7000. #include <clipping_planes_pars_fragment>
  7001. void main() {
  7002. #include <clipping_planes_fragment>
  7003. vec4 diffuseColor = vec4( diffuse, opacity );
  7004. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  7005. vec3 totalEmissiveRadiance = emissive;
  7006. #include <logdepthbuf_fragment>
  7007. #include <map_fragment>
  7008. #include <color_fragment>
  7009. #include <alphamap_fragment>
  7010. #include <alphatest_fragment>
  7011. #include <alphahash_fragment>
  7012. #include <roughnessmap_fragment>
  7013. #include <metalnessmap_fragment>
  7014. #include <normal_fragment_begin>
  7015. #include <normal_fragment_maps>
  7016. #include <clearcoat_normal_fragment_begin>
  7017. #include <clearcoat_normal_fragment_maps>
  7018. #include <emissivemap_fragment>
  7019. #include <lights_physical_fragment>
  7020. #include <lights_fragment_begin>
  7021. #include <lights_fragment_maps>
  7022. #include <lights_fragment_end>
  7023. #include <aomap_fragment>
  7024. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  7025. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  7026. #include <transmission_fragment>
  7027. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  7028. #ifdef USE_SHEEN
  7029. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  7030. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  7031. #endif
  7032. #ifdef USE_CLEARCOAT
  7033. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  7034. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  7035. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  7036. #endif
  7037. #include <opaque_fragment>
  7038. #include <tonemapping_fragment>
  7039. #include <colorspace_fragment>
  7040. #include <fog_fragment>
  7041. #include <premultiplied_alpha_fragment>
  7042. #include <dithering_fragment>
  7043. }`,pje=`#define TOON
  7044. varying vec3 vViewPosition;
  7045. #include <common>
  7046. #include <batching_pars_vertex>
  7047. #include <uv_pars_vertex>
  7048. #include <displacementmap_pars_vertex>
  7049. #include <color_pars_vertex>
  7050. #include <fog_pars_vertex>
  7051. #include <normal_pars_vertex>
  7052. #include <morphtarget_pars_vertex>
  7053. #include <skinning_pars_vertex>
  7054. #include <shadowmap_pars_vertex>
  7055. #include <logdepthbuf_pars_vertex>
  7056. #include <clipping_planes_pars_vertex>
  7057. void main() {
  7058. #include <uv_vertex>
  7059. #include <color_vertex>
  7060. #include <morphcolor_vertex>
  7061. #include <batching_vertex>
  7062. #include <beginnormal_vertex>
  7063. #include <morphnormal_vertex>
  7064. #include <skinbase_vertex>
  7065. #include <skinnormal_vertex>
  7066. #include <defaultnormal_vertex>
  7067. #include <normal_vertex>
  7068. #include <begin_vertex>
  7069. #include <morphtarget_vertex>
  7070. #include <skinning_vertex>
  7071. #include <displacementmap_vertex>
  7072. #include <project_vertex>
  7073. #include <logdepthbuf_vertex>
  7074. #include <clipping_planes_vertex>
  7075. vViewPosition = - mvPosition.xyz;
  7076. #include <worldpos_vertex>
  7077. #include <shadowmap_vertex>
  7078. #include <fog_vertex>
  7079. }`,hje=`#define TOON
  7080. uniform vec3 diffuse;
  7081. uniform vec3 emissive;
  7082. uniform float opacity;
  7083. #include <common>
  7084. #include <packing>
  7085. #include <dithering_pars_fragment>
  7086. #include <color_pars_fragment>
  7087. #include <uv_pars_fragment>
  7088. #include <map_pars_fragment>
  7089. #include <alphamap_pars_fragment>
  7090. #include <alphatest_pars_fragment>
  7091. #include <alphahash_pars_fragment>
  7092. #include <aomap_pars_fragment>
  7093. #include <lightmap_pars_fragment>
  7094. #include <emissivemap_pars_fragment>
  7095. #include <gradientmap_pars_fragment>
  7096. #include <fog_pars_fragment>
  7097. #include <bsdfs>
  7098. #include <lights_pars_begin>
  7099. #include <normal_pars_fragment>
  7100. #include <lights_toon_pars_fragment>
  7101. #include <shadowmap_pars_fragment>
  7102. #include <bumpmap_pars_fragment>
  7103. #include <normalmap_pars_fragment>
  7104. #include <logdepthbuf_pars_fragment>
  7105. #include <clipping_planes_pars_fragment>
  7106. void main() {
  7107. #include <clipping_planes_fragment>
  7108. vec4 diffuseColor = vec4( diffuse, opacity );
  7109. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  7110. vec3 totalEmissiveRadiance = emissive;
  7111. #include <logdepthbuf_fragment>
  7112. #include <map_fragment>
  7113. #include <color_fragment>
  7114. #include <alphamap_fragment>
  7115. #include <alphatest_fragment>
  7116. #include <alphahash_fragment>
  7117. #include <normal_fragment_begin>
  7118. #include <normal_fragment_maps>
  7119. #include <emissivemap_fragment>
  7120. #include <lights_toon_fragment>
  7121. #include <lights_fragment_begin>
  7122. #include <lights_fragment_maps>
  7123. #include <lights_fragment_end>
  7124. #include <aomap_fragment>
  7125. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  7126. #include <opaque_fragment>
  7127. #include <tonemapping_fragment>
  7128. #include <colorspace_fragment>
  7129. #include <fog_fragment>
  7130. #include <premultiplied_alpha_fragment>
  7131. #include <dithering_fragment>
  7132. }`,fje=`uniform float size;
  7133. uniform float scale;
  7134. #include <common>
  7135. #include <color_pars_vertex>
  7136. #include <fog_pars_vertex>
  7137. #include <morphtarget_pars_vertex>
  7138. #include <logdepthbuf_pars_vertex>
  7139. #include <clipping_planes_pars_vertex>
  7140. #ifdef USE_POINTS_UV
  7141. varying vec2 vUv;
  7142. uniform mat3 uvTransform;
  7143. #endif
  7144. void main() {
  7145. #ifdef USE_POINTS_UV
  7146. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  7147. #endif
  7148. #include <color_vertex>
  7149. #include <morphcolor_vertex>
  7150. #include <begin_vertex>
  7151. #include <morphtarget_vertex>
  7152. #include <project_vertex>
  7153. gl_PointSize = size;
  7154. #ifdef USE_SIZEATTENUATION
  7155. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7156. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  7157. #endif
  7158. #include <logdepthbuf_vertex>
  7159. #include <clipping_planes_vertex>
  7160. #include <worldpos_vertex>
  7161. #include <fog_vertex>
  7162. }`,gje=`uniform vec3 diffuse;
  7163. uniform float opacity;
  7164. #include <common>
  7165. #include <color_pars_fragment>
  7166. #include <map_particle_pars_fragment>
  7167. #include <alphatest_pars_fragment>
  7168. #include <alphahash_pars_fragment>
  7169. #include <fog_pars_fragment>
  7170. #include <logdepthbuf_pars_fragment>
  7171. #include <clipping_planes_pars_fragment>
  7172. void main() {
  7173. #include <clipping_planes_fragment>
  7174. vec3 outgoingLight = vec3( 0.0 );
  7175. vec4 diffuseColor = vec4( diffuse, opacity );
  7176. #include <logdepthbuf_fragment>
  7177. #include <map_particle_fragment>
  7178. #include <color_fragment>
  7179. #include <alphatest_fragment>
  7180. #include <alphahash_fragment>
  7181. outgoingLight = diffuseColor.rgb;
  7182. #include <opaque_fragment>
  7183. #include <tonemapping_fragment>
  7184. #include <colorspace_fragment>
  7185. #include <fog_fragment>
  7186. #include <premultiplied_alpha_fragment>
  7187. }`,bje=`#include <common>
  7188. #include <batching_pars_vertex>
  7189. #include <fog_pars_vertex>
  7190. #include <morphtarget_pars_vertex>
  7191. #include <skinning_pars_vertex>
  7192. #include <logdepthbuf_pars_vertex>
  7193. #include <shadowmap_pars_vertex>
  7194. void main() {
  7195. #include <batching_vertex>
  7196. #include <beginnormal_vertex>
  7197. #include <morphnormal_vertex>
  7198. #include <skinbase_vertex>
  7199. #include <skinnormal_vertex>
  7200. #include <defaultnormal_vertex>
  7201. #include <begin_vertex>
  7202. #include <morphtarget_vertex>
  7203. #include <skinning_vertex>
  7204. #include <project_vertex>
  7205. #include <logdepthbuf_vertex>
  7206. #include <worldpos_vertex>
  7207. #include <shadowmap_vertex>
  7208. #include <fog_vertex>
  7209. }`,xje=`uniform vec3 color;
  7210. uniform float opacity;
  7211. #include <common>
  7212. #include <packing>
  7213. #include <fog_pars_fragment>
  7214. #include <bsdfs>
  7215. #include <lights_pars_begin>
  7216. #include <logdepthbuf_pars_fragment>
  7217. #include <shadowmap_pars_fragment>
  7218. #include <shadowmask_pars_fragment>
  7219. void main() {
  7220. #include <logdepthbuf_fragment>
  7221. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  7222. #include <tonemapping_fragment>
  7223. #include <colorspace_fragment>
  7224. #include <fog_fragment>
  7225. }`,yje=`uniform float rotation;
  7226. uniform vec2 center;
  7227. #include <common>
  7228. #include <uv_pars_vertex>
  7229. #include <fog_pars_vertex>
  7230. #include <logdepthbuf_pars_vertex>
  7231. #include <clipping_planes_pars_vertex>
  7232. void main() {
  7233. #include <uv_vertex>
  7234. vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
  7235. vec2 scale;
  7236. scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
  7237. scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
  7238. #ifndef USE_SIZEATTENUATION
  7239. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7240. if ( isPerspective ) scale *= - mvPosition.z;
  7241. #endif
  7242. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  7243. vec2 rotatedPosition;
  7244. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  7245. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  7246. mvPosition.xy += rotatedPosition;
  7247. gl_Position = projectionMatrix * mvPosition;
  7248. #include <logdepthbuf_vertex>
  7249. #include <clipping_planes_vertex>
  7250. #include <fog_vertex>
  7251. }`,vje=`uniform vec3 diffuse;
  7252. uniform float opacity;
  7253. #include <common>
  7254. #include <uv_pars_fragment>
  7255. #include <map_pars_fragment>
  7256. #include <alphamap_pars_fragment>
  7257. #include <alphatest_pars_fragment>
  7258. #include <alphahash_pars_fragment>
  7259. #include <fog_pars_fragment>
  7260. #include <logdepthbuf_pars_fragment>
  7261. #include <clipping_planes_pars_fragment>
  7262. void main() {
  7263. #include <clipping_planes_fragment>
  7264. vec3 outgoingLight = vec3( 0.0 );
  7265. vec4 diffuseColor = vec4( diffuse, opacity );
  7266. #include <logdepthbuf_fragment>
  7267. #include <map_fragment>
  7268. #include <alphamap_fragment>
  7269. #include <alphatest_fragment>
  7270. #include <alphahash_fragment>
  7271. outgoingLight = diffuseColor.rgb;
  7272. #include <opaque_fragment>
  7273. #include <tonemapping_fragment>
  7274. #include <colorspace_fragment>
  7275. #include <fog_fragment>
  7276. }`,ar={alphahash_fragment:HPe,alphahash_pars_fragment:qPe,alphamap_fragment:$Pe,alphamap_pars_fragment:VPe,alphatest_fragment:GPe,alphatest_pars_fragment:WPe,aomap_fragment:KPe,aomap_pars_fragment:QPe,batching_pars_vertex:YPe,batching_vertex:XPe,begin_vertex:ZPe,beginnormal_vertex:JPe,bsdfs:eTe,iridescence_fragment:tTe,bumpmap_pars_fragment:nTe,clipping_planes_fragment:rTe,clipping_planes_pars_fragment:aTe,clipping_planes_pars_vertex:iTe,clipping_planes_vertex:sTe,color_fragment:oTe,color_pars_fragment:lTe,color_pars_vertex:cTe,color_vertex:dTe,common:uTe,cube_uv_reflection_fragment:mTe,defaultnormal_vertex:pTe,displacementmap_pars_vertex:hTe,displacementmap_vertex:fTe,emissivemap_fragment:gTe,emissivemap_pars_fragment:bTe,colorspace_fragment:xTe,colorspace_pars_fragment:yTe,envmap_fragment:vTe,envmap_common_pars_fragment:wTe,envmap_pars_fragment:STe,envmap_pars_vertex:_Te,envmap_physical_pars_fragment:LTe,envmap_vertex:kTe,fog_vertex:NTe,fog_pars_vertex:CTe,fog_fragment:PTe,fog_pars_fragment:TTe,gradientmap_pars_fragment:ATe,lightmap_fragment:jTe,lightmap_pars_fragment:MTe,lights_lambert_fragment:ETe,lights_lambert_pars_fragment:DTe,lights_pars_begin:FTe,lights_toon_fragment:RTe,lights_toon_pars_fragment:ITe,lights_phong_fragment:OTe,lights_phong_pars_fragment:zTe,lights_physical_fragment:UTe,lights_physical_pars_fragment:BTe,lights_fragment_begin:HTe,lights_fragment_maps:qTe,lights_fragment_end:$Te,logdepthbuf_fragment:VTe,logdepthbuf_pars_fragment:GTe,logdepthbuf_pars_vertex:WTe,logdepthbuf_vertex:KTe,map_fragment:QTe,map_pars_fragment:YTe,map_particle_fragment:XTe,map_particle_pars_fragment:ZTe,metalnessmap_fragment:JTe,metalnessmap_pars_fragment:eAe,morphcolor_vertex:tAe,morphnormal_vertex:nAe,morphtarget_pars_vertex:rAe,morphtarget_vertex:aAe,normal_fragment_begin:iAe,normal_fragment_maps:sAe,normal_pars_fragment:oAe,normal_pars_vertex:lAe,normal_vertex:cAe,normalmap_pars_fragment:dAe,clearcoat_normal_fragment_begin:uAe,clearcoat_normal_fragment_maps:mAe,clearcoat_pars_fragment:pAe,iridescence_pars_fragment:hAe,opaque_fragment:fAe,packing:gAe,premultiplied_alpha_fragment:bAe,project_vertex:xAe,dithering_fragment:yAe,dithering_pars_fragment:vAe,roughnessmap_fragment:wAe,roughnessmap_pars_fragment:SAe,shadowmap_pars_fragment:_Ae,shadowmap_pars_vertex:kAe,shadowmap_vertex:NAe,shadowmask_pars_fragment:CAe,skinbase_vertex:PAe,skinning_pars_vertex:TAe,skinning_vertex:AAe,skinnormal_vertex:jAe,specularmap_fragment:MAe,specularmap_pars_fragment:EAe,tonemapping_fragment:DAe,tonemapping_pars_fragment:FAe,transmission_fragment:LAe,transmission_pars_fragment:RAe,uv_pars_fragment:IAe,uv_pars_vertex:OAe,uv_vertex:zAe,worldpos_vertex:UAe,background_vert:BAe,background_frag:HAe,backgroundCube_vert:qAe,backgroundCube_frag:$Ae,cube_vert:VAe,cube_frag:GAe,depth_vert:WAe,depth_frag:KAe,distanceRGBA_vert:QAe,distanceRGBA_frag:YAe,equirect_vert:XAe,equirect_frag:ZAe,linedashed_vert:JAe,linedashed_frag:eje,meshbasic_vert:tje,meshbasic_frag:nje,meshlambert_vert:rje,meshlambert_frag:aje,meshmatcap_vert:ije,meshmatcap_frag:sje,meshnormal_vert:oje,meshnormal_frag:lje,meshphong_vert:cje,meshphong_frag:dje,meshphysical_vert:uje,meshphysical_frag:mje,meshtoon_vert:pje,meshtoon_frag:hje,points_vert:fje,points_frag:gje,shadow_vert:bje,shadow_frag:xje,sprite_vert:yje,sprite_frag:vje},sn={common:{diffuse:{value:new On(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new pr},alphaMap:{value:null},alphaMapTransform:{value:new pr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new pr}},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 pr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new pr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new pr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new pr},normalScale:{value:new Wn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new pr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new pr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new pr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new pr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new On(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 On(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new pr},alphaTest:{value:0},uvTransform:{value:new pr}},sprite:{diffuse:{value:new On(16777215)},opacity:{value:1},center:{value:new Wn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new pr},alphaMap:{value:null},alphaMapTransform:{value:new pr},alphaTest:{value:0}}},qo={basic:{uniforms:go([sn.common,sn.specularmap,sn.envmap,sn.aomap,sn.lightmap,sn.fog]),vertexShader:ar.meshbasic_vert,fragmentShader:ar.meshbasic_frag},lambert:{uniforms:go([sn.common,sn.specularmap,sn.envmap,sn.aomap,sn.lightmap,sn.emissivemap,sn.bumpmap,sn.normalmap,sn.displacementmap,sn.fog,sn.lights,{emissive:{value:new On(0)}}]),vertexShader:ar.meshlambert_vert,fragmentShader:ar.meshlambert_frag},phong:{uniforms:go([sn.common,sn.specularmap,sn.envmap,sn.aomap,sn.lightmap,sn.emissivemap,sn.bumpmap,sn.normalmap,sn.displacementmap,sn.fog,sn.lights,{emissive:{value:new On(0)},specular:{value:new On(1118481)},shininess:{value:30}}]),vertexShader:ar.meshphong_vert,fragmentShader:ar.meshphong_frag},standard:{uniforms:go([sn.common,sn.envmap,sn.aomap,sn.lightmap,sn.emissivemap,sn.bumpmap,sn.normalmap,sn.displacementmap,sn.roughnessmap,sn.metalnessmap,sn.fog,sn.lights,{emissive:{value:new On(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ar.meshphysical_vert,fragmentShader:ar.meshphysical_frag},toon:{uniforms:go([sn.common,sn.aomap,sn.lightmap,sn.emissivemap,sn.bumpmap,sn.normalmap,sn.displacementmap,sn.gradientmap,sn.fog,sn.lights,{emissive:{value:new On(0)}}]),vertexShader:ar.meshtoon_vert,fragmentShader:ar.meshtoon_frag},matcap:{uniforms:go([sn.common,sn.bumpmap,sn.normalmap,sn.displacementmap,sn.fog,{matcap:{value:null}}]),vertexShader:ar.meshmatcap_vert,fragmentShader:ar.meshmatcap_frag},points:{uniforms:go([sn.points,sn.fog]),vertexShader:ar.points_vert,fragmentShader:ar.points_frag},dashed:{uniforms:go([sn.common,sn.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ar.linedashed_vert,fragmentShader:ar.linedashed_frag},depth:{uniforms:go([sn.common,sn.displacementmap]),vertexShader:ar.depth_vert,fragmentShader:ar.depth_frag},normal:{uniforms:go([sn.common,sn.bumpmap,sn.normalmap,sn.displacementmap,{opacity:{value:1}}]),vertexShader:ar.meshnormal_vert,fragmentShader:ar.meshnormal_frag},sprite:{uniforms:go([sn.sprite,sn.fog]),vertexShader:ar.sprite_vert,fragmentShader:ar.sprite_frag},background:{uniforms:{uvTransform:{value:new pr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ar.background_vert,fragmentShader:ar.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:ar.backgroundCube_vert,fragmentShader:ar.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ar.cube_vert,fragmentShader:ar.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ar.equirect_vert,fragmentShader:ar.equirect_frag},distanceRGBA:{uniforms:go([sn.common,sn.displacementmap,{referencePosition:{value:new yt},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ar.distanceRGBA_vert,fragmentShader:ar.distanceRGBA_frag},shadow:{uniforms:go([sn.lights,sn.fog,{color:{value:new On(0)},opacity:{value:1}}]),vertexShader:ar.shadow_vert,fragmentShader:ar.shadow_frag}};qo.physical={uniforms:go([qo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new pr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new pr},clearcoatNormalScale:{value:new Wn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new pr},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new pr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new pr},sheen:{value:0},sheenColor:{value:new On(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new pr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new pr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new pr},transmissionSamplerSize:{value:new Wn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new pr},attenuationDistance:{value:0},attenuationColor:{value:new On(0)},specularColor:{value:new On(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new pr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new pr},anisotropyVector:{value:new Wn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new pr}}]),vertexShader:ar.meshphysical_vert,fragmentShader:ar.meshphysical_frag};const x1={r:0,b:0,g:0};function wje(t,e,n,a,i,s,o){const l=new On(0);let c=s===!0?0:1,d,u,m=null,p=0,f=null;function g(b,x){let S=!1,k=x.isScene===!0?x.background:null;k&&k.isTexture&&(k=(x.backgroundBlurriness>0?n:e).get(k)),k===null?w(l,c):k&&k.isColor&&(w(k,1),S=!0);const C=t.xr.getEnvironmentBlendMode();C==="additive"?a.buffers.color.setClear(0,0,0,1,o):C==="alpha-blend"&&a.buffers.color.setClear(0,0,0,0,o),(t.autoClear||S)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),k&&(k.isCubeTexture||k.mapping===LT)?(u===void 0&&(u=new cd(new US(1,1,1),new Yh({name:"BackgroundCubeMaterial",uniforms:Py(qo.backgroundCube.uniforms),vertexShader:qo.backgroundCube.vertexShader,fragmentShader:qo.backgroundCube.fragmentShader,side:Ko,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(P,T,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),u.material.uniforms.envMap.value=k,u.material.uniforms.flipEnvMap.value=k.isCubeTexture&&k.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,u.material.toneMapped=sa.getTransfer(k.colorSpace)!==Ta,(m!==k||p!==k.version||f!==t.toneMapping)&&(u.material.needsUpdate=!0,m=k,p=k.version,f=t.toneMapping),u.layers.enableAll(),b.unshift(u,u.geometry,u.material,0,0,null)):k&&k.isTexture&&(d===void 0&&(d=new cd(new t4(2,2),new Yh({name:"BackgroundMaterial",uniforms:Py(qo.background.uniforms),vertexShader:qo.background.vertexShader,fragmentShader:qo.background.fragmentShader,side:Qh,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=k,d.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,d.material.toneMapped=sa.getTransfer(k.colorSpace)!==Ta,k.matrixAutoUpdate===!0&&k.updateMatrix(),d.material.uniforms.uvTransform.value.copy(k.matrix),(m!==k||p!==k.version||f!==t.toneMapping)&&(d.material.needsUpdate=!0,m=k,p=k.version,f=t.toneMapping),d.layers.enableAll(),b.unshift(d,d.geometry,d.material,0,0,null))}function w(b,x){b.getRGB(x1,wee(t)),a.buffers.color.setClear(x1.r,x1.g,x1.b,x,o)}return{getClearColor:function(){return l},setClearColor:function(b,x=1){l.set(b),c=x,w(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(b){c=b,w(l,c)},render:g}}function Sje(t,e,n,a){const i=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=a.isWebGL2?null:e.get("OES_vertex_array_object"),o=a.isWebGL2||s!==null,l={},c=b(null);let d=c,u=!1;function m(L,Z,ne,Y,ce){let ue=!1;if(o){const oe=w(Y,ne,Z);d!==oe&&(d=oe,f(d.object)),ue=x(L,Y,ne,ce),ue&&S(L,Y,ne,ce)}else{const oe=Z.wireframe===!0;(d.geometry!==Y.id||d.program!==ne.id||d.wireframe!==oe)&&(d.geometry=Y.id,d.program=ne.id,d.wireframe=oe,ue=!0)}ce!==null&&n.update(ce,t.ELEMENT_ARRAY_BUFFER),(ue||u)&&(u=!1,F(L,Z,ne,Y),ce!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(ce).buffer))}function p(){return a.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function f(L){return a.isWebGL2?t.bindVertexArray(L):s.bindVertexArrayOES(L)}function g(L){return a.isWebGL2?t.deleteVertexArray(L):s.deleteVertexArrayOES(L)}function w(L,Z,ne){const Y=ne.wireframe===!0;let ce=l[L.id];ce===void 0&&(ce={},l[L.id]=ce);let ue=ce[Z.id];ue===void 0&&(ue={},ce[Z.id]=ue);let oe=ue[Y];return oe===void 0&&(oe=b(p()),ue[Y]=oe),oe}function b(L){const Z=[],ne=[],Y=[];for(let ce=0;ce<i;ce++)Z[ce]=0,ne[ce]=0,Y[ce]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:Z,enabledAttributes:ne,attributeDivisors:Y,object:L,attributes:{},index:null}}function x(L,Z,ne,Y){const ce=d.attributes,ue=Z.attributes;let oe=0;const Q=ne.getAttributes();for(const le in Q)if(Q[le].location>=0){const he=ce[le];let we=ue[le];if(we===void 0&&(le==="instanceMatrix"&&L.instanceMatrix&&(we=L.instanceMatrix),le==="instanceColor"&&L.instanceColor&&(we=L.instanceColor)),he===void 0||he.attribute!==we||we&&he.data!==we.data)return!0;oe++}return d.attributesNum!==oe||d.index!==Y}function S(L,Z,ne,Y){const ce={},ue=Z.attributes;let oe=0;const Q=ne.getAttributes();for(const le in Q)if(Q[le].location>=0){let he=ue[le];he===void 0&&(le==="instanceMatrix"&&L.instanceMatrix&&(he=L.instanceMatrix),le==="instanceColor"&&L.instanceColor&&(he=L.instanceColor));const we={};we.attribute=he,he&&he.data&&(we.data=he.data),ce[le]=we,oe++}d.attributes=ce,d.attributesNum=oe,d.index=Y}function k(){const L=d.newAttributes;for(let Z=0,ne=L.length;Z<ne;Z++)L[Z]=0}function C(L){P(L,0)}function P(L,Z){const ne=d.newAttributes,Y=d.enabledAttributes,ce=d.attributeDivisors;ne[L]=1,Y[L]===0&&(t.enableVertexAttribArray(L),Y[L]=1),ce[L]!==Z&&((a.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[a.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](L,Z),ce[L]=Z)}function T(){const L=d.newAttributes,Z=d.enabledAttributes;for(let ne=0,Y=Z.length;ne<Y;ne++)Z[ne]!==L[ne]&&(t.disableVertexAttribArray(ne),Z[ne]=0)}function A(L,Z,ne,Y,ce,ue,oe){oe===!0?t.vertexAttribIPointer(L,Z,ne,ce,ue):t.vertexAttribPointer(L,Z,ne,Y,ce,ue)}function F(L,Z,ne,Y){if(a.isWebGL2===!1&&(L.isInstancedMesh||Y.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;k();const ce=Y.attributes,ue=ne.getAttributes(),oe=Z.defaultAttributeValues;for(const Q in ue){const le=ue[Q];if(le.location>=0){let pe=ce[Q];if(pe===void 0&&(Q==="instanceMatrix"&&L.instanceMatrix&&(pe=L.instanceMatrix),Q==="instanceColor"&&L.instanceColor&&(pe=L.instanceColor)),pe!==void 0){const he=pe.normalized,we=pe.itemSize,$=n.get(pe);if($===void 0)continue;const J=$.buffer,j=$.type,E=$.bytesPerElement,B=a.isWebGL2===!0&&(j===t.INT||j===t.UNSIGNED_INT||pe.gpuType===tee);if(pe.isInterleavedBufferAttribute){const W=pe.data,O=W.stride,ie=pe.offset;if(W.isInstancedInterleavedBuffer){for(let U=0;U<le.locationSize;U++)P(le.location+U,W.meshPerAttribute);L.isInstancedMesh!==!0&&Y._maxInstanceCount===void 0&&(Y._maxInstanceCount=W.meshPerAttribute*W.count)}else for(let U=0;U<le.locationSize;U++)C(le.location+U);t.bindBuffer(t.ARRAY_BUFFER,J);for(let U=0;U<le.locationSize;U++)A(le.location+U,we/le.locationSize,j,he,O*E,(ie+we/le.locationSize*U)*E,B)}else{if(pe.isInstancedBufferAttribute){for(let W=0;W<le.locationSize;W++)P(le.location+W,pe.meshPerAttribute);L.isInstancedMesh!==!0&&Y._maxInstanceCount===void 0&&(Y._maxInstanceCount=pe.meshPerAttribute*pe.count)}else for(let W=0;W<le.locationSize;W++)C(le.location+W);t.bindBuffer(t.ARRAY_BUFFER,J);for(let W=0;W<le.locationSize;W++)A(le.location+W,we/le.locationSize,j,he,we*E,we/le.locationSize*W*E,B)}}else if(oe!==void 0){const he=oe[Q];if(he!==void 0)switch(he.length){case 2:t.vertexAttrib2fv(le.location,he);break;case 3:t.vertexAttrib3fv(le.location,he);break;case 4:t.vertexAttrib4fv(le.location,he);break;default:t.vertexAttrib1fv(le.location,he)}}}}T()}function _(){I();for(const L in l){const Z=l[L];for(const ne in Z){const Y=Z[ne];for(const ce in Y)g(Y[ce].object),delete Y[ce];delete Z[ne]}delete l[L]}}function M(L){if(l[L.id]===void 0)return;const Z=l[L.id];for(const ne in Z){const Y=Z[ne];for(const ce in Y)g(Y[ce].object),delete Y[ce];delete Z[ne]}delete l[L.id]}function H(L){for(const Z in l){const ne=l[Z];if(ne[L.id]===void 0)continue;const Y=ne[L.id];for(const ce in Y)g(Y[ce].object),delete Y[ce];delete ne[L.id]}}function I(){z(),u=!0,d!==c&&(d=c,f(d.object))}function z(){c.geometry=null,c.program=null,c.wireframe=!1}return{setup:m,reset:I,resetDefaultState:z,dispose:_,releaseStatesOfGeometry:M,releaseStatesOfProgram:H,initAttributes:k,enableAttribute:C,disableUnusedAttributes:T}}function _je(t,e,n,a){const i=a.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,g;if(i)f=t,g="drawArraysInstanced";else if(f=e.get("ANGLE_instanced_arrays"),g="drawArraysInstancedANGLE",f===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}f[g](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 g=0;g<p;g++)this.render(u[g],m[g]);else{f.multiDrawArraysWEBGL(s,u,0,m,0,p);let g=0;for(let w=0;w<p;w++)g+=m[w];n.update(g,s,1)}}this.setMode=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=d}function kje(t,e,n){let a;function i(){if(a!==void 0)return a;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");a=t.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else a=0;return a}function s(A){if(A==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="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),g=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),w=t.getParameter(t.MAX_VERTEX_ATTRIBS),b=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),x=t.getParameter(t.MAX_VARYING_VECTORS),S=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),k=p>0,C=o||e.has("OES_texture_float"),P=k&&C,T=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:g,maxAttributes:w,maxVertexUniforms:b,maxVaryings:x,maxFragmentUniforms:S,vertexTextures:k,floatFragmentTextures:C,floatVertexTextures:P,maxSamples:T}}function Nje(t){const e=this;let n=null,a=0,i=!1,s=!1;const o=new ah,l=new pr,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||a!==0||i;return i=p,a=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 g=m.clippingPlanes,w=m.clipIntersection,b=m.clipShadows,x=t.get(m);if(!i||g===null||g.length===0||s&&!b)s?u(null):d();else{const S=s?0:a,k=S*4;let C=x.clippingState||null;c.value=C,C=u(g,p,k,f);for(let P=0;P!==k;++P)C[P]=n[P];x.clippingState=C,this.numIntersection=w?this.numPlanes:0,this.numPlanes+=S}};function d(){c.value!==n&&(c.value=n,c.needsUpdate=a>0),e.numPlanes=a,e.numIntersection=0}function u(m,p,f,g){const w=m!==null?m.length:0;let b=null;if(w!==0){if(b=c.value,g!==!0||b===null){const x=f+w*4,S=p.matrixWorldInverse;l.getNormalMatrix(S),(b===null||b.length<x)&&(b=new Float32Array(x));for(let k=0,C=f;k!==w;++k,C+=4)o.copy(m[k]).applyMatrix4(S,l),o.normal.toArray(b,C),b[C+3]=o.constant}c.value=b,c.needsUpdate=!0}return e.numPlanes=w,e.numIntersection=0,b}}function Cje(t){let e=new WeakMap;function n(o,l){return l===QL?o.mapping=ky:l===YL&&(o.mapping=Ny),o}function a(o){if(o&&o.isTexture){const l=o.mapping;if(l===QL||l===YL)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 OPe(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:a,dispose:s}}class Pje extends See{constructor(e=-1,n=1,a=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=a,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,a,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=a,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),a=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=a-e,o=a+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 Qx=4,I$=[.125,.215,.35,.446,.526,.582],tg=20,h2=new Pje,O$=new On;let f2=null,g2=0,b2=0;const Kf=(1+Math.sqrt(5))/2,Px=1/Kf,z$=[new yt(1,1,1),new yt(-1,1,1),new yt(1,1,-1),new yt(-1,1,-1),new yt(0,Kf,Px),new yt(0,Kf,-Px),new yt(Px,0,Kf),new yt(-Px,0,Kf),new yt(Kf,Px,0),new yt(-Kf,Px,0)];class U${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,a=.1,i=100){f2=this._renderer.getRenderTarget(),g2=this._renderer.getActiveCubeFace(),b2=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,a,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=q$(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=H$(),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(f2,g2,b2),e.scissorTest=!1,y1(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===ky||e.mapping===Ny?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),f2=this._renderer.getRenderTarget(),g2=this._renderer.getActiveCubeFace(),b2=this._renderer.getActiveMipmapLevel();const a=n||this._allocateTargets();return this._textureToCubeUV(e,a),this._applyPMREM(a),this._cleanup(a),a}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,a={magFilter:ic,minFilter:ic,generateMipmaps:!1,type:Hw,format:sc,colorSpace:Qm,depthBuffer:!1},i=B$(e,n,a);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=B$(e,n,a);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=Tje(s)),this._blurMaterial=Aje(s,e,n)}return i}_compileMaterial(e){const n=new cd(this._lodPlanes[0],e);this._renderer.compile(n,h2)}_sceneToCubeUV(e,n,a,i){const l=new gl(90,1,n,a),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(O$),u.toneMapping=Rh,u.autoClear=!1;const f=new xee({name:"PMREM.Background",side:Ko,depthWrite:!1,depthTest:!1}),g=new cd(new US,f);let w=!1;const b=e.background;b?b.isColor&&(f.color.copy(b),e.background=null,w=!0):(f.color.copy(O$),w=!0);for(let x=0;x<6;x++){const S=x%3;S===0?(l.up.set(0,c[x],0),l.lookAt(d[x],0,0)):S===1?(l.up.set(0,0,c[x]),l.lookAt(0,d[x],0)):(l.up.set(0,c[x],0),l.lookAt(0,0,d[x]));const k=this._cubeSize;y1(i,S*k,x>2?k:0,k,k),u.setRenderTarget(i),w&&u.render(g,l),u.render(e,l)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=p,u.autoClear=m,e.background=b}_textureToCubeUV(e,n){const a=this._renderer,i=e.mapping===ky||e.mapping===Ny;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=q$()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=H$());const s=i?this._cubemapMaterial:this._equirectMaterial,o=new cd(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;y1(n,0,0,3*c,2*c),a.setRenderTarget(n),a.render(o,h2)}_applyPMREM(e){const n=this._renderer,a=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=z$[(i-1)%z$.length];this._blur(e,i-1,i,s,o)}n.autoClear=a}_blur(e,n,a,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,a,i,"latitudinal",s),this._halfBlur(o,e,a,a,i,"longitudinal",s)}_halfBlur(e,n,a,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 cd(this._lodPlanes[i],d),p=d.uniforms,f=this._sizeLods[a]-1,g=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*tg-1),w=s/g,b=isFinite(s)?1+Math.floor(u*w):tg;b>tg&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${tg}`);const x=[];let S=0;for(let A=0;A<tg;++A){const F=A/w,_=Math.exp(-F*F/2);x.push(_),A===0?S+=_:A<b&&(S+=2*_)}for(let A=0;A<x.length;A++)x[A]=x[A]/S;p.envMap.value=e.texture,p.samples.value=b,p.weights.value=x,p.latitudinal.value=o==="latitudinal",l&&(p.poleAxis.value=l);const{_lodMax:k}=this;p.dTheta.value=g,p.mipInt.value=k-a;const C=this._sizeLods[i],P=3*C*(i>k-Qx?i-k+Qx:0),T=4*(this._cubeSize-C);y1(n,P,T,3*C,2*C),c.setRenderTarget(n),c.render(m,h2)}}function Tje(t){const e=[],n=[],a=[];let i=t;const s=t-Qx+1+I$.length;for(let o=0;o<s;o++){const l=Math.pow(2,i);n.push(l);let c=1/l;o>t-Qx?c=I$[o-t+Qx-1]:o===0&&(c=0),a.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,g=6,w=3,b=2,x=1,S=new Float32Array(w*g*f),k=new Float32Array(b*g*f),C=new Float32Array(x*g*f);for(let T=0;T<f;T++){const A=T%3*2/3-1,F=T>2?0:-1,_=[A,F,0,A+2/3,F,0,A+2/3,F+1,0,A,F,0,A+2/3,F+1,0,A,F+1,0];S.set(_,w*g*T),k.set(p,b*g*T);const M=[T,T,T,T,T,T];C.set(M,x*g*T)}const P=new io;P.setAttribute("position",new _l(S,w)),P.setAttribute("uv",new _l(k,b)),P.setAttribute("faceIndex",new _l(C,x)),e.push(P),i>Qx&&i--}return{lodPlanes:e,sizeLods:n,sigmas:a}}function B$(t,e,n){const a=new Og(t,e,n);return a.texture.mapping=LT,a.texture.name="PMREM.cubeUv",a.scissorTest=!0,a}function y1(t,e,n,a,i){t.viewport.set(e,n,a,i),t.scissor.set(e,n,a,i)}function Aje(t,e,n){const a=new Float32Array(tg),i=new yt(0,1,0);return new Yh({name:"SphericalGaussianBlur",defines:{n:tg,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:a},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:n4(),fragmentShader:`
  7277. precision mediump float;
  7278. precision mediump int;
  7279. varying vec3 vOutputDirection;
  7280. uniform sampler2D envMap;
  7281. uniform int samples;
  7282. uniform float weights[ n ];
  7283. uniform bool latitudinal;
  7284. uniform float dTheta;
  7285. uniform float mipInt;
  7286. uniform vec3 poleAxis;
  7287. #define ENVMAP_TYPE_CUBE_UV
  7288. #include <cube_uv_reflection_fragment>
  7289. vec3 getSample( float theta, vec3 axis ) {
  7290. float cosTheta = cos( theta );
  7291. // Rodrigues' axis-angle rotation
  7292. vec3 sampleDirection = vOutputDirection * cosTheta
  7293. + cross( axis, vOutputDirection ) * sin( theta )
  7294. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  7295. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  7296. }
  7297. void main() {
  7298. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  7299. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  7300. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  7301. }
  7302. axis = normalize( axis );
  7303. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  7304. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  7305. for ( int i = 1; i < n; i++ ) {
  7306. if ( i >= samples ) {
  7307. break;
  7308. }
  7309. float theta = dTheta * float( i );
  7310. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  7311. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  7312. }
  7313. }
  7314. `,blending:Lh,depthTest:!1,depthWrite:!1})}function H$(){return new Yh({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:n4(),fragmentShader:`
  7315. precision mediump float;
  7316. precision mediump int;
  7317. varying vec3 vOutputDirection;
  7318. uniform sampler2D envMap;
  7319. #include <common>
  7320. void main() {
  7321. vec3 outputDirection = normalize( vOutputDirection );
  7322. vec2 uv = equirectUv( outputDirection );
  7323. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  7324. }
  7325. `,blending:Lh,depthTest:!1,depthWrite:!1})}function q$(){return new Yh({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:n4(),fragmentShader:`
  7326. precision mediump float;
  7327. precision mediump int;
  7328. uniform float flipEnvMap;
  7329. varying vec3 vOutputDirection;
  7330. uniform samplerCube envMap;
  7331. void main() {
  7332. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  7333. }
  7334. `,blending:Lh,depthTest:!1,depthWrite:!1})}function n4(){return`
  7335. precision mediump float;
  7336. precision mediump int;
  7337. attribute float faceIndex;
  7338. varying vec3 vOutputDirection;
  7339. // RH coordinate system; PMREM face-indexing convention
  7340. vec3 getDirection( vec2 uv, float face ) {
  7341. uv = 2.0 * uv - 1.0;
  7342. vec3 direction = vec3( uv, 1.0 );
  7343. if ( face == 0.0 ) {
  7344. direction = direction.zyx; // ( 1, v, u ) pos x
  7345. } else if ( face == 1.0 ) {
  7346. direction = direction.xzy;
  7347. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  7348. } else if ( face == 2.0 ) {
  7349. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  7350. } else if ( face == 3.0 ) {
  7351. direction = direction.zyx;
  7352. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  7353. } else if ( face == 4.0 ) {
  7354. direction = direction.xzy;
  7355. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  7356. } else if ( face == 5.0 ) {
  7357. direction.z *= -1.0; // ( u, v, -1 ) neg z
  7358. }
  7359. return direction;
  7360. }
  7361. void main() {
  7362. vOutputDirection = getDirection( uv, faceIndex );
  7363. gl_Position = vec4( position, 1.0 );
  7364. }
  7365. `}function jje(t){let e=new WeakMap,n=null;function a(l){if(l&&l.isTexture){const c=l.mapping,d=c===QL||c===YL,u=c===ky||c===Ny;if(d||u)if(l.isRenderTargetTexture&&l.needsPMREMUpdate===!0){l.needsPMREMUpdate=!1;let m=e.get(l);return n===null&&(n=new U$(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 U$(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:a,dispose:o}}function Mje(t){const e={};function n(a){if(e[a]!==void 0)return e[a];let i;switch(a){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(a)}return e[a]=i,i}return{has:function(a){return n(a)!==null},init:function(a){a.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(a){const i=n(a);return i===null&&console.warn("THREE.WebGLRenderer: "+a+" extension not supported."),i}}}function Eje(t,e,n,a){const i={},s=new WeakMap;function o(m){const p=m.target;p.index!==null&&e.remove(p.index);for(const g in p.attributes)e.remove(p.attributes[g]);for(const g in p.morphAttributes){const w=p.morphAttributes[g];for(let b=0,x=w.length;b<x;b++)e.remove(w[b])}p.removeEventListener("dispose",o),delete i[p.id];const f=s.get(p);f&&(e.remove(f),s.delete(p)),a.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 g in p)e.update(p[g],t.ARRAY_BUFFER);const f=m.morphAttributes;for(const g in f){const w=f[g];for(let b=0,x=w.length;b<x;b++)e.update(w[b],t.ARRAY_BUFFER)}}function d(m){const p=[],f=m.index,g=m.attributes.position;let w=0;if(f!==null){const S=f.array;w=f.version;for(let k=0,C=S.length;k<C;k+=3){const P=S[k+0],T=S[k+1],A=S[k+2];p.push(P,T,T,A,A,P)}}else if(g!==void 0){const S=g.array;w=g.version;for(let k=0,C=S.length/3-1;k<C;k+=3){const P=k+0,T=k+1,A=k+2;p.push(P,T,T,A,A,P)}}else return;const b=new(mee(p)?vee:yee)(p,1);b.version=w;const x=s.get(m);x&&e.remove(x),s.set(m,b)}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 Dje(t,e,n,a){const i=a.isWebGL2;let s;function o(f){s=f}let l,c;function d(f){l=f.type,c=f.bytesPerElement}function u(f,g){t.drawElements(s,g,l,f*c),n.update(g,s,1)}function m(f,g,w){if(w===0)return;let b,x;if(i)b=t,x="drawElementsInstanced";else if(b=e.get("ANGLE_instanced_arrays"),x="drawElementsInstancedANGLE",b===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}b[x](s,g,l,f*c,w),n.update(g,s,w)}function p(f,g,w){if(w===0)return;const b=e.get("WEBGL_multi_draw");if(b===null)for(let x=0;x<w;x++)this.render(f[x]/c,g[x]);else{b.multiDrawElementsWEBGL(s,g,0,l,f,0,w);let x=0;for(let S=0;S<w;S++)x+=g[S];n.update(x,s,1)}}this.setMode=o,this.setIndex=d,this.render=u,this.renderInstances=m,this.renderMultiDraw=p}function Fje(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function a(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:a}}function Lje(t,e){return t[0]-e[0]}function Rje(t,e){return Math.abs(e[1])-Math.abs(t[1])}function Ije(t,e,n){const a={},i=new Float32Array(8),s=new WeakMap,o=new la,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 g=u.morphAttributes.position||u.morphAttributes.normal||u.morphAttributes.color,w=g!==void 0?g.length:0;let b=s.get(u);if(b===void 0||b.count!==w){let Z=function(){z.dispose(),s.delete(u),u.removeEventListener("dispose",Z)};var f=Z;b!==void 0&&b.texture.dispose();const k=u.morphAttributes.position!==void 0,C=u.morphAttributes.normal!==void 0,P=u.morphAttributes.color!==void 0,T=u.morphAttributes.position||[],A=u.morphAttributes.normal||[],F=u.morphAttributes.color||[];let _=0;k===!0&&(_=1),C===!0&&(_=2),P===!0&&(_=3);let M=u.attributes.position.count*_,H=1;M>e.maxTextureSize&&(H=Math.ceil(M/e.maxTextureSize),M=e.maxTextureSize);const I=new Float32Array(M*H*4*w),z=new fee(I,M,H,w);z.type=km,z.needsUpdate=!0;const L=_*4;for(let ne=0;ne<w;ne++){const Y=T[ne],ce=A[ne],ue=F[ne],oe=M*H*4*ne;for(let Q=0;Q<Y.count;Q++){const le=Q*L;k===!0&&(o.fromBufferAttribute(Y,Q),I[oe+le+0]=o.x,I[oe+le+1]=o.y,I[oe+le+2]=o.z,I[oe+le+3]=0),C===!0&&(o.fromBufferAttribute(ce,Q),I[oe+le+4]=o.x,I[oe+le+5]=o.y,I[oe+le+6]=o.z,I[oe+le+7]=0),P===!0&&(o.fromBufferAttribute(ue,Q),I[oe+le+8]=o.x,I[oe+le+9]=o.y,I[oe+le+10]=o.z,I[oe+le+11]=ue.itemSize===4?o.w:1)}}b={count:w,texture:z,size:new Wn(M,H)},s.set(u,b),u.addEventListener("dispose",Z)}let x=0;for(let k=0;k<p.length;k++)x+=p[k];const S=u.morphTargetsRelative?1:1-x;m.getUniforms().setValue(t,"morphTargetBaseInfluence",S),m.getUniforms().setValue(t,"morphTargetInfluences",p),m.getUniforms().setValue(t,"morphTargetsTexture",b.texture,n),m.getUniforms().setValue(t,"morphTargetsTextureSize",b.size)}else{const g=p===void 0?0:p.length;let w=a[u.id];if(w===void 0||w.length!==g){w=[];for(let C=0;C<g;C++)w[C]=[C,0];a[u.id]=w}for(let C=0;C<g;C++){const P=w[C];P[0]=C,P[1]=p[C]}w.sort(Rje);for(let C=0;C<8;C++)C<g&&w[C][1]?(l[C][0]=w[C][0],l[C][1]=w[C][1]):(l[C][0]=Number.MAX_SAFE_INTEGER,l[C][1]=0);l.sort(Lje);const b=u.morphAttributes.position,x=u.morphAttributes.normal;let S=0;for(let C=0;C<8;C++){const P=l[C],T=P[0],A=P[1];T!==Number.MAX_SAFE_INTEGER&&A?(b&&u.getAttribute("morphTarget"+C)!==b[T]&&u.setAttribute("morphTarget"+C,b[T]),x&&u.getAttribute("morphNormal"+C)!==x[T]&&u.setAttribute("morphNormal"+C,x[T]),i[C]=A,S+=A):(b&&u.hasAttribute("morphTarget"+C)===!0&&u.deleteAttribute("morphTarget"+C),x&&u.hasAttribute("morphNormal"+C)===!0&&u.deleteAttribute("morphNormal"+C),i[C]=0)}const k=u.morphTargetsRelative?1:1-S;m.getUniforms().setValue(t,"morphTargetBaseInfluence",k),m.getUniforms().setValue(t,"morphTargetInfluences",i)}}return{update:c}}function Oje(t,e,n,a){let i=new WeakMap;function s(c){const d=a.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 Nee extends Qo{constructor(e,n,a,i,s,o,l,c,d,u){if(u=u!==void 0?u:gg,u!==gg&&u!==Cy)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");a===void 0&&u===gg&&(a=yh),a===void 0&&u===Cy&&(a=fg),super(null,i,s,o,l,c,u,a,d),this.isDepthTexture=!0,this.image={width:e,height:n},this.magFilter=l!==void 0?l:js,this.minFilter=c!==void 0?c:js,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 Cee=new Qo,Pee=new Nee(1,1);Pee.compareFunction=dee;const Tee=new fee,Aee=new SPe,jee=new _ee,$$=[],V$=[],G$=new Float32Array(16),W$=new Float32Array(9),K$=new Float32Array(4);function ev(t,e,n){const a=t[0];if(a<=0||a>0)return t;const i=e*n;let s=$$[i];if(s===void 0&&(s=new Float32Array(i),$$[i]=s),e!==0){a.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function Bi(t,e){if(t.length!==e.length)return!1;for(let n=0,a=t.length;n<a;n++)if(t[n]!==e[n])return!1;return!0}function Hi(t,e){for(let n=0,a=e.length;n<a;n++)t[n]=e[n]}function OT(t,e){let n=V$[e];n===void 0&&(n=new Int32Array(e),V$[e]=n);for(let a=0;a!==e;++a)n[a]=t.allocateTextureUnit();return n}function zje(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function Uje(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(Bi(n,e))return;t.uniform2fv(this.addr,e),Hi(n,e)}}function Bje(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(Bi(n,e))return;t.uniform3fv(this.addr,e),Hi(n,e)}}function Hje(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(Bi(n,e))return;t.uniform4fv(this.addr,e),Hi(n,e)}}function qje(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(Bi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),Hi(n,e)}else{if(Bi(n,a))return;K$.set(a),t.uniformMatrix2fv(this.addr,!1,K$),Hi(n,a)}}function $je(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(Bi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),Hi(n,e)}else{if(Bi(n,a))return;W$.set(a),t.uniformMatrix3fv(this.addr,!1,W$),Hi(n,a)}}function Vje(t,e){const n=this.cache,a=e.elements;if(a===void 0){if(Bi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),Hi(n,e)}else{if(Bi(n,a))return;G$.set(a),t.uniformMatrix4fv(this.addr,!1,G$),Hi(n,a)}}function Gje(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function Wje(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(Bi(n,e))return;t.uniform2iv(this.addr,e),Hi(n,e)}}function Kje(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(Bi(n,e))return;t.uniform3iv(this.addr,e),Hi(n,e)}}function Qje(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(Bi(n,e))return;t.uniform4iv(this.addr,e),Hi(n,e)}}function Yje(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function Xje(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(Bi(n,e))return;t.uniform2uiv(this.addr,e),Hi(n,e)}}function Zje(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(Bi(n,e))return;t.uniform3uiv(this.addr,e),Hi(n,e)}}function Jje(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(Bi(n,e))return;t.uniform4uiv(this.addr,e),Hi(n,e)}}function eMe(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i);const s=this.type===t.SAMPLER_2D_SHADOW?Pee:Cee;n.setTexture2D(e||s,i)}function tMe(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTexture3D(e||Aee,i)}function nMe(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTextureCube(e||jee,i)}function rMe(t,e,n){const a=this.cache,i=n.allocateTextureUnit();a[0]!==i&&(t.uniform1i(this.addr,i),a[0]=i),n.setTexture2DArray(e||Tee,i)}function aMe(t){switch(t){case 5126:return zje;case 35664:return Uje;case 35665:return Bje;case 35666:return Hje;case 35674:return qje;case 35675:return $je;case 35676:return Vje;case 5124:case 35670:return Gje;case 35667:case 35671:return Wje;case 35668:case 35672:return Kje;case 35669:case 35673:return Qje;case 5125:return Yje;case 36294:return Xje;case 36295:return Zje;case 36296:return Jje;case 35678:case 36198:case 36298:case 36306:case 35682:return eMe;case 35679:case 36299:case 36307:return tMe;case 35680:case 36300:case 36308:case 36293:return nMe;case 36289:case 36303:case 36311:case 36292:return rMe}}function iMe(t,e){t.uniform1fv(this.addr,e)}function sMe(t,e){const n=ev(e,this.size,2);t.uniform2fv(this.addr,n)}function oMe(t,e){const n=ev(e,this.size,3);t.uniform3fv(this.addr,n)}function lMe(t,e){const n=ev(e,this.size,4);t.uniform4fv(this.addr,n)}function cMe(t,e){const n=ev(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function dMe(t,e){const n=ev(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function uMe(t,e){const n=ev(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function mMe(t,e){t.uniform1iv(this.addr,e)}function pMe(t,e){t.uniform2iv(this.addr,e)}function hMe(t,e){t.uniform3iv(this.addr,e)}function fMe(t,e){t.uniform4iv(this.addr,e)}function gMe(t,e){t.uniform1uiv(this.addr,e)}function bMe(t,e){t.uniform2uiv(this.addr,e)}function xMe(t,e){t.uniform3uiv(this.addr,e)}function yMe(t,e){t.uniform4uiv(this.addr,e)}function vMe(t,e,n){const a=this.cache,i=e.length,s=OT(n,i);Bi(a,s)||(t.uniform1iv(this.addr,s),Hi(a,s));for(let o=0;o!==i;++o)n.setTexture2D(e[o]||Cee,s[o])}function wMe(t,e,n){const a=this.cache,i=e.length,s=OT(n,i);Bi(a,s)||(t.uniform1iv(this.addr,s),Hi(a,s));for(let o=0;o!==i;++o)n.setTexture3D(e[o]||Aee,s[o])}function SMe(t,e,n){const a=this.cache,i=e.length,s=OT(n,i);Bi(a,s)||(t.uniform1iv(this.addr,s),Hi(a,s));for(let o=0;o!==i;++o)n.setTextureCube(e[o]||jee,s[o])}function _Me(t,e,n){const a=this.cache,i=e.length,s=OT(n,i);Bi(a,s)||(t.uniform1iv(this.addr,s),Hi(a,s));for(let o=0;o!==i;++o)n.setTexture2DArray(e[o]||Tee,s[o])}function kMe(t){switch(t){case 5126:return iMe;case 35664:return sMe;case 35665:return oMe;case 35666:return lMe;case 35674:return cMe;case 35675:return dMe;case 35676:return uMe;case 5124:case 35670:return mMe;case 35667:case 35671:return pMe;case 35668:case 35672:return hMe;case 35669:case 35673:return fMe;case 5125:return gMe;case 36294:return bMe;case 36295:return xMe;case 36296:return yMe;case 35678:case 36198:case 36298:case 36306:case 35682:return vMe;case 35679:case 36299:case 36307:return wMe;case 35680:case 36300:case 36308:case 36293:return SMe;case 36289:case 36303:case 36311:case 36292:return _Me}}class NMe{constructor(e,n,a){this.id=e,this.addr=a,this.cache=[],this.type=n.type,this.setValue=aMe(n.type)}}class CMe{constructor(e,n,a){this.id=e,this.addr=a,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=kMe(n.type)}}class PMe{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,a){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const l=i[s];l.setValue(e,n[l.id],a)}}}const x2=/(\w+)(\])?(\[|\.)?/g;function Q$(t,e){t.seq.push(e),t.map[e.id]=e}function TMe(t,e,n){const a=t.name,i=a.length;for(x2.lastIndex=0;;){const s=x2.exec(a),o=x2.lastIndex;let l=s[1];const c=s[2]==="]",d=s[3];if(c&&(l=l|0),d===void 0||d==="["&&o+2===i){Q$(n,d===void 0?new NMe(l,t,e):new CMe(l,t,e));break}else{let m=n.map[l];m===void 0&&(m=new PMe(l),Q$(n,m)),n=m}}}class TN{constructor(e,n){this.seq=[],this.map={};const a=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let i=0;i<a;++i){const s=e.getActiveUniform(n,i),o=e.getUniformLocation(n,s.name);TMe(s,o,this)}}setValue(e,n,a,i){const s=this.map[n];s!==void 0&&s.setValue(e,a,i)}setOptional(e,n,a){const i=n[a];i!==void 0&&this.setValue(e,a,i)}static upload(e,n,a,i){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=a[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,i)}}static seqWithValue(e,n){const a=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in n&&a.push(o)}return a}}function Y$(t,e,n){const a=t.createShader(e);return t.shaderSource(a,n),t.compileShader(a),a}const AMe=37297;let jMe=0;function MMe(t,e){const n=t.split(`
  7366. `),a=[],i=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=i;o<s;o++){const l=o+1;a.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return a.join(`
  7367. `)}function EMe(t){const e=sa.getPrimaries(sa.workingColorSpace),n=sa.getPrimaries(t);let a;switch(e===n?a="":e===bC&&n===gC?a="LinearDisplayP3ToLinearSRGB":e===gC&&n===bC&&(a="LinearSRGBToLinearDisplayP3"),t){case Qm:case RT:return[a,"LinearTransferOETF"];case Ms:case XO:return[a,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[a,"LinearTransferOETF"]}}function X$(t,e,n){const a=t.getShaderParameter(e,t.COMPILE_STATUS),i=t.getShaderInfoLog(e).trim();if(a&&i==="")return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const o=parseInt(s[1]);return n.toUpperCase()+`
  7368. `+i+`
  7369. `+MMe(t.getShaderSource(e),o)}else return i}function DMe(t,e){const n=EMe(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function FMe(t,e){let n;switch(e){case DCe:n="Linear";break;case FCe:n="Reinhard";break;case LCe:n="OptimizedCineon";break;case RCe:n="ACESFilmic";break;case ICe:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function LMe(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(R0).join(`
  7370. `)}function RMe(t){const e=[];for(const n in t){const a=t[n];a!==!1&&e.push("#define "+n+" "+a)}return e.join(`
  7371. `)}function IMe(t,e){const n={},a=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let i=0;i<a;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 R0(t){return t!==""}function Z$(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 J$(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const OMe=/^[ \t]*#include +<([\w\d./]+)>/gm;function nR(t){return t.replace(OMe,UMe)}const zMe=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function UMe(t,e){let n=ar[e];if(n===void 0){const a=zMe.get(e);if(a!==void 0)n=ar[a],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,a);else throw new Error("Can not resolve #include <"+e+">")}return nR(n)}const BMe=/#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 eV(t){return t.replace(BMe,HMe)}function HMe(t,e,n,a){let i="";for(let s=parseInt(e);s<parseInt(n);s++)i+=a.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function tV(t){let e="precision "+t.precision+` float;
  7372. precision `+t.precision+" int;";return t.precision==="highp"?e+=`
  7373. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  7374. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  7375. #define LOW_PRECISION`),e}function qMe(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===JJ?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===oCe?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===um&&(e="SHADOWMAP_TYPE_VSM"),e}function $Me(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case ky:case Ny:e="ENVMAP_TYPE_CUBE";break;case LT:e="ENVMAP_TYPE_CUBE_UV";break}return e}function VMe(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===Ny&&(e="ENVMAP_MODE_REFRACTION"),e}function GMe(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case QO:e="ENVMAP_BLENDING_MULTIPLY";break;case MCe:e="ENVMAP_BLENDING_MIX";break;case ECe:e="ENVMAP_BLENDING_ADD";break}return e}function WMe(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,a=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:a,maxMip:n}}function KMe(t,e,n,a){const i=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=qMe(n),d=$Me(n),u=VMe(n),m=GMe(n),p=WMe(n),f=n.isWebGL2?"":LMe(n),g=RMe(s),w=i.createProgram();let b,x,S=n.glslVersion?"#version "+n.glslVersion+`
  7376. `:"";n.isRawShaderMaterial?(b=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(R0).join(`
  7377. `),b.length>0&&(b+=`
  7378. `),x=[f,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g].filter(R0).join(`
  7379. `),x.length>0&&(x+=`
  7380. `)):(b=[tV(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,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",`
  7381. `].filter(R0).join(`
  7382. `),x=[f,tV(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,g,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!==Rh?"#define TONE_MAPPING":"",n.toneMapping!==Rh?ar.tonemapping_pars_fragment:"",n.toneMapping!==Rh?FMe("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ar.colorspace_pars_fragment,DMe("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  7383. `].filter(R0).join(`
  7384. `)),o=nR(o),o=Z$(o,n),o=J$(o,n),l=nR(l),l=Z$(l,n),l=J$(l,n),o=eV(o),l=eV(l),n.isWebGL2&&n.isRawShaderMaterial!==!0&&(S=`#version 300 es
  7385. `,b=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(`
  7386. `)+`
  7387. `+b,x=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===y$?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===y$?"":"#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(`
  7388. `)+`
  7389. `+x);const k=S+b+o,C=S+x+l,P=Y$(i,i.VERTEX_SHADER,k),T=Y$(i,i.FRAGMENT_SHADER,C);i.attachShader(w,P),i.attachShader(w,T),n.index0AttributeName!==void 0?i.bindAttribLocation(w,0,n.index0AttributeName):n.morphTargets===!0&&i.bindAttribLocation(w,0,"position"),i.linkProgram(w);function A(H){if(t.debug.checkShaderErrors){const I=i.getProgramInfoLog(w).trim(),z=i.getShaderInfoLog(P).trim(),L=i.getShaderInfoLog(T).trim();let Z=!0,ne=!0;if(i.getProgramParameter(w,i.LINK_STATUS)===!1)if(Z=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(i,w,P,T);else{const Y=X$(i,P,"vertex"),ce=X$(i,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(w,i.VALIDATE_STATUS)+`
  7390. Program Info Log: `+I+`
  7391. `+Y+`
  7392. `+ce)}else I!==""?console.warn("THREE.WebGLProgram: Program Info Log:",I):(z===""||L==="")&&(ne=!1);ne&&(H.diagnostics={runnable:Z,programLog:I,vertexShader:{log:z,prefix:b},fragmentShader:{log:L,prefix:x}})}i.deleteShader(P),i.deleteShader(T),F=new TN(i,w),_=IMe(i,w)}let F;this.getUniforms=function(){return F===void 0&&A(this),F};let _;this.getAttributes=function(){return _===void 0&&A(this),_};let M=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return M===!1&&(M=i.getProgramParameter(w,AMe)),M},this.destroy=function(){a.releaseStatesOfProgram(this),i.deleteProgram(w),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=jMe++,this.cacheKey=e,this.usedTimes=1,this.program=w,this.vertexShader=P,this.fragmentShader=T,this}let QMe=0;class YMe{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,a=e.fragmentShader,i=this._getShaderStage(n),s=this._getShaderStage(a),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 a of n)a.usedTimes--,a.usedTimes===0&&this.shaderCache.delete(a.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 a=n.get(e);return a===void 0&&(a=new Set,n.set(e,a)),a}_getShaderStage(e){const n=this.shaderCache;let a=n.get(e);return a===void 0&&(a=new XMe(e),n.set(e,a)),a}}class XMe{constructor(e){this.id=QMe++,this.code=e,this.usedTimes=0}}function ZMe(t,e,n,a,i,s,o){const l=new gee,c=new YMe,d=[],u=i.isWebGL2,m=i.logarithmicDepthBuffer,p=i.vertexTextures;let f=i.precision;const g={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 w(_){return _===0?"uv":`uv${_}`}function b(_,M,H,I,z){const L=I.fog,Z=z.geometry,ne=_.isMeshStandardMaterial?I.environment:null,Y=(_.isMeshStandardMaterial?n:e).get(_.envMap||ne),ce=Y&&Y.mapping===LT?Y.image.height:null,ue=g[_.type];_.precision!==null&&(f=i.getMaxPrecision(_.precision),f!==_.precision&&console.warn("THREE.WebGLProgram.getParameters:",_.precision,"not supported, using",f,"instead."));const oe=Z.morphAttributes.position||Z.morphAttributes.normal||Z.morphAttributes.color,Q=oe!==void 0?oe.length:0;let le=0;Z.morphAttributes.position!==void 0&&(le=1),Z.morphAttributes.normal!==void 0&&(le=2),Z.morphAttributes.color!==void 0&&(le=3);let pe,he,we,$;if(ue){const tt=qo[ue];pe=tt.vertexShader,he=tt.fragmentShader}else pe=_.vertexShader,he=_.fragmentShader,c.update(_),we=c.getVertexShaderID(_),$=c.getFragmentShaderID(_);const J=t.getRenderTarget(),j=z.isInstancedMesh===!0,E=z.isBatchedMesh===!0,B=!!_.map,W=!!_.matcap,O=!!Y,ie=!!_.aoMap,U=!!_.lightMap,G=!!_.bumpMap,K=!!_.normalMap,X=!!_.displacementMap,se=!!_.emissiveMap,te=!!_.metalnessMap,fe=!!_.roughnessMap,de=_.anisotropy>0,me=_.clearcoat>0,q=_.iridescence>0,R=_.sheen>0,re=_.transmission>0,be=de&&!!_.anisotropyMap,ye=me&&!!_.clearcoatMap,_e=me&&!!_.clearcoatNormalMap,xe=me&&!!_.clearcoatRoughnessMap,ge=q&&!!_.iridescenceMap,Me=q&&!!_.iridescenceThicknessMap,Be=R&&!!_.sheenColorMap,Fe=R&&!!_.sheenRoughnessMap,Oe=!!_.specularMap,Re=!!_.specularColorMap,We=!!_.specularIntensityMap,ze=re&&!!_.transmissionMap,st=re&&!!_.thicknessMap,Ee=!!_.gradientMap,it=!!_.alphaMap,Ce=_.alphaTest>0,Ze=!!_.alphaHash,Ie=!!_.extensions,ke=!!Z.attributes.uv1,Ve=!!Z.attributes.uv2,rt=!!Z.attributes.uv3;let Qe=Rh;return _.toneMapped&&(J===null||J.isXRRenderTarget===!0)&&(Qe=t.toneMapping),{isWebGL2:u,shaderID:ue,shaderType:_.type,shaderName:_.name,vertexShader:pe,fragmentShader:he,defines:_.defines,customVertexShaderID:we,customFragmentShaderID:$,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:f,batching:E,instancing:j,instancingColor:j&&z.instanceColor!==null,supportsVertexTextures:p,outputColorSpace:J===null?t.outputColorSpace:J.isXRRenderTarget===!0?J.texture.colorSpace:Qm,map:B,matcap:W,envMap:O,envMapMode:O&&Y.mapping,envMapCubeUVHeight:ce,aoMap:ie,lightMap:U,bumpMap:G,normalMap:K,displacementMap:p&&X,emissiveMap:se,normalMapObjectSpace:K&&_.normalMapType===QCe,normalMapTangentSpace:K&&_.normalMapType===cee,metalnessMap:te,roughnessMap:fe,anisotropy:de,anisotropyMap:be,clearcoat:me,clearcoatMap:ye,clearcoatNormalMap:_e,clearcoatRoughnessMap:xe,iridescence:q,iridescenceMap:ge,iridescenceThicknessMap:Me,sheen:R,sheenColorMap:Be,sheenRoughnessMap:Fe,specularMap:Oe,specularColorMap:Re,specularIntensityMap:We,transmission:re,transmissionMap:ze,thicknessMap:st,gradientMap:Ee,opaque:_.transparent===!1&&_.blending===sy,alphaMap:it,alphaTest:Ce,alphaHash:Ze,combine:_.combine,mapUv:B&&w(_.map.channel),aoMapUv:ie&&w(_.aoMap.channel),lightMapUv:U&&w(_.lightMap.channel),bumpMapUv:G&&w(_.bumpMap.channel),normalMapUv:K&&w(_.normalMap.channel),displacementMapUv:X&&w(_.displacementMap.channel),emissiveMapUv:se&&w(_.emissiveMap.channel),metalnessMapUv:te&&w(_.metalnessMap.channel),roughnessMapUv:fe&&w(_.roughnessMap.channel),anisotropyMapUv:be&&w(_.anisotropyMap.channel),clearcoatMapUv:ye&&w(_.clearcoatMap.channel),clearcoatNormalMapUv:_e&&w(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:xe&&w(_.clearcoatRoughnessMap.channel),iridescenceMapUv:ge&&w(_.iridescenceMap.channel),iridescenceThicknessMapUv:Me&&w(_.iridescenceThicknessMap.channel),sheenColorMapUv:Be&&w(_.sheenColorMap.channel),sheenRoughnessMapUv:Fe&&w(_.sheenRoughnessMap.channel),specularMapUv:Oe&&w(_.specularMap.channel),specularColorMapUv:Re&&w(_.specularColorMap.channel),specularIntensityMapUv:We&&w(_.specularIntensityMap.channel),transmissionMapUv:ze&&w(_.transmissionMap.channel),thicknessMapUv:st&&w(_.thicknessMap.channel),alphaMapUv:it&&w(_.alphaMap.channel),vertexTangents:!!Z.attributes.tangent&&(K||de),vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!Z.attributes.color&&Z.attributes.color.itemSize===4,vertexUv1s:ke,vertexUv2s:Ve,vertexUv3s:rt,pointsUvs:z.isPoints===!0&&!!Z.attributes.uv&&(B||it),fog:!!L,useFog:_.fog===!0,fogExp2:L&&L.isFogExp2,flatShading:_.flatShading===!0,sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:m,skinning:z.isSkinnedMesh===!0,morphTargets:Z.morphAttributes.position!==void 0,morphNormals:Z.morphAttributes.normal!==void 0,morphColors:Z.morphAttributes.color!==void 0,morphTargetsCount:Q,morphTextureStride:le,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:_.dithering,shadowMapEnabled:t.shadowMap.enabled&&H.length>0,shadowMapType:t.shadowMap.type,toneMapping:Qe,useLegacyLights:t._useLegacyLights,decodeVideoTexture:B&&_.map.isVideoTexture===!0&&sa.getTransfer(_.map.colorSpace)===Ta,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===xm,flipSided:_.side===Ko,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionDerivatives:Ie&&_.extensions.derivatives===!0,extensionFragDepth:Ie&&_.extensions.fragDepth===!0,extensionDrawBuffers:Ie&&_.extensions.drawBuffers===!0,extensionShaderTextureLOD:Ie&&_.extensions.shaderTextureLOD===!0,rendererExtensionFragDepth:u||a.has("EXT_frag_depth"),rendererExtensionDrawBuffers:u||a.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:u||a.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:a.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()}}function x(_){const M=[];if(_.shaderID?M.push(_.shaderID):(M.push(_.customVertexShaderID),M.push(_.customFragmentShaderID)),_.defines!==void 0)for(const H in _.defines)M.push(H),M.push(_.defines[H]);return _.isRawShaderMaterial===!1&&(S(M,_),k(M,_),M.push(t.outputColorSpace)),M.push(_.customProgramCacheKey),M.join()}function S(_,M){_.push(M.precision),_.push(M.outputColorSpace),_.push(M.envMapMode),_.push(M.envMapCubeUVHeight),_.push(M.mapUv),_.push(M.alphaMapUv),_.push(M.lightMapUv),_.push(M.aoMapUv),_.push(M.bumpMapUv),_.push(M.normalMapUv),_.push(M.displacementMapUv),_.push(M.emissiveMapUv),_.push(M.metalnessMapUv),_.push(M.roughnessMapUv),_.push(M.anisotropyMapUv),_.push(M.clearcoatMapUv),_.push(M.clearcoatNormalMapUv),_.push(M.clearcoatRoughnessMapUv),_.push(M.iridescenceMapUv),_.push(M.iridescenceThicknessMapUv),_.push(M.sheenColorMapUv),_.push(M.sheenRoughnessMapUv),_.push(M.specularMapUv),_.push(M.specularColorMapUv),_.push(M.specularIntensityMapUv),_.push(M.transmissionMapUv),_.push(M.thicknessMapUv),_.push(M.combine),_.push(M.fogExp2),_.push(M.sizeAttenuation),_.push(M.morphTargetsCount),_.push(M.morphAttributeCount),_.push(M.numDirLights),_.push(M.numPointLights),_.push(M.numSpotLights),_.push(M.numSpotLightMaps),_.push(M.numHemiLights),_.push(M.numRectAreaLights),_.push(M.numDirLightShadows),_.push(M.numPointLightShadows),_.push(M.numSpotLightShadows),_.push(M.numSpotLightShadowsWithMaps),_.push(M.numLightProbes),_.push(M.shadowMapType),_.push(M.toneMapping),_.push(M.numClippingPlanes),_.push(M.numClipIntersection),_.push(M.depthPacking)}function k(_,M){l.disableAll(),M.isWebGL2&&l.enable(0),M.supportsVertexTextures&&l.enable(1),M.instancing&&l.enable(2),M.instancingColor&&l.enable(3),M.matcap&&l.enable(4),M.envMap&&l.enable(5),M.normalMapObjectSpace&&l.enable(6),M.normalMapTangentSpace&&l.enable(7),M.clearcoat&&l.enable(8),M.iridescence&&l.enable(9),M.alphaTest&&l.enable(10),M.vertexColors&&l.enable(11),M.vertexAlphas&&l.enable(12),M.vertexUv1s&&l.enable(13),M.vertexUv2s&&l.enable(14),M.vertexUv3s&&l.enable(15),M.vertexTangents&&l.enable(16),M.anisotropy&&l.enable(17),M.alphaHash&&l.enable(18),M.batching&&l.enable(19),_.push(l.mask),l.disableAll(),M.fog&&l.enable(0),M.useFog&&l.enable(1),M.flatShading&&l.enable(2),M.logarithmicDepthBuffer&&l.enable(3),M.skinning&&l.enable(4),M.morphTargets&&l.enable(5),M.morphNormals&&l.enable(6),M.morphColors&&l.enable(7),M.premultipliedAlpha&&l.enable(8),M.shadowMapEnabled&&l.enable(9),M.useLegacyLights&&l.enable(10),M.doubleSided&&l.enable(11),M.flipSided&&l.enable(12),M.useDepthPacking&&l.enable(13),M.dithering&&l.enable(14),M.transmission&&l.enable(15),M.sheen&&l.enable(16),M.opaque&&l.enable(17),M.pointsUvs&&l.enable(18),M.decodeVideoTexture&&l.enable(19),_.push(l.mask)}function C(_){const M=g[_.type];let H;if(M){const I=qo[M];H=e4.clone(I.uniforms)}else H=_.uniforms;return H}function P(_,M){let H;for(let I=0,z=d.length;I<z;I++){const L=d[I];if(L.cacheKey===M){H=L,++H.usedTimes;break}}return H===void 0&&(H=new KMe(t,M,_,s),d.push(H)),H}function T(_){if(--_.usedTimes===0){const M=d.indexOf(_);d[M]=d[d.length-1],d.pop(),_.destroy()}}function A(_){c.remove(_)}function F(){c.dispose()}return{getParameters:b,getProgramCacheKey:x,getUniforms:C,acquireProgram:P,releaseProgram:T,releaseShaderCache:A,programs:d,dispose:F}}function JMe(){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 a(s,o,l){t.get(s)[o]=l}function i(){t=new WeakMap}return{get:e,remove:n,update:a,dispose:i}}function eEe(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 nV(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 rV(){const t=[];let e=0;const n=[],a=[],i=[];function s(){e=0,n.length=0,a.length=0,i.length=0}function o(m,p,f,g,w,b){let x=t[e];return x===void 0?(x={id:m.id,object:m,geometry:p,material:f,groupOrder:g,renderOrder:m.renderOrder,z:w,group:b},t[e]=x):(x.id=m.id,x.object=m,x.geometry=p,x.material=f,x.groupOrder=g,x.renderOrder=m.renderOrder,x.z=w,x.group=b),e++,x}function l(m,p,f,g,w,b){const x=o(m,p,f,g,w,b);f.transmission>0?a.push(x):f.transparent===!0?i.push(x):n.push(x)}function c(m,p,f,g,w,b){const x=o(m,p,f,g,w,b);f.transmission>0?a.unshift(x):f.transparent===!0?i.unshift(x):n.unshift(x)}function d(m,p){n.length>1&&n.sort(m||eEe),a.length>1&&a.sort(p||nV),i.length>1&&i.sort(p||nV)}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:a,transparent:i,init:s,push:l,unshift:c,finish:u,sort:d}}function tEe(){let t=new WeakMap;function e(a,i){const s=t.get(a);let o;return s===void 0?(o=new rV,t.set(a,[o])):i>=s.length?(o=new rV,s.push(o)):o=s[i],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function nEe(){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 yt,color:new On};break;case"SpotLight":n={position:new yt,direction:new yt,color:new On,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new yt,color:new On,distance:0,decay:0};break;case"HemisphereLight":n={direction:new yt,skyColor:new On,groundColor:new On};break;case"RectAreaLight":n={color:new On,position:new yt,halfWidth:new yt,halfHeight:new yt};break}return t[e.id]=n,n}}}function rEe(){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 Wn};break;case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Wn};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Wn,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let aEe=0;function iEe(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function sEe(t,e){const n=new nEe,a=rEe(),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 yt);const s=new yt,o=new Sa,l=new Sa;function c(u,m){let p=0,f=0,g=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let w=0,b=0,x=0,S=0,k=0,C=0,P=0,T=0,A=0,F=0,_=0;u.sort(iEe);const M=m===!0?Math.PI:1;for(let I=0,z=u.length;I<z;I++){const L=u[I],Z=L.color,ne=L.intensity,Y=L.distance,ce=L.shadow&&L.shadow.map?L.shadow.map.texture:null;if(L.isAmbientLight)p+=Z.r*ne*M,f+=Z.g*ne*M,g+=Z.b*ne*M;else if(L.isLightProbe){for(let ue=0;ue<9;ue++)i.probe[ue].addScaledVector(L.sh.coefficients[ue],ne);_++}else if(L.isDirectionalLight){const ue=n.get(L);if(ue.color.copy(L.color).multiplyScalar(L.intensity*M),L.castShadow){const oe=L.shadow,Q=a.get(L);Q.shadowBias=oe.bias,Q.shadowNormalBias=oe.normalBias,Q.shadowRadius=oe.radius,Q.shadowMapSize=oe.mapSize,i.directionalShadow[w]=Q,i.directionalShadowMap[w]=ce,i.directionalShadowMatrix[w]=L.shadow.matrix,C++}i.directional[w]=ue,w++}else if(L.isSpotLight){const ue=n.get(L);ue.position.setFromMatrixPosition(L.matrixWorld),ue.color.copy(Z).multiplyScalar(ne*M),ue.distance=Y,ue.coneCos=Math.cos(L.angle),ue.penumbraCos=Math.cos(L.angle*(1-L.penumbra)),ue.decay=L.decay,i.spot[x]=ue;const oe=L.shadow;if(L.map&&(i.spotLightMap[A]=L.map,A++,oe.updateMatrices(L),L.castShadow&&F++),i.spotLightMatrix[x]=oe.matrix,L.castShadow){const Q=a.get(L);Q.shadowBias=oe.bias,Q.shadowNormalBias=oe.normalBias,Q.shadowRadius=oe.radius,Q.shadowMapSize=oe.mapSize,i.spotShadow[x]=Q,i.spotShadowMap[x]=ce,T++}x++}else if(L.isRectAreaLight){const ue=n.get(L);ue.color.copy(Z).multiplyScalar(ne),ue.halfWidth.set(L.width*.5,0,0),ue.halfHeight.set(0,L.height*.5,0),i.rectArea[S]=ue,S++}else if(L.isPointLight){const ue=n.get(L);if(ue.color.copy(L.color).multiplyScalar(L.intensity*M),ue.distance=L.distance,ue.decay=L.decay,L.castShadow){const oe=L.shadow,Q=a.get(L);Q.shadowBias=oe.bias,Q.shadowNormalBias=oe.normalBias,Q.shadowRadius=oe.radius,Q.shadowMapSize=oe.mapSize,Q.shadowCameraNear=oe.camera.near,Q.shadowCameraFar=oe.camera.far,i.pointShadow[b]=Q,i.pointShadowMap[b]=ce,i.pointShadowMatrix[b]=L.shadow.matrix,P++}i.point[b]=ue,b++}else if(L.isHemisphereLight){const ue=n.get(L);ue.skyColor.copy(L.color).multiplyScalar(ne*M),ue.groundColor.copy(L.groundColor).multiplyScalar(ne*M),i.hemi[k]=ue,k++}}S>0&&(e.isWebGL2||t.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=sn.LTC_FLOAT_1,i.rectAreaLTC2=sn.LTC_FLOAT_2):t.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=sn.LTC_HALF_1,i.rectAreaLTC2=sn.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]=g;const H=i.hash;(H.directionalLength!==w||H.pointLength!==b||H.spotLength!==x||H.rectAreaLength!==S||H.hemiLength!==k||H.numDirectionalShadows!==C||H.numPointShadows!==P||H.numSpotShadows!==T||H.numSpotMaps!==A||H.numLightProbes!==_)&&(i.directional.length=w,i.spot.length=x,i.rectArea.length=S,i.point.length=b,i.hemi.length=k,i.directionalShadow.length=C,i.directionalShadowMap.length=C,i.pointShadow.length=P,i.pointShadowMap.length=P,i.spotShadow.length=T,i.spotShadowMap.length=T,i.directionalShadowMatrix.length=C,i.pointShadowMatrix.length=P,i.spotLightMatrix.length=T+A-F,i.spotLightMap.length=A,i.numSpotLightShadowsWithMaps=F,i.numLightProbes=_,H.directionalLength=w,H.pointLength=b,H.spotLength=x,H.rectAreaLength=S,H.hemiLength=k,H.numDirectionalShadows=C,H.numPointShadows=P,H.numSpotShadows=T,H.numSpotMaps=A,H.numLightProbes=_,i.version=aEe++)}function d(u,m){let p=0,f=0,g=0,w=0,b=0;const x=m.matrixWorldInverse;for(let S=0,k=u.length;S<k;S++){const C=u[S];if(C.isDirectionalLight){const P=i.directional[p];P.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),P.direction.sub(s),P.direction.transformDirection(x),p++}else if(C.isSpotLight){const P=i.spot[g];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(x),P.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),P.direction.sub(s),P.direction.transformDirection(x),g++}else if(C.isRectAreaLight){const P=i.rectArea[w];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(x),l.identity(),o.copy(C.matrixWorld),o.premultiply(x),l.extractRotation(o),P.halfWidth.set(C.width*.5,0,0),P.halfHeight.set(0,C.height*.5,0),P.halfWidth.applyMatrix4(l),P.halfHeight.applyMatrix4(l),w++}else if(C.isPointLight){const P=i.point[f];P.position.setFromMatrixPosition(C.matrixWorld),P.position.applyMatrix4(x),f++}else if(C.isHemisphereLight){const P=i.hemi[b];P.direction.setFromMatrixPosition(C.matrixWorld),P.direction.transformDirection(x),b++}}}return{setup:c,setupView:d,state:i}}function aV(t,e){const n=new sEe(t,e),a=[],i=[];function s(){a.length=0,i.length=0}function o(m){a.push(m)}function l(m){i.push(m)}function c(m){n.setup(a,m)}function d(m){n.setupView(a,m)}return{init:s,state:{lightsArray:a,shadowsArray:i,lights:n},setupLights:c,setupLightsView:d,pushLight:o,pushShadow:l}}function oEe(t,e){let n=new WeakMap;function a(s,o=0){const l=n.get(s);let c;return l===void 0?(c=new aV(t,e),n.set(s,[c])):o>=l.length?(c=new aV(t,e),l.push(c)):c=l[o],c}function i(){n=new WeakMap}return{get:a,dispose:i}}class lEe extends Jy{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=WCe,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 cEe extends Jy{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 dEe=`void main() {
  7393. gl_Position = vec4( position, 1.0 );
  7394. }`,uEe=`uniform sampler2D shadow_pass;
  7395. uniform vec2 resolution;
  7396. uniform float radius;
  7397. #include <packing>
  7398. void main() {
  7399. const float samples = float( VSM_SAMPLES );
  7400. float mean = 0.0;
  7401. float squared_mean = 0.0;
  7402. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  7403. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  7404. for ( float i = 0.0; i < samples; i ++ ) {
  7405. float uvOffset = uvStart + i * uvStride;
  7406. #ifdef HORIZONTAL_PASS
  7407. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  7408. mean += distribution.x;
  7409. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  7410. #else
  7411. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  7412. mean += depth;
  7413. squared_mean += depth * depth;
  7414. #endif
  7415. }
  7416. mean = mean / samples;
  7417. squared_mean = squared_mean / samples;
  7418. float std_dev = sqrt( squared_mean - mean * mean );
  7419. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  7420. }`;function mEe(t,e,n){let a=new IT;const i=new Wn,s=new Wn,o=new la,l=new lEe({depthPacking:KCe}),c=new cEe,d={},u=n.maxTextureSize,m={[Qh]:Ko,[Ko]:Qh,[xm]:xm},p=new Yh({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Wn},radius:{value:4}},vertexShader:dEe,fragmentShader:uEe}),f=p.clone();f.defines.HORIZONTAL_PASS=1;const g=new io;g.setAttribute("position",new _l(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const w=new cd(g,p),b=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=JJ;let x=this.type;this.render=function(P,T,A){if(b.enabled===!1||b.autoUpdate===!1&&b.needsUpdate===!1||P.length===0)return;const F=t.getRenderTarget(),_=t.getActiveCubeFace(),M=t.getActiveMipmapLevel(),H=t.state;H.setBlending(Lh),H.buffers.color.setClear(1,1,1,1),H.buffers.depth.setTest(!0),H.setScissorTest(!1);const I=x!==um&&this.type===um,z=x===um&&this.type!==um;for(let L=0,Z=P.length;L<Z;L++){const ne=P[L],Y=ne.shadow;if(Y===void 0){console.warn("THREE.WebGLShadowMap:",ne,"has no shadow.");continue}if(Y.autoUpdate===!1&&Y.needsUpdate===!1)continue;i.copy(Y.mapSize);const ce=Y.getFrameExtents();if(i.multiply(ce),s.copy(Y.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/ce.x),i.x=s.x*ce.x,Y.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/ce.y),i.y=s.y*ce.y,Y.mapSize.y=s.y)),Y.map===null||I===!0||z===!0){const oe=this.type!==um?{minFilter:js,magFilter:js}:{};Y.map!==null&&Y.map.dispose(),Y.map=new Og(i.x,i.y,oe),Y.map.texture.name=ne.name+".shadowMap",Y.camera.updateProjectionMatrix()}t.setRenderTarget(Y.map),t.clear();const ue=Y.getViewportCount();for(let oe=0;oe<ue;oe++){const Q=Y.getViewport(oe);o.set(s.x*Q.x,s.y*Q.y,s.x*Q.z,s.y*Q.w),H.viewport(o),Y.updateMatrices(ne,oe),a=Y.getFrustum(),C(T,A,Y.camera,ne,this.type)}Y.isPointLightShadow!==!0&&this.type===um&&S(Y,A),Y.needsUpdate=!1}x=this.type,b.needsUpdate=!1,t.setRenderTarget(F,_,M)};function S(P,T){const A=e.update(w);p.defines.VSM_SAMPLES!==P.blurSamples&&(p.defines.VSM_SAMPLES=P.blurSamples,f.defines.VSM_SAMPLES=P.blurSamples,p.needsUpdate=!0,f.needsUpdate=!0),P.mapPass===null&&(P.mapPass=new Og(i.x,i.y)),p.uniforms.shadow_pass.value=P.map.texture,p.uniforms.resolution.value=P.mapSize,p.uniforms.radius.value=P.radius,t.setRenderTarget(P.mapPass),t.clear(),t.renderBufferDirect(T,null,A,p,w,null),f.uniforms.shadow_pass.value=P.mapPass.texture,f.uniforms.resolution.value=P.mapSize,f.uniforms.radius.value=P.radius,t.setRenderTarget(P.map),t.clear(),t.renderBufferDirect(T,null,A,f,w,null)}function k(P,T,A,F){let _=null;const M=A.isPointLight===!0?P.customDistanceMaterial:P.customDepthMaterial;if(M!==void 0)_=M;else if(_=A.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){const H=_.uuid,I=T.uuid;let z=d[H];z===void 0&&(z={},d[H]=z);let L=z[I];L===void 0&&(L=_.clone(),z[I]=L),_=L}if(_.visible=T.visible,_.wireframe=T.wireframe,F===um?_.side=T.shadowSide!==null?T.shadowSide:T.side:_.side=T.shadowSide!==null?T.shadowSide:m[T.side],_.alphaMap=T.alphaMap,_.alphaTest=T.alphaTest,_.map=T.map,_.clipShadows=T.clipShadows,_.clippingPlanes=T.clippingPlanes,_.clipIntersection=T.clipIntersection,_.displacementMap=T.displacementMap,_.displacementScale=T.displacementScale,_.displacementBias=T.displacementBias,_.wireframeLinewidth=T.wireframeLinewidth,_.linewidth=T.linewidth,A.isPointLight===!0&&_.isMeshDistanceMaterial===!0){const H=t.properties.get(_);H.light=A}return _}function C(P,T,A,F,_){if(P.visible===!1)return;if(P.layers.test(T.layers)&&(P.isMesh||P.isLine||P.isPoints)&&(P.castShadow||P.receiveShadow&&_===um)&&(!P.frustumCulled||a.intersectsObject(P))){P.modelViewMatrix.multiplyMatrices(A.matrixWorldInverse,P.matrixWorld);const I=e.update(P),z=P.material;if(Array.isArray(z)){const L=I.groups;for(let Z=0,ne=L.length;Z<ne;Z++){const Y=L[Z],ce=z[Y.materialIndex];if(ce&&ce.visible){const ue=k(P,ce,F,_);P.onBeforeShadow(t,P,T,A,I,ue,Y),t.renderBufferDirect(A,null,I,ue,P,Y),P.onAfterShadow(t,P,T,A,I,ue,Y)}}}else if(z.visible){const L=k(P,z,F,_);P.onBeforeShadow(t,P,T,A,I,L,null),t.renderBufferDirect(A,null,I,L,P,null),P.onAfterShadow(t,P,T,A,I,L,null)}}const H=P.children;for(let I=0,z=H.length;I<z;I++)C(H[I],T,A,F,_)}}function pEe(t,e,n){const a=n.isWebGL2;function i(){let Ce=!1;const Ze=new la;let Ie=null;const ke=new la(0,0,0,0);return{setMask:function(Ve){Ie!==Ve&&!Ce&&(t.colorMask(Ve,Ve,Ve,Ve),Ie=Ve)},setLocked:function(Ve){Ce=Ve},setClear:function(Ve,rt,Qe,Te,tt){tt===!0&&(Ve*=Te,rt*=Te,Qe*=Te),Ze.set(Ve,rt,Qe,Te),ke.equals(Ze)===!1&&(t.clearColor(Ve,rt,Qe,Te),ke.copy(Ze))},reset:function(){Ce=!1,Ie=null,ke.set(-1,0,0,0)}}}function s(){let Ce=!1,Ze=null,Ie=null,ke=null;return{setTest:function(Ve){Ve?E(t.DEPTH_TEST):B(t.DEPTH_TEST)},setMask:function(Ve){Ze!==Ve&&!Ce&&(t.depthMask(Ve),Ze=Ve)},setFunc:function(Ve){if(Ie!==Ve){switch(Ve){case kCe:t.depthFunc(t.NEVER);break;case NCe:t.depthFunc(t.ALWAYS);break;case CCe:t.depthFunc(t.LESS);break;case hC:t.depthFunc(t.LEQUAL);break;case PCe:t.depthFunc(t.EQUAL);break;case TCe:t.depthFunc(t.GEQUAL);break;case ACe:t.depthFunc(t.GREATER);break;case jCe:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Ie=Ve}},setLocked:function(Ve){Ce=Ve},setClear:function(Ve){ke!==Ve&&(t.clearDepth(Ve),ke=Ve)},reset:function(){Ce=!1,Ze=null,Ie=null,ke=null}}}function o(){let Ce=!1,Ze=null,Ie=null,ke=null,Ve=null,rt=null,Qe=null,Te=null,tt=null;return{setTest:function(ot){Ce||(ot?E(t.STENCIL_TEST):B(t.STENCIL_TEST))},setMask:function(ot){Ze!==ot&&!Ce&&(t.stencilMask(ot),Ze=ot)},setFunc:function(ot,Tt,Ut){(Ie!==ot||ke!==Tt||Ve!==Ut)&&(t.stencilFunc(ot,Tt,Ut),Ie=ot,ke=Tt,Ve=Ut)},setOp:function(ot,Tt,Ut){(rt!==ot||Qe!==Tt||Te!==Ut)&&(t.stencilOp(ot,Tt,Ut),rt=ot,Qe=Tt,Te=Ut)},setLocked:function(ot){Ce=ot},setClear:function(ot){tt!==ot&&(t.clearStencil(ot),tt=ot)},reset:function(){Ce=!1,Ze=null,Ie=null,ke=null,Ve=null,rt=null,Qe=null,Te=null,tt=null}}}const l=new i,c=new s,d=new o,u=new WeakMap,m=new WeakMap;let p={},f={},g=new WeakMap,w=[],b=null,x=!1,S=null,k=null,C=null,P=null,T=null,A=null,F=null,_=new On(0,0,0),M=0,H=!1,I=null,z=null,L=null,Z=null,ne=null;const Y=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let ce=!1,ue=0;const oe=t.getParameter(t.VERSION);oe.indexOf("WebGL")!==-1?(ue=parseFloat(/^WebGL (\d)/.exec(oe)[1]),ce=ue>=1):oe.indexOf("OpenGL ES")!==-1&&(ue=parseFloat(/^OpenGL ES (\d)/.exec(oe)[1]),ce=ue>=2);let Q=null,le={};const pe=t.getParameter(t.SCISSOR_BOX),he=t.getParameter(t.VIEWPORT),we=new la().fromArray(pe),$=new la().fromArray(he);function J(Ce,Ze,Ie,ke){const Ve=new Uint8Array(4),rt=t.createTexture();t.bindTexture(Ce,rt),t.texParameteri(Ce,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Ce,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let Qe=0;Qe<Ie;Qe++)a&&(Ce===t.TEXTURE_3D||Ce===t.TEXTURE_2D_ARRAY)?t.texImage3D(Ze,0,t.RGBA,1,1,ke,0,t.RGBA,t.UNSIGNED_BYTE,Ve):t.texImage2D(Ze+Qe,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Ve);return rt}const j={};j[t.TEXTURE_2D]=J(t.TEXTURE_2D,t.TEXTURE_2D,1),j[t.TEXTURE_CUBE_MAP]=J(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),a&&(j[t.TEXTURE_2D_ARRAY]=J(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),j[t.TEXTURE_3D]=J(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),l.setClear(0,0,0,1),c.setClear(1),d.setClear(0),E(t.DEPTH_TEST),c.setFunc(hC),se(!1),te(Uq),E(t.CULL_FACE),K(Lh);function E(Ce){p[Ce]!==!0&&(t.enable(Ce),p[Ce]=!0)}function B(Ce){p[Ce]!==!1&&(t.disable(Ce),p[Ce]=!1)}function W(Ce,Ze){return f[Ce]!==Ze?(t.bindFramebuffer(Ce,Ze),f[Ce]=Ze,a&&(Ce===t.DRAW_FRAMEBUFFER&&(f[t.FRAMEBUFFER]=Ze),Ce===t.FRAMEBUFFER&&(f[t.DRAW_FRAMEBUFFER]=Ze)),!0):!1}function O(Ce,Ze){let Ie=w,ke=!1;if(Ce)if(Ie=g.get(Ze),Ie===void 0&&(Ie=[],g.set(Ze,Ie)),Ce.isWebGLMultipleRenderTargets){const Ve=Ce.texture;if(Ie.length!==Ve.length||Ie[0]!==t.COLOR_ATTACHMENT0){for(let rt=0,Qe=Ve.length;rt<Qe;rt++)Ie[rt]=t.COLOR_ATTACHMENT0+rt;Ie.length=Ve.length,ke=!0}}else Ie[0]!==t.COLOR_ATTACHMENT0&&(Ie[0]=t.COLOR_ATTACHMENT0,ke=!0);else Ie[0]!==t.BACK&&(Ie[0]=t.BACK,ke=!0);ke&&(n.isWebGL2?t.drawBuffers(Ie):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(Ie))}function ie(Ce){return b!==Ce?(t.useProgram(Ce),b=Ce,!0):!1}const U={[eg]:t.FUNC_ADD,[cCe]:t.FUNC_SUBTRACT,[dCe]:t.FUNC_REVERSE_SUBTRACT};if(a)U[$q]=t.MIN,U[Vq]=t.MAX;else{const Ce=e.get("EXT_blend_minmax");Ce!==null&&(U[$q]=Ce.MIN_EXT,U[Vq]=Ce.MAX_EXT)}const G={[uCe]:t.ZERO,[mCe]:t.ONE,[pCe]:t.SRC_COLOR,[WL]:t.SRC_ALPHA,[yCe]:t.SRC_ALPHA_SATURATE,[bCe]:t.DST_COLOR,[fCe]:t.DST_ALPHA,[hCe]:t.ONE_MINUS_SRC_COLOR,[KL]:t.ONE_MINUS_SRC_ALPHA,[xCe]:t.ONE_MINUS_DST_COLOR,[gCe]:t.ONE_MINUS_DST_ALPHA,[vCe]:t.CONSTANT_COLOR,[wCe]:t.ONE_MINUS_CONSTANT_COLOR,[SCe]:t.CONSTANT_ALPHA,[_Ce]:t.ONE_MINUS_CONSTANT_ALPHA};function K(Ce,Ze,Ie,ke,Ve,rt,Qe,Te,tt,ot){if(Ce===Lh){x===!0&&(B(t.BLEND),x=!1);return}if(x===!1&&(E(t.BLEND),x=!0),Ce!==lCe){if(Ce!==S||ot!==H){if((k!==eg||T!==eg)&&(t.blendEquation(t.FUNC_ADD),k=eg,T=eg),ot)switch(Ce){case sy:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case Bq:t.blendFunc(t.ONE,t.ONE);break;case Hq:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case qq:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",Ce);break}else switch(Ce){case sy:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case Bq:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case Hq:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case qq:t.blendFunc(t.ZERO,t.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",Ce);break}C=null,P=null,A=null,F=null,_.set(0,0,0),M=0,S=Ce,H=ot}return}Ve=Ve||Ze,rt=rt||Ie,Qe=Qe||ke,(Ze!==k||Ve!==T)&&(t.blendEquationSeparate(U[Ze],U[Ve]),k=Ze,T=Ve),(Ie!==C||ke!==P||rt!==A||Qe!==F)&&(t.blendFuncSeparate(G[Ie],G[ke],G[rt],G[Qe]),C=Ie,P=ke,A=rt,F=Qe),(Te.equals(_)===!1||tt!==M)&&(t.blendColor(Te.r,Te.g,Te.b,tt),_.copy(Te),M=tt),S=Ce,H=!1}function X(Ce,Ze){Ce.side===xm?B(t.CULL_FACE):E(t.CULL_FACE);let Ie=Ce.side===Ko;Ze&&(Ie=!Ie),se(Ie),Ce.blending===sy&&Ce.transparent===!1?K(Lh):K(Ce.blending,Ce.blendEquation,Ce.blendSrc,Ce.blendDst,Ce.blendEquationAlpha,Ce.blendSrcAlpha,Ce.blendDstAlpha,Ce.blendColor,Ce.blendAlpha,Ce.premultipliedAlpha),c.setFunc(Ce.depthFunc),c.setTest(Ce.depthTest),c.setMask(Ce.depthWrite),l.setMask(Ce.colorWrite);const ke=Ce.stencilWrite;d.setTest(ke),ke&&(d.setMask(Ce.stencilWriteMask),d.setFunc(Ce.stencilFunc,Ce.stencilRef,Ce.stencilFuncMask),d.setOp(Ce.stencilFail,Ce.stencilZFail,Ce.stencilZPass)),de(Ce.polygonOffset,Ce.polygonOffsetFactor,Ce.polygonOffsetUnits),Ce.alphaToCoverage===!0?E(t.SAMPLE_ALPHA_TO_COVERAGE):B(t.SAMPLE_ALPHA_TO_COVERAGE)}function se(Ce){I!==Ce&&(Ce?t.frontFace(t.CW):t.frontFace(t.CCW),I=Ce)}function te(Ce){Ce!==iCe?(E(t.CULL_FACE),Ce!==z&&(Ce===Uq?t.cullFace(t.BACK):Ce===sCe?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):B(t.CULL_FACE),z=Ce}function fe(Ce){Ce!==L&&(ce&&t.lineWidth(Ce),L=Ce)}function de(Ce,Ze,Ie){Ce?(E(t.POLYGON_OFFSET_FILL),(Z!==Ze||ne!==Ie)&&(t.polygonOffset(Ze,Ie),Z=Ze,ne=Ie)):B(t.POLYGON_OFFSET_FILL)}function me(Ce){Ce?E(t.SCISSOR_TEST):B(t.SCISSOR_TEST)}function q(Ce){Ce===void 0&&(Ce=t.TEXTURE0+Y-1),Q!==Ce&&(t.activeTexture(Ce),Q=Ce)}function R(Ce,Ze,Ie){Ie===void 0&&(Q===null?Ie=t.TEXTURE0+Y-1:Ie=Q);let ke=le[Ie];ke===void 0&&(ke={type:void 0,texture:void 0},le[Ie]=ke),(ke.type!==Ce||ke.texture!==Ze)&&(Q!==Ie&&(t.activeTexture(Ie),Q=Ie),t.bindTexture(Ce,Ze||j[Ce]),ke.type=Ce,ke.texture=Ze)}function re(){const Ce=le[Q];Ce!==void 0&&Ce.type!==void 0&&(t.bindTexture(Ce.type,null),Ce.type=void 0,Ce.texture=void 0)}function be(){try{t.compressedTexImage2D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function ye(){try{t.compressedTexImage3D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function _e(){try{t.texSubImage2D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function xe(){try{t.texSubImage3D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function ge(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function Me(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function Be(){try{t.texStorage2D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function Fe(){try{t.texStorage3D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function Oe(){try{t.texImage2D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function Re(){try{t.texImage3D.apply(t,arguments)}catch(Ce){console.error("THREE.WebGLState:",Ce)}}function We(Ce){we.equals(Ce)===!1&&(t.scissor(Ce.x,Ce.y,Ce.z,Ce.w),we.copy(Ce))}function ze(Ce){$.equals(Ce)===!1&&(t.viewport(Ce.x,Ce.y,Ce.z,Ce.w),$.copy(Ce))}function st(Ce,Ze){let Ie=m.get(Ze);Ie===void 0&&(Ie=new WeakMap,m.set(Ze,Ie));let ke=Ie.get(Ce);ke===void 0&&(ke=t.getUniformBlockIndex(Ze,Ce.name),Ie.set(Ce,ke))}function Ee(Ce,Ze){const ke=m.get(Ze).get(Ce);u.get(Ze)!==ke&&(t.uniformBlockBinding(Ze,ke,Ce.__bindingPointIndex),u.set(Ze,ke))}function it(){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),a===!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={},Q=null,le={},f={},g=new WeakMap,w=[],b=null,x=!1,S=null,k=null,C=null,P=null,T=null,A=null,F=null,_=new On(0,0,0),M=0,H=!1,I=null,z=null,L=null,Z=null,ne=null,we.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:E,disable:B,bindFramebuffer:W,drawBuffers:O,useProgram:ie,setBlending:K,setMaterial:X,setFlipSided:se,setCullFace:te,setLineWidth:fe,setPolygonOffset:de,setScissorTest:me,activeTexture:q,bindTexture:R,unbindTexture:re,compressedTexImage2D:be,compressedTexImage3D:ye,texImage2D:Oe,texImage3D:Re,updateUBOMapping:st,uniformBlockBinding:Ee,texStorage2D:Be,texStorage3D:Fe,texSubImage2D:_e,texSubImage3D:xe,compressedTexSubImage2D:ge,compressedTexSubImage3D:Me,scissor:We,viewport:ze,reset:it}}function hEe(t,e,n,a,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),g=new WeakMap;let w;const b=new WeakMap;let x=!1;try{x=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function S(q,R){return x?new OffscreenCanvas(q,R):yC("canvas")}function k(q,R,re,be){let ye=1;if((q.width>be||q.height>be)&&(ye=be/Math.max(q.width,q.height)),ye<1||R===!0)if(typeof HTMLImageElement<"u"&&q instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&q instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&q instanceof ImageBitmap){const _e=R?xC:Math.floor,xe=_e(ye*q.width),ge=_e(ye*q.height);w===void 0&&(w=S(xe,ge));const Me=re?S(xe,ge):w;return Me.width=xe,Me.height=ge,Me.getContext("2d").drawImage(q,0,0,xe,ge),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+q.width+"x"+q.height+") to ("+xe+"x"+ge+")."),Me}else return"data"in q&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+q.width+"x"+q.height+")."),q;return q}function C(q){return tR(q.width)&&tR(q.height)}function P(q){return l?!1:q.wrapS!==rd||q.wrapT!==rd||q.minFilter!==js&&q.minFilter!==ic}function T(q,R){return q.generateMipmaps&&R&&q.minFilter!==js&&q.minFilter!==ic}function A(q){t.generateMipmap(q)}function F(q,R,re,be,ye=!1){if(l===!1)return R;if(q!==null){if(t[q]!==void 0)return t[q];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+q+"'")}let _e=R;if(R===t.RED&&(re===t.FLOAT&&(_e=t.R32F),re===t.HALF_FLOAT&&(_e=t.R16F),re===t.UNSIGNED_BYTE&&(_e=t.R8)),R===t.RED_INTEGER&&(re===t.UNSIGNED_BYTE&&(_e=t.R8UI),re===t.UNSIGNED_SHORT&&(_e=t.R16UI),re===t.UNSIGNED_INT&&(_e=t.R32UI),re===t.BYTE&&(_e=t.R8I),re===t.SHORT&&(_e=t.R16I),re===t.INT&&(_e=t.R32I)),R===t.RG&&(re===t.FLOAT&&(_e=t.RG32F),re===t.HALF_FLOAT&&(_e=t.RG16F),re===t.UNSIGNED_BYTE&&(_e=t.RG8)),R===t.RGBA){const xe=ye?fC:sa.getTransfer(be);re===t.FLOAT&&(_e=t.RGBA32F),re===t.HALF_FLOAT&&(_e=t.RGBA16F),re===t.UNSIGNED_BYTE&&(_e=xe===Ta?t.SRGB8_ALPHA8:t.RGBA8),re===t.UNSIGNED_SHORT_4_4_4_4&&(_e=t.RGBA4),re===t.UNSIGNED_SHORT_5_5_5_1&&(_e=t.RGB5_A1)}return(_e===t.R16F||_e===t.R32F||_e===t.RG16F||_e===t.RG32F||_e===t.RGBA16F||_e===t.RGBA32F)&&e.get("EXT_color_buffer_float"),_e}function _(q,R,re){return T(q,re)===!0||q.isFramebufferTexture&&q.minFilter!==js&&q.minFilter!==ic?Math.log2(Math.max(R.width,R.height))+1:q.mipmaps!==void 0&&q.mipmaps.length>0?q.mipmaps.length:q.isCompressedTexture&&Array.isArray(q.image)?R.mipmaps.length:1}function M(q){return q===js||q===Gq||q===VE?t.NEAREST:t.LINEAR}function H(q){const R=q.target;R.removeEventListener("dispose",H),z(R),R.isVideoTexture&&g.delete(R)}function I(q){const R=q.target;R.removeEventListener("dispose",I),Z(R)}function z(q){const R=a.get(q);if(R.__webglInit===void 0)return;const re=q.source,be=b.get(re);if(be){const ye=be[R.__cacheKey];ye.usedTimes--,ye.usedTimes===0&&L(q),Object.keys(be).length===0&&b.delete(re)}a.remove(q)}function L(q){const R=a.get(q);t.deleteTexture(R.__webglTexture);const re=q.source,be=b.get(re);delete be[R.__cacheKey],o.memory.textures--}function Z(q){const R=q.texture,re=a.get(q),be=a.get(R);if(be.__webglTexture!==void 0&&(t.deleteTexture(be.__webglTexture),o.memory.textures--),q.depthTexture&&q.depthTexture.dispose(),q.isWebGLCubeRenderTarget)for(let ye=0;ye<6;ye++){if(Array.isArray(re.__webglFramebuffer[ye]))for(let _e=0;_e<re.__webglFramebuffer[ye].length;_e++)t.deleteFramebuffer(re.__webglFramebuffer[ye][_e]);else t.deleteFramebuffer(re.__webglFramebuffer[ye]);re.__webglDepthbuffer&&t.deleteRenderbuffer(re.__webglDepthbuffer[ye])}else{if(Array.isArray(re.__webglFramebuffer))for(let ye=0;ye<re.__webglFramebuffer.length;ye++)t.deleteFramebuffer(re.__webglFramebuffer[ye]);else t.deleteFramebuffer(re.__webglFramebuffer);if(re.__webglDepthbuffer&&t.deleteRenderbuffer(re.__webglDepthbuffer),re.__webglMultisampledFramebuffer&&t.deleteFramebuffer(re.__webglMultisampledFramebuffer),re.__webglColorRenderbuffer)for(let ye=0;ye<re.__webglColorRenderbuffer.length;ye++)re.__webglColorRenderbuffer[ye]&&t.deleteRenderbuffer(re.__webglColorRenderbuffer[ye]);re.__webglDepthRenderbuffer&&t.deleteRenderbuffer(re.__webglDepthRenderbuffer)}if(q.isWebGLMultipleRenderTargets)for(let ye=0,_e=R.length;ye<_e;ye++){const xe=a.get(R[ye]);xe.__webglTexture&&(t.deleteTexture(xe.__webglTexture),o.memory.textures--),a.remove(R[ye])}a.remove(R),a.remove(q)}let ne=0;function Y(){ne=0}function ce(){const q=ne;return q>=c&&console.warn("THREE.WebGLTextures: Trying to use "+q+" texture units while this GPU supports only "+c),ne+=1,q}function ue(q){const R=[];return R.push(q.wrapS),R.push(q.wrapT),R.push(q.wrapR||0),R.push(q.magFilter),R.push(q.minFilter),R.push(q.anisotropy),R.push(q.internalFormat),R.push(q.format),R.push(q.type),R.push(q.generateMipmaps),R.push(q.premultiplyAlpha),R.push(q.flipY),R.push(q.unpackAlignment),R.push(q.colorSpace),R.join()}function oe(q,R){const re=a.get(q);if(q.isVideoTexture&&de(q),q.isRenderTargetTexture===!1&&q.version>0&&re.__version!==q.version){const be=q.image;if(be===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(be.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{E(re,q,R);return}}n.bindTexture(t.TEXTURE_2D,re.__webglTexture,t.TEXTURE0+R)}function Q(q,R){const re=a.get(q);if(q.version>0&&re.__version!==q.version){E(re,q,R);return}n.bindTexture(t.TEXTURE_2D_ARRAY,re.__webglTexture,t.TEXTURE0+R)}function le(q,R){const re=a.get(q);if(q.version>0&&re.__version!==q.version){E(re,q,R);return}n.bindTexture(t.TEXTURE_3D,re.__webglTexture,t.TEXTURE0+R)}function pe(q,R){const re=a.get(q);if(q.version>0&&re.__version!==q.version){B(re,q,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,re.__webglTexture,t.TEXTURE0+R)}const he={[XL]:t.REPEAT,[rd]:t.CLAMP_TO_EDGE,[ZL]:t.MIRRORED_REPEAT},we={[js]:t.NEAREST,[Gq]:t.NEAREST_MIPMAP_NEAREST,[VE]:t.NEAREST_MIPMAP_LINEAR,[ic]:t.LINEAR,[OCe]:t.LINEAR_MIPMAP_NEAREST,[Bw]:t.LINEAR_MIPMAP_LINEAR},$={[YCe]:t.NEVER,[nPe]:t.ALWAYS,[XCe]:t.LESS,[dee]:t.LEQUAL,[ZCe]:t.EQUAL,[tPe]:t.GEQUAL,[JCe]:t.GREATER,[ePe]:t.NOTEQUAL};function J(q,R,re){if(re?(t.texParameteri(q,t.TEXTURE_WRAP_S,he[R.wrapS]),t.texParameteri(q,t.TEXTURE_WRAP_T,he[R.wrapT]),(q===t.TEXTURE_3D||q===t.TEXTURE_2D_ARRAY)&&t.texParameteri(q,t.TEXTURE_WRAP_R,he[R.wrapR]),t.texParameteri(q,t.TEXTURE_MAG_FILTER,we[R.magFilter]),t.texParameteri(q,t.TEXTURE_MIN_FILTER,we[R.minFilter])):(t.texParameteri(q,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(q,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(q===t.TEXTURE_3D||q===t.TEXTURE_2D_ARRAY)&&t.texParameteri(q,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(R.wrapS!==rd||R.wrapT!==rd)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(q,t.TEXTURE_MAG_FILTER,M(R.magFilter)),t.texParameteri(q,t.TEXTURE_MIN_FILTER,M(R.minFilter)),R.minFilter!==js&&R.minFilter!==ic&&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(q,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(q,t.TEXTURE_COMPARE_FUNC,$[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const be=e.get("EXT_texture_filter_anisotropic");if(R.magFilter===js||R.minFilter!==VE&&R.minFilter!==Bw||R.type===km&&e.has("OES_texture_float_linear")===!1||l===!1&&R.type===Hw&&e.has("OES_texture_half_float_linear")===!1)return;(R.anisotropy>1||a.get(R).__currentAnisotropy)&&(t.texParameterf(q,be.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,i.getMaxAnisotropy())),a.get(R).__currentAnisotropy=R.anisotropy)}}function j(q,R){let re=!1;q.__webglInit===void 0&&(q.__webglInit=!0,R.addEventListener("dispose",H));const be=R.source;let ye=b.get(be);ye===void 0&&(ye={},b.set(be,ye));const _e=ue(R);if(_e!==q.__cacheKey){ye[_e]===void 0&&(ye[_e]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,re=!0),ye[_e].usedTimes++;const xe=ye[q.__cacheKey];xe!==void 0&&(ye[q.__cacheKey].usedTimes--,xe.usedTimes===0&&L(R)),q.__cacheKey=_e,q.__webglTexture=ye[_e].texture}return re}function E(q,R,re){let be=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(be=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(be=t.TEXTURE_3D);const ye=j(q,R),_e=R.source;n.bindTexture(be,q.__webglTexture,t.TEXTURE0+re);const xe=a.get(_e);if(_e.version!==xe.__version||ye===!0){n.activeTexture(t.TEXTURE0+re);const ge=sa.getPrimaries(sa.workingColorSpace),Me=R.colorSpace===oc?null:sa.getPrimaries(R.colorSpace),Be=R.colorSpace===oc||ge===Me?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,Be);const Fe=P(R)&&C(R.image)===!1;let Oe=k(R.image,Fe,!1,u);Oe=me(R,Oe);const Re=C(Oe)||l,We=s.convert(R.format,R.colorSpace);let ze=s.convert(R.type),st=F(R.internalFormat,We,ze,R.colorSpace,R.isVideoTexture);J(be,R,Re);let Ee;const it=R.mipmaps,Ce=l&&R.isVideoTexture!==!0&&st!==oee,Ze=xe.__version===void 0||ye===!0,Ie=_(R,Oe,Re);if(R.isDepthTexture)st=t.DEPTH_COMPONENT,l?R.type===km?st=t.DEPTH_COMPONENT32F:R.type===yh?st=t.DEPTH_COMPONENT24:R.type===fg?st=t.DEPTH24_STENCIL8:st=t.DEPTH_COMPONENT16:R.type===km&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),R.format===gg&&st===t.DEPTH_COMPONENT&&R.type!==YO&&R.type!==yh&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),R.type=yh,ze=s.convert(R.type)),R.format===Cy&&st===t.DEPTH_COMPONENT&&(st=t.DEPTH_STENCIL,R.type!==fg&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),R.type=fg,ze=s.convert(R.type))),Ze&&(Ce?n.texStorage2D(t.TEXTURE_2D,1,st,Oe.width,Oe.height):n.texImage2D(t.TEXTURE_2D,0,st,Oe.width,Oe.height,0,We,ze,null));else if(R.isDataTexture)if(it.length>0&&Re){Ce&&Ze&&n.texStorage2D(t.TEXTURE_2D,Ie,st,it[0].width,it[0].height);for(let ke=0,Ve=it.length;ke<Ve;ke++)Ee=it[ke],Ce?n.texSubImage2D(t.TEXTURE_2D,ke,0,0,Ee.width,Ee.height,We,ze,Ee.data):n.texImage2D(t.TEXTURE_2D,ke,st,Ee.width,Ee.height,0,We,ze,Ee.data);R.generateMipmaps=!1}else Ce?(Ze&&n.texStorage2D(t.TEXTURE_2D,Ie,st,Oe.width,Oe.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,Oe.width,Oe.height,We,ze,Oe.data)):n.texImage2D(t.TEXTURE_2D,0,st,Oe.width,Oe.height,0,We,ze,Oe.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){Ce&&Ze&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ie,st,it[0].width,it[0].height,Oe.depth);for(let ke=0,Ve=it.length;ke<Ve;ke++)Ee=it[ke],R.format!==sc?We!==null?Ce?n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,ke,0,0,0,Ee.width,Ee.height,Oe.depth,We,Ee.data,0,0):n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,ke,st,Ee.width,Ee.height,Oe.depth,0,Ee.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ce?n.texSubImage3D(t.TEXTURE_2D_ARRAY,ke,0,0,0,Ee.width,Ee.height,Oe.depth,We,ze,Ee.data):n.texImage3D(t.TEXTURE_2D_ARRAY,ke,st,Ee.width,Ee.height,Oe.depth,0,We,ze,Ee.data)}else{Ce&&Ze&&n.texStorage2D(t.TEXTURE_2D,Ie,st,it[0].width,it[0].height);for(let ke=0,Ve=it.length;ke<Ve;ke++)Ee=it[ke],R.format!==sc?We!==null?Ce?n.compressedTexSubImage2D(t.TEXTURE_2D,ke,0,0,Ee.width,Ee.height,We,Ee.data):n.compressedTexImage2D(t.TEXTURE_2D,ke,st,Ee.width,Ee.height,0,Ee.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ce?n.texSubImage2D(t.TEXTURE_2D,ke,0,0,Ee.width,Ee.height,We,ze,Ee.data):n.texImage2D(t.TEXTURE_2D,ke,st,Ee.width,Ee.height,0,We,ze,Ee.data)}else if(R.isDataArrayTexture)Ce?(Ze&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ie,st,Oe.width,Oe.height,Oe.depth),n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,Oe.width,Oe.height,Oe.depth,We,ze,Oe.data)):n.texImage3D(t.TEXTURE_2D_ARRAY,0,st,Oe.width,Oe.height,Oe.depth,0,We,ze,Oe.data);else if(R.isData3DTexture)Ce?(Ze&&n.texStorage3D(t.TEXTURE_3D,Ie,st,Oe.width,Oe.height,Oe.depth),n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,Oe.width,Oe.height,Oe.depth,We,ze,Oe.data)):n.texImage3D(t.TEXTURE_3D,0,st,Oe.width,Oe.height,Oe.depth,0,We,ze,Oe.data);else if(R.isFramebufferTexture){if(Ze)if(Ce)n.texStorage2D(t.TEXTURE_2D,Ie,st,Oe.width,Oe.height);else{let ke=Oe.width,Ve=Oe.height;for(let rt=0;rt<Ie;rt++)n.texImage2D(t.TEXTURE_2D,rt,st,ke,Ve,0,We,ze,null),ke>>=1,Ve>>=1}}else if(it.length>0&&Re){Ce&&Ze&&n.texStorage2D(t.TEXTURE_2D,Ie,st,it[0].width,it[0].height);for(let ke=0,Ve=it.length;ke<Ve;ke++)Ee=it[ke],Ce?n.texSubImage2D(t.TEXTURE_2D,ke,0,0,We,ze,Ee):n.texImage2D(t.TEXTURE_2D,ke,st,We,ze,Ee);R.generateMipmaps=!1}else Ce?(Ze&&n.texStorage2D(t.TEXTURE_2D,Ie,st,Oe.width,Oe.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,We,ze,Oe)):n.texImage2D(t.TEXTURE_2D,0,st,We,ze,Oe);T(R,Re)&&A(be),xe.__version=_e.version,R.onUpdate&&R.onUpdate(R)}q.__version=R.version}function B(q,R,re){if(R.image.length!==6)return;const be=j(q,R),ye=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,q.__webglTexture,t.TEXTURE0+re);const _e=a.get(ye);if(ye.version!==_e.__version||be===!0){n.activeTexture(t.TEXTURE0+re);const xe=sa.getPrimaries(sa.workingColorSpace),ge=R.colorSpace===oc?null:sa.getPrimaries(R.colorSpace),Me=R.colorSpace===oc||xe===ge?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,Me);const Be=R.isCompressedTexture||R.image[0].isCompressedTexture,Fe=R.image[0]&&R.image[0].isDataTexture,Oe=[];for(let ke=0;ke<6;ke++)!Be&&!Fe?Oe[ke]=k(R.image[ke],!1,!0,d):Oe[ke]=Fe?R.image[ke].image:R.image[ke],Oe[ke]=me(R,Oe[ke]);const Re=Oe[0],We=C(Re)||l,ze=s.convert(R.format,R.colorSpace),st=s.convert(R.type),Ee=F(R.internalFormat,ze,st,R.colorSpace),it=l&&R.isVideoTexture!==!0,Ce=_e.__version===void 0||be===!0;let Ze=_(R,Re,We);J(t.TEXTURE_CUBE_MAP,R,We);let Ie;if(Be){it&&Ce&&n.texStorage2D(t.TEXTURE_CUBE_MAP,Ze,Ee,Re.width,Re.height);for(let ke=0;ke<6;ke++){Ie=Oe[ke].mipmaps;for(let Ve=0;Ve<Ie.length;Ve++){const rt=Ie[Ve];R.format!==sc?ze!==null?it?n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,0,0,rt.width,rt.height,ze,rt.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,Ee,rt.width,rt.height,0,rt.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):it?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,0,0,rt.width,rt.height,ze,st,rt.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve,Ee,rt.width,rt.height,0,ze,st,rt.data)}}}else{Ie=R.mipmaps,it&&Ce&&(Ie.length>0&&Ze++,n.texStorage2D(t.TEXTURE_CUBE_MAP,Ze,Ee,Oe[0].width,Oe[0].height));for(let ke=0;ke<6;ke++)if(Fe){it?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,Oe[ke].width,Oe[ke].height,ze,st,Oe[ke].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ee,Oe[ke].width,Oe[ke].height,0,ze,st,Oe[ke].data);for(let Ve=0;Ve<Ie.length;Ve++){const Qe=Ie[Ve].image[ke].image;it?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,0,0,Qe.width,Qe.height,ze,st,Qe.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,Ee,Qe.width,Qe.height,0,ze,st,Qe.data)}}else{it?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,0,0,ze,st,Oe[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,0,Ee,ze,st,Oe[ke]);for(let Ve=0;Ve<Ie.length;Ve++){const rt=Ie[Ve];it?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,0,0,ze,st,rt.image[ke]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+ke,Ve+1,Ee,ze,st,rt.image[ke])}}}T(R,We)&&A(t.TEXTURE_CUBE_MAP),_e.__version=ye.version,R.onUpdate&&R.onUpdate(R)}q.__version=R.version}function W(q,R,re,be,ye,_e){const xe=s.convert(re.format,re.colorSpace),ge=s.convert(re.type),Me=F(re.internalFormat,xe,ge,re.colorSpace);if(!a.get(R).__hasExternalTextures){const Fe=Math.max(1,R.width>>_e),Oe=Math.max(1,R.height>>_e);ye===t.TEXTURE_3D||ye===t.TEXTURE_2D_ARRAY?n.texImage3D(ye,_e,Me,Fe,Oe,R.depth,0,xe,ge,null):n.texImage2D(ye,_e,Me,Fe,Oe,0,xe,ge,null)}n.bindFramebuffer(t.FRAMEBUFFER,q),fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,be,ye,a.get(re).__webglTexture,0,te(R)):(ye===t.TEXTURE_2D||ye>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&ye<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,be,ye,a.get(re).__webglTexture,_e),n.bindFramebuffer(t.FRAMEBUFFER,null)}function O(q,R,re){if(t.bindRenderbuffer(t.RENDERBUFFER,q),R.depthBuffer&&!R.stencilBuffer){let be=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(re||fe(R)){const ye=R.depthTexture;ye&&ye.isDepthTexture&&(ye.type===km?be=t.DEPTH_COMPONENT32F:ye.type===yh&&(be=t.DEPTH_COMPONENT24));const _e=te(R);fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,_e,be,R.width,R.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,_e,be,R.width,R.height)}else t.renderbufferStorage(t.RENDERBUFFER,be,R.width,R.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,q)}else if(R.depthBuffer&&R.stencilBuffer){const be=te(R);re&&fe(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,be,t.DEPTH24_STENCIL8,R.width,R.height):fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,be,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,q)}else{const be=R.isWebGLMultipleRenderTargets===!0?R.texture:[R.texture];for(let ye=0;ye<be.length;ye++){const _e=be[ye],xe=s.convert(_e.format,_e.colorSpace),ge=s.convert(_e.type),Me=F(_e.internalFormat,xe,ge,_e.colorSpace),Be=te(R);re&&fe(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Be,Me,R.width,R.height):fe(R)?p.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Be,Me,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Me,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function ie(q,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,q),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!a.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 be=a.get(R.depthTexture).__webglTexture,ye=te(R);if(R.depthTexture.format===gg)fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,be,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,be,0);else if(R.depthTexture.format===Cy)fe(R)?p.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,be,0,ye):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,be,0);else throw new Error("Unknown depthTexture format")}function U(q){const R=a.get(q),re=q.isWebGLCubeRenderTarget===!0;if(q.depthTexture&&!R.__autoAllocateDepthBuffer){if(re)throw new Error("target.depthTexture not supported in Cube render targets");ie(R.__webglFramebuffer,q)}else if(re){R.__webglDepthbuffer=[];for(let be=0;be<6;be++)n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[be]),R.__webglDepthbuffer[be]=t.createRenderbuffer(),O(R.__webglDepthbuffer[be],q,!1)}else n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer=t.createRenderbuffer(),O(R.__webglDepthbuffer,q,!1);n.bindFramebuffer(t.FRAMEBUFFER,null)}function G(q,R,re){const be=a.get(q);R!==void 0&&W(be.__webglFramebuffer,q,q.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),re!==void 0&&U(q)}function K(q){const R=q.texture,re=a.get(q),be=a.get(R);q.addEventListener("dispose",I),q.isWebGLMultipleRenderTargets!==!0&&(be.__webglTexture===void 0&&(be.__webglTexture=t.createTexture()),be.__version=R.version,o.memory.textures++);const ye=q.isWebGLCubeRenderTarget===!0,_e=q.isWebGLMultipleRenderTargets===!0,xe=C(q)||l;if(ye){re.__webglFramebuffer=[];for(let ge=0;ge<6;ge++)if(l&&R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer[ge]=[];for(let Me=0;Me<R.mipmaps.length;Me++)re.__webglFramebuffer[ge][Me]=t.createFramebuffer()}else re.__webglFramebuffer[ge]=t.createFramebuffer()}else{if(l&&R.mipmaps&&R.mipmaps.length>0){re.__webglFramebuffer=[];for(let ge=0;ge<R.mipmaps.length;ge++)re.__webglFramebuffer[ge]=t.createFramebuffer()}else re.__webglFramebuffer=t.createFramebuffer();if(_e)if(i.drawBuffers){const ge=q.texture;for(let Me=0,Be=ge.length;Me<Be;Me++){const Fe=a.get(ge[Me]);Fe.__webglTexture===void 0&&(Fe.__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&&q.samples>0&&fe(q)===!1){const ge=_e?R:[R];re.__webglMultisampledFramebuffer=t.createFramebuffer(),re.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,re.__webglMultisampledFramebuffer);for(let Me=0;Me<ge.length;Me++){const Be=ge[Me];re.__webglColorRenderbuffer[Me]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,re.__webglColorRenderbuffer[Me]);const Fe=s.convert(Be.format,Be.colorSpace),Oe=s.convert(Be.type),Re=F(Be.internalFormat,Fe,Oe,Be.colorSpace,q.isXRRenderTarget===!0),We=te(q);t.renderbufferStorageMultisample(t.RENDERBUFFER,We,Re,q.width,q.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Me,t.RENDERBUFFER,re.__webglColorRenderbuffer[Me])}t.bindRenderbuffer(t.RENDERBUFFER,null),q.depthBuffer&&(re.__webglDepthRenderbuffer=t.createRenderbuffer(),O(re.__webglDepthRenderbuffer,q,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(ye){n.bindTexture(t.TEXTURE_CUBE_MAP,be.__webglTexture),J(t.TEXTURE_CUBE_MAP,R,xe);for(let ge=0;ge<6;ge++)if(l&&R.mipmaps&&R.mipmaps.length>0)for(let Me=0;Me<R.mipmaps.length;Me++)W(re.__webglFramebuffer[ge][Me],q,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,Me);else W(re.__webglFramebuffer[ge],q,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0);T(R,xe)&&A(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(_e){const ge=q.texture;for(let Me=0,Be=ge.length;Me<Be;Me++){const Fe=ge[Me],Oe=a.get(Fe);n.bindTexture(t.TEXTURE_2D,Oe.__webglTexture),J(t.TEXTURE_2D,Fe,xe),W(re.__webglFramebuffer,q,Fe,t.COLOR_ATTACHMENT0+Me,t.TEXTURE_2D,0),T(Fe,xe)&&A(t.TEXTURE_2D)}n.unbindTexture()}else{let ge=t.TEXTURE_2D;if((q.isWebGL3DRenderTarget||q.isWebGLArrayRenderTarget)&&(l?ge=q.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),n.bindTexture(ge,be.__webglTexture),J(ge,R,xe),l&&R.mipmaps&&R.mipmaps.length>0)for(let Me=0;Me<R.mipmaps.length;Me++)W(re.__webglFramebuffer[Me],q,R,t.COLOR_ATTACHMENT0,ge,Me);else W(re.__webglFramebuffer,q,R,t.COLOR_ATTACHMENT0,ge,0);T(R,xe)&&A(ge),n.unbindTexture()}q.depthBuffer&&U(q)}function X(q){const R=C(q)||l,re=q.isWebGLMultipleRenderTargets===!0?q.texture:[q.texture];for(let be=0,ye=re.length;be<ye;be++){const _e=re[be];if(T(_e,R)){const xe=q.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,ge=a.get(_e).__webglTexture;n.bindTexture(xe,ge),A(xe),n.unbindTexture()}}}function se(q){if(l&&q.samples>0&&fe(q)===!1){const R=q.isWebGLMultipleRenderTargets?q.texture:[q.texture],re=q.width,be=q.height;let ye=t.COLOR_BUFFER_BIT;const _e=[],xe=q.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,ge=a.get(q),Me=q.isWebGLMultipleRenderTargets===!0;if(Me)for(let Be=0;Be<R.length;Be++)n.bindFramebuffer(t.FRAMEBUFFER,ge.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,ge.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,ge.__webglMultisampledFramebuffer),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ge.__webglFramebuffer);for(let Be=0;Be<R.length;Be++){_e.push(t.COLOR_ATTACHMENT0+Be),q.depthBuffer&&_e.push(xe);const Fe=ge.__ignoreDepthValues!==void 0?ge.__ignoreDepthValues:!1;if(Fe===!1&&(q.depthBuffer&&(ye|=t.DEPTH_BUFFER_BIT),q.stencilBuffer&&(ye|=t.STENCIL_BUFFER_BIT)),Me&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,ge.__webglColorRenderbuffer[Be]),Fe===!0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[xe]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[xe])),Me){const Oe=a.get(R[Be]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,Oe,0)}t.blitFramebuffer(0,0,re,be,0,0,re,be,ye,t.NEAREST),f&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,_e)}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),Me)for(let Be=0;Be<R.length;Be++){n.bindFramebuffer(t.FRAMEBUFFER,ge.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.RENDERBUFFER,ge.__webglColorRenderbuffer[Be]);const Fe=a.get(R[Be]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,ge.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Be,t.TEXTURE_2D,Fe,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,ge.__webglMultisampledFramebuffer)}}function te(q){return Math.min(m,q.samples)}function fe(q){const R=a.get(q);return l&&q.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function de(q){const R=o.render.frame;g.get(q)!==R&&(g.set(q,R),q.update())}function me(q,R){const re=q.colorSpace,be=q.format,ye=q.type;return q.isCompressedTexture===!0||q.isVideoTexture===!0||q.format===eR||re!==Qm&&re!==oc&&(sa.getTransfer(re)===Ta?l===!1?e.has("EXT_sRGB")===!0&&be===sc?(q.format=eR,q.minFilter=ic,q.generateMipmaps=!1):R=pee.sRGBToLinear(R):(be!==sc||ye!==Ih)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",re)),R}this.allocateTextureUnit=ce,this.resetTextureUnits=Y,this.setTexture2D=oe,this.setTexture2DArray=Q,this.setTexture3D=le,this.setTextureCube=pe,this.rebindTextures=G,this.setupRenderTarget=K,this.updateRenderTargetMipmap=X,this.updateMultisampleRenderTarget=se,this.setupDepthRenderbuffer=U,this.setupFrameBufferTexture=W,this.useMultisampledRTT=fe}function fEe(t,e,n){const a=n.isWebGL2;function i(s,o=oc){let l;const c=sa.getTransfer(o);if(s===Ih)return t.UNSIGNED_BYTE;if(s===nee)return t.UNSIGNED_SHORT_4_4_4_4;if(s===ree)return t.UNSIGNED_SHORT_5_5_5_1;if(s===zCe)return t.BYTE;if(s===UCe)return t.SHORT;if(s===YO)return t.UNSIGNED_SHORT;if(s===tee)return t.INT;if(s===yh)return t.UNSIGNED_INT;if(s===km)return t.FLOAT;if(s===Hw)return a?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===BCe)return t.ALPHA;if(s===sc)return t.RGBA;if(s===HCe)return t.LUMINANCE;if(s===qCe)return t.LUMINANCE_ALPHA;if(s===gg)return t.DEPTH_COMPONENT;if(s===Cy)return t.DEPTH_STENCIL;if(s===eR)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===$Ce)return t.RED;if(s===aee)return t.RED_INTEGER;if(s===VCe)return t.RG;if(s===iee)return t.RG_INTEGER;if(s===see)return t.RGBA_INTEGER;if(s===GE||s===WE||s===KE||s===QE)if(c===Ta)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===GE)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===WE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===KE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===QE)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===GE)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===WE)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===KE)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===QE)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===Wq||s===Kq||s===Qq||s===Yq)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===Wq)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===Kq)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===Qq)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===Yq)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===oee)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===Xq||s===Zq)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===Xq)return c===Ta?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===Zq)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===Jq||s===e$||s===t$||s===n$||s===r$||s===a$||s===i$||s===s$||s===o$||s===l$||s===c$||s===d$||s===u$||s===m$)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===Jq)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===e$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===t$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===n$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===r$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===a$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===i$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===s$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===o$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===l$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===c$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===d$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===u$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===m$)return c===Ta?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===YE||s===p$||s===h$)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===YE)return c===Ta?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===p$)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===h$)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===GCe||s===f$||s===g$||s===b$)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===YE)return l.COMPRESSED_RED_RGTC1_EXT;if(s===f$)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===g$)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===b$)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===fg?a?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 gEe extends gl{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class I0 extends So{constructor(){super(),this.isGroup=!0,this.type="Group"}}const bEe={type:"move"};class y2{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new I0,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 I0,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new yt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new yt),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new I0,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new yt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new yt),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 a of e.hand.values())this._getHandJoint(n,a)}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,a){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 w of e.hand.values()){const b=n.getJointPose(w,a),x=this._getHandJoint(d,w);b!==null&&(x.matrix.fromArray(b.transform.matrix),x.matrix.decompose(x.position,x.rotation,x.scale),x.matrixWorldNeedsUpdate=!0,x.jointRadius=b.radius),x.visible=b!==null}const u=d.joints["index-finger-tip"],m=d.joints["thumb-tip"],p=u.position.distanceTo(m.position),f=.02,g=.005;d.inputState.pinching&&p>f+g?(d.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!d.inputState.pinching&&p<=f-g&&(d.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,a),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,a),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(bEe)))}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 a=new I0;a.matrixAutoUpdate=!1,a.visible=!1,e.joints[n.jointName]=a,e.add(a)}return e.joints[n.jointName]}}class xEe extends cb{constructor(e,n){super();const a=this;let i=null,s=1,o=null,l="local-floor",c=1,d=null,u=null,m=null,p=null,f=null,g=null;const w=n.getContextAttributes();let b=null,x=null;const S=[],k=[],C=new Wn;let P=null;const T=new gl;T.layers.enable(1),T.viewport=new la;const A=new gl;A.layers.enable(2),A.viewport=new la;const F=[T,A],_=new gEe;_.layers.enable(1),_.layers.enable(2);let M=null,H=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(pe){let he=S[pe];return he===void 0&&(he=new y2,S[pe]=he),he.getTargetRaySpace()},this.getControllerGrip=function(pe){let he=S[pe];return he===void 0&&(he=new y2,S[pe]=he),he.getGripSpace()},this.getHand=function(pe){let he=S[pe];return he===void 0&&(he=new y2,S[pe]=he),he.getHandSpace()};function I(pe){const he=k.indexOf(pe.inputSource);if(he===-1)return;const we=S[he];we!==void 0&&(we.update(pe.inputSource,pe.frame,d||o),we.dispatchEvent({type:pe.type,data:pe.inputSource}))}function z(){i.removeEventListener("select",I),i.removeEventListener("selectstart",I),i.removeEventListener("selectend",I),i.removeEventListener("squeeze",I),i.removeEventListener("squeezestart",I),i.removeEventListener("squeezeend",I),i.removeEventListener("end",z),i.removeEventListener("inputsourceschange",L);for(let pe=0;pe<S.length;pe++){const he=k[pe];he!==null&&(k[pe]=null,S[pe].disconnect(he))}M=null,H=null,e.setRenderTarget(b),f=null,p=null,m=null,i=null,x=null,le.stop(),a.isPresenting=!1,e.setPixelRatio(P),e.setSize(C.width,C.height,!1),a.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(pe){s=pe,a.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(pe){l=pe,a.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return d||o},this.setReferenceSpace=function(pe){d=pe},this.getBaseLayer=function(){return p!==null?p:f},this.getBinding=function(){return m},this.getFrame=function(){return g},this.getSession=function(){return i},this.setSession=async function(pe){if(i=pe,i!==null){if(b=e.getRenderTarget(),i.addEventListener("select",I),i.addEventListener("selectstart",I),i.addEventListener("selectend",I),i.addEventListener("squeeze",I),i.addEventListener("squeezestart",I),i.addEventListener("squeezeend",I),i.addEventListener("end",z),i.addEventListener("inputsourceschange",L),w.xrCompatible!==!0&&await n.makeXRCompatible(),P=e.getPixelRatio(),e.getSize(C),i.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const he={antialias:i.renderState.layers===void 0?w.antialias:!0,alpha:!0,depth:w.depth,stencil:w.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,n,he),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),x=new Og(f.framebufferWidth,f.framebufferHeight,{format:sc,type:Ih,colorSpace:e.outputColorSpace,stencilBuffer:w.stencil})}else{let he=null,we=null,$=null;w.depth&&($=w.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,he=w.stencil?Cy:gg,we=w.stencil?fg:yh);const J={colorFormat:n.RGBA8,depthFormat:$,scaleFactor:s};m=new XRWebGLBinding(i,n),p=m.createProjectionLayer(J),i.updateRenderState({layers:[p]}),e.setPixelRatio(1),e.setSize(p.textureWidth,p.textureHeight,!1),x=new Og(p.textureWidth,p.textureHeight,{format:sc,type:Ih,depthTexture:new Nee(p.textureWidth,p.textureHeight,we,void 0,void 0,void 0,void 0,void 0,void 0,he),stencilBuffer:w.stencil,colorSpace:e.outputColorSpace,samples:w.antialias?4:0});const j=e.properties.get(x);j.__ignoreDepthValues=p.ignoreDepthValues}x.isXRRenderTarget=!0,this.setFoveation(c),d=null,o=await i.requestReferenceSpace(l),le.setContext(i),le.start(),a.isPresenting=!0,a.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode};function L(pe){for(let he=0;he<pe.removed.length;he++){const we=pe.removed[he],$=k.indexOf(we);$>=0&&(k[$]=null,S[$].disconnect(we))}for(let he=0;he<pe.added.length;he++){const we=pe.added[he];let $=k.indexOf(we);if($===-1){for(let j=0;j<S.length;j++)if(j>=k.length){k.push(we),$=j;break}else if(k[j]===null){k[j]=we,$=j;break}if($===-1)break}const J=S[$];J&&J.connect(we)}}const Z=new yt,ne=new yt;function Y(pe,he,we){Z.setFromMatrixPosition(he.matrixWorld),ne.setFromMatrixPosition(we.matrixWorld);const $=Z.distanceTo(ne),J=he.projectionMatrix.elements,j=we.projectionMatrix.elements,E=J[14]/(J[10]-1),B=J[14]/(J[10]+1),W=(J[9]+1)/J[5],O=(J[9]-1)/J[5],ie=(J[8]-1)/J[0],U=(j[8]+1)/j[0],G=E*ie,K=E*U,X=$/(-ie+U),se=X*-ie;he.matrixWorld.decompose(pe.position,pe.quaternion,pe.scale),pe.translateX(se),pe.translateZ(X),pe.matrixWorld.compose(pe.position,pe.quaternion,pe.scale),pe.matrixWorldInverse.copy(pe.matrixWorld).invert();const te=E+X,fe=B+X,de=G-se,me=K+($-se),q=W*B/fe*te,R=O*B/fe*te;pe.projectionMatrix.makePerspective(de,me,q,R,te,fe),pe.projectionMatrixInverse.copy(pe.projectionMatrix).invert()}function ce(pe,he){he===null?pe.matrixWorld.copy(pe.matrix):pe.matrixWorld.multiplyMatrices(he.matrixWorld,pe.matrix),pe.matrixWorldInverse.copy(pe.matrixWorld).invert()}this.updateCamera=function(pe){if(i===null)return;_.near=A.near=T.near=pe.near,_.far=A.far=T.far=pe.far,(M!==_.near||H!==_.far)&&(i.updateRenderState({depthNear:_.near,depthFar:_.far}),M=_.near,H=_.far);const he=pe.parent,we=_.cameras;ce(_,he);for(let $=0;$<we.length;$++)ce(we[$],he);we.length===2?Y(_,T,A):_.projectionMatrix.copy(T.projectionMatrix),ue(pe,_,he)};function ue(pe,he,we){we===null?pe.matrix.copy(he.matrixWorld):(pe.matrix.copy(we.matrixWorld),pe.matrix.invert(),pe.matrix.multiply(he.matrixWorld)),pe.matrix.decompose(pe.position,pe.quaternion,pe.scale),pe.updateMatrixWorld(!0),pe.projectionMatrix.copy(he.projectionMatrix),pe.projectionMatrixInverse.copy(he.projectionMatrixInverse),pe.isPerspectiveCamera&&(pe.fov=$w*2*Math.atan(1/pe.projectionMatrix.elements[5]),pe.zoom=1)}this.getCamera=function(){return _},this.getFoveation=function(){if(!(p===null&&f===null))return c},this.setFoveation=function(pe){c=pe,p!==null&&(p.fixedFoveation=pe),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=pe)};let oe=null;function Q(pe,he){if(u=he.getViewerPose(d||o),g=he,u!==null){const we=u.views;f!==null&&(e.setRenderTargetFramebuffer(x,f.framebuffer),e.setRenderTarget(x));let $=!1;we.length!==_.cameras.length&&(_.cameras.length=0,$=!0);for(let J=0;J<we.length;J++){const j=we[J];let E=null;if(f!==null)E=f.getViewport(j);else{const W=m.getViewSubImage(p,j);E=W.viewport,J===0&&(e.setRenderTargetTextures(x,W.colorTexture,p.ignoreDepthValues?void 0:W.depthStencilTexture),e.setRenderTarget(x))}let B=F[J];B===void 0&&(B=new gl,B.layers.enable(J),B.viewport=new la,F[J]=B),B.matrix.fromArray(j.transform.matrix),B.matrix.decompose(B.position,B.quaternion,B.scale),B.projectionMatrix.fromArray(j.projectionMatrix),B.projectionMatrixInverse.copy(B.projectionMatrix).invert(),B.viewport.set(E.x,E.y,E.width,E.height),J===0&&(_.matrix.copy(B.matrix),_.matrix.decompose(_.position,_.quaternion,_.scale)),$===!0&&_.cameras.push(B)}}for(let we=0;we<S.length;we++){const $=k[we],J=S[we];$!==null&&J!==void 0&&J.update($,he,d||o)}oe&&oe(pe,he),he.detectedPlanes&&a.dispatchEvent({type:"planesdetected",data:he}),g=null}const le=new kee;le.setAnimationLoop(Q),this.setAnimationLoop=function(pe){oe=pe},this.dispose=function(){}}}function yEe(t,e){function n(b,x){b.matrixAutoUpdate===!0&&b.updateMatrix(),x.value.copy(b.matrix)}function a(b,x){x.color.getRGB(b.fogColor.value,wee(t)),x.isFog?(b.fogNear.value=x.near,b.fogFar.value=x.far):x.isFogExp2&&(b.fogDensity.value=x.density)}function i(b,x,S,k,C){x.isMeshBasicMaterial||x.isMeshLambertMaterial?s(b,x):x.isMeshToonMaterial?(s(b,x),m(b,x)):x.isMeshPhongMaterial?(s(b,x),u(b,x)):x.isMeshStandardMaterial?(s(b,x),p(b,x),x.isMeshPhysicalMaterial&&f(b,x,C)):x.isMeshMatcapMaterial?(s(b,x),g(b,x)):x.isMeshDepthMaterial?s(b,x):x.isMeshDistanceMaterial?(s(b,x),w(b,x)):x.isMeshNormalMaterial?s(b,x):x.isLineBasicMaterial?(o(b,x),x.isLineDashedMaterial&&l(b,x)):x.isPointsMaterial?c(b,x,S,k):x.isSpriteMaterial?d(b,x):x.isShadowMaterial?(b.color.value.copy(x.color),b.opacity.value=x.opacity):x.isShaderMaterial&&(x.uniformsNeedUpdate=!1)}function s(b,x){b.opacity.value=x.opacity,x.color&&b.diffuse.value.copy(x.color),x.emissive&&b.emissive.value.copy(x.emissive).multiplyScalar(x.emissiveIntensity),x.map&&(b.map.value=x.map,n(x.map,b.mapTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.bumpMap&&(b.bumpMap.value=x.bumpMap,n(x.bumpMap,b.bumpMapTransform),b.bumpScale.value=x.bumpScale,x.side===Ko&&(b.bumpScale.value*=-1)),x.normalMap&&(b.normalMap.value=x.normalMap,n(x.normalMap,b.normalMapTransform),b.normalScale.value.copy(x.normalScale),x.side===Ko&&b.normalScale.value.negate()),x.displacementMap&&(b.displacementMap.value=x.displacementMap,n(x.displacementMap,b.displacementMapTransform),b.displacementScale.value=x.displacementScale,b.displacementBias.value=x.displacementBias),x.emissiveMap&&(b.emissiveMap.value=x.emissiveMap,n(x.emissiveMap,b.emissiveMapTransform)),x.specularMap&&(b.specularMap.value=x.specularMap,n(x.specularMap,b.specularMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest);const S=e.get(x).envMap;if(S&&(b.envMap.value=S,b.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,b.reflectivity.value=x.reflectivity,b.ior.value=x.ior,b.refractionRatio.value=x.refractionRatio),x.lightMap){b.lightMap.value=x.lightMap;const k=t._useLegacyLights===!0?Math.PI:1;b.lightMapIntensity.value=x.lightMapIntensity*k,n(x.lightMap,b.lightMapTransform)}x.aoMap&&(b.aoMap.value=x.aoMap,b.aoMapIntensity.value=x.aoMapIntensity,n(x.aoMap,b.aoMapTransform))}function o(b,x){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,x.map&&(b.map.value=x.map,n(x.map,b.mapTransform))}function l(b,x){b.dashSize.value=x.dashSize,b.totalSize.value=x.dashSize+x.gapSize,b.scale.value=x.scale}function c(b,x,S,k){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,b.size.value=x.size*S,b.scale.value=k*.5,x.map&&(b.map.value=x.map,n(x.map,b.uvTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest)}function d(b,x){b.diffuse.value.copy(x.color),b.opacity.value=x.opacity,b.rotation.value=x.rotation,x.map&&(b.map.value=x.map,n(x.map,b.mapTransform)),x.alphaMap&&(b.alphaMap.value=x.alphaMap,n(x.alphaMap,b.alphaMapTransform)),x.alphaTest>0&&(b.alphaTest.value=x.alphaTest)}function u(b,x){b.specular.value.copy(x.specular),b.shininess.value=Math.max(x.shininess,1e-4)}function m(b,x){x.gradientMap&&(b.gradientMap.value=x.gradientMap)}function p(b,x){b.metalness.value=x.metalness,x.metalnessMap&&(b.metalnessMap.value=x.metalnessMap,n(x.metalnessMap,b.metalnessMapTransform)),b.roughness.value=x.roughness,x.roughnessMap&&(b.roughnessMap.value=x.roughnessMap,n(x.roughnessMap,b.roughnessMapTransform)),e.get(x).envMap&&(b.envMapIntensity.value=x.envMapIntensity)}function f(b,x,S){b.ior.value=x.ior,x.sheen>0&&(b.sheenColor.value.copy(x.sheenColor).multiplyScalar(x.sheen),b.sheenRoughness.value=x.sheenRoughness,x.sheenColorMap&&(b.sheenColorMap.value=x.sheenColorMap,n(x.sheenColorMap,b.sheenColorMapTransform)),x.sheenRoughnessMap&&(b.sheenRoughnessMap.value=x.sheenRoughnessMap,n(x.sheenRoughnessMap,b.sheenRoughnessMapTransform))),x.clearcoat>0&&(b.clearcoat.value=x.clearcoat,b.clearcoatRoughness.value=x.clearcoatRoughness,x.clearcoatMap&&(b.clearcoatMap.value=x.clearcoatMap,n(x.clearcoatMap,b.clearcoatMapTransform)),x.clearcoatRoughnessMap&&(b.clearcoatRoughnessMap.value=x.clearcoatRoughnessMap,n(x.clearcoatRoughnessMap,b.clearcoatRoughnessMapTransform)),x.clearcoatNormalMap&&(b.clearcoatNormalMap.value=x.clearcoatNormalMap,n(x.clearcoatNormalMap,b.clearcoatNormalMapTransform),b.clearcoatNormalScale.value.copy(x.clearcoatNormalScale),x.side===Ko&&b.clearcoatNormalScale.value.negate())),x.iridescence>0&&(b.iridescence.value=x.iridescence,b.iridescenceIOR.value=x.iridescenceIOR,b.iridescenceThicknessMinimum.value=x.iridescenceThicknessRange[0],b.iridescenceThicknessMaximum.value=x.iridescenceThicknessRange[1],x.iridescenceMap&&(b.iridescenceMap.value=x.iridescenceMap,n(x.iridescenceMap,b.iridescenceMapTransform)),x.iridescenceThicknessMap&&(b.iridescenceThicknessMap.value=x.iridescenceThicknessMap,n(x.iridescenceThicknessMap,b.iridescenceThicknessMapTransform))),x.transmission>0&&(b.transmission.value=x.transmission,b.transmissionSamplerMap.value=S.texture,b.transmissionSamplerSize.value.set(S.width,S.height),x.transmissionMap&&(b.transmissionMap.value=x.transmissionMap,n(x.transmissionMap,b.transmissionMapTransform)),b.thickness.value=x.thickness,x.thicknessMap&&(b.thicknessMap.value=x.thicknessMap,n(x.thicknessMap,b.thicknessMapTransform)),b.attenuationDistance.value=x.attenuationDistance,b.attenuationColor.value.copy(x.attenuationColor)),x.anisotropy>0&&(b.anisotropyVector.value.set(x.anisotropy*Math.cos(x.anisotropyRotation),x.anisotropy*Math.sin(x.anisotropyRotation)),x.anisotropyMap&&(b.anisotropyMap.value=x.anisotropyMap,n(x.anisotropyMap,b.anisotropyMapTransform))),b.specularIntensity.value=x.specularIntensity,b.specularColor.value.copy(x.specularColor),x.specularColorMap&&(b.specularColorMap.value=x.specularColorMap,n(x.specularColorMap,b.specularColorMapTransform)),x.specularIntensityMap&&(b.specularIntensityMap.value=x.specularIntensityMap,n(x.specularIntensityMap,b.specularIntensityMapTransform))}function g(b,x){x.matcap&&(b.matcap.value=x.matcap)}function w(b,x){const S=e.get(x).light;b.referencePosition.value.setFromMatrixPosition(S.matrixWorld),b.nearDistance.value=S.shadow.camera.near,b.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:a,refreshMaterialUniforms:i}}function vEe(t,e,n,a){let i={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(S,k){const C=k.program;a.uniformBlockBinding(S,C)}function d(S,k){let C=i[S.id];C===void 0&&(g(S),C=u(S),i[S.id]=C,S.addEventListener("dispose",b));const P=k.program;a.updateUBOMapping(S,P);const T=e.render.frame;s[S.id]!==T&&(p(S),s[S.id]=T)}function u(S){const k=m();S.__bindingPointIndex=k;const C=t.createBuffer(),P=S.__size,T=S.usage;return t.bindBuffer(t.UNIFORM_BUFFER,C),t.bufferData(t.UNIFORM_BUFFER,P,T),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,k,C),C}function m(){for(let S=0;S<l;S++)if(o.indexOf(S)===-1)return o.push(S),S;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function p(S){const k=i[S.id],C=S.uniforms,P=S.__cache;t.bindBuffer(t.UNIFORM_BUFFER,k);for(let T=0,A=C.length;T<A;T++){const F=C[T];if(f(F,T,P)===!0){const _=F.__offset,M=Array.isArray(F.value)?F.value:[F.value];let H=0;for(let I=0;I<M.length;I++){const z=M[I],L=w(z);typeof z=="number"?(F.__data[0]=z,t.bufferSubData(t.UNIFORM_BUFFER,_+H,F.__data)):z.isMatrix3?(F.__data[0]=z.elements[0],F.__data[1]=z.elements[1],F.__data[2]=z.elements[2],F.__data[3]=z.elements[0],F.__data[4]=z.elements[3],F.__data[5]=z.elements[4],F.__data[6]=z.elements[5],F.__data[7]=z.elements[0],F.__data[8]=z.elements[6],F.__data[9]=z.elements[7],F.__data[10]=z.elements[8],F.__data[11]=z.elements[0]):(z.toArray(F.__data,H),H+=L.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,_,F.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function f(S,k,C){const P=S.value;if(C[k]===void 0){if(typeof P=="number")C[k]=P;else{const T=Array.isArray(P)?P:[P],A=[];for(let F=0;F<T.length;F++)A.push(T[F].clone());C[k]=A}return!0}else if(typeof P=="number"){if(C[k]!==P)return C[k]=P,!0}else{const T=Array.isArray(C[k])?C[k]:[C[k]],A=Array.isArray(P)?P:[P];for(let F=0;F<T.length;F++){const _=T[F];if(_.equals(A[F])===!1)return _.copy(A[F]),!0}}return!1}function g(S){const k=S.uniforms;let C=0;const P=16;let T=0;for(let A=0,F=k.length;A<F;A++){const _=k[A],M={boundary:0,storage:0},H=Array.isArray(_.value)?_.value:[_.value];for(let I=0,z=H.length;I<z;I++){const L=H[I],Z=w(L);M.boundary+=Z.boundary,M.storage+=Z.storage}if(_.__data=new Float32Array(M.storage/Float32Array.BYTES_PER_ELEMENT),_.__offset=C,A>0){T=C%P;const I=P-T;T!==0&&I-M.boundary<0&&(C+=P-T,_.__offset=C)}C+=M.storage}return T=C%P,T>0&&(C+=P-T),S.__size=C,S.__cache={},this}function w(S){const k={boundary:0,storage:0};return typeof S=="number"?(k.boundary=4,k.storage=4):S.isVector2?(k.boundary=8,k.storage=8):S.isVector3||S.isColor?(k.boundary=16,k.storage=12):S.isVector4?(k.boundary=16,k.storage=16):S.isMatrix3?(k.boundary=48,k.storage=48):S.isMatrix4?(k.boundary=64,k.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),k}function b(S){const k=S.target;k.removeEventListener("dispose",b);const C=o.indexOf(k.__bindingPointIndex);o.splice(C,1),t.deleteBuffer(i[k.id]),delete i[k.id],delete s[k.id]}function x(){for(const S in i)t.deleteBuffer(i[S]);o=[],i={},s={}}return{bind:c,update:d,dispose:x}}class rR{constructor(e={}){const{canvas:n=bPe(),context:a=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;a!==null?p=a.getContextAttributes().alpha:p=o;const f=new Uint32Array(4),g=new Int32Array(4);let w=null,b=null;const x=[],S=[];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=Ms,this._useLegacyLights=!1,this.toneMapping=Rh,this.toneMappingExposure=1;const k=this;let C=!1,P=0,T=0,A=null,F=-1,_=null;const M=new la,H=new la;let I=null;const z=new On(0);let L=0,Z=n.width,ne=n.height,Y=1,ce=null,ue=null;const oe=new la(0,0,Z,ne),Q=new la(0,0,Z,ne);let le=!1;const pe=new IT;let he=!1,we=!1,$=null;const J=new Sa,j=new Wn,E=new yt,B={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function W(){return A===null?Y:1}let O=a;function ie(Le,Ae){for(let Ge=0;Ge<Le.length;Ge++){const Je=Le[Ge],De=n.getContext(Je,Ae);if(De!==null)return De}return null}try{const Le={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${FT}`),n.addEventListener("webglcontextlost",it,!1),n.addEventListener("webglcontextrestored",Ce,!1),n.addEventListener("webglcontextcreationerror",Ze,!1),O===null){const Ae=["webgl2","webgl","experimental-webgl"];if(k.isWebGL1Renderer===!0&&Ae.shift(),O=ie(Ae,Le),O===null)throw ie(Ae)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&O instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),O.getShaderPrecisionFormat===void 0&&(O.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(Le){throw console.error("THREE.WebGLRenderer: "+Le.message),Le}let U,G,K,X,se,te,fe,de,me,q,R,re,be,ye,_e,xe,ge,Me,Be,Fe,Oe,Re,We,ze;function st(){U=new Mje(O),G=new kje(O,U,e),U.init(G),Re=new fEe(O,U,G),K=new pEe(O,U,G),X=new Fje(O),se=new JMe,te=new hEe(O,U,K,se,G,Re,X),fe=new Cje(k),de=new jje(k),me=new BPe(O,G),We=new Sje(O,U,me,G),q=new Eje(O,me,X,We),R=new Oje(O,q,me,X),Be=new Ije(O,G,te),xe=new Nje(se),re=new ZMe(k,fe,de,U,G,We,xe),be=new yEe(k,se),ye=new tEe,_e=new oEe(U,G),Me=new wje(k,fe,de,K,R,p,c),ge=new mEe(k,R,G),ze=new vEe(O,X,G,K),Fe=new _je(O,U,X,G),Oe=new Dje(O,U,X,G),X.programs=re.programs,k.capabilities=G,k.extensions=U,k.properties=se,k.renderLists=ye,k.shadowMap=ge,k.state=K,k.info=X}st();const Ee=new xEe(k,O);this.xr=Ee,this.getContext=function(){return O},this.getContextAttributes=function(){return O.getContextAttributes()},this.forceContextLoss=function(){const Le=U.get("WEBGL_lose_context");Le&&Le.loseContext()},this.forceContextRestore=function(){const Le=U.get("WEBGL_lose_context");Le&&Le.restoreContext()},this.getPixelRatio=function(){return Y},this.setPixelRatio=function(Le){Le!==void 0&&(Y=Le,this.setSize(Z,ne,!1))},this.getSize=function(Le){return Le.set(Z,ne)},this.setSize=function(Le,Ae,Ge=!0){if(Ee.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}Z=Le,ne=Ae,n.width=Math.floor(Le*Y),n.height=Math.floor(Ae*Y),Ge===!0&&(n.style.width=Le+"px",n.style.height=Ae+"px"),this.setViewport(0,0,Le,Ae)},this.getDrawingBufferSize=function(Le){return Le.set(Z*Y,ne*Y).floor()},this.setDrawingBufferSize=function(Le,Ae,Ge){Z=Le,ne=Ae,Y=Ge,n.width=Math.floor(Le*Ge),n.height=Math.floor(Ae*Ge),this.setViewport(0,0,Le,Ae)},this.getCurrentViewport=function(Le){return Le.copy(M)},this.getViewport=function(Le){return Le.copy(oe)},this.setViewport=function(Le,Ae,Ge,Je){Le.isVector4?oe.set(Le.x,Le.y,Le.z,Le.w):oe.set(Le,Ae,Ge,Je),K.viewport(M.copy(oe).multiplyScalar(Y).floor())},this.getScissor=function(Le){return Le.copy(Q)},this.setScissor=function(Le,Ae,Ge,Je){Le.isVector4?Q.set(Le.x,Le.y,Le.z,Le.w):Q.set(Le,Ae,Ge,Je),K.scissor(H.copy(Q).multiplyScalar(Y).floor())},this.getScissorTest=function(){return le},this.setScissorTest=function(Le){K.setScissorTest(le=Le)},this.setOpaqueSort=function(Le){ce=Le},this.setTransparentSort=function(Le){ue=Le},this.getClearColor=function(Le){return Le.copy(Me.getClearColor())},this.setClearColor=function(){Me.setClearColor.apply(Me,arguments)},this.getClearAlpha=function(){return Me.getClearAlpha()},this.setClearAlpha=function(){Me.setClearAlpha.apply(Me,arguments)},this.clear=function(Le=!0,Ae=!0,Ge=!0){let Je=0;if(Le){let De=!1;if(A!==null){const mt=A.texture.format;De=mt===see||mt===iee||mt===aee}if(De){const mt=A.texture.type,Ne=mt===Ih||mt===yh||mt===YO||mt===fg||mt===nee||mt===ree,Ye=Me.getClearColor(),nt=Me.getClearAlpha(),at=Ye.r,et=Ye.g,vt=Ye.b;Ne?(f[0]=at,f[1]=et,f[2]=vt,f[3]=nt,O.clearBufferuiv(O.COLOR,0,f)):(g[0]=at,g[1]=et,g[2]=vt,g[3]=nt,O.clearBufferiv(O.COLOR,0,g))}else Je|=O.COLOR_BUFFER_BIT}Ae&&(Je|=O.DEPTH_BUFFER_BIT),Ge&&(Je|=O.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),O.clear(Je)},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",it,!1),n.removeEventListener("webglcontextrestored",Ce,!1),n.removeEventListener("webglcontextcreationerror",Ze,!1),ye.dispose(),_e.dispose(),se.dispose(),fe.dispose(),de.dispose(),R.dispose(),We.dispose(),ze.dispose(),re.dispose(),Ee.dispose(),Ee.removeEventListener("sessionstart",tt),Ee.removeEventListener("sessionend",ot),$&&($.dispose(),$=null),Tt.stop()};function it(Le){Le.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),C=!0}function Ce(){console.log("THREE.WebGLRenderer: Context Restored."),C=!1;const Le=X.autoReset,Ae=ge.enabled,Ge=ge.autoUpdate,Je=ge.needsUpdate,De=ge.type;st(),X.autoReset=Le,ge.enabled=Ae,ge.autoUpdate=Ge,ge.needsUpdate=Je,ge.type=De}function Ze(Le){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",Le.statusMessage)}function Ie(Le){const Ae=Le.target;Ae.removeEventListener("dispose",Ie),ke(Ae)}function ke(Le){Ve(Le),se.remove(Le)}function Ve(Le){const Ae=se.get(Le).programs;Ae!==void 0&&(Ae.forEach(function(Ge){re.releaseProgram(Ge)}),Le.isShaderMaterial&&re.releaseShaderCache(Le))}this.renderBufferDirect=function(Le,Ae,Ge,Je,De,mt){Ae===null&&(Ae=B);const Ne=De.isMesh&&De.matrixWorld.determinant()<0,Ye=Nt(Le,Ae,Ge,Je,De);K.setMaterial(Je,Ne);let nt=Ge.index,at=1;if(Je.wireframe===!0){if(nt=q.getWireframeAttribute(Ge),nt===void 0)return;at=2}const et=Ge.drawRange,vt=Ge.attributes.position;let wt=et.start*at,Ue=(et.start+et.count)*at;mt!==null&&(wt=Math.max(wt,mt.start*at),Ue=Math.min(Ue,(mt.start+mt.count)*at)),nt!==null?(wt=Math.max(wt,0),Ue=Math.min(Ue,nt.count)):vt!=null&&(wt=Math.max(wt,0),Ue=Math.min(Ue,vt.count));const He=Ue-wt;if(He<0||He===1/0)return;We.setup(De,Je,Ye,Ge,nt);let Dt,Rt=Fe;if(nt!==null&&(Dt=me.get(nt),Rt=Oe,Rt.setIndex(Dt)),De.isMesh)Je.wireframe===!0?(K.setLineWidth(Je.wireframeLinewidth*W()),Rt.setMode(O.LINES)):Rt.setMode(O.TRIANGLES);else if(De.isLine){let qe=Je.linewidth;qe===void 0&&(qe=1),K.setLineWidth(qe*W()),De.isLineSegments?Rt.setMode(O.LINES):De.isLineLoop?Rt.setMode(O.LINE_LOOP):Rt.setMode(O.LINE_STRIP)}else De.isPoints?Rt.setMode(O.POINTS):De.isSprite&&Rt.setMode(O.TRIANGLES);if(De.isBatchedMesh)Rt.renderMultiDraw(De._multiDrawStarts,De._multiDrawCounts,De._multiDrawCount);else if(De.isInstancedMesh)Rt.renderInstances(wt,He,De.count);else if(Ge.isInstancedBufferGeometry){const qe=Ge._maxInstanceCount!==void 0?Ge._maxInstanceCount:1/0,Ke=Math.min(Ge.instanceCount,qe);Rt.renderInstances(wt,He,Ke)}else Rt.render(wt,He)};function rt(Le,Ae,Ge){Le.transparent===!0&&Le.side===xm&&Le.forceSinglePass===!1?(Le.side=Ko,Le.needsUpdate=!0,cn(Le,Ae,Ge),Le.side=Qh,Le.needsUpdate=!0,cn(Le,Ae,Ge),Le.side=xm):cn(Le,Ae,Ge)}this.compile=function(Le,Ae,Ge=null){Ge===null&&(Ge=Le),b=_e.get(Ge),b.init(),S.push(b),Ge.traverseVisible(function(De){De.isLight&&De.layers.test(Ae.layers)&&(b.pushLight(De),De.castShadow&&b.pushShadow(De))}),Le!==Ge&&Le.traverseVisible(function(De){De.isLight&&De.layers.test(Ae.layers)&&(b.pushLight(De),De.castShadow&&b.pushShadow(De))}),b.setupLights(k._useLegacyLights);const Je=new Set;return Le.traverse(function(De){const mt=De.material;if(mt)if(Array.isArray(mt))for(let Ne=0;Ne<mt.length;Ne++){const Ye=mt[Ne];rt(Ye,Ge,De),Je.add(Ye)}else rt(mt,Ge,De),Je.add(mt)}),S.pop(),b=null,Je},this.compileAsync=function(Le,Ae,Ge=null){const Je=this.compile(Le,Ae,Ge);return new Promise(De=>{function mt(){if(Je.forEach(function(Ne){se.get(Ne).currentProgram.isReady()&&Je.delete(Ne)}),Je.size===0){De(Le);return}setTimeout(mt,10)}U.get("KHR_parallel_shader_compile")!==null?mt():setTimeout(mt,10)})};let Qe=null;function Te(Le){Qe&&Qe(Le)}function tt(){Tt.stop()}function ot(){Tt.start()}const Tt=new kee;Tt.setAnimationLoop(Te),typeof self<"u"&&Tt.setContext(self),this.setAnimationLoop=function(Le){Qe=Le,Ee.setAnimationLoop(Le),Le===null?Tt.stop():Tt.start()},Ee.addEventListener("sessionstart",tt),Ee.addEventListener("sessionend",ot),this.render=function(Le,Ae){if(Ae!==void 0&&Ae.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;Le.matrixWorldAutoUpdate===!0&&Le.updateMatrixWorld(),Ae.parent===null&&Ae.matrixWorldAutoUpdate===!0&&Ae.updateMatrixWorld(),Ee.enabled===!0&&Ee.isPresenting===!0&&(Ee.cameraAutoUpdate===!0&&Ee.updateCamera(Ae),Ae=Ee.getCamera()),Le.isScene===!0&&Le.onBeforeRender(k,Le,Ae,A),b=_e.get(Le,S.length),b.init(),S.push(b),J.multiplyMatrices(Ae.projectionMatrix,Ae.matrixWorldInverse),pe.setFromProjectionMatrix(J),we=this.localClippingEnabled,he=xe.init(this.clippingPlanes,we),w=ye.get(Le,x.length),w.init(),x.push(w),Ut(Le,Ae,0,k.sortObjects),w.finish(),k.sortObjects===!0&&w.sort(ce,ue),this.info.render.frame++,he===!0&&xe.beginShadows();const Ge=b.state.shadowsArray;if(ge.render(Ge,Le,Ae),he===!0&&xe.endShadows(),this.info.autoReset===!0&&this.info.reset(),Me.render(w,Le),b.setupLights(k._useLegacyLights),Ae.isArrayCamera){const Je=Ae.cameras;for(let De=0,mt=Je.length;De<mt;De++){const Ne=Je[De];bt(w,Le,Ne,Ne.viewport)}}else bt(w,Le,Ae);A!==null&&(te.updateMultisampleRenderTarget(A),te.updateRenderTargetMipmap(A)),Le.isScene===!0&&Le.onAfterRender(k,Le,Ae),We.resetDefaultState(),F=-1,_=null,S.pop(),S.length>0?b=S[S.length-1]:b=null,x.pop(),x.length>0?w=x[x.length-1]:w=null};function Ut(Le,Ae,Ge,Je){if(Le.visible===!1)return;if(Le.layers.test(Ae.layers)){if(Le.isGroup)Ge=Le.renderOrder;else if(Le.isLOD)Le.autoUpdate===!0&&Le.update(Ae);else if(Le.isLight)b.pushLight(Le),Le.castShadow&&b.pushShadow(Le);else if(Le.isSprite){if(!Le.frustumCulled||pe.intersectsSprite(Le)){Je&&E.setFromMatrixPosition(Le.matrixWorld).applyMatrix4(J);const Ne=R.update(Le),Ye=Le.material;Ye.visible&&w.push(Le,Ne,Ye,Ge,E.z,null)}}else if((Le.isMesh||Le.isLine||Le.isPoints)&&(!Le.frustumCulled||pe.intersectsObject(Le))){const Ne=R.update(Le),Ye=Le.material;if(Je&&(Le.boundingSphere!==void 0?(Le.boundingSphere===null&&Le.computeBoundingSphere(),E.copy(Le.boundingSphere.center)):(Ne.boundingSphere===null&&Ne.computeBoundingSphere(),E.copy(Ne.boundingSphere.center)),E.applyMatrix4(Le.matrixWorld).applyMatrix4(J)),Array.isArray(Ye)){const nt=Ne.groups;for(let at=0,et=nt.length;at<et;at++){const vt=nt[at],wt=Ye[vt.materialIndex];wt&&wt.visible&&w.push(Le,Ne,wt,Ge,E.z,vt)}}else Ye.visible&&w.push(Le,Ne,Ye,Ge,E.z,null)}}const mt=Le.children;for(let Ne=0,Ye=mt.length;Ne<Ye;Ne++)Ut(mt[Ne],Ae,Ge,Je)}function bt(Le,Ae,Ge,Je){const De=Le.opaque,mt=Le.transmissive,Ne=Le.transparent;b.setupLightsView(Ge),he===!0&&xe.setGlobalState(k.clippingPlanes,Ge),mt.length>0&&Wt(De,mt,Ae,Ge),Je&&K.viewport(M.copy(Je)),De.length>0&&Zt(De,Ae,Ge),mt.length>0&&Zt(mt,Ae,Ge),Ne.length>0&&Zt(Ne,Ae,Ge),K.buffers.depth.setTest(!0),K.buffers.depth.setMask(!0),K.buffers.color.setMask(!0),K.setPolygonOffset(!1)}function Wt(Le,Ae,Ge,Je){if((Ge.isScene===!0?Ge.overrideMaterial:null)!==null)return;const mt=G.isWebGL2;$===null&&($=new Og(1,1,{generateMipmaps:!0,type:U.has("EXT_color_buffer_half_float")?Hw:Ih,minFilter:Bw,samples:mt?4:0})),k.getDrawingBufferSize(j),mt?$.setSize(j.x,j.y):$.setSize(xC(j.x),xC(j.y));const Ne=k.getRenderTarget();k.setRenderTarget($),k.getClearColor(z),L=k.getClearAlpha(),L<1&&k.setClearColor(16777215,.5),k.clear();const Ye=k.toneMapping;k.toneMapping=Rh,Zt(Le,Ge,Je),te.updateMultisampleRenderTarget($),te.updateRenderTargetMipmap($);let nt=!1;for(let at=0,et=Ae.length;at<et;at++){const vt=Ae[at],wt=vt.object,Ue=vt.geometry,He=vt.material,Dt=vt.group;if(He.side===xm&&wt.layers.test(Je.layers)){const Rt=He.side;He.side=Ko,He.needsUpdate=!0,ln(wt,Ge,Je,Ue,He,Dt),He.side=Rt,He.needsUpdate=!0,nt=!0}}nt===!0&&(te.updateMultisampleRenderTarget($),te.updateRenderTargetMipmap($)),k.setRenderTarget(Ne),k.setClearColor(z,L),k.toneMapping=Ye}function Zt(Le,Ae,Ge){const Je=Ae.isScene===!0?Ae.overrideMaterial:null;for(let De=0,mt=Le.length;De<mt;De++){const Ne=Le[De],Ye=Ne.object,nt=Ne.geometry,at=Je===null?Ne.material:Je,et=Ne.group;Ye.layers.test(Ge.layers)&&ln(Ye,Ae,Ge,nt,at,et)}}function ln(Le,Ae,Ge,Je,De,mt){Le.onBeforeRender(k,Ae,Ge,Je,De,mt),Le.modelViewMatrix.multiplyMatrices(Ge.matrixWorldInverse,Le.matrixWorld),Le.normalMatrix.getNormalMatrix(Le.modelViewMatrix),De.onBeforeRender(k,Ae,Ge,Je,Le,mt),De.transparent===!0&&De.side===xm&&De.forceSinglePass===!1?(De.side=Ko,De.needsUpdate=!0,k.renderBufferDirect(Ge,Ae,Je,De,Le,mt),De.side=Qh,De.needsUpdate=!0,k.renderBufferDirect(Ge,Ae,Je,De,Le,mt),De.side=xm):k.renderBufferDirect(Ge,Ae,Je,De,Le,mt),Le.onAfterRender(k,Ae,Ge,Je,De,mt)}function cn(Le,Ae,Ge){Ae.isScene!==!0&&(Ae=B);const Je=se.get(Le),De=b.state.lights,mt=b.state.shadowsArray,Ne=De.state.version,Ye=re.getParameters(Le,De.state,mt,Ae,Ge),nt=re.getProgramCacheKey(Ye);let at=Je.programs;Je.environment=Le.isMeshStandardMaterial?Ae.environment:null,Je.fog=Ae.fog,Je.envMap=(Le.isMeshStandardMaterial?de:fe).get(Le.envMap||Je.environment),at===void 0&&(Le.addEventListener("dispose",Ie),at=new Map,Je.programs=at);let et=at.get(nt);if(et!==void 0){if(Je.currentProgram===et&&Je.lightsStateVersion===Ne)return kt(Le,Ye),et}else Ye.uniforms=re.getUniforms(Le),Le.onBuild(Ge,Ye,k),Le.onBeforeCompile(Ye,k),et=re.acquireProgram(Ye,nt),at.set(nt,et),Je.uniforms=Ye.uniforms;const vt=Je.uniforms;return(!Le.isShaderMaterial&&!Le.isRawShaderMaterial||Le.clipping===!0)&&(vt.clippingPlanes=xe.uniform),kt(Le,Ye),Je.needsLights=Ct(Le),Je.lightsStateVersion=Ne,Je.needsLights&&(vt.ambientLightColor.value=De.state.ambient,vt.lightProbe.value=De.state.probe,vt.directionalLights.value=De.state.directional,vt.directionalLightShadows.value=De.state.directionalShadow,vt.spotLights.value=De.state.spot,vt.spotLightShadows.value=De.state.spotShadow,vt.rectAreaLights.value=De.state.rectArea,vt.ltc_1.value=De.state.rectAreaLTC1,vt.ltc_2.value=De.state.rectAreaLTC2,vt.pointLights.value=De.state.point,vt.pointLightShadows.value=De.state.pointShadow,vt.hemisphereLights.value=De.state.hemi,vt.directionalShadowMap.value=De.state.directionalShadowMap,vt.directionalShadowMatrix.value=De.state.directionalShadowMatrix,vt.spotShadowMap.value=De.state.spotShadowMap,vt.spotLightMatrix.value=De.state.spotLightMatrix,vt.spotLightMap.value=De.state.spotLightMap,vt.pointShadowMap.value=De.state.pointShadowMap,vt.pointShadowMatrix.value=De.state.pointShadowMatrix),Je.currentProgram=et,Je.uniformsList=null,et}function ct(Le){if(Le.uniformsList===null){const Ae=Le.currentProgram.getUniforms();Le.uniformsList=TN.seqWithValue(Ae.seq,Le.uniforms)}return Le.uniformsList}function kt(Le,Ae){const Ge=se.get(Le);Ge.outputColorSpace=Ae.outputColorSpace,Ge.batching=Ae.batching,Ge.instancing=Ae.instancing,Ge.instancingColor=Ae.instancingColor,Ge.skinning=Ae.skinning,Ge.morphTargets=Ae.morphTargets,Ge.morphNormals=Ae.morphNormals,Ge.morphColors=Ae.morphColors,Ge.morphTargetsCount=Ae.morphTargetsCount,Ge.numClippingPlanes=Ae.numClippingPlanes,Ge.numIntersection=Ae.numClipIntersection,Ge.vertexAlphas=Ae.vertexAlphas,Ge.vertexTangents=Ae.vertexTangents,Ge.toneMapping=Ae.toneMapping}function Nt(Le,Ae,Ge,Je,De){Ae.isScene!==!0&&(Ae=B),te.resetTextureUnits();const mt=Ae.fog,Ne=Je.isMeshStandardMaterial?Ae.environment:null,Ye=A===null?k.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Qm,nt=(Je.isMeshStandardMaterial?de:fe).get(Je.envMap||Ne),at=Je.vertexColors===!0&&!!Ge.attributes.color&&Ge.attributes.color.itemSize===4,et=!!Ge.attributes.tangent&&(!!Je.normalMap||Je.anisotropy>0),vt=!!Ge.morphAttributes.position,wt=!!Ge.morphAttributes.normal,Ue=!!Ge.morphAttributes.color;let He=Rh;Je.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(He=k.toneMapping);const Dt=Ge.morphAttributes.position||Ge.morphAttributes.normal||Ge.morphAttributes.color,Rt=Dt!==void 0?Dt.length:0,qe=se.get(Je),Ke=b.state.lights;if(he===!0&&(we===!0||Le!==_)){const Dr=Le===_&&Je.id===F;xe.setState(Je,Le,Dr)}let Bt=!1;Je.version===qe.__version?(qe.needsLights&&qe.lightsStateVersion!==Ke.state.version||qe.outputColorSpace!==Ye||De.isBatchedMesh&&qe.batching===!1||!De.isBatchedMesh&&qe.batching===!0||De.isInstancedMesh&&qe.instancing===!1||!De.isInstancedMesh&&qe.instancing===!0||De.isSkinnedMesh&&qe.skinning===!1||!De.isSkinnedMesh&&qe.skinning===!0||De.isInstancedMesh&&qe.instancingColor===!0&&De.instanceColor===null||De.isInstancedMesh&&qe.instancingColor===!1&&De.instanceColor!==null||qe.envMap!==nt||Je.fog===!0&&qe.fog!==mt||qe.numClippingPlanes!==void 0&&(qe.numClippingPlanes!==xe.numPlanes||qe.numIntersection!==xe.numIntersection)||qe.vertexAlphas!==at||qe.vertexTangents!==et||qe.morphTargets!==vt||qe.morphNormals!==wt||qe.morphColors!==Ue||qe.toneMapping!==He||G.isWebGL2===!0&&qe.morphTargetsCount!==Rt)&&(Bt=!0):(Bt=!0,qe.__version=Je.version);let Qt=qe.currentProgram;Bt===!0&&(Qt=cn(Je,Ae,De));let dn=!1,nn=!1,rn=!1;const yn=Qt.getUniforms(),Mn=qe.uniforms;if(K.useProgram(Qt.program)&&(dn=!0,nn=!0,rn=!0),Je.id!==F&&(F=Je.id,nn=!0),dn||_!==Le){yn.setValue(O,"projectionMatrix",Le.projectionMatrix),yn.setValue(O,"viewMatrix",Le.matrixWorldInverse);const Dr=yn.map.cameraPosition;Dr!==void 0&&Dr.setValue(O,E.setFromMatrixPosition(Le.matrixWorld)),G.logarithmicDepthBuffer&&yn.setValue(O,"logDepthBufFC",2/(Math.log(Le.far+1)/Math.LN2)),(Je.isMeshPhongMaterial||Je.isMeshToonMaterial||Je.isMeshLambertMaterial||Je.isMeshBasicMaterial||Je.isMeshStandardMaterial||Je.isShaderMaterial)&&yn.setValue(O,"isOrthographic",Le.isOrthographicCamera===!0),_!==Le&&(_=Le,nn=!0,rn=!0)}if(De.isSkinnedMesh){yn.setOptional(O,De,"bindMatrix"),yn.setOptional(O,De,"bindMatrixInverse");const Dr=De.skeleton;Dr&&(G.floatVertexTextures?(Dr.boneTexture===null&&Dr.computeBoneTexture(),yn.setValue(O,"boneTexture",Dr.boneTexture,te)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}De.isBatchedMesh&&(yn.setOptional(O,De,"batchingTexture"),yn.setValue(O,"batchingTexture",De._matricesTexture,te));const or=Ge.morphAttributes;if((or.position!==void 0||or.normal!==void 0||or.color!==void 0&&G.isWebGL2===!0)&&Be.update(De,Ge,Qt),(nn||qe.receiveShadow!==De.receiveShadow)&&(qe.receiveShadow=De.receiveShadow,yn.setValue(O,"receiveShadow",De.receiveShadow)),Je.isMeshGouraudMaterial&&Je.envMap!==null&&(Mn.envMap.value=nt,Mn.flipEnvMap.value=nt.isCubeTexture&&nt.isRenderTargetTexture===!1?-1:1),nn&&(yn.setValue(O,"toneMappingExposure",k.toneMappingExposure),qe.needsLights&&ut(Mn,rn),mt&&Je.fog===!0&&be.refreshFogUniforms(Mn,mt),be.refreshMaterialUniforms(Mn,Je,Y,ne,$),TN.upload(O,ct(qe),Mn,te)),Je.isShaderMaterial&&Je.uniformsNeedUpdate===!0&&(TN.upload(O,ct(qe),Mn,te),Je.uniformsNeedUpdate=!1),Je.isSpriteMaterial&&yn.setValue(O,"center",De.center),yn.setValue(O,"modelViewMatrix",De.modelViewMatrix),yn.setValue(O,"normalMatrix",De.normalMatrix),yn.setValue(O,"modelMatrix",De.matrixWorld),Je.isShaderMaterial||Je.isRawShaderMaterial){const Dr=Je.uniformsGroups;for(let Gn=0,pi=Dr.length;Gn<pi;Gn++)if(G.isWebGL2){const Un=Dr[Gn];ze.update(Un,Qt),ze.bind(Un,Qt)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return Qt}function ut(Le,Ae){Le.ambientLightColor.needsUpdate=Ae,Le.lightProbe.needsUpdate=Ae,Le.directionalLights.needsUpdate=Ae,Le.directionalLightShadows.needsUpdate=Ae,Le.pointLights.needsUpdate=Ae,Le.pointLightShadows.needsUpdate=Ae,Le.spotLights.needsUpdate=Ae,Le.spotLightShadows.needsUpdate=Ae,Le.rectAreaLights.needsUpdate=Ae,Le.hemisphereLights.needsUpdate=Ae}function Ct(Le){return Le.isMeshLambertMaterial||Le.isMeshToonMaterial||Le.isMeshPhongMaterial||Le.isMeshStandardMaterial||Le.isShadowMaterial||Le.isShaderMaterial&&Le.lights===!0}this.getActiveCubeFace=function(){return P},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return A},this.setRenderTargetTextures=function(Le,Ae,Ge){se.get(Le.texture).__webglTexture=Ae,se.get(Le.depthTexture).__webglTexture=Ge;const Je=se.get(Le);Je.__hasExternalTextures=!0,Je.__hasExternalTextures&&(Je.__autoAllocateDepthBuffer=Ge===void 0,Je.__autoAllocateDepthBuffer||U.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),Je.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(Le,Ae){const Ge=se.get(Le);Ge.__webglFramebuffer=Ae,Ge.__useDefaultFramebuffer=Ae===void 0},this.setRenderTarget=function(Le,Ae=0,Ge=0){A=Le,P=Ae,T=Ge;let Je=!0,De=null,mt=!1,Ne=!1;if(Le){const nt=se.get(Le);nt.__useDefaultFramebuffer!==void 0?(K.bindFramebuffer(O.FRAMEBUFFER,null),Je=!1):nt.__webglFramebuffer===void 0?te.setupRenderTarget(Le):nt.__hasExternalTextures&&te.rebindTextures(Le,se.get(Le.texture).__webglTexture,se.get(Le.depthTexture).__webglTexture);const at=Le.texture;(at.isData3DTexture||at.isDataArrayTexture||at.isCompressedArrayTexture)&&(Ne=!0);const et=se.get(Le).__webglFramebuffer;Le.isWebGLCubeRenderTarget?(Array.isArray(et[Ae])?De=et[Ae][Ge]:De=et[Ae],mt=!0):G.isWebGL2&&Le.samples>0&&te.useMultisampledRTT(Le)===!1?De=se.get(Le).__webglMultisampledFramebuffer:Array.isArray(et)?De=et[Ge]:De=et,M.copy(Le.viewport),H.copy(Le.scissor),I=Le.scissorTest}else M.copy(oe).multiplyScalar(Y).floor(),H.copy(Q).multiplyScalar(Y).floor(),I=le;if(K.bindFramebuffer(O.FRAMEBUFFER,De)&&G.drawBuffers&&Je&&K.drawBuffers(Le,De),K.viewport(M),K.scissor(H),K.setScissorTest(I),mt){const nt=se.get(Le.texture);O.framebufferTexture2D(O.FRAMEBUFFER,O.COLOR_ATTACHMENT0,O.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,nt.__webglTexture,Ge)}else if(Ne){const nt=se.get(Le.texture),at=Ae||0;O.framebufferTextureLayer(O.FRAMEBUFFER,O.COLOR_ATTACHMENT0,nt.__webglTexture,Ge||0,at)}F=-1},this.readRenderTargetPixels=function(Le,Ae,Ge,Je,De,mt,Ne){if(!(Le&&Le.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ye=se.get(Le).__webglFramebuffer;if(Le.isWebGLCubeRenderTarget&&Ne!==void 0&&(Ye=Ye[Ne]),Ye){K.bindFramebuffer(O.FRAMEBUFFER,Ye);try{const nt=Le.texture,at=nt.format,et=nt.type;if(at!==sc&&Re.convert(at)!==O.getParameter(O.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const vt=et===Hw&&(U.has("EXT_color_buffer_half_float")||G.isWebGL2&&U.has("EXT_color_buffer_float"));if(et!==Ih&&Re.convert(et)!==O.getParameter(O.IMPLEMENTATION_COLOR_READ_TYPE)&&!(et===km&&(G.isWebGL2||U.has("OES_texture_float")||U.has("WEBGL_color_buffer_float")))&&!vt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Ae>=0&&Ae<=Le.width-Je&&Ge>=0&&Ge<=Le.height-De&&O.readPixels(Ae,Ge,Je,De,Re.convert(at),Re.convert(et),mt)}finally{const nt=A!==null?se.get(A).__webglFramebuffer:null;K.bindFramebuffer(O.FRAMEBUFFER,nt)}}},this.copyFramebufferToTexture=function(Le,Ae,Ge=0){const Je=Math.pow(2,-Ge),De=Math.floor(Ae.image.width*Je),mt=Math.floor(Ae.image.height*Je);te.setTexture2D(Ae,0),O.copyTexSubImage2D(O.TEXTURE_2D,Ge,0,0,Le.x,Le.y,De,mt),K.unbindTexture()},this.copyTextureToTexture=function(Le,Ae,Ge,Je=0){const De=Ae.image.width,mt=Ae.image.height,Ne=Re.convert(Ge.format),Ye=Re.convert(Ge.type);te.setTexture2D(Ge,0),O.pixelStorei(O.UNPACK_FLIP_Y_WEBGL,Ge.flipY),O.pixelStorei(O.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Ge.premultiplyAlpha),O.pixelStorei(O.UNPACK_ALIGNMENT,Ge.unpackAlignment),Ae.isDataTexture?O.texSubImage2D(O.TEXTURE_2D,Je,Le.x,Le.y,De,mt,Ne,Ye,Ae.image.data):Ae.isCompressedTexture?O.compressedTexSubImage2D(O.TEXTURE_2D,Je,Le.x,Le.y,Ae.mipmaps[0].width,Ae.mipmaps[0].height,Ne,Ae.mipmaps[0].data):O.texSubImage2D(O.TEXTURE_2D,Je,Le.x,Le.y,Ne,Ye,Ae.image),Je===0&&Ge.generateMipmaps&&O.generateMipmap(O.TEXTURE_2D),K.unbindTexture()},this.copyTextureToTexture3D=function(Le,Ae,Ge,Je,De=0){if(k.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const mt=Le.max.x-Le.min.x+1,Ne=Le.max.y-Le.min.y+1,Ye=Le.max.z-Le.min.z+1,nt=Re.convert(Je.format),at=Re.convert(Je.type);let et;if(Je.isData3DTexture)te.setTexture3D(Je,0),et=O.TEXTURE_3D;else if(Je.isDataArrayTexture)te.setTexture2DArray(Je,0),et=O.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}O.pixelStorei(O.UNPACK_FLIP_Y_WEBGL,Je.flipY),O.pixelStorei(O.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Je.premultiplyAlpha),O.pixelStorei(O.UNPACK_ALIGNMENT,Je.unpackAlignment);const vt=O.getParameter(O.UNPACK_ROW_LENGTH),wt=O.getParameter(O.UNPACK_IMAGE_HEIGHT),Ue=O.getParameter(O.UNPACK_SKIP_PIXELS),He=O.getParameter(O.UNPACK_SKIP_ROWS),Dt=O.getParameter(O.UNPACK_SKIP_IMAGES),Rt=Ge.isCompressedTexture?Ge.mipmaps[0]:Ge.image;O.pixelStorei(O.UNPACK_ROW_LENGTH,Rt.width),O.pixelStorei(O.UNPACK_IMAGE_HEIGHT,Rt.height),O.pixelStorei(O.UNPACK_SKIP_PIXELS,Le.min.x),O.pixelStorei(O.UNPACK_SKIP_ROWS,Le.min.y),O.pixelStorei(O.UNPACK_SKIP_IMAGES,Le.min.z),Ge.isDataTexture||Ge.isData3DTexture?O.texSubImage3D(et,De,Ae.x,Ae.y,Ae.z,mt,Ne,Ye,nt,at,Rt.data):Ge.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),O.compressedTexSubImage3D(et,De,Ae.x,Ae.y,Ae.z,mt,Ne,Ye,nt,Rt.data)):O.texSubImage3D(et,De,Ae.x,Ae.y,Ae.z,mt,Ne,Ye,nt,at,Rt),O.pixelStorei(O.UNPACK_ROW_LENGTH,vt),O.pixelStorei(O.UNPACK_IMAGE_HEIGHT,wt),O.pixelStorei(O.UNPACK_SKIP_PIXELS,Ue),O.pixelStorei(O.UNPACK_SKIP_ROWS,He),O.pixelStorei(O.UNPACK_SKIP_IMAGES,Dt),De===0&&Je.generateMipmaps&&O.generateMipmap(et),K.unbindTexture()},this.initTexture=function(Le){Le.isCubeTexture?te.setTextureCube(Le,0):Le.isData3DTexture?te.setTexture3D(Le,0):Le.isDataArrayTexture||Le.isCompressedArrayTexture?te.setTexture2DArray(Le,0):te.setTexture2D(Le,0),K.unbindTexture()},this.resetState=function(){P=0,T=0,A=null,K.reset(),We.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return eu}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===XO?"display-p3":"srgb",n.unpackColorSpace=sa.workingColorSpace===RT?"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===Ms?bg:lee}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===bg?Ms:Qm}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 wEe extends rR{}wEe.prototype.isWebGL1Renderer=!0;class r4{constructor(e,n=1,a=1e3){this.isFog=!0,this.name="",this.color=new On(e),this.near=n,this.far=a}clone(){return new r4(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class SEe extends So{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 _Ee{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=JL,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Rm()}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,a){e*=this.stride,a*=n.stride;for(let i=0,s=this.stride;i<s;i++)this.array[e+i]=n.array[a+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=Rm()),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]),a=new this.constructor(n,this.stride);return a.setUsage(this.usage),a}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=Rm()),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 po=new yt;class vh{constructor(e,n,a,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=n,this.offset=a,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,a=this.data.count;n<a;n++)po.fromBufferAttribute(this,n),po.applyMatrix4(e),this.setXYZ(n,po.x,po.y,po.z);return this}applyNormalMatrix(e){for(let n=0,a=this.count;n<a;n++)po.fromBufferAttribute(this,n),po.applyNormalMatrix(e),this.setXYZ(n,po.x,po.y,po.z);return this}transformDirection(e){for(let n=0,a=this.count;n<a;n++)po.fromBufferAttribute(this,n),po.transformDirection(e),this.setXYZ(n,po.x,po.y,po.z);return this}setX(e,n){return this.normalized&&(n=ia(n,this.array)),this.data.array[e*this.data.stride+this.offset]=n,this}setY(e,n){return this.normalized&&(n=ia(n,this.array)),this.data.array[e*this.data.stride+this.offset+1]=n,this}setZ(e,n){return this.normalized&&(n=ia(n,this.array)),this.data.array[e*this.data.stride+this.offset+2]=n,this}setW(e,n){return this.normalized&&(n=ia(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=Yd(n,this.array)),n}getY(e){let n=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(n=Yd(n,this.array)),n}getZ(e){let n=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(n=Yd(n,this.array)),n}getW(e){let n=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(n=Yd(n,this.array)),n}setXY(e,n,a){return e=e*this.data.stride+this.offset,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=a,this}setXYZ(e,n,a,i){return e=e*this.data.stride+this.offset,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array),i=ia(i,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=a,this.data.array[e+2]=i,this}setXYZW(e,n,a,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(n=ia(n,this.array),a=ia(a,this.array),i=ia(i,this.array),s=ia(s,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=a,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 a=0;a<this.count;a++){const i=a*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[i+s])}return new _l(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 vh(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 a=0;a<this.count;a++){const i=a*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 kEe extends Qo{constructor(e=null,n=1,a=1,i,s,o,l,c,d=js,u=js,m,p){super(null,o,l,c,d,u,i,s,m,p),this.isDataTexture=!0,this.image={data:e,width:n,height:a},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function NEe(t,e){return t.z-e.z}function CEe(t,e){return e.z-t.z}class PEe{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,n){const a=this.pool,i=this.list;this.index>=a.length&&a.push({start:-1,count:-1,z:-1});const s=a[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 Tx="batchId",Qp=new Sa,iV=new Sa,TEe=new Sa,sV=new Sa,v2=new IT,v1=new gc,Hf=new lu,m0=new yt,w2=new PEe,Ws=new cd,w1=[];function AEe(t,e,n=0){const a=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<a;o++)e.setComponent(s+n,o,t.getComponent(s,o))}else e.array.set(t.array,n*a);e.needsUpdate=!0}class jEe extends cd{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,n,a=n*2,i){super(new io,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=a,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),a=new kEe(n,e,e,sc,km);this._matricesTexture=a}_initializeGeometry(e){const n=this.geometry,a=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(a*u),f=new c.constructor(p,u,m);f.setUsage(c.usage),n.setAttribute(l,f)}if(e.getIndex()!==null){const l=a>65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new _l(l,1))}const o=i>65536?new Uint32Array(a):new Uint16Array(a);n.setAttribute(Tx,new _l(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(Tx))throw new Error(`BatchedMesh: Geometry cannot use attribute "${Tx}"`);const n=this.geometry;if(!!e.getIndex()!=!!n.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const a in n.attributes){if(a===Tx)continue;if(!e.hasAttribute(a))throw new Error(`BatchedMesh: Added geometry missing "${a}". All geometries must have consistent attributes.`);const i=e.getAttribute(a),s=n.getAttribute(a);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 gc);const e=this._geometryCount,n=this.boundingBox,a=this._active;n.makeEmpty();for(let i=0;i<e;i++)a[i]!==!1&&(this.getMatrixAt(i,Qp),this.getBoundingBoxAt(i,v1).applyMatrix4(Qp),n.union(v1))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new lu);const e=this._geometryCount,n=this.boundingSphere,a=this._active;n.makeEmpty();for(let i=0;i<e;i++)a[i]!==!1&&(this.getMatrixAt(i,Qp),this.getBoundingSphereAt(i,Hf).applyMatrix4(Qp),n.union(Hf))}addGeometry(e,n=-1,a=-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&&(a===-1?i.indexCount=d.count:i.indexCount=a,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,g=this._matricesTexture.image.data;m.push(!0),p.push(!0);const w=this._geometryCount;this._geometryCount++,TEe.toArray(g,w*16),f.needsUpdate=!0,o.push(i),l.push({start:u?i.indexStart:i.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new gc,sphereInitialized:!1,sphere:new lu});const b=this.geometry.getAttribute(Tx);for(let x=0;x<i.vertexCount;x++)b.setX(i.vertexStart+x,w);return b.needsUpdate=!0,this.setGeometryAt(w,e),w}setGeometryAt(e,n){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(n);const a=this.geometry,i=a.getIndex()!==null,s=a.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 a.attributes){if(f===Tx)continue;const g=n.getAttribute(f),w=a.getAttribute(f);AEe(g,w,c);const b=g.itemSize;for(let x=g.count,S=d;x<S;x++){const k=c+x;for(let C=0;C<b;C++)w.setComponent(k,C,0)}w.needsUpdate=!0}if(i){const f=l.indexStart;for(let g=0;g<o.count;g++)s.setX(f+g,c+o.getX(g));for(let g=o.count,w=l.indexCount;g<w;g++)s.setX(f+g,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(m0.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,v1),v1.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)),m0.fromBufferAttribute(c,f),u=Math.max(u,s.center.distanceToSquared(m0))}s.radius=Math.sqrt(u),i.sphereInitialized=!0}return n.copy(s),n}setMatrixAt(e,n){const a=this._active,i=this._matricesTexture,s=this._matricesTexture.image.data,o=this._geometryCount;return e>=o||a[e]===!1?this:(n.toArray(s,e*16),i.needsUpdate=!0,this)}getMatrixAt(e,n){const a=this._active,i=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||a[e]===!1?null:n.fromArray(i,e*16)}setVisibleAt(e,n){const a=this._visibility,i=this._active,s=this._geometryCount;return e>=s||i[e]===!1||a[e]===n?this:(a[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,a=this._active,i=this._geometryCount;return e>=i||a[e]===!1?!1:n[e]}raycast(e,n){const a=this._visibility,i=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;Ws.material=this.material,Ws.geometry.index=c.index,Ws.geometry.attributes=c.attributes,Ws.geometry.boundingBox===null&&(Ws.geometry.boundingBox=new gc),Ws.geometry.boundingSphere===null&&(Ws.geometry.boundingSphere=new lu);for(let d=0;d<o;d++){if(!a[d]||!i[d])continue;const u=s[d];Ws.geometry.setDrawRange(u.start,u.count),this.getMatrixAt(d,Ws.matrixWorld).premultiply(l),this.getBoundingBoxAt(d,Ws.geometry.boundingBox),this.getBoundingSphereAt(d,Ws.geometry.boundingSphere),Ws.raycast(e,w1);for(let m=0,p=w1.length;m<p;m++){const f=w1[m];f.object=this,f.batchId=d,n.push(f)}w1.length=0}Ws.material=null,Ws.geometry.index=null,Ws.geometry.attributes={},Ws.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,a,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&&(sV.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse).multiply(this.matrixWorld),v2.setFromProjectionMatrix(sV,e.isWebGPURenderer?qw:eu));let f=0;if(this.sortObjects){iV.copy(this.matrixWorld).invert(),m0.setFromMatrixPosition(a.matrixWorld).applyMatrix4(iV);for(let b=0,x=c.length;b<x;b++)if(c[b]){this.getMatrixAt(b,Qp),this.getBoundingSphereAt(b,Hf).applyMatrix4(Qp);let S=!1;if(p&&(S=!v2.intersectsSphere(Hf)),!S){const k=m0.distanceTo(Hf.center);w2.push(m[b],k)}}const g=w2.list,w=this.customSort;w===null?g.sort(s.transparent?CEe:NEe):w.call(this,g,a);for(let b=0,x=g.length;b<x;b++){const S=g[b];d[f]=S.start*l,u[f]=S.count,f++}w2.reset()}else for(let g=0,w=c.length;g<w;g++)if(c[g]){let b=!1;if(p&&(this.getMatrixAt(g,Qp),this.getBoundingSphereAt(g,Hf).applyMatrix4(Qp),b=!v2.intersectsSphere(Hf)),!b){const x=m[g];d[f]=x.start*l,u[f]=x.count,f++}}this._multiDrawCount=f,this._visibilityChanged=!1}onBeforeShadow(e,n,a,i,s,o){this.onBeforeRender(e,null,i,s,o)}}class BS extends Jy{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new On(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 oV=new yt,lV=new yt,cV=new Sa,S2=new JO,S1=new lu;let MEe=class extends So{constructor(e=new io,n=new BS){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,a=[0];for(let i=1,s=n.count;i<s;i++)oV.fromBufferAttribute(n,i-1),lV.fromBufferAttribute(n,i),a[i]=a[i-1],a[i]+=oV.distanceTo(lV);e.setAttribute("lineDistance",new ui(a,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const a=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=a.drawRange;if(a.boundingSphere===null&&a.computeBoundingSphere(),S1.copy(a.boundingSphere),S1.applyMatrix4(i),S1.radius+=s,e.ray.intersectsSphere(S1)===!1)return;cV.copy(i).invert(),S2.copy(e.ray).applyMatrix4(cV);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,d=new yt,u=new yt,m=new yt,p=new yt,f=this.isLineSegments?2:1,g=a.index,b=a.attributes.position;if(g!==null){const x=Math.max(0,o.start),S=Math.min(g.count,o.start+o.count);for(let k=x,C=S-1;k<C;k+=f){const P=g.getX(k),T=g.getX(k+1);if(d.fromBufferAttribute(b,P),u.fromBufferAttribute(b,T),S2.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:k,face:null,faceIndex:null,object:this})}}else{const x=Math.max(0,o.start),S=Math.min(b.count,o.start+o.count);for(let k=x,C=S-1;k<C;k+=f){if(d.fromBufferAttribute(b,k),u.fromBufferAttribute(b,k+1),S2.distanceSqToSegment(d,u,p,m)>c)continue;p.applyMatrix4(this.matrixWorld);const T=e.ray.origin.distanceTo(p);T<e.near||T>e.far||n.push({distance:T,point:m.clone().applyMatrix4(this.matrixWorld),index:k,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,a=Object.keys(n);if(a.length>0){const i=n[a[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 dV=new yt,uV=new yt;class zT extends MEe{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,a=[];for(let i=0,s=n.count;i<s;i+=2)dV.fromBufferAttribute(n,i),uV.fromBufferAttribute(n,i+1),a[i]=i===0?0:a[i-1],a[i+1]=a[i]+dV.distanceTo(uV);e.setAttribute("lineDistance",new ui(a,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class EEe extends io{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const n=[],a=new Set,i=new yt,s=new yt;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 g=p,w=p+f;g<w;g+=3)for(let b=0;b<3;b++){const x=l.getX(g+b),S=l.getX(g+(b+1)%3);i.fromBufferAttribute(o,x),s.fromBufferAttribute(o,S),mV(i,s,a)===!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),mV(i,s,a)===!0&&(n.push(i.x,i.y,i.z),n.push(s.x,s.y,s.z))}}this.setAttribute("position",new ui(n,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function mV(t,e,n){const a=`${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(a)===!0||n.has(i)===!0?!1:(n.add(a),n.add(i),!0)}class DEe extends Jy{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new On(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new On(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=cee,this.normalScale=new Wn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=QO,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 FEe extends BS{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 Mee extends So{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new On(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 _2=new Sa,pV=new yt,hV=new yt;class LEe{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Wn(512,512),this.map=null,this.mapPass=null,this.matrix=new Sa,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new IT,this._frameExtents=new Wn(1,1),this._viewportCount=1,this._viewports=[new la(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,a=this.matrix;pV.setFromMatrixPosition(e.matrixWorld),n.position.copy(pV),hV.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(hV),n.updateMatrixWorld(),_2.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(_2),a.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),a.multiply(_2)}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 fV=new Sa,p0=new yt,k2=new yt;class REe extends LEe{constructor(){super(new gl(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Wn(4,2),this._viewportCount=6,this._viewports=[new la(2,1,1,1),new la(0,1,1,1),new la(3,1,1,1),new la(1,1,1,1),new la(3,0,1,1),new la(1,0,1,1)],this._cubeDirections=[new yt(1,0,0),new yt(-1,0,0),new yt(0,0,1),new yt(0,0,-1),new yt(0,1,0),new yt(0,-1,0)],this._cubeUps=[new yt(0,1,0),new yt(0,1,0),new yt(0,1,0),new yt(0,1,0),new yt(0,0,1),new yt(0,0,-1)]}updateMatrices(e,n=0){const a=this.camera,i=this.matrix,s=e.distance||a.far;s!==a.far&&(a.far=s,a.updateProjectionMatrix()),p0.setFromMatrixPosition(e.matrixWorld),a.position.copy(p0),k2.copy(a.position),k2.add(this._cubeDirections[n]),a.up.copy(this._cubeUps[n]),a.lookAt(k2),a.updateMatrixWorld(),i.makeTranslation(-p0.x,-p0.y,-p0.z),fV.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),this._frustum.setFromProjectionMatrix(fV)}}class IEe extends Mee{constructor(e,n,a=0,i=2){super(e,n),this.isPointLight=!0,this.type="PointLight",this.distance=a,this.decay=i,this.shadow=new REe}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 OEe extends Mee{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}}class zEe extends io{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 _Ee{constructor(e,n,a=1){super(e,n),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=a}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 gV{constructor(e=1,n=0,a=0){return this.radius=e,this.phi=n,this.theta=a,this}set(e,n,a){return this.radius=e,this.phi=n,this.theta=a,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,a){return this.radius=Math.sqrt(e*e+n*n+a*a),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,a),this.phi=Math.acos(Ds(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const bV=new yt,_1=new yt;class UEe{constructor(e=new yt,n=new yt){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){bV.subVectors(e,this.start),_1.subVectors(this.end,this.start);const a=_1.dot(_1);let s=_1.dot(bV)/a;return n&&(s=Ds(s,0,1)),s}closestPointToPoint(e,n,a){const i=this.closestPointToPointParameter(e,n);return this.delta(a).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 BEe extends zT{constructor(e=1){const n=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],a=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new io;i.setAttribute("position",new ui(n,3)),i.setAttribute("color",new ui(a,3));const s=new BS({vertexColors:!0,toneMapped:!1});super(i,s),this.type="AxesHelper"}setColors(e,n,a){const i=new On,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(a),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:FT}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=FT);class cu{constructor(e,n,a,i,s="div"){this.parent=e,this.object=n,this.property=a,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"),cu.nextNameID=cu.nextNameID||0,this.$name.id=`lil-gui-name-${++cu.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(a)}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 HEe extends cu{constructor(e,n,a){super(e,n,a,"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 qEe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:iR,toHexString:iR},Vw={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},$Ee={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const a=Vw.fromHexString(t);e[0]=(a>>16&255)/255*n,e[1]=(a>>8&255)/255*n,e[2]=(a&255)/255*n},toHexString([t,e,n],a=1){a=255/a;const i=t*a<<16^e*a<<8^n*a<<0;return Vw.toHexString(i)}},VEe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const a=Vw.fromHexString(t);e.r=(a>>16&255)/255*n,e.g=(a>>8&255)/255*n,e.b=(a&255)/255*n},toHexString({r:t,g:e,b:n},a=1){a=255/a;const i=t*a<<16^e*a<<8^n*a<<0;return Vw.toHexString(i)}},GEe=[qEe,Vw,$Ee,VEe];function WEe(t){return GEe.find(e=>e.match(t))}class KEe extends cu{constructor(e,n,a,i){super(e,n,a,"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=WEe(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 N2 extends cu{constructor(e,n,a){super(e,n,a,"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 QEe extends cu{constructor(e,n,a,i,s,o){super(e,n,a,"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 S=parseFloat(this.$input.value);isNaN(S)||(this._stepExplicit&&(S=this._snap(S)),this.setValue(this._clamp(S)))},a=S=>{const k=parseFloat(this.$input.value);isNaN(k)||(this._snapClampSetValue(k+S),this.$input.value=this.getValue())},i=S=>{S.key==="Enter"&&this.$input.blur(),S.code==="ArrowUp"&&(S.preventDefault(),a(this._step*this._arrowKeyMultiplier(S))),S.code==="ArrowDown"&&(S.preventDefault(),a(this._step*this._arrowKeyMultiplier(S)*-1))},s=S=>{this._inputFocused&&(S.preventDefault(),a(this._step*this._normalizeMouseWheel(S)))};let o=!1,l,c,d,u,m;const p=5,f=S=>{l=S.clientX,c=d=S.clientY,o=!0,u=this.getValue(),m=0,window.addEventListener("mousemove",g),window.addEventListener("mouseup",w)},g=S=>{if(o){const k=S.clientX-l,C=S.clientY-c;Math.abs(C)>p?(S.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(k)>p&&w()}if(!o){const k=S.clientY-d;m-=k*this._step*this._arrowKeyMultiplier(S),u+m>this._max?m=this._max-u:u+m<this._min&&(m=this._min-u),this._snapClampSetValue(u+m)}d=S.clientY},w=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",w)},b=()=>{this._inputFocused=!0},x=()=>{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",b),this.$input.addEventListener("blur",x)}_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=(x,S,k,C,P)=>(x-S)/(k-S)*(P-C)+C,n=x=>{const S=this.$slider.getBoundingClientRect();let k=e(x,S.left,S.right,this._min,this._max);this._snapClampSetValue(k)},a=x=>{this._setDraggingStyle(!0),n(x.clientX),window.addEventListener("mousemove",i),window.addEventListener("mouseup",s)},i=x=>{n(x.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",s)};let o=!1,l,c;const d=x=>{x.preventDefault(),this._setDraggingStyle(!0),n(x.touches[0].clientX),o=!1},u=x=>{x.touches.length>1||(this._hasScrollBar?(l=x.touches[0].clientX,c=x.touches[0].clientY,o=!0):d(x),window.addEventListener("touchmove",m,{passive:!1}),window.addEventListener("touchend",p))},m=x=>{if(o){const S=x.touches[0].clientX-l,k=x.touches[0].clientY-c;Math.abs(S)>Math.abs(k)?d(x):(window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p))}else x.preventDefault(),n(x.touches[0].clientX)},p=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",m),window.removeEventListener("touchend",p)},f=this._callOnFinishChange.bind(this),g=400;let w;const b=x=>{if(Math.abs(x.deltaX)<Math.abs(x.deltaY)&&this._hasScrollBar)return;x.preventDefault();const k=this._normalizeMouseWheel(x)*this._step;this._snapClampSetValue(this.getValue()+k),this.$input.value=this.getValue(),clearTimeout(w),w=setTimeout(f,g)};this.$slider.addEventListener("mousedown",a),this.$slider.addEventListener("touchstart",u,{passive:!1}),this.$slider.addEventListener("wheel",b,{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:a}=e;return Math.floor(e.deltaY)!==e.deltaY&&e.wheelDelta&&(n=0,a=-e.wheelDelta/120,a*=this._stepExplicit?1:10),n+-a}_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 YEe extends cu{constructor(e,n,a,i){super(e,n,a,"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 a=document.createElement("option");a.textContent=n,this.$select.appendChild(a)}),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 XEe extends cu{constructor(e,n,a){super(e,n,a,"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 ZEe=`.lil-gui {
  7421. font-family: var(--font-family);
  7422. font-size: var(--font-size);
  7423. line-height: 1;
  7424. font-weight: normal;
  7425. font-style: normal;
  7426. text-align: left;
  7427. color: var(--text-color);
  7428. user-select: none;
  7429. -webkit-user-select: none;
  7430. touch-action: manipulation;
  7431. --background-color: #1f1f1f;
  7432. --text-color: #ebebeb;
  7433. --title-background-color: #111111;
  7434. --title-text-color: #ebebeb;
  7435. --widget-color: #424242;
  7436. --hover-color: #4f4f4f;
  7437. --focus-color: #595959;
  7438. --number-color: #2cc9ff;
  7439. --string-color: #a2db3c;
  7440. --font-size: 11px;
  7441. --input-font-size: 11px;
  7442. --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
  7443. --font-family-mono: Menlo, Monaco, Consolas, "Droid Sans Mono", monospace;
  7444. --padding: 4px;
  7445. --spacing: 4px;
  7446. --widget-height: 20px;
  7447. --title-height: calc(var(--widget-height) + var(--spacing) * 1.25);
  7448. --name-width: 45%;
  7449. --slider-knob-width: 2px;
  7450. --slider-input-width: 27%;
  7451. --color-input-width: 27%;
  7452. --slider-input-min-width: 45px;
  7453. --color-input-min-width: 45px;
  7454. --folder-indent: 7px;
  7455. --widget-padding: 0 0 0 3px;
  7456. --widget-border-radius: 2px;
  7457. --checkbox-size: calc(0.75 * var(--widget-height));
  7458. --scrollbar-width: 5px;
  7459. }
  7460. .lil-gui, .lil-gui * {
  7461. box-sizing: border-box;
  7462. margin: 0;
  7463. padding: 0;
  7464. }
  7465. .lil-gui.root {
  7466. width: var(--width, 245px);
  7467. display: flex;
  7468. flex-direction: column;
  7469. background: var(--background-color);
  7470. }
  7471. .lil-gui.root > .title {
  7472. background: var(--title-background-color);
  7473. color: var(--title-text-color);
  7474. }
  7475. .lil-gui.root > .children {
  7476. overflow-x: hidden;
  7477. overflow-y: auto;
  7478. }
  7479. .lil-gui.root > .children::-webkit-scrollbar {
  7480. width: var(--scrollbar-width);
  7481. height: var(--scrollbar-width);
  7482. background: var(--background-color);
  7483. }
  7484. .lil-gui.root > .children::-webkit-scrollbar-thumb {
  7485. border-radius: var(--scrollbar-width);
  7486. background: var(--focus-color);
  7487. }
  7488. @media (pointer: coarse) {
  7489. .lil-gui.allow-touch-styles, .lil-gui.allow-touch-styles .lil-gui {
  7490. --widget-height: 28px;
  7491. --padding: 6px;
  7492. --spacing: 6px;
  7493. --font-size: 13px;
  7494. --input-font-size: 16px;
  7495. --folder-indent: 10px;
  7496. --scrollbar-width: 7px;
  7497. --slider-input-min-width: 50px;
  7498. --color-input-min-width: 65px;
  7499. }
  7500. }
  7501. .lil-gui.force-touch-styles, .lil-gui.force-touch-styles .lil-gui {
  7502. --widget-height: 28px;
  7503. --padding: 6px;
  7504. --spacing: 6px;
  7505. --font-size: 13px;
  7506. --input-font-size: 16px;
  7507. --folder-indent: 10px;
  7508. --scrollbar-width: 7px;
  7509. --slider-input-min-width: 50px;
  7510. --color-input-min-width: 65px;
  7511. }
  7512. .lil-gui.autoPlace {
  7513. max-height: 100%;
  7514. position: fixed;
  7515. top: 0;
  7516. right: 15px;
  7517. z-index: 1001;
  7518. }
  7519. .lil-gui .controller {
  7520. display: flex;
  7521. align-items: center;
  7522. padding: 0 var(--padding);
  7523. margin: var(--spacing) 0;
  7524. }
  7525. .lil-gui .controller.disabled {
  7526. opacity: 0.5;
  7527. }
  7528. .lil-gui .controller.disabled, .lil-gui .controller.disabled * {
  7529. pointer-events: none !important;
  7530. }
  7531. .lil-gui .controller > .name {
  7532. min-width: var(--name-width);
  7533. flex-shrink: 0;
  7534. white-space: pre;
  7535. padding-right: var(--spacing);
  7536. line-height: var(--widget-height);
  7537. }
  7538. .lil-gui .controller .widget {
  7539. position: relative;
  7540. display: flex;
  7541. align-items: center;
  7542. width: 100%;
  7543. min-height: var(--widget-height);
  7544. }
  7545. .lil-gui .controller.string input {
  7546. color: var(--string-color);
  7547. }
  7548. .lil-gui .controller.boolean {
  7549. cursor: pointer;
  7550. }
  7551. .lil-gui .controller.color .display {
  7552. width: 100%;
  7553. height: var(--widget-height);
  7554. border-radius: var(--widget-border-radius);
  7555. position: relative;
  7556. }
  7557. @media (hover: hover) {
  7558. .lil-gui .controller.color .display:hover:before {
  7559. content: " ";
  7560. display: block;
  7561. position: absolute;
  7562. border-radius: var(--widget-border-radius);
  7563. border: 1px solid #fff9;
  7564. top: 0;
  7565. right: 0;
  7566. bottom: 0;
  7567. left: 0;
  7568. }
  7569. }
  7570. .lil-gui .controller.color input[type=color] {
  7571. opacity: 0;
  7572. width: 100%;
  7573. height: 100%;
  7574. cursor: pointer;
  7575. }
  7576. .lil-gui .controller.color input[type=text] {
  7577. margin-left: var(--spacing);
  7578. font-family: var(--font-family-mono);
  7579. min-width: var(--color-input-min-width);
  7580. width: var(--color-input-width);
  7581. flex-shrink: 0;
  7582. }
  7583. .lil-gui .controller.option select {
  7584. opacity: 0;
  7585. position: absolute;
  7586. width: 100%;
  7587. max-width: 100%;
  7588. }
  7589. .lil-gui .controller.option .display {
  7590. position: relative;
  7591. pointer-events: none;
  7592. border-radius: var(--widget-border-radius);
  7593. height: var(--widget-height);
  7594. line-height: var(--widget-height);
  7595. max-width: 100%;
  7596. overflow: hidden;
  7597. word-break: break-all;
  7598. padding-left: 0.55em;
  7599. padding-right: 1.75em;
  7600. background: var(--widget-color);
  7601. }
  7602. @media (hover: hover) {
  7603. .lil-gui .controller.option .display.focus {
  7604. background: var(--focus-color);
  7605. }
  7606. }
  7607. .lil-gui .controller.option .display.active {
  7608. background: var(--focus-color);
  7609. }
  7610. .lil-gui .controller.option .display:after {
  7611. font-family: "lil-gui";
  7612. content: "↕";
  7613. position: absolute;
  7614. top: 0;
  7615. right: 0;
  7616. bottom: 0;
  7617. padding-right: 0.375em;
  7618. }
  7619. .lil-gui .controller.option .widget,
  7620. .lil-gui .controller.option select {
  7621. cursor: pointer;
  7622. }
  7623. @media (hover: hover) {
  7624. .lil-gui .controller.option .widget:hover .display {
  7625. background: var(--hover-color);
  7626. }
  7627. }
  7628. .lil-gui .controller.number input {
  7629. color: var(--number-color);
  7630. }
  7631. .lil-gui .controller.number.hasSlider input {
  7632. margin-left: var(--spacing);
  7633. width: var(--slider-input-width);
  7634. min-width: var(--slider-input-min-width);
  7635. flex-shrink: 0;
  7636. }
  7637. .lil-gui .controller.number .slider {
  7638. width: 100%;
  7639. height: var(--widget-height);
  7640. background: var(--widget-color);
  7641. border-radius: var(--widget-border-radius);
  7642. padding-right: var(--slider-knob-width);
  7643. overflow: hidden;
  7644. cursor: ew-resize;
  7645. touch-action: pan-y;
  7646. }
  7647. @media (hover: hover) {
  7648. .lil-gui .controller.number .slider:hover {
  7649. background: var(--hover-color);
  7650. }
  7651. }
  7652. .lil-gui .controller.number .slider.active {
  7653. background: var(--focus-color);
  7654. }
  7655. .lil-gui .controller.number .slider.active .fill {
  7656. opacity: 0.95;
  7657. }
  7658. .lil-gui .controller.number .fill {
  7659. height: 100%;
  7660. border-right: var(--slider-knob-width) solid var(--number-color);
  7661. box-sizing: content-box;
  7662. }
  7663. .lil-gui-dragging .lil-gui {
  7664. --hover-color: var(--widget-color);
  7665. }
  7666. .lil-gui-dragging * {
  7667. cursor: ew-resize !important;
  7668. }
  7669. .lil-gui-dragging.lil-gui-vertical * {
  7670. cursor: ns-resize !important;
  7671. }
  7672. .lil-gui .title {
  7673. height: var(--title-height);
  7674. line-height: calc(var(--title-height) - 4px);
  7675. font-weight: 600;
  7676. padding: 0 var(--padding);
  7677. -webkit-tap-highlight-color: transparent;
  7678. cursor: pointer;
  7679. outline: none;
  7680. text-decoration-skip: objects;
  7681. }
  7682. .lil-gui .title:before {
  7683. font-family: "lil-gui";
  7684. content: "▾";
  7685. padding-right: 2px;
  7686. display: inline-block;
  7687. }
  7688. .lil-gui .title:active {
  7689. background: var(--title-background-color);
  7690. opacity: 0.75;
  7691. }
  7692. @media (hover: hover) {
  7693. body:not(.lil-gui-dragging) .lil-gui .title:hover {
  7694. background: var(--title-background-color);
  7695. opacity: 0.85;
  7696. }
  7697. .lil-gui .title:focus {
  7698. text-decoration: underline var(--focus-color);
  7699. }
  7700. }
  7701. .lil-gui.root > .title:focus {
  7702. text-decoration: none !important;
  7703. }
  7704. .lil-gui.closed > .title:before {
  7705. content: "▸";
  7706. }
  7707. .lil-gui.closed > .children {
  7708. transform: translateY(-7px);
  7709. opacity: 0;
  7710. }
  7711. .lil-gui.closed:not(.transition) > .children {
  7712. display: none;
  7713. }
  7714. .lil-gui.transition > .children {
  7715. transition-duration: 300ms;
  7716. transition-property: height, opacity, transform;
  7717. transition-timing-function: cubic-bezier(0.2, 0.6, 0.35, 1);
  7718. overflow: hidden;
  7719. pointer-events: none;
  7720. }
  7721. .lil-gui .children:empty:before {
  7722. content: "Empty";
  7723. padding: 0 var(--padding);
  7724. margin: var(--spacing) 0;
  7725. display: block;
  7726. height: var(--widget-height);
  7727. font-style: italic;
  7728. line-height: var(--widget-height);
  7729. opacity: 0.5;
  7730. }
  7731. .lil-gui.root > .children > .lil-gui > .title {
  7732. border: 0 solid var(--widget-color);
  7733. border-width: 1px 0;
  7734. transition: border-color 300ms;
  7735. }
  7736. .lil-gui.root > .children > .lil-gui.closed > .title {
  7737. border-bottom-color: transparent;
  7738. }
  7739. .lil-gui + .controller {
  7740. border-top: 1px solid var(--widget-color);
  7741. margin-top: 0;
  7742. padding-top: var(--spacing);
  7743. }
  7744. .lil-gui .lil-gui .lil-gui > .title {
  7745. border: none;
  7746. }
  7747. .lil-gui .lil-gui .lil-gui > .children {
  7748. border: none;
  7749. margin-left: var(--folder-indent);
  7750. border-left: 2px solid var(--widget-color);
  7751. }
  7752. .lil-gui .lil-gui .controller {
  7753. border: none;
  7754. }
  7755. .lil-gui label, .lil-gui input, .lil-gui button {
  7756. -webkit-tap-highlight-color: transparent;
  7757. }
  7758. .lil-gui input {
  7759. border: 0;
  7760. outline: none;
  7761. font-family: var(--font-family);
  7762. font-size: var(--input-font-size);
  7763. border-radius: var(--widget-border-radius);
  7764. height: var(--widget-height);
  7765. background: var(--widget-color);
  7766. color: var(--text-color);
  7767. width: 100%;
  7768. }
  7769. @media (hover: hover) {
  7770. .lil-gui input:hover {
  7771. background: var(--hover-color);
  7772. }
  7773. .lil-gui input:active {
  7774. background: var(--focus-color);
  7775. }
  7776. }
  7777. .lil-gui input:disabled {
  7778. opacity: 1;
  7779. }
  7780. .lil-gui input[type=text],
  7781. .lil-gui input[type=number] {
  7782. padding: var(--widget-padding);
  7783. -moz-appearance: textfield;
  7784. }
  7785. .lil-gui input[type=text]:focus,
  7786. .lil-gui input[type=number]:focus {
  7787. background: var(--focus-color);
  7788. }
  7789. .lil-gui input[type=checkbox] {
  7790. appearance: none;
  7791. width: var(--checkbox-size);
  7792. height: var(--checkbox-size);
  7793. border-radius: var(--widget-border-radius);
  7794. text-align: center;
  7795. cursor: pointer;
  7796. }
  7797. .lil-gui input[type=checkbox]:checked:before {
  7798. font-family: "lil-gui";
  7799. content: "✓";
  7800. font-size: var(--checkbox-size);
  7801. line-height: var(--checkbox-size);
  7802. }
  7803. @media (hover: hover) {
  7804. .lil-gui input[type=checkbox]:focus {
  7805. box-shadow: inset 0 0 0 1px var(--focus-color);
  7806. }
  7807. }
  7808. .lil-gui button {
  7809. outline: none;
  7810. cursor: pointer;
  7811. font-family: var(--font-family);
  7812. font-size: var(--font-size);
  7813. color: var(--text-color);
  7814. width: 100%;
  7815. height: var(--widget-height);
  7816. text-transform: none;
  7817. background: var(--widget-color);
  7818. border-radius: var(--widget-border-radius);
  7819. border: none;
  7820. }
  7821. @media (hover: hover) {
  7822. .lil-gui button:hover {
  7823. background: var(--hover-color);
  7824. }
  7825. .lil-gui button:focus {
  7826. box-shadow: inset 0 0 0 1px var(--focus-color);
  7827. }
  7828. }
  7829. .lil-gui button:active {
  7830. background: var(--focus-color);
  7831. }
  7832. @font-face {
  7833. font-family: "lil-gui";
  7834. 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");
  7835. }`;function JEe(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 xV=!1;class vC{constructor({parent:e,autoPlace:n=e===void 0,container:a,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"),!xV&&l&&(JEe(ZEe),xV=!0),a?a.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,a,i,s){if(Object(a)===a)return new YEe(this,e,n,a);const o=e[n];switch(typeof o){case"number":return new QEe(this,e,n,a,i,s);case"boolean":return new HEe(this,e,n);case"string":return new XEe(this,e,n);case"function":return new N2(this,e,n)}console.error(`gui.add failed
  7836. property:`,n,`
  7837. object:`,e,`
  7838. value:`,o)}addColor(e,n,a=1){return new KEe(this,e,n,a)}addFolder(e){const n=new vC({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(a=>{a instanceof N2||a._name in e.controllers&&a.load(e.controllers[a._name])}),n&&e.folders&&this.folders.forEach(a=>{a._title in e.folders&&a.load(e.folders[a._title])}),this}save(e=!0){const n={controllers:{},folders:{}};return this.controllers.forEach(a=>{if(!(a instanceof N2)){if(a._name in n.controllers)throw new Error(`Cannot save GUI with duplicate property "${a._name}"`);n.controllers[a._name]=a.save()}}),e&&this.folders.forEach(a=>{if(a._title in n.folders)throw new Error(`Cannot save GUI with duplicate folder "${a._title}"`);n.folders[a._title]=a.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 a=s=>{s.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",a))};this.$children.addEventListener("transitionend",a);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(a=>a.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 C2(t,e,n,a){return new(n||(n=Promise))((function(i,s){function o(d){try{c(a.next(d))}catch(u){s(u)}}function l(d){try{c(a.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((a=a.apply(t,[])).next())}))}class a4{constructor(e,n,a,i){this.size=e,this.width=n,this.height=a,this.charLength=i,this.chars=""}static parse(e){const n=e.split(" "),a=n[0],i=a.split("x");return new a4(a,+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 i4{constructor(e,n,a,i){this.src=e,this.gcode=n,this.params=a,this.comment=i}}class yV extends i4{constructor(e,n,a,i){super(e,n,a,i),this.params=a}}class Yp extends i4{constructor(e,n,a,i){super(e,n,void 0,a),this.toolIndex=i}}class vV{constructor(e,n,a,i=0){this.layer=e,this.commands=n,this.lineNumber=a,this.height=i}}class wC{constructor(e){this.lines=[],this.preamble=new vV(-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(`
  7839. `);this.lines=this.lines.concat(n);const a=this.lines2commands(n);this.groupIntoLayers(a);const i=this.parseMetadata(a.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 a;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?`${(a=l[0])===null||a===void 0?void 0:a.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 yV(e,c,d,o);case"t0":return new Yp(e,c,o,0);case"t1":return new Yp(e,c,o,1);case"t2":return new Yp(e,c,o,2);case"t3":return new Yp(e,c,o,3);case"t4":return new Yp(e,c,o,4);case"t5":return new Yp(e,c,o,5);case"t6":return new Yp(e,c,o,6);case"t7":return new Yp(e,c,o,7);default:return new i4(e,c,d,o)}}parseMove(e){return e.reduce(((n,a)=>{const i=a.charAt(0).toLowerCase();return i!="x"&&i!="y"&&i!="z"&&i!="e"&&i!="r"&&i!="f"&&i!="i"&&i!="j"||(n[i]=parseFloat(a.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,a,i,s)=>{if(i%2==0)return n;let o=s[i-1];return o=o.toLowerCase(),this.isAlpha(o)&&(n[o]=parseFloat(a)),n}),{})}groupIntoLayers(e){var n;for(let a=0;a<e.length;a++){const i=e[a];if(i instanceof yV){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 vV(this.layers.length,[],a,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 a;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?a=a4.parse(s.slice(o+15).trim()):a&&(l==-1?a.chars+=s.trim():(a.isValid&&(n[a.size]=a),a=void 0))}return{thumbnails:n}}}wC.prototype.parseGcode=wC.prototype.parseGCode;const wV={type:"change"},P2={type:"start"},SV={type:"end"},k1=new JO,_V=new ah,e2e=Math.cos(70*uee.DEG2RAD);class t2e extends cb{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new yt,this.cursor=new yt,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:dx.ROTATE,MIDDLE:dx.DOLLY,RIGHT:dx.PAN},this.touches={ONE:ux.ROTATE,TWO:ux.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(G){G.addEventListener("keydown",W),this._domElementKeyEvents=G},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",W),this._domElementKeyEvents=null},this.saveState=function(){a.target0.copy(a.target),a.position0.copy(a.object.position),a.zoom0=a.object.zoom},this.reset=function(){a.target.copy(a.target0),a.object.position.copy(a.position0),a.object.zoom=a.zoom0,a.object.updateProjectionMatrix(),a.dispatchEvent(wV),a.update(),s=i.NONE},this.update=(function(){const G=new yt,K=new zg().setFromUnitVectors(e.up,new yt(0,1,0)),X=K.clone().invert(),se=new yt,te=new zg,fe=new yt,de=2*Math.PI;return function(me=null){const q=a.object.position;G.copy(q).sub(a.target),G.applyQuaternion(K),l.setFromVector3(G),a.autoRotate&&s===i.NONE&&M((function(ye){return ye!==null?2*Math.PI/60*a.autoRotateSpeed*ye:2*Math.PI/60/60*a.autoRotateSpeed})(me)),a.enableDamping?(l.theta+=c.theta*a.dampingFactor,l.phi+=c.phi*a.dampingFactor):(l.theta+=c.theta,l.phi+=c.phi);let R=a.minAzimuthAngle,re=a.maxAzimuthAngle;isFinite(R)&&isFinite(re)&&(R<-Math.PI?R+=de:R>Math.PI&&(R-=de),re<-Math.PI?re+=de:re>Math.PI&&(re-=de),l.theta=R<=re?Math.max(R,Math.min(re,l.theta)):l.theta>(R+re)/2?Math.max(R,l.theta):Math.min(re,l.theta)),l.phi=Math.max(a.minPolarAngle,Math.min(a.maxPolarAngle,l.phi)),l.makeSafe(),a.enableDamping===!0?a.target.addScaledVector(u,a.dampingFactor):a.target.add(u),a.target.sub(a.cursor),a.target.clampLength(a.minTargetRadius,a.maxTargetRadius),a.target.add(a.cursor),a.zoomToCursor&&T||a.object.isOrthographicCamera?l.radius=ce(l.radius):l.radius=ce(l.radius*d),G.setFromSpherical(l),G.applyQuaternion(X),q.copy(a.target).add(G),a.object.lookAt(a.target),a.enableDamping===!0?(c.theta*=1-a.dampingFactor,c.phi*=1-a.dampingFactor,u.multiplyScalar(1-a.dampingFactor)):(c.set(0,0,0),u.set(0,0,0));let be=!1;if(a.zoomToCursor&&T){let ye=null;if(a.object.isPerspectiveCamera){const _e=G.length();ye=ce(_e*d);const xe=_e-ye;a.object.position.addScaledVector(C,xe),a.object.updateMatrixWorld()}else if(a.object.isOrthographicCamera){const _e=new yt(P.x,P.y,0);_e.unproject(a.object),a.object.zoom=Math.max(a.minZoom,Math.min(a.maxZoom,a.object.zoom/d)),a.object.updateProjectionMatrix(),be=!0;const xe=new yt(P.x,P.y,0);xe.unproject(a.object),a.object.position.sub(xe).add(_e),a.object.updateMatrixWorld(),ye=G.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),a.zoomToCursor=!1;ye!==null&&(this.screenSpacePanning?a.target.set(0,0,-1).transformDirection(a.object.matrix).multiplyScalar(ye).add(a.object.position):(k1.origin.copy(a.object.position),k1.direction.set(0,0,-1).transformDirection(a.object.matrix),Math.abs(a.object.up.dot(k1.direction))<e2e?e.lookAt(a.target):(_V.setFromNormalAndCoplanarPoint(a.object.up,a.target),k1.intersectPlane(_V,a.target))))}else a.object.isOrthographicCamera&&(a.object.zoom=Math.max(a.minZoom,Math.min(a.maxZoom,a.object.zoom/d)),a.object.updateProjectionMatrix(),be=!0);return d=1,T=!1,!!(be||se.distanceToSquared(a.object.position)>o||8*(1-te.dot(a.object.quaternion))>o||fe.distanceToSquared(a.target)>0)&&(a.dispatchEvent(wV),se.copy(a.object.position),te.copy(a.object.quaternion),fe.copy(a.target),!0)}})(),this.dispose=function(){a.domElement.removeEventListener("contextmenu",O),a.domElement.removeEventListener("pointerdown",J),a.domElement.removeEventListener("pointercancel",E),a.domElement.removeEventListener("wheel",B),a.domElement.removeEventListener("pointermove",j),a.domElement.removeEventListener("pointerup",E),a._domElementKeyEvents!==null&&(a._domElementKeyEvents.removeEventListener("keydown",W),a._domElementKeyEvents=null)};const a=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 gV,c=new gV;let d=1;const u=new yt,m=new Wn,p=new Wn,f=new Wn,g=new Wn,w=new Wn,b=new Wn,x=new Wn,S=new Wn,k=new Wn,C=new yt,P=new Wn;let T=!1;const A=[],F={};function _(){return Math.pow(.95,a.zoomSpeed)}function M(G){c.theta-=G}function H(G){c.phi-=G}const I=(function(){const G=new yt;return function(K,X){G.setFromMatrixColumn(X,0),G.multiplyScalar(-K),u.add(G)}})(),z=(function(){const G=new yt;return function(K,X){a.screenSpacePanning===!0?G.setFromMatrixColumn(X,1):(G.setFromMatrixColumn(X,0),G.crossVectors(a.object.up,G)),G.multiplyScalar(K),u.add(G)}})(),L=(function(){const G=new yt;return function(K,X){const se=a.domElement;if(a.object.isPerspectiveCamera){const te=a.object.position;G.copy(te).sub(a.target);let fe=G.length();fe*=Math.tan(a.object.fov/2*Math.PI/180),I(2*K*fe/se.clientHeight,a.object.matrix),z(2*X*fe/se.clientHeight,a.object.matrix)}else a.object.isOrthographicCamera?(I(K*(a.object.right-a.object.left)/a.object.zoom/se.clientWidth,a.object.matrix),z(X*(a.object.top-a.object.bottom)/a.object.zoom/se.clientHeight,a.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),a.enablePan=!1)}})();function Z(G){a.object.isPerspectiveCamera||a.object.isOrthographicCamera?d/=G:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),a.enableZoom=!1)}function ne(G){a.object.isPerspectiveCamera||a.object.isOrthographicCamera?d*=G:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),a.enableZoom=!1)}function Y(G){if(!a.zoomToCursor)return;T=!0;const K=a.domElement.getBoundingClientRect(),X=G.clientX-K.left,se=G.clientY-K.top,te=K.width,fe=K.height;P.x=X/te*2-1,P.y=-se/fe*2+1,C.set(P.x,P.y,1).unproject(a.object).sub(a.object.position).normalize()}function ce(G){return Math.max(a.minDistance,Math.min(a.maxDistance,G))}function ue(G){m.set(G.clientX,G.clientY)}function oe(G){g.set(G.clientX,G.clientY)}function Q(){if(A.length===1)m.set(A[0].pageX,A[0].pageY);else{const G=.5*(A[0].pageX+A[1].pageX),K=.5*(A[0].pageY+A[1].pageY);m.set(G,K)}}function le(){if(A.length===1)g.set(A[0].pageX,A[0].pageY);else{const G=.5*(A[0].pageX+A[1].pageX),K=.5*(A[0].pageY+A[1].pageY);g.set(G,K)}}function pe(){const G=A[0].pageX-A[1].pageX,K=A[0].pageY-A[1].pageY,X=Math.sqrt(G*G+K*K);x.set(0,X)}function he(G){if(A.length==1)p.set(G.pageX,G.pageY);else{const X=U(G),se=.5*(G.pageX+X.x),te=.5*(G.pageY+X.y);p.set(se,te)}f.subVectors(p,m).multiplyScalar(a.rotateSpeed);const K=a.domElement;M(2*Math.PI*f.x/K.clientHeight),H(2*Math.PI*f.y/K.clientHeight),m.copy(p)}function we(G){if(A.length===1)w.set(G.pageX,G.pageY);else{const K=U(G),X=.5*(G.pageX+K.x),se=.5*(G.pageY+K.y);w.set(X,se)}b.subVectors(w,g).multiplyScalar(a.panSpeed),L(b.x,b.y),g.copy(w)}function $(G){const K=U(G),X=G.pageX-K.x,se=G.pageY-K.y,te=Math.sqrt(X*X+se*se);S.set(0,te),k.set(0,Math.pow(S.y/x.y,a.zoomSpeed)),Z(k.y),x.copy(S)}function J(G){a.enabled!==!1&&(A.length===0&&(a.domElement.setPointerCapture(G.pointerId),a.domElement.addEventListener("pointermove",j),a.domElement.addEventListener("pointerup",E)),(function(K){A.push(K)})(G),G.pointerType==="touch"?(function(K){switch(ie(K),A.length){case 1:switch(a.touches.ONE){case ux.ROTATE:if(a.enableRotate===!1)return;Q(),s=i.TOUCH_ROTATE;break;case ux.PAN:if(a.enablePan===!1)return;le(),s=i.TOUCH_PAN;break;default:s=i.NONE}break;case 2:switch(a.touches.TWO){case ux.DOLLY_PAN:if(a.enableZoom===!1&&a.enablePan===!1)return;a.enableZoom&&pe(),a.enablePan&&le(),s=i.TOUCH_DOLLY_PAN;break;case ux.DOLLY_ROTATE:if(a.enableZoom===!1&&a.enableRotate===!1)return;a.enableZoom&&pe(),a.enableRotate&&Q(),s=i.TOUCH_DOLLY_ROTATE;break;default:s=i.NONE}break;default:s=i.NONE}s!==i.NONE&&a.dispatchEvent(P2)})(G):(function(K){let X;switch(K.button){case 0:X=a.mouseButtons.LEFT;break;case 1:X=a.mouseButtons.MIDDLE;break;case 2:X=a.mouseButtons.RIGHT;break;default:X=-1}switch(X){case dx.DOLLY:if(a.enableZoom===!1)return;(function(se){Y(se),x.set(se.clientX,se.clientY)})(K),s=i.DOLLY;break;case dx.ROTATE:if(K.ctrlKey||K.metaKey||K.shiftKey){if(a.enablePan===!1)return;oe(K),s=i.PAN}else{if(a.enableRotate===!1)return;ue(K),s=i.ROTATE}break;case dx.PAN:if(K.ctrlKey||K.metaKey||K.shiftKey){if(a.enableRotate===!1)return;ue(K),s=i.ROTATE}else{if(a.enablePan===!1)return;oe(K),s=i.PAN}break;default:s=i.NONE}s!==i.NONE&&a.dispatchEvent(P2)})(G))}function j(G){a.enabled!==!1&&(G.pointerType==="touch"?(function(K){switch(ie(K),s){case i.TOUCH_ROTATE:if(a.enableRotate===!1)return;he(K),a.update();break;case i.TOUCH_PAN:if(a.enablePan===!1)return;we(K),a.update();break;case i.TOUCH_DOLLY_PAN:if(a.enableZoom===!1&&a.enablePan===!1)return;(function(X){a.enableZoom&&$(X),a.enablePan&&we(X)})(K),a.update();break;case i.TOUCH_DOLLY_ROTATE:if(a.enableZoom===!1&&a.enableRotate===!1)return;(function(X){a.enableZoom&&$(X),a.enableRotate&&he(X)})(K),a.update();break;default:s=i.NONE}})(G):(function(K){switch(s){case i.ROTATE:if(a.enableRotate===!1)return;(function(X){p.set(X.clientX,X.clientY),f.subVectors(p,m).multiplyScalar(a.rotateSpeed);const se=a.domElement;M(2*Math.PI*f.x/se.clientHeight),H(2*Math.PI*f.y/se.clientHeight),m.copy(p),a.update()})(K);break;case i.DOLLY:if(a.enableZoom===!1)return;(function(X){S.set(X.clientX,X.clientY),k.subVectors(S,x),k.y>0?Z(_()):k.y<0&&ne(_()),x.copy(S),a.update()})(K);break;case i.PAN:if(a.enablePan===!1)return;(function(X){w.set(X.clientX,X.clientY),b.subVectors(w,g).multiplyScalar(a.panSpeed),L(b.x,b.y),g.copy(w),a.update()})(K)}})(G))}function E(G){(function(K){delete F[K.pointerId];for(let X=0;X<A.length;X++)if(A[X].pointerId==K.pointerId)return void A.splice(X,1)})(G),A.length===0&&(a.domElement.releasePointerCapture(G.pointerId),a.domElement.removeEventListener("pointermove",j),a.domElement.removeEventListener("pointerup",E)),a.dispatchEvent(SV),s=i.NONE}function B(G){a.enabled!==!1&&a.enableZoom!==!1&&s===i.NONE&&(G.preventDefault(),a.dispatchEvent(P2),(function(K){Y(K),K.deltaY<0?ne(_()):K.deltaY>0&&Z(_()),a.update()})(G),a.dispatchEvent(SV))}function W(G){a.enabled!==!1&&a.enablePan!==!1&&(function(K){let X=!1;switch(K.code){case a.keys.UP:K.ctrlKey||K.metaKey||K.shiftKey?H(2*Math.PI*a.rotateSpeed/a.domElement.clientHeight):L(0,a.keyPanSpeed),X=!0;break;case a.keys.BOTTOM:K.ctrlKey||K.metaKey||K.shiftKey?H(-2*Math.PI*a.rotateSpeed/a.domElement.clientHeight):L(0,-a.keyPanSpeed),X=!0;break;case a.keys.LEFT:K.ctrlKey||K.metaKey||K.shiftKey?M(2*Math.PI*a.rotateSpeed/a.domElement.clientHeight):L(a.keyPanSpeed,0),X=!0;break;case a.keys.RIGHT:K.ctrlKey||K.metaKey||K.shiftKey?M(-2*Math.PI*a.rotateSpeed/a.domElement.clientHeight):L(-a.keyPanSpeed,0),X=!0}X&&(K.preventDefault(),a.update())})(G)}function O(G){a.enabled!==!1&&G.preventDefault()}function ie(G){let K=F[G.pointerId];K===void 0&&(K=new Wn,F[G.pointerId]=K),K.set(G.pageX,G.pageY)}function U(G){const K=G.pointerId===A[0].pointerId?A[1]:A[0];return F[K.pointerId]}a.domElement.addEventListener("contextmenu",O),a.domElement.addEventListener("pointerdown",J),a.domElement.addEventListener("pointercancel",E),a.domElement.addEventListener("wheel",B,{passive:!1}),this.update()}}sn.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Wn(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},qo.line={uniforms:e4.merge([sn.common,sn.fog,sn.line]),vertexShader:`
  7840. #include <common>
  7841. #include <color_pars_vertex>
  7842. #include <fog_pars_vertex>
  7843. #include <logdepthbuf_pars_vertex>
  7844. #include <clipping_planes_pars_vertex>
  7845. uniform float linewidth;
  7846. uniform vec2 resolution;
  7847. attribute vec3 instanceStart;
  7848. attribute vec3 instanceEnd;
  7849. attribute vec3 instanceColorStart;
  7850. attribute vec3 instanceColorEnd;
  7851. #ifdef WORLD_UNITS
  7852. varying vec4 worldPos;
  7853. varying vec3 worldStart;
  7854. varying vec3 worldEnd;
  7855. #ifdef USE_DASH
  7856. varying vec2 vUv;
  7857. #endif
  7858. #else
  7859. varying vec2 vUv;
  7860. #endif
  7861. #ifdef USE_DASH
  7862. uniform float dashScale;
  7863. attribute float instanceDistanceStart;
  7864. attribute float instanceDistanceEnd;
  7865. varying float vLineDistance;
  7866. #endif
  7867. void trimSegment( const in vec4 start, inout vec4 end ) {
  7868. // trim end segment so it terminates between the camera plane and the near plane
  7869. // conservative estimate of the near plane
  7870. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  7871. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  7872. float nearEstimate = - 0.5 * b / a;
  7873. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  7874. end.xyz = mix( start.xyz, end.xyz, alpha );
  7875. }
  7876. void main() {
  7877. #ifdef USE_COLOR
  7878. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  7879. #endif
  7880. #ifdef USE_DASH
  7881. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  7882. vUv = uv;
  7883. #endif
  7884. float aspect = resolution.x / resolution.y;
  7885. // camera space
  7886. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  7887. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  7888. #ifdef WORLD_UNITS
  7889. worldStart = start.xyz;
  7890. worldEnd = end.xyz;
  7891. #else
  7892. vUv = uv;
  7893. #endif
  7894. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7895. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7896. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7897. // perhaps there is a more elegant solution -- WestLangley
  7898. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  7899. if ( perspective ) {
  7900. if ( start.z < 0.0 && end.z >= 0.0 ) {
  7901. trimSegment( start, end );
  7902. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  7903. trimSegment( end, start );
  7904. }
  7905. }
  7906. // clip space
  7907. vec4 clipStart = projectionMatrix * start;
  7908. vec4 clipEnd = projectionMatrix * end;
  7909. // ndc space
  7910. vec3 ndcStart = clipStart.xyz / clipStart.w;
  7911. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  7912. // direction
  7913. vec2 dir = ndcEnd.xy - ndcStart.xy;
  7914. // account for clip-space aspect ratio
  7915. dir.x *= aspect;
  7916. dir = normalize( dir );
  7917. #ifdef WORLD_UNITS
  7918. // get the offset direction as perpendicular to the view vector
  7919. vec3 worldDir = normalize( end.xyz - start.xyz );
  7920. vec3 offset;
  7921. if ( position.y < 0.5 ) {
  7922. offset = normalize( cross( start.xyz, worldDir ) );
  7923. } else {
  7924. offset = normalize( cross( end.xyz, worldDir ) );
  7925. }
  7926. // sign flip
  7927. if ( position.x < 0.0 ) offset *= - 1.0;
  7928. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  7929. // don't extend the line if we're rendering dashes because we
  7930. // won't be rendering the endcaps
  7931. #ifndef USE_DASH
  7932. // extend the line bounds to encompass endcaps
  7933. start.xyz += - worldDir * linewidth * 0.5;
  7934. end.xyz += worldDir * linewidth * 0.5;
  7935. // shift the position of the quad so it hugs the forward edge of the line
  7936. offset.xy -= dir * forwardOffset;
  7937. offset.z += 0.5;
  7938. #endif
  7939. // endcaps
  7940. if ( position.y > 1.0 || position.y < 0.0 ) {
  7941. offset.xy += dir * 2.0 * forwardOffset;
  7942. }
  7943. // adjust for linewidth
  7944. offset *= linewidth * 0.5;
  7945. // set the world position
  7946. worldPos = ( position.y < 0.5 ) ? start : end;
  7947. worldPos.xyz += offset;
  7948. // project the worldpos
  7949. vec4 clip = projectionMatrix * worldPos;
  7950. // shift the depth of the projected points so the line
  7951. // segments overlap neatly
  7952. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  7953. clip.z = clipPose.z * clip.w;
  7954. #else
  7955. vec2 offset = vec2( dir.y, - dir.x );
  7956. // undo aspect ratio adjustment
  7957. dir.x /= aspect;
  7958. offset.x /= aspect;
  7959. // sign flip
  7960. if ( position.x < 0.0 ) offset *= - 1.0;
  7961. // endcaps
  7962. if ( position.y < 0.0 ) {
  7963. offset += - dir;
  7964. } else if ( position.y > 1.0 ) {
  7965. offset += dir;
  7966. }
  7967. // adjust for linewidth
  7968. offset *= linewidth;
  7969. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7970. offset /= resolution.y;
  7971. // select end
  7972. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  7973. // back to clip space
  7974. offset *= clip.w;
  7975. clip.xy += offset;
  7976. #endif
  7977. gl_Position = clip;
  7978. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  7979. #include <logdepthbuf_vertex>
  7980. #include <clipping_planes_vertex>
  7981. #include <fog_vertex>
  7982. }
  7983. `,fragmentShader:`
  7984. uniform vec3 diffuse;
  7985. uniform float opacity;
  7986. uniform float linewidth;
  7987. #ifdef USE_DASH
  7988. uniform float dashOffset;
  7989. uniform float dashSize;
  7990. uniform float gapSize;
  7991. #endif
  7992. varying float vLineDistance;
  7993. #ifdef WORLD_UNITS
  7994. varying vec4 worldPos;
  7995. varying vec3 worldStart;
  7996. varying vec3 worldEnd;
  7997. #ifdef USE_DASH
  7998. varying vec2 vUv;
  7999. #endif
  8000. #else
  8001. varying vec2 vUv;
  8002. #endif
  8003. #include <common>
  8004. #include <color_pars_fragment>
  8005. #include <fog_pars_fragment>
  8006. #include <logdepthbuf_pars_fragment>
  8007. #include <clipping_planes_pars_fragment>
  8008. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  8009. float mua;
  8010. float mub;
  8011. vec3 p13 = p1 - p3;
  8012. vec3 p43 = p4 - p3;
  8013. vec3 p21 = p2 - p1;
  8014. float d1343 = dot( p13, p43 );
  8015. float d4321 = dot( p43, p21 );
  8016. float d1321 = dot( p13, p21 );
  8017. float d4343 = dot( p43, p43 );
  8018. float d2121 = dot( p21, p21 );
  8019. float denom = d2121 * d4343 - d4321 * d4321;
  8020. float numer = d1343 * d4321 - d1321 * d4343;
  8021. mua = numer / denom;
  8022. mua = clamp( mua, 0.0, 1.0 );
  8023. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  8024. mub = clamp( mub, 0.0, 1.0 );
  8025. return vec2( mua, mub );
  8026. }
  8027. void main() {
  8028. #include <clipping_planes_fragment>
  8029. #ifdef USE_DASH
  8030. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  8031. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  8032. #endif
  8033. float alpha = opacity;
  8034. #ifdef WORLD_UNITS
  8035. // Find the closest points on the view ray and the line segment
  8036. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  8037. vec3 lineDir = worldEnd - worldStart;
  8038. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  8039. vec3 p1 = worldStart + lineDir * params.x;
  8040. vec3 p2 = rayEnd * params.y;
  8041. vec3 delta = p1 - p2;
  8042. float len = length( delta );
  8043. float norm = len / linewidth;
  8044. #ifndef USE_DASH
  8045. #ifdef USE_ALPHA_TO_COVERAGE
  8046. float dnorm = fwidth( norm );
  8047. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  8048. #else
  8049. if ( norm > 0.5 ) {
  8050. discard;
  8051. }
  8052. #endif
  8053. #endif
  8054. #else
  8055. #ifdef USE_ALPHA_TO_COVERAGE
  8056. // artifacts appear on some hardware if a derivative is taken within a conditional
  8057. float a = vUv.x;
  8058. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8059. float len2 = a * a + b * b;
  8060. float dlen = fwidth( len2 );
  8061. if ( abs( vUv.y ) > 1.0 ) {
  8062. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  8063. }
  8064. #else
  8065. if ( abs( vUv.y ) > 1.0 ) {
  8066. float a = vUv.x;
  8067. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8068. float len2 = a * a + b * b;
  8069. if ( len2 > 1.0 ) discard;
  8070. }
  8071. #endif
  8072. #endif
  8073. vec4 diffuseColor = vec4( diffuse, alpha );
  8074. #include <logdepthbuf_fragment>
  8075. #include <color_fragment>
  8076. gl_FragColor = vec4( diffuseColor.rgb, alpha );
  8077. #include <tonemapping_fragment>
  8078. #include <colorspace_fragment>
  8079. #include <fog_fragment>
  8080. #include <premultiplied_alpha_fragment>
  8081. }
  8082. `};class Eee extends Yh{constructor(e){super({type:"LineMaterial",uniforms:e4.clone(qo.line.uniforms),vertexShader:qo.line.vertexShader,fragmentShader:qo.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 kV=new gc,N1=new yt;class Dee extends zEe{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 ui([-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 ui([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,a=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),a.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 a=new aR(n,6,1);return this.setAttribute("instanceStart",new vh(a,3,0)),this.setAttribute("instanceEnd",new vh(a,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const a=new aR(n,6,1);return this.setAttribute("instanceColorStart",new vh(a,3,0)),this.setAttribute("instanceColorEnd",new vh(a,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 EEe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new gc);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),kV.setFromBufferAttribute(n),this.boundingBox.union(kV))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new lu),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const a=this.boundingSphere.center;this.boundingBox.getCenter(a);let i=0;for(let s=0,o=e.count;s<o;s++)N1.fromBufferAttribute(e,s),i=Math.max(i,a.distanceToSquared(N1)),N1.fromBufferAttribute(n,s),i=Math.max(i,a.distanceToSquared(N1));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 NV=new yt,CV=new yt,ks=new la,Ns=new la,Ld=new la,T2=new yt,A2=new Sa,Cs=new UEe,PV=new yt,C1=new gc,P1=new lu,Rd=new la;let Id,ng;function TV(t,e,n){return Rd.set(0,0,-e,1).applyMatrix4(t.projectionMatrix),Rd.multiplyScalar(1/Rd.w),Rd.x=ng/n.width,Rd.y=ng/n.height,Rd.applyMatrix4(t.projectionMatrixInverse),Rd.multiplyScalar(1/Rd.w),Math.abs(Math.max(Rd.x,Rd.y))}class n2e extends cd{constructor(e=new Dee,n=new Eee({color:16777215*Math.random()})){super(e,n),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,n=e.attributes.instanceStart,a=e.attributes.instanceEnd,i=new Float32Array(2*n.count);for(let o=0,l=0,c=n.count;o<c;o++,l+=2)NV.fromBufferAttribute(n,o),CV.fromBufferAttribute(a,o),i[l]=l===0?0:i[l-1],i[l+1]=i[l]+NV.distanceTo(CV);const s=new aR(i,2,1);return e.setAttribute("instanceDistanceStart",new vh(s,1,0)),e.setAttribute("instanceDistanceEnd",new vh(s,1,1)),this}raycast(e,n){const a=this.material.worldUnits,i=e.camera;i!==null||a||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;Id=e.ray;const o=this.matrixWorld,l=this.geometry,c=this.material;let d,u;ng=c.linewidth+s,l.boundingSphere===null&&l.computeBoundingSphere(),P1.copy(l.boundingSphere).applyMatrix4(o),a?d=.5*ng:d=TV(i,Math.max(i.near,P1.distanceToPoint(Id.origin)),c.resolution),P1.radius+=d,Id.intersectsSphere(P1)!==!1&&(l.boundingBox===null&&l.computeBoundingBox(),C1.copy(l.boundingBox).applyMatrix4(o),a?u=.5*ng:u=TV(i,Math.max(i.near,C1.distanceToPoint(Id.origin)),c.resolution),C1.expandByScalar(u),Id.intersectsBox(C1)!==!1&&(a?(function(m,p){const f=m.matrixWorld,g=m.geometry,w=g.attributes.instanceStart,b=g.attributes.instanceEnd;for(let x=0,S=Math.min(g.instanceCount,w.count);x<S;x++){Cs.start.fromBufferAttribute(w,x),Cs.end.fromBufferAttribute(b,x),Cs.applyMatrix4(f);const k=new yt,C=new yt;Id.distanceSqToSegment(Cs.start,Cs.end,C,k),C.distanceTo(k)<.5*ng&&p.push({point:C,pointOnLine:k,distance:Id.origin.distanceTo(C),object:m,face:null,faceIndex:x,uv:null,uv1:null})}})(this,n):(function(m,p,f){const g=p.projectionMatrix,w=m.material.resolution,b=m.matrixWorld,x=m.geometry,S=x.attributes.instanceStart,k=x.attributes.instanceEnd,C=Math.min(x.instanceCount,S.count),P=-p.near;Id.at(1,Ld),Ld.w=1,Ld.applyMatrix4(p.matrixWorldInverse),Ld.applyMatrix4(g),Ld.multiplyScalar(1/Ld.w),Ld.x*=w.x/2,Ld.y*=w.y/2,Ld.z=0,T2.copy(Ld),A2.multiplyMatrices(p.matrixWorldInverse,b);for(let T=0,A=C;T<A;T++){if(ks.fromBufferAttribute(S,T),Ns.fromBufferAttribute(k,T),ks.w=1,Ns.w=1,ks.applyMatrix4(A2),Ns.applyMatrix4(A2),ks.z>P&&Ns.z>P)continue;if(ks.z>P){const I=ks.z-Ns.z,z=(ks.z-P)/I;ks.lerp(Ns,z)}else if(Ns.z>P){const I=Ns.z-ks.z,z=(Ns.z-P)/I;Ns.lerp(ks,z)}ks.applyMatrix4(g),Ns.applyMatrix4(g),ks.multiplyScalar(1/ks.w),Ns.multiplyScalar(1/Ns.w),ks.x*=w.x/2,ks.y*=w.y/2,Ns.x*=w.x/2,Ns.y*=w.y/2,Cs.start.copy(ks),Cs.start.z=0,Cs.end.copy(Ns),Cs.end.z=0;const F=Cs.closestPointToPointParameter(T2,!0);Cs.at(F,PV);const _=uee.lerp(ks.z,Ns.z,F),M=_>=-1&&_<=1,H=T2.distanceTo(PV)<.5*ng;if(M&&H){Cs.start.fromBufferAttribute(S,T),Cs.end.fromBufferAttribute(k,T),Cs.start.applyMatrix4(b),Cs.end.applyMatrix4(b);const I=new yt,z=new yt;Id.distanceSqToSegment(Cs.start,Cs.end,z,I),f.push({point:z,pointOnLine:I,distance:Id.origin.distanceTo(z),object:m,face:null,faceIndex:T,uv:null,uv1:null})}}})(this,i,n)))}}class r2e extends zT{constructor(e,n,a,i,s=4473924,o=8947848){s=new On(s),o=new On(o);const l=Math.round(e/n);a=Math.round(a/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*a,p,0,a);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*a;p<=a;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 io;m.setAttribute("position",new ui(c,3)),m.setAttribute("color",new ui(d,3)),super(m,new BS({vertexColors:!0,toneMapped:!1}))}}function a2e(t,e,n,a){const i=(function(o,l,c){o*=.5,l*=.5,c*=.5;const d=new io,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 ui(u,3)),d})(t,e,n),s=new zT(i,new FEe({color:new On(a),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var rw=function(){var t=0,e=document.createElement("div");function n(u){return e.appendChild(u.dom),u}function a(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(),a(++t%e.children.length)}),!1);var i=(performance||Date).now(),s=i,o=0,l=n(new rw.Panel("FPS","#0ff","#002")),c=n(new rw.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=n(new rw.Panel("MB","#f08","#201"));return a(0),{REVISION:16,dom:e,addPanel:n,showPanel:a,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:a}};rw.Panel=function(t,e,n){var a=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,g=30*o,w=document.createElement("canvas");w.width=l,w.height=c,w.style.cssText="width:80px;height:48px";var b=w.getContext("2d");return b.font="bold "+9*o+"px Helvetica,Arial,sans-serif",b.textBaseline="top",b.fillStyle=n,b.fillRect(0,0,l,c),b.fillStyle=e,b.fillText(t,d,u),b.fillRect(m,p,f,g),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m,p,f,g),{dom:w,update:function(x,S){a=Math.min(a,x),i=Math.max(i,x),b.fillStyle=n,b.globalAlpha=1,b.fillRect(0,0,l,p),b.fillStyle=e,b.fillText(s(x)+" "+t+" ("+s(a)+"-"+s(i)+")",d,u),b.drawImage(w,m+o,p,f-o,g,m,p,f-o,g),b.fillRect(m+f-o,p,o,g),b.fillStyle=n,b.globalAlpha=.9,b.fillRect(m+f-o,p,o,s((1-x/S)*g))}}};var i2e=rw;class AV{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new vC,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 vC,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 a=e.addFolder("Camera rotation");a.add(this.watchedObject.camera.rotation,"x").listen(),a.add(this.watchedObject.camera.rotation,"y").listen(),a.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 s2e extends io{constructor(e=[new yt],n=.6,a=.2,i=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:a,radialSegments:i,closed:!1};const s=new yt,o=new yt,l=new Wn,c=[],d=[],u=[],m=[];function p(f){const[g,w,b]=(function(x){const S=e[x],k=new yt,C=new yt,P=new yt,T=new yt;k.copy(S).sub(e[x-1]||S).normalize().add((e[x+1]||S).clone().sub(S).normalize()).normalize();let A=Number.MAX_VALUE;const F=Math.abs(k.x),_=Math.abs(k.y),M=Math.abs(k.z);return F<=A&&(A=F,C.set(1,0,0)),_<=A&&(A=_,C.set(0,1,0)),M<=A&&C.set(0,0,1),T.crossVectors(k,C).normalize(),C.crossVectors(k,T),P.crossVectors(k,C),[S,C,P]})(f);for(let x=0;x<=i;x++){const S=x/i*Math.PI*2,k=Math.sin(S),C=-Math.cos(S);o.x=C*w.x+k*b.x,o.y=C*w.y+k*b.y,o.z=C*w.z+k*b.z,o.normalize(),d.push(o.x,o.y,o.z),s.x=g.x+n*o.x*.5,s.y=g.y+n*o.y*.5,s.z=g.z+a*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 g=0;g<=i;g++)l.x=f/e.length,l.y=g/i,u.push(l.x,l.y)})(),(function(){for(let f=1;f<e.length;f++)for(let g=1;g<=i;g++){const w=(i+1)*(f-1)+(g-1),b=(i+1)*f+(g-1),x=(i+1)*f+g,S=(i+1)*(f-1)+g;m.push(w,b,S),m.push(b,x,S)}})()})(),this.setIndex(m),this.setAttribute("position",new ui(c,3)),this.setAttribute("normal",new ui(d,3)),this.setAttribute("uv",new ui(u,2))}}class aw{static get initial(){const e=new aw;return Object.assign(e,{x:0,y:0,z:0,r:0,e:0,i:0,j:0,t:0}),e}}const j2={h:0,s:0,l:0};class ly{constructor(e){var n,a,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=aw.initial,this.beyondFirstMove=!1,this.disposables=[],this._extrusionColor=ly.defaultExtrusionColor,this.renderLayerIndex=0,this._geometries={},this._backgroundColor=new On(14737632),this._travelColor=new On(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 wC(this.minLayerThreshold),this.scene=new SEe,this.scene.background=this._backgroundColor,e.backgroundColor!==void 0&&(this.backgroundColor=new On(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=(a=e.initialCameraPosition)!==null&&a!==void 0?a: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 i2e:void 0,e.extrusionColor!==void 0&&(this.extrusionColor=e.extrusionColor),e.travelColor!==void 0&&(this.travelColor=new On(e.travelColor)),e.topLayerColor!==void 0&&(this.topLayerColor=new On(e.topLayerColor)),e.lastSegmentColor!==void 0&&(this.lastSegmentColor=new On(e.lastSegmentColor)),e.toolColors){this._toolColors={};for(const[f,g]of Object.entries(e.toolColors))this._toolColors[parseInt(f)]=new On(g)}if(e.disableGradient!==void 0&&(this.disableGradient=e.disableGradient),console.info("Using THREE r"+FT),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 gl(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 r4(this._backgroundColor,p,m),this.resize(),this.controls=new t2e(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,a]of e.entries())this._extrusionColor[n]=new On(a)}else this._extrusionColor=new On(e)}get currentToolColor(){var e;return this._extrusionColor===void 0?ly.defaultExtrusionColor:this._extrusionColor instanceof On?this._extrusionColor:(e=this._extrusionColor[this.state.t])!==null&&e!==void 0?e:ly.defaultExtrusionColor}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){this._backgroundColor=new On(e),this.scene.background=this._backgroundColor}get travelColor(){return this._travelColor}set travelColor(e){this._travelColor=new On(e)}get topLayerColor(){return this._topLayerColor}set topLayerColor(e){this._topLayerColor=e!==void 0?new On(e):void 0}get lastSegmentColor(){return this._lastSegmentColor}set lastSegmentColor(e){this._lastSegmentColor=e!==void 0?new On(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 BEe(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 OEe(13421772,.3*Math.PI),n=new IEe(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 I0;return n.name=e,n.quaternion.setFromEuler(new zS(-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=aw.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 C2(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 a=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(a))};a()}))}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,a,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,g={x:(n=f.params.x)!==null&&n!==void 0?n:this.state.x,y:(a=f.params.y)!==null&&a!==void 0?a: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 w=((d=f.params.e)!==null&&d!==void 0?d:0)>0||this.nonTravelmoves.indexOf(p.gcode)>-1;(g.x!=this.state.x||g.y!=this.state.y||g.z!=this.state.z)&&(w&&this.renderExtrusion||!w&&this.renderTravel)&&(p.gcode=="g2"||p.gcode=="g3"||p.gcode=="g02"||p.gcode=="g03"?this.addArcSegment(m,this.state,g,w,p.gcode=="g2"||p.gcode=="g02"):this.addLineSegment(m,this.state,g,w))}this.state.x=g.x,this.state.y=g.y,this.state.z=g.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(m,e)}doRenderExtrusion(e,n){var a,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(j2),s=new On().setHSL(j2.h,j2.s,o)}if(n==this.layers.length-1){const o=(a=this._topLayerColor)!==null&&a!==void 0?a: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 r2e(this.buildVolume.x,10,this.buildVolume.y,10));const e=a2e(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 wC(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=aw.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,a,i){(i?e.extrusion:e.travel).push(n.x,n.y,n.z,a.x,a.y,a.z)}addArcSegment(e,n,a,i,s){const o=i?e.extrusion:e.travel,l=n.x,c=n.y,d=n.z,u=a.x,m=a.y,p=a.z;let f=a.r,g=a.i,w=a.j;if(f){const Z=u-l,ne=m-c,Y=Math.sqrt(Math.pow(Z/2,2)+Math.pow(ne/2,2));f=Math.max(f,Y);const ce=Math.pow(Z,2)+Math.pow(ne,2),ue=Math.pow(f,2)-ce/4;let oe=Math.sqrt(ue/ce);(s&&f<0||!s&&f>0)&&(oe=-oe),g=Z/2+ne*oe,w=ne/2-Z*oe}const b=l==u&&c==m,x=l+g,S=c+w,k=Math.sqrt(g*g+w*w),C=Math.atan2(-w,-g),P=Math.atan2(m-S,u-x);let T;b?T=2*Math.PI:(T=s?C-P:P-C,T<0&&(T+=2*Math.PI));let A=k*T/1.8;this.inches&&(A*=25),A<1&&(A=1);let F=T/A;F*=s?-1:1;const _=[];_.push({x:l,y:c,z:d});const M=(d-p)/A;let H=l,I=c,z=d,L=C;for(let Z=0;Z<A-1;Z++)L+=F,H=x+k*Math.cos(L),I=S+k*Math.sin(L),z+=M,_.push({x:H,y:I,z});_.push({x:a.x,y:a.y,z:a.z});for(let Z=0;Z<_.length-1;Z++)o.push(_[Z].x,_[Z].y,_[Z].z,_[Z+1].x,_[Z+1].y,_[Z+1].z)}addLine(e,n){var a;if(typeof this.lineWidth=="number"&&this.lineWidth>0)return void this.addThickLine(e,n);const i=new io;i.setAttribute("position",new ui(e,3)),this.disposables.push(i);const s=new BS({color:n});this.disposables.push(s);const o=new zT(i,s);(a=this.group)===null||a===void 0||a.add(o)}addTubeLine(e,n,a=.2){let i=[];const s=[];for(let o=0;o<e.length;o+=6){const l=e.slice(o,o+9),c=new yt(l[0],l[1],l[2]),d=new yt(l[3],l[4],l[5]),u=new yt(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 s2e(o,this.extrusionWidth,this.lineHeight||a,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var a;if(!e.length||!this.lineWidth)return;const i=new Dee;this.disposables.push(i);const s=new Eee({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),i.setPositions(e);const o=new n2e(i,s);(a=this.group)===null||a===void 0||a.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=>C2(this,void 0,void 0,(function*(){var n,a;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const i=((a=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&a!==void 0?a:[])[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 a=this._geometries[e].pop();n.addGeometry(a)}}}createBatchMesh(e){var n;const a=this._geometries[e],i=new DEe({color:e,wireframe:this._wireframe});this.disposables.push(i);const s=a.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new jEe(a.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,a;return C2(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+=(a=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&a!==void 0?a:0;const d=(c=s.value,new TextDecoder("utf-8").decode(c)),u=d.lastIndexOf(`
  8083. `),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 AV(this):typeof this.devMode=="object"&&(this.devGui=new AV(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())}}ly.defaultExtrusionColor=new On("hotpink");function Fee({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:a=""}){const i=y.useRef(null),s=y.useRef(null),o=y.useRef(null),l=y.useRef(!1),[c,d]=y.useState(!0),[u,m]=y.useState(null),[p,f]=y.useState(!1),[g,w]=y.useState(0),[b,x]=y.useState(0),S=y.useMemo(()=>JSON.stringify(n),[n]);y.useEffect(()=>{if(!i.current||l.current)return;l.current=!0;const P=i.current,T=P.parentElement?.getBoundingClientRect();T&&(P.width=T.width,P.height=T.height);const A=n&&n.length>1,F=n?.[0]||"#00ae42",_=new ly({canvas:P,buildVolume:e,backgroundColor:1710618,extrusionColor:A?n:F,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});s.current=_;const M={},H=Wm();H&&(M.Authorization=`Bearer ${H}`),fetch(t,{headers:M}).then(async z=>{if(!z.ok)throw z.status===404&&(await z.json().catch(()=>({}))).detail?.includes("sliced")?(f(!0),new Error("not_sliced")):new Error("Failed to load G-code");return z.text()}).then(z=>{const L=new Set,Z=/^(\s*)T(\d+)(\s*;.*)?$/gim;let ne;for(;(ne=Z.exec(z))!==null;){const le=parseInt(ne[2],10);le<=15&&L.add(le)}const Y=new Map,ce=Array.from(L).sort((le,pe)=>le-pe);ce.forEach((le,pe)=>{Y.set(le,pe%8)});const ue=[];ce.forEach((le,pe)=>{const he=n?.[le]||"#00ae42";ue[pe%8]=he});const oe=z.split(`
  8084. `).map(le=>{const pe=le.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(pe){const he=parseInt(pe[2],10);if(he>15)return`; FILTERED: ${le.trim()}`;const we=Y.get(he)??0;return`${pe[1]}T${we}${pe[3]||""}`}return le}).join(`
  8085. `);ue.length>0&&(_.extrusionColor=ue),_.processGCode(oe);const Q=_.layers?.length||0;x(Q),w(Q),_.render(),d(!1)}).catch(z=>{z.message!=="not_sliced"&&m(z.message),d(!1)});const I=()=>{if(P.parentElement&&s.current){const z=P.parentElement.getBoundingClientRect();P.width=z.width,P.height=z.height,s.current.resize()}};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),o.current&&cancelAnimationFrame(o.current),s.current&&(s.current.dispose(),s.current=null),l.current=!1}},[t,S]);const k=y.useCallback(P=>{if(!s.current)return;const T=Math.max(1,Math.min(P,b));w(T),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{s.current&&(s.current.endLayer=T,s.current.render())})},[b]),C=P=>{k(parseInt(P.target.value,10))};return r.jsxs("div",{className:`relative flex flex-col h-full ${a}`,children:[r.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[r.jsx("canvas",{ref:i,className:"w-full h-full"}),c&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:r.jsxs("div",{className:"text-center",children:[r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),p&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:r.jsxs("div",{className:"text-center max-w-sm px-4",children:[r.jsx(bbe,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),r.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),r.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&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:r.jsx("div",{className:"text-center text-red-400",children:r.jsx("p",{className:"text-sm",children:u})})})]}),!c&&!u&&!p&&b>0&&r.jsx("div",{className:"mt-4 px-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ca,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("button",{onClick:()=>k(g-1),disabled:g<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsx("input",{type:"range",min:1,max:b,value:g,onChange:C,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),r.jsx("button",{onClick:()=>k(g+1),disabled:g>=b,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:r.jsx(qa,{className:"w-4 h-4"})}),r.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[g," / ",b]})]})})]})}function o2e({printerId:t,filePath:e,filename:n,onClose:a}){const[i,s]=y.useState(null),[o,l]=y.useState([]),[c,d]=y.useState(!1),[u,m]=y.useState(null),p=n.toLowerCase().split(".").pop()||"",f=p==="3mf"||p==="stl",g=p==="gcode"||p==="3mf";y.useEffect(()=>{s(f?"3d":g?"gcode":null)},[f,g]),y.useEffect(()=>{l([]),m(null),f&&(d(!0),ae.getPrinterFilePlates(t,e).then(x=>l(x.plates||[])).catch(()=>l([])).finally(()=>d(!1)))},[e,f,t]);const w=o.length>1,b=u==null?null:o.find(x=>x.index===u)??null;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6",onClick:a,children:r.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:x=>x.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:n}),r.jsx(je,{variant:"ghost",size:"sm",onClick:a,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.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:[r.jsx(Si,{className:"w-4 h-4"}),"3D Model",!f&&r.jsx("span",{className:"text-xs",children:"(not available)"})]}),r.jsxs("button",{onClick:()=>g&&s("gcode"),disabled:!g,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":g?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Rs,{className:"w-4 h-4"}),"G-code Preview",!g&&r.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:i==="3d"&&f?r.jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[w&&r.jsxs("div",{className:"rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(Si,{className:"w-4 h-4"}),"Plates",c&&r.jsx(ft,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[r.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:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(Si,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:"All Plates"}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[o.length," plate",o.length!==1?"s":""]})]}),u==null&&r.jsx(gs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]}),o.map(x=>r.jsxs("button",{type:"button",onClick:()=>m(x.index),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${u===x.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[x.has_thumbnail?r.jsx("img",{src:ae.getPrinterFilePlateThumbnail(t,x.index,e),alt:`Plate ${x.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(Si,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:x.name||`Plate ${x.index}`}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:x.objects.length>0?x.objects.slice(0,2).join(", ")+(x.objects.length>2?"…":""):`${x.filaments.length} filament${x.filaments.length!==1?"s":""}`})]}),u===x.index&&r.jsx(gs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},x.index))]}),b&&r.jsxs("div",{className:"mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1",children:[r.jsxs("span",{children:["Plate ",b.index]}),b.print_time_seconds!=null&&r.jsxs("span",{children:["ETA ",Math.round(b.print_time_seconds/60)," min"]}),b.filament_used_grams!=null&&r.jsxs("span",{children:[b.filament_used_grams.toFixed(1)," g"]}),b.filaments.length>0&&r.jsxs("span",{children:[b.filaments.length," filament",b.filaments.length!==1?"s":""]})]})]}),r.jsx("div",{className:"flex-1",children:r.jsx(ZJ,{url:ae.getPrinterFileDownloadUrl(t,e),fileType:p,selectedPlateId:u,className:"w-full h-full"})})]}):i==="gcode"&&g?r.jsx(Fee,{gcodeUrl:ae.getPrinterFileGcodeUrl(t,e),className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function jV(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 l2e(t,e){if(e)return OZ;switch(t.toLowerCase().split(".").pop()||""){case"3mf":return Ph;case"gcode":return Rs;case"mp4":case"avi":return Th;case"png":case"jpg":case"jpeg":return mu;default:return NT}}const c2e=[{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 d2e({printerId:t,printerName:e,onClose:n}){const{t:a}=_t(),{showToast:i}=on(),s=tn(),[o,l]=y.useState("/"),[c,d]=y.useState(new Set),[u,m]=y.useState(""),[p,f]=y.useState([]),[g,w]=y.useState("name-asc"),[b,x]=y.useState(null),[S,k]=y.useState(null);y.useEffect(()=>{const Y=ce=>{ce.key==="Escape"&&n()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[n]);const{data:C,isLoading:P,refetch:T}=Xe({queryKey:["printerFiles",t,o],queryFn:()=>ae.getPrinterFiles(t,o),refetchInterval:3e4}),{data:A}=Xe({queryKey:["printerStorage",t],queryFn:()=>ae.getPrinterStorage(t),staleTime:3e4}),F=lt({mutationFn:async Y=>{for(const ce of Y)await ae.deletePrinterFile(t,ce)},onSuccess:()=>{i(a("printerFiles.toast.filesDeleted",{count:p.length})),s.invalidateQueries({queryKey:["printerFiles",t]}),d(new Set),f([])},onError:Y=>{i(a("printerFiles.toast.deleteFailed",{error:Y.message}),"error")}}),_=Y=>{l(Y),d(new Set)},M=()=>{if(o==="/")return;const Y=o.split("/").filter(Boolean);Y.pop(),l(Y.length?"/"+Y.join("/"):"/"),d(new Set)},H=(Y,ce)=>{ce.stopPropagation(),d(ue=>{const oe=new Set(ue);return oe.has(Y)?oe.delete(Y):oe.add(Y),oe})},I=()=>{if(!C?.files)return;const Y=C.files.filter(ce=>!ce.is_directory&&(!u||ce.name.toLowerCase().includes(u.toLowerCase()))).map(ce=>ce.path);d(new Set(Y))},z=()=>{d(new Set)},L=async()=>{if(c.size===0)return;const Y=Array.from(c);if(Y.length===1){ae.downloadPrinterFile(t,Y[0]).catch(ce=>{console.error("Printer file download failed:",ce)}),d(new Set);return}x({current:0,total:Y.length});try{const ce=await ae.downloadPrinterFilesAsZip(t,Y),ue=URL.createObjectURL(ce),oe=document.createElement("a");oe.href=ue,oe.download=`${e.replace(/[^a-zA-Z0-9]/g,"_")}-files.zip`,document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),URL.revokeObjectURL(ue),i(`Downloaded ${Y.length} files as ZIP`),d(new Set)}catch(ce){i(`Download failed: ${ce instanceof Error?ce.message:"Unknown error"}`,"error")}finally{x(null)}},Z=()=>{c.size!==0&&f(Array.from(c))},ne=[{path:"/",label:"Root"},{path:"/cache",label:"Cache"},{path:"/model",label:"Models"},{path:"/timelapse",label:"Timelapse"}];return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:n,children:[r.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:Y=>Y.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ib,{className:"w-5 h-5 text-bambu-green"}),r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("printerFiles.title")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:e})]})]}),r.jsxs("div",{className:"flex items-center gap-4",children:[A&&(A.used_bytes!=null||A.free_bytes!=null)&&r.jsxs("div",{className:"text-sm text-bambu-gray flex items-center gap-2",children:[A.used_bytes!=null&&r.jsxs("span",{children:[a("printerFiles.storageUsed")," ",jV(A.used_bytes)]}),A.used_bytes!=null&&A.free_bytes!=null&&r.jsx("span",{className:"text-bambu-dark-tertiary",children:"|"}),A.free_bytes!=null&&r.jsxs("span",{children:[a("printerFiles.storageFree")," ",jV(A.free_bytes)]})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:"Close file manager","aria-label":"Close file manager",children:r.jsx(Vt,{className:"w-5 h-5"})})]})]}),r.jsxs("div",{className:"flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[ne.map(Y=>r.jsx("button",{onClick:()=>{_(Y.path),m("")},className:`px-3 py-1 text-sm rounded-full transition-colors ${o===Y.path?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:Y.label},Y.path)),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:a("printerFiles.filterPlaceholder"),value:u,onChange:Y=>m(Y.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"})]}),r.jsxs("div",{className:"relative flex items-center gap-1",children:[r.jsx(_T,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("select",{value:g,onChange:Y=>w(Y.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:c2e.map(Y=>r.jsx("option",{value:Y.value,children:Y.label},Y.value))})]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>T(),disabled:P,children:r.jsx(tr,{className:`w-4 h-4 ${P?"animate-spin":""}`})})]}),r.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0",children:[r.jsx("button",{onClick:M,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:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsx("span",{className:"text-bambu-gray font-mono",children:o})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:P?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):C?.files?.length?r.jsx("div",{className:"space-y-1",children:[...C.files].filter(Y=>!u||Y.name.toLowerCase().includes(u.toLowerCase())).sort((Y,ce)=>{if(Y.is_directory&&!ce.is_directory)return-1;if(!Y.is_directory&&ce.is_directory)return 1;switch(g){case"name-asc":return Y.name.localeCompare(ce.name);case"name-desc":return ce.name.localeCompare(Y.name);case"size-asc":return Y.size-ce.size;case"size-desc":return ce.size-Y.size;case"date-asc":{const ue=Y.mtime?Yn(Y.mtime)?.getTime()??0:0,oe=ce.mtime?Yn(ce.mtime)?.getTime()??0:0;return ue-oe}case"date-desc":{const ue=Y.mtime?Yn(Y.mtime)?.getTime()??0:0;return(ce.mtime?Yn(ce.mtime)?.getTime()??0:0)-ue}default:return Y.name.localeCompare(ce.name)}}).map(Y=>{const ce=l2e(Y.name,Y.is_directory),ue=c.has(Y.path);return r.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${ue?"bg-bambu-green/20 border border-bambu-green/50":"hover:bg-bambu-dark-tertiary"}`,onClick:()=>{Y.is_directory&&_(Y.path)},children:[Y.is_directory?null:r.jsx("button",{onClick:oe=>H(Y.path,oe),className:"flex-shrink-0 text-bambu-gray hover:text-white",children:ue?r.jsx(gs,{className:"w-5 h-5 text-bambu-green"}):r.jsx(ro,{className:"w-5 h-5"})}),r.jsx(ce,{className:`w-5 h-5 flex-shrink-0 ${Y.is_directory?"text-bambu-green":"text-bambu-gray"}`}),r.jsx("span",{className:"flex-1 text-white truncate",children:Y.name}),!Y.is_directory&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:ls(Y.size)}),(Y.name.toLowerCase().endsWith(".3mf")||Y.name.toLowerCase().endsWith(".gcode")||Y.name.toLowerCase().endsWith(".stl"))&&r.jsx("button",{onClick:oe=>{oe.stopPropagation(),k({path:Y.path,name:Y.name})},className:"p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green",title:"3D View",children:r.jsx(Si,{className:"w-4 h-4"})})]}),Y.is_directory&&r.jsx(Xo,{className:"w-4 h-4 text-bambu-gray rotate-180"})]},Y.path)})}):r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"No files in this directory"})}),r.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:c.size>0?`${c.size} selected`:u?`${C?.files?.filter(Y=>Y.name.toLowerCase().includes(u.toLowerCase())).length||0} of ${C?.files?.length||0} items`:`${C?.files?.length||0} items`}),C?.files?.some(Y=>!Y.is_directory)&&r.jsx("div",{className:"flex items-center gap-2",children:c.size>0?r.jsxs("button",{onClick:z,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[r.jsx(Gye,{className:"w-4 h-4"}),"Deselect All"]}):r.jsxs("button",{onClick:I,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[r.jsx(gs,{className:"w-4 h-4"}),"Select All"]})})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",disabled:c.size===0||b!==null,onClick:L,children:b?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),b.current,"/",b.total]}):r.jsxs(r.Fragment,{children:[r.jsx(Zr,{className:"w-4 h-4"}),"Download",c.size>1?` (${c.size})`:""]})}),r.jsxs(je,{variant:"secondary",disabled:c.size===0||F.isPending,onClick:Z,className:"text-red-400 hover:text-red-300",children:[F.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),a("printerFiles.deleteButton"),c.size>1?` (${c.size})`:""]})]})]})]}),p.length>0&&r.jsx(wn,{title:p.length>1?a("printerFiles.deleteFiles",{count:p.length}):a("fileManager.deleteFile"),message:p.length>1?a("printerFiles.deleteFilesConfirm",{count:p.length}):a("printerFiles.deleteFileConfirm",{name:p[0].split("/").pop()}),confirmText:a("common.delete"),variant:"danger",onConfirm:()=>{F.mutate(p)},onCancel:()=>f([])}),S&&r.jsx(o2e,{printerId:t,filePath:S.path,filename:S.name,onClose:()=>k(null)})]})}function s4({on:t,className:e="w-5 h-5"}){const n=t?"#facc15":"none",a=t?"#78350f":"currentColor",i=t?1:0;return r.jsxs("svg",{viewBox:"0 0 32 32",fill:"none",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[r.jsxs("g",{stroke:a,opacity:i,children:[r.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),r.jsx("line",{x1:"6.1",y1:"6.1",x2:"8.9",y2:"8.9"}),r.jsx("line",{x1:"25.9",y1:"6.1",x2:"23.1",y2:"8.9"}),r.jsx("line",{x1:"2",y1:"16",x2:"6",y2:"16"}),r.jsx("line",{x1:"30",y1:"16",x2:"26",y2:"16"})]}),r.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:a}),r.jsx("path",{d:"M12 24h8",stroke:a}),r.jsx("path",{d:"M12 27h8",stroke:a}),r.jsx("path",{d:"M13 30h6",stroke:a})]})}const UT=({className:t})=>r.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[r.jsx("rect",{x:"2",y:"15",width:"5",height:"5",rx:"0.5"}),r.jsx("rect",{x:"9.5",y:"15",width:"5",height:"5",rx:"0.5",fill:"currentColor",opacity:"0.3"}),r.jsx("rect",{x:"17",y:"15",width:"5",height:"5",rx:"0.5"}),r.jsx("path",{d:"M4 12 C4 6, 14 6, 14 12"}),r.jsx("polyline",{points:"12,10 14,12 12,14"})]});function o4({printerId:t,isOpen:e,onClose:n}){const{t:a}=_t(),{showToast:i}=on(),{hasPermission:s}=dr(),[o,l]=y.useState(null),[c,d]=y.useState(!1),{data:u}=Xe({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),refetchInterval:3e4,enabled:e}),{data:m,refetch:p}=Xe({queryKey:["printableObjects",t],queryFn:()=>ae.getPrintableObjects(t),enabled:e,refetchInterval:e?5e3:!1}),f=lt({mutationFn:g=>ae.skipObjects(t,g),onSuccess:g=>{i(g.message||a("printers.skipObjects.objectsSkipped")),l(null),p()},onError:g=>i(g.message||a("printers.toast.failedToSkipObjects"),"error")});return e?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:n,onKeyDown:g=>{g.key==="Escape"&&(c?d(!1):n())},tabIndex:-1,ref:g=>g?.focus(),children:[r.jsx("div",{className:"absolute inset-0 bg-black/50 z-0"}),r.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:g=>g.stopPropagation(),children:[r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(UT,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:a("printers.skipObjects.title")})]}),r.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:r.jsx(Vt,{className:"w-4 h-4"})})]}),m?m.objects.length===0?r.jsxs("div",{className:"text-center py-8 px-4 text-bambu-gray",children:[r.jsx("p",{className:"text-sm",children:a("printers.noObjectsFound")}),r.jsx("p",{className:"text-xs mt-1 opacity-70",children:a("printers.objectsLoadedOnPrintStart")})]}):r.jsxs("div",{className:"flex flex-col overflow-hidden",children:[r.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:[r.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:r.jsx(kO,{className:"w-4 h-4 text-blue-500 dark:text-blue-400"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300",children:a("printers.skipObjects.matchIdsInfo")}),r.jsx("p",{className:"text-[10px] text-blue-500/70 dark:text-blue-300/60",children:a("printers.skipObjects.printerShowsIds")})]}),r.jsxs("div",{className:"flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray",children:[m.skipped_count,"/",m.total," ",a("printers.skipObjects.skipped")]})]}),(u?.layer_num??0)<=1&&r.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:[r.jsx(Ha,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0"}),r.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:a("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0})})]}),r.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[r.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:r.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>d(!0),children:[u?.cover_url?r.jsx("img",{src:La(`${u.cover_url}?view=top`),alt:a("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"}):r.jsx("div",{className:"w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center",children:r.jsx(Si,{className:"w-8 h-8 text-gray-300 dark:text-bambu-gray/30"})}),r.jsx("div",{className:"absolute top-2 right-2 p-1 bg-black/60 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(CT,{className:"w-3.5 h-3.5 text-white"})}),m.objects.length>0&&r.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((g,w)=>{let b,x;if(g.x!=null&&g.y!=null&&m.bbox_all){const[S,k,C,P]=m.bbox_all,T=C-S,A=P-k,F=8,_=100-F*2;b=F+(g.x-S)/T*_,x=F+(P-g.y)/A*_,b=Math.max(5,Math.min(95,b)),x=Math.max(5,Math.min(95,x))}else if(g.x!=null&&g.y!=null)b=g.x/256*100,x=100-g.y/256*100,b=Math.max(5,Math.min(95,b)),x=Math.max(5,Math.min(95,x));else{const S=Math.ceil(Math.sqrt(m.objects.length)),k=Math.floor(w/S),C=w%S,P=Math.ceil(m.objects.length/S);b=15+C*(70/S)+35/S,x=15+k*(70/P)+35/P}return r.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${g.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${x}%`,transform:"translate(-50%, -50%)"},title:g.name,children:g.id},g.id)})}),r.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:a("printers.skipObjects.activeCount",{count:m.objects.filter(g=>!g.skipped).length})})]})}),r.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:m.objects.map(g=>r.jsxs("div",{className:`
  8086. flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary/50 last:border-0
  8087. ${g.skipped?"bg-red-50 dark:bg-red-500/10":"hover:bg-gray-50 dark:hover:bg-bambu-dark/50"}
  8088. `,children:[r.jsxs("div",{className:`
  8089. w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center
  8090. ${g.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"}
  8091. `,children:[r.jsx("span",{className:`text-lg font-mono font-bold ${g.skipped?"text-red-500 dark:text-red-400":"text-green-600 dark:text-bambu-green"}`,children:g.id}),r.jsx("span",{className:`text-[8px] uppercase tracking-wider ${g.skipped?"text-red-400/60":"text-green-500/60 dark:text-bambu-green/60"}`,children:"ID"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:`block text-sm truncate ${g.skipped?"text-red-500 dark:text-red-400 line-through":"text-gray-900 dark:text-white"}`,children:g.name}),g.skipped&&r.jsx("span",{className:"text-[10px] text-red-400/60",children:a("printers.willBeSkipped")})]}),g.skipped?r.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:a("printers.skipObjects.skipped")}):r.jsx("button",{onClick:()=>l({id:g.id,name:g.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?a("printers.skipObjects.waitForLayer",{layer:u?.layer_num??0}):a("printers.skipObjects.skip"):a("printers.permission.noControl"),children:a("printers.skipObjects.skip")})]},g.id))})]})]}):r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&r.jsx(wn,{variant:"warning",title:a("printers.skipObjects.confirmTitle"),message:a("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:a("printers.skipObjects.skip"),isLoading:f.isPending,onConfirm:()=>f.mutate([o.id]),onCancel:()=>l(null)}),c&&m&&r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>d(!1),children:[r.jsx("button",{onClick:()=>d(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-6 h-6"})}),r.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:g=>g.stopPropagation(),children:[u?.cover_url?r.jsx("img",{src:La(`${u.cover_url}?view=top`),alt:a("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):r.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:r.jsx(Si,{className:"w-16 h-16 text-gray-500"})}),m.objects.length>0&&r.jsx("div",{className:"absolute inset-0 pointer-events-none",children:m.objects.map((g,w)=>{let b,x;if(g.x!=null&&g.y!=null&&m.bbox_all){const[S,k,C,P]=m.bbox_all,T=C-S,A=P-k,F=8,_=100-F*2;b=F+(g.x-S)/T*_,x=F+(P-g.y)/A*_,b=Math.max(5,Math.min(95,b)),x=Math.max(5,Math.min(95,x))}else if(g.x!=null&&g.y!=null)b=g.x/256*100,x=100-g.y/256*100,b=Math.max(5,Math.min(95,b)),x=Math.max(5,Math.min(95,x));else{const S=Math.ceil(Math.sqrt(m.objects.length)),k=Math.floor(w/S),C=w%S,P=Math.ceil(m.objects.length/S);b=15+C*(70/S)+35/S,x=15+k*(70/P)+35/P}return r.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${g.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${b}%`,top:`${x}%`,transform:"translate(-50%, -50%)"},title:g.name,children:g.id},g.id)})}),r.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:a("printers.skipObjects.activeCount",{count:m.objects.filter(g=>!g.skipped).length})})]})]})]}):null}function u2e({status:t}){return t==="ok"?r.jsx(yl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}):t==="failed"?r.jsx($r,{className:"w-5 h-5 text-red-400 flex-shrink-0"}):r.jsx(vge,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"})}function m2e({printerId:t,printerName:e,onClose:n}){const{t:a}=_t(),i=lt({mutationFn:()=>ae.diagnoseCamera(t)});y.useEffect(()=>{i.mutate()},[]),y.useEffect(()=>{const o=l=>{l.key==="Escape"&&n()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[n]);const s=i.data;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg flex flex-col",onClick:o=>o.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(GZ,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:a("camera.diagnose.modalTitle",{name:e||""})})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:a("common.close"),children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 space-y-4",children:[i.isPending&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:a("camera.diagnose.running")})]}),i.isError&&r.jsx("div",{className:"rounded-lg bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-300",children:a("camera.diagnose.runFailed",{error:i.error.message})}),s&&r.jsxs(r.Fragment,{children:[r.jsx("ol",{className:"space-y-2",children:s.stages.map(o=>r.jsxs("li",{className:"flex items-center gap-3 bg-bambu-dark rounded-lg px-4 py-2.5",children:[r.jsx(u2e,{status:o.status}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm text-white",children:a(`camera.diagnose.stage.${o.name}`)}),o.code&&r.jsx("div",{className:"text-xs text-bambu-gray font-mono",children:o.code})]}),r.jsxs("div",{className:"text-xs text-bambu-gray tabular-nums flex-shrink-0",children:[o.duration_ms," ms"]})]},o.name))}),r.jsx("div",{className:s.overall_status==="ok"?"rounded-lg bg-bambu-green/10 border border-bambu-green/30 px-4 py-3 text-sm text-bambu-green":"rounded-lg bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-300",children:a(`camera.diagnose.summary.${s.summary_code}`,{defaultValue:a("camera.diagnose.summary.unknown_failure")})}),r.jsx("div",{className:"text-xs text-bambu-gray space-y-0.5",children:r.jsxs("div",{children:[r.jsxs("span",{className:"text-bambu-gray/60",children:[a("camera.diagnose.meta.protocol"),": "]}),r.jsx("span",{className:"font-mono",children:s.protocol})," • ",r.jsxs("span",{className:"text-bambu-gray/60",children:[a("camera.diagnose.meta.port"),": "]}),r.jsx("span",{className:"font-mono",children:s.port})," • ",r.jsxs("span",{className:"text-bambu-gray/60",children:[a("camera.diagnose.meta.profile"),": "]}),r.jsx("span",{className:"font-mono",children:s.profile})]})})]})]}),r.jsxs("div",{className:"px-6 py-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx("button",{onClick:()=>i.mutate(),disabled:i.isPending,className:"px-4 py-2 bg-bambu-dark hover:bg-bambu-dark-tertiary disabled:opacity-50 text-white text-sm rounded-lg transition-colors",children:a("camera.diagnose.retry")}),r.jsx("button",{onClick:n,className:"px-4 py-2 bg-bambu-green hover:bg-bambu-green/90 text-white text-sm rounded-lg transition-colors",children:a("common.close")})]})]})})}const p2e="embeddedCameraState_",MV=5,h2e=2e3,f2e=3e4,g2e=5e3,M2={x:window.innerWidth-420,y:20,width:400,height:300};function b2e({printerId:t,printerName:e,viewerIndex:n=0,onClose:a}){const{t:i}=_t(),s=tn(),{showToast:o}=on(),{hasPermission:l}=dr(),c=`${p2e}${t}`,d=()=>{try{const Te=localStorage.getItem(c);if(Te){const tt=JSON.parse(Te);return{x:Math.min(Math.max(0,tt.x),window.innerWidth-100),y:Math.min(Math.max(0,tt.y),window.innerHeight-100),width:Math.max(200,Math.min(tt.width,window.innerWidth-20)),height:Math.max(150,Math.min(tt.height,window.innerHeight-20))}}}catch{}const Qe=n*30;return{...M2,x:Math.max(0,M2.x-Qe),y:Math.max(0,M2.y+Qe)}},[u,m]=y.useState(d),[p,f]=y.useState(!1),[g,w]=y.useState(!1),[b,x]=y.useState({x:0,y:0}),[S,k]=y.useState(!1),[C,P]=y.useState(!1),[T,A]=y.useState(1),[F,_]=y.useState({x:0,y:0}),[M,H]=y.useState(!1),[I,z]=y.useState({x:0,y:0}),[L,Z]=y.useState(null),[ne,Y]=y.useState(null),[ce,ue]=y.useState(!1),[oe,Q]=y.useState(!0),[le,pe]=y.useState(Date.now()),[he,we]=y.useState(0),[$,J]=y.useState(!1),[j,E]=y.useState(0),B=y.useRef(null),W=y.useRef(null),O=y.useRef(null),ie=y.useRef(null),U=y.useRef(null),[G,K]=y.useState(!1),[X,se]=y.useState(!1),{data:te}=Xe({queryKey:["printer",t],queryFn:()=>ae.getPrinter(t),enabled:t>0}),{data:fe}=Xe({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),de=lt({mutationFn:Qe=>ae.setChamberLight(t,Qe),onMutate:async Qe=>{await s.cancelQueries({queryKey:["printerStatus",t]});const Te=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],tt=>({...tt,chamber_light:Qe})),{previousStatus:Te}},onSuccess:(Qe,Te)=>{o(`Chamber light ${Te?"on":"off"}`)},onError:(Qe,Te,tt)=>{tt?.previousStatus&&s.setQueryData(["printerStatus",t],tt.previousStatus),o(Qe.message||i("printers.toast.failedToControlChamberLight"),"error")}}),me=(fe?.state==="RUNNING"||fe?.state==="PAUSE")&&(fe?.printable_objects_count??0)>=2;y.useEffect(()=>{const Qe=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(u))},500);return()=>clearTimeout(Qe)},[u,c]);const q=y.useRef(!1);y.useEffect(()=>{q.current=!1;const Qe=`/api/v1/printers/${t}/camera/stop`,Te=()=>{if(t>0&&!q.current){q.current=!0;const ot={},Tt=Wm();Tt&&(ot.Authorization=`Bearer ${Tt}`),fetch(Qe,{method:"POST",keepalive:!0,headers:ot}).catch(()=>{})}},tt=W.current;return()=>{tt&&(tt.src=""),Te(),O.current&&clearTimeout(O.current),ie.current&&clearInterval(ie.current),U.current&&clearInterval(U.current)}},[t]),y.useEffect(()=>{if(oe){const Qe=setTimeout(()=>Q(!1),3e3);return()=>clearTimeout(Qe)}},[oe,le]);const R=y.useCallback(()=>{if(he>=MV){J(!1),ue(!0);return}const Qe=Math.min(h2e*Math.pow(2,he),f2e);J(!0),E(Math.ceil(Qe/1e3)),ie.current=setInterval(()=>{E(Te=>Te<=1?(ie.current&&clearInterval(ie.current),0):Te-1)},1e3),O.current=setTimeout(()=>{we(Te=>Te+1),J(!1),Q(!0),ue(!1),W.current&&(W.current.src=""),pe(Date.now())},Qe)},[he]);y.useEffect(()=>{if(oe||$||S){U.current&&(clearInterval(U.current),U.current=null);return}return U.current=setInterval(async()=>{try{const Qe=await ae.getCameraStatus(t);(Qe.stalled||!Qe.active&&!ce)&&(U.current&&(clearInterval(U.current),U.current=null),Q(!1),R())}catch{}},g2e),()=>{U.current&&(clearInterval(U.current),U.current=null)}},[oe,ce,$,S,t,R]),y.useEffect(()=>{const Qe=()=>{const Te=!!document.fullscreenElement;P(Te),Te||(A(1),_({x:0,y:0}))};return document.addEventListener("fullscreenchange",Qe),()=>document.removeEventListener("fullscreenchange",Qe)},[]);const re=()=>{B.current&&(document.fullscreenElement?document.exitFullscreen():B.current.requestFullscreen())},be=()=>{A(Qe=>Math.min(Qe+.5,4))},ye=()=>{A(Qe=>{const Te=Math.max(Qe-.5,1);return Te===1&&_({x:0,y:0}),Te})},_e=Qe=>{Qe.preventDefault(),Qe.deltaY<0?be():ye()},xe=Qe=>{T>1&&(Qe.preventDefault(),H(!0),z({x:Qe.clientX-F.x,y:Qe.clientY-F.y}))},ge=y.useCallback(()=>{if(!B.current||!W.current)return{x:200,y:150};const Qe=B.current.getBoundingClientRect(),Te=Qe.width*(T-1)/2,tt=Qe.height*(T-1)/2;return{x:Math.max(50,Te),y:Math.max(50,tt)}},[T]),Me=Qe=>{if(M&&T>1){const Te=Qe.clientX-I.x,tt=Qe.clientY-I.y,ot=ge();_({x:Math.max(-ot.x,Math.min(ot.x,Te)),y:Math.max(-ot.y,Math.min(ot.y,tt))})}},Be=()=>{H(!1)},Fe=Qe=>{if(Qe.length<2)return 0;const Te=Qe[0].clientX-Qe[1].clientX,tt=Qe[0].clientY-Qe[1].clientY;return Math.sqrt(Te*Te+tt*tt)},Oe=Qe=>Qe.length<2?{x:Qe[0].clientX,y:Qe[0].clientY}:{x:(Qe[0].clientX+Qe[1].clientX)/2,y:(Qe[0].clientY+Qe[1].clientY)/2},Re=Qe=>{Qe.touches.length===2?(Qe.preventDefault(),Z(Fe(Qe.touches)),Y(Oe(Qe.touches))):Qe.touches.length===1&&T>1&&(Qe.preventDefault(),H(!0),z({x:Qe.touches[0].clientX-F.x,y:Qe.touches[0].clientY-F.y}))},We=Qe=>{if(Qe.touches.length===2&&L!==null){Qe.preventDefault();const Te=Fe(Qe.touches),tt=Te/L;A(Tt=>{const Ut=Math.max(1,Math.min(4,Tt*tt));return Ut===1&&_({x:0,y:0}),Ut}),Z(Te);const ot=Oe(Qe.touches);if(ne){const Tt=ge();_(Ut=>({x:Math.max(-Tt.x,Math.min(Tt.x,Ut.x+(ot.x-ne.x))),y:Math.max(-Tt.y,Math.min(Tt.y,Ut.y+(ot.y-ne.y)))}))}Y(ot)}else if(Qe.touches.length===1&&M&&T>1){Qe.preventDefault();const Te=Qe.touches[0].clientX-I.x,tt=Qe.touches[0].clientY-I.y,ot=ge();_({x:Math.max(-ot.x,Math.min(ot.x,Te)),y:Math.max(-ot.y,Math.min(ot.y,tt))})}},ze=Qe=>{Qe.touches.length<2&&(Z(null),Y(null)),Qe.touches.length===0&&H(!1)},st=()=>{A(1),_({x:0,y:0})},Ee=()=>{Q(!1),he<MV?R():ue(!0)},it=()=>{Q(!1),ue(!1),we(0),J(!1),O.current&&clearTimeout(O.current),ie.current&&clearInterval(ie.current)},Ce=()=>{Q(!0),ue(!1),we(0),J(!1),O.current&&clearTimeout(O.current),ie.current&&clearInterval(ie.current);const Qe={},Te=Wm();Te&&(Qe.Authorization=`Bearer ${Te}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Qe}).catch(()=>{}),W.current&&(W.current.src=""),setTimeout(()=>pe(Date.now()),100)},Ze=Qe=>{Qe.target.closest(".no-drag")||(f(!0),x({x:Qe.clientX-u.x,y:Qe.clientY-u.y}))},Ie=Qe=>{if(Qe.target.closest(".no-drag"))return;const Te=Qe.touches[0];f(!0),x({x:Te.clientX-u.x,y:Te.clientY-u.y})},ke=Qe=>{Qe.stopPropagation(),w(!0)},Ve=Qe=>{Qe.stopPropagation(),w(!0)};y.useEffect(()=>{const Qe=ot=>{if(p)m(Tt=>({...Tt,x:Math.max(0,Math.min(ot.clientX-b.x,window.innerWidth-Tt.width)),y:Math.max(0,Math.min(ot.clientY-b.y,window.innerHeight-Tt.height))}));else if(g&&B.current){const Tt=B.current.getBoundingClientRect();m(Ut=>({...Ut,width:Math.max(200,Math.min(ot.clientX-Tt.left,window.innerWidth-Ut.x-10)),height:Math.max(150,Math.min(ot.clientY-Tt.top,window.innerHeight-Ut.y-10))}))}},Te=ot=>{if(!p&&!g)return;ot.preventDefault();const Tt=ot.touches[0];if(p)m(Ut=>({...Ut,x:Math.max(0,Math.min(Tt.clientX-b.x,window.innerWidth-Ut.width)),y:Math.max(0,Math.min(Tt.clientY-b.y,window.innerHeight-Ut.height))}));else if(g&&B.current){const Ut=B.current.getBoundingClientRect();m(bt=>({...bt,width:Math.max(200,Math.min(Tt.clientX-Ut.left,window.innerWidth-bt.x-10)),height:Math.max(150,Math.min(Tt.clientY-Ut.top,window.innerHeight-bt.y-10))}))}},tt=()=>{f(!1),w(!1)};if(p||g)return document.addEventListener("mousemove",Qe),document.addEventListener("mouseup",tt),document.addEventListener("touchmove",Te,{passive:!1}),document.addEventListener("touchend",tt),document.addEventListener("touchcancel",tt),()=>{document.removeEventListener("mousemove",Qe),document.removeEventListener("mouseup",tt),document.removeEventListener("touchmove",Te),document.removeEventListener("touchend",tt),document.removeEventListener("touchcancel",tt)}},[p,g,b]);const rt=La(`/api/v1/printers/${t}/camera/stream?fps=15&t=${le}`);return r.jsxs("div",{ref:B,className:`${C?"fixed inset-0 z-[100]":"fixed z-40 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:C?void 0:{left:u.x,top:u.y,width:S?200:u.width,height:S?40:u.height,cursor:p?"grabbing":"default"},children:[r.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:Ze,onTouchStart:Ie,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[r.jsx(Ah,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:te?.name||e})]}),r.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[r.jsx("button",{onClick:()=>de.mutate(!fe?.chamber_light),disabled:!fe?.connected||de.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${fe?.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:r.jsx(s4,{on:fe?.chamber_light??!1,className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>K(!0),disabled:!me||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${me&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?i(me?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):i("printers.permission.noControl"),children:r.jsx(UT,{className:"w-3.5 h-3.5 text-bambu-gray"})}),r.jsx("button",{onClick:Ce,disabled:oe||$,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:r.jsx(tr,{className:`w-3.5 h-3.5 text-bambu-gray ${oe?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>se(!0),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:i("camera.diagnose.button"),children:r.jsx(GZ,{className:"w-3.5 h-3.5 text-bambu-gray"})}),r.jsx("button",{onClick:re,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:C?"Exit fullscreen":"Fullscreen",children:C?r.jsx(BZ,{className:"w-3.5 h-3.5 text-bambu-gray"}):r.jsx(Fbe,{className:"w-3.5 h-3.5 text-bambu-gray"})}),r.jsx("button",{onClick:()=>k(!S),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:S?"Expand":"Minimize",children:S?r.jsx(CT,{className:"w-3.5 h-3.5 text-bambu-gray"}):r.jsx(_O,{className:"w-3.5 h-3.5 text-bambu-gray"})}),r.jsx("button",{onClick:a,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:r.jsx(Vt,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!S&&r.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:_e,onMouseMove:Me,onMouseUp:Be,onMouseLeave:Be,onTouchStart:Re,onTouchMove:We,onTouchEnd:ze,style:{touchAction:"none"},children:[oe&&!$&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsx(tr,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),$&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-2",children:[r.jsx(hu,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",j,"s..."]})]})}),ce&&!$&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-2",children:[r.jsx(Nn,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("camera.unavailable")}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:Ce,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:i("camera.retry")}),r.jsx("button",{onClick:()=>se(!0),className:"px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:i("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:rt,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${T}) translate(${F.x/T}px, ${F.y/T}px) rotate(${te?.camera_rotation||0}deg)`,...te?.camera_rotation===90||te?.camera_rotation===270?{maxWidth:"100%",maxHeight:"100%"}:{},cursor:T>1?M?"grabbing":"grab":"default"},onError:Ee,onLoad:it,onMouseDown:xe,draggable:!1},le),r.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:[r.jsx("button",{onClick:ye,disabled:T<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:r.jsx(PO,{className:"w-3.5 h-3.5 text-white"})}),r.jsxs("button",{onClick:st,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(T*100),"%"]}),r.jsx("button",{onClick:be,disabled:T>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:r.jsx(CO,{className:"w-3.5 h-3.5 text-white"})})]}),!C&&r.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:ke,onTouchStart:Ve,title:"Drag to resize",children:r.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:r.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),r.jsx(o4,{printerId:t,isOpen:G,onClose:()=>K(!1)}),X&&r.jsx(m2e,{printerId:t,printerName:te?.name||null,onClose:()=>se(!1)})]})}function x2e({printerId:t,printerName:e,onClose:n}){const{t:a}=_t(),i=tn(),[s,o]=y.useState(!0),[l,c]=y.useState(new Set),[d,u]=y.useState(""),[m,p]=y.useState("all"),f=y.useRef(null),{data:g,isLoading:w,refetch:b}=Xe({queryKey:["mqtt-logs",t],queryFn:()=>ae.getMQTTLogs(t),refetchInterval:1e3}),x=lt({mutationFn:()=>ae.enableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),S=lt({mutationFn:()=>ae.disableMQTTLogging(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}}),k=lt({mutationFn:()=>ae.clearMQTTLogs(t),onSuccess:()=>{i.invalidateQueries({queryKey:["mqtt-logs",t]})}});y.useEffect(()=>{const M=H=>{H.key==="Escape"&&n()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[n]),y.useEffect(()=>{s&&f.current&&(f.current.scrollTop=f.current.scrollHeight)},[g?.logs,s]);const C=M=>{c(H=>{const I=new Set(H);return I.has(M)?I.delete(M):I.add(M),I})},P=M=>new Date(M).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),T=(M,H)=>{if(M==null)return"<empty>";const I=typeof M=="string"?JSON.parse(M):M,z=JSON.stringify(I,null,H?2:0);return!H&&z.length>100?z.substring(0,100)+"...":z},A=g?.logging_enabled??!1,F=y.useMemo(()=>g?.logs??[],[g?.logs]),_=y.useMemo(()=>F.filter(M=>{if(m!=="all"&&M.direction!==m)return!1;if(d.trim()){const H=d.toLowerCase(),I=M.topic.toLowerCase().includes(H),L=JSON.stringify(M.payload).toLowerCase().includes(H);return I||L}return!0}),[F,d,m]);return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("mqttDebug.title")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[A?r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>S.mutate(),disabled:S.isPending,children:[r.jsx(ro,{className:"w-4 h-4"}),a("mqttDebug.stopLogging")]}):r.jsxs(je,{size:"sm",onClick:()=>x.mutate(),disabled:x.isPending,children:[r.jsx(hs,{className:"w-4 h-4"}),a("mqttDebug.startLogging")]}),r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>k.mutate(),disabled:k.isPending||F.length===0,children:[r.jsx(en,{className:"w-4 h-4"}),a("mqttDebug.clearLog")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>b(),disabled:w,children:r.jsx(tr,{className:`w-4 h-4 ${w?"animate-spin":""}`})}),r.jsx("div",{className:"flex-1"}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:s,onChange:M=>o(M.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[_.length,"/",F.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:a("mqttDebug.searchPlaceholder"),value:d,onChange:M=>u(M.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&&r.jsx("button",{onClick:()=>u(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[r.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:a("mqttDebug.all")}),r.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:[r.jsx(qh,{className:"w-3 h-3"}),a("mqttDebug.incoming")]}),r.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:[r.jsx(qm,{className:"w-3 h-3"}),a("mqttDebug.outgoing")]})]})]})]}),r.jsx("div",{ref:f,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:F.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[r.jsx("p",{className:"mb-2",children:a("mqttDebug.noMessages")}),!A&&r.jsx("p",{className:"text-sm",children:a("mqttDebug.startLoggingHint")})]}):_.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[r.jsx("p",{className:"mb-2",children:a("mqttDebug.noMessagesMatch")}),r.jsx("p",{className:"text-sm",children:a("mqttDebug.adjustFilterHint")})]}):r.jsx("div",{className:"space-y-1",children:_.map((M,H)=>{const I=l.has(H),z=M.direction==="in";return r.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${I?"bg-bambu-dark-secondary":""}`,onClick:()=>C(H),children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:"text-bambu-gray shrink-0",children:P(M.timestamp)}),r.jsx("span",{className:`shrink-0 ${z?"text-blue-400":"text-green-400"}`,title:a(z?"mqttDebug.incoming":"mqttDebug.outgoing"),children:z?r.jsx(qh,{className:"w-3 h-3"}):r.jsx(qm,{className:"w-3 h-3"})}),r.jsx("span",{className:"text-purple-400 shrink-0",children:M.topic})]}),I?r.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:T(M.payload,!0)}):r.jsx("pre",{className:"mt-1 text-white/80 truncate",children:T(M.payload,!1)})]},H)})})}),r.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:A?r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),a("mqttDebug.loggingActive")]}):r.jsx("span",{children:a("mqttDebug.loggingStopped")})}),r.jsx(je,{variant:"secondary",onClick:n,children:a("common.close")})]})]})})}function Lee(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("x2d")||e==="n6"?"/img/printers/x2d.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 Ree(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 Iee(t,e,n){return t.filter(a=>{if(a.required_filament_types&&a.required_filament_types.length>0&&e!==void 0&&!a.required_filament_types.every(i=>e.has(i.toUpperCase())))return!1;if(a.filament_overrides&&a.filament_overrides.length>0&&n!==void 0){const i=a.filament_overrides.filter(o=>o.force_color_match===!0),s=a.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 y2e({printerId:t,printerModel:e,loadedFilamentTypes:n,loadedFilaments:a}){const{t:i}=_t(),{data:s}=Xe({queryKey:["queue",t,"pending",e],queryFn:()=>ae.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),o=s?Iee(s,n,a):void 0,l=o?.length||0;if(l===0)return null;const c=o?.[0];return r.jsx(Es,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[r.jsx(wa,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:i("queue.nextInQueue")}),r.jsx("p",{className:"text-sm text-white truncate",children:c?.archive_name||c?.library_file_name||`File #${c?.archive_id||c?.library_file_id}`})]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),c?.scheduled_time?Eh(c.scheduled_time,"system",i):i("time.waiting")]}),l>1&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",l-1]}),r.jsx(qa,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function Oee(t){var e,n,a="";if(typeof t=="string"||typeof t=="number")a+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=Oee(t[e]))&&(a&&(a+=" "),a+=n)}else for(n in t)t[n]&&(a&&(a+=" "),a+=n);return a}function Er(){for(var t,e,n=0,a="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=Oee(t))&&(a&&(a+=" "),a+=e);return a}var v2e=["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 l4(t){if(typeof t!="string")return!1;var e=v2e;return e.includes(t)}var w2e=["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"],S2e=new Set(w2e);function zee(t){return typeof t!="string"?!1:S2e.has(t)}function Uee(t){return typeof t=="string"&&t.startsWith("data-")}function _o(t){if(typeof t!="object"||t===null)return{};var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(zee(n)||Uee(n))&&(e[n]=t[n]);return e}function Ug(t){if(t==null)return null;if(y.isValidElement(t)&&typeof t.props=="object"&&t.props!==null){var e=t.props;return _o(e)}return typeof t=="object"&&!Array.isArray(t)?_o(t):null}function Os(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(zee(n)||Uee(n)||l4(n))&&(e[n]=t[n]);return e}function _2e(t){return t==null?null:y.isValidElement(t)?Os(t.props):typeof t=="object"&&!Array.isArray(t)?Os(t):null}var k2e=["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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},sR.apply(null,arguments)}function N2e(t,e){if(t==null)return{};var n,a,i=C2e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function C2e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var c4=y.forwardRef((t,e)=>{var{children:n,width:a,height:i,viewBox:s,className:o,style:l,title:c,desc:d}=t,u=N2e(t,k2e),m=s||{width:a,height:i,x:0,y:0},p=Er("recharts-surface",o);return y.createElement("svg",sR({},Os(u),{className:p,width:a,height:i,style:l,viewBox:"".concat(m.x," ").concat(m.y," ").concat(m.width," ").concat(m.height),ref:e}),y.createElement("title",null,c),y.createElement("desc",null,d),n)}),P2e=["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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},oR.apply(null,arguments)}function T2e(t,e){if(t==null)return{};var n,a,i=A2e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function A2e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var $a=y.forwardRef((t,e)=>{var{children:n,className:a}=t,i=T2e(t,P2e),s=Er("recharts-layer",a);return y.createElement("g",oR({className:s},Os(i),{ref:e}),n)}),Bee=y.createContext(null),j2e=()=>y.useContext(Bee);function va(t){return function(){return t}}const Hee=Math.cos,SC=Math.sin,yd=Math.sqrt,_C=Math.PI,BT=2*_C,lR=Math.PI,cR=2*lR,Qf=1e-6,M2e=cR-Qf;function qee(t){this._+=t[0];for(let e=1,n=t.length;e<n;++e)this._+=arguments[e]+t[e]}function E2e(t){let e=Math.floor(t);if(!(e>=0))throw new Error(`invalid digits: ${t}`);if(e>15)return qee;const n=10**e;return function(a){this._+=a[0];for(let i=1,s=a.length;i<s;++i)this._+=Math.round(arguments[i]*n)/n+a[i]}}class D2e{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?qee:E2e(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,a,i){this._append`Q${+e},${+n},${this._x1=+a},${this._y1=+i}`}bezierCurveTo(e,n,a,i,s,o){this._append`C${+e},${+n},${+a},${+i},${this._x1=+s},${this._y1=+o}`}arcTo(e,n,a,i,s){if(e=+e,n=+n,a=+a,i=+i,s=+s,s<0)throw new Error(`negative radius: ${s}`);let o=this._x1,l=this._y1,c=a-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>Qf)if(!(Math.abs(m*c-d*u)>Qf)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let f=a-o,g=i-l,w=c*c+d*d,b=f*f+g*g,x=Math.sqrt(w),S=Math.sqrt(p),k=s*Math.tan((lR-Math.acos((w+p-b)/(2*x*S)))/2),C=k/S,P=k/x;Math.abs(C-1)>Qf&&this._append`L${e+C*u},${n+C*m}`,this._append`A${s},${s},0,0,${+(m*f>u*g)},${this._x1=e+P*c},${this._y1=n+P*d}`}}arc(e,n,a,i,s,o){if(e=+e,n=+n,a=+a,o=!!o,a<0)throw new Error(`negative radius: ${a}`);let l=a*Math.cos(i),c=a*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)>Qf||Math.abs(this._y1-u)>Qf)&&this._append`L${d},${u}`,a&&(p<0&&(p=p%cR+cR),p>M2e?this._append`A${a},${a},0,1,${m},${e-l},${n-c}A${a},${a},0,1,${m},${this._x1=d},${this._y1=u}`:p>Qf&&this._append`A${a},${a},0,${+(p>=lR)},${m},${this._x1=e+a*Math.cos(s)},${this._y1=n+a*Math.sin(s)}`)}rect(e,n,a,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${a=+a}v${+i}h${-a}Z`}toString(){return this._}}function d4(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{const a=Math.floor(n);if(!(a>=0))throw new RangeError(`invalid digits: ${n}`);e=a}return t},()=>new D2e(e)}function u4(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function $ee(t){this._context=t}$ee.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 HT(t){return new $ee(t)}function Vee(t){return t[0]}function Gee(t){return t[1]}function Wee(t,e){var n=va(!0),a=null,i=HT,s=null,o=d4(l);t=typeof t=="function"?t:t===void 0?Vee:va(t),e=typeof e=="function"?e:e===void 0?Gee:va(e);function l(c){var d,u=(c=u4(c)).length,m,p=!1,f;for(a==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:va(+c),l):t},l.y=function(c){return arguments.length?(e=typeof c=="function"?c:va(+c),l):e},l.defined=function(c){return arguments.length?(n=typeof c=="function"?c:va(!!c),l):n},l.curve=function(c){return arguments.length?(i=c,a!=null&&(s=i(a)),l):i},l.context=function(c){return arguments.length?(c==null?a=s=null:s=i(a=c),l):a},l}function T1(t,e,n){var a=null,i=va(!0),s=null,o=HT,l=null,c=d4(d);t=typeof t=="function"?t:t===void 0?Vee:va(+t),e=typeof e=="function"?e:va(e===void 0?0:+e),n=typeof n=="function"?n:n===void 0?Gee:va(+n);function d(m){var p,f,g,w=(m=u4(m)).length,b,x=!1,S,k=new Array(w),C=new Array(w);for(s==null&&(l=o(S=c())),p=0;p<=w;++p){if(!(p<w&&i(b=m[p],p,m))===x)if(x=!x)f=p,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),g=p-1;g>=f;--g)l.point(k[g],C[g]);l.lineEnd(),l.areaEnd()}x&&(k[p]=+t(b,p,m),C[p]=+e(b,p,m),l.point(a?+a(b,p,m):k[p],n?+n(b,p,m):C[p]))}if(S)return l=null,S+""||null}function u(){return Wee().defined(i).curve(o).context(s)}return d.x=function(m){return arguments.length?(t=typeof m=="function"?m:va(+m),a=null,d):t},d.x0=function(m){return arguments.length?(t=typeof m=="function"?m:va(+m),d):t},d.x1=function(m){return arguments.length?(a=m==null?null:typeof m=="function"?m:va(+m),d):a},d.y=function(m){return arguments.length?(e=typeof m=="function"?m:va(+m),n=null,d):e},d.y0=function(m){return arguments.length?(e=typeof m=="function"?m:va(+m),d):e},d.y1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:va(+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(a).y(e)},d.defined=function(m){return arguments.length?(i=typeof m=="function"?m:va(!!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 Kee{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 F2e(t){return new Kee(t,!0)}function L2e(t){return new Kee(t,!1)}const m4={draw(t,e){const n=yd(e/_C);t.moveTo(n,0),t.arc(0,0,n,0,BT)}},R2e={draw(t,e){const n=yd(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()}},Qee=yd(1/3),I2e=Qee*2,O2e={draw(t,e){const n=yd(e/I2e),a=n*Qee;t.moveTo(0,-n),t.lineTo(a,0),t.lineTo(0,n),t.lineTo(-a,0),t.closePath()}},z2e={draw(t,e){const n=yd(e),a=-n/2;t.rect(a,a,n,n)}},U2e=.8908130915292852,Yee=SC(_C/10)/SC(7*_C/10),B2e=SC(BT/10)*Yee,H2e=-Hee(BT/10)*Yee,q2e={draw(t,e){const n=yd(e*U2e),a=B2e*n,i=H2e*n;t.moveTo(0,-n),t.lineTo(a,i);for(let s=1;s<5;++s){const o=BT*s/5,l=Hee(o),c=SC(o);t.lineTo(c*n,-l*n),t.lineTo(l*a-c*i,c*a+l*i)}t.closePath()}},E2=yd(3),$2e={draw(t,e){const n=-yd(e/(E2*3));t.moveTo(0,n*2),t.lineTo(-E2*n,-n),t.lineTo(E2*n,-n),t.closePath()}},Kl=-.5,Ql=yd(3)/2,dR=1/yd(12),V2e=(dR/2+1)*3,G2e={draw(t,e){const n=yd(e/V2e),a=n/2,i=n*dR,s=a,o=n*dR+n,l=-s,c=o;t.moveTo(a,i),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(Kl*a-Ql*i,Ql*a+Kl*i),t.lineTo(Kl*s-Ql*o,Ql*s+Kl*o),t.lineTo(Kl*l-Ql*c,Ql*l+Kl*c),t.lineTo(Kl*a+Ql*i,Kl*i-Ql*a),t.lineTo(Kl*s+Ql*o,Kl*o-Ql*s),t.lineTo(Kl*l+Ql*c,Kl*c-Ql*l),t.closePath()}};function W2e(t,e){let n=null,a=d4(i);t=typeof t=="function"?t:va(t||m4),e=typeof e=="function"?e:va(e===void 0?64:+e);function i(){let s;if(n||(n=s=a()),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:va(s),i):t},i.size=function(s){return arguments.length?(e=typeof s=="function"?s:va(+s),i):e},i.context=function(s){return arguments.length?(n=s??null,i):n},i}function kC(){}function NC(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 Xee(t){this._context=t}Xee.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:NC(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:NC(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function K2e(t){return new Xee(t)}function Zee(t){this._context=t}Zee.prototype={areaStart:kC,areaEnd:kC,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:NC(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Q2e(t){return new Zee(t)}function Jee(t){this._context=t}Jee.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,a=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,a):this._context.moveTo(n,a);break;case 3:this._point=4;default:NC(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Y2e(t){return new Jee(t)}function ete(t){this._context=t}ete.prototype={areaStart:kC,areaEnd:kC,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 X2e(t){return new ete(t)}function EV(t){return t<0?-1:1}function DV(t,e,n){var a=t._x1-t._x0,i=e-t._x1,s=(t._y1-t._y0)/(a||i<0&&-0),o=(n-t._y1)/(i||a<0&&-0),l=(s*i+o*a)/(a+i);return(EV(s)+EV(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function FV(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function D2(t,e,n){var a=t._x0,i=t._y0,s=t._x1,o=t._y1,l=(s-a)/3;t._context.bezierCurveTo(a+l,i+l*e,s-l,o-l*n,s,o)}function CC(t){this._context=t}CC.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:D2(this,this._t0,FV(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,D2(this,FV(this,n=DV(this,t,e)),n);break;default:D2(this,this._t0,n=DV(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function tte(t){this._context=new nte(t)}(tte.prototype=Object.create(CC.prototype)).point=function(t,e){CC.prototype.point.call(this,e,t)};function nte(t){this._context=t}nte.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,a,i,s){this._context.bezierCurveTo(e,t,a,n,s,i)}};function Z2e(t){return new CC(t)}function J2e(t){return new tte(t)}function rte(t){this._context=t}rte.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 a=LV(t),i=LV(e),s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(a[0][s],i[0][s],a[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 LV(t){var e,n=t.length-1,a,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)a=i[e]/s[e-1],s[e]-=a,o[e]-=a*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 eDe(t){return new rte(t)}function qT(t,e){this._context=t,this._t=e}qT.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 tDe(t){return new qT(t,.5)}function nDe(t){return new qT(t,0)}function rDe(t){return new qT(t,1)}function Bg(t,e){if((o=t.length)>1)for(var n=1,a,i,s=t[e[0]],o,l=s.length;n<o;++n)for(i=s,s=t[e[n]],a=0;a<l;++a)s[a][1]+=s[a][0]=isNaN(i[a][1])?i[a][0]:i[a][1]}function uR(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function aDe(t,e){return t[e]}function iDe(t){const e=[];return e.key=t,e}function sDe(){var t=va([]),e=uR,n=Bg,a=aDe;function i(s){var o=Array.from(t.apply(this,arguments),iDe),l,c=o.length,d=-1,u;for(const m of s)for(l=0,++d;l<c;++l)(o[l][d]=[0,+a(m,o[l].key,d,s)]).data=m;for(l=0,u=u4(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:va(Array.from(s)),i):t},i.value=function(s){return arguments.length?(a=typeof s=="function"?s:va(+s),i):a},i.order=function(s){return arguments.length?(e=s==null?uR:typeof s=="function"?s:va(Array.from(s)),i):e},i.offset=function(s){return arguments.length?(n=s??Bg,i):n},i}function oDe(t,e){if((a=t.length)>0){for(var n,a,i=0,s=t[0].length,o;i<s;++i){for(o=n=0;n<a;++n)o+=t[n][i][1]||0;if(o)for(n=0;n<a;++n)t[n][i][1]/=o}Bg(t,e)}}function lDe(t,e){if((i=t.length)>0){for(var n=0,a=t[e[0]],i,s=a.length;n<s;++n){for(var o=0,l=0;o<i;++o)l+=t[o][n][1]||0;a[n][1]+=a[n][0]=-l/2}Bg(t,e)}}function cDe(t,e){if(!(!((o=t.length)>0)||!((s=(i=t[e[0]]).length)>0))){for(var n=0,a=1,i,s,o;a<s;++a){for(var l=0,c=0,d=0;l<o;++l){for(var u=t[e[l]],m=u[a][1]||0,p=u[a-1][1]||0,f=(m-p)/2,g=0;g<l;++g){var w=t[e[g]],b=w[a][1]||0,x=w[a-1][1]||0;f+=b-x}c+=m,d+=f*m}i[a-1][1]+=i[a-1][0]=n,c&&(n-=d/c)}i[a-1][1]+=i[a-1][0]=n,Bg(t,e)}}var F2={},L2={},RV;function dDe(){return RV||(RV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==="__proto__"}t.isUnsafeProperty=e})(L2)),L2}var R2={},IV;function ate(){return IV||(IV=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})(R2)),R2}var I2={},OV;function p4(){return OV||(OV=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})(I2)),I2}var O2={},z2={},zV;function uDe(){return zV||(zV=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 a=String(n);return a==="0"&&Object.is(Number(n),-0)?"-0":a}t.toString=e})(z2)),z2}var UV;function h4(){return UV||(UV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=uDe(),n=p4();function a(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=a})(O2)),O2}var BV;function f4(){return BV||(BV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=dDe(),n=ate(),a=p4(),i=h4();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=a.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})(F2)),F2}var U2,HV;function mDe(){return HV||(HV=1,U2=f4().get),U2}var pDe=mDe();const Hg=Tc(pDe);var hDe=4;function wh(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:hDe,n=10**e,a=Math.round(t*n)/n;return Object.is(a,-0)?0:a}function ti(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),a=1;a<e;a++)n[a-1]=arguments[a];return t.reduce((i,s,o)=>{var l=n[o-1];return typeof l=="string"?i+l+s:l!==void 0?i+wh(l)+s:i+s},"")}var us=t=>t===0?0:t>0?1:-1,hd=t=>typeof t=="number"&&t!=+t,qg=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,hn=t=>(typeof t=="number"||t instanceof Number)&&!hd(t),kc=t=>hn(t)||typeof t=="string",fDe=0,Gw=t=>{var e=++fDe;return"".concat(t||"").concat(e)},no=function(e,n){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!hn(e)&&typeof e!="string")return a;var s;if(qg(e)){if(n==null)return a;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return hd(s)&&(s=a),i&&n!=null&&s>n&&(s=n),s},ite=t=>{if(!Array.isArray(t))return!1;for(var e=t.length,n={},a=0;a<e;a++)if(!n[String(t[a])])n[String(t[a])]=!0;else return!0;return!1};function qr(t,e,n){return hn(t)&&hn(e)?wh(t+n*(e-t)):e}function ste(t,e,n){if(!(!t||!t.length))return t.find(a=>a&&(typeof e=="function"?e(a):Hg(a,e))===n)}var Ua=t=>t===null||typeof t>"u",HS=t=>Ua(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function Vo(t){return t!=null}function af(){}var gDe=["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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},mR.apply(null,arguments)}function qV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function $V(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?qV(Object(n),!0).forEach(function(a){bDe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):qV(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function bDe(t,e,n){return(e=xDe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function xDe(t){var e=yDe(t,"string");return typeof e=="symbol"?e:e+""}function yDe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vDe(t,e){if(t==null)return{};var n,a,i=wDe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function wDe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var ote={symbolCircle:m4,symbolCross:R2e,symbolDiamond:O2e,symbolSquare:z2e,symbolStar:q2e,symbolTriangle:$2e,symbolWye:G2e},SDe=Math.PI/180,_De=t=>{var e="symbol".concat(HS(t));return ote[e]||m4},kDe=(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 a=18*SDe;return 1.25*t*t*(Math.tan(a)-Math.tan(a*2)*Math.tan(a)**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}},NDe=(t,e)=>{ote["symbol".concat(HS(t))]=e},g4=t=>{var{type:e="circle",size:n=64,sizeType:a="area"}=t,i=vDe(t,gDe),s=$V($V({},i),{},{type:e,size:n,sizeType:a}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var p=_De(o),f=W2e().type(p).size(kDe(n,a,o)),g=f();if(g!==null)return g},{className:c,cx:d,cy:u}=s,m=Os(s);return hn(d)&&hn(u)&&hn(n)?y.createElement("path",mR({},m,{className:Er("recharts-symbols",c),transform:"translate(".concat(d,", ").concat(u,")"),d:l()})):null};g4.registerSymbol=NDe;var lte=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,b4=(t,e)=>{if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(y.isValidElement(t)&&(n=t.props),typeof n!="object"&&typeof n!="function")return null;var a={};return Object.keys(n).forEach(i=>{l4(i)&&(a[i]=(s=>n[i](n,s)))}),a},CDe=(t,e,n)=>a=>(t(e,n,a),null),qS=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var a=null;return Object.keys(t).forEach(i=>{var s=t[i];l4(i)&&typeof s=="function"&&(a||(a={}),a[i]=CDe(s,e,n))}),a};function VV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function PDe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?VV(Object(n),!0).forEach(function(a){TDe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):VV(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function TDe(t,e,n){return(e=ADe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ADe(t){var e=jDe(t,"string");return typeof e=="symbol"?e:e+""}function jDe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Va(t,e){var n=PDe({},t),a=e,i=Object.keys(e),s=i.reduce((o,l)=>(o[l]===void 0&&a[l]!==void 0&&(o[l]=a[l]),o),n);return s}function PC(){return PC=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},PC.apply(null,arguments)}function GV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function MDe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?GV(Object(n),!0).forEach(function(a){EDe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):GV(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function EDe(t,e,n){return(e=DDe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function DDe(t){var e=FDe(t,"string");return typeof e=="symbol"?e:e+""}function FDe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Zl=32,LDe={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle"};function RDe(t){var{data:e,iconType:n,inactiveColor:a}=t,i=Zl/2,s=Zl/6,o=Zl/3,l=e.inactive?a:e.color,c=n??e.type;if(c==="none")return null;if(c==="plainline"){var d;return y.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:Zl,y2:i,className:"recharts-legend-icon"})}if(c==="line")return y.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(i,"h").concat(o,`
  8092. A`).concat(s,",").concat(s,",0,1,1,").concat(2*o,",").concat(i,`
  8093. H`).concat(Zl,"M").concat(2*o,",").concat(i,`
  8094. A`).concat(s,",").concat(s,",0,1,1,").concat(o,",").concat(i),className:"recharts-legend-icon"});if(c==="rect")return y.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Zl/8,"h").concat(Zl,"v").concat(Zl*3/4,"h").concat(-Zl,"z"),className:"recharts-legend-icon"});if(y.isValidElement(e.legendIcon)){var u=MDe({},e);return delete u.legendIcon,y.cloneElement(e.legendIcon,u)}return y.createElement(g4,{fill:l,cx:i,cy:i,size:Zl,sizeType:"diameter",type:c})}function IDe(t){var{payload:e,iconSize:n,layout:a,formatter:i,inactiveColor:s,iconType:o}=t,l={x:0,y:0,width:Zl,height:Zl},c={display:a==="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=Er({"recharts-legend-item":!0,["legend-item-".concat(m)]:!0,inactive:u.inactive});if(u.type==="none")return null;var g=u.inactive?s:u.color,w=p?p(u.value,u,m):u.value;return y.createElement("li",PC({className:f,style:c,key:"legend-item-".concat(m)},qS(t,u,m)),y.createElement(c4,{width:n,height:n,viewBox:l,style:d,"aria-label":"".concat(w," legend icon")},y.createElement(RDe,{data:u,iconType:o,inactiveColor:s})),y.createElement("span",{className:"recharts-legend-item-text",style:{color:g}},w))})}var ODe=t=>{var e=Va(t,LDe),{payload:n,layout:a,align:i}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:a==="horizontal"?i:"left"};return y.createElement("ul",{className:"recharts-default-legend",style:s},y.createElement(IDe,PC({},e,{payload:n})))},B2={},H2={},WV;function zDe(){return WV||(WV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,a){const i=new Map;for(let s=0;s<n.length;s++){const o=n[s],l=a(o,s,n);i.has(l)||i.set(l,o)}return Array.from(i.values())}t.uniqBy=e})(H2)),H2}var q2={},KV;function UDe(){return KV||(KV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,a){return function(...i){return n.apply(this,i.slice(0,a))}}t.ary=e})(q2)),q2}var $2={},QV;function cte(){return QV||(QV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n}t.identity=e})($2)),$2}var V2={},G2={},W2={},YV;function BDe(){return YV||(YV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Number.isSafeInteger(n)&&n>=0}t.isLength=e})(W2)),W2}var XV;function x4(){return XV||(XV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BDe();function n(a){return a!=null&&typeof a!="function"&&e.isLength(a.length)}t.isArrayLike=n})(G2)),G2}var K2={},ZV;function HDe(){return ZV||(ZV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(K2)),K2}var JV;function qDe(){return JV||(JV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=x4(),n=HDe();function a(i){return n.isObjectLike(i)&&e.isArrayLike(i)}t.isArrayLikeObject=a})(V2)),V2}var Q2={},Y2={},eG;function $De(){return eG||(eG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=f4();function n(a){return function(i){return e.get(i,a)}}t.property=n})(Y2)),Y2}var X2={},Z2={},J2={},eD={},tG;function dte(){return tG||(tG=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})(eD)),eD}var tD={},nG;function ute(){return nG||(nG=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})(tD)),tD}var nD={},rG;function mte(){return rG||(rG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,a){return n===a||Number.isNaN(n)&&Number.isNaN(a)}t.isEqualsSameValueZero=e})(nD)),nD}var aG;function VDe(){return aG||(aG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=dte(),n=ute(),a=mte();function i(u,m,p){return typeof p!="function"?i(u,m,()=>{}):s(u,m,function f(g,w,b,x,S,k){const C=p(g,w,b,x,S,k);return C!==void 0?!!C:s(g,w,f,k)},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):a.isEqualsSameValueZero(u,m);default:return e.isObject(u)?typeof m=="string"?m==="":!0:a.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 g=Object.keys(m);if(u==null||n.isPrimitive(u))return g.length===0;if(g.length===0)return!0;if(f?.has(m))return f.get(m)===u;f?.set(m,u);try{for(let w=0;w<g.length;w++){const b=g[w];if(!n.isPrimitive(u)&&!(b in u)||m[b]===void 0&&u[b]!==void 0||m[b]===null&&u[b]!==null||!p(u[b],m[b],b,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[g,w]of m.entries()){const b=u.get(g);if(p(b,w,g,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 g=new Set;for(let w=0;w<m.length;w++){const b=m[w];let x=!1;for(let S=0;S<u.length;S++){if(g.has(S))continue;const k=u[S];let C=!1;if(p(k,b,w,u,m,f)&&(C=!0),C){g.add(S),x=!0;break}}if(!x)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})(J2)),J2}var iG;function pte(){return iG||(iG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=VDe();function n(a,i){return e.isMatchWith(a,i,()=>{})}t.isMatch=n})(Z2)),Z2}var rD={},aD={},iD={},sG;function GDe(){return sG||(sG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Object.getOwnPropertySymbols(n).filter(a=>Object.prototype.propertyIsEnumerable.call(n,a))}t.getSymbols=e})(iD)),iD}var sD={},oG;function y4(){return oG||(oG=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})(sD)),sD}var oD={},lG;function hte(){return lG||(lG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",a="[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]",g="[object Error]",w="[object DataView]",b="[object Uint8Array]",x="[object Uint8ClampedArray]",S="[object Uint16Array]",k="[object Uint32Array]",C="[object BigUint64Array]",P="[object Int8Array]",T="[object Int16Array]",A="[object Int32Array]",F="[object BigInt64Array]",_="[object Float32Array]",M="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=p,t.arrayTag=u,t.bigInt64ArrayTag=F,t.bigUint64ArrayTag=C,t.booleanTag=i,t.dataViewTag=w,t.dateTag=l,t.errorTag=g,t.float32ArrayTag=_,t.float64ArrayTag=M,t.functionTag=m,t.int16ArrayTag=T,t.int32ArrayTag=A,t.int8ArrayTag=P,t.mapTag=c,t.numberTag=a,t.objectTag=f,t.regexpTag=e,t.setTag=d,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=S,t.uint32ArrayTag=k,t.uint8ArrayTag=b,t.uint8ClampedArrayTag=x})(oD)),oD}var lD={},cG;function WDe(){return cG||(cG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(lD)),lD}var dG;function fte(){return dG||(dG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=GDe(),n=y4(),a=hte(),i=ute(),s=WDe();function o(u,m){return l(u,void 0,u,new Map,m)}function l(u,m,p,f=new Map,g=void 0){const w=g?.(u,m,p,f);if(w!==void 0)return w;if(i.isPrimitive(u))return u;if(f.has(u))return f.get(u);if(Array.isArray(u)){const b=new Array(u.length);f.set(u,b);for(let x=0;x<u.length;x++)b[x]=l(u[x],x,p,f,g);return Object.hasOwn(u,"index")&&(b.index=u.index),Object.hasOwn(u,"input")&&(b.input=u.input),b}if(u instanceof Date)return new Date(u.getTime());if(u instanceof RegExp){const b=new RegExp(u.source,u.flags);return b.lastIndex=u.lastIndex,b}if(u instanceof Map){const b=new Map;f.set(u,b);for(const[x,S]of u)b.set(x,l(S,x,p,f,g));return b}if(u instanceof Set){const b=new Set;f.set(u,b);for(const x of u)b.add(l(x,void 0,p,f,g));return b}if(typeof Buffer<"u"&&Buffer.isBuffer(u))return u.subarray();if(s.isTypedArray(u)){const b=new(Object.getPrototypeOf(u)).constructor(u.length);f.set(u,b);for(let x=0;x<u.length;x++)b[x]=l(u[x],x,p,f,g);return b}if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer)return u.slice(0);if(u instanceof DataView){const b=new DataView(u.buffer.slice(0),u.byteOffset,u.byteLength);return f.set(u,b),c(b,u,p,f,g),b}if(typeof File<"u"&&u instanceof File){const b=new File([u],u.name,{type:u.type});return f.set(u,b),c(b,u,p,f,g),b}if(typeof Blob<"u"&&u instanceof Blob){const b=new Blob([u],{type:u.type});return f.set(u,b),c(b,u,p,f,g),b}if(u instanceof Error){const b=new u.constructor;return f.set(u,b),b.message=u.message,b.name=u.name,b.stack=u.stack,b.cause=u.cause,c(b,u,p,f,g),b}if(u instanceof Boolean){const b=new Boolean(u.valueOf());return f.set(u,b),c(b,u,p,f,g),b}if(u instanceof Number){const b=new Number(u.valueOf());return f.set(u,b),c(b,u,p,f,g),b}if(u instanceof String){const b=new String(u.valueOf());return f.set(u,b),c(b,u,p,f,g),b}if(typeof u=="object"&&d(u)){const b=Object.create(Object.getPrototypeOf(u));return f.set(u,b),c(b,u,p,f,g),b}return u}function c(u,m,p=u,f,g){const w=[...Object.keys(m),...e.getSymbols(m)];for(let b=0;b<w.length;b++){const x=w[b],S=Object.getOwnPropertyDescriptor(u,x);(S==null||S.writable)&&(u[x]=l(m[x],x,p,f,g))}}function d(u){switch(n.getTag(u)){case a.argumentsTag:case a.arrayTag:case a.arrayBufferTag:case a.dataViewTag:case a.booleanTag:case a.dateTag:case a.float32ArrayTag:case a.float64ArrayTag:case a.int8ArrayTag:case a.int16ArrayTag:case a.int32ArrayTag:case a.mapTag:case a.numberTag:case a.objectTag:case a.regexpTag:case a.setTag:case a.stringTag:case a.symbolTag:case a.uint8ArrayTag:case a.uint8ClampedArrayTag:case a.uint16ArrayTag:case a.uint32ArrayTag:return!0;default:return!1}}t.cloneDeepWith=o,t.cloneDeepWithImpl=l,t.copyProperties=c})(aD)),aD}var uG;function KDe(){return uG||(uG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=fte();function n(a){return e.cloneDeepWithImpl(a,void 0,a,new Map,void 0)}t.cloneDeep=n})(rD)),rD}var mG;function QDe(){return mG||(mG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pte(),n=KDe();function a(i){return i=n.cloneDeep(i),s=>e.isMatch(s,i)}t.matches=a})(X2)),X2}var cD={},dD={},uD={},pG;function YDe(){return pG||(pG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=fte(),n=y4(),a=hte();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)===a.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 a.numberTag:case a.stringTag:case a.booleanTag:{const p=new s.constructor(s?.valueOf());return e.copyProperties(p,s),p}case a.argumentsTag:{const p={};return e.copyProperties(p,s),p.length=s.length,p[Symbol.iterator]=s[Symbol.iterator],p}default:return}}})}t.cloneDeepWith=i})(uD)),uD}var hG;function XDe(){return hG||(hG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=YDe();function n(a){return e.cloneDeepWith(a)}t.cloneDeep=n})(dD)),dD}var mD={},pD={},fG;function gte(){return fG||(fG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(a,i=Number.MAX_SAFE_INTEGER){switch(typeof a){case"number":return Number.isInteger(a)&&a>=0&&a<i;case"symbol":return!1;case"string":return e.test(a)}}t.isIndex=n})(pD)),pD}var hD={},gG;function ZDe(){return gG||(gG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=y4();function n(a){return a!==null&&typeof a=="object"&&e.getTag(a)==="[object Arguments]"}t.isArguments=n})(hD)),hD}var bG;function JDe(){return bG||(bG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=ate(),n=gte(),a=ZDe(),i=h4();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)||a.isArguments(d))&&n.isIndex(m)&&m<d.length))return!1;d=d[m]}return!0}t.has=s})(mD)),mD}var xG;function e3e(){return xG||(xG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pte(),n=p4(),a=XDe(),i=f4(),s=JDe();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=a.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})(cD)),cD}var yG;function t3e(){return yG||(yG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=cte(),n=$De(),a=QDe(),i=e3e();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]):a.matches(o);case"string":case"symbol":case"number":return n.property(o)}}t.iteratee=s})(Q2)),Q2}var vG;function n3e(){return vG||(vG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=zDe(),n=UDe(),a=cte(),i=qDe(),s=t3e();function o(l,c=a.identity){return i.isArrayLikeObject(l)?e.uniqBy(Array.from(l),n.ary(s.iteratee(c),1)):[]}t.uniqBy=o})(B2)),B2}var fD,wG;function r3e(){return wG||(wG=1,fD=n3e().uniqBy),fD}var a3e=r3e();const SG=Tc(a3e);function bte(t,e,n){return e===!0?SG(t,n):typeof e=="function"?SG(t,e):t}var gD={exports:{}},bD={};var _G;function i3e(){if(_G)return bD;_G=1;var t=tb(),e=KX();function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var a=typeof Object.is=="function"?Object.is:n,i=e.useSyncExternalStore,s=t.useRef,o=t.useEffect,l=t.useMemo,c=t.useDebugValue;return bD.useSyncExternalStoreWithSelector=function(d,u,m,p,f){var g=s(null);if(g.current===null){var w={hasValue:!1,value:null};g.current=w}else w=g.current;g=l(function(){function x(T){if(!S){if(S=!0,k=T,T=p(T),f!==void 0&&w.hasValue){var A=w.value;if(f(A,T))return C=A}return C=T}if(A=C,a(k,T))return A;var F=p(T);return f!==void 0&&f(A,F)?(k=T,A):(k=T,C=F)}var S=!1,k,C,P=m===void 0?null:m;return[function(){return x(u())},P===null?void 0:function(){return x(P())}]},[u,m,p,f]);var b=i(d,g[0],g[1]);return o(function(){w.hasValue=!0,w.value=b},[b]),c(b),b},bD}var kG;function s3e(){return kG||(kG=1,gD.exports=i3e()),gD.exports}var xte=s3e(),v4=y.createContext(null),o3e=t=>t,ga=()=>{var t=y.useContext(v4);return t?t.store.dispatch:o3e},AN=()=>{},l3e=()=>AN,c3e=(t,e)=>t===e;function bn(t){var e=y.useContext(v4),n=y.useMemo(()=>e?a=>{if(a!=null)return t(a)}:AN,[e,t]);return xte.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:l3e,e?e.store.getState:AN,e?e.store.getState:AN,n,c3e)}function d3e(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function u3e(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function m3e(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(n=>typeof n=="function")){const n=t.map(a=>typeof a=="function"?`function ${a.name||"unnamed"}()`:typeof a).join(", ");throw new TypeError(`${e}[${n}]`)}}var NG=t=>Array.isArray(t)?t:[t];function p3e(t){const e=Array.isArray(t[0])?t[0]:t;return m3e(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function h3e(t,e){const n=[],{length:a}=t;for(let i=0;i<a;i++)n.push(t[i].apply(null,e));return n}var f3e=class{constructor(t){this.value=t}deref(){return this.value}},g3e=typeof WeakRef<"u"?WeakRef:f3e,b3e=0,CG=1;function A1(){return{s:b3e,v:void 0,o:null,p:null}}function yte(t,e={}){let n=A1();const{resultEqualityCheck:a}=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 g=l.o;g===null&&(l.o=g=new WeakMap);const w=g.get(f);w===void 0?(l=A1(),g.set(f,l)):l=w}else{let g=l.p;g===null&&(l.p=g=new Map);const w=g.get(f);w===void 0?(l=A1(),g.set(f,l)):l=w}}const d=l;let u;if(l.s===CG)u=l.v;else if(u=t.apply(null,arguments),s++,a){const m=i?.deref?.()??i;m!=null&&a(m,u)&&(u=m,s!==0&&s--),i=typeof u=="object"&&u!==null||typeof u=="function"?new g3e(u):u}return d.s=CG,d.v=u,u}return o.clearCache=()=>{n=A1(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function x3e(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,a=(...i)=>{let s=0,o=0,l,c={},d=i.pop();typeof d=="object"&&(c=d,d=i.pop()),d3e(d,`createSelector expects an output function after the inputs, but received: [${typeof d}]`);const u={...n,...c},{memoize:m,memoizeOptions:p=[],argsMemoize:f=yte,argsMemoizeOptions:g=[]}=u,w=NG(p),b=NG(g),x=p3e(i),S=m(function(){return s++,d.apply(null,arguments)},...w),k=f(function(){o++;const P=h3e(x,arguments);return l=S.apply(null,P),l},...b);return Object.assign(k,{resultFunc:d,memoizedResultFunc:S,dependencies:x,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:m,argsMemoize:f})};return Object.assign(a,{withTypes:()=>a}),a}var Pt=x3e(yte),y3e=Object.assign((t,e=Pt)=>{u3e(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),a=n.map(s=>t[s]);return e(a,(...s)=>s.reduce((o,l,c)=>(o[n[c]]=l,o),{}))},{withTypes:()=>y3e}),xD={},yD={},vD={},PG;function v3e(){return PG||(PG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(a){return typeof a=="symbol"?1:a===null?2:a===void 0?3:a!==a?4:0}const n=(a,i,s)=>{if(a!==i){const o=e(a),l=e(i);if(o===l&&o===0){if(a<i)return s==="desc"?1:-1;if(a>i)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(vD)),vD}var wD={},SD={},TG;function vte(){return TG||(TG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(SD)),SD}var AG;function w3e(){return AG||(AG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=vte(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,a=/^\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"&&(a.test(s)||!n.test(s))||o!=null&&Object.hasOwn(o,s)}t.isKey=i})(wD)),wD}var jG;function S3e(){return jG||(jG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=v3e(),n=w3e(),a=h4();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,g)=>{let w=f;for(let b=0;b<g.length&&w!=null;++b)w=w[g[b]];return w},u=(f,g)=>g==null||f==null?g:typeof f=="object"&&"key"in f?Object.hasOwn(g,f.key)?g[f.key]:d(g,f.path):typeof f=="function"?f(g):Array.isArray(f)?d(g,f):typeof g=="object"?g[f]:g,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:a.toPath(f)}));return s.map(f=>({original:f,criteria:m.map(g=>u(g,f))})).slice().sort((f,g)=>{for(let w=0;w<m.length;w++){const b=e.compareValues(f.criteria[w],g.criteria[w],l[w]);if(b!==0)return b}return 0}).map(f=>f.original)}t.orderBy=i})(yD)),yD}var _D={},MG;function _3e(){return MG||(MG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,a=1){const i=[],s=Math.floor(a),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})(_D)),_D}var kD={},EG;function wte(){return EG||(EG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=gte(),n=x4(),a=dte(),i=mte();function s(o,l,c){return a.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})(kD)),kD}var DG;function k3e(){return DG||(DG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=S3e(),n=_3e(),a=wte();function i(s,...o){const l=o.length;return l>1&&a.isIterateeCall(s,o[0],o[1])?o=[]:l>2&&a.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),e.orderBy(s,n.flatten(o),["asc"])}t.sortBy=i})(xD)),xD}var ND,FG;function N3e(){return FG||(FG=1,ND=k3e().sortBy),ND}var C3e=N3e();const $T=Tc(C3e);var Ste=t=>t.legend.settings,P3e=t=>t.legend.size,T3e=t=>t.legend.payload,A3e=Pt([T3e,Ste],(t,e)=>{var{itemSorter:n}=e,a=t.flat(1);return n?$T(a,n):a});function j3e(){return bn(A3e)}var j1=1;function _te(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[e,n]=y.useState({height:0,left:0,top:0,width:0}),a=y.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)>j1||Math.abs(o.left-e.left)>j1||Math.abs(o.top-e.top)>j1||Math.abs(o.width-e.width)>j1)&&n({height:o.height,left:o.left,top:o.top,width:o.width})}},[e.width,e.height,e.top,e.left,...t]);return[e,a]}function Ps(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 M3e=typeof Symbol=="function"&&Symbol.observable||"@@observable",LG=M3e,CD=()=>Math.random().toString(36).substring(7).split("").join("."),E3e={INIT:`@@redux/INIT${CD()}`,REPLACE:`@@redux/REPLACE${CD()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${CD()}`},TC=E3e;function w4(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 kte(t,e,n){if(typeof t!="function")throw new Error(Ps(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Ps(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Ps(1));return n(kte)(t,e)}let a=t,i=e,s=new Map,o=s,l=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((b,x)=>{o.set(x,b)}))}function u(){if(c)throw new Error(Ps(3));return i}function m(b){if(typeof b!="function")throw new Error(Ps(4));if(c)throw new Error(Ps(5));let x=!0;d();const S=l++;return o.set(S,b),function(){if(x){if(c)throw new Error(Ps(6));x=!1,d(),o.delete(S),s=null}}}function p(b){if(!w4(b))throw new Error(Ps(7));if(typeof b.type>"u")throw new Error(Ps(8));if(typeof b.type!="string")throw new Error(Ps(17));if(c)throw new Error(Ps(9));try{c=!0,i=a(i,b)}finally{c=!1}return(s=o).forEach(S=>{S()}),b}function f(b){if(typeof b!="function")throw new Error(Ps(10));a=b,p({type:TC.REPLACE})}function g(){const b=m;return{subscribe(x){if(typeof x!="object"||x===null)throw new Error(Ps(11));function S(){const C=x;C.next&&C.next(u())}return S(),{unsubscribe:b(S)}},[LG](){return this}}}return p({type:TC.INIT}),{dispatch:p,subscribe:m,getState:u,replaceReducer:f,[LG]:g}}function D3e(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:TC.INIT})>"u")throw new Error(Ps(12));if(typeof n(void 0,{type:TC.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Ps(13))})}function Nte(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 a=Object.keys(n);let i;try{D3e(n)}catch(s){i=s}return function(o={},l){if(i)throw i;let c=!1;const d={};for(let u=0;u<a.length;u++){const m=a[u],p=n[m],f=o[m],g=p(f,l);if(typeof g>"u")throw l&&l.type,new Error(Ps(14));d[m]=g,c=c||g!==f}return c=c||a.length!==Object.keys(o).length,c?d:o}}function AC(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...a)=>e(n(...a)))}function F3e(...t){return e=>(n,a)=>{const i=e(n,a);let s=()=>{throw new Error(Ps(15))};const o={getState:i.getState,dispatch:(c,...d)=>s(c,...d)},l=t.map(c=>c(o));return s=AC(...l)(i.dispatch),{...i,dispatch:s}}}function Cte(t){return w4(t)&&"type"in t&&typeof t.type=="string"}var Pte=Symbol.for("immer-nothing"),RG=Symbol.for("immer-draftable"),ko=Symbol.for("immer-state");function ad(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var vl=Object,Ty=vl.getPrototypeOf,jC="constructor",VT="prototype",pR="configurable",MC="enumerable",jN="writable",Ww="value",Ym=t=>!!t&&!!t[ko];function fd(t){return t?Tte(t)||WT(t)||!!t[RG]||!!t[jC]?.[RG]||KT(t)||QT(t):!1}var L3e=vl[VT][jC].toString(),IG=new WeakMap;function Tte(t){if(!t||!S4(t))return!1;const e=Ty(t);if(e===null||e===vl[VT])return!0;const n=vl.hasOwnProperty.call(e,jC)&&e[jC];if(n===Object)return!0;if(!Ux(n))return!1;let a=IG.get(n);return a===void 0&&(a=Function.toString.call(n),IG.set(n,a)),a===L3e}function GT(t,e,n=!0){$S(t)===0?(n?Reflect.ownKeys(t):vl.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((a,i)=>e(i,a,t))}function $S(t){const e=t[ko];return e?e.type_:WT(t)?1:KT(t)?2:QT(t)?3:0}var OG=(t,e,n=$S(t))=>n===2?t.has(e):vl[VT].hasOwnProperty.call(t,e),hR=(t,e,n=$S(t))=>n===2?t.get(e):t[e],EC=(t,e,n,a=$S(t))=>{a===2?t.set(e,n):a===3?t.add(n):t[e]=n};function R3e(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var WT=Array.isArray,KT=t=>t instanceof Map,QT=t=>t instanceof Set,S4=t=>typeof t=="object",Ux=t=>typeof t=="function",PD=t=>typeof t=="boolean";function I3e(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var fm=t=>t.copy_||t.base_,_4=t=>t.modified_?t.copy_:t.base_;function fR(t,e){if(KT(t))return new Map(t);if(QT(t))return new Set(t);if(WT(t))return Array[VT].slice.call(t);const n=Tte(t);if(e===!0||e==="class_only"&&!n){const a=vl.getOwnPropertyDescriptors(t);delete a[ko];let i=Reflect.ownKeys(a);for(let s=0;s<i.length;s++){const o=i[s],l=a[o];l[jN]===!1&&(l[jN]=!0,l[pR]=!0),(l.get||l.set)&&(a[o]={[pR]:!0,[jN]:!0,[MC]:l[MC],[Ww]:t[o]})}return vl.create(Ty(t),a)}else{const a=Ty(t);if(a!==null&&n)return{...t};const i=vl.create(a);return vl.assign(i,t)}}function k4(t,e=!1){return YT(t)||Ym(t)||!fd(t)||($S(t)>1&&vl.defineProperties(t,{set:M1,add:M1,clear:M1,delete:M1}),vl.freeze(t),e&&GT(t,(n,a)=>{k4(a,!0)},!1)),t}function O3e(){ad(2)}var M1={[Ww]:O3e};function YT(t){return t===null||!S4(t)?!0:vl.isFrozen(t)}var DC="MapSet",gR="Patches",zG="ArrayMethods",Ate={};function $g(t){const e=Ate[t];return e||ad(0,t),e}var UG=t=>!!Ate[t],Kw,jte=()=>Kw,z3e=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:UG(DC)?$g(DC):void 0,arrayMethodsPlugin_:UG(zG)?$g(zG):void 0});function BG(t,e){e&&(t.patchPlugin_=$g(gR),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function bR(t){xR(t),t.drafts_.forEach(U3e),t.drafts_=null}function xR(t){t===Kw&&(Kw=t.parent_)}var HG=t=>Kw=z3e(Kw,t);function U3e(t){const e=t[ko];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function qG(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[ko].modified_&&(bR(e),ad(4)),fd(t)&&(t=$G(e,t));const{patchPlugin_:i}=e;i&&i.generateReplacementPatches_(n[ko].base_,t,e)}else t=$G(e,n);return B3e(e,t,!0),bR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==Pte?t:void 0}function $G(t,e){if(YT(e))return e;const n=e[ko];if(!n)return FC(e,t.handledSet_,t);if(!XT(n,t))return e;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:a}=n;if(a)for(;a.length>0;)a.pop()(t);Dte(n,t)}return n.copy_}function B3e(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&k4(e,n)}function Mte(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var XT=(t,e)=>t.scope_===e,H3e=[];function Ete(t,e,n,a){const i=fm(t),s=t.type_;if(a!==void 0&&hR(i,a,s)===e){EC(i,a,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;GT(i,(c,d)=>{if(Ym(d)){const u=l.get(d)||[];u.push(c),l.set(d,u)}})}const o=t.draftLocations_.get(e)??H3e;for(const l of o)EC(i,l,n,s)}function q3e(t,e,n){t.callbacks_.push(function(i){const s=e;if(!s||!XT(s,i))return;i.mapSetPlugin_?.fixSetContents(s);const o=_4(s);Ete(t,s.draft_??s,o,n),Dte(s,i)})}function Dte(t,e){if(t.modified_&&!t.finalized_&&(t.type_===3||t.type_===1&&t.allIndicesReassigned_||(t.assigned_?.size??0)>0)){const{patchPlugin_:a}=e;if(a){const i=a.getPath(t);i&&a.generatePatches_(t,i,e)}Mte(t)}}function $3e(t,e,n){const{scope_:a}=t;if(Ym(n)){const i=n[ko];XT(i,a)&&i.callbacks_.push(function(){MN(t);const o=_4(i);Ete(t,n,o,e)})}else fd(n)&&t.callbacks_.push(function(){const s=fm(t);t.type_===3?s.has(n)&&FC(n,a.handledSet_,a):hR(s,e,t.type_)===n&&a.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&FC(hR(t.copy_,e,t.type_),a.handledSet_,a)})}function FC(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Ym(t)||e.has(t)||!fd(t)||YT(t)||(e.add(t),GT(t,(a,i)=>{if(Ym(i)){const s=i[ko];if(XT(s,n)){const o=_4(s);EC(t,a,o,t.type_),Mte(s)}}else fd(i)&&FC(i,e,n)})),t}function V3e(t,e){const n=WT(t),a={type_:n?1:0,scope_:e?e.scope_:jte(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=a,s=LC;n&&(i=[a],s=Qw);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return a.draft_=l,a.revoke_=o,[l,a]}var LC={get(t,e){if(e===ko)return t;let n=t.scope_.arrayMethodsPlugin_;const a=t.type_===1&&typeof e=="string";if(a&&n?.isArrayOperationMethod(e))return n.createMethodInterceptor(t,e);const i=fm(t);if(!OG(i,e,t.type_))return G3e(t,i,e);const s=i[e];if(t.finalized_||!fd(s)||a&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&I3e(e))return s;if(s===TD(t.base_,e)){MN(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 fm(t)},ownKeys(t){return Reflect.ownKeys(fm(t))},set(t,e,n){const a=Fte(fm(t),e);if(a?.set)return a.set.call(t.draft_,n),!0;if(!t.modified_){const i=TD(fm(t),e),s=i?.[ko];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(R3e(n,i)&&(n!==void 0||OG(t.base_,e,t.type_)))return!0;MN(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),$3e(t,e,n)),!0},deleteProperty(t,e){return MN(t),TD(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=fm(t),a=Reflect.getOwnPropertyDescriptor(n,e);return a&&{[jN]:!0,[pR]:t.type_!==1||e!=="length",[MC]:a[MC],[Ww]:n[e]}},defineProperty(){ad(11)},getPrototypeOf(t){return Ty(t.base_)},setPrototypeOf(){ad(12)}},Qw={};for(let t in LC){let e=LC[t];Qw[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}Qw.deleteProperty=function(t,e){return Qw.set.call(this,t,e,void 0)};Qw.set=function(t,e,n){return LC.set.call(this,t[0],e,n,t[0])};function TD(t,e){const n=t[ko];return(n?fm(n):t)[e]}function G3e(t,e,n){const a=Fte(e,n);return a?Ww in a?a[Ww]:a.get?.call(t.draft_):void 0}function Fte(t,e){if(!(e in t))return;let n=Ty(t);for(;n;){const a=Object.getOwnPropertyDescriptor(n,e);if(a)return a;n=Ty(n)}}function yR(t){t.modified_||(t.modified_=!0,t.parent_&&yR(t.parent_))}function MN(t){t.copy_||(t.assigned_=new Map,t.copy_=fR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var W3e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,a,i)=>{if(Ux(n)&&!Ux(a)){const o=a;a=n;const l=this;return function(d=o,...u){return l.produce(d,m=>a.call(this,m,...u))}}Ux(a)||ad(6),i!==void 0&&!Ux(i)&&ad(7);let s;if(fd(n)){const o=HG(this),l=vR(o,n,void 0);let c=!0;try{s=a(l),c=!1}finally{c?bR(o):xR(o)}return BG(o,i),qG(s,o)}else if(!n||!S4(n)){if(s=a(n),s===void 0&&(s=n),s===Pte&&(s=void 0),this.autoFreeze_&&k4(s,!0),i){const o=[],l=[];$g(gR).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),i(o,l)}return s}else ad(1,n)},this.produceWithPatches=(n,a)=>{if(Ux(n))return(l,...c)=>this.produceWithPatches(l,d=>n(d,...c));let i,s;return[this.produce(n,a,(l,c)=>{i=l,s=c}),i,s]},PD(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),PD(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),PD(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){fd(e)||ad(8),Ym(e)&&(e=ud(e));const n=HG(this),a=vR(n,e,void 0);return a[ko].isManual_=!0,xR(n),a}finishDraft(e,n){const a=e&&e[ko];(!a||!a.isManual_)&&ad(9);const{scope_:i}=a;return BG(i,n),qG(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 a;for(a=n.length-1;a>=0;a--){const s=n[a];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}a>-1&&(n=n.slice(a+1));const i=$g(gR).applyPatches_;return Ym(e)?i(e,n):this.produce(e,s=>i(s,n))}};function vR(t,e,n,a){const[i,s]=KT(e)?$g(DC).proxyMap_(e,n):QT(e)?$g(DC).proxySet_(e,n):V3e(e,n);return(n?.scope_??jte()).drafts_.push(i),s.callbacks_=n?.callbacks_??[],s.key_=a,n&&a!==void 0?q3e(n,s,a):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:d}=c;s.modified_&&d&&d.generatePatches_(s,[],c)}),i}function ud(t){return Ym(t)||ad(10,t),Lte(t)}function Lte(t){if(!fd(t)||YT(t))return t;const e=t[ko];let n,a=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=fR(t,e.scope_.immer_.useStrictShallowCopy_),a=e.scope_.immer_.shouldUseStrictIteration()}else n=fR(t,!0);return GT(n,(i,s)=>{EC(n,i,Lte(s))},a),e&&(e.finalized_=!1),n}var K3e=new W3e,Rte=K3e.produce;function Ite(t){return({dispatch:n,getState:a})=>i=>s=>typeof s=="function"?s(n,a,t):i(s)}var Q3e=Ite(),Y3e=Ite,X3e=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?AC:AC.apply(null,arguments)};function Nc(t,e){function n(...a){if(e){let i=e(...a);if(!i)throw new Error(kl(0));return{type:t,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:t,payload:a[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=a=>Cte(a)&&a.type===t,n}var Ote=class O0 extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,O0.prototype)}static get[Symbol.species](){return O0}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new O0(...e[0].concat(this)):new O0(...e.concat(this))}};function VG(t){return fd(t)?Rte(t,()=>{}):t}function E1(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function Z3e(t){return typeof t=="boolean"}var J3e=()=>function(e){const{thunk:n=!0,immutableCheck:a=!0,serializableCheck:i=!0,actionCreatorCheck:s=!0}=e??{};let o=new Ote;return n&&(Z3e(n)?o.push(Q3e):o.push(Y3e(n.extraArgument))),o},zte="RTK_autoBatch",Ra=()=>t=>({payload:t,meta:{[zte]:!0}}),GG=t=>e=>{setTimeout(e,t)},Ute=(t={type:"raf"})=>e=>(...n)=>{const a=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:GG(10):t.type==="callback"?t.queueNotification:GG(t.timeout),d=()=>{o=!1,s&&(s=!1,l.forEach(u=>u()))};return Object.assign({},a,{subscribe(u){const m=()=>i&&u(),p=a.subscribe(m);return l.add(u),()=>{p(),l.delete(u)}},dispatch(u){try{return i=!u?.meta?.[zte],s=!i,s&&(o||(o=!0,c(d))),a.dispatch(u)}finally{i=!0}}})},eFe=t=>function(n){const{autoBatch:a=!0}=n??{};let i=new Ote(t);return a&&i.push(Ute(typeof a=="object"?a:void 0)),i};function tFe(t){const e=J3e(),{reducer:n=void 0,middleware:a,devTools:i=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(w4(n))l=Nte(n);else throw new Error(kl(1));let c;typeof a=="function"?c=a(e):c=e();let d=AC;i&&(d=X3e({trace:!1,...typeof i=="object"&&i}));const u=F3e(...c),m=eFe(u);let p=typeof o=="function"?o(m):m();const f=d(...p);return kte(l,s,f)}function Bte(t){const e={},n=[];let a;const i={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(kl(28));if(l in e)throw new Error(kl(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 a=s,i}};return t(i),[e,n,a]}function nFe(t){return typeof t=="function"}function rFe(t,e){let[n,a,i]=Bte(e),s;if(nFe(t))s=()=>VG(t());else{const l=VG(t);s=()=>l}function o(l=s(),c){let d=[n[c.type],...a.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(Ym(u)){const f=m(u,c);return f===void 0?u:f}else{if(fd(u))return Rte(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 aFe="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",iFe=(t=21)=>{let e="",n=t;for(;n--;)e+=aFe[Math.random()*64|0];return e},sFe=Symbol.for("rtk-slice-createasyncthunk");function oFe(t,e){return`${t}/${e}`}function lFe({creators:t}={}){const e=t?.asyncThunk?.[sFe];return function(a){const{name:i,reducerPath:s=i}=a;if(!i)throw new Error(kl(11));const o=(typeof a.reducers=="function"?a.reducers(dFe()):a.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(k,C){const P=typeof k=="string"?k:k.type;if(!P)throw new Error(kl(12));if(P in c.sliceCaseReducersByType)throw new Error(kl(13));return c.sliceCaseReducersByType[P]=C,d},addMatcher(k,C){return c.sliceMatchers.push({matcher:k,reducer:C}),d},exposeAction(k,C){return c.actionCreators[k]=C,d},exposeCaseReducer(k,C){return c.sliceCaseReducersByName[k]=C,d}};l.forEach(k=>{const C=o[k],P={reducerName:k,type:oFe(i,k),createNotation:typeof a.reducers=="function"};mFe(C)?hFe(P,C,d,e):uFe(P,C,d)});function u(){const[k={},C=[],P=void 0]=typeof a.extraReducers=="function"?Bte(a.extraReducers):[a.extraReducers],T={...k,...c.sliceCaseReducersByType};return rFe(a.initialState,A=>{for(let F in T)A.addCase(F,T[F]);for(let F of c.sliceMatchers)A.addMatcher(F.matcher,F.reducer);for(let F of C)A.addMatcher(F.matcher,F.reducer);P&&A.addDefaultCase(P)})}const m=k=>k,p=new Map,f=new WeakMap;let g;function w(k,C){return g||(g=u()),g(k,C)}function b(){return g||(g=u()),g.getInitialState()}function x(k,C=!1){function P(A){let F=A[k];return typeof F>"u"&&C&&(F=E1(f,P,b)),F}function T(A=m){const F=E1(p,C,()=>new WeakMap);return E1(F,A,()=>{const _={};for(const[M,H]of Object.entries(a.selectors??{}))_[M]=cFe(H,A,()=>E1(f,A,b),C);return _})}return{reducerPath:k,getSelectors:T,get selectors(){return T(P)},selectSlice:P}}const S={name:i,reducer:w,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:b,...x(s),injectInto(k,{reducerPath:C,...P}={}){const T=C??s;return k.inject({reducerPath:T,reducer:w},P),{...S,...x(T,!0)}}};return S}}function cFe(t,e,n,a){function i(s,...o){let l=e(s);return typeof l>"u"&&a&&(l=n()),t(l,...o)}return i.unwrapped=t,i}var Jo=lFe();function dFe(){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 uFe({type:t,reducerName:e,createNotation:n},a,i){let s,o;if("reducer"in a){if(n&&!pFe(a))throw new Error(kl(17));s=a.reducer,o=a.prepare}else s=a;i.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?Nc(t,o):Nc(t))}function mFe(t){return t._reducerDefinitionType==="asyncThunk"}function pFe(t){return t._reducerDefinitionType==="reducerWithPrepare"}function hFe({type:t,reducerName:e},n,a,i){if(!i)throw new Error(kl(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:d,options:u}=n,m=i(t,s,u);a.exposeAction(e,m),o&&a.addCase(m.fulfilled,o),l&&a.addCase(m.pending,l),c&&a.addCase(m.rejected,c),d&&a.addMatcher(m.settled,d),a.exposeCaseReducer(e,{fulfilled:o||D1,pending:l||D1,rejected:c||D1,settled:d||D1})}function D1(){}var fFe="task",Hte="listener",qte="completed",N4="cancelled",gFe=`task-${N4}`,bFe=`task-${qte}`,wR=`${Hte}-${N4}`,xFe=`${Hte}-${qte}`,ZT=class{constructor(t){this.code=t,this.message=`${fFe} ${N4} (reason: ${t})`}name="TaskAbortError";message},C4=(t,e)=>{if(typeof t!="function")throw new TypeError(kl(32))},RC=()=>{},$te=(t,e=RC)=>(t.catch(e),t),Vte=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),xg=t=>{if(t.aborted)throw new ZT(t.reason)};function Gte(t,e){let n=RC;return new Promise((a,i)=>{const s=()=>i(new ZT(t.reason));if(t.aborted){s();return}n=Vte(t,s),e.finally(()=>n()).then(a,i)}).finally(()=>{n=RC})}var yFe=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof ZT?"cancelled":"rejected",error:n}}finally{e?.()}},IC=t=>e=>$te(Gte(t,e).then(n=>(xg(t),n))),Wte=t=>{const e=IC(t);return n=>e(new Promise(a=>setTimeout(a,n)))},{assign:cy}=Object,WG={},JT="listenerMiddleware",vFe=(t,e)=>{const n=a=>Vte(t,()=>a.abort(t.reason));return(a,i)=>{C4(a);const s=new AbortController;n(s);const o=yFe(async()=>{xg(t),xg(s.signal);const l=await a({pause:IC(s.signal),delay:Wte(s.signal),signal:s.signal});return xg(s.signal),l},()=>s.abort(bFe));return i?.autoJoin&&e.push(o.catch(RC)),{result:IC(t)(o),cancel(){s.abort(gFe)}}}},wFe=(t,e)=>{const n=async(a,i)=>{xg(e);let s=()=>{};const l=[new Promise((c,d)=>{let u=t({predicate:a,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 Gte(e,Promise.race(l));return xg(e),c}finally{s()}};return(a,i)=>$te(n(a,i))},Kte=t=>{let{type:e,actionCreator:n,matcher:a,predicate:i,effect:s}=t;if(e)i=Nc(e).match;else if(n)e=n.type,i=n.match;else if(a)i=a;else if(!i)throw new Error(kl(21));return C4(s),{predicate:i,type:e,effect:s}},Qte=cy(t=>{const{type:e,predicate:n,effect:a}=Kte(t);return{id:iFe(),effect:a,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(kl(22))}}},{withTypes:()=>Qte}),KG=(t,e)=>{const{type:n,effect:a,predicate:i}=Kte(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===i)&&s.effect===a)},SR=t=>{t.pending.forEach(e=>{e.abort(wR)})},SFe=(t,e)=>()=>{for(const n of e.keys())SR(n);t.clear()},QG=(t,e,n)=>{try{t(e,n)}catch(a){setTimeout(()=>{throw a},0)}},Yte=cy(Nc(`${JT}/add`),{withTypes:()=>Yte}),_Fe=Nc(`${JT}/removeAll`),Xte=cy(Nc(`${JT}/remove`),{withTypes:()=>Xte}),kFe=(...t)=>{console.error(`${JT}/error`,...t)},VS=(t={})=>{const e=new Map,n=new Map,a=f=>{const g=n.get(f)??0;n.set(f,g+1)},i=f=>{const g=n.get(f)??1;g===1?n.delete(f):n.set(f,g-1)},{extra:s,onError:o=kFe}=t;C4(o);const l=f=>(f.unsubscribe=()=>e.delete(f.id),e.set(f.id,f),g=>{f.unsubscribe(),g?.cancelActive&&SR(f)}),c=f=>{const g=KG(e,f)??Qte(f);return l(g)};cy(c,{withTypes:()=>c});const d=f=>{const g=KG(e,f);return g&&(g.unsubscribe(),f.cancelActive&&SR(g)),!!g};cy(d,{withTypes:()=>d});const u=async(f,g,w,b)=>{const x=new AbortController,S=wFe(c,x.signal),k=[];try{f.pending.add(x),a(f),await Promise.resolve(f.effect(g,cy({},w,{getOriginalState:b,condition:(C,P)=>S(C,P).then(Boolean),take:S,delay:Wte(x.signal),pause:IC(x.signal),extra:s,signal:x.signal,fork:vFe(x.signal,k),unsubscribe:f.unsubscribe,subscribe:()=>{e.set(f.id,f)},cancelActiveListeners:()=>{f.pending.forEach((C,P,T)=>{C!==x&&(C.abort(wR),T.delete(C))})},cancel:()=>{x.abort(wR),f.pending.delete(x)},throwIfCancelled:()=>{xg(x.signal)}})))}catch(C){C instanceof ZT||QG(o,C,{raisedBy:"effect"})}finally{await Promise.all(k),x.abort(xFe),i(f),f.pending.delete(x)}},m=SFe(e,n);return{middleware:f=>g=>w=>{if(!Cte(w))return g(w);if(Yte.match(w))return c(w.payload);if(_Fe.match(w)){m();return}if(Xte.match(w))return d(w.payload);let b=f.getState();const x=()=>{if(b===WG)throw new Error(kl(23));return b};let S;try{if(S=g(w),e.size>0){const k=f.getState(),C=Array.from(e.values());for(const P of C){let T=!1;try{T=P.predicate(w,k,b)}catch(A){T=!1,QG(o,A,{raisedBy:"predicate"})}T&&u(P,w,f,x)}}}finally{b=WG}return S},startListening:c,stopListening:d,clearListeners:m}};function kl(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 NFe={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},Zte=Jo({name:"chartLayout",initialState:NFe,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,a,i,s;t.margin.top=(n=e.payload.top)!==null&&n!==void 0?n:0,t.margin.right=(a=e.payload.right)!==null&&a!==void 0?a: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:CFe,setLayout:PFe,setChartSize:TFe,setScale:AFe}=Zte.actions,jFe=Zte.reducer;function Jte(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function Kn(t){return Number.isFinite(t)}function gu(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function YG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Yx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?YG(Object(n),!0).forEach(function(a){MFe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):YG(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}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 a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Gr(t,e,n){return Ua(t)||Ua(e)?n:kc(e)?Hg(t,e,n):typeof e=="function"?e(t):n}var FFe=(t,e,n)=>{if(e&&n){var{width:a,height:i}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&hn(t[s]))return Yx(Yx({},t),{},{[s]:t[s]+(a||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&hn(t[o]))return Yx(Yx({},t),{},{[o]:t[o]+(i||0)})}return t},vd=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",ene=(t,e,n,a)=>{if(a)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},tne=(t,e,n)=>{if(!t)return null;var{duplicateDomain:a,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 g=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,w=i==="category"&&o.bandwidth?o.bandwidth()/g:0;if(w=f==="angleAxis"&&s&&s.length>=2?us(s[0]-s[1])*2*w:w,m||p){var b=(m||p||[]).map((x,S)=>{var k=a?a.indexOf(x):x,C=o.map(k);return Kn(C)?{coordinate:C+w,value:x,offset:w,index:S}:null}).filter(Vo);return b}return c&&d?d.map((x,S)=>{var k=o.map(x);return Kn(k)?{coordinate:k+w,value:x,index:S,offset:w}:null}).filter(Vo):o.ticks&&u!=null?o.ticks(u).map((x,S)=>{var k=o.map(x);return Kn(k)?{coordinate:k+w,value:x,index:S,offset:w}:null}).filter(Vo):o.domain().map((x,S)=>{var k=o.map(x);return Kn(k)?{coordinate:k+w,value:a?a[x]:x,index:S,offset:w}:null}).filter(Vo)},LFe=(t,e)=>{if(!e||e.length!==2||!hn(e[0])||!hn(e[1]))return t;var n=Math.min(e[0],e[1]),a=Math.max(e[0],e[1]),i=[t[0],t[1]];return(!hn(t[0])||t[0]<n)&&(i[0]=n),(!hn(t[1])||t[1]>a)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]<n&&(i[1]=n),i},RFe=t=>{var e,n=t.length;if(!(n<=0)){var a=(e=t[0])===null||e===void 0?void 0:e.length;if(!(a==null||a<=0))for(var i=0;i<a;++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=hd(u)?m:u;p>=0?(d[0]=s,s+=p,d[1]=s):(d[0]=o,o+=p,d[1]=o)}}}},IFe=t=>{var e,n=t.length;if(!(n<=0)){var a=(e=t[0])===null||e===void 0?void 0:e.length;if(!(a==null||a<=0))for(var i=0;i<a;++i)for(var s=0,o=0;o<n;++o){var l=t[o],c=l?.[i];if(c!=null){var d=hd(c[1])?c[0]:c[1];d>=0?(c[0]=s,s+=d,c[1]=s):(c[0]=0,c[1]=0)}}}},OFe={sign:RFe,expand:oDe,none:Bg,silhouette:lDe,wiggle:cDe,positive:IFe},zFe=(t,e,n)=>{var a,i=(a=OFe[n])!==null&&a!==void 0?a:Bg,s=sDe().keys(e).value((l,c)=>Number(Gr(l,c,0))).order(uR).offset(i),o=s(t);return o.forEach((l,c)=>{l.forEach((d,u)=>{var m=Gr(t[u],e[c],0);Array.isArray(m)&&m.length===2&&hn(m[0])&&hn(m[1])&&(d[0]=m[0],d[1]=m[1])})}),o};function nne(t){return t==null?void 0:String(t)}function OC(t){var{axis:e,ticks:n,bandSize:a,entry:i,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!Ua(i[e.dataKey])){var l=ste(n,"value",i[e.dataKey]);if(l)return l.coordinate+a/2}return n!=null&&n[s]?n[s].coordinate+a/2:null}var c=Gr(i,Ua(o)?e.dataKey:o),d=e.scale.map(c);return hn(d)?d:null}var XG=t=>{var{axis:e,ticks:n,offset:a,bandSize:i,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+a:null;var l=Gr(s,e.dataKey,e.scale.domain()[o]);if(Ua(l))return null;var c=e.scale.map(l);return hn(c)?c-i/2+a:null},UFe=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var a=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return a<=0&&i>=0?0:i<0?i:a}return n[0]},BFe=t=>{var e=t.flat(2).filter(hn);return[Math.min(...e),Math.max(...e)]},HFe=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],qFe=(t,e,n)=>{if(t!=null)return HFe(Object.keys(t).reduce((a,i)=>{var s=t[i];if(!s)return a;var{stackedData:o}=s,l=o.reduce((c,d)=>{var u=Jte(d,e,n),m=BFe(u);return!Kn(m[0])||!Kn(m[1])?c:[Math.min(c[0],m[0]),Math.max(c[1],m[1])]},[1/0,-1/0]);return[Math.min(l[0],a[0]),Math.max(l[1],a[1])]},[1/0,-1/0]))},ZG=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,JG=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Xh=(t,e,n)=>{if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!n||a>0)return a}if(t&&e&&e.length>=2){for(var i=$T(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 e7(t){var{tooltipEntrySettings:e,dataKey:n,payload:a,value:i,name:s}=t;return Yx(Yx({},e),{},{dataKey:n,payload:a,value:i,name:s})}function sf(t,e){if(t)return String(t);if(typeof e=="string")return e}var $Fe=(t,e)=>{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},VFe=(t,e)=>e==="centric"?t.angle:t.radius,rp=t=>t.layout.width,ap=t=>t.layout.height,GFe=t=>t.layout.scale,rne=t=>t.layout.margin,eA=Pt(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),tA=Pt(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),ane="data-recharts-item-index",ine="data-recharts-item-id",GS=60;function t7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function F1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?t7(Object(n),!0).forEach(function(a){WFe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):t7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function WFe(t,e,n){return(e=KFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function KFe(t){var e=QFe(t,"string");return typeof e=="symbol"?e:e+""}function QFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var YFe=t=>t.brush.height;function XFe(t){var e=tA(t);return e.reduce((n,a)=>{if(a.orientation==="left"&&!a.mirror&&!a.hide){var i=typeof a.width=="number"?a.width:GS;return n+i}return n},0)}function ZFe(t){var e=tA(t);return e.reduce((n,a)=>{if(a.orientation==="right"&&!a.mirror&&!a.hide){var i=typeof a.width=="number"?a.width:GS;return n+i}return n},0)}function JFe(t){var e=eA(t);return e.reduce((n,a)=>a.orientation==="top"&&!a.mirror&&!a.hide?n+a.height:n,0)}function eLe(t){var e=eA(t);return e.reduce((n,a)=>a.orientation==="bottom"&&!a.mirror&&!a.hide?n+a.height:n,0)}var qi=Pt([rp,ap,rne,YFe,XFe,ZFe,JFe,eLe,Ste,P3e],(t,e,n,a,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=F1(F1({},m),u),f=p.bottom;p.bottom+=a,p=FFe(p,c,d);var g=t-p.left-p.right,w=e-p.top-p.bottom;return F1(F1({brushBottom:f},p),{},{width:Math.max(g,0),height:Math.max(w,0)})}),tLe=Pt(qi,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),P4=Pt(rp,ap,(t,e)=>({x:0,y:0,width:t,height:e})),nLe=y.createContext(null),$i=()=>y.useContext(nLe)!=null,nA=t=>t.brush,rA=Pt([nA,qi,rne],(t,e,n)=>({height:t.height,x:hn(t.x)?t.x:e.left,y:hn(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:hn(t.width)?t.width:e.width})),AD={},jD={},MD={},n7;function rLe(){return n7||(n7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,a,{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(),w()};let p=null;const f=()=>{p!=null&&clearTimeout(p),p=setTimeout(()=>{p=null,m()},a)},g=()=>{p!==null&&(clearTimeout(p),p=null)},w=()=>{g(),o=void 0,l=null},b=()=>{u()},x=function(...S){if(i?.aborted)return;o=this,l=S;const k=p==null;f(),c&&k&&u()};return x.schedule=f,x.cancel=w,x.flush=b,i?.addEventListener("abort",w,{once:!0}),x}t.debounce=e})(MD)),MD}var r7;function aLe(){return r7||(r7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=rLe();function n(a,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(...w){u=a.apply(this,w),m=null},i,{edges:d}),f=function(...w){return c!=null&&(m===null&&(m=Date.now()),Date.now()-m>=c)?(u=a.apply(this,w),m=Date.now(),p.cancel(),p.schedule(),u):(p.apply(this,w),u)},g=()=>(p.flush(),u);return f.cancel=p.cancel,f.flush=g,f}t.debounce=n})(jD)),jD}var a7;function iLe(){return a7||(a7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aLe();function n(a,i=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(a,i,{leading:o,maxWait:i,trailing:l})}t.throttle=n})(AD)),AD}var ED,i7;function sLe(){return i7||(i7=1,ED=iLe().throttle),ED}var oLe=sLe();const lLe=Tc(oLe);var zC=function(e,n){for(var a=arguments.length,i=new Array(a>2?a-2:0),s=2;s<a;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++]))}},tu={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},sne=(t,e,n)=>{var{width:a=tu.width,height:i=tu.height,aspect:s,maxHeight:o}=n,l=qg(a)?t:Number(a),c=qg(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}},cLe={width:0,height:0,overflow:"visible"},dLe={width:0,overflowX:"visible"},uLe={height:0,overflowY:"visible"},mLe={},pLe=t=>{var{width:e,height:n}=t,a=qg(e),i=qg(n);return a&&i?cLe:a?dLe:i?uLe:mLe};function hLe(t){var{width:e,height:n,aspect:a}=t,i=e,s=n;return i===void 0&&s===void 0?(i=tu.width,s=tu.height):i===void 0?i=a&&a>0?void 0:tu.width:s===void 0&&(s=a&&a>0?void 0:tu.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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},_R.apply(null,arguments)}function s7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function o7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?s7(Object(n),!0).forEach(function(a){fLe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):s7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function fLe(t,e,n){return(e=gLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gLe(t){var e=bLe(t,"string");return typeof e=="symbol"?e:e+""}function bLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var one=y.createContext(tu.initialDimension);function xLe(t){return gu(t.width)&&gu(t.height)}function lne(t){var{children:e,width:n,height:a}=t,i=y.useMemo(()=>({width:n,height:a}),[n,a]);return xLe(i)?y.createElement(one.Provider,{value:i},e):null}var T4=()=>y.useContext(one),yLe=y.forwardRef((t,e)=>{var{aspect:n,initialDimension:a=tu.initialDimension,width:i,height:s,minWidth:o=tu.minWidth,minHeight:l,maxHeight:c,children:d,debounce:u=tu.debounce,id:m,className:p,onResize:f,style:g={}}=t,w=y.useRef(null),b=y.useRef();b.current=f,y.useImperativeHandle(e,()=>w.current);var[x,S]=y.useState({containerWidth:a.width,containerHeight:a.height}),k=y.useCallback((F,_)=>{S(M=>{var H=Math.round(F),I=Math.round(_);return M.containerWidth===H&&M.containerHeight===I?M:{containerWidth:H,containerHeight:I}})},[]);y.useEffect(()=>{if(w.current==null||typeof ResizeObserver>"u")return af;var F=I=>{var z,L=I[0];if(L!=null){var{width:Z,height:ne}=L.contentRect;k(Z,ne),(z=b.current)===null||z===void 0||z.call(b,Z,ne)}};u>0&&(F=lLe(F,u,{trailing:!0,leading:!1}));var _=new ResizeObserver(F),{width:M,height:H}=w.current.getBoundingClientRect();return k(M,H),_.observe(w.current),()=>{_.disconnect()}},[k,u]);var{containerWidth:C,containerHeight:P}=x;zC(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:T,calculatedHeight:A}=sne(C,P,{width:i,height:s,aspect:n,maxHeight:c});return zC(T!=null&&T>0||A!=null&&A>0,`The width(%s) and height(%s) of chart should be greater than 0,
  8095. please check the style of container, or the props width(%s) and height(%s),
  8096. or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
  8097. height and width.`,T,A,i,s,o,l,n),y.createElement("div",{id:m?"".concat(m):void 0,className:Er("recharts-responsive-container",p),style:o7(o7({},g),{},{width:i,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:w},y.createElement("div",{style:pLe({width:i,height:s})},y.createElement(lne,{width:T,height:A},d)))}),nu=y.forwardRef((t,e)=>{var n=T4();if(gu(n.width)&&gu(n.height))return t.children;var{width:a,height:i}=hLe({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=sne(void 0,void 0,{width:a,height:i,aspect:t.aspect,maxHeight:t.maxHeight});return hn(s)&&hn(o)?y.createElement(lne,{width:s,height:o},t.children):y.createElement(yLe,_R({},t,{width:a,height:i,ref:e}))});function A4(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 WS=()=>{var t,e=$i(),n=bn(tLe),a=bn(rA),i=(t=bn(nA))===null||t===void 0?void 0:t.padding;return!e||!a||!i?n:{width:a.width-i.left-i.right,height:a.height-i.top-i.bottom,x:i.left,y:i.top}},vLe={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},cne=()=>{var t;return(t=bn(qi))!==null&&t!==void 0?t:vLe},j4=()=>bn(rp),M4=()=>bn(ap),wLe=()=>bn(t=>t.layout.margin),jr=t=>t.layout.layoutType,of=()=>bn(jr),E4=()=>{var t=of();if(t==="horizontal"||t==="vertical")return t},dne=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},SLe=()=>{var t=of();return t!==void 0},KS=t=>{var e=ga(),n=$i(),{width:a,height:i}=t,s=T4(),o=a,l=i;return s&&(o=s.width>0?s.width:a,l=s.height>0?s.height:i),y.useEffect(()=>{!n&&gu(o)&&gu(l)&&e(TFe({width:o,height:l}))},[e,n,o,l]),null},une=Symbol.for("immer-nothing"),l7=Symbol.for("immer-draftable"),Al=Symbol.for("immer-state");function id(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Yw=Object.getPrototypeOf;function Ay(t){return!!t&&!!t[Al]}function Vg(t){return t?mne(t)||Array.isArray(t)||!!t[l7]||!!t.constructor?.[l7]||QS(t)||iA(t):!1}var _Le=Object.prototype.constructor.toString(),c7=new WeakMap;function mne(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 a=c7.get(n);return a===void 0&&(a=Function.toString.call(n),c7.set(n,a)),a===_Le}function UC(t,e,n=!0){aA(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(i=>{e(i,t[i],t)}):t.forEach((a,i)=>e(i,a,t))}function aA(t){const e=t[Al];return e?e.type_:Array.isArray(t)?1:QS(t)?2:iA(t)?3:0}function kR(t,e){return aA(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function pne(t,e,n){const a=aA(t);a===2?t.set(e,n):a===3?t.add(n):t[e]=n}function kLe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function QS(t){return t instanceof Map}function iA(t){return t instanceof Set}function Yf(t){return t.copy_||t.base_}function NR(t,e){if(QS(t))return new Map(t);if(iA(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=mne(t);if(e===!0||e==="class_only"&&!n){const a=Object.getOwnPropertyDescriptors(t);delete a[Al];let i=Reflect.ownKeys(a);for(let s=0;s<i.length;s++){const o=i[s],l=a[o];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(a[o]={configurable:!0,writable:!0,enumerable:l.enumerable,value:t[o]})}return Object.create(Yw(t),a)}else{const a=Yw(t);if(a!==null&&n)return{...t};const i=Object.create(a);return Object.assign(i,t)}}function D4(t,e=!1){return sA(t)||Ay(t)||!Vg(t)||(aA(t)>1&&Object.defineProperties(t,{set:L1,add:L1,clear:L1,delete:L1}),Object.freeze(t),e&&Object.values(t).forEach(n=>D4(n,!0))),t}function NLe(){id(2)}var L1={value:NLe};function sA(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var CLe={};function Gg(t){const e=CLe[t];return e||id(0,t),e}var Xw;function hne(){return Xw}function PLe(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function d7(t,e){e&&(Gg("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function CR(t){PR(t),t.drafts_.forEach(TLe),t.drafts_=null}function PR(t){t===Xw&&(Xw=t.parent_)}function u7(t){return Xw=PLe(Xw,t)}function TLe(t){const e=t[Al];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function m7(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[Al].modified_&&(CR(e),id(4)),Vg(t)&&(t=BC(e,t),e.parent_||HC(e,t)),e.patches_&&Gg("Patches").generateReplacementPatches_(n[Al].base_,t,e.patches_,e.inversePatches_)):t=BC(e,n,[]),CR(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==une?t:void 0}function BC(t,e,n){if(sA(e))return e;const a=t.immer_.shouldUseStrictIteration(),i=e[Al];if(!i)return UC(e,(s,o)=>p7(t,i,e,s,o,n),a),e;if(i.scope_!==t)return e;if(!i.modified_)return HC(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),UC(o,(c,d)=>p7(t,i,s,c,d,n,l),a),HC(t,s,!1),n&&t.patches_&&Gg("Patches").generatePatches_(i,n,t.patches_,t.inversePatches_)}return i.copy_}function p7(t,e,n,a,i,s,o){if(i==null||typeof i!="object"&&!o)return;const l=sA(i);if(!(l&&!o)){if(Ay(i)){const c=s&&e&&e.type_!==3&&!kR(e.assigned_,a)?s.concat(a):void 0,d=BC(t,i,c);if(pne(n,a,d),Ay(d))t.canAutoFreeze_=!1;else return}else o&&n.add(i);if(Vg(i)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[a]===i&&l)return;BC(t,i),(!e||!e.scope_.parent_)&&typeof a!="symbol"&&(QS(n)?n.has(a):Object.prototype.propertyIsEnumerable.call(n,a))&&HC(t,i)}}}function HC(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&D4(e,n)}function ALe(t,e){const n=Array.isArray(t),a={type_:n?1:0,scope_:e?e.scope_:hne(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=a,s=F4;n&&(i=[a],s=Zw);const{revoke:o,proxy:l}=Proxy.revocable(i,s);return a.draft_=l,a.revoke_=o,l}var F4={get(t,e){if(e===Al)return t;const n=Yf(t);if(!kR(n,e))return jLe(t,n,e);const a=n[e];return t.finalized_||!Vg(a)?a:a===DD(t.base_,e)?(FD(t),t.copy_[e]=AR(a,t)):a},has(t,e){return e in Yf(t)},ownKeys(t){return Reflect.ownKeys(Yf(t))},set(t,e,n){const a=fne(Yf(t),e);if(a?.set)return a.set.call(t.draft_,n),!0;if(!t.modified_){const i=DD(Yf(t),e),s=i?.[Al];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if(kLe(n,i)&&(n!==void 0||kR(t.base_,e)))return!0;FD(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 DD(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,FD(t),TR(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Yf(t),a=Reflect.getOwnPropertyDescriptor(n,e);return a&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:a.enumerable,value:n[e]}},defineProperty(){id(11)},getPrototypeOf(t){return Yw(t.base_)},setPrototypeOf(){id(12)}},Zw={};UC(F4,(t,e)=>{Zw[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Zw.deleteProperty=function(t,e){return Zw.set.call(this,t,e,void 0)};Zw.set=function(t,e,n){return F4.set.call(this,t[0],e,n,t[0])};function DD(t,e){const n=t[Al];return(n?Yf(n):t)[e]}function jLe(t,e,n){const a=fne(e,n);return a?"value"in a?a.value:a.get?.call(t.draft_):void 0}function fne(t,e){if(!(e in t))return;let n=Yw(t);for(;n;){const a=Object.getOwnPropertyDescriptor(n,e);if(a)return a;n=Yw(n)}}function TR(t){t.modified_||(t.modified_=!0,t.parent_&&TR(t.parent_))}function FD(t){t.copy_||(t.copy_=NR(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var MLe=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,n,a)=>{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"&&id(6),a!==void 0&&typeof a!="function"&&id(7);let i;if(Vg(e)){const s=u7(this),o=AR(e,void 0);let l=!0;try{i=n(o),l=!1}finally{l?CR(s):PR(s)}return d7(s,a),m7(i,s)}else if(!e||typeof e!="object"){if(i=n(e),i===void 0&&(i=e),i===une&&(i=void 0),this.autoFreeze_&&D4(i,!0),a){const s=[],o=[];Gg("Patches").generateReplacementPatches_(e,i,s,o),a(s,o)}return i}else id(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let a,i;return[this.produce(e,n,(o,l)=>{a=o,i=l}),a,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){Vg(t)||id(8),Ay(t)&&(t=ELe(t));const e=u7(this),n=AR(t,void 0);return n[Al].isManual_=!0,PR(e),n}finishDraft(t,e){const n=t&&t[Al];(!n||!n.isManual_)&&id(9);const{scope_:a}=n;return d7(a,e),m7(void 0,a)}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 a=Gg("Patches").applyPatches_;return Ay(t)?a(t,e):this.produce(t,i=>a(i,e))}};function AR(t,e){const n=QS(t)?Gg("MapSet").proxyMap_(t,e):iA(t)?Gg("MapSet").proxySet_(t,e):ALe(t,e);return(e?e.scope_:hne()).drafts_.push(n),n}function ELe(t){return Ay(t)||id(10,t),gne(t)}function gne(t){if(!Vg(t)||sA(t))return t;const e=t[Al];let n,a=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=NR(t,e.scope_.immer_.useStrictShallowCopy_),a=e.scope_.immer_.shouldUseStrictIteration()}else n=NR(t,!0);return UC(n,(i,s)=>{pne(n,i,gne(s))},a),e&&(e.finalized_=!1),n}var DLe=new MLe;DLe.produce;var FLe={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},bne=Jo({name:"legend",initialState:FLe,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:Ra()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:a}=e.payload,i=ud(t).payload.indexOf(n);i>-1&&(t.payload[i]=a)},prepare:Ra()},removeLegendPayload:{reducer(t,e){var n=ud(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:Ra()}}}),{setLegendSize:h7,setLegendSettings:LLe,addLegendPayload:xne,replaceLegendPayload:yne,removeLegendPayload:vne}=bne.actions,RLe=bne.reducer,ILe=["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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},jR.apply(null,arguments)}function f7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function jy(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?f7(Object(n),!0).forEach(function(a){OLe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):f7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function OLe(t,e,n){return(e=zLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function zLe(t){var e=ULe(t,"string");return typeof e=="symbol"?e:e+""}function ULe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function BLe(t,e){if(t==null)return{};var n,a,i=HLe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function HLe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function qLe(t){return t.value}function $Le(t){var{contextPayload:e}=t,n=BLe(t,ILe),a=bte(e,t.payloadUniqBy,qLe),i=jy(jy({},n),{},{payload:a});return y.isValidElement(t.content)?y.cloneElement(t.content,i):typeof t.content=="function"?y.createElement(t.content,i):y.createElement(ODe,i)}function VLe(t,e,n,a,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:((a||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}),jy(jy({},d),u)}function GLe(t){var e=ga();return y.useEffect(()=>{e(LLe(t))},[e,t]),null}function WLe(t){var e=ga();return y.useEffect(()=>(e(h7(t)),()=>{e(h7({width:0,height:0}))}),[e,t]),null}function KLe(t,e,n,a){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||a}:null}var QLe={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function L4(t){var e=Va(t,QLe),n=j3e(),a=j2e(),i=wLe(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[d,u]=_te([n]),m=j4(),p=M4();if(m==null||p==null)return null;var f=m-(i?.left||0)-(i?.right||0),g=KLe(e.layout,o,s,f),w=c?l:jy(jy({position:"absolute",width:g?.width||s||"auto",height:g?.height||o||"auto"},VLe(l,e,i,m,p,d)),l),b=c??a;if(b==null||n==null)return null;var x=y.createElement("div",{className:"recharts-legend-wrapper",style:w,ref:u},y.createElement(GLe,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&y.createElement(WLe,{width:d.width,height:d.height}),y.createElement($Le,jR({},e,g,{margin:i,chartWidth:m,chartHeight:p,contextPayload:n})));return cc.createPortal(x,b)}L4.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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},MR.apply(null,arguments)}function g7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function h0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?g7(Object(n),!0).forEach(function(a){YLe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):g7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function YLe(t,e,n){return(e=XLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function XLe(t){var e=ZLe(t,"string");return typeof e=="symbol"?e:e+""}function ZLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function JLe(t){return Array.isArray(t)&&kc(t[0])&&kc(t[1])?t.join(" ~ "):t}var Ax={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},eRe=t=>{var{separator:e=Ax.separator,contentStyle:n,itemStyle:a,labelStyle:i=Ax.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:d,label:u,labelFormatter:m,accessibilityLayer:p=Ax.accessibilityLayer}=t,f=()=>{if(s&&s.length){var P={padding:0,margin:0},T=(l?$T(s,l):s).map((A,F)=>{if(A.type==="none")return null;var _=A.formatter||o||JLe,{value:M,name:H}=A,I=M,z=H;if(_){var L=_(M,H,A,F,s);if(Array.isArray(L))[I,z]=L;else if(L!=null)I=L;else return null}var Z=h0(h0({},Ax.itemStyle),{},{color:A.color||Ax.itemStyle.color},a);return y.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(F),style:Z},kc(z)?y.createElement("span",{className:"recharts-tooltip-item-name"},z):null,kc(z)?y.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,y.createElement("span",{className:"recharts-tooltip-item-value"},I),y.createElement("span",{className:"recharts-tooltip-item-unit"},A.unit||""))});return y.createElement("ul",{className:"recharts-tooltip-item-list",style:P},T)}return null},g=h0(h0({},Ax.contentStyle),n),w=h0({margin:0},i),b=!Ua(u),x=b?u:"",S=Er("recharts-default-tooltip",c),k=Er("recharts-tooltip-label",d);b&&m&&s!==void 0&&s!==null&&(x=m(u,s));var C=p?{role:"status","aria-live":"assertive"}:{};return y.createElement("div",MR({className:S,style:g},C),y.createElement("p",{className:k,style:w},y.isValidElement(x)?x:"".concat(x)),f())},f0="recharts-tooltip-wrapper",tRe={visibility:"hidden"};function nRe(t){var{coordinate:e,translateX:n,translateY:a}=t;return Er(f0,{["".concat(f0,"-right")]:hn(n)&&e&&hn(e.x)&&n>=e.x,["".concat(f0,"-left")]:hn(n)&&e&&hn(e.x)&&n<e.x,["".concat(f0,"-bottom")]:hn(a)&&e&&hn(e.y)&&a>=e.y,["".concat(f0,"-top")]:hn(a)&&e&&hn(e.y)&&a<e.y})}function b7(t){var{allowEscapeViewBox:e,coordinate:n,key:a,offset:i,position:s,reverseDirection:o,tooltipDimension:l,viewBox:c,viewBoxDimension:d}=t;if(s&&hn(s[a]))return s[a];var u=n[a]-l-(i>0?i:0),m=n[a]+i;if(e[a])return o[a]?u:m;var p=c[a];if(p==null)return 0;if(o[a]){var f=u,g=p;return f<g?Math.max(m,p):Math.max(u,p)}if(d==null)return 0;var w=m+l,b=p+d;return w>b?Math.max(u,p):Math.max(m,p)}function rRe(t){var{translateX:e,translateY:n,useTranslate3d:a}=t;return{transform:a?"translate3d(".concat(e,"px, ").concat(n,"px, 0)"):"translate(".concat(e,"px, ").concat(n,"px)")}}function aRe(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:a,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=b7({allowEscapeViewBox:e,coordinate:n,key:"x",offset:i,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:d,viewBoxDimension:d.width}),p=b7({allowEscapeViewBox:e,coordinate:n,key:"y",offset:a,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:d,viewBoxDimension:d.height}),u=rRe({translateX:m,translateY:p,useTranslate3d:c})):u=tRe,{cssProperties:u,cssClasses:nRe({translateX:m,translateY:p,coordinate:n})}}function x7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function R1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?x7(Object(n),!0).forEach(function(a){ER(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):x7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function ER(t,e,n){return(e=iRe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function iRe(t){var e=sRe(t,"string");return typeof e=="symbol"?e:e+""}function sRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class oRe extends y.PureComponent{constructor(){super(...arguments),ER(this,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0}}),ER(this,"handleKeyDown",e=>{if(e.key==="Escape"){var n,a,i,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(n=(a=this.props.coordinate)===null||a===void 0?void 0:a.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:a,animationEasing:i,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:d,position:u,reverseDirection:m,useTranslate3d:p,viewBox:f,wrapperStyle:g,lastBoundingBox:w,innerRef:b,hasPortalFromProps:x}=this.props,S=typeof d=="number"?d:d.x,k=typeof d=="number"?d:d.y,{cssClasses:C,cssProperties:P}=aRe({allowEscapeViewBox:n,coordinate:o,offsetLeft:S,offsetTop:k,position:u,reverseDirection:m,tooltipBox:{height:w.height,width:w.width},useTranslate3d:p,viewBox:f}),T=x?{}:R1(R1({transition:c&&e?"transform ".concat(a,"ms ").concat(i):void 0},P),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),A=R1(R1({},T),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},g);return y.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:C,style:A,ref:b},s)}}var wne=()=>{var t;return(t=bn(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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},DR.apply(null,arguments)}function y7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function v7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?y7(Object(n),!0).forEach(function(a){lRe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):y7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function lRe(t,e,n){return(e=cRe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function cRe(t){var e=dRe(t,"string");return typeof e=="symbol"?e:e+""}function dRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var w7={curveBasisClosed:Q2e,curveBasisOpen:Y2e,curveBasis:K2e,curveBumpX:F2e,curveBumpY:L2e,curveLinearClosed:X2e,curveLinear:HT,curveMonotoneX:Z2e,curveMonotoneY:J2e,curveNatural:eDe,curveStep:tDe,curveStepAfter:rDe,curveStepBefore:nDe},qC=t=>Kn(t.x)&&Kn(t.y),S7=t=>t.base!=null&&qC(t.base)&&qC(t),g0=t=>t.x,b0=t=>t.y,uRe=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(HS(t));if((n==="curveMonotone"||n==="curveBump")&&e){var a=w7["".concat(n).concat(e==="vertical"?"Y":"X")];if(a)return a}return w7[n]||HT},_7={connectNulls:!1,type:"linear"},mRe=t=>{var{type:e=_7.type,points:n=[],baseLine:a,layout:i,connectNulls:s=_7.connectNulls}=t,o=uRe(e,i),l=s?n.filter(qC):n;if(Array.isArray(a)){var c,d=n.map((g,w)=>v7(v7({},g),{},{base:a[w]}));i==="vertical"?c=T1().y(b0).x1(g0).x0(g=>g.base.x):c=T1().x(g0).y1(b0).y0(g=>g.base.y);var u=c.defined(S7).curve(o),m=s?d.filter(S7):d;return u(m)}var p;i==="vertical"&&hn(a)?p=T1().y(b0).x1(g0).x0(a):hn(a)?p=T1().x(g0).y1(b0).y0(a):p=Wee().x(g0).y(b0);var f=p.defined(qC).curve(o);return f(l)},dy=t=>{var{className:e,points:n,path:a,pathRef:i}=t,s=of();if((!n||!n.length)&&!a)return null;var o={type:t.type,points:t.points,baseLine:t.baseLine,layout:t.layout||s,connectNulls:t.connectNulls},l=n&&n.length?mRe(o):a;return y.createElement("path",DR({},_o(t),b4(t),{className:Er("recharts-curve",e),d:l===null?void 0:l,ref:i}))},pRe=["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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},FR.apply(null,arguments)}function k7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function hRe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?k7(Object(n),!0).forEach(function(a){fRe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):k7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function fRe(t,e,n){return(e=gRe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gRe(t){var e=bRe(t,"string");return typeof e=="symbol"?e:e+""}function bRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xRe(t,e){if(t==null)return{};var n,a,i=yRe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function yRe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var vRe=(t,e,n,a,i,s)=>"M".concat(t,",").concat(i,"v").concat(a,"M").concat(s,",").concat(e,"h").concat(n),wRe=t=>{var{x:e=0,y:n=0,top:a=0,left:i=0,width:s=0,height:o=0,className:l}=t,c=xRe(t,pRe),d=hRe({x:e,y:n,top:a,left:i,width:s,height:o},c);return!hn(e)||!hn(n)||!hn(s)||!hn(o)||!hn(a)||!hn(i)?null:y.createElement("path",FR({},Os(d),{className:Er("recharts-cross",l),d:vRe(e,n,s,o,a,i)}))};function SRe(t,e,n,a){var i=a/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"?a:n.width-1,height:t==="horizontal"?n.height-1:a}}function N7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function C7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?N7(Object(n),!0).forEach(function(a){_Re(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):N7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function _Re(t,e,n){return(e=kRe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function kRe(t){var e=NRe(t,"string");return typeof e=="symbol"?e:e+""}function NRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var CRe=t=>t.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),Sne=(t,e,n)=>t.map(a=>"".concat(CRe(a)," ").concat(e,"ms ").concat(n)).join(","),PRe=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,a)=>n.filter(i=>a.includes(i))),Jw=(t,e)=>Object.keys(e).reduce((n,a)=>C7(C7({},n),{},{[a]:t(a,e[a])}),{});function P7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Ii(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?P7(Object(n),!0).forEach(function(a){TRe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):P7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function TRe(t,e,n){return(e=ARe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ARe(t){var e=jRe(t,"string");return typeof e=="symbol"?e:e+""}function jRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var $C=(t,e,n)=>t+(e-t)*n,LR=t=>{var{from:e,to:n}=t;return e!==n},_ne=(t,e,n)=>{var a=Jw((i,s)=>{if(LR(s)){var[o,l]=t(s.from,s.to,s.velocity);return Ii(Ii({},s),{},{from:o,velocity:l})}return s},e);return n<1?Jw((i,s)=>LR(s)&&a[i]!=null?Ii(Ii({},s),{},{velocity:$C(s.velocity,a[i].velocity,n),from:$C(s.from,a[i].from,n)}):s,e):_ne(t,a,n-1)};function MRe(t,e,n,a,i,s){var o,l=a.reduce((p,f)=>Ii(Ii({},p),{},{[f]:{from:t[f],velocity:0,to:e[f]}}),{}),c=()=>Jw((p,f)=>f.from,l),d=()=>!Object.values(l).filter(LR).length,u=null,m=p=>{o||(o=p);var f=p-o,g=f/n.dt;l=_ne(n,l,g),i(Ii(Ii(Ii({},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 ERe(t,e,n,a,i,s,o){var l=null,c=i.reduce((m,p)=>{var f=t[p],g=e[p];return f==null||g==null?m:Ii(Ii({},m),{},{[p]:[f,g]})},{}),d,u=m=>{d||(d=m);var p=(m-d)/a,f=Jw((w,b)=>$C(...b,n(p)),c);if(s(Ii(Ii(Ii({},t),e),f)),p<1)l=o.setTimeout(u);else{var g=Jw((w,b)=>$C(...b,n(1)),c);s(Ii(Ii(Ii({},t),e),g))}};return()=>(l=o.setTimeout(u),()=>{var m;(m=l)===null||m===void 0||m()})}const DRe=(t,e,n,a,i,s)=>{var o=PRe(t,e);return n==null?()=>(i(Ii(Ii({},t),e)),()=>{}):n.isStepper===!0?MRe(t,e,n,o,i,s):ERe(t,e,n,a,o,i,s)};var VC=1e-4,kne=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],Nne=(t,e)=>t.map((n,a)=>n*e**a).reduce((n,a)=>n+a),T7=(t,e)=>n=>{var a=kne(t,e);return Nne(a,n)},FRe=(t,e)=>n=>{var a=kne(t,e),i=[...a.map((s,o)=>s*o).slice(1),0];return Nne(i,n)},LRe=t=>{var e,n=t.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var a=(e=n[1])===null||e===void 0||(e=e.split(")")[0])===null||e===void 0?void 0:e.split(",");if(a==null||a.length!==4)return null;var i=a.map(s=>parseFloat(s));return[i[0],i[1],i[2],i[3]]},RRe=function(){for(var e=arguments.length,n=new Array(e),a=0;a<e;a++)n[a]=arguments[a];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=LRe(n[0]);if(i)return i}}return n.length===4?n:[0,0,1,1]},IRe=(t,e,n,a)=>{var i=T7(t,n),s=T7(e,a),o=FRe(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,g=o(m);if(Math.abs(f-u)<VC||g<VC)return s(m);m=l(m-f/g)}return s(m)};return c.isStepper=!1,c},A7=function(){return IRe(...RRe(...arguments))},ORe=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:a=8,dt:i=17}=e,s=(o,l,c)=>{var d=-(o-l)*n,u=c*a,m=c+(d-u)*i/1e3,p=c*i/1e3+o;return Math.abs(p-l)<VC&&Math.abs(m)<VC?[l,0]:[p,m]};return s.isStepper=!0,s.dt=i,s},zRe=t=>{if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return A7(t);case"spring":return ORe();default:if(t.split("(")[0]==="cubic-bezier")return A7(t)}return typeof t=="function"?t:null};function URe(t){var e,n=()=>null,a=!1,i=null,s=o=>{if(!a){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:()=>{a=!0},start:o=>{a=!1,i&&(i(),i=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class BRe{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=performance.now(),i=null,s=o=>{o-a>=n?e(o):typeof requestAnimationFrame=="function"&&(i=requestAnimationFrame(s))};return i=requestAnimationFrame(s),()=>{i!=null&&cancelAnimationFrame(i)}}}function HRe(){return URe(new BRe)}var qRe=y.createContext(HRe);function $Re(t,e){var n=y.useContext(qRe);return y.useMemo(()=>e??n(t),[t,e,n])}var VRe=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),YS={isSsr:VRe()},GRe={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},j7={t:0},LD={t:1};function tv(t){var e=Va(t,GRe),{isActive:n,canBegin:a,duration:i,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:d}=e,u=n==="auto"?!YS.isSsr:n,m=$Re(e.animationId,e.animationManager),[p,f]=y.useState(u?j7:LD),g=y.useRef(null);return y.useEffect(()=>{u||f(LD)},[u]),y.useEffect(()=>{if(!u||!a)return af;var w=DRe(j7,LD,zRe(s),i,f,m.getTimeoutController()),b=()=>{g.current=w()};return m.start([c,o,b,i,l]),()=>{m.stop(),g.current&&g.current(),l()}},[u,a,i,s,o,c,l,m]),d(p.t)}function nv(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=y.useRef(Gw(e)),a=y.useRef(t);return a.current!==t&&(n.current=Gw(e),a.current=t),n.current}var WRe=["radius"],KRe=["radius"],M7,E7,D7,F7,L7,R7,I7,O7,z7,U7;function B7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function H7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?B7(Object(n),!0).forEach(function(a){QRe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):B7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function QRe(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=XRe(t,"string");return typeof e=="symbol"?e:e+""}function XRe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},GC.apply(null,arguments)}function q7(t,e){if(t==null)return{};var n,a,i=ZRe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function ZRe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function Od(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var $7=(t,e,n,a,i)=>{var s=wh(n),o=wh(a),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,g=4;f<g;f++){var w,b=(w=i[f])!==null&&w!==void 0?w:0;p[f]=b>l?l:b}m=ti(M7||(M7=Od(["M",",",""])),t,e+c*p[0]),p[0]>0&&(m+=ti(E7||(E7=Od(["A ",",",",0,0,",",",",",""])),p[0],p[0],u,t+d*p[0],e)),m+=ti(D7||(D7=Od(["L ",",",""])),t+n-d*p[1],e),p[1]>0&&(m+=ti(F7||(F7=Od(["A ",",",",0,0,",`,
  8098. `,",",""])),p[1],p[1],u,t+n,e+c*p[1])),m+=ti(L7||(L7=Od(["L ",",",""])),t+n,e+a-c*p[2]),p[2]>0&&(m+=ti(R7||(R7=Od(["A ",",",",0,0,",`,
  8099. `,",",""])),p[2],p[2],u,t+n-d*p[2],e+a)),m+=ti(I7||(I7=Od(["L ",",",""])),t+d*p[3],e+a),p[3]>0&&(m+=ti(O7||(O7=Od(["A ",",",",0,0,",`,
  8100. `,",",""])),p[3],p[3],u,t,e+a-c*p[3])),m+="Z"}else if(l>0&&i===+i&&i>0){var x=Math.min(l,i);m=ti(z7||(z7=Od(["M ",",",`
  8101. A `,",",",0,0,",",",",",`
  8102. L `,",",`
  8103. A `,",",",0,0,",",",",",`
  8104. L `,",",`
  8105. A `,",",",0,0,",",",",",`
  8106. L `,",",`
  8107. A `,",",",0,0,",",",","," Z"])),t,e+c*x,x,x,u,t+d*x,e,t+n-d*x,e,x,x,u,t+n,e+c*x,t+n,e+a-c*x,x,x,u,t+n-d*x,e+a,t+d*x,e+a,x,x,u,t,e+a-c*x)}else m=ti(U7||(U7=Od(["M ",","," h "," v "," h "," Z"])),t,e,n,a,-n);return m},V7={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Cne=t=>{var e=Va(t,V7),n=y.useRef(null),[a,i]=y.useState(-1);y.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var Y=n.current.getTotalLength();Y&&i(Y)}catch{}},[]);var{x:s,y:o,width:l,height:c,radius:d,className:u}=e,{animationEasing:m,animationDuration:p,animationBegin:f,isAnimationActive:g,isUpdateAnimationActive:w}=e,b=y.useRef(l),x=y.useRef(c),S=y.useRef(s),k=y.useRef(o),C=y.useMemo(()=>({x:s,y:o,width:l,height:c,radius:d}),[s,o,l,c,d]),P=nv(C,"rectangle-");if(s!==+s||o!==+o||l!==+l||c!==+c||l===0||c===0)return null;var T=Er("recharts-rectangle",u);if(!w){var A=Os(e),{radius:F}=A,_=q7(A,WRe);return y.createElement("path",GC({},_,{x:wh(s),y:wh(o),width:wh(l),height:wh(c),radius:typeof d=="number"?d:void 0,className:T,d:$7(s,o,l,c,d)}))}var M=b.current,H=x.current,I=S.current,z=k.current,L="0px ".concat(a===-1?1:a,"px"),Z="".concat(a,"px 0px"),ne=Sne(["strokeDasharray"],p,typeof m=="string"?m:V7.animationEasing);return y.createElement(tv,{animationId:P,key:P,canBegin:a>0,duration:p,easing:m,isActive:w,begin:f},Y=>{var ce=qr(M,l,Y),ue=qr(H,c,Y),oe=qr(I,s,Y),Q=qr(z,o,Y);n.current&&(b.current=ce,x.current=ue,S.current=oe,k.current=Q);var le;g?Y>0?le={transition:ne,strokeDasharray:Z}:le={strokeDasharray:L}:le={strokeDasharray:Z};var pe=Os(e),{radius:he}=pe,we=q7(pe,KRe);return y.createElement("path",GC({},we,{radius:typeof d=="number"?d:void 0,className:T,d:$7(oe,Q,ce,ue,d),ref:n,style:H7(H7({},le),e.style)}))})};function G7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}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(a){JRe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):G7(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function JRe(t,e,n){return(e=eIe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function eIe(t){var e=tIe(t,"string");return typeof e=="symbol"?e:e+""}function tIe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var WC=Math.PI/180,nIe=t=>t*180/Math.PI,ki=(t,e,n,a)=>({x:t+Math.cos(-WC*a)*n,y:e+Math.sin(-WC*a)*n}),Pne=function(e,n){var a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(a.left||0)-(a.right||0)),Math.abs(n-(a.top||0)-(a.bottom||0)))/2},rIe=(t,e)=>{var{x:n,y:a}=t,{x:i,y:s}=e;return Math.sqrt((n-i)**2+(a-s)**2)},aIe=(t,e)=>{var{x:n,y:a}=t,{cx:i,cy:s}=e,o=rIe({x:n,y:a},{x:i,y:s});if(o<=0)return{radius:o,angle:0};var l=(n-i)/o,c=Math.acos(l);return a>s&&(c=2*Math.PI-c),{radius:o,angle:nIe(c),angleInRadian:c}},iIe=t=>{var{startAngle:e,endAngle:n}=t,a=Math.floor(e/360),i=Math.floor(n/360),s=Math.min(a,i);return{startAngle:e-s*360,endAngle:n-s*360}},sIe=(t,e)=>{var{startAngle:n,endAngle:a}=e,i=Math.floor(n/360),s=Math.floor(a/360),o=Math.min(i,s);return t+o*360},oIe=(t,e)=>{var{chartX:n,chartY:a}=t,{radius:i,angle:s}=aIe({x:n,y:a},e),{innerRadius:o,outerRadius:l}=e;if(i<o||i>l||i===0)return null;var{startAngle:c,endAngle:d}=iIe(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?W7(W7({},e),{},{radius:i,angle:sIe(u,e)}):null};function Tne(t){var{cx:e,cy:n,radius:a,startAngle:i,endAngle:s}=t,o=ki(e,n,a,i),l=ki(e,n,a,s);return{points:[o,l],cx:e,cy:n,radius:a,startAngle:i,endAngle:s}}var K7,Q7,Y7,X7,Z7,J7,e9;function RR(){return RR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},RR.apply(null,arguments)}function sg(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var lIe=(t,e)=>{var n=us(e-t),a=Math.min(Math.abs(e-t),359.999);return n*a},I1=t=>{var{cx:e,cy:n,radius:a,angle:i,sign:s,isExternal:o,cornerRadius:l,cornerIsExternal:c}=t,d=l*(o?1:-1)+a,u=Math.asin(l/d)/WC,m=c?i:i+s*u,p=ki(e,n,d,m),f=ki(e,n,a,m),g=c?i-s*u:i,w=ki(e,n,d*Math.cos(u*WC),g);return{center:p,circleTangency:f,lineTangency:w,theta:u}},Ane=t=>{var{cx:e,cy:n,innerRadius:a,outerRadius:i,startAngle:s,endAngle:o}=t,l=lIe(s,o),c=s+l,d=ki(e,n,i,s),u=ki(e,n,i,c),m=ti(K7||(K7=sg(["M ",",",`
  8108. A `,",",`,0,
  8109. `,",",`,
  8110. `,",",`
  8111. `])),d.x,d.y,i,i,+(Math.abs(l)>180),+(s>c),u.x,u.y);if(a>0){var p=ki(e,n,a,s),f=ki(e,n,a,c);m+=ti(Q7||(Q7=sg(["L ",",",`
  8112. A `,",",`,0,
  8113. `,",",`,
  8114. `,","," Z"])),f.x,f.y,a,a,+(Math.abs(l)>180),+(s<=c),p.x,p.y)}else m+=ti(Y7||(Y7=sg(["L ",","," Z"])),e,n);return m},cIe=t=>{var{cx:e,cy:n,innerRadius:a,outerRadius:i,cornerRadius:s,forceCornerRadius:o,cornerIsExternal:l,startAngle:c,endAngle:d}=t,u=us(d-c),{circleTangency:m,lineTangency:p,theta:f}=I1({cx:e,cy:n,radius:i,angle:c,sign:u,cornerRadius:s,cornerIsExternal:l}),{circleTangency:g,lineTangency:w,theta:b}=I1({cx:e,cy:n,radius:i,angle:d,sign:-u,cornerRadius:s,cornerIsExternal:l}),x=l?Math.abs(c-d):Math.abs(c-d)-f-b;if(x<0)return o?ti(X7||(X7=sg(["M ",",",`
  8115. a`,",",",0,0,1,",`,0
  8116. a`,",",",0,0,1,",`,0
  8117. `])),p.x,p.y,s,s,s*2,s,s,-s*2):Ane({cx:e,cy:n,innerRadius:a,outerRadius:i,startAngle:c,endAngle:d});var S=ti(Z7||(Z7=sg(["M ",",",`
  8118. A`,",",",0,0,",",",",",`
  8119. A`,",",",0,",",",",",",",`
  8120. A`,",",",0,0,",",",",",`
  8121. `])),p.x,p.y,s,s,+(u<0),m.x,m.y,i,i,+(x>180),+(u<0),g.x,g.y,s,s,+(u<0),w.x,w.y);if(a>0){var{circleTangency:k,lineTangency:C,theta:P}=I1({cx:e,cy:n,radius:a,angle:c,sign:u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:T,lineTangency:A,theta:F}=I1({cx:e,cy:n,radius:a,angle:d,sign:-u,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),_=l?Math.abs(c-d):Math.abs(c-d)-P-F;if(_<0&&s===0)return"".concat(S,"L").concat(e,",").concat(n,"Z");S+=ti(J7||(J7=sg(["L",",",`
  8122. A`,",",",0,0,",",",",",`
  8123. A`,",",",0,",",",",",",",`
  8124. A`,",",",0,0,",",",",","Z"])),A.x,A.y,s,s,+(u<0),T.x,T.y,a,a,+(_>180),+(u>0),k.x,k.y,s,s,+(u<0),C.x,C.y)}else S+=ti(e9||(e9=sg(["L",",","Z"])),e,n);return S},dIe={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},jne=t=>{var e=Va(t,dIe),{cx:n,cy:a,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=Er("recharts-sector",m),f=s-i,g=no(o,f,0,!0),w;return g>0&&Math.abs(d-u)<360?w=cIe({cx:n,cy:a,innerRadius:i,outerRadius:s,cornerRadius:Math.min(g,f/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:d,endAngle:u}):w=Ane({cx:n,cy:a,innerRadius:i,outerRadius:s,startAngle:d,endAngle:u}),y.createElement("path",RR({},Os(e),{className:p,d:w}))};function uIe(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(lte(e)){if(t==="centric"){var{cx:a,cy:i,innerRadius:s,outerRadius:o,angle:l}=e,c=ki(a,i,s,l),d=ki(a,i,o,l);return[{x:c.x,y:c.y},{x:d.x,y:d.y}]}return Tne(e)}}var RD={},ID={},OD={},t9;function mIe(){return t9||(t9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=vte();function n(a){return e.isSymbol(a)?NaN:Number(a)}t.toNumber=n})(OD)),OD}var n9;function pIe(){return n9||(n9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=mIe();function n(a){return a?(a=e.toNumber(a),a===1/0||a===-1/0?(a<0?-1:1)*Number.MAX_VALUE:a===a?a:0):a===0?a:0}t.toFinite=n})(ID)),ID}var r9;function hIe(){return r9||(r9=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=wte(),n=pIe();function a(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=a})(RD)),RD}var zD,a9;function fIe(){return a9||(a9=1,zD=hIe().range),zD}var gIe=fIe();const Mne=Tc(gIe);function Oh(t,e){return t==null||e==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function bIe(t,e){return t==null||e==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function R4(t){let e,n,a;t.length!==2?(e=Oh,n=(l,c)=>Oh(t(l),c),a=(l,c)=>t(l)-c):(e=t===Oh||t===bIe?t:xIe,n=t,a=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&&a(l[m-1],c)>-a(l[m],c)?m-1:m}return{left:i,center:o,right:s}}function xIe(){return 0}function Ene(t){return t===null?NaN:+t}function*yIe(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const vIe=R4(Oh),XS=vIe.right;R4(Ene).center;class i9 extends Map{constructor(e,n=_Ie){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[a,i]of e)this.set(a,i)}get(e){return super.get(s9(this,e))}has(e){return super.has(s9(this,e))}set(e,n){return super.set(wIe(this,e),n)}delete(e){return super.delete(SIe(this,e))}}function s9({_intern:t,_key:e},n){const a=e(n);return t.has(a)?t.get(a):n}function wIe({_intern:t,_key:e},n){const a=e(n);return t.has(a)?t.get(a):(t.set(a,n),n)}function SIe({_intern:t,_key:e},n){const a=e(n);return t.has(a)&&(n=t.get(a),t.delete(a)),n}function _Ie(t){return t!==null&&typeof t=="object"?t.valueOf():t}function kIe(t=Oh){if(t===Oh)return Dne;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,n)=>{const a=t(e,n);return a||a===0?a:(t(n,n)===0)-(t(e,e)===0)}}function Dne(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(t<e?-1:t>e?1:0)}const NIe=Math.sqrt(50),CIe=Math.sqrt(10),PIe=Math.sqrt(2);function KC(t,e,n){const a=(e-t)/Math.max(0,n),i=Math.floor(Math.log10(a)),s=a/Math.pow(10,i),o=s>=NIe?10:s>=CIe?5:s>=PIe?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?KC(t,e,n*2):[l,c,d]}function IR(t,e,n){if(e=+e,t=+t,n=+n,!(n>0))return[];if(t===e)return[t];const a=e<t,[i,s,o]=a?KC(e,t,n):KC(t,e,n);if(!(s>=i))return[];const l=s-i+1,c=new Array(l);if(a)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 OR(t,e,n){return e=+e,t=+t,n=+n,KC(t,e,n)[2]}function zR(t,e,n){e=+e,t=+t,n=+n;const a=e<t,i=a?OR(e,t,n):OR(t,e,n);return(a?-1:1)*(i<0?1/-i:i)}function o9(t,e){let n;for(const a of t)a!=null&&(n<a||n===void 0&&a>=a)&&(n=a);return n}function l9(t,e){let n;for(const a of t)a!=null&&(n>a||n===void 0&&a>=a)&&(n=a);return n}function Fne(t,e,n=0,a=1/0,i){if(e=Math.floor(e),n=Math.floor(Math.max(0,n)),a=Math.floor(Math.min(t.length-1,a)),!(n<=e&&e<=a))return t;for(i=i===void 0?Dne:kIe(i);a>n;){if(a-n>600){const c=a-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)),g=Math.min(a,Math.floor(e+(c-d)*m/c+p));Fne(t,e,f,g,i)}const s=t[e];let o=n,l=a;for(x0(t,n,e),i(t[a],s)>0&&x0(t,n,a);o<l;){for(x0(t,o,l),++o,--l;i(t[o],s)<0;)++o;for(;i(t[l],s)>0;)--l}i(t[n],s)===0?x0(t,n,l):(++l,x0(t,l,a)),l<=e&&(n=l+1),e<=l&&(a=l-1)}return t}function x0(t,e,n){const a=t[e];t[e]=t[n],t[n]=a}function TIe(t,e,n){if(t=Float64Array.from(yIe(t)),!(!(a=t.length)||isNaN(e=+e))){if(e<=0||a<2)return l9(t);if(e>=1)return o9(t);var a,i=(a-1)*e,s=Math.floor(i),o=o9(Fne(t,s).subarray(0,s+1)),l=l9(t.subarray(s+1));return o+(l-o)*(i-s)}}function AIe(t,e,n=Ene){if(!(!(a=t.length)||isNaN(e=+e))){if(e<=0||a<2)return+n(t[0],0,t);if(e>=1)return+n(t[a-1],a-1,t);var a,i=(a-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 jIe(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var a=-1,i=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(i);++a<i;)s[a]=t+a*n;return s}function jc(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}function ip(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 I4(){var t=new i9,e=[],n=[],a=UR;function i(s){let o=t.get(s);if(o===void 0){if(a!==UR)return a;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 i9;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?(a=s,i):a},i.copy=function(){return I4(e,n).unknown(a)},jc.apply(i,arguments),i}function O4(){var t=I4().unknown(void 0),e=t.domain,n=t.range,a=0,i=1,s,o,l=!1,c=0,d=0,u=.5;delete t.unknown;function m(){var p=e().length,f=i<a,g=f?i:a,w=f?a:i;s=(w-g)/Math.max(1,p-c+d*2),l&&(s=Math.floor(s)),g+=(w-g-s*(p-c))*u,o=s*(1-c),l&&(g=Math.round(g),o=Math.round(o));var b=jIe(p).map(function(x){return g+s*x});return n(f?b.reverse():b)}return t.domain=function(p){return arguments.length?(e(p),m()):e()},t.range=function(p){return arguments.length?([a,i]=p,a=+a,i=+i,m()):[a,i]},t.rangeRound=function(p){return[a,i]=p,a=+a,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 O4(e(),[a,i]).round(l).paddingInner(c).paddingOuter(d).align(u)},jc.apply(m(),arguments)}function Lne(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return Lne(e())},t}function MIe(){return Lne(O4.apply(null,arguments).paddingInner(1))}function z4(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function Rne(t,e){var n=Object.create(t.prototype);for(var a in e)n[a]=e[a];return n}function ZS(){}var eS=.7,QC=1/eS,uy="\\s*([+-]?\\d+)\\s*",tS="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",du="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",EIe=/^#([0-9a-f]{3,8})$/,DIe=new RegExp(`^rgb\\(${uy},${uy},${uy}\\)$`),FIe=new RegExp(`^rgb\\(${du},${du},${du}\\)$`),LIe=new RegExp(`^rgba\\(${uy},${uy},${uy},${tS}\\)$`),RIe=new RegExp(`^rgba\\(${du},${du},${du},${tS}\\)$`),IIe=new RegExp(`^hsl\\(${tS},${du},${du}\\)$`),OIe=new RegExp(`^hsla\\(${tS},${du},${du},${tS}\\)$`),c9={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};z4(ZS,nS,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:d9,formatHex:d9,formatHex8:zIe,formatHsl:UIe,formatRgb:u9,toString:u9});function d9(){return this.rgb().formatHex()}function zIe(){return this.rgb().formatHex8()}function UIe(){return Ine(this).formatHsl()}function u9(){return this.rgb().formatRgb()}function nS(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=EIe.exec(t))?(n=e[1].length,e=parseInt(e[1],16),n===6?m9(e):n===3?new Go(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?O1(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?O1(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=DIe.exec(t))?new Go(e[1],e[2],e[3],1):(e=FIe.exec(t))?new Go(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=LIe.exec(t))?O1(e[1],e[2],e[3],e[4]):(e=RIe.exec(t))?O1(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=IIe.exec(t))?f9(e[1],e[2]/100,e[3]/100,1):(e=OIe.exec(t))?f9(e[1],e[2]/100,e[3]/100,e[4]):c9.hasOwnProperty(t)?m9(c9[t]):t==="transparent"?new Go(NaN,NaN,NaN,0):null}function m9(t){return new Go(t>>16&255,t>>8&255,t&255,1)}function O1(t,e,n,a){return a<=0&&(t=e=n=NaN),new Go(t,e,n,a)}function BIe(t){return t instanceof ZS||(t=nS(t)),t?(t=t.rgb(),new Go(t.r,t.g,t.b,t.opacity)):new Go}function BR(t,e,n,a){return arguments.length===1?BIe(t):new Go(t,e,n,a??1)}function Go(t,e,n,a){this.r=+t,this.g=+e,this.b=+n,this.opacity=+a}z4(Go,BR,Rne(ZS,{brighter(t){return t=t==null?QC:Math.pow(QC,t),new Go(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?eS:Math.pow(eS,t),new Go(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Go(yg(this.r),yg(this.g),yg(this.b),YC(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:p9,formatHex:p9,formatHex8:HIe,formatRgb:h9,toString:h9}));function p9(){return`#${og(this.r)}${og(this.g)}${og(this.b)}`}function HIe(){return`#${og(this.r)}${og(this.g)}${og(this.b)}${og((isNaN(this.opacity)?1:this.opacity)*255)}`}function h9(){const t=YC(this.opacity);return`${t===1?"rgb(":"rgba("}${yg(this.r)}, ${yg(this.g)}, ${yg(this.b)}${t===1?")":`, ${t})`}`}function YC(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function yg(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function og(t){return t=yg(t),(t<16?"0":"")+t.toString(16)}function f9(t,e,n,a){return a<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new sd(t,e,n,a)}function Ine(t){if(t instanceof sd)return new sd(t.h,t.s,t.l,t.opacity);if(t instanceof ZS||(t=nS(t)),!t)return new sd;if(t instanceof sd)return t;t=t.rgb();var e=t.r/255,n=t.g/255,a=t.b/255,i=Math.min(e,n,a),s=Math.max(e,n,a),o=NaN,l=s-i,c=(s+i)/2;return l?(e===s?o=(n-a)/l+(n<a)*6:n===s?o=(a-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 sd(o,l,c,t.opacity)}function qIe(t,e,n,a){return arguments.length===1?Ine(t):new sd(t,e,n,a??1)}function sd(t,e,n,a){this.h=+t,this.s=+e,this.l=+n,this.opacity=+a}z4(sd,qIe,Rne(ZS,{brighter(t){return t=t==null?QC:Math.pow(QC,t),new sd(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?eS:Math.pow(eS,t),new sd(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,a=n+(n<.5?n:1-n)*e,i=2*n-a;return new Go(UD(t>=240?t-240:t+120,i,a),UD(t,i,a),UD(t<120?t+240:t-120,i,a),this.opacity)},clamp(){return new sd(g9(this.h),z1(this.s),z1(this.l),YC(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=YC(this.opacity);return`${t===1?"hsl(":"hsla("}${g9(this.h)}, ${z1(this.s)*100}%, ${z1(this.l)*100}%${t===1?")":`, ${t})`}`}}));function g9(t){return t=(t||0)%360,t<0?t+360:t}function z1(t){return Math.max(0,Math.min(1,t||0))}function UD(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 U4=t=>()=>t;function $Ie(t,e){return function(n){return t+n*e}}function VIe(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(a){return Math.pow(t+a*e,n)}}function GIe(t){return(t=+t)==1?One:function(e,n){return n-e?VIe(e,n,t):U4(isNaN(e)?n:e)}}function One(t,e){var n=e-t;return n?$Ie(t,n):U4(isNaN(t)?e:t)}const b9=(function t(e){var n=GIe(e);function a(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=One(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 a.gamma=t,a})(1);function WIe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,a=e.slice(),i;return function(s){for(i=0;i<n;++i)a[i]=t[i]*(1-s)+e[i]*s;return a}}function KIe(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function QIe(t,e){var n=e?e.length:0,a=t?Math.min(n,t.length):0,i=new Array(a),s=new Array(n),o;for(o=0;o<a;++o)i[o]=rv(t[o],e[o]);for(;o<n;++o)s[o]=e[o];return function(l){for(o=0;o<a;++o)s[o]=i[o](l);return s}}function YIe(t,e){var n=new Date;return t=+t,e=+e,function(a){return n.setTime(t*(1-a)+e*a),n}}function XC(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}function XIe(t,e){var n={},a={},i;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(i in e)i in t?n[i]=rv(t[i],e[i]):a[i]=e[i];return function(s){for(i in n)a[i]=n[i](s);return a}}var HR=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,BD=new RegExp(HR.source,"g");function ZIe(t){return function(){return t}}function JIe(t){return function(e){return t(e)+""}}function eOe(t,e){var n=HR.lastIndex=BD.lastIndex=0,a,i,s,o=-1,l=[],c=[];for(t=t+"",e=e+"";(a=HR.exec(t))&&(i=BD.exec(e));)(s=i.index)>n&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(a=a[0])===(i=i[0])?l[o]?l[o]+=i:l[++o]=i:(l[++o]=null,c.push({i:o,x:XC(a,i)})),n=BD.lastIndex;return n<e.length&&(s=e.slice(n),l[o]?l[o]+=s:l[++o]=s),l.length<2?c[0]?JIe(c[0].x):ZIe(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 rv(t,e){var n=typeof e,a;return e==null||n==="boolean"?U4(e):(n==="number"?XC:n==="string"?(a=nS(e))?(e=a,b9):eOe:e instanceof nS?b9:e instanceof Date?YIe:KIe(e)?WIe:Array.isArray(e)?QIe:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?XIe:XC)(t,e)}function B4(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}function tOe(t,e){e===void 0&&(e=t,t=rv);for(var n=0,a=e.length-1,i=e[0],s=new Array(a<0?0:a);n<a;)s[n]=t(i,i=e[++n]);return function(o){var l=Math.max(0,Math.min(a-1,Math.floor(o*=a)));return s[l](o-l)}}function nOe(t){return function(){return t}}function ZC(t){return+t}var x9=[0,1];function yo(t){return t}function qR(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:nOe(isNaN(e)?NaN:.5)}function rOe(t,e){var n;return t>e&&(n=t,t=e,e=n),function(a){return Math.max(t,Math.min(e,a))}}function aOe(t,e,n){var a=t[0],i=t[1],s=e[0],o=e[1];return i<a?(a=qR(i,a),s=n(o,s)):(a=qR(a,i),s=n(s,o)),function(l){return s(a(l))}}function iOe(t,e,n){var a=Math.min(t.length,e.length)-1,i=new Array(a),s=new Array(a),o=-1;for(t[a]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<a;)i[o]=qR(t[o],t[o+1]),s[o]=n(e[o],e[o+1]);return function(l){var c=XS(t,l,1,a)-1;return s[c](i[c](l))}}function JS(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function oA(){var t=x9,e=x9,n=rv,a,i,s,o=yo,l,c,d;function u(){var p=Math.min(t.length,e.length);return o!==yo&&(o=rOe(t[0],t[p-1])),l=p>2?iOe:aOe,c=d=null,m}function m(p){return p==null||isNaN(p=+p)?s:(c||(c=l(t.map(a),e,n)))(a(o(p)))}return m.invert=function(p){return o(i((d||(d=l(e,t.map(a),XC)))(p)))},m.domain=function(p){return arguments.length?(t=Array.from(p,ZC),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=B4,u()},m.clamp=function(p){return arguments.length?(o=p?!0:yo,u()):o!==yo},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 a=p,i=f,u()}}function H4(){return oA()(yo,yo)}function sOe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function JC(t,e){if(!isFinite(t)||t===0)return null;var n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),a=t.slice(0,n);return[a.length>1?a[0]+a.slice(2):a,+t.slice(n+1)]}function My(t){return t=JC(Math.abs(t)),t?t[1]:NaN}function oOe(t,e){return function(n,a){for(var i=n.length,s=[],o=0,l=t[0],c=0;i>0&&l>0&&(c+l+1>a&&(l=Math.max(1,a-c)),s.push(n.substring(i-=l,i+l)),!((c+=l+1)>a));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function lOe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var cOe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function rS(t){if(!(e=cOe.exec(t)))throw new Error("invalid format: "+t);var e;return new q4({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]})}rS.prototype=q4.prototype;function q4(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+""}q4.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 dOe(t){e:for(var e=t.length,n=1,a=-1,i;n<e;++n)switch(t[n]){case".":a=i=n;break;case"0":a===0&&(a=n),i=n;break;default:if(!+t[n])break e;a>0&&(a=0);break}return a>0?t.slice(0,a)+t.slice(i+1):t}var eP;function uOe(t,e){var n=JC(t,e);if(!n)return eP=void 0,t.toPrecision(e);var a=n[0],i=n[1],s=i-(eP=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=a.length;return s===o?a:s>o?a+new Array(s-o+1).join("0"):s>0?a.slice(0,s)+"."+a.slice(s):"0."+new Array(1-s).join("0")+JC(t,Math.max(0,e+s-1))[0]}function y9(t,e){var n=JC(t,e);if(!n)return t+"";var a=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+a:a.length>i+1?a.slice(0,i+1)+"."+a.slice(i+1):a+new Array(i-a.length+2).join("0")}const v9={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:sOe,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)=>y9(t*100,e),r:y9,s:uOe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function w9(t){return t}var S9=Array.prototype.map,_9=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function mOe(t){var e=t.grouping===void 0||t.thousands===void 0?w9:oOe(S9.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",a=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?w9:lOe(S9.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=rS(m);var f=m.fill,g=m.align,w=m.sign,b=m.symbol,x=m.zero,S=m.width,k=m.comma,C=m.precision,P=m.trim,T=m.type;T==="n"?(k=!0,T="g"):v9[T]||(C===void 0&&(C=12),P=!0,T="g"),(x||f==="0"&&g==="=")&&(x=!0,f="0",g="=");var A=(p&&p.prefix!==void 0?p.prefix:"")+(b==="$"?n:b==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():""),F=(b==="$"?a:/[%p]/.test(T)?o:"")+(p&&p.suffix!==void 0?p.suffix:""),_=v9[T],M=/[defgprs%]/.test(T);C=C===void 0?6:/[gprs]/.test(T)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function H(I){var z=A,L=F,Z,ne,Y;if(T==="c")L=_(I)+L,I="";else{I=+I;var ce=I<0||1/I<0;if(I=isNaN(I)?c:_(Math.abs(I),C),P&&(I=dOe(I)),ce&&+I==0&&w!=="+"&&(ce=!1),z=(ce?w==="("?w:l:w==="-"||w==="("?"":w)+z,L=(T==="s"&&!isNaN(I)&&eP!==void 0?_9[8+eP/3]:"")+L+(ce&&w==="("?")":""),M){for(Z=-1,ne=I.length;++Z<ne;)if(Y=I.charCodeAt(Z),48>Y||Y>57){L=(Y===46?i+I.slice(Z+1):I.slice(Z))+L,I=I.slice(0,Z);break}}}k&&!x&&(I=e(I,1/0));var ue=z.length+I.length+L.length,oe=ue<S?new Array(S-ue+1).join(f):"";switch(k&&x&&(I=e(oe+I,oe.length?S-L.length:1/0),oe=""),g){case"<":I=z+I+L+oe;break;case"=":I=z+oe+I+L;break;case"^":I=oe.slice(0,ue=oe.length>>1)+z+I+L+oe.slice(ue);break;default:I=oe+z+I+L;break}return s(I)}return H.toString=function(){return m+""},H}function u(m,p){var f=Math.max(-8,Math.min(8,Math.floor(My(p)/3)))*3,g=Math.pow(10,-f),w=d((m=rS(m),m.type="f",m),{suffix:_9[8+f/3]});return function(b){return w(g*b)}}return{format:d,formatPrefix:u}}var U1,$4,zne;pOe({thousands:",",grouping:[3],currency:["$",""]});function pOe(t){return U1=mOe(t),$4=U1.format,zne=U1.formatPrefix,U1}function hOe(t){return Math.max(0,-My(Math.abs(t)))}function fOe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(My(e)/3)))*3-My(Math.abs(t)))}function gOe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,My(e)-My(t))+1}function Une(t,e,n,a){var i=zR(t,e,n),s;switch(a=rS(a??",f"),a.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return a.precision==null&&!isNaN(s=fOe(i,o))&&(a.precision=s),zne(a,o)}case"":case"e":case"g":case"p":case"r":{a.precision==null&&!isNaN(s=gOe(i,Math.max(Math.abs(t),Math.abs(e))))&&(a.precision=s-(a.type==="e"));break}case"f":case"%":{a.precision==null&&!isNaN(s=hOe(i))&&(a.precision=s-(a.type==="%")*2);break}}return $4(a)}function lf(t){var e=t.domain;return t.ticks=function(n){var a=e();return IR(a[0],a[a.length-1],n??10)},t.tickFormat=function(n,a){var i=e();return Une(i[0],i[i.length-1],n??10,a)},t.nice=function(n){n==null&&(n=10);var a=e(),i=0,s=a.length-1,o=a[i],l=a[s],c,d,u=10;for(l<o&&(d=o,o=l,l=d,d=i,i=s,s=d);u-- >0;){if(d=OR(o,l,n),d===c)return a[i]=o,a[s]=l,e(a);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 Bne(){var t=H4();return t.copy=function(){return JS(t,Bne())},jc.apply(t,arguments),lf(t)}function Hne(t){var e;function n(a){return a==null||isNaN(a=+a)?e:a}return n.invert=n,n.domain=n.range=function(a){return arguments.length?(t=Array.from(a,ZC),n):t.slice()},n.unknown=function(a){return arguments.length?(e=a,n):e},n.copy=function(){return Hne(t).unknown(e)},t=arguments.length?Array.from(t,ZC):[0,1],lf(n)}function qne(t,e){t=t.slice();var n=0,a=t.length-1,i=t[n],s=t[a],o;return s<i&&(o=n,n=a,a=o,o=i,i=s,s=o),t[n]=e.floor(i),t[a]=e.ceil(s),t}function k9(t){return Math.log(t)}function N9(t){return Math.exp(t)}function bOe(t){return-Math.log(-t)}function xOe(t){return-Math.exp(-t)}function yOe(t){return isFinite(t)?+("1e"+t):t<0?0:t}function vOe(t){return t===10?yOe:t===Math.E?Math.exp:e=>Math.pow(t,e)}function wOe(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 C9(t){return(e,n)=>-t(-e,n)}function V4(t){const e=t(k9,N9),n=e.domain;let a=10,i,s;function o(){return i=wOe(a),s=vOe(a),n()[0]<0?(i=C9(i),s=C9(s),t(bOe,xOe)):t(k9,N9),e}return e.base=function(l){return arguments.length?(a=+l,o()):a},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),g,w;const b=l==null?10:+l;let x=[];if(!(a%1)&&f-p<b){if(p=Math.floor(p),f=Math.ceil(f),d>0){for(;p<=f;++p)for(g=1;g<a;++g)if(w=p<0?g/s(-p):g*s(p),!(w<d)){if(w>u)break;x.push(w)}}else for(;p<=f;++p)for(g=a-1;g>=1;--g)if(w=p>0?g/s(-p):g*s(p),!(w<d)){if(w>u)break;x.push(w)}x.length*2<b&&(x=IR(d,u,b))}else x=IR(p,f,Math.min(f-p,b)).map(s);return m?x.reverse():x},e.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=a===10?"s":","),typeof c!="function"&&(!(a%1)&&(c=rS(c)).precision==null&&(c.trim=!0),c=$4(c)),l===1/0)return c;const d=Math.max(1,a*l/e.ticks().length);return u=>{let m=u/s(Math.round(i(u)));return m*a<a-.5&&(m*=a),m<=d?c(u):""}},e.nice=()=>n(qne(n(),{floor:l=>s(Math.floor(i(l))),ceil:l=>s(Math.ceil(i(l)))})),e}function $ne(){const t=V4(oA()).domain([1,10]);return t.copy=()=>JS(t,$ne()).base(t.base()),jc.apply(t,arguments),t}function P9(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function T9(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function G4(t){var e=1,n=t(P9(e),T9(e));return n.constant=function(a){return arguments.length?t(P9(e=+a),T9(e)):e},lf(n)}function Vne(){var t=G4(oA());return t.copy=function(){return JS(t,Vne()).constant(t.constant())},jc.apply(t,arguments)}function A9(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function SOe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function _Oe(t){return t<0?-t*t:t*t}function W4(t){var e=t(yo,yo),n=1;function a(){return n===1?t(yo,yo):n===.5?t(SOe,_Oe):t(A9(n),A9(1/n))}return e.exponent=function(i){return arguments.length?(n=+i,a()):n},lf(e)}function K4(){var t=W4(oA());return t.copy=function(){return JS(t,K4()).exponent(t.exponent())},jc.apply(t,arguments),t}function kOe(){return K4.apply(null,arguments).exponent(.5)}function j9(t){return Math.sign(t)*t*t}function NOe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Gne(){var t=H4(),e=[0,1],n=!1,a;function i(s){var o=NOe(t(s));return isNaN(o)?a:n?Math.round(o):o}return i.invert=function(s){return t.invert(j9(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,ZC)).map(j9)),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?(a=s,i):a},i.copy=function(){return Gne(t.domain(),e).round(n).clamp(t.clamp()).unknown(a)},jc.apply(i,arguments),lf(i)}function Wne(){var t=[],e=[],n=[],a;function i(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o<l;)n[o-1]=AIe(t,o/l);return s}function s(o){return o==null||isNaN(o=+o)?a:e[XS(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(Oh),i()},s.range=function(o){return arguments.length?(e=Array.from(o),i()):e.slice()},s.unknown=function(o){return arguments.length?(a=o,s):a},s.quantiles=function(){return n.slice()},s.copy=function(){return Wne().domain(t).range(e).unknown(a)},jc.apply(s,arguments)}function Kne(){var t=0,e=1,n=1,a=[.5],i=[0,1],s;function o(c){return c!=null&&c<=c?i[XS(a,c,0,n)]:s}function l(){var c=-1;for(a=new Array(n);++c<n;)a[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,a[0]]:d>=n?[a[n-1],e]:[a[d-1],a[d]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return a.slice()},o.copy=function(){return Kne().domain([t,e]).range(i).unknown(s)},jc.apply(lf(o),arguments)}function Qne(){var t=[.5],e=[0,1],n,a=1;function i(s){return s!=null&&s<=s?e[XS(t,s,0,a)]:n}return i.domain=function(s){return arguments.length?(t=Array.from(s),a=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(s){return arguments.length?(e=Array.from(s),a=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 Qne().domain(t).range(e).unknown(n)},jc.apply(i,arguments)}const HD=new Date,qD=new Date;function Vi(t,e,n,a){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=>Vi(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)=>(HD.setTime(+s),qD.setTime(+o),t(HD),t(qD),Math.floor(n(HD,qD))),i.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?i.filter(a?o=>a(o)%s===0:o=>i.count(0,o)%s===0):i)),i}const tP=Vi(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);tP.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?Vi(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):tP);tP.range;const Nm=1e3,pc=Nm*60,Cm=pc*60,Xm=Cm*24,Q4=Xm*7,M9=Xm*30,$D=Xm*365,lg=Vi(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Nm)},(t,e)=>(e-t)/Nm,t=>t.getUTCSeconds());lg.range;const Y4=Vi(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Nm)},(t,e)=>{t.setTime(+t+e*pc)},(t,e)=>(e-t)/pc,t=>t.getMinutes());Y4.range;const X4=Vi(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*pc)},(t,e)=>(e-t)/pc,t=>t.getUTCMinutes());X4.range;const Z4=Vi(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Nm-t.getMinutes()*pc)},(t,e)=>{t.setTime(+t+e*Cm)},(t,e)=>(e-t)/Cm,t=>t.getHours());Z4.range;const J4=Vi(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Cm)},(t,e)=>(e-t)/Cm,t=>t.getUTCHours());J4.range;const e_=Vi(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*pc)/Xm,t=>t.getDate()-1);e_.range;const lA=Vi(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Xm,t=>t.getUTCDate()-1);lA.range;const Yne=Vi(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Xm,t=>Math.floor(t/Xm));Yne.range;function db(t){return Vi(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())*pc)/Q4)}const cA=db(0),nP=db(1),COe=db(2),POe=db(3),Ey=db(4),TOe=db(5),AOe=db(6);cA.range;nP.range;COe.range;POe.range;Ey.range;TOe.range;AOe.range;function ub(t){return Vi(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)/Q4)}const dA=ub(0),rP=ub(1),jOe=ub(2),MOe=ub(3),Dy=ub(4),EOe=ub(5),DOe=ub(6);dA.range;rP.range;jOe.range;MOe.range;Dy.range;EOe.range;DOe.range;const ez=Vi(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());ez.range;const tz=Vi(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());tz.range;const Zm=Vi(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());Zm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Vi(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)});Zm.range;const Jm=Vi(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());Jm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Vi(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)});Jm.range;function Xne(t,e,n,a,i,s){const o=[[lg,1,Nm],[lg,5,5*Nm],[lg,15,15*Nm],[lg,30,30*Nm],[s,1,pc],[s,5,5*pc],[s,15,15*pc],[s,30,30*pc],[i,1,Cm],[i,3,3*Cm],[i,6,6*Cm],[i,12,12*Cm],[a,1,Xm],[a,2,2*Xm],[n,1,Q4],[e,1,M9],[e,3,3*M9],[t,1,$D]];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),g=f?f.range(d,+u+1):[];return p?g.reverse():g}function c(d,u,m){const p=Math.abs(u-d)/m,f=R4(([,,b])=>b).right(o,p);if(f===o.length)return t.every(zR(d/$D,u/$D,m));if(f===0)return tP.every(Math.max(zR(d,u,m),1));const[g,w]=o[p/o[f-1][2]<o[f][2]/p?f-1:f];return g.every(w)}return[l,c]}const[FOe,LOe]=Xne(Jm,tz,dA,Yne,J4,X4),[ROe,IOe]=Xne(Zm,ez,cA,e_,Z4,Y4);function VD(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 GD(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 y0(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,a=t.time,i=t.periods,s=t.days,o=t.shortDays,l=t.months,c=t.shortMonths,d=v0(i),u=w0(i),m=v0(s),p=w0(s),f=v0(o),g=w0(o),w=v0(l),b=w0(l),x=v0(c),S=w0(c),k={a:Y,A:ce,b:ue,B:oe,c:null,d:I9,e:I9,f:o4e,g:b4e,G:y4e,H:a4e,I:i4e,j:s4e,L:Zne,m:l4e,M:c4e,p:Q,q:le,Q:U9,s:B9,S:d4e,u:u4e,U:m4e,V:p4e,w:h4e,W:f4e,x:null,X:null,y:g4e,Y:x4e,Z:v4e,"%":z9},C={a:pe,A:he,b:we,B:$,c:null,d:O9,e:O9,f:k4e,g:F4e,G:R4e,H:w4e,I:S4e,j:_4e,L:ere,m:N4e,M:C4e,p:J,q:j,Q:U9,s:B9,S:P4e,u:T4e,U:A4e,V:j4e,w:M4e,W:E4e,x:null,X:null,y:D4e,Y:L4e,Z:I4e,"%":z9},P={a:M,A:H,b:I,B:z,c:L,d:L9,e:L9,f:e4e,g:F9,G:D9,H:R9,I:R9,j:YOe,L:JOe,m:QOe,M:XOe,p:_,q:KOe,Q:n4e,s:r4e,S:ZOe,u:qOe,U:$Oe,V:VOe,w:HOe,W:GOe,x:Z,X:ne,y:F9,Y:D9,Z:WOe,"%":t4e};k.x=T(n,k),k.X=T(a,k),k.c=T(e,k),C.x=T(n,C),C.X=T(a,C),C.c=T(e,C);function T(E,B){return function(W){var O=[],ie=-1,U=0,G=E.length,K,X,se;for(W instanceof Date||(W=new Date(+W));++ie<G;)E.charCodeAt(ie)===37&&(O.push(E.slice(U,ie)),(X=E9[K=E.charAt(++ie)])!=null?K=E.charAt(++ie):X=K==="e"?" ":"0",(se=B[K])&&(K=se(W,X)),O.push(K),U=ie+1);return O.push(E.slice(U,ie)),O.join("")}}function A(E,B){return function(W){var O=y0(1900,void 0,1),ie=F(O,E,W+="",0),U,G;if(ie!=W.length)return null;if("Q"in O)return new Date(O.Q);if("s"in O)return new Date(O.s*1e3+("L"in O?O.L:0));if(B&&!("Z"in O)&&(O.Z=0),"p"in O&&(O.H=O.H%12+O.p*12),O.m===void 0&&(O.m="q"in O?O.q:0),"V"in O){if(O.V<1||O.V>53)return null;"w"in O||(O.w=1),"Z"in O?(U=GD(y0(O.y,0,1)),G=U.getUTCDay(),U=G>4||G===0?rP.ceil(U):rP(U),U=lA.offset(U,(O.V-1)*7),O.y=U.getUTCFullYear(),O.m=U.getUTCMonth(),O.d=U.getUTCDate()+(O.w+6)%7):(U=VD(y0(O.y,0,1)),G=U.getDay(),U=G>4||G===0?nP.ceil(U):nP(U),U=e_.offset(U,(O.V-1)*7),O.y=U.getFullYear(),O.m=U.getMonth(),O.d=U.getDate()+(O.w+6)%7)}else("W"in O||"U"in O)&&("w"in O||(O.w="u"in O?O.u%7:"W"in O?1:0),G="Z"in O?GD(y0(O.y,0,1)).getUTCDay():VD(y0(O.y,0,1)).getDay(),O.m=0,O.d="W"in O?(O.w+6)%7+O.W*7-(G+5)%7:O.w+O.U*7-(G+6)%7);return"Z"in O?(O.H+=O.Z/100|0,O.M+=O.Z%100,GD(O)):VD(O)}}function F(E,B,W,O){for(var ie=0,U=B.length,G=W.length,K,X;ie<U;){if(O>=G)return-1;if(K=B.charCodeAt(ie++),K===37){if(K=B.charAt(ie++),X=P[K in E9?B.charAt(ie++):K],!X||(O=X(E,W,O))<0)return-1}else if(K!=W.charCodeAt(O++))return-1}return O}function _(E,B,W){var O=d.exec(B.slice(W));return O?(E.p=u.get(O[0].toLowerCase()),W+O[0].length):-1}function M(E,B,W){var O=f.exec(B.slice(W));return O?(E.w=g.get(O[0].toLowerCase()),W+O[0].length):-1}function H(E,B,W){var O=m.exec(B.slice(W));return O?(E.w=p.get(O[0].toLowerCase()),W+O[0].length):-1}function I(E,B,W){var O=x.exec(B.slice(W));return O?(E.m=S.get(O[0].toLowerCase()),W+O[0].length):-1}function z(E,B,W){var O=w.exec(B.slice(W));return O?(E.m=b.get(O[0].toLowerCase()),W+O[0].length):-1}function L(E,B,W){return F(E,e,B,W)}function Z(E,B,W){return F(E,n,B,W)}function ne(E,B,W){return F(E,a,B,W)}function Y(E){return o[E.getDay()]}function ce(E){return s[E.getDay()]}function ue(E){return c[E.getMonth()]}function oe(E){return l[E.getMonth()]}function Q(E){return i[+(E.getHours()>=12)]}function le(E){return 1+~~(E.getMonth()/3)}function pe(E){return o[E.getUTCDay()]}function he(E){return s[E.getUTCDay()]}function we(E){return c[E.getUTCMonth()]}function $(E){return l[E.getUTCMonth()]}function J(E){return i[+(E.getUTCHours()>=12)]}function j(E){return 1+~~(E.getUTCMonth()/3)}return{format:function(E){var B=T(E+="",k);return B.toString=function(){return E},B},parse:function(E){var B=A(E+="",!1);return B.toString=function(){return E},B},utcFormat:function(E){var B=T(E+="",C);return B.toString=function(){return E},B},utcParse:function(E){var B=A(E+="",!0);return B.toString=function(){return E},B}}}var E9={"-":"",_:" ",0:"0"},bs=/^\s*\d+/,zOe=/^%/,UOe=/[\\^$*+?|[\]().{}]/g;function Ur(t,e,n){var a=t<0?"-":"",i=(a?-t:t)+"",s=i.length;return a+(s<n?new Array(n-s+1).join(e)+i:i)}function BOe(t){return t.replace(UOe,"\\$&")}function v0(t){return new RegExp("^(?:"+t.map(BOe).join("|")+")","i")}function w0(t){return new Map(t.map((e,n)=>[e.toLowerCase(),n]))}function HOe(t,e,n){var a=bs.exec(e.slice(n,n+1));return a?(t.w=+a[0],n+a[0].length):-1}function qOe(t,e,n){var a=bs.exec(e.slice(n,n+1));return a?(t.u=+a[0],n+a[0].length):-1}function $Oe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.U=+a[0],n+a[0].length):-1}function VOe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.V=+a[0],n+a[0].length):-1}function GOe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.W=+a[0],n+a[0].length):-1}function D9(t,e,n){var a=bs.exec(e.slice(n,n+4));return a?(t.y=+a[0],n+a[0].length):-1}function F9(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.y=+a[0]+(+a[0]>68?1900:2e3),n+a[0].length):-1}function WOe(t,e,n){var a=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return a?(t.Z=a[1]?0:-(a[2]+(a[3]||"00")),n+a[0].length):-1}function KOe(t,e,n){var a=bs.exec(e.slice(n,n+1));return a?(t.q=a[0]*3-3,n+a[0].length):-1}function QOe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.m=a[0]-1,n+a[0].length):-1}function L9(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.d=+a[0],n+a[0].length):-1}function YOe(t,e,n){var a=bs.exec(e.slice(n,n+3));return a?(t.m=0,t.d=+a[0],n+a[0].length):-1}function R9(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.H=+a[0],n+a[0].length):-1}function XOe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.M=+a[0],n+a[0].length):-1}function ZOe(t,e,n){var a=bs.exec(e.slice(n,n+2));return a?(t.S=+a[0],n+a[0].length):-1}function JOe(t,e,n){var a=bs.exec(e.slice(n,n+3));return a?(t.L=+a[0],n+a[0].length):-1}function e4e(t,e,n){var a=bs.exec(e.slice(n,n+6));return a?(t.L=Math.floor(a[0]/1e3),n+a[0].length):-1}function t4e(t,e,n){var a=zOe.exec(e.slice(n,n+1));return a?n+a[0].length:-1}function n4e(t,e,n){var a=bs.exec(e.slice(n));return a?(t.Q=+a[0],n+a[0].length):-1}function r4e(t,e,n){var a=bs.exec(e.slice(n));return a?(t.s=+a[0],n+a[0].length):-1}function I9(t,e){return Ur(t.getDate(),e,2)}function a4e(t,e){return Ur(t.getHours(),e,2)}function i4e(t,e){return Ur(t.getHours()%12||12,e,2)}function s4e(t,e){return Ur(1+e_.count(Zm(t),t),e,3)}function Zne(t,e){return Ur(t.getMilliseconds(),e,3)}function o4e(t,e){return Zne(t,e)+"000"}function l4e(t,e){return Ur(t.getMonth()+1,e,2)}function c4e(t,e){return Ur(t.getMinutes(),e,2)}function d4e(t,e){return Ur(t.getSeconds(),e,2)}function u4e(t){var e=t.getDay();return e===0?7:e}function m4e(t,e){return Ur(cA.count(Zm(t)-1,t),e,2)}function Jne(t){var e=t.getDay();return e>=4||e===0?Ey(t):Ey.ceil(t)}function p4e(t,e){return t=Jne(t),Ur(Ey.count(Zm(t),t)+(Zm(t).getDay()===4),e,2)}function h4e(t){return t.getDay()}function f4e(t,e){return Ur(nP.count(Zm(t)-1,t),e,2)}function g4e(t,e){return Ur(t.getFullYear()%100,e,2)}function b4e(t,e){return t=Jne(t),Ur(t.getFullYear()%100,e,2)}function x4e(t,e){return Ur(t.getFullYear()%1e4,e,4)}function y4e(t,e){var n=t.getDay();return t=n>=4||n===0?Ey(t):Ey.ceil(t),Ur(t.getFullYear()%1e4,e,4)}function v4e(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Ur(e/60|0,"0",2)+Ur(e%60,"0",2)}function O9(t,e){return Ur(t.getUTCDate(),e,2)}function w4e(t,e){return Ur(t.getUTCHours(),e,2)}function S4e(t,e){return Ur(t.getUTCHours()%12||12,e,2)}function _4e(t,e){return Ur(1+lA.count(Jm(t),t),e,3)}function ere(t,e){return Ur(t.getUTCMilliseconds(),e,3)}function k4e(t,e){return ere(t,e)+"000"}function N4e(t,e){return Ur(t.getUTCMonth()+1,e,2)}function C4e(t,e){return Ur(t.getUTCMinutes(),e,2)}function P4e(t,e){return Ur(t.getUTCSeconds(),e,2)}function T4e(t){var e=t.getUTCDay();return e===0?7:e}function A4e(t,e){return Ur(dA.count(Jm(t)-1,t),e,2)}function tre(t){var e=t.getUTCDay();return e>=4||e===0?Dy(t):Dy.ceil(t)}function j4e(t,e){return t=tre(t),Ur(Dy.count(Jm(t),t)+(Jm(t).getUTCDay()===4),e,2)}function M4e(t){return t.getUTCDay()}function E4e(t,e){return Ur(rP.count(Jm(t)-1,t),e,2)}function D4e(t,e){return Ur(t.getUTCFullYear()%100,e,2)}function F4e(t,e){return t=tre(t),Ur(t.getUTCFullYear()%100,e,2)}function L4e(t,e){return Ur(t.getUTCFullYear()%1e4,e,4)}function R4e(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Dy(t):Dy.ceil(t),Ur(t.getUTCFullYear()%1e4,e,4)}function I4e(){return"+0000"}function z9(){return"%"}function U9(t){return+t}function B9(t){return Math.floor(+t/1e3)}var jx,nre,rre;O4e({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 O4e(t){return jx=OOe(t),nre=jx.format,jx.parse,rre=jx.utcFormat,jx.utcParse,jx}function z4e(t){return new Date(t)}function U4e(t){return t instanceof Date?+t:+new Date(+t)}function nz(t,e,n,a,i,s,o,l,c,d){var u=H4(),m=u.invert,p=u.domain,f=d(".%L"),g=d(":%S"),w=d("%I:%M"),b=d("%I %p"),x=d("%a %d"),S=d("%b %d"),k=d("%B"),C=d("%Y");function P(T){return(c(T)<T?f:l(T)<T?g:o(T)<T?w:s(T)<T?b:a(T)<T?i(T)<T?x:S:n(T)<T?k:C)(T)}return u.invert=function(T){return new Date(m(T))},u.domain=function(T){return arguments.length?p(Array.from(T,U4e)):p().map(z4e)},u.ticks=function(T){var A=p();return t(A[0],A[A.length-1],T??10)},u.tickFormat=function(T,A){return A==null?P:d(A)},u.nice=function(T){var A=p();return(!T||typeof T.range!="function")&&(T=e(A[0],A[A.length-1],T??10)),T?p(qne(A,T)):u},u.copy=function(){return JS(u,nz(t,e,n,a,i,s,o,l,c,d))},u}function B4e(){return jc.apply(nz(ROe,IOe,Zm,ez,cA,e_,Z4,Y4,lg,nre).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function H4e(){return jc.apply(nz(FOe,LOe,Jm,tz,dA,lA,J4,X4,lg,rre).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function uA(){var t=0,e=1,n,a,i,s,o=yo,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),a=s(e=+e),i=n===a?0:1/(a-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,g;return arguments.length?([f,g]=p,o=m(f,g),d):[o(0),o(1)]}}return d.range=u(rv),d.rangeRound=u(B4),d.unknown=function(m){return arguments.length?(c=m,d):c},function(m){return s=m,n=m(t),a=m(e),i=n===a?0:1/(a-n),d}}function cf(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function are(){var t=lf(uA()(yo));return t.copy=function(){return cf(t,are())},ip.apply(t,arguments)}function ire(){var t=V4(uA()).domain([1,10]);return t.copy=function(){return cf(t,ire()).base(t.base())},ip.apply(t,arguments)}function sre(){var t=G4(uA());return t.copy=function(){return cf(t,sre()).constant(t.constant())},ip.apply(t,arguments)}function rz(){var t=W4(uA());return t.copy=function(){return cf(t,rz()).exponent(t.exponent())},ip.apply(t,arguments)}function q4e(){return rz.apply(null,arguments).exponent(.5)}function ore(){var t=[],e=yo;function n(a){if(a!=null&&!isNaN(a=+a))return e((XS(t,a,1)-1)/(t.length-1))}return n.domain=function(a){if(!arguments.length)return t.slice();t=[];for(let i of a)i!=null&&!isNaN(i=+i)&&t.push(i);return t.sort(Oh),n},n.interpolator=function(a){return arguments.length?(e=a,n):e},n.range=function(){return t.map((a,i)=>e(i/(t.length-1)))},n.quantiles=function(a){return Array.from({length:a+1},(i,s)=>TIe(t,s/a))},n.copy=function(){return ore(e).domain(t)},ip.apply(n,arguments)}function mA(){var t=0,e=.5,n=1,a=1,i,s,o,l,c,d=yo,u,m=!1,p;function f(w){return isNaN(w=+w)?p:(w=.5+((w=+u(w))-s)*(a*w<a*s?l:c),d(m?Math.max(0,Math.min(1,w)):w))}f.domain=function(w){return arguments.length?([t,e,n]=w,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),a=s<i?-1:1,f):[t,e,n]},f.clamp=function(w){return arguments.length?(m=!!w,f):m},f.interpolator=function(w){return arguments.length?(d=w,f):d};function g(w){return function(b){var x,S,k;return arguments.length?([x,S,k]=b,d=tOe(w,[x,S,k]),f):[d(0),d(.5),d(1)]}}return f.range=g(rv),f.rangeRound=g(B4),f.unknown=function(w){return arguments.length?(p=w,f):p},function(w){return u=w,i=w(t),s=w(e),o=w(n),l=i===s?0:.5/(s-i),c=s===o?0:.5/(o-s),a=s<i?-1:1,f}}function lre(){var t=lf(mA()(yo));return t.copy=function(){return cf(t,lre())},ip.apply(t,arguments)}function cre(){var t=V4(mA()).domain([.1,1,10]);return t.copy=function(){return cf(t,cre()).base(t.base())},ip.apply(t,arguments)}function dre(){var t=G4(mA());return t.copy=function(){return cf(t,dre()).constant(t.constant())},ip.apply(t,arguments)}function az(){var t=W4(mA());return t.copy=function(){return cf(t,az()).exponent(t.exponent())},ip.apply(t,arguments)}function $4e(){return az.apply(null,arguments).exponent(.5)}const z0=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:O4,scaleDiverging:lre,scaleDivergingLog:cre,scaleDivergingPow:az,scaleDivergingSqrt:$4e,scaleDivergingSymlog:dre,scaleIdentity:Hne,scaleImplicit:UR,scaleLinear:Bne,scaleLog:$ne,scaleOrdinal:I4,scalePoint:MIe,scalePow:K4,scaleQuantile:Wne,scaleQuantize:Kne,scaleRadial:Gne,scaleSequential:are,scaleSequentialLog:ire,scaleSequentialPow:rz,scaleSequentialQuantile:ore,scaleSequentialSqrt:q4e,scaleSequentialSymlog:sre,scaleSqrt:kOe,scaleSymlog:Vne,scaleThreshold:Qne,scaleTime:B4e,scaleUtc:H4e,tickFormat:Une},Symbol.toStringTag,{value:"Module"}));var sp=t=>t.chartData,pA=Pt([sp],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),iz=(t,e,n,a)=>a?pA(t):sp(t),ure=(t,e,n)=>n?pA(t):sp(t);function ep(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(Kn(e)&&Kn(n))return!0}return!1}function H9(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function mre(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,a]=t,i,s;if(Kn(n))i=n;else if(typeof n=="function")return;if(Kn(a))s=a;else if(typeof a=="function")return;var o=[i,s];if(ep(o))return o}}function V4e(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var a=t(e,n);if(ep(a))return H9(a,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(hn(i))o=i;else if(typeof i=="function")try{e!=null&&(o=i(e?.[0]))}catch{}else if(typeof i=="string"&&ZG.test(i)){var c=ZG.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(hn(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&JG.test(s)){var u=JG.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(ep(p))return e==null?p:H9(p,e,n)}}}var av=1e9,G4e={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},oz,Oa=!0,Cc="[DecimalError] ",vg=Cc+"Invalid argument: ",sz=Cc+"Exponent out of range: ",iv=Math.floor,Xf=Math.pow,W4e=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,bl,as=1e7,ja=7,pre=9007199254740991,aP=iv(pre/ja),xn={};xn.absoluteValue=xn.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};xn.comparedTo=xn.cmp=function(t){var e,n,a,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(a=s.d.length,i=t.d.length,e=0,n=a<i?a:i;e<n;++e)if(s.d[e]!==t.d[e])return s.d[e]>t.d[e]^s.s<0?1:-1;return a===i?0:a>i^s.s<0?1:-1};xn.decimalPlaces=xn.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*ja;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};xn.dividedBy=xn.div=function(t){return Im(this,new this.constructor(t))};xn.dividedToIntegerBy=xn.idiv=function(t){var e=this,n=e.constructor;return fa(Im(e,new n(t),0,1),n.precision)};xn.equals=xn.eq=function(t){return!this.cmp(t)};xn.exponent=function(){return Pi(this)};xn.greaterThan=xn.gt=function(t){return this.cmp(t)>0};xn.greaterThanOrEqualTo=xn.gte=function(t){return this.cmp(t)>=0};xn.isInteger=xn.isint=function(){return this.e>this.d.length-2};xn.isNegative=xn.isneg=function(){return this.s<0};xn.isPositive=xn.ispos=function(){return this.s>0};xn.isZero=function(){return this.s===0};xn.lessThan=xn.lt=function(t){return this.cmp(t)<0};xn.lessThanOrEqualTo=xn.lte=function(t){return this.cmp(t)<1};xn.logarithm=xn.log=function(t){var e,n=this,a=n.constructor,i=a.precision,s=i+5;if(t===void 0)t=new a(10);else if(t=new a(t),t.s<1||t.eq(bl))throw Error(Cc+"NaN");if(n.s<1)throw Error(Cc+(n.s?"NaN":"-Infinity"));return n.eq(bl)?new a(0):(Oa=!1,e=Im(aS(n,s),aS(t,s),s),Oa=!0,fa(e,i))};xn.minus=xn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?gre(e,t):hre(e,(t.s=-t.s,t))};xn.modulo=xn.mod=function(t){var e,n=this,a=n.constructor,i=a.precision;if(t=new a(t),!t.s)throw Error(Cc+"NaN");return n.s?(Oa=!1,e=Im(n,t,0,1).times(t),Oa=!0,n.minus(e)):fa(new a(n),i)};xn.naturalExponential=xn.exp=function(){return fre(this)};xn.naturalLogarithm=xn.ln=function(){return aS(this)};xn.negated=xn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};xn.plus=xn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?hre(e,t):gre(e,(t.s=-t.s,t))};xn.precision=xn.sd=function(t){var e,n,a,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(vg+t);if(e=Pi(i)+1,a=i.d.length-1,n=a*ja+1,a=i.d[a],a){for(;a%10==0;a/=10)n--;for(a=i.d[0];a>=10;a/=10)n++}return t&&e>n?e:n};xn.squareRoot=xn.sqrt=function(){var t,e,n,a,i,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(Cc+"NaN")}for(t=Pi(l),Oa=!1,i=Math.sqrt(+l),i==0||i==1/0?(e=ru(l.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=iv((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),a=new c(e)):a=new c(i.toString()),n=c.precision,i=o=n+3;;)if(s=a,a=s.plus(Im(l,s,o+2)).times(.5),ru(s.d).slice(0,o)===(e=ru(a.d)).slice(0,o)){if(e=e.slice(o-3,o+1),i==o&&e=="4999"){if(fa(s,n+1,0),s.times(s).eq(l)){a=s;break}}else if(e!="9999")break;o+=4}return Oa=!0,fa(a,n)};xn.times=xn.mul=function(t){var e,n,a,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,a=o;a--;)s.push(0);for(a=d;--a>=0;){for(e=0,i=c+a;i>a;)l=s[i]+f[a]*p[i-a-1]+e,s[i--]=l%as|0,e=l/as|0;s[i]=(s[i]+e)%as|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,Oa?fa(t,m.precision):t};xn.toDecimalPlaces=xn.todp=function(t,e){var n=this,a=n.constructor;return n=new a(n),t===void 0?n:(bu(t,0,av),e===void 0?e=a.rounding:bu(e,0,8),fa(n,t+Pi(n)+1,e))};xn.toExponential=function(t,e){var n,a=this,i=a.constructor;return t===void 0?n=Wg(a,!0):(bu(t,0,av),e===void 0?e=i.rounding:bu(e,0,8),a=fa(new i(a),t+1,e),n=Wg(a,!0,t+1)),n};xn.toFixed=function(t,e){var n,a,i=this,s=i.constructor;return t===void 0?Wg(i):(bu(t,0,av),e===void 0?e=s.rounding:bu(e,0,8),a=fa(new s(i),t+Pi(i)+1,e),n=Wg(a.abs(),!1,t+Pi(a)+1),i.isneg()&&!i.isZero()?"-"+n:n)};xn.toInteger=xn.toint=function(){var t=this,e=t.constructor;return fa(new e(t),Pi(t)+1,e.rounding)};xn.toNumber=function(){return+this};xn.toPower=xn.pow=function(t){var e,n,a,i,s,o,l=this,c=l.constructor,d=12,u=+(t=new c(t));if(!t.s)return new c(bl);if(l=new c(l),!l.s){if(t.s<1)throw Error(Cc+"Infinity");return l}if(l.eq(bl))return l;if(a=c.precision,t.eq(bl))return fa(l,a);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=u<0?-u:u)<=pre){for(i=new c(bl),e=Math.ceil(a/ja+4),Oa=!1;n%2&&(i=i.times(l),$9(i.d,e)),n=iv(n/2),n!==0;)l=l.times(l),$9(l.d,e);return Oa=!0,t.s<0?new c(bl).div(i):fa(i,a)}}else if(s<0)throw Error(Cc+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,Oa=!1,i=t.times(aS(l,a+d)),Oa=!0,i=fre(i),i.s=s,i};xn.toPrecision=function(t,e){var n,a,i=this,s=i.constructor;return t===void 0?(n=Pi(i),a=Wg(i,n<=s.toExpNeg||n>=s.toExpPos)):(bu(t,1,av),e===void 0?e=s.rounding:bu(e,0,8),i=fa(new s(i),t,e),n=Pi(i),a=Wg(i,t<=n||n<=s.toExpNeg,t)),a};xn.toSignificantDigits=xn.tosd=function(t,e){var n=this,a=n.constructor;return t===void 0?(t=a.precision,e=a.rounding):(bu(t,1,av),e===void 0?e=a.rounding:bu(e,0,8)),fa(new a(n),t,e)};xn.toString=xn.valueOf=xn.val=xn.toJSON=xn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=Pi(t),n=t.constructor;return Wg(t,e<=n.toExpNeg||e>=n.toExpPos)};function hre(t,e){var n,a,i,s,o,l,c,d,u=t.constructor,m=u.precision;if(!t.s||!e.s)return e.s||(e=new u(t)),Oa?fa(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?(a=c,s=-s,l=d.length):(a=d,i=o,l=c.length),o=Math.ceil(m/ja),l=o>l?o+1:l+1,s>l&&(s=l,a.length=1),a.reverse();s--;)a.push(0);a.reverse()}for(l=c.length,s=d.length,l-s<0&&(s=l,a=d,d=c,c=a),n=0;s;)n=(c[--s]=c[s]+d[s]+n)/as|0,c[s]%=as;for(n&&(c.unshift(n),++i),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=i,Oa?fa(e,m):e}function bu(t,e,n){if(t!==~~t||t<e||t>n)throw Error(vg+t)}function ru(t){var e,n,a,i=t.length-1,s="",o=t[0];if(i>0){for(s+=o,e=1;e<i;e++)a=t[e]+"",n=ja-a.length,n&&(s+=ih(n)),s+=a;o=t[e],a=o+"",n=ja-a.length,n&&(s+=ih(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}var Im=(function(){function t(a,i){var s,o=0,l=a.length;for(a=a.slice();l--;)s=a[l]*i+o,a[l]=s%as|0,o=s/as|0;return o&&a.unshift(o),a}function e(a,i,s,o){var l,c;if(s!=o)c=s>o?1:-1;else for(l=c=0;l<s;l++)if(a[l]!=i[l]){c=a[l]>i[l]?1:-1;break}return c}function n(a,i,s){for(var o=0;s--;)a[s]-=o,o=a[s]<i[s]?1:0,a[s]=o*as+a[s]-i[s];for(;!a[0]&&a.length>1;)a.shift()}return function(a,i,s,o){var l,c,d,u,m,p,f,g,w,b,x,S,k,C,P,T,A,F,_=a.constructor,M=a.s==i.s?1:-1,H=a.d,I=i.d;if(!a.s)return new _(a);if(!i.s)throw Error(Cc+"Division by zero");for(c=a.e-i.e,A=I.length,P=H.length,f=new _(M),g=f.d=[],d=0;I[d]==(H[d]||0);)++d;if(I[d]>(H[d]||0)&&--c,s==null?S=s=_.precision:o?S=s+(Pi(a)-Pi(i))+1:S=s,S<0)return new _(0);if(S=S/ja+2|0,d=0,A==1)for(u=0,I=I[0],S++;(d<P||u)&&S--;d++)k=u*as+(H[d]||0),g[d]=k/I|0,u=k%I|0;else{for(u=as/(I[0]+1)|0,u>1&&(I=t(I,u),H=t(H,u),A=I.length,P=H.length),C=A,w=H.slice(0,A),b=w.length;b<A;)w[b++]=0;F=I.slice(),F.unshift(0),T=I[0],I[1]>=as/2&&++T;do u=0,l=e(I,w,A,b),l<0?(x=w[0],A!=b&&(x=x*as+(w[1]||0)),u=x/T|0,u>1?(u>=as&&(u=as-1),m=t(I,u),p=m.length,b=w.length,l=e(m,w,p,b),l==1&&(u--,n(m,A<p?F:I,p))):(u==0&&(l=u=1),m=I.slice()),p=m.length,p<b&&m.unshift(0),n(w,m,b),l==-1&&(b=w.length,l=e(I,w,A,b),l<1&&(u++,n(w,A<b?F:I,b))),b=w.length):l===0&&(u++,w=[0]),g[d++]=u,l&&w[0]?w[b++]=H[C]||0:(w=[H[C]],b=1);while((C++<P||w[0]!==void 0)&&S--)}return g[0]||g.shift(),f.e=c,fa(f,o?s+Pi(f)+1:s)}})();function fre(t,e){var n,a,i,s,o,l,c=0,d=0,u=t.constructor,m=u.precision;if(Pi(t)>16)throw Error(sz+Pi(t));if(!t.s)return new u(bl);for(Oa=!1,l=m,o=new u(.03125);t.abs().gte(.1);)t=t.times(o),d+=5;for(a=Math.log(Xf(2,d))/Math.LN10*2+5|0,l+=a,n=i=s=new u(bl),u.precision=l;;){if(i=fa(i.times(t),l),n=n.times(++c),o=s.plus(Im(i,n,l)),ru(o.d).slice(0,l)===ru(s.d).slice(0,l)){for(;d--;)s=fa(s.times(s),l);return u.precision=m,e==null?(Oa=!0,fa(s,m)):s}s=o}}function Pi(t){for(var e=t.e*ja,n=t.d[0];n>=10;n/=10)e++;return e}function WD(t,e,n){if(e>t.LN10.sd())throw Oa=!0,n&&(t.precision=n),Error(Cc+"LN10 precision limit exceeded");return fa(new t(t.LN10),e)}function ih(t){for(var e="";t--;)e+="0";return e}function aS(t,e){var n,a,i,s,o,l,c,d,u,m=1,p=10,f=t,g=f.d,w=f.constructor,b=w.precision;if(f.s<1)throw Error(Cc+(f.s?"NaN":"-Infinity"));if(f.eq(bl))return new w(0);if(e==null?(Oa=!1,d=b):d=e,f.eq(10))return e==null&&(Oa=!0),WD(w,d);if(d+=p,w.precision=d,n=ru(g),a=n.charAt(0),s=Pi(f),Math.abs(s)<15e14){for(;a<7&&a!=1||a==1&&n.charAt(1)>3;)f=f.times(t),n=ru(f.d),a=n.charAt(0),m++;s=Pi(f),a>1?(f=new w("0."+n),s++):f=new w(a+"."+n.slice(1))}else return c=WD(w,d+2,b).times(s+""),f=aS(new w(a+"."+n.slice(1)),d-p).plus(c),w.precision=b,e==null?(Oa=!0,fa(f,b)):f;for(l=o=f=Im(f.minus(bl),f.plus(bl),d),u=fa(f.times(f),d),i=3;;){if(o=fa(o.times(u),d),c=l.plus(Im(o,new w(i),d)),ru(c.d).slice(0,d)===ru(l.d).slice(0,d))return l=l.times(2),s!==0&&(l=l.plus(WD(w,d+2,b).times(s+""))),l=Im(l,new w(m),d),w.precision=b,e==null?(Oa=!0,fa(l,b)):l;l=c,i+=2}}function q9(t,e){var n,a,i;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(a=e.search(/e/i))>0?(n<0&&(n=a),n+=+e.slice(a+1),e=e.substring(0,a)):n<0&&(n=e.length),a=0;e.charCodeAt(a)===48;)++a;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(a,i),e){if(i-=a,n=n-a-1,t.e=iv(n/ja),t.d=[],a=(n+1)%ja,n<0&&(a+=ja),a<i){for(a&&t.d.push(+e.slice(0,a)),i-=ja;a<i;)t.d.push(+e.slice(a,a+=ja));e=e.slice(a),a=ja-e.length}else a-=i;for(;a--;)e+="0";if(t.d.push(+e),Oa&&(t.e>aP||t.e<-aP))throw Error(sz+n)}else t.s=0,t.e=0,t.d=[0];return t}function fa(t,e,n){var a,i,s,o,l,c,d,u,m=t.d;for(o=1,s=m[0];s>=10;s/=10)o++;if(a=e-o,a<0)a+=ja,i=e,d=m[u=0];else{if(u=Math.ceil((a+1)/ja),s=m.length,u>=s)return t;for(d=s=m[u],o=1;s>=10;s/=10)o++;a%=ja,i=a-ja+o}if(n!==void 0&&(s=Xf(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&&(a>0?i>0?d/Xf(10,o-i):0:m[u-1])%10&1||n==(t.s<0?8:7))),e<1||!m[0])return c?(s=Pi(t),m.length=1,e=e-s-1,m[0]=Xf(10,(ja-e%ja)%ja),t.e=iv(-e/ja)||0):(m.length=1,m[0]=t.e=t.s=0),t;if(a==0?(m.length=u,s=1,u--):(m.length=u+1,s=Xf(10,ja-a),m[u]=i>0?(d/Xf(10,o-i)%Xf(10,i)|0)*s:0),c)for(;;)if(u==0){(m[0]+=s)==as&&(m[0]=1,++t.e);break}else{if(m[u]+=s,m[u]!=as)break;m[u--]=0,s=1}for(a=m.length;m[--a]===0;)m.pop();if(Oa&&(t.e>aP||t.e<-aP))throw Error(sz+Pi(t));return t}function gre(t,e){var n,a,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),Oa?fa(e,f):e;if(c=t.d,m=e.d,a=e.e,d=t.e,c=c.slice(),o=d-a,o){for(u=o<0,u?(n=c,o=-o,l=m.length):(n=m,a=d,l=c.length),i=Math.max(Math.ceil(f/ja),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]=as-1;--c[s],c[i]+=as}c[i]-=m[i]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--a;return c[0]?(e.d=c,e.e=a,Oa?fa(e,f):e):new p(0)}function Wg(t,e,n){var a,i=Pi(t),s=ru(t.d),o=s.length;return e?(n&&(a=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+ih(a):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(i<0?"e":"e+")+i):i<0?(s="0."+ih(-i-1)+s,n&&(a=n-o)>0&&(s+=ih(a))):i>=o?(s+=ih(i+1-o),n&&(a=n-i-1)>0&&(s=s+"."+ih(a))):((a=i+1)<o&&(s=s.slice(0,a)+"."+s.slice(a)),n&&(a=n-o)>0&&(i+1===o&&(s+="."),s+=ih(a))),t.s<0?"-"+s:s}function $9(t,e){if(t.length>e)return t.length=e,!0}function bre(t){var e,n,a;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(vg+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 q9(o,s.toString())}else if(typeof s!="string")throw Error(vg+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,W4e.test(s))q9(o,s);else throw Error(vg+s)}if(i.prototype=xn,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=bre,i.config=i.set=K4e,t===void 0&&(t={}),t)for(a=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e<a.length;)t.hasOwnProperty(n=a[e++])||(t[n]=this[n]);return i.config(t),i}function K4e(t){if(!t||typeof t!="object")throw Error(Cc+"Object expected");var e,n,a,i=["precision",1,av,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e<i.length;e+=3)if((a=t[n=i[e]])!==void 0)if(iv(a)===a&&a>=i[e+1]&&a<=i[e+2])this[n]=a;else throw Error(vg+n+": "+a);if((a=t[n="LN10"])!==void 0)if(a==Math.LN10)this[n]=new this(a);else throw Error(vg+n+": "+a);return this}var oz=bre(G4e);bl=new oz(1);const Xr=oz;function xre(t){var e;return t===0?e=1:e=Math.floor(new Xr(t).abs().log(10).toNumber())+1,e}function yre(t,e,n){for(var a=new Xr(t),i=0,s=[];a.lt(e)&&i<1e5;)s.push(a.toNumber()),a=a.add(n),i++;return s}var vre=t=>{var[e,n]=t,[a,i]=[e,n];return e>n&&([a,i]=[n,e]),[a,i]},wre=(t,e,n)=>{if(t.lte(0))return new Xr(0);var a=xre(t.toNumber()),i=new Xr(10).pow(a),s=t.div(i),o=a!==1?.05:.1,l=new Xr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(i);return e?new Xr(c.toNumber()):new Xr(Math.ceil(c.toNumber()))},Q4e=(t,e,n)=>{var a=new Xr(1),i=new Xr(t);if(!i.isint()&&n){var s=Math.abs(t);s<1?(a=new Xr(10).pow(xre(t)-1),i=new Xr(Math.floor(i.div(a).toNumber())).mul(a)):s>1&&(i=new Xr(Math.floor(t)))}else t===0?i=new Xr(Math.floor((e-1)/2)):n||(i=new Xr(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c<e;c++)l.push(i.add(new Xr(c-o).mul(a)).toNumber());return l},Sre=function(e,n,a,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(a-1)))return{step:new Xr(0),tickMin:new Xr(0),tickMax:new Xr(0)};var o=wre(new Xr(n).sub(e).div(a-1),i,s),l;e<=0&&n>=0?l=new Xr(0):(l=new Xr(e).add(n).div(2),l=l.sub(new Xr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),d=Math.ceil(new Xr(n).sub(l).div(o).toNumber()),u=c+d+1;return u>a?Sre(e,n,a,i,s+1):(u<a&&(d=n>0?d+(a-u):d,c=n>0?c:c+(a-u)),{step:o,tickMin:l.sub(new Xr(c).mul(o)),tickMax:l.add(new Xr(d).mul(o))})},Y4e=function(e){var[n,a]=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]=vre([n,a]);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>a?d.reverse():d}if(l===c)return Q4e(l,i,s);var{step:u,tickMin:m,tickMax:p}=Sre(l,c,o,s,0),f=yre(m,p.add(new Xr(.1).mul(u)),u);return n>a?f.reverse():f},X4e=function(e,n){var[a,i]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=vre([a,i]);if(o===-1/0||l===1/0)return[a,i];if(o===l)return[o];var c=Math.max(n,2),d=wre(new Xr(l).sub(o).div(c-1),s,0),u=[...yre(new Xr(o),new Xr(l),d),l];return s===!1&&(u=u.map(m=>Math.round(m))),a>i?u.reverse():u},_re=t=>t.rootProps.maxBarSize,Z4e=t=>t.rootProps.barGap,kre=t=>t.rootProps.barCategoryGap,J4e=t=>t.rootProps.barSize,t_=t=>t.rootProps.stackOffset,Nre=t=>t.rootProps.reverseStackOrder,lz=t=>t.options.chartName,cz=t=>t.rootProps.syncId,Cre=t=>t.rootProps.syncMethod,dz=t=>t.options.eventEmitter,eze=t=>t.rootProps.baseValue,ii={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},qf={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},zd={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},hA=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function fA(t,e,n){if(n!=="auto")return n;if(t!=null)return vd(t,e)?"category":"number"}function V9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function iP(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?V9(Object(n),!0).forEach(function(a){tze(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):V9(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function tze(t,e,n){return(e=nze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function nze(t){var e=rze(t,"string");return typeof e=="symbol"?e:e+""}function rze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var G9={allowDataOverflow:qf.allowDataOverflow,allowDecimals:qf.allowDecimals,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:qf.angleAxisId,includeHidden:!1,name:void 0,reversed:qf.reversed,scale:qf.scale,tick:qf.tick,tickCount:void 0,ticks:void 0,type:qf.type,unit:void 0},W9={allowDataOverflow:zd.allowDataOverflow,allowDecimals:zd.allowDecimals,allowDuplicatedCategory:zd.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:zd.radiusAxisId,includeHidden:zd.includeHidden,name:void 0,reversed:zd.reversed,scale:zd.scale,tick:zd.tick,tickCount:zd.tickCount,ticks:void 0,type:zd.type,unit:void 0},aze=(t,e)=>{if(e!=null)return t.polarAxis.angleAxis[e]},uz=Pt([aze,dne],(t,e)=>{var n;if(t!=null)return t;var a=(n=fA(e,"angleAxis",G9.type))!==null&&n!==void 0?n:"category";return iP(iP({},G9),{},{type:a})}),ize=(t,e)=>t.polarAxis.radiusAxis[e],mz=Pt([ize,dne],(t,e)=>{var n;if(t!=null)return t;var a=(n=fA(e,"radiusAxis",W9.type))!==null&&n!==void 0?n:"category";return iP(iP({},W9),{},{type:a})}),gA=t=>t.polarOptions,pz=Pt([rp,ap,qi],Pne),Pre=Pt([gA,pz],(t,e)=>{if(t!=null)return no(t.innerRadius,e,0)}),Tre=Pt([gA,pz],(t,e)=>{if(t!=null)return no(t.outerRadius,e,e*.8)}),sze=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},Are=Pt([gA],sze);Pt([uz,Are],hA);var jre=Pt([pz,Pre,Tre],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});Pt([mz,jre],hA);var Mre=Pt([jr,gA,Pre,Tre,rp,ap],(t,e,n,a,i,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||a==null)){var{cx:o,cy:l,startAngle:c,endAngle:d}=e;return{cx:no(o,i,i/2),cy:no(l,s,s/2),innerRadius:n,outerRadius:a,startAngle:c,endAngle:d,clockWise:!1}}}),Ga=(t,e)=>e,n_=(t,e,n)=>n;function bA(t){return t?.id}function Ere(t,e,n){var{chartData:a=[]}=e,{allowDuplicatedCategory:i,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,d=(c=l.data)!==null&&c!==void 0?c:a;if(!(d==null||d.length===0)){var u=bA(l);d.forEach((m,p)=>{var f=s==null||i?p:String(Gr(m,s,null)),g=Gr(m,l.dataKey,0),w;o.has(f)?w=o.get(f):w={},Object.assign(w,{[u]:g}),o.set(f,w)})}}),Array.from(o.values())}function xA(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var yA=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function vA(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function oze(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 xs=t=>{var e=jr(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},sv=t=>t.tooltip.settings.axisId;function lze(t){if(t in z0)return z0[t]();var e="scale".concat(HS(t));if(e in z0)return z0[e]()}function K9(t){var e=t.ticks,n=t.bandwidth,a=t.range(),i=[Math.min(...a),Math.max(...a)];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 Q9(t,e,n){if(typeof t=="function")return K9(t.copy().domain(e).range(n));if(t!=null){var a=lze(t);if(a!=null)return a.domain(e).range(n),K9(a)}}var Dre=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!ep(e)){for(var n,a,i=0;i<e.length;i++){var s=e[i];Kn(s)&&((n===void 0||s<n)&&(n=s),(a===void 0||s>a)&&(a=s))}return n!==void 0&&a!==void 0?[n,a]:void 0}return e}default:return e}};function Y9(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function sP(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Y9(Object(n),!0).forEach(function(a){cze(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Y9(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function cze(t,e,n){return(e=dze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function dze(t){var e=uze(t,"string");return typeof e=="symbol"?e:e+""}function uze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var $R=[0,"auto"],ts={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},Fre=(t,e)=>t.cartesianAxis.xAxis[e],ku=(t,e)=>{var n=Fre(t,e);return n??ts},ns={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:GS},Lre=(t,e)=>t.cartesianAxis.yAxis[e],Nu=(t,e)=>{var n=Lre(t,e);return n??ns},mze={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:""},hz=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??mze},oi=(t,e,n)=>{switch(e){case"xAxis":return ku(t,n);case"yAxis":return Nu(t,n);case"zAxis":return hz(t,n);case"angleAxis":return uz(t,n);case"radiusAxis":return mz(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},pze=(t,e,n)=>{switch(e){case"xAxis":return ku(t,n);case"yAxis":return Nu(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},ov=(t,e,n)=>{switch(e){case"xAxis":return ku(t,n);case"yAxis":return Nu(t,n);case"angleAxis":return uz(t,n);case"radiusAxis":return mz(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},Rre=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function fz(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 r_=t=>t.graphicalItems.cartesianItems,hze=Pt([Ga,n_],fz),gz=(t,e,n)=>t.filter(n).filter(a=>e?.includeHidden===!0?!0:!a.hide),a_=Pt([r_,oi,hze],gz,{memoizeOptions:{resultEqualityCheck:vA}}),Ire=Pt([a_],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(xA)),Ore=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),fze=Pt([a_],Ore),bz=t=>t.map(e=>e.data).filter(Boolean).flat(1),gze=Pt([a_],bz,{memoizeOptions:{resultEqualityCheck:vA}}),xz=(t,e)=>{var{chartData:n=[],dataStartIndex:a,dataEndIndex:i}=e;return t.length>0?t:n.slice(a,i+1)},yz=Pt([gze,iz],xz),vz=(t,e,n)=>e?.dataKey!=null?t.map(a=>({value:Gr(a,e.dataKey)})):n.length>0?n.map(a=>a.dataKey).flatMap(a=>t.map(i=>({value:Gr(i,a)}))):t.map(a=>({value:a})),wA=Pt([yz,oi,a_],vz);function zre(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function EN(t){if(kc(t)||t instanceof Date){var e=Number(t);if(Kn(e))return e}}function X9(t){if(Array.isArray(t)){var e=[EN(t[0]),EN(t[1])];return ep(e)?e:void 0}var n=EN(t);if(n!=null)return[n,n]}function tp(t){return t.map(EN).filter(Vo)}function bze(t,e,n){return!n||typeof e!="number"||hd(e)?[]:n.length?tp(n.flatMap(a=>{var i=Gr(t,a.dataKey),s,o;if(Array.isArray(i)?[s,o]=i:s=o=i,!(!Kn(s)||!Kn(o)))return[e-s,e+o]})):[]}var Gi=t=>{var e=xs(t),n=sv(t);return ov(t,e,n)},i_=Pt([Gi],t=>t?.dataKey),xze=Pt([Ire,iz,Gi],Ere),Ure=(t,e,n,a)=>{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=a?[...c].reverse():c,u=d.map(bA);return[l,{stackedData:zFe(t,u,n),graphicalItems:d}]}))},oP=Pt([xze,Ire,t_,Nre],Ure),Bre=(t,e,n,a)=>{var{dataStartIndex:i,dataEndIndex:s}=e;if(a==null&&n!=="zAxis"){var o=qFe(t,i,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},yze=Pt([oi],t=>t.allowDataOverflow),wz=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=tp(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},Sz=Pt([oi],wz),_z=Pt([Sz,yze],mre),vze=Pt([oP,sp,Ga,_z],Bre,{memoizeOptions:{resultEqualityCheck:yA}}),SA=t=>t.errorBars,wze=(t,e,n)=>t.flatMap(a=>e[a.id]).filter(Boolean).filter(a=>zre(n,a)),lP=function(){for(var e=arguments.length,n=new Array(e),a=0;a<e;a++)n[a]=arguments[a];var i=n.filter(Boolean);if(i.length!==0){var s=i.flat(),o=Math.min(...s),l=Math.max(...s);return[o,l]}},kz=(t,e,n,a,i)=>{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var d,u,m=(d=a[c.id])===null||d===void 0?void 0:d.filter(x=>zre(i,x)),p=Gr(l,(u=e.dataKey)!==null&&u!==void 0?u:c.dataKey),f=bze(l,p,m);if(f.length>=2){var g=Math.min(...f),w=Math.max(...f);(s==null||g<s)&&(s=g),(o==null||w>o)&&(o=w)}var b=X9(p);b!=null&&(s=s==null?b[0]:Math.min(s,b[0]),o=o==null?b[1]:Math.max(o,b[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=X9(Gr(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]))}),Kn(s)&&Kn(o))return[s,o]},Sze=Pt([yz,oi,fze,SA,Ga],kz,{memoizeOptions:{resultEqualityCheck:yA}});function _ze(t){var{value:e}=t;if(kc(e)||e instanceof Date)return e}var kze=(t,e,n)=>{var a=t.map(_ze).filter(i=>i!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&ite(a))?Mne(0,t.length):e.allowDuplicatedCategory?a:Array.from(new Set(a))},Hre=t=>t.referenceElements.dots,lv=(t,e,n)=>t.filter(a=>a.ifOverflow==="extendDomain").filter(a=>e==="xAxis"?a.xAxisId===n:a.yAxisId===n),Nze=Pt([Hre,Ga,n_],lv),qre=t=>t.referenceElements.areas,Cze=Pt([qre,Ga,n_],lv),$re=t=>t.referenceElements.lines,Pze=Pt([$re,Ga,n_],lv),Vre=(t,e)=>{if(t!=null){var n=tp(t.map(a=>e==="xAxis"?a.x:a.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},Tze=Pt(Nze,Ga,Vre),Gre=(t,e)=>{if(t!=null){var n=tp(t.flatMap(a=>[e==="xAxis"?a.x1:a.y1,e==="xAxis"?a.x2:a.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},Aze=Pt([Cze,Ga],Gre);function jze(t){var e;if(t.x!=null)return tp([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(a=>a.x);return n==null||n.length===0?[]:tp(n)}function Mze(t){var e;if(t.y!=null)return tp([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(a=>a.y);return n==null||n.length===0?[]:tp(n)}var Wre=(t,e)=>{if(t!=null){var n=t.flatMap(a=>e==="xAxis"?jze(a):Mze(a));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},Eze=Pt([Pze,Ga],Wre),Dze=Pt(Tze,Eze,Aze,(t,e,n)=>lP(t,n,e)),Nz=(t,e,n,a,i,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",d=c?lP(a,s,i):lP(s,i);return V4e(e,d,t.allowDataOverflow)},Fze=Pt([oi,Sz,_z,vze,Sze,Dze,jr,Ga],Nz,{memoizeOptions:{resultEqualityCheck:yA}}),Lze=[0,1],Cz=(t,e,n,a,i,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,d=vd(e,s);if(d&&l==null){var u;return Mne(0,(u=n?.length)!==null&&u!==void 0?u:0)}return c==="category"?kze(a,t,d):i==="expand"?Lze:o}},Pz=Pt([oi,jr,yz,wA,t_,Ga,Fze],Cz);function Rze(t){return t in z0}var Kre=(t,e,n)=>{if(t!=null){var{scale:a,type:i}=t;if(a==="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 a=="string"){var s="scale".concat(HS(a));return Rze(s)?s:"point"}}},df=Pt([oi,Rre,lz],Kre);function Tz(t,e,n,a){if(!(n==null||a==null))return typeof t.scale=="function"?Q9(t.scale,n,a):Q9(e,n,a)}var Az=(t,e,n)=>{var a=wz(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(a)&&(a[0]==="auto"||a[1]==="auto")&&ep(t))return Y4e(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&ep(t))return X4e(t,e.tickCount,e.allowDecimals)}},jz=Pt([Pz,ov,df],Az),Mz=(t,e,n,a)=>{if(a!=="angleAxis"&&t?.type==="number"&&ep(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},Ize=Pt([oi,Pz,jz,Ga],Mz),Oze=Pt(wA,oi,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,a=Array.from(tp(t.map(m=>m.value))).sort((m,p)=>m-p),i=a[0],s=a[a.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<a.length-1;l++){var c=a[l],d=a[l+1];if(!(c==null||d==null)){var u=d-c;n=Math.min(n,u)}}return n/o}}),Qre=Pt(Oze,jr,kre,qi,(t,e,n,a,i)=>i,(t,e,n,a,i)=>{if(!Kn(t))return 0;var s=e==="vertical"?a.height:a.width;if(i==="gap")return t*s/2;if(i==="no-gap"){var o=no(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),zze=(t,e,n)=>{var a=ku(t,e);return a==null||typeof a.padding!="string"?0:Qre(t,"xAxis",e,n,a.padding)},Uze=(t,e,n)=>{var a=Nu(t,e);return a==null||typeof a.padding!="string"?0:Qre(t,"yAxis",e,n,a.padding)},Bze=Pt(ku,zze,(t,e)=>{var n,a;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:((a=i.right)!==null&&a!==void 0?a:0)+e}}),Hze=Pt(Nu,Uze,(t,e)=>{var n,a;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:((a=i.bottom)!==null&&a!==void 0?a:0)+e}}),qze=Pt([qi,Bze,rA,nA,(t,e,n)=>n],(t,e,n,a,i)=>{var{padding:s}=a;return i?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),$ze=Pt([qi,jr,Hze,rA,nA,(t,e,n)=>n],(t,e,n,a,i,s)=>{var{padding:o}=i;return s?[a.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]}),s_=(t,e,n,a)=>{var i;switch(e){case"xAxis":return qze(t,n,a);case"yAxis":return $ze(t,n,a);case"zAxis":return(i=hz(t,n))===null||i===void 0?void 0:i.range;case"angleAxis":return Are(t);case"radiusAxis":return jre(t,n);default:return}},Yre=Pt([oi,s_],hA),Vze=Pt([df,Ize],Dre),Fy=Pt([oi,df,Vze,Yre],Tz);Pt([a_,SA,Ga],wze);function Xre(t,e){return t.id<e.id?-1:t.id>e.id?1:0}var _A=(t,e)=>e,kA=(t,e,n)=>n,Gze=Pt(eA,_A,kA,(t,e,n)=>t.filter(a=>a.orientation===e).filter(a=>a.mirror===n).sort(Xre)),Wze=Pt(tA,_A,kA,(t,e,n)=>t.filter(a=>a.orientation===e).filter(a=>a.mirror===n).sort(Xre)),Zre=(t,e)=>({width:t.width,height:e.height}),Kze=(t,e)=>{var n=typeof e.width=="number"?e.width:GS;return{width:n,height:t.height}},Jre=Pt(qi,ku,Zre),Qze=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},Yze=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},Xze=Pt(ap,qi,Gze,_A,kA,(t,e,n,a,i)=>{var s={},o;return n.forEach(l=>{var c=Zre(e,l);o==null&&(o=Qze(e,a,t));var d=a==="top"&&!i||a==="bottom"&&i;s[l.id]=o-Number(d)*c.height,o+=(d?-1:1)*c.height}),s}),Zze=Pt(rp,qi,Wze,_A,kA,(t,e,n,a,i)=>{var s={},o;return n.forEach(l=>{var c=Kze(e,l);o==null&&(o=Yze(e,a,t));var d=a==="left"&&!i||a==="right"&&i;s[l.id]=o-Number(d)*c.width,o+=(d?-1:1)*c.width}),s}),Jze=(t,e)=>{var n=ku(t,e);if(n!=null)return Xze(t,n.orientation,n.mirror)},e5e=Pt([qi,ku,Jze,(t,e)=>e],(t,e,n,a)=>{if(e!=null){var i=n?.[a];return i==null?{x:t.left,y:0}:{x:t.left,y:i}}}),t5e=(t,e)=>{var n=Nu(t,e);if(n!=null)return Zze(t,n.orientation,n.mirror)},n5e=Pt([qi,Nu,t5e,(t,e)=>e],(t,e,n,a)=>{if(e!=null){var i=n?.[a];return i==null?{x:0,y:t.top}:{x:i,y:t.top}}}),eae=Pt(qi,Nu,(t,e)=>{var n=typeof e.width=="number"?e.width:GS;return{width:n,height:t.height}}),Z9=(t,e,n)=>{switch(e){case"xAxis":return Jre(t,n).width;case"yAxis":return eae(t,n).height;default:return}},tae=(t,e,n,a)=>{if(n!=null){var{allowDuplicatedCategory:i,type:s,dataKey:o}=n,l=vd(t,a),c=e.map(d=>d.value);if(o&&l&&s==="category"&&i&&ite(c))return c}},Ez=Pt([jr,wA,oi,Ga],tae),nae=(t,e,n,a)=>{if(!(n==null||n.dataKey==null)){var{type:i,scale:s}=n,o=vd(t,a);if(o&&(i==="number"||s!=="auto"))return e.map(l=>l.value)}},Dz=Pt([jr,wA,ov,Ga],nae),J9=Pt([jr,pze,df,Fy,Ez,Dz,s_,jz,Ga],(t,e,n,a,i,s,o,l,c)=>{if(e!=null){var d=vd(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:a}}}),r5e=(t,e,n,a,i,s,o,l,c)=>{if(!(e==null||a==null)){var d=vd(t,c),{type:u,ticks:m,tickCount:p}=e,f=n==="scaleBand"&&typeof a.bandwidth=="function"?a.bandwidth()/2:2,g=u==="category"&&a.bandwidth?a.bandwidth()/f:0;g=c==="angleAxis"&&s!=null&&s.length>=2?us(s[0]-s[1])*2*g:g;var w=m||i;return w?w.map((b,x)=>{var S=o?o.indexOf(b):b,k=a.map(S);return Kn(k)?{index:x,coordinate:k+g,value:b,offset:g}:null}).filter(Vo):d&&l?l.map((b,x)=>{var S=a.map(b);return Kn(S)?{coordinate:S+g,value:b,index:x,offset:g}:null}).filter(Vo):a.ticks?a.ticks(p).map((b,x)=>{var S=a.map(b);return Kn(S)?{coordinate:S+g,value:b,index:x,offset:g}:null}).filter(Vo):a.domain().map((b,x)=>{var S=a.map(b);return Kn(S)?{coordinate:S+g,value:o?o[b]:b,index:x,offset:g}:null}).filter(Vo)}},rae=Pt([jr,ov,df,Fy,jz,s_,Ez,Dz,Ga],r5e),a5e=(t,e,n,a,i,s,o)=>{if(!(e==null||n==null||a==null||a[0]===a[1])){var l=vd(t,o),{tickCount:c}=e,d=0;return d=o==="angleAxis"&&a?.length>=2?us(a[0]-a[1])*2*d:d,l&&s?s.map((u,m)=>{var p=n.map(u);return Kn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(Vo):n.ticks?n.ticks(c).map((u,m)=>{var p=n.map(u);return Kn(p)?{coordinate:p+d,value:u,index:m,offset:d}:null}).filter(Vo):n.domain().map((u,m)=>{var p=n.map(u);return Kn(p)?{coordinate:p+d,value:i?i[u]:u,index:m,offset:d}:null}).filter(Vo)}},xu=Pt([jr,ov,Fy,s_,Ez,Dz,Ga],a5e),yu=Pt(oi,Fy,(t,e)=>{if(!(t==null||e==null))return sP(sP({},t),{},{scale:e})}),i5e=Pt([oi,df,Pz,Yre],Tz);Pt((t,e,n)=>hz(t,n),i5e,(t,e)=>{if(!(t==null||e==null))return sP(sP({},t),{},{scale:e})});var s5e=Pt([jr,eA,tA],(t,e,n)=>{switch(t){case"horizontal":return e.some(a=>a.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(a=>a.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),aae=t=>t.options.defaultTooltipEventType,iae=t=>t.options.validateTooltipEventTypes;function sae(t,e,n){if(t==null)return e;var a=t?"axis":"item";return n==null?e:n.includes(a)?a:e}function Fz(t,e){var n=aae(t),a=iae(t);return sae(e,n,a)}function o5e(t){return bn(e=>Fz(e,t))}var oae=(t,e)=>{var n,a=Number(e);if(!(hd(a)||e==null))return a>=0?t==null||(n=t[a])===null||n===void 0?void 0:n.value:void 0},l5e=t=>t.tooltip.settings,mh={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},c5e={itemInteraction:{click:mh,hover:mh},axisInteraction:{click:mh,hover:mh},keyboardInteraction:mh,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}},lae=Jo({name:"tooltip",initialState:c5e,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:Ra()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:a}=e.payload,i=ud(t).tooltipItemPayloads.indexOf(n);i>-1&&(t.tooltipItemPayloads[i]=a)},prepare:Ra()},removeTooltipEntrySettings:{reducer(t,e){var n=ud(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:Ra()},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:d5e,replaceTooltipEntrySettings:u5e,removeTooltipEntrySettings:m5e,setTooltipSettingsState:p5e,setActiveMouseOverItemIndex:cae,mouseLeaveItem:h5e,mouseLeaveChart:dae,setActiveClickItemIndex:f5e,setMouseOverAxisIndex:uae,setMouseClickAxisIndex:g5e,setSyncInteraction:VR,setKeyboardInteraction:GR}=lae.actions,b5e=lae.reducer;function eW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function B1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?eW(Object(n),!0).forEach(function(a){x5e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):eW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function x5e(t,e,n){return(e=y5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y5e(t){var e=v5e(t,"string");return typeof e=="symbol"?e:e+""}function v5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function w5e(t,e,n){return e==="axis"?n==="click"?t.axisInteraction.click:t.axisInteraction.hover:n==="click"?t.itemInteraction.click:t.itemInteraction.hover}function S5e(t){return t.index!=null}var mae=(t,e,n,a)=>{if(e==null)return mh;var i=w5e(t,e,n);if(i==null)return mh;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(S5e(i)){if(s)return B1(B1({},i),{},{active:!0})}else if(a!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:a,graphicalItemId:void 0};return B1(B1({},mh),{},{coordinate:i.coordinate})};function _5e(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 k5e(t,e){var n=_5e(t),a=e[0],i=e[1];if(n===void 0)return!1;var s=Math.min(a,i),o=Math.max(a,i);return n>=s&&n<=o}function N5e(t,e,n){if(n==null||e==null)return!0;var a=Gr(t,e);return a==null||!ep(n)?!0:k5e(a,n)}var Lz=(t,e,n,a)=>{var i=t?.index;if(i==null)return null;var s=Number(i);if(!Kn(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||N5e(d,n,a)?String(c):null},pae=(t,e,n,a,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:(a.top+e)/2}:{x:(a.left+t)/2,y:d.coordinate}}},hae=(t,e,n,a)=>{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&&a!=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})},fae=t=>t.options.tooltipPayloadSearcher,cv=t=>t.tooltip;function tW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function nW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?tW(Object(n),!0).forEach(function(a){C5e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):tW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}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 a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function A5e(t,e){return t??e}var gae=(t,e,n,a,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 g,{dataDefinedOnItem:w,settings:b}=f,x=A5e(w,l),S=Array.isArray(x)?Jte(x,d,u):x,k=(g=b?.dataKey)!==null&&g!==void 0?g:a,C=b?.nameKey,P;if(a&&Array.isArray(S)&&!Array.isArray(S[0])&&o==="axis"?P=ste(S,a,i):P=s(S,e,c,C),Array.isArray(P))P.forEach(A=>{var F=nW(nW({},b),{},{name:A.name,unit:A.unit,color:void 0,fill:void 0});p.push(e7({tooltipEntrySettings:F,dataKey:A.dataKey,payload:A.payload,value:Gr(A.payload,A.dataKey),name:A.name}))});else{var T;p.push(e7({tooltipEntrySettings:b,dataKey:k,payload:P,value:Gr(P,k),name:(T=Gr(P,C))!==null&&T!==void 0?T:b?.name}))}return p},m)}},Rz=Pt([Gi,Rre,lz],Kre),j5e=Pt([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),M5e=Pt([xs,sv],fz),dv=Pt([j5e,Gi,M5e],gz,{memoizeOptions:{resultEqualityCheck:vA}}),E5e=Pt([dv],t=>t.filter(xA)),D5e=Pt([dv],bz,{memoizeOptions:{resultEqualityCheck:vA}}),uv=Pt([D5e,sp],xz),F5e=Pt([E5e,sp,Gi],Ere),Iz=Pt([uv,Gi,dv],vz),bae=Pt([Gi],wz),L5e=Pt([Gi],t=>t.allowDataOverflow),xae=Pt([bae,L5e],mre),R5e=Pt([dv],t=>t.filter(xA)),I5e=Pt([F5e,R5e,t_,Nre],Ure),O5e=Pt([I5e,sp,xs,xae],Bre),z5e=Pt([dv],Ore),U5e=Pt([uv,Gi,z5e,SA,xs],kz,{memoizeOptions:{resultEqualityCheck:yA}}),B5e=Pt([Hre,xs,sv],lv),H5e=Pt([B5e,xs],Vre),q5e=Pt([qre,xs,sv],lv),$5e=Pt([q5e,xs],Gre),V5e=Pt([$re,xs,sv],lv),G5e=Pt([V5e,xs],Wre),W5e=Pt([H5e,G5e,$5e],lP),K5e=Pt([Gi,bae,xae,O5e,U5e,W5e,jr,xs],Nz),o_=Pt([Gi,jr,uv,Iz,t_,xs,K5e],Cz),Q5e=Pt([o_,Gi,Rz],Az),Y5e=Pt([Gi,o_,Q5e,xs],Mz),yae=t=>{var e=xs(t),n=sv(t),a=!1;return s_(t,e,n,a)},vae=Pt([Gi,yae],hA),wae=Pt([Gi,Rz,Y5e,vae],Tz),X5e=Pt([jr,Iz,Gi,xs],tae),Z5e=Pt([jr,Iz,Gi,xs],nae),J5e=(t,e,n,a,i,s,o,l)=>{if(e){var{type:c}=e,d=vd(t,l);if(a){var u=n==="scaleBand"&&a.bandwidth?a.bandwidth()/2:2,m=c==="category"&&a.bandwidth?a.bandwidth()/u:0;return m=l==="angleAxis"&&i!=null&&i?.length>=2?us(i[0]-i[1])*2*m:m,d&&o?o.map((p,f)=>{var g=a.map(p);return Kn(g)?{coordinate:g+m,value:p,index:f,offset:m}:null}).filter(Vo):a.domain().map((p,f)=>{var g=a.map(p);return Kn(g)?{coordinate:g+m,value:s?s[p]:p,index:f,offset:m}:null}).filter(Vo)}}},op=Pt([jr,Gi,Rz,wae,yae,X5e,Z5e,xs],J5e),Oz=Pt([aae,iae,l5e],(t,e,n)=>sae(n.shared,t,e)),Sae=t=>t.tooltip.settings.trigger,zz=t=>t.tooltip.settings.defaultIndex,l_=Pt([cv,Oz,Sae,zz],mae),Zh=Pt([l_,uv,i_,o_],Lz),_ae=Pt([op,Zh],oae),Uz=Pt([l_],t=>{if(t)return t.dataKey}),eUe=Pt([l_],t=>{if(t)return t.graphicalItemId}),kae=Pt([cv,Oz,Sae,zz],hae),tUe=Pt([rp,ap,jr,qi,op,zz,kae],pae),nUe=Pt([l_,tUe],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),rUe=Pt([l_],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),aUe=Pt([kae,Zh,sp,i_,_ae,fae,Oz],gae),iUe=Pt([aUe],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function rW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function aW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rW(Object(n),!0).forEach(function(a){sUe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function sUe(t,e,n){return(e=oUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function oUe(t){var e=lUe(t,"string");return typeof e=="symbol"?e:e+""}function lUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var cUe=()=>bn(Gi),dUe=()=>{var t=cUe(),e=bn(op),n=bn(wae);return Xh(!t||!n?void 0:aW(aW({},t),{},{scale:n}),e)};function iW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Mx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?iW(Object(n),!0).forEach(function(a){uUe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):iW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function uUe(t,e,n){return(e=mUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mUe(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 a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var hUe=(t,e,n,a)=>{var i=e.find(s=>s&&s.index===n);if(i){if(t==="horizontal")return{x:i.coordinate,y:a.chartY};if(t==="vertical")return{x:a.chartX,y:i.coordinate}}return{x:0,y:0}},fUe=(t,e,n,a)=>{var i=e.find(d=>d&&d.index===n);if(i){if(t==="centric"){var s=i.coordinate,{radius:o}=a;return Mx(Mx(Mx({},a),ki(a.cx,a.cy,o,s)),{},{angle:s,radius:o})}var l=i.coordinate,{angle:c}=a;return Mx(Mx(Mx({},a),ki(a.cx,a.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 gUe(t,e){var{chartX:n,chartY:a}=t;return n>=e.left&&n<=e.left+e.width&&a>=e.top&&a<=e.top+e.height}var Nae=(t,e,n,a,i)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(a==="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,g=(u=n[l])===null||u===void 0?void 0:u.coordinate,w=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,b=void 0;if(!(f==null||g==null||w==null))if(us(g-f)!==us(w-g)){var x=[];if(us(w-g)===us(i[1]-i[0])){b=w;var S=g+i[1]-i[0];x[0]=Math.min(S,(S+f)/2),x[1]=Math.max(S,(S+f)/2)}else{b=f;var k=w+i[1]-i[0];x[0]=Math.min(g,(k+g)/2),x[1]=Math.max(g,(k+g)/2)}var C=[Math.min(g,(b+g)/2),Math.max(g,(b+g)/2)];if(t>C[0]&&t<=C[1]||t>=x[0]&&t<=x[1]){var P;return(P=n[l])===null||P===void 0?void 0:P.index}}else{var T=Math.min(f,w),A=Math.max(f,w);if(t>(T+g)/2&&t<=(A+g)/2){var F;return(F=n[l])===null||F===void 0?void 0:F.index}}}else if(e)for(var _=0;_<o;_++){var M=e[_];if(M!=null){var H=e[_+1],I=e[_-1];if(_===0&&H!=null&&t<=(M.coordinate+H.coordinate)/2||_===o-1&&I!=null&&t>(M.coordinate+I.coordinate)/2||_>0&&_<o-1&&I!=null&&H!=null&&t>(M.coordinate+I.coordinate)/2&&t<=(M.coordinate+H.coordinate)/2)return M.index}}return-1},Cae=()=>bn(lz),Bz=(t,e)=>e,Pae=(t,e,n)=>n,Hz=(t,e,n,a)=>a,bUe=Pt(op,t=>$T(t,e=>e.coordinate)),qz=Pt([cv,Bz,Pae,Hz],mae),$z=Pt([qz,uv,i_,o_],Lz),xUe=(t,e,n)=>{if(e!=null){var a=cv(t);return e==="axis"?n==="hover"?a.axisInteraction.hover.dataKey:a.axisInteraction.click.dataKey:n==="hover"?a.itemInteraction.hover.dataKey:a.itemInteraction.click.dataKey}},Tae=Pt([cv,Bz,Pae,Hz],hae),cP=Pt([rp,ap,jr,qi,op,Hz,Tae],pae),yUe=Pt([qz,cP],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),Aae=Pt([op,$z],oae),vUe=Pt([Tae,$z,sp,i_,Aae,fae,Bz],gae),wUe=Pt([qz,$z],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),SUe=(t,e,n,a,i,s,o)=>{if(!(!t||!n||!a||!i)&&gUe(t,o)){var l=$Fe(t,e),c=Nae(l,s,i,n,a),d=hUe(e,i,c,t);return{activeIndex:String(c),activeCoordinate:d}}},_Ue=(t,e,n,a,i,s,o)=>{if(!(!t||!a||!i||!s||!n)){var l=oIe(t,n);if(l){var c=VFe(l,e),d=Nae(c,o,s,a,i),u=fUe(e,s,d,l);return{activeIndex:String(d),activeCoordinate:u}}}},kUe=(t,e,n,a,i,s,o,l)=>{if(!(!t||!e||!a||!i||!s))return e==="horizontal"||e==="vertical"?SUe(t,e,a,i,s,o,l):_Ue(t,e,n,a,i,s,o)},NUe=Pt(t=>t.zIndex.zIndexMap,(t,e)=>e,(t,e,n)=>n,(t,e,n)=>{if(e!=null){var a=t[e];if(a!=null)return n?a.panoramaElement:a.element}}),CUe=Pt(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(a=>parseInt(a,10)).concat(Object.values(ii)),n=Array.from(new Set(e));return n.sort((a,i)=>a-i)},{memoizeOptions:{resultEqualityCheck:oze}});function sW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}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(a){PUe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):sW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function PUe(t,e,n){return(e=TUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function TUe(t){var e=AUe(t,"string");return typeof e=="symbol"?e:e+""}function AUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var jUe={},MUe={zIndexMap:Object.values(ii).reduce((t,e)=>oW(oW({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),jUe)},EUe=new Set(Object.values(ii));function DUe(t){return EUe.has(t)}var jae=Jo({name:"zIndex",initialState:MUe,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:Ra()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!DUe(n)&&delete t.zIndexMap[n])},prepare:Ra()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:a,isPanorama:i}=e.payload;t.zIndexMap[n]?i?t.zIndexMap[n].panoramaElement=a:t.zIndexMap[n].element=a:t.zIndexMap[n]={consumers:0,element:i?void 0:a,panoramaElement:i?a:void 0}},prepare:Ra()},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:Ra()}}}),{registerZIndexPortal:FUe,unregisterZIndexPortal:LUe,registerZIndexPortalElement:RUe,unregisterZIndexPortalElement:IUe}=jae.actions,OUe=jae.reducer;function so(t){var{zIndex:e,children:n}=t,a=SLe(),i=a&&e!==void 0&&e!==0,s=$i(),o=ga();y.useLayoutEffect(()=>i?(o(FUe({zIndex:e})),()=>{o(LUe({zIndex:e}))}):af,[o,e,i]);var l=bn(c=>NUe(c,e,s));return i?l?cc.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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},WR.apply(null,arguments)}function lW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function H1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?lW(Object(n),!0).forEach(function(a){zUe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function zUe(t,e,n){return(e=UUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function UUe(t){var e=BUe(t,"string");return typeof e=="symbol"?e:e+""}function BUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function HUe(t){var{cursor:e,cursorComp:n,cursorProps:a}=t;return y.isValidElement(e)?y.cloneElement(e,a):y.createElement(n,a)}function qUe(t){var e,{coordinate:n,payload:a,index:i,offset:s,tooltipAxisBandSize:o,layout:l,cursor:c,tooltipEventType:d,chartName:u}=t,m=n,p=a,f=i;if(!c||!m||u!=="ScatterChart"&&d!=="axis")return null;var g,w,b;if(u==="ScatterChart")g=m,w=wRe,b=ii.cursorLine;else if(u==="BarChart")g=SRe(l,m,s,o),w=Cne,b=ii.cursorRectangle;else if(l==="radial"&&lte(m)){var{cx:x,cy:S,radius:k,startAngle:C,endAngle:P}=Tne(m);g={cx:x,cy:S,startAngle:C,endAngle:P,innerRadius:k,outerRadius:k},w=jne,b=ii.cursorLine}else g={points:uIe(l,m,s)},w=dy,b=ii.cursorLine;var T=typeof c=="object"&&"className"in c?c.className:void 0,A=H1(H1(H1(H1({stroke:"#ccc",pointerEvents:"none"},s),g),Ug(c)),{},{payload:p,payloadIndex:f,className:Er("recharts-tooltip-cursor",T)});return y.createElement(so,{zIndex:(e=t.zIndex)!==null&&e!==void 0?e:b},y.createElement(HUe,{cursor:c,cursorComp:w,cursorProps:A}))}function $Ue(t){var e=dUe(),n=cne(),a=of(),i=Cae();return e==null||n==null||a==null||i==null?null:y.createElement(qUe,WR({},t,{offset:n,layout:a,tooltipAxisBandSize:e,chartName:i}))}var Mae=y.createContext(null),VUe=()=>y.useContext(Mae),KD={exports:{}},cW;function GUe(){return cW||(cW=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function a(){}Object.create&&(a.prototype=Object.create(null),new a().__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),g=n?n+d:d;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function o(c,d){--c._eventsCount===0?c._events=new a:delete c._events[d]}function l(){this._events=new a,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,g=new Array(f);p<f;p++)g[p]=m[p].fn;return g},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,g){var w=n?n+d:d;if(!this._events[w])return!1;var b=this._events[w],x=arguments.length,S,k;if(b.fn){switch(b.once&&this.removeListener(d,b.fn,void 0,!0),x){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,u),!0;case 3:return b.fn.call(b.context,u,m),!0;case 4:return b.fn.call(b.context,u,m,p),!0;case 5:return b.fn.call(b.context,u,m,p,f),!0;case 6:return b.fn.call(b.context,u,m,p,f,g),!0}for(k=1,S=new Array(x-1);k<x;k++)S[k-1]=arguments[k];b.fn.apply(b.context,S)}else{var C=b.length,P;for(k=0;k<C;k++)switch(b[k].once&&this.removeListener(d,b[k].fn,void 0,!0),x){case 1:b[k].fn.call(b[k].context);break;case 2:b[k].fn.call(b[k].context,u);break;case 3:b[k].fn.call(b[k].context,u,m);break;case 4:b[k].fn.call(b[k].context,u,m,p);break;default:if(!S)for(P=1,S=new Array(x-1);P<x;P++)S[P-1]=arguments[P];b[k].fn.apply(b[k].context,S)}}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 g=this._events[f];if(g.fn)g.fn===u&&(!p||g.once)&&(!m||g.context===m)&&o(this,f);else{for(var w=0,b=[],x=g.length;w<x;w++)(g[w].fn!==u||p&&!g[w].once||m&&g[w].context!==m)&&b.push(g[w]);b.length?this._events[f]=b.length===1?b[0]:b: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 a,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})(KD)),KD.exports}var WUe=GUe();const KUe=Tc(WUe);var iS=new KUe,KR="recharts.syncEvent.tooltip",dW="recharts.syncEvent.brush",NA=(t,e)=>{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!hd(n))return t[n]}},QUe={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},Eae=Jo({name:"options",initialState:QUe,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),YUe=Eae.reducer,{createEventEmitter:XUe}=Eae.actions;function ZUe(t){return t.tooltip.syncInteraction}var JUe={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},Dae=Jo({name:"chartData",initialState:JUe,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:a}=e.payload;n!=null&&(t.dataStartIndex=n),a!=null&&(t.dataEndIndex=a)}}}),{setChartData:uW,setDataStartEndIndexes:eBe,setComputedData:kct}=Dae.actions,tBe=Dae.reducer,nBe=["x","y"];function mW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Ex(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?mW(Object(n),!0).forEach(function(a){rBe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):mW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function rBe(t,e,n){return(e=aBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function aBe(t){var e=iBe(t,"string");return typeof e=="symbol"?e:e+""}function iBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function sBe(t,e){if(t==null)return{};var n,a,i=oBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function oBe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function lBe(){var t=bn(cz),e=bn(dz),n=ga(),a=bn(Cre),i=bn(op),s=of(),o=WS(),l=bn(c=>c.rootProps.className);y.useEffect(()=>{if(t==null)return af;var c=(d,u,m)=>{if(e!==m&&t===d){if(a==="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:g,y:w}=f,b=sBe(f,nBe),{x,y:S,width:k,height:C}=u.payload.sourceViewBox,P=Ex(Ex({},b),{},{x:o.x+(k?(g-x)/k:0)*o.width,y:o.y+(C?(w-S)/C:0)*o.height});n(Ex(Ex({},u),{},{payload:Ex(Ex({},u.payload),{},{coordinate:P})}))}else n(u);return}if(i!=null){var T;if(typeof a=="function"){var A={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=a(i,A);T=i[F]}else a==="value"&&(T=i.find(ne=>String(ne.value)===u.payload.label));var{coordinate:_}=u.payload;if(T==null||u.payload.active===!1||_==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:M,y:H}=_,I=Math.min(M,o.x+o.width),z=Math.min(H,o.y+o.height),L={x:s==="horizontal"?T.coordinate:I,y:s==="horizontal"?z:T.coordinate},Z=VR({active:u.payload.active,coordinate:L,dataKey:u.payload.dataKey,index:String(T.index),label:u.payload.label,sourceViewBox:u.payload.sourceViewBox,graphicalItemId:u.payload.graphicalItemId});n(Z)}}};return iS.on(KR,c),()=>{iS.off(KR,c)}},[l,n,e,t,a,i,s,o])}function cBe(){var t=bn(cz),e=bn(dz),n=ga();y.useEffect(()=>{if(t==null)return af;var a=(i,s,o)=>{e!==o&&t===i&&n(eBe(s))};return iS.on(dW,a),()=>{iS.off(dW,a)}},[n,e,t])}function dBe(){var t=ga();y.useEffect(()=>{t(XUe())},[t]),lBe(),cBe()}function uBe(t,e,n,a,i,s){var o=bn(f=>xUe(f,t,e)),l=bn(dz),c=bn(cz),d=bn(Cre),u=bn(ZUe),m=u?.active,p=WS();y.useEffect(()=>{if(!m&&c!=null&&l!=null){var f=VR({active:s,coordinate:n,dataKey:o,index:i,label:typeof a=="number"?String(a):a,sourceViewBox:p,graphicalItemId:void 0});iS.emit(KR,c,f,l)}},[m,n,o,i,a,l,c,d,s,p])}function pW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function hW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?pW(Object(n),!0).forEach(function(a){mBe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):pW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function mBe(t,e,n){return(e=pBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function pBe(t){var e=hBe(t,"string");return typeof e=="symbol"?e:e+""}function hBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fBe(t){return t.dataKey}function gBe(t,e){return y.isValidElement(t)?y.cloneElement(t,e):typeof t=="function"?y.createElement(t,e):y.createElement(eRe,e)}var fW=[],bBe={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 au(t){var e,n,a=Va(t,bBe),{active:i,allowEscapeViewBox:s,animationDuration:o,animationEasing:l,content:c,filterNull:d,isAnimationActive:u,offset:m,payloadUniqBy:p,position:f,reverseDirection:g,useTranslate3d:w,wrapperStyle:b,cursor:x,shared:S,trigger:k,defaultIndex:C,portal:P,axisId:T}=a,A=ga(),F=typeof C=="number"?String(C):C;y.useEffect(()=>{A(p5e({shared:S,trigger:k,axisId:T,active:i,defaultIndex:F}))},[A,S,k,T,i,F]);var _=WS(),M=wne(),H=o5e(S),{activeIndex:I,isActive:z}=(e=bn(J=>wUe(J,H,k,F)))!==null&&e!==void 0?e:{},L=bn(J=>vUe(J,H,k,F)),Z=bn(J=>Aae(J,H,k,F)),ne=bn(J=>yUe(J,H,k,F)),Y=L,ce=VUe(),ue=(n=i??z)!==null&&n!==void 0?n:!1,[oe,Q]=_te([Y,ue]),le=H==="axis"?Z:void 0;uBe(H,k,ne,le,I,ue);var pe=P??ce;if(pe==null||_==null||H==null)return null;var he=Y??fW;ue||(he=fW),d&&he.length&&(he=bte(he.filter(J=>J.value!=null&&(J.hide!==!0||a.includeHidden)),p,fBe));var we=he.length>0,$=y.createElement(oRe,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:u,active:ue,coordinate:ne,hasPayload:we,offset:m,position:f,reverseDirection:g,useTranslate3d:w,viewBox:_,wrapperStyle:b,lastBoundingBox:oe,innerRef:Q,hasPortalFromProps:!!P},gBe(c,hW(hW({},a),{},{payload:he,label:le,active:ue,activeIndex:I,coordinate:ne,accessibilityLayer:M})));return y.createElement(y.Fragment,null,cc.createPortal($,pe),ue&&y.createElement($Ue,{cursor:x,tooltipEventType:H,coordinate:ne,payload:he,index:I}))}var Ly=t=>null;Ly.displayName="Cell";function xBe(t,e,n){return(e=yBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yBe(t){var e=vBe(t,"string");return typeof e=="symbol"?e:e+""}function vBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class wBe{constructor(e){xBe(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 a=this.cache.keys().next().value;a!=null&&this.cache.delete(a)}this.cache.set(e,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function gW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function SBe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gW(Object(n),!0).forEach(function(a){_Be(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function _Be(t,e,n){return(e=kBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function kBe(t){var e=NBe(t,"string");return typeof e=="symbol"?e:e+""}function NBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var CBe={cacheSize:2e3,enableCache:!0},Fae=SBe({},CBe),bW=new wBe(Fae.cacheSize),PBe={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},xW="recharts_measurement_span";function TBe(t,e){var n=e.fontSize||"",a=e.fontFamily||"",i=e.fontWeight||"",s=e.fontStyle||"",o=e.letterSpacing||"",l=e.textTransform||"";return"".concat(t,"|").concat(n,"|").concat(a,"|").concat(i,"|").concat(s,"|").concat(o,"|").concat(l)}var yW=(t,e)=>{try{var n=document.getElementById(xW);n||(n=document.createElement("span"),n.setAttribute("id",xW),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,PBe,e),n.textContent="".concat(t);var a=n.getBoundingClientRect();return{width:a.width,height:a.height}}catch{return{width:0,height:0}}},iw=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||YS.isSsr)return{width:0,height:0};if(!Fae.enableCache)return yW(e,n);var a=TBe(e,n),i=bW.get(a);if(i)return i;var s=yW(e,n);return bW.set(a,s),s},Lae;function ABe(t,e,n){return(e=jBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function jBe(t){var e=MBe(t,"string");return typeof e=="symbol"?e:e+""}function MBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var vW=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,wW=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,EBe=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,DBe=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,FBe={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},LBe=["cm","mm","pt","pc","in","Q","px"];function RBe(t){return LBe.includes(t)}var Xx="NaN";function IBe(t,e){return t*FBe[e]}class As{static parse(e){var n,[,a,i]=(n=DBe.exec(e))!==null&&n!==void 0?n:[];return a==null?As.NaN:new As(parseFloat(a),i??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,hd(e)&&(this.unit=""),n!==""&&!EBe.test(n)&&(this.num=NaN,this.unit=""),RBe(n)&&(this.num=IBe(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new As(NaN,""):new As(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new As(NaN,""):new As(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new As(NaN,""):new As(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new As(NaN,""):new As(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return hd(this.num)}}Lae=As;ABe(As,"NaN",new Lae(NaN,""));function Rae(t){if(t==null||t.includes(Xx))return Xx;for(var e=t;e.includes("*")||e.includes("/");){var n,[,a,i,s]=(n=vW.exec(e))!==null&&n!==void 0?n:[],o=As.parse(a??""),l=As.parse(s??""),c=i==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return Xx;e=e.replace(vW,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var d,[,u,m,p]=(d=wW.exec(e))!==null&&d!==void 0?d:[],f=As.parse(u??""),g=As.parse(p??""),w=m==="+"?f.add(g):f.subtract(g);if(w.isNaN())return Xx;e=e.replace(wW,w.toString())}return e}var SW=/\(([^()]*)\)/;function OBe(t){for(var e=t,n;(n=SW.exec(e))!=null;){var[,a]=n;e=e.replace(SW,Rae(a))}return e}function zBe(t){var e=t.replace(/\s+/g,"");return e=OBe(e),e=Rae(e),e}function UBe(t){try{return zBe(t)}catch{return Xx}}function QD(t){var e=UBe(t.slice(5,-1));return e===Xx?"":e}var BBe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],HBe=["dx","dy","angle","className","breakAll"];function QR(){return QR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},QR.apply(null,arguments)}function _W(t,e){if(t==null)return{};var n,a,i=qBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function qBe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var Iae=/[ \f\n\r\t\v\u2028\u2029]+/,Oae=t=>{var{children:e,breakAll:n,style:a}=t;try{var i=[];Ua(e)||(n?i=e.toString().split(""):i=e.toString().split(Iae));var s=i.map(l=>({word:l,width:iw(l,a).width})),o=n?0:iw(" ",a).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function $Be(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var zae=(t,e,n,a)=>t.reduce((i,s)=>{var{word:o,width:l}=s,c=i[i.length-1];if(c&&l!=null&&(e==null||a||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},[]),Uae=t=>t.reduce((e,n)=>e.width>n.width?e:n),VBe="…",kW=(t,e,n,a,i,s,o,l)=>{var c=t.slice(0,e),d=Oae({breakAll:n,style:a,children:c+VBe});if(!d)return[!1,[]];var u=zae(d.wordsWithComputedWidth,s,o,l),m=u.length>i||Uae(u).width>Number(s);return[m,u]},GBe=(t,e,n,a,i)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,d=hn(s),u=String(o),m=zae(e,a,n,i);if(!d||i)return m;var p=m.length>s||Uae(m).width>Number(a);if(!p)return m;for(var f=0,g=u.length-1,w=0,b;f<=g&&w<=u.length-1;){var x=Math.floor((f+g)/2),S=x-1,[k,C]=kW(u,S,c,l,s,a,n,i),[P]=kW(u,x,c,l,s,a,n,i);if(!k&&!P&&(f=x+1),k&&P&&(g=x-1),!k&&P){b=C;break}w++}return b||m},NW=t=>{var e=Ua(t)?[]:t.toString().split(Iae);return[{words:e,width:void 0}]},WBe=t=>{var{width:e,scaleToFit:n,children:a,style:i,breakAll:s,maxLines:o}=t;if((e||n)&&!YS.isSsr){var l,c,d=Oae({breakAll:s,children:a,style:i});if(d){var{wordsWithComputedWidth:u,spaceWidth:m}=d;l=u,c=m}else return NW(a);return GBe({breakAll:s,children:a,maxLines:o,style:i},l,c,e,!!n)}return NW(a)},Bae="#808080",KBe={angle:0,breakAll:!1,capHeight:"0.71em",fill:Bae,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},CA=y.forwardRef((t,e)=>{var n=Va(t,KBe),{x:a,y:i,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:d,verticalAnchor:u}=n,m=_W(n,BBe),p=y.useMemo(()=>WBe({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:g,angle:w,className:b,breakAll:x}=m,S=_W(m,HBe);if(!kc(a)||!kc(i)||p.length===0)return null;var k=Number(a)+(hn(f)?f:0),C=Number(i)+(hn(g)?g:0);if(!Kn(k)||!Kn(C))return null;var P;switch(u){case"start":P=QD("calc(".concat(o,")"));break;case"middle":P=QD("calc(".concat((p.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:P=QD("calc(".concat(p.length-1," * -").concat(s,")"));break}var T=[],A=p[0];if(c&&A!=null){var F=A.width,{width:_}=m;T.push("scale(".concat(hn(_)&&hn(F)?_/F:1,")"))}return w&&T.push("rotate(".concat(w,", ").concat(k,", ").concat(C,")")),T.length&&(S.transform=T.join(" ")),y.createElement("text",QR({},Os(S),{ref:e,x:k,y:C,className:Er("recharts-text",b),textAnchor:d,fill:l.includes("url")?Bae:l}),p.map((M,H)=>{var I=M.words.join(x?"":" ");return y.createElement("tspan",{x:k,dy:H===0?P:s,key:"".concat(I,"-").concat(H)},I)}))});CA.displayName="Text";function CW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Ud(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?CW(Object(n),!0).forEach(function(a){QBe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):CW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function QBe(t,e,n){return(e=YBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function YBe(t){var e=XBe(t,"string");return typeof e=="symbol"?e:e+""}function XBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var ZBe=t=>{var{viewBox:e,position:n,offset:a=0,parentViewBox:i}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:d}=A4(e),u=s,m=s+(c-d)/2,p=(u+m)/2,f=(c+d)/2,g=u+c/2,w=l>=0?1:-1,b=w*a,x=w>0?"end":"start",S=w>0?"start":"end",k=c>=0?1:-1,C=k*a,P=k>0?"end":"start",T=k>0?"start":"end",A=i;if(n==="top"){var F={x:u+c/2,y:o-b,horizontalAnchor:"middle",verticalAnchor:x};return A&&(F.height=Math.max(o-A.y,0),F.width=c),F}if(n==="bottom"){var _={x:m+d/2,y:o+l+b,horizontalAnchor:"middle",verticalAnchor:S};return A&&(_.height=Math.max(A.y+A.height-(o+l),0),_.width=d),_}if(n==="left"){var M={x:p-C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"};return A&&(M.width=Math.max(M.x-A.x,0),M.height=l),M}if(n==="right"){var H={x:p+f+C,y:o+l/2,horizontalAnchor:T,verticalAnchor:"middle"};return A&&(H.width=Math.max(A.x+A.width-H.x,0),H.height=l),H}var I=A?{width:f,height:l}:{};return n==="insideLeft"?Ud({x:p+C,y:o+l/2,horizontalAnchor:T,verticalAnchor:"middle"},I):n==="insideRight"?Ud({x:p+f-C,y:o+l/2,horizontalAnchor:P,verticalAnchor:"middle"},I):n==="insideTop"?Ud({x:u+c/2,y:o+b,horizontalAnchor:"middle",verticalAnchor:S},I):n==="insideBottom"?Ud({x:m+d/2,y:o+l-b,horizontalAnchor:"middle",verticalAnchor:x},I):n==="insideTopLeft"?Ud({x:u+C,y:o+b,horizontalAnchor:T,verticalAnchor:S},I):n==="insideTopRight"?Ud({x:u+c-C,y:o+b,horizontalAnchor:P,verticalAnchor:S},I):n==="insideBottomLeft"?Ud({x:m+C,y:o+l-b,horizontalAnchor:T,verticalAnchor:x},I):n==="insideBottomRight"?Ud({x:m+d-C,y:o+l-b,horizontalAnchor:P,verticalAnchor:x},I):n&&typeof n=="object"&&(hn(n.x)||qg(n.x))&&(hn(n.y)||qg(n.y))?Ud({x:s+no(n.x,f),y:o+no(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},I):Ud({x:g,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},I)},JBe=["labelRef"],eHe=["content"];function PW(t,e){if(t==null)return{};var n,a,i=tHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function tHe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function TW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function U0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?TW(Object(n),!0).forEach(function(a){nHe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):TW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function nHe(t,e,n){return(e=rHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function rHe(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 a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ym(){return ym=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},ym.apply(null,arguments)}var Hae=y.createContext(null),qae=t=>{var{x:e,y:n,upperWidth:a,lowerWidth:i,width:s,height:o,children:l}=t,c=y.useMemo(()=>({x:e,y:n,upperWidth:a,lowerWidth:i,width:s,height:o}),[e,n,a,i,s,o]);return y.createElement(Hae.Provider,{value:c},l)},$ae=()=>{var t=y.useContext(Hae),e=WS();return t||(e?A4(e):void 0)},iHe=y.createContext(null),sHe=()=>{var t=y.useContext(iHe),e=bn(Mre);return t||e},oHe=t=>{var{value:e,formatter:n}=t,a=Ua(t.children)?e:t.children;return typeof n=="function"?n(a):a},Vz=t=>t!=null&&typeof t=="function",lHe=(t,e)=>{var n=us(e-t),a=Math.min(Math.abs(e-t),360);return n*a},cHe=(t,e,n,a,i)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:d,outerRadius:u,startAngle:m,endAngle:p,clockWise:f}=i,g=(d+u)/2,w=lHe(m,p),b=w>=0?1:-1,x,S;switch(e){case"insideStart":x=m+b*s,S=f;break;case"insideEnd":x=p-b*s,S=!f;break;case"end":x=p+b*s,S=f;break;default:throw new Error("Unsupported position ".concat(e))}S=w<=0?S:!S;var k=ki(l,c,g,x),C=ki(l,c,g,x+(S?1:-1)*359),P="M".concat(k.x,",").concat(k.y,`
  8125. A`).concat(g,",").concat(g,",0,1,").concat(S?0:1,`,
  8126. `).concat(C.x,",").concat(C.y),T=Ua(t.id)?Gw("recharts-radial-line-"):t.id;return y.createElement("text",ym({},a,{dominantBaseline:"central",className:Er("recharts-radial-bar-label",o)}),y.createElement("defs",null,y.createElement("path",{id:T,d:P})),y.createElement("textPath",{xlinkHref:"#".concat(T)},n))},dHe=(t,e,n)=>{var{cx:a,cy:i,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,d=(l+c)/2;if(n==="outside"){var{x:u,y:m}=ki(a,i,o+e,d);return{x:u,y:m,textAnchor:u>=a?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:a,y:i,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:a,y:i,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:a,y:i,textAnchor:"middle",verticalAnchor:"end"};var p=(s+o)/2,{x:f,y:g}=ki(a,i,p,d);return{x:f,y:g,textAnchor:"middle",verticalAnchor:"middle"}},DN=t=>t!=null&&"cx"in t&&hn(t.cx),uHe={angle:0,offset:5,zIndex:ii.label,position:"middle",textBreakAll:!1};function mHe(t){if(!DN(t))return t;var{cx:e,cy:n,outerRadius:a}=t,i=a*2;return{x:e-a,y:n-a,width:i,upperWidth:i,lowerWidth:i,height:i}}function sh(t){var e=Va(t,uHe),{viewBox:n,parentViewBox:a,position:i,value:s,children:o,content:l,className:c="",textBreakAll:d,labelRef:u}=e,m=sHe(),p=$ae(),f=i==="center"?p:m??p,g,w,b;n==null?g=f:DN(n)?g=n:g=A4(n);var x=mHe(g);if(!g||Ua(s)&&Ua(o)&&!y.isValidElement(l)&&typeof l!="function")return null;var S=U0(U0({},e),{},{viewBox:g});if(y.isValidElement(l)){var{labelRef:k}=S,C=PW(S,JBe);return y.cloneElement(l,C)}if(typeof l=="function"){var{content:P}=S,T=PW(S,eHe);if(w=y.createElement(l,T),y.isValidElement(w))return w}else w=oHe(e);var A=Os(e);if(DN(g)){if(i==="insideStart"||i==="insideEnd"||i==="end")return cHe(e,i,w,A,g);b=dHe(g,e.offset,e.position)}else{if(!x)return null;var F=ZBe({viewBox:x,position:i,offset:e.offset,parentViewBox:DN(a)?void 0:a});b=U0(U0({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 y.createElement(so,{zIndex:e.zIndex},y.createElement(CA,ym({ref:u,className:Er("recharts-label",c)},A,b,{textAnchor:$Be(A.textAnchor)?A.textAnchor:b.textAnchor,breakAll:d}),w))}sh.displayName="Label";var pHe=(t,e,n)=>{if(!t)return null;var a={viewBox:e,labelRef:n};return t===!0?y.createElement(sh,ym({key:"label-implicit"},a)):kc(t)?y.createElement(sh,ym({key:"label-implicit",value:t},a)):y.isValidElement(t)?t.type===sh?y.cloneElement(t,U0({key:"label-implicit"},a)):y.createElement(sh,ym({key:"label-implicit",content:t},a)):Vz(t)?y.createElement(sh,ym({key:"label-implicit",content:t},a)):t&&typeof t=="object"?y.createElement(sh,ym({},t,{key:"label-implicit"},a)):null};function Vae(t){var{label:e,labelRef:n}=t,a=$ae();return pHe(e,a,n)||null}var YD={},XD={},AW;function hHe(){return AW||(AW=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(XD)),XD}var ZD={},jW;function fHe(){return jW||(jW=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(ZD)),ZD}var MW;function gHe(){return MW||(MW=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=hHe(),n=fHe(),a=x4();function i(s){if(a.isArrayLike(s))return e.last(n.toArray(s))}t.last=i})(YD)),YD}var JD,EW;function bHe(){return EW||(EW=1,JD=gHe().last),JD}var xHe=bHe();const yHe=Tc(xHe);var vHe=["valueAccessor"],wHe=["dataKey","clockWise","id","textBreakAll","zIndex"];function dP(){return dP=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},dP.apply(null,arguments)}function DW(t,e){if(t==null)return{};var n,a,i=SHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function SHe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var _He=t=>Array.isArray(t.value)?yHe(t.value):t.value,Gae=y.createContext(void 0),Gz=Gae.Provider,Wae=y.createContext(void 0),kHe=Wae.Provider;function NHe(){return y.useContext(Gae)}function CHe(){return y.useContext(Wae)}function FN(t){var{valueAccessor:e=_He}=t,n=DW(t,vHe),{dataKey:a,clockWise:i,id:s,textBreakAll:o,zIndex:l}=n,c=DW(n,wHe),d=NHe(),u=CHe(),m=d||u;return!m||!m.length?null:y.createElement(so,{zIndex:l??ii.label},y.createElement($a,{className:"recharts-label-list"},m.map((p,f)=>{var g,w=Ua(a)?e(p,f):Gr(p.payload,a),b=Ua(s)?{}:{id:"".concat(s,"-").concat(f)};return y.createElement(sh,dP({key:"label-".concat(f)},Os(p),c,b,{fill:(g=n.fill)!==null&&g!==void 0?g:p.fill,parentViewBox:p.parentViewBox,value:w,textBreakAll:o,viewBox:p.viewBox,index:f,zIndex:0}))})))}FN.displayName="LabelList";function PA(t){var{label:e}=t;return e?e===!0?y.createElement(FN,{key:"labelList-implicit"}):y.isValidElement(e)||Vz(e)?y.createElement(FN,{key:"labelList-implicit",content:e}):typeof e=="object"?y.createElement(FN,dP({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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},YR.apply(null,arguments)}var Kae=t=>{var{cx:e,cy:n,r:a,className:i}=t,s=Er("recharts-dot",i);return hn(e)&&hn(n)&&hn(a)?y.createElement("circle",YR({},_o(t),b4(t),{className:s,cx:e,cy:n,r:a})):null},Qae=t=>t.graphicalItems.polarItems,PHe=Pt([Ga,n_],fz),TA=Pt([Qae,oi,PHe],gz),THe=Pt([TA],bz),AA=Pt([THe,pA],xz),AHe=Pt([AA,oi,TA],vz);Pt([AA,oi,TA],(t,e,n)=>n.length>0?t.flatMap(a=>n.flatMap(i=>{var s,o=Gr(a,(s=e.dataKey)!==null&&s!==void 0?s:i.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(a=>({value:Gr(a,e.dataKey),errorDomain:[]})):t.map(a=>({value:a,errorDomain:[]})));var FW=()=>{},jHe=Pt([AA,oi,TA,SA,Ga],kz),MHe=Pt([oi,Sz,_z,FW,jHe,FW,jr,Ga],Nz),Yae=Pt([oi,jr,AA,AHe,t_,Ga,MHe],Cz),EHe=Pt([Yae,ov,df],Az),DHe=Pt([oi,Yae,EHe,Ga],Mz);Pt([df,DHe],Dre);var FHe={radiusAxis:{},angleAxis:{}},Xae=Jo({name:"polarAxis",initialState:FHe,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:Nct,removeRadiusAxis:Cct,addAngleAxis:Pct,removeAngleAxis:Tct}=Xae.actions,LHe=Xae.reducer;function Zae(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function LW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function RW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?LW(Object(n),!0).forEach(function(a){RHe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):LW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function RHe(t,e,n){return(e=IHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function IHe(t){var e=OHe(t,"string");return typeof e=="symbol"?e:e+""}function OHe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var zHe=(t,e)=>e,Wz=Pt([Qae,zHe],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),UHe=[],Kz=(t,e,n)=>n?.length===0?UHe:n,Jae=Pt([pA,Wz,Kz],(t,e,n)=>{var{chartData:a}=t;if(e!=null){var i;if(e?.data!=null&&e.data.length>0?i=e.data:i=a,(!i||!i.length)&&n!=null&&(i=n.map(s=>RW(RW({},e.presentationProps),s.props))),i!=null)return i}}),BHe=Pt([Jae,Wz,Kz],(t,e,n)=>{if(!(t==null||e==null))return t.map((a,i)=>{var s,o=Gr(a,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 a=="object"&&a!=null&&"fill"in a?l=a.fill:l=e.fill,{value:sf(o,e.dataKey),color:l,payload:a,type:e.legendType}})}),HHe=Pt([Jae,Wz,Kz,qi],(t,e,n,a)=>{if(!(e==null||t==null))return q8e({offset:a,pieSettings:e,displayedData:t,cells:n})}),e3={exports:{}},ra={};var IW;function qHe(){if(IW)return ra;IW=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=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 g(w){if(typeof w=="object"&&w!==null){var b=w.$$typeof;switch(b){case t:switch(w=w.type,w){case n:case i:case a:case c:case d:case p:return w;default:switch(w=w&&w.$$typeof,w){case o:case l:case m:case u:return w;case s:return w;default:return b}}case e:return b}}}return ra.ContextConsumer=s,ra.ContextProvider=o,ra.Element=t,ra.ForwardRef=l,ra.Fragment=n,ra.Lazy=m,ra.Memo=u,ra.Portal=e,ra.Profiler=i,ra.StrictMode=a,ra.Suspense=c,ra.SuspenseList=d,ra.isContextConsumer=function(w){return g(w)===s},ra.isContextProvider=function(w){return g(w)===o},ra.isElement=function(w){return typeof w=="object"&&w!==null&&w.$$typeof===t},ra.isForwardRef=function(w){return g(w)===l},ra.isFragment=function(w){return g(w)===n},ra.isLazy=function(w){return g(w)===m},ra.isMemo=function(w){return g(w)===u},ra.isPortal=function(w){return g(w)===e},ra.isProfiler=function(w){return g(w)===i},ra.isStrictMode=function(w){return g(w)===a},ra.isSuspense=function(w){return g(w)===c},ra.isSuspenseList=function(w){return g(w)===d},ra.isValidElementType=function(w){return typeof w=="string"||typeof w=="function"||w===n||w===i||w===a||w===c||w===d||typeof w=="object"&&w!==null&&(w.$$typeof===m||w.$$typeof===u||w.$$typeof===o||w.$$typeof===s||w.$$typeof===l||w.$$typeof===f||w.getModuleId!==void 0)},ra.typeOf=g,ra}var OW;function $He(){return OW||(OW=1,e3.exports=qHe()),e3.exports}var VHe=$He(),zW=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",UW=null,t3=null,eie=t=>{if(t===UW&&Array.isArray(t3))return t3;var e=[];return y.Children.forEach(t,n=>{Ua(n)||(VHe.isFragment(n)?e=e.concat(eie(n.props.children)):e.push(n))}),t3=e,UW=t,e};function Qz(t,e){var n=[],a=[];return Array.isArray(e)?a=e.map(i=>zW(i)):a=[zW(e)],eie(t).forEach(i=>{var s=Hg(i,"type.displayName")||Hg(i,"type.name");s&&a.indexOf(s)!==-1&&n.push(i)}),n}var Yz=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,n3={},BW;function GHe(){return BW||(BW=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 a=n;for(;Object.getPrototypeOf(a)!==null;)a=Object.getPrototypeOf(a);return Object.getPrototypeOf(n)===a}t.isPlainObject=e})(n3)),n3}var r3,HW;function WHe(){return HW||(HW=1,r3=GHe().isPlainObject),r3}var KHe=WHe();const QHe=Tc(KHe);var qW,$W,VW,GW,WW;function KW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function QW(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?KW(Object(n),!0).forEach(function(a){YHe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):KW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function YHe(t,e,n){return(e=XHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function XHe(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 a=n.call(t,e);if(typeof a!="object")return a;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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},uP.apply(null,arguments)}function S0(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var YW=(t,e,n,a,i)=>{var s=n-a,o;return o=ti(qW||(qW=S0(["M ",",",""])),t,e),o+=ti($W||($W=S0(["L ",",",""])),t+n,e),o+=ti(VW||(VW=S0(["L ",",",""])),t+n-s/2,e+i),o+=ti(GW||(GW=S0(["L ",",",""])),t+n-s/2-a,e+i),o+=ti(WW||(WW=S0(["L ",","," Z"])),t,e),o},JHe={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},e8e=t=>{var e=Va(t,JHe),{x:n,y:a,upperWidth:i,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:d,animationBegin:u,isUpdateAnimationActive:m}=e,p=y.useRef(null),[f,g]=y.useState(-1),w=y.useRef(i),b=y.useRef(s),x=y.useRef(o),S=y.useRef(n),k=y.useRef(a),C=nv(t,"trapezoid-");if(y.useEffect(()=>{if(p.current&&p.current.getTotalLength)try{var L=p.current.getTotalLength();L&&g(L)}catch{}},[]),n!==+n||a!==+a||i!==+i||s!==+s||o!==+o||i===0&&s===0||o===0)return null;var P=Er("recharts-trapezoid",l);if(!m)return y.createElement("g",null,y.createElement("path",uP({},Os(e),{className:P,d:YW(n,a,i,s,o)})));var T=w.current,A=b.current,F=x.current,_=S.current,M=k.current,H="0px ".concat(f===-1?1:f,"px"),I="".concat(f,"px 0px"),z=Sne(["strokeDasharray"],d,c);return y.createElement(tv,{animationId:C,key:C,canBegin:f>0,duration:d,easing:c,isActive:m,begin:u},L=>{var Z=qr(T,i,L),ne=qr(A,s,L),Y=qr(F,o,L),ce=qr(_,n,L),ue=qr(M,a,L);p.current&&(w.current=Z,b.current=ne,x.current=Y,S.current=ce,k.current=ue);var oe=L>0?{transition:z,strokeDasharray:I}:{strokeDasharray:H};return y.createElement("path",uP({},Os(e),{className:P,d:YW(ce,ue,Z,ne,Y),ref:p,style:QW(QW({},oe),e.style)}))})},t8e=["option","shapeType","activeClassName"];function n8e(t,e){if(t==null)return{};var n,a,i=r8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function r8e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function XW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function mP(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?XW(Object(n),!0).forEach(function(a){a8e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):XW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function a8e(t,e,n){return(e=i8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i8e(t){var e=s8e(t,"string");return typeof e=="symbol"?e:e+""}function s8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function o8e(t,e){return mP(mP({},e),t)}function l8e(t,e){return t==="symbols"}function ZW(t){var{shapeType:e,elementProps:n}=t;switch(e){case"rectangle":return y.createElement(Cne,n);case"trapezoid":return y.createElement(e8e,n);case"sector":return y.createElement(jne,n);case"symbols":if(l8e(e))return y.createElement(g4,n);break;case"curve":return y.createElement(dy,n);default:return null}}function c8e(t){return y.isValidElement(t)?t.props:t}function Xz(t){var{option:e,shapeType:n,activeClassName:a="recharts-active-shape"}=t,i=n8e(t,t8e),s;if(y.isValidElement(e))s=y.cloneElement(e,mP(mP({},i),c8e(e)));else if(typeof e=="function")s=e(i,i.index);else if(QHe(e)&&typeof e!="boolean"){var o=o8e(e,i);s=y.createElement(ZW,{shapeType:n,elementProps:o})}else{var l=i;s=y.createElement(ZW,{shapeType:n,elementProps:l})}return i.isActive?y.createElement($a,{className:a},s):s}var Zz=(t,e,n)=>{var a=ga();return(i,s)=>o=>{t?.(i,s,o),a(cae({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}},Jz=t=>{var e=ga();return(n,a)=>i=>{t?.(n,a,i),e(h5e())}},e5=(t,e,n)=>{var a=ga();return(i,s)=>o=>{t?.(i,s,o),a(f5e({activeIndex:String(s),activeDataKey:e,activeCoordinate:i.tooltipPosition,activeGraphicalItemId:n}))}};function jA(t){var{tooltipEntrySettings:e}=t,n=ga(),a=$i(),i=y.useRef(null);return y.useLayoutEffect(()=>{a||(i.current===null?n(d5e(e)):i.current!==e&&n(u5e({prev:i.current,next:e})),i.current=e)},[e,n,a]),y.useLayoutEffect(()=>()=>{i.current&&(n(m5e(i.current)),i.current=null)},[n]),null}function t5(t){var{legendPayload:e}=t,n=ga(),a=$i(),i=y.useRef(null);return y.useLayoutEffect(()=>{a||(i.current===null?n(xne(e)):i.current!==e&&n(yne({prev:i.current,next:e})),i.current=e)},[n,a,e]),y.useLayoutEffect(()=>()=>{i.current&&(n(vne(i.current)),i.current=null)},[n]),null}function d8e(t){var{legendPayload:e}=t,n=ga(),a=bn(jr),i=y.useRef(null);return y.useLayoutEffect(()=>{a!=="centric"&&a!=="radial"||(i.current===null?n(xne(e)):i.current!==e&&n(yne({prev:i.current,next:e})),i.current=e)},[n,a,e]),y.useLayoutEffect(()=>()=>{i.current&&(n(vne(i.current)),i.current=null)},[n]),null}var a3,u8e=()=>{var[t]=y.useState(()=>Gw("uid-"));return t},m8e=(a3=Wue.useId)!==null&&a3!==void 0?a3:u8e;function p8e(t,e){var n=m8e();return e||(t?"".concat(t,"-").concat(n):n)}var h8e=y.createContext(void 0),MA=t=>{var{id:e,type:n,children:a}=t,i=p8e("recharts-".concat(n),e);return y.createElement(h8e.Provider,{value:i},a(i))},f8e={cartesianItems:[],polarItems:[]},tie=Jo({name:"graphicalItems",initialState:f8e,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:Ra()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:a}=e.payload,i=ud(t).cartesianItems.indexOf(n);i>-1&&(t.cartesianItems[i]=a)},prepare:Ra()},removeCartesianGraphicalItem:{reducer(t,e){var n=ud(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:Ra()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:Ra()},removePolarGraphicalItem:{reducer(t,e){var n=ud(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:Ra()}}}),{addCartesianGraphicalItem:g8e,replaceCartesianGraphicalItem:b8e,removeCartesianGraphicalItem:x8e,addPolarGraphicalItem:y8e,removePolarGraphicalItem:v8e}=tie.actions,w8e=tie.reducer,S8e=t=>{var e=ga(),n=y.useRef(null);return y.useLayoutEffect(()=>{n.current===null?e(g8e(t)):n.current!==t&&e(b8e({prev:n.current,next:t})),n.current=t},[e,t]),y.useLayoutEffect(()=>()=>{n.current&&(e(x8e(n.current)),n.current=null)},[e]),null},n5=y.memo(S8e);function _8e(t){var e=ga();return y.useLayoutEffect(()=>(e(y8e(t)),()=>{e(v8e(t))}),[e,t]),null}var k8e=["key"],N8e=["onMouseEnter","onClick","onMouseLeave"],C8e=["id"],P8e=["id"];function JW(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function ni(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?JW(Object(n),!0).forEach(function(a){T8e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):JW(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function T8e(t,e,n){return(e=A8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function A8e(t){var e=j8e(t,"string");return typeof e=="symbol"?e:e+""}function j8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},Jh.apply(null,arguments)}function EA(t,e){if(t==null)return{};var n,a,i=M8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function M8e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function E8e(t){var e=y.useMemo(()=>Qz(t.children,Ly),[t.children]),n=bn(a=>BHe(a,t.id,e));return n==null?null:y.createElement(d8e,{legendPayload:n})}var D8e=y.memo(t=>{var{dataKey:e,nameKey:n,sectors:a,stroke:i,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:a.map(p=>p.tooltipPayload),getPosition:p=>{var f;return(f=a[Number(p)])===null||f===void 0?void 0:f.tooltipPosition},settings:{stroke:i,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:sf(l,e),hide:c,type:d,color:o,unit:"",graphicalItemId:u}};return y.createElement(jA,{tooltipEntrySettings:m})}),F8e=(t,e)=>t>e?"start":t<e?"end":"middle",L8e=(t,e,n)=>no(typeof e=="function"?e(t):e,n,n*.8),R8e=(t,e,n)=>{var{top:a,left:i,width:s,height:o}=e,l=Pne(s,o),c=i+no(t.cx,s,s/2),d=a+no(t.cy,o,o/2),u=no(t.innerRadius,l,0),m=L8e(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}},I8e=(t,e)=>{var n=us(e-t),a=Math.min(Math.abs(e-t),360);return n*a},O8e=(t,e)=>{if(y.isValidElement(t))return y.cloneElement(t,e);if(typeof t=="function")return t(e);var n=Er("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:a}=e,i=EA(e,k8e);return y.createElement(dy,Jh({},i,{type:"linear",className:n}))},z8e=(t,e,n)=>{if(y.isValidElement(t))return y.cloneElement(t,e);var a=n;if(typeof t=="function"&&(a=t(e),y.isValidElement(a)))return a;var i=Er("recharts-pie-label-text",Zae(t));return y.createElement(CA,Jh({},e,{alignmentBaseline:"middle",className:i}),a)};function U8e(t){var{sectors:e,props:n,showLabels:a}=t,{label:i,labelLine:s,dataKey:o}=n;if(!a||!i||!e)return null;var l=_o(n),c=Ug(i),d=Ug(s),u=typeof i=="object"&&"offsetRadius"in i&&typeof i.offsetRadius=="number"&&i.offsetRadius||20,m=e.map((p,f)=>{var g=(p.startAngle+p.endAngle)/2,w=ki(p.cx,p.cy,p.outerRadius+u,g),b=ni(ni(ni(ni({},l),p),{},{stroke:"none"},c),{},{index:f,textAnchor:F8e(w.x,p.cx)},w),x=ni(ni(ni(ni({},l),p),{},{fill:"none",stroke:p.fill},d),{},{index:f,points:[ki(p.cx,p.cy,p.outerRadius,g),w],key:"line"});return y.createElement(so,{zIndex:ii.label,key:"label-".concat(p.startAngle,"-").concat(p.endAngle,"-").concat(p.midAngle,"-").concat(f)},y.createElement($a,null,s&&O8e(s,x),z8e(i,b,Gr(p,o))))});return y.createElement($a,{className:"recharts-pie-labels"},m)}function B8e(t){var{sectors:e,props:n,showLabels:a}=t,{label:i}=n;return typeof i=="object"&&i!=null&&"position"in i?y.createElement(PA,{label:i}):y.createElement(U8e,{sectors:e,props:n,showLabels:a})}function H8e(t){var{sectors:e,activeShape:n,inactiveShape:a,allOtherPieProps:i,shape:s,id:o}=t,l=bn(Zh),c=bn(Uz),d=bn(eUe),{onMouseEnter:u,onClick:m,onMouseLeave:p}=i,f=EA(i,N8e),g=Zz(u,i.dataKey,o),w=Jz(p),b=e5(m,i.dataKey,o);return e==null||e.length===0?null:y.createElement(y.Fragment,null,e.map((x,S)=>{if(x?.startAngle===0&&x?.endAngle===0&&e.length!==1)return null;var k=d==null||d===o,C=String(S)===l&&(c==null||i.dataKey===c)&&k,P=l?a:null,T=n&&C?n:P,A=ni(ni({},x),{},{stroke:x.stroke,tabIndex:-1,[ane]:S,[ine]:o});return y.createElement($a,Jh({key:"sector-".concat(x?.startAngle,"-").concat(x?.endAngle,"-").concat(x.midAngle,"-").concat(S),tabIndex:-1,className:"recharts-pie-sector"},qS(f,x,S),{onMouseEnter:g(x,S),onMouseLeave:w(x,S),onClick:b(x,S)}),y.createElement(Xz,Jh({option:s??T,index:S,shapeType:"sector",isActive:C},A)))}))}function q8e(t){var e,{pieSettings:n,displayedData:a,cells:i,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:d,nameKey:u,tooltipType:m}=n,p=Math.abs(n.minAngle),f=I8e(l,c),g=Math.abs(f),w=a.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,b=a.filter(T=>Gr(T,d,0)!==0).length,x=(g>=360?b:b-1)*w,S=g-b*p-x,k=a.reduce((T,A)=>{var F=Gr(A,d,0);return T+(hn(F)?F:0)},0),C;if(k>0){var P;C=a.map((T,A)=>{var F=Gr(T,d,0),_=Gr(T,u,A),M=R8e(n,s,T),H=(hn(F)?F:0)/k,I,z=ni(ni({},T),i&&i[A]&&i[A].props);A?I=P.endAngle+us(f)*w*(F!==0?1:0):I=l;var L=I+us(f)*((F!==0?p:0)+H*S),Z=(I+L)/2,ne=(M.innerRadius+M.outerRadius)/2,Y=[{name:_,value:F,payload:z,dataKey:d,type:m,graphicalItemId:n.id}],ce=ki(M.cx,M.cy,ne,Z);return P=ni(ni(ni(ni({},n.presentationProps),{},{percent:H,cornerRadius:typeof o=="string"?parseFloat(o):o,name:_,tooltipPayload:Y,midAngle:Z,middleRadius:ne,tooltipPosition:ce},z),M),{},{value:F,dataKey:d,startAngle:I,endAngle:L,payload:z,paddingAngle:us(f)*w}),P})}return C}function $8e(t){var{showLabels:e,sectors:n,children:a}=t,i=y.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 y.createElement(kHe,{value:e?i:void 0},a)}function V8e(t){var{props:e,previousSectorsRef:n,id:a}=t,{sectors:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:d,inactiveShape:u,onAnimationStart:m,onAnimationEnd:p}=e,f=nv(e,"recharts-pie-"),g=n.current,[w,b]=y.useState(!1),x=y.useCallback(()=>{typeof p=="function"&&p(),b(!1)},[p]),S=y.useCallback(()=>{typeof m=="function"&&m(),b(!0)},[m]);return y.createElement($8e,{showLabels:!w,sectors:i},y.createElement(tv,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:S,onAnimationEnd:x,key:f},k=>{var C,P=[],T=i&&i[0],A=(C=T?.startAngle)!==null&&C!==void 0?C:0;return i?.forEach((F,_)=>{var M=g&&g[_],H=_>0?Hg(F,"paddingAngle",0):0;if(M){var I=qr(M.endAngle-M.startAngle,F.endAngle-F.startAngle,k),z=ni(ni({},F),{},{startAngle:A+H,endAngle:A+I+H});P.push(z),A=z.endAngle}else{var{endAngle:L,startAngle:Z}=F,ne=qr(0,L-Z,k),Y=ni(ni({},F),{},{startAngle:A+H,endAngle:A+ne+H});P.push(Y),A=Y.endAngle}}),n.current=P,y.createElement($a,null,y.createElement(H8e,{sectors:P,activeShape:d,inactiveShape:u,allOtherPieProps:e,shape:e.shape,id:a}))}),y.createElement(B8e,{showLabels:!w,sectors:i,props:e}),e.children)}var G8e={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:ii.area};function W8e(t){var{id:e}=t,n=EA(t,C8e),{hide:a,className:i,rootTabIndex:s}=t,o=y.useMemo(()=>Qz(t.children,Ly),[t.children]),l=bn(u=>HHe(u,e,o)),c=y.useRef(null),d=Er("recharts-pie",i);return a||l==null?(c.current=null,y.createElement($a,{tabIndex:s,className:d})):y.createElement(so,{zIndex:t.zIndex},y.createElement(D8e,{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}),y.createElement($a,{tabIndex:s,className:d},y.createElement(V8e,{props:ni(ni({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function XR(t){var e=Va(t,G8e),{id:n}=e,a=EA(e,P8e),i=_o(a);return y.createElement(MA,{id:n,type:"pie"},s=>y.createElement(y.Fragment,null,y.createElement(_8e,{type:"pie",id:s,data:a.data,dataKey:a.dataKey,hide:a.hide,angleAxisId:0,radiusAxisId:0,name:a.name,nameKey:a.nameKey,tooltipType:a.tooltipType,legendType:a.legendType,fill:a.fill,cx:a.cx,cy:a.cy,startAngle:a.startAngle,endAngle:a.endAngle,paddingAngle:a.paddingAngle,minAngle:a.minAngle,innerRadius:a.innerRadius,outerRadius:a.outerRadius,cornerRadius:a.cornerRadius,presentationProps:i,maxRadius:e.maxRadius}),y.createElement(E8e,Jh({},a,{id:s})),y.createElement(W8e,Jh({},a,{id:s}))))}XR.displayName="Pie";var K8e=["points"];function eK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function i3(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?eK(Object(n),!0).forEach(function(a){Q8e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):eK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function Q8e(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=X8e(t,"string");return typeof e=="symbol"?e:e+""}function X8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function pP(){return pP=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},pP.apply(null,arguments)}function Z8e(t,e){if(t==null)return{};var n,a,i=J8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function J8e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function e6e(t){var{option:e,dotProps:n,className:a}=t;if(y.isValidElement(e))return y.cloneElement(e,n);if(typeof e=="function")return e(n);var i=Er(a,typeof e!="boolean"?e.className:""),s=n??{},{points:o}=s,l=Z8e(s,K8e);return y.createElement(Kae,pP({},l,{className:i}))}function t6e(t,e){return t==null?!1:e?!0:t.length===1}function nie(t){var{points:e,dot:n,className:a,dotClassName:i,dataKey:s,baseProps:o,needClip:l,clipPathId:c,zIndex:d=ii.scatter}=t;if(!t6e(e,n))return null;var u=Yz(n),m=_2e(n),p=e.map((g,w)=>{var b,x,S=i3(i3(i3({r:3},o),m),{},{index:w,cx:(b=g.x)!==null&&b!==void 0?b:void 0,cy:(x=g.y)!==null&&x!==void 0?x:void 0,dataKey:s,value:g.value,payload:g.payload,points:e});return y.createElement(e6e,{key:"dot-".concat(w),option:n,dotProps:S,className:i})}),f={};return l&&c!=null&&(f.clipPath="url(#clipPath-".concat(u?"":"dots-").concat(c,")")),y.createElement(so,{zIndex:d},y.createElement($a,pP({className:a},f),p))}function tK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function nK(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?tK(Object(n),!0).forEach(function(a){n6e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):tK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function n6e(t,e,n){return(e=r6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function r6e(t){var e=a6e(t,"string");return typeof e=="symbol"?e:e+""}function a6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var rie=0,i6e={xAxis:{},yAxis:{},zAxis:{}},aie=Jo({name:"cartesianAxis",initialState:i6e,reducers:{addXAxis:{reducer(t,e){t.xAxis[e.payload.id]=e.payload},prepare:Ra()},replaceXAxis:{reducer(t,e){var{prev:n,next:a}=e.payload;t.xAxis[n.id]!==void 0&&(n.id!==a.id&&delete t.xAxis[n.id],t.xAxis[a.id]=a)},prepare:Ra()},removeXAxis:{reducer(t,e){delete t.xAxis[e.payload.id]},prepare:Ra()},addYAxis:{reducer(t,e){t.yAxis[e.payload.id]=e.payload},prepare:Ra()},replaceYAxis:{reducer(t,e){var{prev:n,next:a}=e.payload;t.yAxis[n.id]!==void 0&&(n.id!==a.id&&delete t.yAxis[n.id],t.yAxis[a.id]=a)},prepare:Ra()},removeYAxis:{reducer(t,e){delete t.yAxis[e.payload.id]},prepare:Ra()},addZAxis:{reducer(t,e){t.zAxis[e.payload.id]=e.payload},prepare:Ra()},replaceZAxis:{reducer(t,e){var{prev:n,next:a}=e.payload;t.zAxis[n.id]!==void 0&&(n.id!==a.id&&delete t.zAxis[n.id],t.zAxis[a.id]=a)},prepare:Ra()},removeZAxis:{reducer(t,e){delete t.zAxis[e.payload.id]},prepare:Ra()},updateYAxisWidth(t,e){var{id:n,width:a}=e.payload,i=t.yAxis[n];if(i){var s,o=i.widthHistory||[];if(o.length===3&&o[0]===o[2]&&a===o[1]&&a!==i.width&&Math.abs(a-((s=o[0])!==null&&s!==void 0?s:0))<=1)return;var l=[...o,a].slice(-3);t.yAxis[n]=nK(nK({},i),{},{width:a,widthHistory:l})}}}}),{addXAxis:s6e,replaceXAxis:o6e,removeXAxis:l6e,addYAxis:c6e,replaceYAxis:d6e,removeYAxis:u6e,addZAxis:Act,replaceZAxis:jct,removeZAxis:Mct,updateYAxisWidth:m6e}=aie.actions,p6e=aie.reducer,h6e=Pt([qi],t=>({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),f6e=Pt([h6e,rp,ap],(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)}}),DA=()=>bn(f6e),g6e=()=>bn(iUe);function rK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function s3(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rK(Object(n),!0).forEach(function(a){b6e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function b6e(t,e,n){return(e=x6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function x6e(t){var e=y6e(t,"string");return typeof e=="symbol"?e:e+""}function y6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var v6e=t=>{var{point:e,childIndex:n,mainColor:a,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:a??"none",strokeWidth:2,stroke:"#fff",payload:e.payload,value:e.value},c=s3(s3(s3({},l),Ug(i)),b4(i)),d;return y.isValidElement(i)?d=y.cloneElement(i,c):typeof i=="function"?d=i(c):d=y.createElement(Kae,c),y.createElement($a,{className:"recharts-active-dot",clipPath:o},d)};function ZR(t){var{points:e,mainColor:n,activeDot:a,itemDataKey:i,clipPath:s,zIndex:o=ii.activeDot}=t,l=bn(Zh),c=g6e();if(e==null||c==null)return null;var d=e.find(u=>c.includes(u.payload));return Ua(d)?null:y.createElement(so,{zIndex:o},y.createElement(v6e,{point:d,childIndex:Number(l),mainColor:n,dataKey:i,activeDot:a,clipPath:s}))}var aK=(t,e,n)=>{var a=n??t;if(!Ua(a))return no(a,e,0)},w6e=(t,e,n)=>{var a={},i=t.filter(xA),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},a),l=Object.entries(o).map(d=>{var u,[m,p]=d,f=p.map(w=>w.dataKey),g=aK(e,n,(u=p[0])===null||u===void 0?void 0:u.barSize);return{stackId:m,dataKeys:f,barSize:g}}),c=s.map(d=>{var u=[d.dataKey].filter(p=>p!=null),m=aK(e,n,d.barSize);return{stackId:void 0,dataKeys:u,barSize:m}});return[...l,...c]};function iK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function q1(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?iK(Object(n),!0).forEach(function(a){S6e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):iK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function S6e(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=k6e(t,"string");return typeof e=="symbol"?e:e+""}function k6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function N6e(t,e,n,a,i){var s,o=a.length;if(!(o<1)){var l=no(t,n,0,!0),c,d=[];if(Kn((s=a[0])===null||s===void 0?void 0:s.barSize)){var u=!1,m=n/o,p=a.reduce((S,k)=>S+(k.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,g={offset:f-l,size:0};c=a.reduce((S,k)=>{var C,P={stackId:k.stackId,dataKeys:k.dataKeys,position:{offset:g.offset+g.size+l,size:u?m:(C=k.barSize)!==null&&C!==void 0?C:0}},T=[...S,P];return g=P.position,T},d)}else{var w=no(e,n,0,!0);n-2*w-(o-1)*l<=0&&(l=0);var b=(n-2*w-(o-1)*l)/o;b>1&&(b>>=0);var x=Kn(i)?Math.min(b,i):b;c=a.reduce((S,k,C)=>[...S,{stackId:k.stackId,dataKeys:k.dataKeys,position:{offset:w+(b+l)*C+(b-x)/2,size:x}}],d)}return c}}var C6e=(t,e,n,a,i,s,o)=>{var l=Ua(o)?e:o,c=N6e(n,a,i!==s?i:s,t,l);return i!==s&&c!=null&&(c=c.map(d=>q1(q1({},d),{},{position:q1(q1({},d.position),{},{offset:d.position.offset-i/2})}))),c},P6e=(t,e)=>{var n=bA(e);if(!(!t||n==null||e==null)){var{stackId:a}=e;if(a!=null){var i=t[a];if(i){var{stackedData:s}=i;if(s)return s.find(o=>o.key===n)}}}},T6e=(t,e)=>{if(!(t==null||e==null)){var n=t.find(a=>a.stackId===e.stackId&&e.dataKey!=null&&a.dataKeys.includes(e.dataKey));if(n!=null)return n.position}};function A6e(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&Kn(t.zIndex)?t.zIndex:e}var iie=t=>{var{chartData:e}=t,n=ga(),a=$i();return y.useEffect(()=>a?()=>{}:(n(uW(e)),()=>{n(uW(void 0))}),[e,n,a]),null},sK={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},sie=Jo({name:"brush",initialState:sK,reducers:{setBrushSettings(t,e){return e.payload==null?sK:e.payload}}}),{setBrushSettings:Ect}=sie.actions,j6e=sie.reducer,M6e=(t,e)=>{var{x:n,y:a}=t,{x:i,y:s}=e;return{x:Math.min(n,i),y:Math.min(a,s),width:Math.abs(i-n),height:Math.abs(s-a)}},E6e=t=>{var{x1:e,y1:n,x2:a,y2:i}=t;return M6e({x:e,y:n},{x:a,y:i})};function D6e(t){return(t%180+180)%180}var F6e=function(e){var{width:n,height:a}=e,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=D6e(i),o=s*Math.PI/180,l=Math.atan(a/n),c=o>l&&o<Math.PI-l?a/Math.sin(o):n/Math.cos(o);return Math.abs(c)},L6e={dots:[],areas:[],lines:[]},oie=Jo({name:"referenceElements",initialState:L6e,reducers:{addDot:(t,e)=>{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=ud(t).dots.findIndex(a=>a===e.payload);n!==-1&&t.dots.splice(n,1)},addArea:(t,e)=>{t.areas.push(e.payload)},removeArea:(t,e)=>{var n=ud(t).areas.findIndex(a=>a===e.payload);n!==-1&&t.areas.splice(n,1)},addLine:(t,e)=>{t.lines.push(e.payload)},removeLine:(t,e)=>{var n=ud(t).lines.findIndex(a=>a===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:Dct,removeDot:Fct,addArea:Lct,removeArea:Rct,addLine:R6e,removeLine:I6e}=oie.actions,O6e=oie.reducer,lie=y.createContext(void 0),z6e=t=>{var{children:e}=t,[n]=y.useState("".concat(Gw("recharts"),"-clip")),a=DA();if(a==null)return null;var{x:i,y:s,width:o,height:l}=a;return y.createElement(lie.Provider,{value:n},y.createElement("defs",null,y.createElement("clipPath",{id:n},y.createElement("rect",{x:i,y:s,height:l,width:o}))),e)},U6e=()=>y.useContext(lie);class B6e{constructor(e){var{x:n,y:a}=e;this.xAxisScale=n,this.yAxisScale=a}map(e,n){var a,i,{position:s}=n;return{x:(a=this.xAxisScale.map(e.x,{position:s}))!==null&&a!==void 0?a:0,y:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:0}}mapWithFallback(e,n){var a,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:(a=this.xAxisScale.map(e.x,{position:s}))!==null&&a!==void 0?a:c,y:(i=this.yAxisScale.map(e.y,{position:s}))!==null&&i!==void 0?i:l}}isInRange(e){var{x:n,y:a}=e,i=n==null||this.xAxisScale.isInRange(n),s=a==null||this.yAxisScale.isInRange(a);return i&&s}}function oK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function lK(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?oK(Object(n),!0).forEach(function(a){H6e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function H6e(t,e,n){return(e=q6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function q6e(t){var e=$6e(t,"string");return typeof e=="symbol"?e:e+""}function $6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function hP(){return hP=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},hP.apply(null,arguments)}var V6e=(t,e)=>{var n;if(y.isValidElement(t))n=y.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!Kn(e.x1)||!Kn(e.y1)||!Kn(e.x2)||!Kn(e.y2))return null;n=y.createElement("line",hP({},e,{className:"recharts-reference-line-line"}))}return n},G6e=(t,e,n,a,i,s)=>{var{x:o,width:l}=s,c=i.map(t,{position:n});if(!Kn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:o+l,y:c},{x:o,y:c}];return a==="left"?d.reverse():d},W6e=(t,e,n,a,i,s)=>{var{y:o,height:l}=s,c=i.map(t,{position:n});if(!Kn(c)||e==="discard"&&!i.isInRange(c))return null;var d=[{x:c,y:o+l},{x:c,y:o}];return a==="top"?d.reverse():d},K6e=(t,e,n,a)=>{var i=[a.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),a.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&i.some(s=>!a.isInRange(s))?null:i},Q6e=(t,e,n,a,i,s,o)=>{var{x:l,y:c,segment:d,ifOverflow:u}=o,m=kc(l),p=kc(c);return p?G6e(c,u,a,s,e,n):m?W6e(l,u,a,i,t,n):d!=null&&d.length===2?K6e(d,u,a,new B6e({x:t,y:e})):null};function Y6e(t){var e=ga();return y.useEffect(()=>(e(R6e(t)),()=>{e(I6e(t))})),null}function X6e(t){var{xAxisId:e,yAxisId:n,shape:a,className:i,ifOverflow:s}=t,o=$i(),l=U6e(),c=bn(A=>ku(A,e)),d=bn(A=>Nu(A,n)),u=bn(A=>Fy(A,"xAxis",e,o)),m=bn(A=>Fy(A,"yAxis",n,o)),p=WS();if(!l||!p||c==null||d==null||u==null||m==null)return null;var f=Q6e(u,m,p,t.position,c.orientation,d.orientation,t);if(!f)return null;var g=f[0],w=f[1];if(g==null||w==null)return null;var{x:b,y:x}=g,{x:S,y:k}=w,C=s==="hidden"?"url(#".concat(l,")"):void 0,P=lK(lK({clipPath:C},Os(t)),{},{x1:b,y1:x,x2:S,y2:k}),T=E6e({x1:b,y1:x,x2:S,y2:k});return y.createElement(so,{zIndex:t.zIndex},y.createElement($a,{className:Er("recharts-reference-line",i)},V6e(a,P),y.createElement(qae,hP({},T,{lowerWidth:T.width,upperWidth:T.width}),y.createElement(Vae,{label:t.label}),t.children)))}var Z6e={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:ii.line};function iu(t){var e=Va(t,Z6e);return y.createElement(y.Fragment,null,y.createElement(Y6e,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),y.createElement(X6e,e))}iu.displayName="ReferenceLine";function cie(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],a=0;a<t.length;a+=e){var i=t[a];i!==void 0&&n.push(i)}return n}function J6e(t,e,n){var a={width:t.width+e.width,height:t.height+e.height};return F6e(a,n)}function eqe(t,e,n){var a=n==="width",{x:i,y:s,width:o,height:l}=t;return e===1?{start:a?i:s,end:a?i+o:s+l}:{start:a?i+o:s+l,end:a?i:s}}function sS(t,e,n,a,i){if(t*e<t*a||t*e>t*i)return!1;var s=n();return t*(e-t*s/2-a)>=0&&t*(e+t*s/2-i)<=0}function tqe(t,e){return cie(t,e+1)}function nqe(t,e,n,a,i){for(var s=(a||[]).slice(),{start:o,end:l}=e,c=0,d=1,u=o,m=function(){var g=a?.[c];if(g===void 0)return{v:cie(a,d)};var w=c,b,x=()=>(b===void 0&&(b=n(g,w)),b),S=g.coordinate,k=c===0||sS(t,S,x,u,l);k||(c=0,u=o,d+=1),k&&(u=S+t*(x()/2+i),c+=d)},p;d<=s.length;)if(p=m(),p)return p.v;return[]}function rqe(t,e,n,a,i){var s=(a||[]).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 C=a[w];if(C==null)return 0;var P=w,T,A=()=>(T===void 0&&(T=n(C,P)),T),F=C.coordinate,_=w===u||sS(t,F,A,m,c);if(!_)return p=!1,1;_&&(m=F+t*(A()/2+i))},g,w=u;w<o&&(g=f(),!(g!==0&&g===1));w+=d);if(p){for(var b=[],x=u;x<o;x+=d){var S=a[x];S!=null&&b.push(S)}return b}}return[]}function cK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Qs(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cK(Object(n),!0).forEach(function(a){aqe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function aqe(t,e,n){return(e=iqe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function iqe(t){var e=sqe(t,"string");return typeof e=="symbol"?e:e+""}function sqe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function oqe(t,e,n,a,i){for(var s=(a||[]).slice(),o=s.length,{start:l}=e,{end:c}=e,d=function(p){var f=s[p];if(f==null)return 1;var g=f,w,b=()=>(w===void 0&&(w=n(f,p)),w);if(p===o-1){var x=t*(g.coordinate+t*b()/2-c);s[p]=g=Qs(Qs({},g),{},{tickCoord:x>0?g.coordinate-x*t:g.coordinate})}else s[p]=g=Qs(Qs({},g),{},{tickCoord:g.coordinate});if(g.tickCoord!=null){var S=sS(t,g.tickCoord,b,l,c);S&&(c=g.tickCoord-t*(b()/2+i),s[p]=Qs(Qs({},g),{},{isShow:!0}))}},u=o-1;u>=0;u--)d(u);return s}function lqe(t,e,n,a,i,s){var o=(a||[]).slice(),l=o.length,{start:c,end:d}=e;if(s){var u=a[l-1];if(u!=null){var m=n(u,l-1),p=t*(u.coordinate+t*m/2-d);if(o[l-1]=u=Qs(Qs({},u),{},{tickCoord:p>0?u.coordinate-p*t:u.coordinate}),u.tickCoord!=null){var f=sS(t,u.tickCoord,()=>m,c,d);f&&(d=u.tickCoord-t*(m/2+i),o[l-1]=Qs(Qs({},u),{},{isShow:!0}))}}}for(var g=s?l-1:l,w=function(S){var k=o[S];if(k==null)return 1;var C=k,P,T=()=>(P===void 0&&(P=n(k,S)),P);if(S===0){var A=t*(C.coordinate-t*T()/2-c);o[S]=C=Qs(Qs({},C),{},{tickCoord:A<0?C.coordinate-A*t:C.coordinate})}else o[S]=C=Qs(Qs({},C),{},{tickCoord:C.coordinate});if(C.tickCoord!=null){var F=sS(t,C.tickCoord,T,c,d);F&&(c=C.tickCoord+t*(T()/2+i),o[S]=Qs(Qs({},C),{},{isShow:!0}))}},b=0;b<g;b++)w(b);return o}function r5(t,e,n){var{tick:a,ticks:i,viewBox:s,minTickGap:o,orientation:l,interval:c,tickFormatter:d,unit:u,angle:m}=t;if(!i||!i.length||!a)return[];if(hn(c)||YS.isSsr){var p;return(p=tqe(i,hn(c)?c:0))!==null&&p!==void 0?p:[]}var f=[],g=l==="top"||l==="bottom"?"width":"height",w=u&&g==="width"?iw(u,{fontSize:e,letterSpacing:n}):{width:0,height:0},b=(P,T)=>{var A=typeof d=="function"?d(P.value,T):P.value;return g==="width"?J6e(iw(A,{fontSize:e,letterSpacing:n}),w,m):iw(A,{fontSize:e,letterSpacing:n})[g]},x=i[0],S=i[1],k=i.length>=2&&x!=null&&S!=null?us(S.coordinate-x.coordinate):1,C=eqe(s,k,g);return c==="equidistantPreserveStart"?nqe(k,C,b,i,o):c==="equidistantPreserveEnd"?rqe(k,C,b,i,o):(c==="preserveStart"||c==="preserveStartEnd"?f=lqe(k,C,b,i,o,c==="preserveStartEnd"):f=oqe(k,C,b,i,o),f.filter(P=>P.isShow))}var cqe=t=>{var{ticks:e,label:n,labelGapWithTick:a=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?a:0);return Math.round(d)}return 0},dqe=["axisLine","width","height","className","hide","ticks","axisType"];function uqe(t,e){if(t==null)return{};var n,a,i=mqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function mqe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function Kg(){return Kg=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},Kg.apply(null,arguments)}function dK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function ei(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?dK(Object(n),!0).forEach(function(a){pqe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):dK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function pqe(t,e,n){return(e=hqe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function hqe(t){var e=fqe(t,"string");return typeof e=="symbol"?e:e+""}function fqe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Om={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:ii.axis};function gqe(t){var{x:e,y:n,width:a,height:i,orientation:s,mirror:o,axisLine:l,otherSvgProps:c}=t;if(!l)return null;var d=ei(ei(ei({},c),_o(l)),{},{fill:"none"});if(s==="top"||s==="bottom"){var u=+(s==="top"&&!o||s==="bottom"&&o);d=ei(ei({},d),{},{x1:e,y1:n+u*i,x2:e+a,y2:n+u*i})}else{var m=+(s==="left"&&!o||s==="right"&&o);d=ei(ei({},d),{},{x1:e+m*a,y1:n,x2:e+m*a,y2:n+i})}return y.createElement("line",Kg({},d,{className:Er("recharts-cartesian-axis-line",Hg(l,"className"))}))}function bqe(t,e,n,a,i,s,o,l,c){var d,u,m,p,f,g,w=l?-1:1,b=t.tickSize||o,x=hn(t.tickCoord)?t.tickCoord:t.coordinate;switch(s){case"top":d=u=t.coordinate,p=n+ +!l*i,m=p-w*b,g=m-w*c,f=x;break;case"left":m=p=t.coordinate,u=e+ +!l*a,d=u-w*b,f=d-w*c,g=x;break;case"right":m=p=t.coordinate,u=e+ +l*a,d=u+w*b,f=d+w*c,g=x;break;default:d=u=t.coordinate,p=n+ +l*i,m=p+w*b,g=m+w*c,f=x;break}return{line:{x1:d,y1:m,x2:u,y2:p},tick:{x:f,y:g}}}function xqe(t,e){switch(t){case"left":return e?"start":"end";case"right":return e?"end":"start";default:return"middle"}}function yqe(t,e){switch(t){case"left":case"right":return"middle";case"top":return e?"start":"end";default:return e?"end":"start"}}function vqe(t){var{option:e,tickProps:n,value:a}=t,i,s=Er(n.className,"recharts-cartesian-axis-tick-value");if(y.isValidElement(e))i=y.cloneElement(e,ei(ei({},n),{},{className:s}));else if(typeof e=="function")i=e(ei(ei({},n),{},{className:s}));else{var o="recharts-cartesian-axis-tick-value";typeof e!="boolean"&&(o=Er(o,Zae(e))),i=y.createElement(CA,Kg({},n,{className:o}),a)}return i}var wqe=y.forwardRef((t,e)=>{var{ticks:n=[],tick:a,tickLine:i,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:d,orientation:u,mirror:m,x:p,y:f,width:g,height:w,tickSize:b,tickMargin:x,fontSize:S,letterSpacing:k,getTicksConfig:C,events:P,axisType:T}=t,A=r5(ei(ei({},C),{},{ticks:n}),S,k),F=xqe(u,m),_=yqe(u,m),M=_o(C),H=Ug(a),I={};typeof i=="object"&&(I=i);var z=ei(ei({},M),{},{fill:"none"},I),L=A.map(Y=>ei({entry:Y},bqe(Y,p,f,g,w,u,b,m,x))),Z=L.map(Y=>{var{entry:ce,line:ue}=Y;return y.createElement($a,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(ce.value,"-").concat(ce.coordinate,"-").concat(ce.tickCoord)},i&&y.createElement("line",Kg({},z,ue,{className:Er("recharts-cartesian-axis-tick-line",Hg(i,"className"))})))}),ne=L.map((Y,ce)=>{var ue,oe,{entry:Q,tick:le}=Y,pe=ei(ei(ei(ei({verticalAnchor:_},M),{},{textAnchor:F,stroke:"none",fill:s},le),{},{index:ce,payload:Q,visibleTicksCount:A.length,tickFormatter:o,padding:c},d),{},{angle:(ue=(oe=d?.angle)!==null&&oe!==void 0?oe:M.angle)!==null&&ue!==void 0?ue:0}),he=ei(ei({},pe),H);return y.createElement($a,Kg({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(Q.value,"-").concat(Q.coordinate,"-").concat(Q.tickCoord)},qS(P,Q,ce)),a&&y.createElement(vqe,{option:a,tickProps:he,value:"".concat(typeof o=="function"?o(Q.value,ce):Q.value).concat(l||"")}))});return y.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(T,"-ticks")},ne.length>0&&y.createElement(so,{zIndex:ii.label},y.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(T,"-tick-labels"),ref:e},ne)),Z.length>0&&y.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(T,"-tick-lines")},Z))}),Sqe=y.forwardRef((t,e)=>{var{axisLine:n,width:a,height:i,className:s,hide:o,ticks:l,axisType:c}=t,d=uqe(t,dqe),[u,m]=y.useState(""),[p,f]=y.useState(""),g=y.useRef(null);y.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var b;return cqe({ticks:g.current,label:(b=t.labelRef)===null||b===void 0?void 0:b.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var w=y.useCallback(b=>{if(b){var x=b.getElementsByClassName("recharts-cartesian-axis-tick-value");g.current=x;var S=x[0];if(S){var k=window.getComputedStyle(S),C=k.fontSize,P=k.letterSpacing;(C!==u||P!==p)&&(m(C),f(P))}}},[u,p]);return o||a!=null&&a<=0||i!=null&&i<=0?null:y.createElement(so,{zIndex:t.zIndex},y.createElement($a,{className:Er("recharts-cartesian-axis",s)},y.createElement(gqe,{x:t.x,y:t.y,width:a,height:i,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:_o(t)}),y.createElement(wqe,{ref:w,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}),y.createElement(qae,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},y.createElement(Vae,{label:t.label,labelRef:t.labelRef}),t.children)))}),a5=y.forwardRef((t,e)=>{var n=Va(t,Om);return y.createElement(Sqe,Kg({},n,{ref:e}))});a5.displayName="CartesianAxis";var _qe=["x1","y1","x2","y2","key"],kqe=["offset"],Nqe=["xAxisId","yAxisId"],Cqe=["xAxisId","yAxisId"];function uK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Zs(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?uK(Object(n),!0).forEach(function(a){Pqe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):uK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function Pqe(t,e,n){return(e=Tqe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Tqe(t){var e=Aqe(t,"string");return typeof e=="symbol"?e:e+""}function Aqe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function cg(){return cg=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},cg.apply(null,arguments)}function fP(t,e){if(t==null)return{};var n,a,i=jqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function jqe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var Mqe=t=>{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:a,y:i,width:s,height:o,ry:l}=t;return y.createElement("rect",{x:a,y:i,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function die(t){var{option:e,lineItemProps:n}=t,a;if(y.isValidElement(e))a=y.cloneElement(e,n);else if(typeof e=="function")a=e(n);else{var i,{x1:s,y1:o,x2:l,y2:c,key:d}=n,u=fP(n,_qe),m=(i=_o(u))!==null&&i!==void 0?i:{},{offset:p}=m,f=fP(m,kqe);a=y.createElement("line",cg({},f,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:d}))}return a}function Eqe(t){var{x:e,width:n,horizontal:a=!0,horizontalPoints:i}=t;if(!a||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=fP(t,Nqe),c=i.map((d,u)=>{var m=Zs(Zs({},l),{},{x1:e,y1:d,x2:e+n,y2:d,key:"line-".concat(u),index:u});return y.createElement(die,{key:"line-".concat(u),option:a,lineItemProps:m})});return y.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function Dqe(t){var{y:e,height:n,vertical:a=!0,verticalPoints:i}=t;if(!a||!i||!i.length)return null;var{xAxisId:s,yAxisId:o}=t,l=fP(t,Cqe),c=i.map((d,u)=>{var m=Zs(Zs({},l),{},{x1:d,y1:e,x2:d,y2:e+n,key:"line-".concat(u),index:u});return y.createElement(die,{option:a,lineItemProps:m,key:"line-".concat(u)})});return y.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function Fqe(t){var{horizontalFill:e,fillOpacity:n,x:a,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],g=f==null,w=g?i+o-m:f-m;if(w<=0)return null;var b=p%e.length;return y.createElement("rect",{key:"react-".concat(p),y:m,x:a,height:w,width:s,stroke:"none",fill:e[b],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return y.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},u)}function Lqe(t){var{vertical:e=!0,verticalFill:n,fillOpacity:a,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],g=f==null,w=g?i+o-m:f-m;if(w<=0)return null;var b=p%n.length;return y.createElement("rect",{key:"react-".concat(p),x:m,y:s,width:w,height:l,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return y.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},u)}var Rqe=(t,e)=>{var{xAxis:n,width:a,height:i,offset:s}=t;return ene(r5(Zs(Zs(Zs({},Om),n),{},{ticks:tne(n),viewBox:{x:0,y:0,width:a,height:i}})),s.left,s.left+s.width,e)},Iqe=(t,e)=>{var{yAxis:n,width:a,height:i,offset:s}=t;return ene(r5(Zs(Zs(Zs({},Om),n),{},{ticks:tne(n),viewBox:{x:0,y:0,width:a,height:i}})),s.top,s.top+s.height,e)},Oqe={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:ii.grid};function Pm(t){var e=j4(),n=M4(),a=cne(),i=Zs(Zs({},Va(t,Oqe)),{},{x:hn(t.x)?t.x:a.left,y:hn(t.y)?t.y:a.top,width:hn(t.width)?t.width:a.width,height:hn(t.height)?t.height:a.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:d,height:u,syncWithTicks:m,horizontalValues:p,verticalValues:f}=i,g=$i(),w=bn(_=>J9(_,"xAxis",s,g)),b=bn(_=>J9(_,"yAxis",o,g));if(!gu(d)||!gu(u)||!hn(l)||!hn(c))return null;var x=i.verticalCoordinatesGenerator||Rqe,S=i.horizontalCoordinatesGenerator||Iqe,{horizontalPoints:k,verticalPoints:C}=i;if((!k||!k.length)&&typeof S=="function"){var P=p&&p.length,T=S({yAxis:b?Zs(Zs({},b),{},{ticks:P?p:b.ticks}):void 0,width:e??d,height:n??u,offset:a},P?!0:m);zC(Array.isArray(T),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof T,"]")),Array.isArray(T)&&(k=T)}if((!C||!C.length)&&typeof x=="function"){var A=f&&f.length,F=x({xAxis:w?Zs(Zs({},w),{},{ticks:A?f:w.ticks}):void 0,width:e??d,height:n??u,offset:a},A?!0:m);zC(Array.isArray(F),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof F,"]")),Array.isArray(F)&&(C=F)}return y.createElement(so,{zIndex:i.zIndex},y.createElement("g",{className:"recharts-cartesian-grid"},y.createElement(Mqe,{fill:i.fill,fillOpacity:i.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),y.createElement(Fqe,cg({},i,{horizontalPoints:k})),y.createElement(Lqe,cg({},i,{verticalPoints:C})),y.createElement(Eqe,cg({},i,{offset:a,horizontalPoints:k,xAxis:w,yAxis:b})),y.createElement(Dqe,cg({},i,{offset:a,verticalPoints:C,xAxis:w,yAxis:b}))))}Pm.displayName="CartesianGrid";var zqe={},uie=Jo({name:"errorBars",initialState:zqe,reducers:{addErrorBar:(t,e)=>{var{itemId:n,errorBar:a}=e.payload;t[n]||(t[n]=[]),t[n].push(a)},replaceErrorBar:(t,e)=>{var{itemId:n,prev:a,next:i}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===a.dataKey&&s.direction===a.direction?i:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:a}=e.payload;t[n]&&(t[n]=t[n].filter(i=>i.dataKey!==a.dataKey||i.direction!==a.direction))}}}),{addErrorBar:Ict,replaceErrorBar:Oct,removeErrorBar:zct}=uie.actions,Uqe=uie.reducer,Bqe=["children"];function Hqe(t,e){if(t==null)return{};var n,a,i=qqe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function qqe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var $qe={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},Vqe=y.createContext($qe);function mie(t){var{children:e}=t,n=Hqe(t,Bqe);return y.createElement(Vqe.Provider,{value:n},e)}function FA(t,e){var n,a,i=bn(d=>ku(d,t)),s=bn(d=>Nu(d,e)),o=(n=i?.allowDataOverflow)!==null&&n!==void 0?n:ts.allowDataOverflow,l=(a=s?.allowDataOverflow)!==null&&a!==void 0?a:ns.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function i5(t){var{xAxisId:e,yAxisId:n,clipPathId:a}=t,i=DA(),{needClipX:s,needClipY:o,needClip:l}=FA(e,n);if(!l||!i)return null;var{x:c,y:d,width:u,height:m}=i;return y.createElement("clipPath",{id:"clipPath-".concat(a)},y.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 pie=(t,e,n,a)=>yu(t,"xAxis",e,a),hie=(t,e,n,a)=>xu(t,"xAxis",e,a),fie=(t,e,n,a)=>yu(t,"yAxis",n,a),gie=(t,e,n,a)=>xu(t,"yAxis",n,a),Gqe=Pt([jr,pie,fie,hie,gie],(t,e,n,a,i)=>vd(t,"xAxis")?Xh(e,a,!1):Xh(n,i,!1)),Wqe=(t,e,n,a,i)=>i;function Kqe(t){return t.type==="line"}var Qqe=Pt([r_,Wqe],(t,e)=>t.filter(Kqe).find(n=>n.id===e)),Yqe=Pt([jr,pie,fie,hie,gie,Qqe,Gqe,iz],(t,e,n,a,i,s,o,l)=>{var{chartData:c,dataStartIndex:d,dataEndIndex:u}=l;if(!(s==null||e==null||n==null||a==null||i==null||a.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 R$e({layout:t,xAxis:e,yAxis:n,xAxisTicks:a,yAxisTicks:i,dataKey:m,bandSize:o,displayedData:f})}});function bie(t){var e=Ug(t),n=3,a=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=a),{r:o,strokeWidth:l}}return{r:n,strokeWidth:a}}var o3={exports:{}},l3={};var mK;function Xqe(){if(mK)return l3;mK=1;var t=tb();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,a=t.useSyncExternalStore,i=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return l3.useSyncExternalStoreWithSelector=function(c,d,u,m,p){var f=i(null);if(f.current===null){var g={hasValue:!1,value:null};f.current=g}else g=f.current;f=o(function(){function b(P){if(!x){if(x=!0,S=P,P=m(P),p!==void 0&&g.hasValue){var T=g.value;if(p(T,P))return k=T}return k=P}if(T=k,n(S,P))return T;var A=m(P);return p!==void 0&&p(T,A)?(S=P,T):(S=P,k=A)}var x=!1,S,k,C=u===void 0?null:u;return[function(){return b(d())},C===null?void 0:function(){return b(C())}]},[d,u,m,p]);var w=a(c,f[0],f[1]);return s(function(){g.hasValue=!0,g.value=w},[w]),l(w),w},l3}var pK;function Zqe(){return pK||(pK=1,o3.exports=Xqe()),o3.exports}Zqe();function Jqe(t){t()}function e$e(){let t=null,e=null;return{clear(){t=null,e=null},notify(){Jqe(()=>{let n=t;for(;n;)n.callback(),n=n.next})},get(){const n=[];let a=t;for(;a;)n.push(a),a=a.next;return n},subscribe(n){let a=!0;const i=e={callback:n,next:null,prev:e};return i.prev?i.prev.next=i:t=i,function(){!a||t===null||(a=!1,i.next?i.next.prev=i.prev:e=i.prev,i.prev?i.prev.next=i.next:t=i.next)}}}}var hK={notify(){},get:()=>[]};function t$e(t,e){let n,a=hK,i=0,s=!1;function o(w){u();const b=a.subscribe(w);let x=!1;return()=>{x||(x=!0,b(),m())}}function l(){a.notify()}function c(){g.onStateChange&&g.onStateChange()}function d(){return s}function u(){i++,n||(n=t.subscribe(c),a=e$e())}function m(){i--,n&&i===0&&(n(),n=void 0,a.clear(),a=hK)}function p(){s||(s=!0,u())}function f(){s&&(s=!1,m())}const g={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:d,trySubscribe:p,tryUnsubscribe:f,getListeners:()=>a};return g}var n$e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",r$e=n$e(),a$e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",i$e=a$e(),s$e=()=>r$e||i$e?y.useLayoutEffect:y.useEffect,o$e=s$e();function fK(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function l$e(t,e){if(fK(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Object.keys(t),a=Object.keys(e);if(n.length!==a.length)return!1;for(let i=0;i<n.length;i++)if(!Object.prototype.hasOwnProperty.call(e,n[i])||!fK(t[n[i]],e[n[i]]))return!1;return!0}var c$e=Symbol.for("react-redux-context"),d$e=typeof globalThis<"u"?globalThis:{};function u$e(){if(!y.createContext)return{};const t=d$e[c$e]??=new Map;let e=t.get(y.createContext);return e||(e=y.createContext(null),t.set(y.createContext,e)),e}var m$e=u$e();function p$e(t){const{children:e,context:n,serverState:a,store:i}=t,s=y.useMemo(()=>{const c=t$e(i);return{store:i,subscription:c,getServerState:a?()=>a:void 0}},[i,a]),o=y.useMemo(()=>i.getState(),[i]);o$e(()=>{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||m$e;return y.createElement(l.Provider,{value:s},e)}var h$e=p$e,f$e=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function g$e(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function c_(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var a of n)if(f$e.has(a)){if(t[a]==null&&e[a]==null)continue;if(!l$e(t[a],e[a]))return!1}else if(!g$e(t[a],e[a]))return!1;return!0}var b$e=["id"],x$e=["type","layout","connectNulls","needClip","shape"],y$e=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function oS(){return oS=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},oS.apply(null,arguments)}function gK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Kd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gK(Object(n),!0).forEach(function(a){v$e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function v$e(t,e,n){return(e=w$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function w$e(t){var e=S$e(t,"string");return typeof e=="symbol"?e:e+""}function S$e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function s5(t,e){if(t==null)return{};var n,a,i=_$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function _$e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var k$e=t=>{var{dataKey:e,name:n,stroke:a,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:a,value:sf(n,e),payload:t}]},N$e=y.memo(t=>{var{dataKey:e,data:n,stroke:a,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:af,settings:{stroke:a,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:sf(o,e),hide:l,type:d,color:a,unit:c,graphicalItemId:u}};return y.createElement(jA,{tooltipEntrySettings:m})}),xie=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function C$e(t,e){for(var n=t.length%2!==0?[...t,0]:t,a=[],i=0;i<e;++i)a=[...a,...n];return a}var P$e=(t,e,n)=>{var a=n.reduce((f,g)=>f+g);if(!a)return xie(e,t);for(var i=Math.floor(t/a),s=t%a,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[...C$e(n,i),...l,...p].map(f=>"".concat(f,"px")).join(", ")};function T$e(t){var{clipPathId:e,points:n,props:a}=t,{dot:i,dataKey:s,needClip:o}=a,{id:l}=a,c=s5(a,b$e),d=_o(c);return y.createElement(nie,{points:n,dot:i,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:d,needClip:o,clipPathId:e})}function A$e(t){var{showLabels:e,children:n,points:a}=t,i=y.useMemo(()=>a?.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 Kd(Kd({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[a]);return y.createElement(Gz,{value:e?i:void 0},n)}function bK(t){var{clipPathId:e,pathRef:n,points:a,strokeDasharray:i,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:d,shape:u}=s,m=s5(s,x$e),p=Kd(Kd({},Os(m)),{},{fill:"none",className:"recharts-line-curve",clipPath:d?"url(#clipPath-".concat(e,")"):void 0,points:a,type:o,layout:l,connectNulls:c,strokeDasharray:i??s.strokeDasharray});return y.createElement(y.Fragment,null,a?.length>1&&y.createElement(Xz,oS({shapeType:"curve",option:u},p,{pathRef:n})),y.createElement(T$e,{points:a,clipPathId:e,props:s}))}function j$e(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function M$e(t){var{clipPathId:e,props:n,pathRef:a,previousPointsRef:i,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,animateNewValues:p,width:f,height:g,onAnimationEnd:w,onAnimationStart:b}=n,x=i.current,S=nv(o,"recharts-line-"),k=y.useRef(S),[C,P]=y.useState(!1),T=!C,A=y.useCallback(()=>{typeof w=="function"&&w(),P(!1)},[w]),F=y.useCallback(()=>{typeof b=="function"&&b(),P(!0)},[b]),_=j$e(a.current),M=y.useRef(0);k.current!==S&&(M.current=s.current,k.current=S);var H=M.current;return y.createElement(A$e,{points:o,showLabels:T},n.children,y.createElement(tv,{animationId:S,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:A,onAnimationStart:F,key:S},I=>{var z=qr(H,_+H,I),L=Math.min(z,_),Z;if(c)if(l){var ne="".concat(l).split(/[,\s]+/gim).map(ue=>parseFloat(ue));Z=P$e(L,_,ne)}else Z=xie(_,L);else Z=l==null?void 0:String(l);if(I>0&&_>0&&(i.current=o,s.current=Math.max(s.current,L)),x){var Y=x.length/o.length,ce=I===1?o:o.map((ue,oe)=>{var Q=Math.floor(oe*Y);if(x[Q]){var le=x[Q];return Kd(Kd({},ue),{},{x:qr(le.x,ue.x,I),y:qr(le.y,ue.y,I)})}return p?Kd(Kd({},ue),{},{x:qr(f*2,ue.x,I),y:qr(g/2,ue.y,I)}):Kd(Kd({},ue),{},{x:ue.x,y:ue.y})});return i.current=ce,y.createElement(bK,{props:n,points:ce,clipPathId:e,pathRef:a,strokeDasharray:Z})}return y.createElement(bK,{props:n,points:o,clipPathId:e,pathRef:a,strokeDasharray:Z})}),y.createElement(PA,{label:n.label}))}function E$e(t){var{clipPathId:e,props:n}=t,a=y.useRef(null),i=y.useRef(0),s=y.useRef(null);return y.createElement(M$e,{props:n,clipPathId:e,previousPointsRef:a,longestAnimatedLengthRef:i,pathRef:s})}var D$e=(t,e)=>{var n,a;return{x:(n=t.x)!==null&&n!==void 0?n:void 0,y:(a=t.y)!==null&&a!==void 0?a:void 0,value:t.value,errorVal:Gr(t.payload,e)}};class F$e extends y.Component{render(){var{hide:e,dot:n,points:a,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 g=Er("recharts-line",i),w=m,{r:b,strokeWidth:x}=bie(n),S=Yz(n),k=b*2+x,C=p?"url(#clipPath-".concat(S?"":"dots-").concat(w,")"):void 0;return y.createElement(so,{zIndex:f},y.createElement($a,{className:g},p&&y.createElement("defs",null,y.createElement(i5,{clipPathId:w,xAxisId:s,yAxisId:o}),!S&&y.createElement("clipPath",{id:"clipPath-dots-".concat(w)},y.createElement("rect",{x:c-k/2,y:l-k/2,width:d+k,height:u+k}))),y.createElement(mie,{xAxisId:s,yAxisId:o,data:a,dataPointFormatter:D$e,errorBarOffset:0},y.createElement(E$e,{props:this.props,clipPathId:w}))),y.createElement(ZR,{activeDot:this.props.activeDot,points:a,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}}var yie={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:ii.line,type:"linear"};function L$e(t){var e=Va(t,yie),{activeDot:n,animateNewValues:a,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:d,isAnimationActive:u,label:m,legendType:p,xAxisId:f,yAxisId:g,id:w}=e,b=s5(e,y$e),{needClip:x}=FA(f,g),S=DA(),k=of(),C=$i(),P=bn(M=>Yqe(M,f,g,C,w));if(k!=="horizontal"&&k!=="vertical"||P==null||S==null)return null;var{height:T,width:A,x:F,y:_}=S;return y.createElement(F$e,oS({},b,{id:w,connectNulls:l,dot:c,activeDot:n,animateNewValues:a,animationBegin:i,animationDuration:s,animationEasing:o,isAnimationActive:u,hide:d,label:m,legendType:p,xAxisId:f,yAxisId:g,points:P,layout:k,height:T,width:A,left:F,top:_,needClip:x}))}function R$e(t){var{layout:e,xAxis:n,yAxis:a,xAxisTicks:i,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((d,u)=>{var m=Gr(d,o);if(e==="horizontal"){var p=OC({axis:n,ticks:i,bandSize:l,entry:d,index:u}),f=Ua(m)?null:a.scale.map(m);return{x:p,y:f??null,value:m,payload:d}}var g=Ua(m)?null:n.scale.map(m),w=OC({axis:a,ticks:s,bandSize:l,entry:d,index:u});return g==null||w==null?null:{x:g,y:w,value:m,payload:d}}).filter(Boolean)}function I$e(t){var e=Va(t,yie),n=$i();return y.createElement(MA,{id:e.id,type:"line"},a=>y.createElement(y.Fragment,null,y.createElement(t5,{legendPayload:k$e(e)}),y.createElement(N$e,{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:a}),y.createElement(n5,{type:"line",id:a,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),y.createElement(L$e,oS({},e,{id:a}))))}var vie=y.memo(I$e,c_);vie.displayName="Line";function Cu(t,e){var n,a;return(n=(a=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||a===void 0?void 0:a.xAxisId)!==null&&n!==void 0?n:rie}function Pu(t,e){var n,a;return(n=(a=t.graphicalItems.cartesianItems.find(i=>i.id===e))===null||a===void 0?void 0:a.yAxisId)!==null&&n!==void 0?n:rie}var wie=(t,e,n)=>yu(t,"xAxis",Cu(t,e),n),Sie=(t,e,n)=>xu(t,"xAxis",Cu(t,e),n),_ie=(t,e,n)=>yu(t,"yAxis",Pu(t,e),n),kie=(t,e,n)=>xu(t,"yAxis",Pu(t,e),n),O$e=Pt([jr,wie,_ie,Sie,kie],(t,e,n,a,i)=>vd(t,"xAxis")?Xh(e,a,!1):Xh(n,i,!1)),z$e=(t,e)=>e,Nie=Pt([r_,z$e],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),Cie=t=>{var e=jr(t),n=vd(e,"xAxis");return n?"yAxis":"xAxis"},U$e=(t,e)=>{var n=Cie(t);return n==="yAxis"?Pu(t,e):Cu(t,e)},B$e=(t,e,n)=>oP(t,Cie(t),U$e(t,e),n),H$e=Pt([Nie,B$e],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:a}=t,i=bA(t);if(!(a==null||i==null)){var s=(n=e[a])===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]])}}}),q$e=Pt([jr,wie,_ie,Sie,kie,H$e,ure,O$e,Nie,eze],(t,e,n,a,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||a==null||i==null||a.length===0||i.length===0||l==null)){var{data:f}=c,g;if(f&&f.length>0?g=f:g=u?.slice(m,p+1),g!=null)return lVe({layout:t,xAxis:e,yAxis:n,xAxisTicks:a,yAxisTicks:i,dataStartIndex:m,areaSettings:c,stackedData:s,displayedData:g,chartBaseValue:d,bandSize:l})}}),$$e=["id"],V$e=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function wg(){return wg=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},wg.apply(null,arguments)}function Pie(t,e){if(t==null)return{};var n,a,i=G$e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function G$e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function xK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function Zx(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?xK(Object(n),!0).forEach(function(a){W$e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):xK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function W$e(t,e,n){return(e=K$e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function K$e(t){var e=Q$e(t,"string");return typeof e=="symbol"?e:e+""}function Q$e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function gP(t,e){return t&&t!=="none"?t:e}var Y$e=t=>{var{dataKey:e,name:n,stroke:a,fill:i,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:gP(a,i),value:sf(n,e),payload:t}]},X$e=y.memo(t=>{var{dataKey:e,data:n,stroke:a,strokeWidth:i,fill:s,name:o,hide:l,unit:c,tooltipType:d,id:u}=t,m={dataDefinedOnItem:n,getPosition:af,settings:{stroke:a,strokeWidth:i,fill:s,dataKey:e,nameKey:void 0,name:sf(o,e),hide:l,type:d,color:gP(a,s),unit:c,graphicalItemId:u}};return y.createElement(jA,{tooltipEntrySettings:m})});function Z$e(t){var{clipPathId:e,points:n,props:a}=t,{needClip:i,dot:s,dataKey:o}=a,l=_o(a);return y.createElement(nie,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:i,clipPathId:e})}function J$e(t){var{showLabels:e,children:n,points:a}=t,i=a.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 Zx(Zx({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return y.createElement(Gz,{value:e?i:void 0},n)}function yK(t){var{points:e,baseLine:n,needClip:a,clipPathId:i,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:d,isRange:u}=s,{id:m}=s,p=Pie(s,$$e),f=_o(p),g=Os(p);return y.createElement(y.Fragment,null,e?.length>1&&y.createElement($a,{clipPath:a?"url(#clipPath-".concat(i,")"):void 0},y.createElement(dy,wg({},g,{id:m,points:e,connectNulls:d,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&y.createElement(dy,wg({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:e})),c!=="none"&&u&&y.createElement(dy,wg({},f,{className:"recharts-area-curve",layout:o,type:l,connectNulls:d,fill:"none",points:n}))),y.createElement(Z$e,{points:e,props:p,clipPathId:i}))}function eVe(t){var e,n,{alpha:a,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(!Kn(l)||!Kn(c))return null;var d=a*Math.abs(l-c),u=Math.max(...s.map(m=>m.x||0));return hn(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.x||0),u)),hn(u)?y.createElement("rect",{x:0,y:l<c?l:l-d,width:u+(o?parseInt("".concat(o),10):1),height:Math.floor(d)}):null}function tVe(t){var e,n,{alpha:a,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(!Kn(l)||!Kn(c))return null;var d=a*Math.abs(l-c),u=Math.max(...s.map(m=>m.y||0));return hn(i)?u=Math.max(i,u):i&&Array.isArray(i)&&i.length&&(u=Math.max(...i.map(m=>m.y||0),u)),hn(u)?y.createElement("rect",{x:l<c?l:l-d,y:0,width:d,height:Math.floor(u+(o?parseInt("".concat(o),10):1))}):null}function nVe(t){var{alpha:e,layout:n,points:a,baseLine:i,strokeWidth:s}=t;return n==="vertical"?y.createElement(eVe,{alpha:e,points:a,baseLine:i,strokeWidth:s}):y.createElement(tVe,{alpha:e,points:a,baseLine:i,strokeWidth:s})}function rVe(t){var{needClip:e,clipPathId:n,props:a,previousPointsRef:i,previousBaselineRef:s}=t,{points:o,baseLine:l,isAnimationActive:c,animationBegin:d,animationDuration:u,animationEasing:m,onAnimationStart:p,onAnimationEnd:f}=a,g=y.useMemo(()=>({points:o,baseLine:l}),[o,l]),w=nv(g,"recharts-area-"),b=E4(),[x,S]=y.useState(!1),k=!x,C=y.useCallback(()=>{typeof f=="function"&&f(),S(!1)},[f]),P=y.useCallback(()=>{typeof p=="function"&&p(),S(!0)},[p]);if(b==null)return null;var T=i.current,A=s.current;return y.createElement(J$e,{showLabels:k,points:o},a.children,y.createElement(tv,{animationId:w,begin:d,duration:u,isActive:c,easing:m,onAnimationEnd:C,onAnimationStart:P,key:w},F=>{if(T){var _=T.length/o.length,M=F===1?o:o.map((I,z)=>{var L=Math.floor(z*_);if(T[L]){var Z=T[L];return Zx(Zx({},I),{},{x:qr(Z.x,I.x,F),y:qr(Z.y,I.y,F)})}return I}),H;return hn(l)?H=qr(A,l,F):Ua(l)||hd(l)?H=qr(A,0,F):H=l.map((I,z)=>{var L=Math.floor(z*_);if(Array.isArray(A)&&A[L]){var Z=A[L];return Zx(Zx({},I),{},{x:qr(Z.x,I.x,F),y:qr(Z.y,I.y,F)})}return I}),F>0&&(i.current=M,s.current=H),y.createElement(yK,{points:M,baseLine:H,needClip:e,clipPathId:n,props:a})}return F>0&&(i.current=o,s.current=l),y.createElement($a,null,c&&y.createElement("defs",null,y.createElement("clipPath",{id:"animationClipPath-".concat(n)},y.createElement(nVe,{alpha:F,points:o,baseLine:l,layout:b,strokeWidth:a.strokeWidth}))),y.createElement($a,{clipPath:"url(#animationClipPath-".concat(n,")")},y.createElement(yK,{points:o,baseLine:l,needClip:e,clipPathId:n,props:a})))}),y.createElement(PA,{label:a.label}))}function aVe(t){var{needClip:e,clipPathId:n,props:a}=t,i=y.useRef(null),s=y.useRef();return y.createElement(rVe,{needClip:e,clipPathId:n,props:a,previousPointsRef:i,previousBaselineRef:s})}class iVe extends y.PureComponent{render(){var{hide:e,dot:n,points:a,className:i,top:s,left:o,needClip:l,xAxisId:c,yAxisId:d,width:u,height:m,id:p,baseLine:f,zIndex:g}=this.props;if(e)return null;var w=Er("recharts-area",i),b=p,{r:x,strokeWidth:S}=bie(n),k=Yz(n),C=x*2+S,P=l?"url(#clipPath-".concat(k?"":"dots-").concat(b,")"):void 0;return y.createElement(so,{zIndex:g},y.createElement($a,{className:w},l&&y.createElement("defs",null,y.createElement(i5,{clipPathId:b,xAxisId:c,yAxisId:d}),!k&&y.createElement("clipPath",{id:"clipPath-dots-".concat(b)},y.createElement("rect",{x:o-C/2,y:s-C/2,width:u+C,height:m+C}))),y.createElement(aVe,{needClip:l,clipPathId:b,props:this.props})),y.createElement(ZR,{points:a,mainColor:gP(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:P}),this.props.isRange&&Array.isArray(f)&&y.createElement(ZR,{points:f,mainColor:gP(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:P}))}}var Tie={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:ii.area};function sVe(t){var e,n=Va(t,Tie),{activeDot:a,animationBegin:i,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:d,fillOpacity:u,hide:m,isAnimationActive:p,legendType:f,stroke:g,xAxisId:w,yAxisId:b}=n,x=Pie(n,V$e),S=of(),k=Cae(),{needClip:C}=FA(w,b),P=$i(),{points:T,isRange:A,baseLine:F}=(e=bn(L=>q$e(L,t.id,P)))!==null&&e!==void 0?e:{},_=DA();if(S!=="horizontal"&&S!=="vertical"||_==null||k!=="AreaChart"&&k!=="ComposedChart")return null;var{height:M,width:H,x:I,y:z}=_;return!T||!T.length?null:y.createElement(iVe,wg({},x,{activeDot:a,animationBegin:i,animationDuration:s,animationEasing:o,baseLine:F,connectNulls:l,dot:c,fill:d,fillOpacity:u,height:M,hide:m,layout:S,isAnimationActive:p==="auto"?!YS.isSsr:p,isRange:A,legendType:f,needClip:C,points:T,stroke:g,width:H,left:I,top:z,xAxisId:w,yAxisId:b}))}var oVe=(t,e,n,a,i)=>{var s=n??e;if(hn(s))return s;var o=t==="horizontal"?i:a,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 lVe(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:a},stackedData:i,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:d,dataStartIndex:u,xAxisTicks:m,yAxisTicks:p,bandSize:f}=t,g=i&&i.length,w=oVe(s,o,n,l,c),b=s==="horizontal",x=!1,S=d.map((C,P)=>{var T,A,F,_;if(g)_=i[u+P];else{var M=Gr(C,a);Array.isArray(M)?(_=M,x=!0):_=[w,M]}var H=(T=(A=_)===null||A===void 0?void 0:A[1])!==null&&T!==void 0?T:null,I=H==null||g&&!e&&Gr(C,a)==null;if(b){var z;return{x:OC({axis:l,ticks:m,bandSize:f,entry:C,index:P}),y:I?null:(z=c.scale.map(H))!==null&&z!==void 0?z:null,value:_,payload:C}}return{x:I?null:(F=l.scale.map(H))!==null&&F!==void 0?F:null,y:OC({axis:c,ticks:p,bandSize:f,entry:C,index:P}),value:_,payload:C}}),k;return g||x?k=S.map(C=>{var P,T=Array.isArray(C.value)?C.value[0]:null;if(b){var A;return{x:C.x,y:T!=null&&C.y!=null&&(A=c.scale.map(T))!==null&&A!==void 0?A:null,payload:C.payload}}return{x:T!=null&&(P=l.scale.map(T))!==null&&P!==void 0?P:null,y:C.y,payload:C.payload}}):k=b?c.scale.map(w):l.scale.map(w),{points:S,baseLine:k??0,isRange:x}}function cVe(t){var e=Va(t,Tie),n=$i();return y.createElement(MA,{id:e.id,type:"area"},a=>y.createElement(y.Fragment,null,y.createElement(t5,{legendPayload:Y$e(e)}),y.createElement(X$e,{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:a}),y.createElement(n5,{type:"area",id:a,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:nne(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),y.createElement(sVe,wg({},e,{id:a}))))}var LA=y.memo(cVe,c_);LA.displayName="Area";var dVe="Invariant failed";function uVe(t,e){throw new Error(dVe)}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 a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},JR.apply(null,arguments)}function bP(t){return y.createElement(Xz,JR({shapeType:"rectangle",activeClassName:"recharts-active-bar"},t))}var mVe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(a,i)=>{if(hn(e))return e;var s=hn(a)||Ua(a);return s?e(a,i):(s||uVe(),n)}},pVe=(t,e,n)=>n,hVe=(t,e)=>e,d_=Pt([r_,hVe],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),fVe=Pt([d_],t=>t?.maxBarSize),gVe=(t,e,n,a)=>a,bVe=Pt([jr,r_,Cu,Pu,pVe],(t,e,n,a,i)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===a).filter(s=>s.isPanorama===i).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),xVe=(t,e,n)=>{var a=jr(t),i=Cu(t,e),s=Pu(t,e);if(!(i==null||s==null))return a==="horizontal"?oP(t,"yAxis",s,n):oP(t,"xAxis",i,n)},yVe=(t,e)=>{var n=jr(t),a=Cu(t,e),i=Pu(t,e);if(!(a==null||i==null))return n==="horizontal"?Z9(t,"xAxis",a):Z9(t,"yAxis",i)},vVe=Pt([bVe,J4e,yVe],w6e),wVe=(t,e,n)=>{var a,i,s=d_(t,e);if(s==null)return 0;var o=Cu(t,e),l=Pu(t,e);if(o==null||l==null)return 0;var c=jr(t),d=_re(t),{maxBarSize:u}=s,m=Ua(u)?d:u,p,f;return c==="horizontal"?(p=yu(t,"xAxis",o,n),f=xu(t,"xAxis",o,n)):(p=yu(t,"yAxis",l,n),f=xu(t,"yAxis",l,n)),(a=(i=Xh(p,f,!0))!==null&&i!==void 0?i:m)!==null&&a!==void 0?a:0},Aie=(t,e,n)=>{var a=jr(t),i=Cu(t,e),s=Pu(t,e);if(!(i==null||s==null)){var o,l;return a==="horizontal"?(o=yu(t,"xAxis",i,n),l=xu(t,"xAxis",i,n)):(o=yu(t,"yAxis",s,n),l=xu(t,"yAxis",s,n)),Xh(o,l)}},SVe=Pt([vVe,_re,Z4e,kre,wVe,Aie,fVe],C6e),_Ve=(t,e,n)=>{var a=Cu(t,e);if(a!=null)return yu(t,"xAxis",a,n)},kVe=(t,e,n)=>{var a=Pu(t,e);if(a!=null)return yu(t,"yAxis",a,n)},NVe=(t,e,n)=>{var a=Cu(t,e);if(a!=null)return xu(t,"xAxis",a,n)},CVe=(t,e,n)=>{var a=Pu(t,e);if(a!=null)return xu(t,"yAxis",a,n)},PVe=Pt([SVe,d_],T6e),TVe=Pt([xVe,d_],P6e),AVe=Pt([qi,P4,_Ve,kVe,NVe,CVe,PVe,jr,ure,Aie,TVe,d_,gVe],(t,e,n,a,i,s,o,l,c,d,u,m,p)=>{var{chartData:f,dataStartIndex:g,dataEndIndex:w}=c;if(!(m==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||a==null||i==null||s==null||d==null)){var{data:b}=m,x;if(b!=null&&b.length>0?x=b:x=f?.slice(g,w+1),x!=null)return rGe({layout:l,barSettings:m,pos:o,parentViewBox:e,bandSize:d,xAxis:n,yAxis:a,xAxisTicks:i,yAxisTicks:s,stackedData:u,displayedData:x,offset:t,cells:p,dataStartIndex:g})}}),jVe=["index"];function eI(){return eI=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},eI.apply(null,arguments)}function MVe(t,e){if(t==null)return{};var n,a,i=EVe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],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 a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var jie=y.createContext(void 0),DVe=t=>{var e=y.useContext(jie);if(e!=null)return e.stackId;if(t!=null)return nne(t)},FVe=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),LVe=t=>{var e=y.useContext(jie);if(e!=null){var{stackId:n}=e;return"url(#".concat(FVe(n,t),")")}},Mie=t=>{var{index:e}=t,n=MVe(t,jVe),a=LVe(e);return y.createElement($a,eI({className:"recharts-bar-stack-layer",clipPath:a},n))},RVe=["onMouseEnter","onMouseLeave","onClick"],IVe=["value","background","tooltipPosition"],OVe=["id"],zVe=["onMouseEnter","onClick","onMouseLeave"];function np(){return np=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},np.apply(null,arguments)}function vK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function xo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?vK(Object(n),!0).forEach(function(a){UVe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):vK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function UVe(t,e,n){return(e=BVe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function BVe(t){var e=HVe(t,"string");return typeof e=="symbol"?e:e+""}function HVe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xP(t,e){if(t==null)return{};var n,a,i=qVe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function qVe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var $Ve=t=>{var{dataKey:e,name:n,fill:a,legendType:i,hide:s}=t;return[{inactive:s,dataKey:e,type:i,color:a,value:sf(n,e),payload:t}]},VVe=y.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:a,fill:i,name:s,hide:o,unit:l,tooltipType:c,id:d}=t,u={dataDefinedOnItem:void 0,getPosition:af,settings:{stroke:n,strokeWidth:a,fill:i,dataKey:e,nameKey:void 0,name:sf(s,e),hide:o,type:c,color:i,unit:l,graphicalItemId:d}};return y.createElement(jA,{tooltipEntrySettings:u})});function GVe(t){var e=bn(Zh),{data:n,dataKey:a,background:i,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,d=xP(s,RVe),u=Zz(o,a,s.id),m=Jz(l),p=e5(c,a,s.id);if(!i||n==null)return null;var f=Ug(i);return y.createElement(so,{zIndex:A6e(i,ii.barBackground)},n.map((g,w)=>{var{value:b,background:x,tooltipPosition:S}=g,k=xP(g,IVe);if(!x)return null;var C=u(g,w),P=m(g,w),T=p(g,w),A=xo(xo(xo(xo(xo({option:i,isActive:String(w)===e},k),{},{fill:"#eee"},x),f),qS(d,g,w)),{},{onMouseEnter:C,onMouseLeave:P,onClick:T,dataKey:a,index:w,className:"recharts-bar-background-rectangle"});return y.createElement(bP,np({key:"background-bar-".concat(w)},A))}))}function WVe(t){var{showLabels:e,children:n,rects:a}=t,i=a?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return xo(xo({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return y.createElement(Gz,{value:e?i:void 0},n)}function KVe(t){var{shape:e,activeBar:n,baseProps:a,entry:i,index:s,dataKey:o}=t,l=bn(Zh),c=bn(Uz),d=n&&String(s)===l&&(c==null||o===c),u=d?n:e;return d?y.createElement(so,{zIndex:ii.activeBar},y.createElement(Mie,{index:s},y.createElement(bP,np({},a,{name:String(a.name)},i,{isActive:d,option:u,index:s,dataKey:o})))):y.createElement(bP,np({},a,{name:String(a.name)},i,{isActive:d,option:u,index:s,dataKey:o}))}function QVe(t){var{shape:e,baseProps:n,entry:a,index:i,dataKey:s}=t;return y.createElement(bP,np({},n,{name:String(n.name)},a,{isActive:!1,option:e,index:i,dataKey:s}))}function YVe(t){var e,{data:n,props:a}=t,i=(e=_o(a))!==null&&e!==void 0?e:{},{id:s}=i,o=xP(i,OVe),{shape:l,dataKey:c,activeBar:d}=a,{onMouseEnter:u,onClick:m,onMouseLeave:p}=a,f=xP(a,zVe),g=Zz(u,c,s),w=Jz(p),b=e5(m,c,s);return n?y.createElement(y.Fragment,null,n.map((x,S)=>y.createElement(Mie,np({index:S,key:"rectangle-".concat(x?.x,"-").concat(x?.y,"-").concat(x?.value,"-").concat(S),className:"recharts-bar-rectangle"},qS(f,x,S),{onMouseEnter:g(x,S),onMouseLeave:w(x,S),onClick:b(x,S)}),d?y.createElement(KVe,{shape:l,activeBar:d,baseProps:o,entry:x,index:S,dataKey:c}):y.createElement(QVe,{shape:l,baseProps:o,entry:x,index:S,dataKey:c})))):null}function XVe(t){var{props:e,previousRectanglesRef:n}=t,{data:a,layout:i,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:d,onAnimationStart:u}=e,m=n.current,p=nv(e,"recharts-bar-"),[f,g]=y.useState(!1),w=!f,b=y.useCallback(()=>{typeof d=="function"&&d(),g(!1)},[d]),x=y.useCallback(()=>{typeof u=="function"&&u(),g(!0)},[u]);return y.createElement(WVe,{showLabels:w,rects:a},y.createElement(tv,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:b,onAnimationStart:x,key:p},S=>{var k=S===1?a:a?.map((C,P)=>{var T=m&&m[P];if(T)return xo(xo({},C),{},{x:qr(T.x,C.x,S),y:qr(T.y,C.y,S),width:qr(T.width,C.width,S),height:qr(T.height,C.height,S)});if(i==="horizontal"){var A=qr(0,C.height,S),F=qr(C.stackedBarStart,C.y,S);return xo(xo({},C),{},{y:F,height:A})}var _=qr(0,C.width,S),M=qr(C.stackedBarStart,C.x,S);return xo(xo({},C),{},{width:_,x:M})});return S>0&&(n.current=k??null),k==null?null:y.createElement($a,null,y.createElement(YVe,{props:e,data:k}))}),y.createElement(PA,{label:e.label}),e.children)}function ZVe(t){var e=y.useRef(null);return y.createElement(XVe,{previousRectanglesRef:e,props:t})}var Eie=0,JVe=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:Gr(t,e)}};class eGe extends y.PureComponent{render(){var{hide:e,data:n,dataKey:a,className:i,xAxisId:s,yAxisId:o,needClip:l,background:c,id:d}=this.props;if(e||n==null)return null;var u=Er("recharts-bar",i),m=d;return y.createElement($a,{className:u,id:d},l&&y.createElement("defs",null,y.createElement(i5,{clipPathId:m,xAxisId:s,yAxisId:o})),y.createElement($a,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(m,")"):void 0},y.createElement(GVe,{data:n,dataKey:a,background:c,allOtherBarProps:this.props}),y.createElement(ZVe,this.props)))}}var tGe={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:Eie,xAxisId:0,yAxisId:0,zIndex:ii.bar};function nGe(t){var{xAxisId:e,yAxisId:n,hide:a,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u}=t,{needClip:m}=FA(e,n),p=of(),f=$i(),g=Qz(t.children,Ly),w=bn(S=>AVe(S,t.id,f,g));if(p!=="vertical"&&p!=="horizontal")return null;var b,x=w?.[0];return x==null||x.height==null||x.width==null?b=0:b=p==="vertical"?x.height/2:x.width/2,y.createElement(mie,{xAxisId:e,yAxisId:n,data:w,dataPointFormatter:JVe,errorBarOffset:b},y.createElement(eGe,np({},t,{layout:p,needClip:m,data:w,xAxisId:e,yAxisId:n,hide:a,legendType:i,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:d,isAnimationActive:u})))}function rGe(t){var{layout:e,barSettings:{dataKey:n,minPointSize:a},pos:i,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:d,stackedData:u,displayedData:m,offset:p,cells:f,parentViewBox:g,dataStartIndex:w}=t,b=e==="horizontal"?l:o,x=u?b.scale.domain():null,S=UFe({numericAxis:b}),k=b.scale.map(S);return m.map((C,P)=>{var T,A,F,_,M,H;if(u){var I=u[P+w];if(I==null)return null;T=LFe(I,x)}else T=Gr(C,n),Array.isArray(T)||(T=[S,T]);var z=mVe(a,Eie)(T[1],P);if(e==="horizontal"){var L,Z=l.scale.map(T[0]),ne=l.scale.map(T[1]);if(Z==null||ne==null)return null;A=XG({axis:o,ticks:c,bandSize:s,offset:i.offset,entry:C,index:P}),F=(L=ne??Z)!==null&&L!==void 0?L:void 0,_=i.size;var Y=Z-ne;if(M=hd(Y)?0:Y,H={x:A,y:p.top,width:_,height:p.height},Math.abs(z)>0&&Math.abs(M)<Math.abs(z)){var ce=us(M||z)*(Math.abs(z)-Math.abs(M));F-=ce,M+=ce}}else{var ue=o.scale.map(T[0]),oe=o.scale.map(T[1]);if(ue==null||oe==null)return null;if(A=ue,F=XG({axis:l,ticks:d,bandSize:s,offset:i.offset,entry:C,index:P}),_=oe-ue,M=i.size,H={x:p.left,y:F,width:p.width,height:M},Math.abs(z)>0&&Math.abs(_)<Math.abs(z)){var Q=us(_||z)*(Math.abs(z)-Math.abs(_));_+=Q}}if(A==null||F==null||_==null||M==null)return null;var le=xo(xo({},C),{},{stackedBarStart:k,x:A,y:F,width:_,height:M,value:u?T:T[1],payload:C,background:H,tooltipPosition:{x:A+_/2,y:F+M/2},parentViewBox:g},f&&f[P]&&f[P].props);return le}).filter(Boolean)}function aGe(t){var e=Va(t,tGe),n=DVe(e.stackId),a=$i();return y.createElement(MA,{id:e.id,type:"bar"},i=>y.createElement(y.Fragment,null,y.createElement(t5,{legendPayload:$Ve(e)}),y.createElement(VVe,{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}),y.createElement(n5,{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:a}),y.createElement(so,{zIndex:e.zIndex},y.createElement(nGe,np({},e,{id:i})))))}var Bx=y.memo(aGe,c_);Bx.displayName="Bar";var iGe=["domain","range"],sGe=["domain","range"];function wK(t,e){if(t==null)return{};var n,a,i=oGe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function oGe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function SK(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 Die(t,e){if(t===e)return!0;var{domain:n,range:a}=t,i=wK(t,iGe),{domain:s,range:o}=e,l=wK(e,sGe);return!SK(n,s)||!SK(a,o)?!1:c_(i,l)}var lGe=["type"],cGe=["dangerouslySetInnerHTML","ticks","scale"],dGe=["id","scale"];function tI(){return tI=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},tI.apply(null,arguments)}function _K(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function kK(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_K(Object(n),!0).forEach(function(a){uGe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_K(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function uGe(t,e,n){return(e=mGe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mGe(t){var e=pGe(t,"string");return typeof e=="symbol"?e:e+""}function pGe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function nI(t,e){if(t==null)return{};var n,a,i=hGe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function hGe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function fGe(t){var e=ga(),n=y.useRef(null),a=E4(),{type:i}=t,s=nI(t,lGe),o=fA(a,"xAxis",i),l=y.useMemo(()=>{if(o!=null)return kK(kK({},s),{},{type:o})},[s,o]);return y.useLayoutEffect(()=>{l!=null&&(n.current===null?e(s6e(l)):n.current!==l&&e(o6e({prev:n.current,next:l})),n.current=l)},[l,e]),y.useLayoutEffect(()=>()=>{n.current&&(e(l6e(n.current)),n.current=null)},[e]),null}var gGe=t=>{var{xAxisId:e,className:n}=t,a=bn(P4),i=$i(),s="xAxis",o=bn(x=>rae(x,s,e,i)),l=bn(x=>Jre(x,e)),c=bn(x=>e5e(x,e)),d=bn(x=>Fre(x,e));if(l==null||c==null||d==null)return null;var{dangerouslySetInnerHTML:u,ticks:m,scale:p}=t,f=nI(t,cGe),{id:g,scale:w}=d,b=nI(d,dGe);return y.createElement(a5,tI({},f,b,{x:c.x,y:c.y,width:l.width,height:l.height,className:Er("recharts-".concat(s," ").concat(s),n),viewBox:a,ticks:o,axisType:s}))},bGe={allowDataOverflow:ts.allowDataOverflow,allowDecimals:ts.allowDecimals,allowDuplicatedCategory:ts.allowDuplicatedCategory,angle:ts.angle,axisLine:Om.axisLine,height:ts.height,hide:!1,includeHidden:ts.includeHidden,interval:ts.interval,label:!1,minTickGap:ts.minTickGap,mirror:ts.mirror,orientation:ts.orientation,padding:ts.padding,reversed:ts.reversed,scale:ts.scale,tick:ts.tick,tickCount:ts.tickCount,tickLine:Om.tickLine,tickSize:Om.tickSize,type:ts.type,xAxisId:0},xGe=t=>{var e=Va(t,bGe);return y.createElement(y.Fragment,null,y.createElement(fGe,{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}),y.createElement(gGe,e))},Tm=y.memo(xGe,Die);Tm.displayName="XAxis";var yGe=["type"],vGe=["dangerouslySetInnerHTML","ticks","scale"],wGe=["id","scale"];function rI(){return rI=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},rI.apply(null,arguments)}function NK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function CK(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?NK(Object(n),!0).forEach(function(a){SGe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):NK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function SGe(t,e,n){return(e=_Ge(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _Ge(t){var e=kGe(t,"string");return typeof e=="symbol"?e:e+""}function kGe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function aI(t,e){if(t==null)return{};var n,a,i=NGe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function NGe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function CGe(t){var e=ga(),n=y.useRef(null),a=E4(),{type:i}=t,s=aI(t,yGe),o=fA(a,"yAxis",i),l=y.useMemo(()=>{if(o!=null)return CK(CK({},s),{},{type:o})},[o,s]);return y.useLayoutEffect(()=>{l!=null&&(n.current===null?e(c6e(l)):n.current!==l&&e(d6e({prev:n.current,next:l})),n.current=l)},[l,e]),y.useLayoutEffect(()=>()=>{n.current&&(e(u6e(n.current)),n.current=null)},[e]),null}function PGe(t){var{yAxisId:e,className:n,width:a,label:i}=t,s=y.useRef(null),o=y.useRef(null),l=bn(P4),c=$i(),d=ga(),u="yAxis",m=bn(T=>eae(T,e)),p=bn(T=>n5e(T,e)),f=bn(T=>rae(T,u,e,c)),g=bn(T=>Lre(T,e));if(y.useLayoutEffect(()=>{if(!(a!=="auto"||!m||Vz(i)||y.isValidElement(i)||g==null)){var T=s.current;if(T){var A=T.getCalculatedWidth();Math.round(m.width)!==Math.round(A)&&d(m6e({id:e,width:A}))}}},[f,m,d,i,e,a,g]),m==null||p==null||g==null)return null;var{dangerouslySetInnerHTML:w,ticks:b,scale:x}=t,S=aI(t,vGe),{id:k,scale:C}=g,P=aI(g,wGe);return y.createElement(a5,rI({},S,P,{ref:s,labelRef:o,x:p.x,y:p.y,tickTextProps:a==="auto"?{width:void 0}:{width:a},width:m.width,height:m.height,className:Er("recharts-".concat(u," ").concat(u),n),viewBox:l,ticks:f,axisType:u}))}var TGe={allowDataOverflow:ns.allowDataOverflow,allowDecimals:ns.allowDecimals,allowDuplicatedCategory:ns.allowDuplicatedCategory,angle:ns.angle,axisLine:Om.axisLine,hide:!1,includeHidden:ns.includeHidden,interval:ns.interval,label:!1,minTickGap:ns.minTickGap,mirror:ns.mirror,orientation:ns.orientation,padding:ns.padding,reversed:ns.reversed,scale:ns.scale,tick:ns.tick,tickCount:ns.tickCount,tickLine:Om.tickLine,tickSize:Om.tickSize,type:ns.type,width:ns.width,yAxisId:0},AGe=t=>{var e=Va(t,TGe);return y.createElement(y.Fragment,null,y.createElement(CGe,{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}),y.createElement(PGe,e))},Am=y.memo(AGe,Die);Am.displayName="YAxis";var jGe=(t,e)=>e,o5=Pt([jGe,jr,Mre,xs,vae,op,bUe,qi],kUe),l5=t=>{var e=t.currentTarget.getBoundingClientRect(),n=e.width/t.currentTarget.offsetWidth,a=e.height/t.currentTarget.offsetHeight;return{chartX:Math.round((t.clientX-e.left)/n),chartY:Math.round((t.clientY-e.top)/a)}},Fie=Nc("mouseClick"),Lie=VS();Lie.startListening({actionCreator:Fie,effect:(t,e)=>{var n=t.payload,a=o5(e.getState(),l5(n));a?.activeIndex!=null&&e.dispatch(g5e({activeIndex:a.activeIndex,activeDataKey:void 0,activeCoordinate:a.activeCoordinate}))}});var iI=Nc("mouseMove"),Rie=VS(),$1=null;Rie.startListening({actionCreator:iI,effect:(t,e)=>{var n=t.payload;$1!==null&&cancelAnimationFrame($1);var a=l5(n);$1=requestAnimationFrame(()=>{var i=e.getState(),s=Fz(i,i.tooltip.settings.shared);if(s==="axis"){var o=o5(i,a);o?.activeIndex!=null?e.dispatch(uae({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(dae())}$1=null})}});function MGe(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 PK={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},Iie=Jo({name:"rootProps",initialState:PK,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:PK.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}}}),EGe=Iie.reducer,{updateOptions:DGe}=Iie.actions,FGe=null,LGe={updatePolarOptions:(t,e)=>e.payload},Oie=Jo({name:"polarOptions",initialState:FGe,reducers:LGe}),{updatePolarOptions:RGe}=Oie.actions,IGe=Oie.reducer,zie=Nc("keyDown"),Uie=Nc("focus"),c5=VS();c5.startListening({actionCreator:zie,effect:(t,e)=>{var n=e.getState(),a=n.rootProps.accessibilityLayer!==!1;if(a){var{keyboardInteraction:i}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=Lz(i,uv(n),i_(n),o_(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=op(n);if(s==="Enter"){var d=cP(n,"axis","hover",String(i.index));e.dispatch(GR({active:!i.active,activeIndex:i.index,activeCoordinate:d}));return}var u=s5e(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 g=cP(n,"axis","hover",String(f));e.dispatch(GR({active:!0,activeIndex:f.toString(),activeCoordinate:g}))}}}}}});c5.startListening({actionCreator:Uie,effect:(t,e)=>{var n=e.getState(),a=n.rootProps.accessibilityLayer!==!1;if(a){var{keyboardInteraction:i}=n.tooltip;if(!i.active&&i.index==null){var s="0",o=cP(n,"axis","hover",String(s));e.dispatch(GR({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Xl=Nc("externalEvent"),Bie=VS(),c3=new Map;Bie.startListening({actionCreator:Xl,effect:(t,e)=>{var{handler:n,reactEvent:a}=t.payload;if(n!=null){a.persist();var i=a.type,s=c3.get(i);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:nUe(l),activeDataKey:Uz(l),activeIndex:Zh(l),activeLabel:_ae(l),activeTooltipIndex:Zh(l),isTooltipActive:rUe(l)};n(c,a)}finally{c3.delete(i)}});c3.set(i,o)}}});var OGe=Pt([cv],t=>t.tooltipItemPayloads),zGe=Pt([OGe,(t,e)=>e,(t,e,n)=>n],(t,e,n)=>{if(e!=null){var a=t.find(s=>s.settings.graphicalItemId===n);if(a!=null){var{getPosition:i}=a;if(i!=null)return i(e)}}}),Hie=Nc("touchMove"),qie=VS();qie.startListening({actionCreator:Hie,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var a=e.getState(),i=Fz(a,a.tooltip.settings.shared);if(i==="axis"){var s=n.touches[0];if(s==null)return;var o=o5(a,l5({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(uae({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(ane),m=(l=d.getAttribute(ine))!==null&&l!==void 0?l:void 0,p=dv(a).find(w=>w.id===m);if(u==null||p==null||m==null)return;var{dataKey:f}=p,g=zGe(a,u,m);e.dispatch(cae({activeDataKey:f,activeIndex:u,activeCoordinate:g,activeGraphicalItemId:m}))}}}});var UGe=Nte({brush:j6e,cartesianAxis:p6e,chartData:tBe,errorBars:Uqe,graphicalItems:w8e,layout:jFe,legend:RLe,options:YUe,polarAxis:LHe,polarOptions:IGe,referenceElements:O6e,rootProps:EGe,tooltip:b5e,zIndex:OUe}),BGe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return tFe({reducer:UGe,preloadedState:e,middleware:a=>{var i;return a({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((i="es6")!==null&&i!==void 0?i:"")}).concat([Lie.middleware,Rie.middleware,c5.middleware,Bie.middleware,qie.middleware])},enhancers:a=>{var i=a;return typeof a=="function"&&(i=a()),i.concat(Ute({type:"raf"}))},devTools:{serialize:{replacer:MGe},name:"recharts-".concat(n)}})};function $ie(t){var{preloadedState:e,children:n,reduxStoreName:a}=t,i=$i(),s=y.useRef(null);if(i)return n;s.current==null&&(s.current=BGe(e,a));var o=v4;return y.createElement(h$e,{context:o,store:s.current},n)}function HGe(t){var{layout:e,margin:n}=t,a=ga(),i=$i();return y.useEffect(()=>{i||(a(PFe(e)),a(CFe(n)))},[a,i,e,n]),null}var Vie=y.memo(HGe,c_);function Gie(t){var e=ga();return y.useEffect(()=>{e(DGe(t))},[e,t]),null}function TK(t){var{zIndex:e,isPanorama:n}=t,a=y.useRef(null),i=ga();return y.useLayoutEffect(()=>(a.current&&i(RUe({zIndex:e,element:a.current,isPanorama:n})),()=>{i(IUe({zIndex:e,isPanorama:n}))}),[i,e,n]),y.createElement("g",{tabIndex:-1,ref:a})}function AK(t){var{children:e,isPanorama:n}=t,a=bn(CUe);if(!a||a.length===0)return e;var i=a.filter(o=>o<0),s=a.filter(o=>o>0);return y.createElement(y.Fragment,null,i.map(o=>y.createElement(TK,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>y.createElement(TK,{key:o,zIndex:o,isPanorama:n})))}var qGe=["children"];function $Ge(t,e){if(t==null)return{};var n,a,i=VGe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function VGe(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function yP(){return yP=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},yP.apply(null,arguments)}var GGe={width:"100%",height:"100%",display:"block"},WGe=y.forwardRef((t,e)=>{var n=j4(),a=M4(),i=wne();if(!gu(n)||!gu(a))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),y.createElement(c4,yP({},o,{title:l,desc:c,role:u,tabIndex:d,width:n,height:a,style:GGe,ref:e}),s)}),KGe=t=>{var{children:e}=t,n=bn(rA);if(!n)return null;var{width:a,height:i,y:s,x:o}=n;return y.createElement(c4,{width:a,height:i,x:o,y:s},e)},jK=y.forwardRef((t,e)=>{var{children:n}=t,a=$Ge(t,qGe),i=$i();return i?y.createElement(KGe,null,y.createElement(AK,{isPanorama:!0},n)):y.createElement(WGe,yP({ref:e},a),y.createElement(AK,{isPanorama:!1},n))});function QGe(){var t=ga(),[e,n]=y.useState(null),a=bn(GFe);return y.useEffect(()=>{if(e!=null){var i=e.getBoundingClientRect(),s=i.width/e.offsetWidth;Kn(s)&&s!==a&&t(AFe(s))}},[e,t,a]),n}function MK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function YGe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?MK(Object(n),!0).forEach(function(a){XGe(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):MK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function XGe(t,e,n){return(e=ZGe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ZGe(t){var e=JGe(t,"string");return typeof e=="symbol"?e:e+""}function JGe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zh(){return zh=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},zh.apply(null,arguments)}var e7e=()=>(dBe(),null);function vP(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var t7e=y.forwardRef((t,e)=>{var n,a,i=y.useRef(null),[s,o]=y.useState({containerWidth:vP((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:vP((a=t.style)===null||a===void 0?void 0:a.height)}),l=y.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=y.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=g=>{var w=g[0];if(w!=null){var{width:b,height:x}=w.contentRect;l(b,x)}},f=new ResizeObserver(p);f.observe(d),i.current=f}},[e,l]);return y.useEffect(()=>()=>{var d=i.current;d?.disconnect()},[l]),y.createElement(y.Fragment,null,y.createElement(KS,{width:s.containerWidth,height:s.containerHeight}),y.createElement("div",zh({ref:c},t)))}),n7e=y.forwardRef((t,e)=>{var{width:n,height:a}=t,[i,s]=y.useState({containerWidth:vP(n),containerHeight:vP(a)}),o=y.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=y.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:d,height:u}=c.getBoundingClientRect();o(d,u)}},[e,o]);return y.createElement(y.Fragment,null,y.createElement(KS,{width:i.containerWidth,height:i.containerHeight}),y.createElement("div",zh({ref:l},t)))}),r7e=y.forwardRef((t,e)=>{var{width:n,height:a}=t;return y.createElement(y.Fragment,null,y.createElement(KS,{width:n,height:a}),y.createElement("div",zh({ref:e},t)))}),a7e=y.forwardRef((t,e)=>{var{width:n,height:a}=t;return typeof n=="string"||typeof a=="string"?y.createElement(n7e,zh({},t,{ref:e})):typeof n=="number"&&typeof a=="number"?y.createElement(r7e,zh({},t,{width:n,height:a,ref:e})):y.createElement(y.Fragment,null,y.createElement(KS,{width:n,height:a}),y.createElement("div",zh({ref:e},t)))});function i7e(t){return t?t7e:a7e}var s7e=y.forwardRef((t,e)=>{var{children:n,className:a,height:i,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:d,onMouseLeave:u,onMouseMove:m,onMouseUp:p,onTouchEnd:f,onTouchMove:g,onTouchStart:w,style:b,width:x,responsive:S,dispatchTouchEvents:k=!0}=t,C=y.useRef(null),P=ga(),[T,A]=y.useState(null),[F,_]=y.useState(null),M=QGe(),H=T4(),I=H?.width>0?H.width:x,z=H?.height>0?H.height:i,L=y.useCallback(E=>{M(E),typeof e=="function"&&e(E),A(E),_(E),E!=null&&(C.current=E)},[M,e,A,_]),Z=y.useCallback(E=>{P(Fie(E)),P(Xl({handler:s,reactEvent:E}))},[P,s]),ne=y.useCallback(E=>{P(iI(E)),P(Xl({handler:d,reactEvent:E}))},[P,d]),Y=y.useCallback(E=>{P(dae()),P(Xl({handler:u,reactEvent:E}))},[P,u]),ce=y.useCallback(E=>{P(iI(E)),P(Xl({handler:m,reactEvent:E}))},[P,m]),ue=y.useCallback(()=>{P(Uie())},[P]),oe=y.useCallback(E=>{P(zie(E.key))},[P]),Q=y.useCallback(E=>{P(Xl({handler:o,reactEvent:E}))},[P,o]),le=y.useCallback(E=>{P(Xl({handler:l,reactEvent:E}))},[P,l]),pe=y.useCallback(E=>{P(Xl({handler:c,reactEvent:E}))},[P,c]),he=y.useCallback(E=>{P(Xl({handler:p,reactEvent:E}))},[P,p]),we=y.useCallback(E=>{P(Xl({handler:w,reactEvent:E}))},[P,w]),$=y.useCallback(E=>{k&&P(Hie(E)),P(Xl({handler:g,reactEvent:E}))},[P,k,g]),J=y.useCallback(E=>{P(Xl({handler:f,reactEvent:E}))},[P,f]),j=i7e(S);return y.createElement(Mae.Provider,{value:T},y.createElement(Bee.Provider,{value:F},y.createElement(j,{width:I??b?.width,height:z??b?.height,className:Er("recharts-wrapper",a),style:YGe({position:"relative",cursor:"default",width:I,height:z},b),onClick:Z,onContextMenu:Q,onDoubleClick:le,onFocus:ue,onKeyDown:oe,onMouseDown:pe,onMouseEnter:ne,onMouseLeave:Y,onMouseMove:ce,onMouseUp:he,onTouchEnd:J,onTouchMove:$,onTouchStart:we,ref:L},y.createElement(e7e,null),n)))}),o7e=["width","height","responsive","children","className","style","compact","title","desc"];function l7e(t,e){if(t==null)return{};var n,a,i=c7e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function c7e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var Wie=y.forwardRef((t,e)=>{var{width:n,height:a,responsive:i,children:s,className:o,style:l,compact:c,title:d,desc:u}=t,m=l7e(t,o7e),p=_o(m);return c?y.createElement(y.Fragment,null,y.createElement(KS,{width:n,height:a}),y.createElement(jK,{otherAttributes:p,title:d,desc:u},s)):y.createElement(s7e,{className:o,style:l,width:n,height:a,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},y.createElement(jK,{otherAttributes:p,title:d,desc:u,ref:e},y.createElement(z6e,null,s)))});function sI(){return sI=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},sI.apply(null,arguments)}var d7e={top:5,right:5,bottom:5,left:5},u7e={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:d7e,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},d5=y.forwardRef(function(e,n){var a,i=Va(e.categoricalChartProps,u7e),{chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,categoricalChartProps:d}=e,u={chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return y.createElement($ie,{preloadedState:{options:u},reduxStoreName:(a=d.id)!==null&&a!==void 0?a:s},y.createElement(iie,{chartData:d.data}),y.createElement(Vie,{layout:i.layout,margin:i.margin}),y.createElement(Gie,{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}),y.createElement(Wie,sI({},i,{ref:n})))}),m7e=["axis"],p7e=y.forwardRef((t,e)=>y.createElement(d5,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:m7e,tooltipPayloadSearcher:NA,categoricalChartProps:t,ref:e})),h7e=["axis","item"],V1=y.forwardRef((t,e)=>y.createElement(d5,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:h7e,tooltipPayloadSearcher:NA,categoricalChartProps:t,ref:e}));function f7e(t){var e=ga();return y.useEffect(()=>{e(RGe(t))},[e,t]),null}var g7e=["layout"];function oI(){return oI=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},oI.apply(null,arguments)}function b7e(t,e){if(t==null)return{};var n,a,i=x7e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(a=0;a<s.length;a++)n=s[a],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}function x7e(t,e){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(e.indexOf(a)!==-1)continue;n[a]=t[a]}return n}var y7e={top:5,right:5,bottom:5,left:5},Kie={accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:y7e,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},v7e=y.forwardRef(function(e,n){var a,i=Va(e.categoricalChartProps,Kie),{layout:s}=i,o=b7e(i,g7e),{chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u}=e,m={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:d,tooltipPayloadSearcher:u,eventEmitter:void 0};return y.createElement($ie,{preloadedState:{options:m},reduxStoreName:(a=i.id)!==null&&a!==void 0?a:l},y.createElement(iie,{chartData:i.data}),y.createElement(Vie,{layout:s,margin:i.margin}),y.createElement(Gie,{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}),y.createElement(f7e,{cx:i.cx,cy:i.cy,startAngle:i.startAngle,endAngle:i.endAngle,innerRadius:i.innerRadius,outerRadius:i.outerRadius}),y.createElement(Wie,oI({},o,{ref:n})))});function EK(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,a)}return n}function DK(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?EK(Object(n),!0).forEach(function(a){w7e(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):EK(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function w7e(t,e,n){return(e=S7e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function S7e(t){var e=_7e(t,"string");return typeof e=="symbol"?e:e+""}function _7e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,e);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var k7e=["item"],N7e=DK(DK({},Kie),{},{layout:"centric",startAngle:0,endAngle:360}),FK=y.forwardRef((t,e)=>{var n=Va(t,N7e);return y.createElement(v7e,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:k7e,tooltipPayloadSearcher:NA,categoricalChartProps:n,ref:e})}),C7e=["axis"],u5=y.forwardRef((t,e)=>y.createElement(d5,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:C7e,tooltipPayloadSearcher:NA,categoricalChartProps:t,ref:e}));const LK=[{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 P7e({isOpen:t,onClose:e,printerId:n,printerName:a,amsId:i,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=_t(),{mode:d}=ob(),[u,m]=y.useState("24h"),[p,f]=y.useState(o),g=d==="dark",{data:w}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),b=w?.time_format||"system";y.useEffect(()=>{if(!t)return;const J=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[t,e]);const x=LK.find(J=>J.value===u)?.hours||24,{data:S,isLoading:k,error:C}=Xe({queryKey:["ams-history",n,i,x],queryFn:()=>ae.getAMSHistory(n,i,x),enabled:t,refetchInterval:6e4});if(!t)return null;const P=S?.data.map(J=>({time:(Yn(J.recorded_at)||new Date).getTime(),humidity:J.humidity,temperature:J.temperature}))||[],T=Date.now()-x*60*60*1e3,A=Date.now(),F=[...P];if(F.length>0){const J=F[0];J.time>T&&F.unshift({...J,time:T});const j=F[F.length-1];j.time<A&&F.push({...j,time:A})}const _=l?.humidityGood||40,M=l?.humidityFair||60,H=l?.tempGood||30,I=l?.tempFair||35,z=F[F.length-1],L=z?.humidity,Z=z?.temperature,ne=J=>{const j=J.filter(U=>U!=null);if(j.length<4)return"stable";const E=j.slice(0,Math.floor(j.length/4)),B=j.slice(-Math.floor(j.length/4)),W=E.reduce((U,G)=>U+G,0)/E.length,ie=B.reduce((U,G)=>U+G,0)/B.length-W;return Math.abs(ie)<2?"stable":ie>0?"up":"down"},Y=ne(F.map(J=>J.humidity)),ce=ne(F.map(J=>J.temperature)),ue=({trend:J})=>J==="up"?r.jsx(sC,{className:"w-4 h-4 text-red-400"}):J==="down"?r.jsx(IS,{className:"w-4 h-4 text-green-400"}):r.jsx(rC,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),oe=J=>J==null?"#9ca3af":J<=_?"#22a352":J<=M?"#d4a017":"#c62828",Q=J=>J==null?"#9ca3af":J<=H?"#22a352":J<=I?"#d4a017":"#c62828",le=g?"#2d2d2d":"#ffffff",pe=g?"#1d1d1d":"#f3f4f6",he=g?"#3d3d3d":"#e5e7eb",we=g?"#ffffff":"#111827",$=g?"#9ca3af":"#4b5563";return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:r.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:le},onClick:J=>J.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:he},children:[r.jsxs("div",{children:[r.jsxs("h2",{className:"text-lg font-semibold",style:{color:we},children:[s," ",c("common.history","History")]}),r.jsx("p",{className:"text-sm",style:{color:$},children:a})]}),r.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:$},children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[r.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[r.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:pe},children:[r.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:[r.jsx(wO,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),r.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:[r.jsx(RS,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),r.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:pe},children:LK.map(J=>r.jsx("button",{onClick:()=>m(J.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${u===J.value?"bg-bambu-green text-white":""}`,style:u!==J.value?{color:$}:void 0,children:J.label},J.value))})]}),r.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:p==="humidity"?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.current","Current")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("p",{className:"text-2xl font-bold",style:{color:oe(L)},children:L!=null?`${L}%`:"—"}),r.jsx(ue,{trend:Y})]})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.average","Average")}),r.jsx("p",{className:"text-2xl font-bold",style:{color:we},children:S?.avg_humidity!=null?`${S.avg_humidity}%`:"—"})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.min","Min")}),r.jsx("p",{className:"text-2xl font-bold text-green-500",children:S?.min_humidity!=null?`${S.min_humidity}%`:"—"})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.max","Max")}),r.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_humidity!=null?`${S.max_humidity}%`:"—"})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.current","Current")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("p",{className:"text-2xl font-bold",style:{color:Q(Z)},children:Z!=null?`${Z}°C`:"—"}),r.jsx(ue,{trend:ce})]})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.average","Average")}),r.jsx("p",{className:"text-2xl font-bold",style:{color:we},children:S?.avg_temperature!=null?`${S.avg_temperature}°C`:"—"})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.min","Min")}),r.jsx("p",{className:"text-2xl font-bold text-blue-500",children:S?.min_temperature!=null?`${S.min_temperature}°C`:"—"})]}),r.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:pe},children:[r.jsx("p",{className:"text-xs",style:{color:$},children:c("common.max","Max")}),r.jsx("p",{className:"text-2xl font-bold text-red-500",children:S?.max_temperature!=null?`${S.max_temperature}°C`:"—"})]})]})}),r.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:pe},children:k?r.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:$},children:c("common.loading","Loading...")}):C?r.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):F.length===0?r.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:$},children:c("common.noData","No data available for this time range")}):r.jsx(nu,{width:"100%",height:300,children:r.jsxs(p7e,{data:F,children:[r.jsx(Pm,{strokeDasharray:"3 3",stroke:g?"#3d3d3d":"#e5e7eb"}),r.jsx(Tm,{dataKey:"time",type:"number",domain:[Date.now()-x*60*60*1e3,Date.now()],tickFormatter:J=>{const j=new Date(J);return x>24?j.toLocaleDateString([],{day:"numeric",month:"short"}):j.toLocaleTimeString([],Lw({hour:"2-digit",minute:"2-digit"},b))},stroke:g?"#9ca3af":"#6b7280",tick:{fontSize:12}}),r.jsx(Am,{stroke:g?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:p==="humidity"?[0,100]:["auto","auto"],tickFormatter:J=>p==="humidity"?`${J}%`:`${J}°C`}),r.jsx(au,{contentStyle:{backgroundColor:g?"#2d2d2d":"#ffffff",border:`1px solid ${g?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:g?"#fff":"#000"},labelFormatter:J=>new Date(J).toLocaleString(void 0,Lw({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},b)),formatter:J=>[p==="humidity"?`${J??0}%`:`${J??0}°C`,p==="humidity"?"Humidity":"Temperature"]}),r.jsx(L4,{}),p==="humidity"?r.jsxs(r.Fragment,{children:[r.jsx(iu,{y:_,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),r.jsx(iu,{y:M,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):r.jsxs(r.Fragment,{children:[r.jsx(iu,{y:H,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),r.jsx(iu,{y:I,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),r.jsx(vie,{type:"monotone",dataKey:p,name:p==="humidity"?"Humidity":"Temperature",stroke:p==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4},connectNulls:!0})]})})}),r.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 d3({data:t,children:e,disabled:n,className:a="",spoolman:i,inventory:s,configureSlot:o}){const{t:l}=_t(),c=ji(),[d,u]=y.useState(!1),[m,p]=y.useState("top"),[f,g]=y.useState(null),[w,b]=y.useState(!1),[x,S]=y.useState(!1),k=y.useRef(null),C=y.useRef(null),P=y.useRef(null),T=()=>{const z=t.trayUuid;z&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(z).then(()=>{b(!0),setTimeout(()=>b(!1),2e3)}).catch(()=>{A(z)}):A(z))},A=z=>{const L=document.createElement("textarea");L.value=z,L.style.position="fixed",L.style.opacity="0",document.body.appendChild(L),L.select();try{document.execCommand("copy"),b(!0),setTimeout(()=>b(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(L)};y.useLayoutEffect(()=>{if(!d){g(null);return}const z=()=>{if(!k.current||!C.current)return;const Z=k.current.getBoundingClientRect(),ne=C.current.offsetHeight,Y=C.current.offsetWidth,ue=Z.top-56,oe=window.innerHeight-Z.bottom,Q=ue<ne+12&&oe>ue?"bottom":"top",le=Z.left+Z.width/2,pe=Math.max(8,Math.min(le-Y/2,window.innerWidth-Y-8)),he=Q==="top"?Z.top-ne-8:Z.bottom+8;p(Q),g({top:he,left:pe})};z();const L=requestAnimationFrame(z);return window.addEventListener("scroll",z,!0),window.addEventListener("resize",z),()=>{cancelAnimationFrame(L),window.removeEventListener("scroll",z,!0),window.removeEventListener("resize",z)}},[d]);const F=()=>{n||(P.current&&clearTimeout(P.current),P.current=setTimeout(()=>u(!0),80))},_=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>u(!1),100)};y.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const M=z=>z<=15?"#ef4444":z<=30?"#f97316":z<=50?"#eab308":"#22c55e",H=t.colorHex?`#${t.colorHex.replace("#","")}`:null,I=s?.assignedSpool?.remainingWeightGrams??null;return r.jsxs("div",{ref:k,className:`relative ${a}`,onMouseEnter:F,onMouseLeave:_,children:[e,d&&cc.createPortal(r.jsxs("div",{ref:C,className:"fixed z-[60] animate-in fade-in-0 zoom-in-95 duration-150",style:{top:f?.top??-9999,left:f?.left??-9999,maxWidth:"calc(100vw - 24px)",visibility:f?"visible":"hidden"},onMouseEnter:F,onMouseLeave:_,children:[r.jsxs("div",{className:`
  8127. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8128. rounded-lg shadow-xl overflow-hidden
  8129. backdrop-blur-sm
  8130. `,children:[r.jsxs("div",{className:"h-12 relative overflow-hidden",style:{backgroundColor:H||"#3d3d3d"},children:[r.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-white/10 to-transparent"}),r.jsx("div",{className:`
  8131. absolute inset-0 flex items-center justify-center
  8132. font-semibold text-sm tracking-wide
  8133. ${rJ(H)?"text-black/80":"text-white/90"}
  8134. `,children:t.colorName}),r.jsx("div",{className:`
  8135. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  8136. ${t.vendor==="Bambu Lab"?"bg-black/60 text-white":"bg-black/50 text-white/90"}
  8137. `,children:t.vendor==="Bambu Lab"?"BBL":"GEN"})]}),r.jsxs("div",{className:"p-3 space-y-2.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.profile")}),r.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[120px]",children:t.profile})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.kFactor")}),r.jsx("span",{className:"text-xs text-bambu-green font-mono font-bold",children:t.kFactor})]}),r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1",children:[r.jsx(wO,{className:"w-3 h-3"}),l("ams.fill")]}),r.jsxs("span",{className:"text-xs text-white font-semibold flex items-center gap-1",children:[r.jsx("span",{children:t.fillLevel!==null?`${t.fillLevel}%`:"—"}),I!==null&&t.fillLevel!==null&&r.jsxs("span",{className:"text-[9px] text-bambu-gray font-normal",children:["• ",I,"g"]})]})]}),r.jsx("div",{className:"h-1.5 bg-black/40 rounded-full overflow-hidden",children:t.fillLevel!==null?r.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${t.fillLevel}%`,backgroundColor:M(t.fillLevel)}}):r.jsx("div",{className:"h-full w-full bg-bambu-gray/30 rounded-full"})})]}),i?.enabled&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("spoolman.spoolId")}),t.trayUuid?r.jsxs("button",{onClick:z=>{z.stopPropagation(),T()},className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",title:"Copy spool UUID",children:[r.jsxs("span",{className:"font-mono text-[10px] truncate max-w-[80px]",children:[t.trayUuid.slice(0,8),"..."]}),w?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):r.jsx(Ti,{className:"w-3 h-3"})]}):r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"—"})]}),i.linkedSpoolId&&r.jsx(r.Fragment,{children:r.jsxs("button",{onClick:z=>{z.stopPropagation(),c(`/inventory?spool=${i.linkedSpoolId}`)},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("inventory.openInInventory"),children:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),l("inventory.openInInventory")]})})]}),s&&r.jsx("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:s.assignedSpool?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}),r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("inventory.assigned")})]}),r.jsxs("div",{className:"flex items-baseline gap-1.5 min-w-0 mb-1",children:[r.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}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-bambu-gray shrink-0",children:["#",s.assignedSpool.id]})]}),(!i?.linkedSpoolId||s.assignedSpool.id!==i.linkedSpoolId)&&r.jsxs("button",{onClick:z=>{z.stopPropagation(),c(`/inventory?spool=${s.assignedSpool.id}`)},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("inventory.openInInventory"),children:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),l("inventory.openInInventory")]}),s.onUnassignSpool&&r.jsxs("button",{onClick:z=>{z.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:[r.jsx(ou,{className:"w-3.5 h-3.5"}),l("inventory.unassignSpool")]})]}):s.onAssignSpool?r.jsxs("button",{onClick:s.isAssigned?void 0:z=>{z.stopPropagation(),s.onAssignSpool?.()},disabled:!!s.isAssigned,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 text-bambu-blue ${s.isAssigned?"opacity-50 cursor-not-allowed":"hover:bg-bambu-blue/30"}`,children:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),l("inventory.assignSpool")]}):null}),o?.enabled&&r.jsx("div",{className:`${i?.enabled&&t.trayUuid?"":"pt-2 mt-2 border-t border-bambu-dark-tertiary"}`,children:r.jsxs("button",{onClick:z=>{z.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:[r.jsx(pu,{className:"w-3.5 h-3.5"}),l("ams.configure")]})})]})]}),r.jsx("div",{className:`
  8138. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8139. border-l-[6px] border-l-transparent
  8140. border-r-[6px] border-r-transparent
  8141. ${m==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8142. `})]}),document.body),x&&r.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center",onClick:()=>S(!1),children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),r.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:z=>z.stopPropagation(),children:r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsx("h3",{className:"text-base font-semibold text-white",children:l("spoolman.unlinkConfirmTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:l("spoolman.unlinkConfirmMessage")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:()=>S(!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")}),r.jsx("button",{onClick:()=>{i?.onUnlinkSpool?.(),S(!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("inventory.unassignSpool")})]})]})})]})]})}function u3({children:t,className:e="",configureSlot:n,onAssignSpool:a,kind:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState(null),u=y.useRef(null),m=y.useRef(null),p=y.useRef(null),f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};return y.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),y.useLayoutEffect(()=>{if(!o){d(null);return}const w=()=>{if(!u.current||!m.current)return;const x=u.current.getBoundingClientRect(),S=m.current.offsetHeight,k=m.current.offsetWidth,C=x.left+x.width/2,P=Math.max(8,Math.min(C-k/2,window.innerWidth-k-8)),T=x.top-S-8;d({top:T,left:P})};w();const b=requestAnimationFrame(w);return window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{cancelAnimationFrame(b),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[o]),r.jsxs("div",{ref:u,className:`relative ${e}`,onMouseEnter:f,onMouseLeave:g,children:[t,o&&cc.createPortal(r.jsxs("div",{ref:m,className:"fixed z-[60] animate-in fade-in-0 zoom-in-95 duration-150",style:{top:c?.top??-9999,left:c?.left??-9999,visibility:c?"visible":"hidden"},onMouseEnter:f,onMouseLeave:g,children:[r.jsxs("div",{className:`
  8143. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8144. rounded-md shadow-lg overflow-hidden
  8145. `,children:[r.jsx("div",{className:"px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap",children:s(i==="reset"?"ams.emptySlotReset":"ams.emptySlot")}),(n?.enabled||a)&&r.jsxs("div",{className:"px-2 pb-2 space-y-1",children:[n?.enabled&&r.jsxs("button",{onClick:w=>{w.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:s("ams.configureSlot"),children:[r.jsx(pu,{className:"w-3.5 h-3.5"}),s("ams.configure")]}),a&&r.jsxs("button",{onClick:w=>{w.stopPropagation(),a()},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:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),s("inventory.assignSpool")]})]})]}),r.jsx("div",{className:`
  8146. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  8147. border-l-[5px] border-l-transparent
  8148. border-r-[5px] border-r-transparent
  8149. border-t-[5px] border-t-bambu-dark-tertiary
  8150. `})]}),document.body)]})}function Qie({isOpen:t,onClose:e,tagUid:n,trayUuid:a,printerId:i,amsId:s,trayId:o}){const{t:l}=_t(),c=tn(),{showToast:d}=on(),[u,m]=y.useState(""),p=a||n,{data:f,isLoading:g}=Xe({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:t}),w=y.useMemo(()=>f?f.filter(x=>{if(!u)return!0;const S=u.toLowerCase();return x.filament_name&&x.filament_name.toLowerCase().includes(S)||x.filament_vendor&&x.filament_vendor.toLowerCase().includes(S)||x.filament_material&&x.filament_material.toLowerCase().includes(S)||String(x.id).includes(S)}):[],[f,u]),b=lt({mutationFn:x=>ae.linkSpool(x,{spoolTag:p,printerId:i,amsId:s,trayId:o}),onSuccess:()=>{c.invalidateQueries({queryKey:["unlinked-spools"]}),c.invalidateQueries({queryKey:["linked-spools"]}),c.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),d(l("spoolman.linkSuccess"),"success"),e()},onError:x=>{d(x.message||l("spoolman.linkFailed"),"error")}});return t?r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[r.jsxs("div",{children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Qy,{className:"w-5 h-5 text-bambu-green"}),l("spoolman.selectSpool")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",i]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 border-b border-white/10",children:[r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:u,onChange:x=>m(x.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"})]}),(a||n)&&r.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:a||n,children:["Tag: ",a||n]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:g?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):w.length===0?r.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):w.map(x=>r.jsxs("button",{onClick:()=>b.mutate(x.id),disabled:b.isPending||!p,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[r.jsx("span",{className:"w-6 h-6 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:x.filament_color_hex?`#${x.filament_color_hex}`:"#808080"}}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm text-white font-medium truncate",children:x.filament_name||l("spoolman.spoolId")}),r.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[x.filament_vendor?`${x.filament_vendor} · `:"",x.filament_material||"Unknown"," · #",x.id]})]}),r.jsx("span",{className:"text-xs text-bambu-gray",children:x.remaining_weight!=null?`${Math.round(x.remaining_weight)}g`:"—"})]},x.id))}),r.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:r.jsx(je,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function T7e(t,e){if(!e)return!0;const n=e.toLowerCase();return String(t.id).includes(n)||t.material.toLowerCase().includes(n)||(t.brand?.toLowerCase().includes(n)??!1)||(t.color_name?.toLowerCase().includes(n)??!1)||(t.subtype?.toLowerCase().includes(n)??!1)||(t.note?.toLowerCase().includes(n)??!1)||(t.slicer_filament_name?.toLowerCase().includes(n)??!1)||(t.storage_location?.toLowerCase().includes(n)??!1)}function lI(t,e){return e?t.filter(n=>T7e(n,e)):t}function Yie({isOpen:t,onClose:e,printerId:n,amsId:a,trayId:i,trayInfo:s,spoolmanEnabled:o}){const{t:l}=_t(),c=tn(),{showToast:d}=on(),[u,m]=y.useState(!1),[p,f]=y.useState(null),[g,w]=y.useState(null);y.useEffect(()=>{f(null),w(null)},[u]);const[b,x]=y.useState(""),[S,k]=y.useState(null),[C,P]=y.useState(!1),[T,A]=y.useState(null);y.useEffect(()=>{t&&m(!1)},[t]);const{data:F,isLoading:_}=Xe({queryKey:["inventory-spools","assign-modal"],queryFn:()=>ae.getSpools(!0),enabled:t&&!o}),{data:M}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),enabled:t}),{data:H}=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings(),enabled:t}),{data:I,isLoading:z}=Xe({queryKey:["spoolman-inventory-spools","assign-modal"],queryFn:()=>ae.getSpoolmanInventorySpools(!1),enabled:t&&!!o}),{data:L}=Xe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:t&&!!o}),Z=y.useMemo(()=>L?new Set(L.filter(j=>!(j.printer_id===n&&j.ams_id===a&&j.tray_id===i)).map(j=>j.spoolman_spool_id)):new Set,[L,n,a,i]),ne=()=>{ae.refreshPrinterStatus(n).catch(()=>{}),c.invalidateQueries({queryKey:["printerStatus",n]})},Y=lt({mutationFn:j=>ae.assignSpool({spool_id:j,printer_id:n,ams_id:a,tray_id:i}),onSuccess:j=>{c.setQueryData(["spool-assignments"],E=>{const B=(E||[]).filter(W=>!(W.printer_id===n&&W.ams_id===a&&W.tray_id===i));return B.push(j),B}),c.invalidateQueries({queryKey:["spool-assignments"]}),ne(),d(l("inventory.assignSuccess"),"success"),P(!1),k(null),A(null),e()},onError:j=>{d(`${l("inventory.assignFailed")}: ${j.message}`,"error")}}),ce=lt({mutationFn:j=>ae.assignSpoolmanSlot({spoolman_spool_id:j,printer_id:n,ams_id:a,tray_id:i}),onSuccess:()=>{c.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),c.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),ne(),d(l("inventory.assignSuccess"),"success"),e()},onError:j=>{d(`${l("inventory.assignFailed")}: ${j.message}`,"error")}}),ue=j=>(j??"").trim().toUpperCase(),oe=(j,E)=>{const B=ue(j),W=ue(E);return!B||!W?"none":B===W?"exact":W.includes(B)||B.includes(W)?"partial":"none"},Q=j=>j.split("@")[0].trim(),le=(j,E)=>{const B=Q(ue(j)),W=Q(ue(E));return!B||!W?!1:B===W};if(!t)return null;const pe=new Set((M||[]).filter(j=>!(j.printer_id===n&&j.ams_id===a&&j.tray_id===i)).map(j=>j.spool_id)),he=F?.filter(j=>!j.archived_at&&(u||!pe.has(j.id)));let we=he;if(!u){const j=Q(ue(s?.profile)),E=ue(s?.material||s?.type);(j||E)&&(we=we?.filter(B=>{const W=Q(ue(B.slicer_filament_name||B.slicer_filament)),O=ue(B.material);return j&&W&&W===j?!0:E&&O?O===E||E.includes(O)||O.includes(E):!W&&!O}))}b&&we&&(we=lI(we,b));const $=()=>{if(g!==null){ce.mutate(g);return}if(!p)return;const j=F?.find(E=>E.id===p);if(!j){d(l("inventory.assignFailed"),"error");return}if(!H?.disable_filament_warnings&&s){const E=s.material||s.type,B=oe(j.material,E),W=j.slicer_filament_name||j.slicer_filament,O=s.profile||s.type,ie=le(W,O);if(B!=="exact"||!ie){let U="profile";B==="none"&&!ie?U="material_profile":B==="partial"&&!ie?U="partial_profile":B==="none"?U="material":B==="partial"&&(U="partial"),k(p),A({type:U,spoolMaterial:j.material||"",trayMaterial:E||"",spoolProfile:W||void 0,trayProfile:O||void 0}),P(!0);return}}Y.mutate(p)},J=()=>{S&&(Y.mutate(S),P(!1),k(null))};return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"fixed inset-0 z-[100] flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Vr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("inventory.assignSpool")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto",children:[s&&r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[l("inventory.selectSpool"),":"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${s.color}`}}),r.jsx("span",{className:"text-white font-medium",children:s.type||l("ams.emptySlot")}),r.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:b,onChange:j=>x(j.target.value),placeholder:l("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"})]}),r.jsxs("div",{className:"space-y-3",children:[!o&&(_?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):we&&we.length>0?r.jsx("div",{className:"max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2",children:we.map(j=>r.jsxs("button",{onClick:()=>{f(j.id),w(null)},title:j.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${p===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[r.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[j.brand?`${j.brand} `:"",j.material,j.subtype?` ${j.subtype}`:""]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[j.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${j.rgba.substring(0,6)}`}}),r.jsx("span",{className:"text-xs text-bambu-gray truncate",children:j.color_name||""})]}),j.label_weight&&r.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[Math.max(0,Math.round(j.label_weight-j.weight_used))," / ",j.label_weight,"g"]})]},j.id))}):he&&he.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx("p",{children:l("inventory.noAvailableSpools")}),F&&r.jsxs("p",{className:"text-[10px] mt-2 opacity-60",children:[F.length," fetched · ",F.filter(j=>j.archived_at).length," archived ·"," ",F.filter(j=>pe.has(j.id)).length," assigned to other slots"]})]}):r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx("p",{children:l("inventory.noSpoolsMatch")}),he&&r.jsxs("p",{className:"text-[10px] mt-2 opacity-60",children:[he.length," unassigned spools — ",he.length-(we?.length??0),' filtered by tray match. Try "Show all spools".']})]})),o&&r.jsx(r.Fragment,{children:z?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ft,{className:"w-5 h-5 text-bambu-green animate-spin"})}):I&&I.filter(j=>!j.archived_at&&!Z.has(j.id)).length>0?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide pt-1",children:l("inventory.spoolmanSpools")}),r.jsx("div",{className:"max-h-64 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2",children:lI(I.filter(j=>!j.archived_at&&!Z.has(j.id)),b).map(j=>r.jsxs("button",{onClick:()=>{w(j.id),f(null)},title:j.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${g===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[r.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[j.brand?`${j.brand} `:"",j.material,j.subtype?` ${j.subtype}`:""]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[j.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${j.rgba.substring(0,6)}`}}),r.jsx("span",{className:"text-xs text-bambu-gray truncate",children:j.color_name||""})]}),j.label_weight&&r.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[Math.max(0,Math.round(j.label_weight-j.weight_used))," / ",j.label_weight,"g"]})]},`spoolman-${j.id}`))})]}):null})]})]}),r.jsxs("div",{className:"flex justify-between items-center p-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{id:"disable-filtering-toggle",type:"checkbox",checked:u,onChange:()=>m(j=>!j),className:"accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary"}),r.jsx("label",{htmlFor:"disable-filtering-toggle",className:"text-xs text-bambu-gray select-none cursor-pointer",children:l("inventory.showAllSpools")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,children:l("common.cancel")}),r.jsx(je,{onClick:$,disabled:!p&&g===null||Y.isPending||ce.isPending,children:Y.isPending||ce.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),l("inventory.assigning")]}):r.jsxs(r.Fragment,{children:[r.jsx(Vr,{className:"w-4 h-4"}),l("inventory.assignSpool")]})})]})]}),Y.isError&&r.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:Y.error.message})]})]}),C&&s&&p&&T&&(()=>{let j="";return T.type==="material"?j=l("inventory.assignMismatchMessage",{spoolMaterial:T.spoolMaterial,trayMaterial:T.trayMaterial,location:s.location}):T.type==="partial"?j=l("inventory.assignPartialMismatchMessage",{spoolMaterial:T.spoolMaterial,trayMaterial:T.trayMaterial,location:s.location}):T.type==="material_profile"?j=`${l("inventory.assignMismatchMessage",{spoolMaterial:T.spoolMaterial,trayMaterial:T.trayMaterial,location:s.location})}
  8151. ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="partial_profile"?j=`${l("inventory.assignPartialMismatchMessage",{spoolMaterial:T.spoolMaterial,trayMaterial:T.trayMaterial,location:s.location})}
  8152. ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="profile"&&(j=l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})),r.jsx(wn,{title:l("inventory.assignMismatchTitle"),message:j,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",overlayZIndex:"z-[110]",isLoading:Y.isPending,onConfirm:J,onCancel:()=>{Y.isPending||(P(!1),k(null),A(null))}})})()]})}function RK(t,e){if(t===255)return"External";let n,a=!1;t>=128&&t<=135?(n=t-128,a=!0):t>=0&&t<=3?(n=t,a=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return a?`HT-${i}`:`AMS-${i}`}function m3(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 sw=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function IK(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),a=n.match(/\bSUPPORT\s+FOR\s+/);if(a){const s=n.slice(a.index+a[0].length);for(const o of sw)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,a.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of sw){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 A7e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const j7e={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"},OK=[{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"}],zK=[{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 UK(t){const e=t.toLowerCase().trim();return j7e[e]||null}function M7e(t){const e=t.indexOf("@");if(e<0)return null;const a=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return a?a[1].trim():null}function Xie({isOpen:t,onClose:e,printerId:n,slotInfo:a,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(""),[k,C]=y.useState(!1),[P,T]=y.useState(!1),A=y.useRef(""),{data:F,isLoading:_,isError:M}=Xe({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:t,retry:!1}),{data:H,isLoading:I}=Xe({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets(),enabled:t}),{data:z,isLoading:L}=Xe({queryKey:["builtinFilaments"],queryFn:()=>ae.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:Z,isLoading:ne}=Xe({queryKey:["kprofiles",n,i],queryFn:()=>ae.getKProfiles(n,i),enabled:t&&!!n}),{data:Y}=Xe({queryKey:["colorCatalog"],queryFn:()=>ae.getColorCatalog(),enabled:t,staleTime:1/0}),ce=lt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const E=d.startsWith("local_"),B=d.startsWith("builtin_"),W=E?parseInt(d.replace("local_",""),10):null,O=B?d.replace("builtin_",""):null,ie=E?H?.filament.find(Me=>Me.id===W):null,U=B?z?.find(Me=>Me.filament_id===O):null,G=!E&&!B?F?.filament.find(Me=>Me.setting_id===d):null;if(!E&&!B&&!G)throw new Error("Selected preset not found");if(E&&!ie)throw new Error("Selected local preset not found");if(B&&!U)throw new Error("Selected builtin preset not found");const K=E?ie.name:B?U.name:G.name,X=IK(K),se=m?.slot_id??-1,te=f||a.trayColor?.slice(0,6)||"FFFFFF",fe=K.replace(/@.+$/,"").trim();let de,me;const q=X.material.toUpperCase();if(E){const Me=(sw.includes(q)?q:ie?.filament_type||X.material||"").toUpperCase(),Be={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};de=Be[Me]||Be[Me.replace(/[-\s]?CF$/,"")]||Be[Me.replace(/\+$/,"")]||Be[Me.split(/[-\s]/)[0]]||"",me=""}else if(B)de=O,me="";else if(de=m3(d),me=d,!d.startsWith("GFS"))try{const Me=await ae.getCloudSettingDetail(d);Me.filament_id&&(de=Me.filament_id)}catch(Me){console.warn("Failed to fetch preset detail for filament_id:",Me)}let R=E&&ie?.nozzle_temp_min?ie.nozzle_temp_min:190,re=E&&ie?.nozzle_temp_max?ie.nozzle_temp_max:230;if(!E||B||!ie?.nozzle_temp_min&&!ie?.nozzle_temp_max){const Me=(E?sw.includes(q)?q:ie?.filament_type||X.material||"":X.material).toUpperCase();Me.includes("PLA")?(R=190,re=230):Me.includes("PETG")?(R=220,re=260):Me.includes("ABS")||Me.includes("ASA")?(R=240,re=280):Me.includes("TPU")?(R=200,re=240):Me==="PCTG"?(R=220,re=260):Me.includes("PC")?(R=260,re=300):(Me.includes("PA")||Me.includes("NYLON"))&&(R=250,re=290)}const be=m?.k_value?parseFloat(m.k_value):0,ye=E?sw.includes(q)?q:ie?.filament_type||X.material||"PLA":X.material||"PLA",_e=await ae.configureAmsSlot(n,a.amsId,a.trayId,{tray_info_idx:de,tray_type:ye,tray_sub_brands:fe,tray_color:te+"FF",nozzle_temp_min:R,nozzle_temp_max:re,cali_idx:se,nozzle_diameter:i,setting_id:me,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:be}),xe=E?`local_${W}`:B?`builtin_${O}`:d,ge=E?"local":B?"builtin":"cloud";try{await ae.saveSlotPreset(n,a.amsId,a.trayId,xe,fe,ge)}catch(Me){console.warn("Failed to save slot preset mapping:",Me)}return _e},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),ue=lt({mutationFn:async()=>ae.resetAmsSlot(n,a.amsId,a.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),oe=y.useMemo(()=>{const E=x.toLowerCase(),B=[],W=new Set,O=a.savedPresetId,ie=a.trayInfoIdx;if(F?.filament)for(const U of F.filament){W.add(U.setting_id);const K=O===U.setting_id||ie&&(U.setting_id===ie||m3(U.setting_id)===ie);if(!(E&&!U.name.toLowerCase().includes(E))){if(!K&&s){const X=M7e(U.name);if(X&&X.toUpperCase()!==s.toUpperCase())continue}B.push({id:U.setting_id,name:U.name,source:"cloud",isUser:A7e(U.setting_id)})}}if(H?.filament)for(const U of H.filament){const G=`local_${U.id}`;E&&!U.name.toLowerCase().includes(E)||B.push({id:G,name:U.name,source:"local",isUser:!1})}if(z)for(const U of z){if(W.has(U.filament_id))continue;const G=U.filament_id.startsWith("GF")?"GFS"+U.filament_id.slice(2):U.filament_id;W.has(G)||(!E||U.name.toLowerCase().includes(E))&&B.push({id:`builtin_${U.filament_id}`,name:U.name,source:"builtin",isUser:!1})}return B.sort((U,G)=>{const K={cloud:0,local:1,builtin:2};return U.source!==G.source?K[U.source]-K[G.source]:U.isUser&&!G.isUser?-1:!U.isUser&&G.isUser?1:U.name.localeCompare(G.name)})},[F?.filament,H?.filament,z,x,s,a.savedPresetId,a.trayInfoIdx]),Q=y.useMemo(()=>{if(!d)return null;let E=null;if(d.startsWith("local_")){const O=parseInt(d.replace("local_",""),10);E=H?.filament.find(U=>U.id===O)?.name||null}else if(d.startsWith("builtin_")){const O=d.replace("builtin_","");E=z?.find(U=>U.filament_id===O)?.name||null}else F?.filament&&(E=F.filament.find(ie=>ie.setting_id===d)?.name||null);if(!E)return null;let B=E.replace(/@.+$/,"").trim();B.startsWith("# ")&&(B=B.slice(2).trim());const W=IK(B);return{fullName:B,material:W.material,brand:W.brand}},[d,F?.filament,H?.filament,z]),le=Q?.fullName||"",pe=y.useMemo(()=>{if(!Y||!Q)return[];const{fullName:E,brand:B}=Q,W=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return Y.filter(O=>{const ie=(O.material||"").toUpperCase(),U=O.manufacturer.toUpperCase();if(!(ie===W.toUpperCase()||ie.includes(W.toUpperCase())||W.toUpperCase().includes(ie)))return!1;if(B){const K=B.toUpperCase();if(!U.includes(K)&&!K.includes(U))return!1}return!0})},[Y,Q]),he=y.useMemo(()=>{if(!Z?.profiles||!Q)return[];const{fullName:E,material:B,brand:W}=Q,O=E.toUpperCase(),ie=B.toUpperCase(),U=W.toUpperCase();if(!ie||ie.length<2)return[];const G=Z.profiles.filter(X=>{const se=X.name.toUpperCase();if(U)return!(!se.includes(U)||!se.includes(ie));if(se.includes(O)||se.includes(ie))return!0;const fe={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ie]||[];for(const de of fe)if(se.includes(de))return!0;return!1}),K=new Map;for(const X of G){const se=`${X.name}|${X.k_value}`,te=K.get(se);te?a.extruderId!==void 0&&X.extruder_id===a.extruderId&&te.extruder_id!==a.extruderId&&K.set(se,X):K.set(se,X)}return Array.from(K.values())},[Z?.profiles,Q,a.extruderId]);y.useEffect(()=>{if(t){if(a.savedPresetId)u(a.savedPresetId);else if(a.trayInfoIdx&&F?.filament){let E=F.filament.find(B=>B.setting_id===a.trayInfoIdx);E||(E=F.filament.find(B=>m3(B.setting_id)===a.trayInfoIdx)),E&&u(E.setting_id)}else if(a.trayInfoIdx&&z?.length){const E=a.trayInfoIdx,B=z.find(W=>W.filament_id===E);B&&u(`builtin_${B.filament_id}`)}if(a.trayColor){const E=a.trayColor.slice(0,6);E&&g(E)}}else u(""),p(null),g(""),b(""),S(""),C(!1),A.current=""},[t,a.savedPresetId,a.trayInfoIdx,a.trayColor,F?.filament,z]),y.useEffect(()=>{if(he.length>0){if(a.caliIdx!=null&&a.caliIdx>0){const E=he.find(B=>B.slot_id===a.caliIdx);if(E){p(E);return}}p(he[0])}else p(null)},[d,he,a.caliIdx]);const we=y.useCallback(E=>{E.key==="Escape"&&e()},[e]);y.useEffect(()=>{if(t)return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[t,we]);const $=_&&!M||I||L||ne;if(y.useEffect(()=>{if(!$&&d&&d!==A.current){const E=requestAnimationFrame(()=>{const W=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);W&&(A.current=d,W.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[d,$]),!t)return null;const J=d&&!ce.isPending,j=f||a.trayColor?.slice(0,6)||"FFFFFF";return r.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pu,{className:"w-5 h-5 text-bambu-blue"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&r.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[r.jsx("span",{className:"text-white/30",children:"|"}),a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:RK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{children:["(",a.traySubBrands,")"]})]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[k&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:r.jsxs("div",{className:"text-center space-y-3",children:[r.jsx(yl,{className:"w-16 h-16 text-bambu-green mx-auto"}),r.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),r.jsxs("div",{className:"flex items-center gap-2",children:[a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:RK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{className:"text-bambu-gray",children:["(",a.traySubBrands,")"]})]})]}),$?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?r.jsxs("div",{className:"flex gap-4 h-full",children:[r.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:E=>S(E.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"}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:oe.length===0?r.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(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]}),r.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),le&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:le})})]}),he.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=he.find(W=>W.name===E.target.value);p(B||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:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),he.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.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&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),r.jsx("button",{onClick:()=>T(!P),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(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(O.split("").map(ie=>ie+ie).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&&r.jsx("button",{onClick:()=>{g(""),b("")},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&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:E=>S(E.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"}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:oe.length===0?r.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(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),E.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),E.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},E.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),le&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:le})})]}),he.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=he.find(W=>W.name===E.target.value);p(B||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:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),he.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.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&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex)),r.jsx("button",{onClick:()=>T(!P),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(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(O.split("").map(ie=>ie+ie).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&&r.jsx("button",{onClick:()=>{g(""),b("")},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&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),r.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[r.jsx(je,{variant:"secondary",onClick:()=>ue.mutate(),disabled:ue.isPending||ce.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:ue.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(je,{onClick:()=>ce.mutate(),disabled:!J,children:ce.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(pu,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(ce.isError||ue.isError)&&r.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:ce.error?.message||ue.error?.message})]})]})}function BK({className:t="w-4 h-4"}){return r.jsx("svg",{viewBox:"0 0 1945 1370",fill:"none",className:t,"aria-hidden":"true",children:r.jsxs("g",{transform:"translate(-754.293 -471.685)",children:[r.jsxs("g",{transform:"translate(0.18191 255.976)",children:[r.jsx("g",{transform:"matrix(1.05469 0 0 0.241063 -153.484 1120.2)",children:r.jsx("rect",{x:"922.048",y:"1195.15",width:"1721.5",height:"470.135",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"168.84",strokeLinecap:"round",strokeLinejoin:"round"})}),r.jsx("g",{transform:"matrix(0.983656 0 0 1.0767 -62.2035 141.539)",children:r.jsx("path",{d:"M2741.42,1175.93L895.832,1175.93L1125.16,621.902L2512.09,621.902L2741.42,1175.93Z",fill:"currentColor",fillOpacity:"0.05",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"125.26",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r.jsx("g",{transform:"translate(21.1916 0.684817)",children:r.jsx("path",{d:"M1981.31,567.518C1954.86,567.518 1933.39,546.047 1933.39,519.601C1933.39,493.156 1954.86,471.685 1981.31,471.685L2146.61,471.685C2173.07,471.685 2194.53,493.138 2194.53,519.601L2194.53,688.741C2194.53,715.187 2173.05,736.658 2146.61,736.658C2120.16,736.658 2098.69,715.187 2098.69,688.741L2098.69,567.518L1981.31,567.518ZM2098.69,1252.54C2098.69,1226.1 2120.16,1204.62 2146.61,1204.62C2173.05,1204.62 2194.53,1226.1 2194.53,1252.54L2194.53,1421.68C2194.53,1448.14 2173.07,1469.6 2146.61,1469.6L1981.31,1469.6C1954.86,1469.6 1933.39,1448.13 1933.39,1421.68C1933.39,1395.24 1954.86,1373.76 1981.31,1373.76L2098.69,1373.76L2098.69,1252.54ZM1430.29,1373.76C1456.74,1373.76 1478.21,1395.24 1478.21,1421.68C1478.21,1448.13 1456.74,1469.6 1430.29,1469.6L1264.99,1469.6C1238.53,1469.6 1217.07,1448.14 1217.07,1421.68L1217.07,1252.54C1217.07,1226.1 1238.55,1204.62 1264.99,1204.62C1291.44,1204.62 1312.91,1226.1 1312.91,1252.54L1312.91,1373.76L1430.29,1373.76ZM1312.91,688.741C1312.91,715.187 1291.44,736.658 1264.99,736.658C1238.55,736.658 1217.07,715.187 1217.07,688.741L1217.07,519.601C1217.07,493.138 1238.53,471.685 1264.99,471.685L1430.29,471.685C1456.74,471.685 1478.21,493.156 1478.21,519.601C1478.21,546.047 1456.74,567.518 1430.29,567.518L1312.91,567.518L1312.91,688.741Z",fill:"currentColor",fillOpacity:"0.99"})})]})})}function Zie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:a,autoUpload:i,validateFile:s,accept:o}){const{t:l}=_t(),[c,d]=y.useState([]),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,w]=y.useState(!0),[b,x]=y.useState(!1),[S,k]=y.useState(!0),[C,P]=y.useState(null),T=y.useRef(null),A=oe=>{oe.preventDefault(),m(!0)},F=oe=>{oe.preventDefault(),m(!1)},_=oe=>{oe.preventDefault(),m(!1),z(Array.from(oe.dataTransfer.files))},M=oe=>{oe.target.files&&z(Array.from(oe.target.files))},H=(oe,Q)=>{d(le=>le.map(pe=>pe.file===oe?{...pe,...Q}:pe))},I=async oe=>{f(!0);for(const Q of oe)if(Q.status==="pending"){H(Q.file,{status:"uploading"});try{if(Q.isZip){const le=await ae.extractZipFile(Q.file,t,g,b,S);H(Q.file,{status:le.errors.length>0&&le.extracted===0?"error":"success",extractedCount:le.extracted,error:le.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:le.errors.length}):void 0})}else{const le=await ae.uploadLibraryFile(Q.file,t,S);H(Q.file,{status:"success"});const pe=a?.(le);if(pe){P(pe),d([]),f(!1);return}}}catch(le){H(Q.file,{status:"error",error:le instanceof Error?le.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),d(Q=>(Q.some(pe=>pe.status==="error")||e(),Q))},z=oe=>{if(P(null),s)for(const le of oe){const pe=s(le);if(pe){P(pe);return}}const Q=oe.map(le=>({file:le,status:"pending",isZip:le.name.toLowerCase().endsWith(".zip"),is3mf:le.name.toLowerCase().endsWith(".3mf")}));d(le=>[...le,...Q]),i&&oe.length>0&&I(Q)},L=oe=>{d(Q=>Q.filter((le,pe)=>pe!==oe))},Z=c.some(oe=>oe.isZip&&oe.status==="pending"),ne=c.some(oe=>oe.file.name.toLowerCase().endsWith(".stl")&&oe.status==="pending"),Y=c.some(oe=>oe.is3mf&&oe.status==="pending"),ce=c.filter(oe=>oe.status==="pending").length,ue=c.length>0&&ce===0&&!p;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{onDragOver:A,onDragLeave:F,onDrop:_,onClick:()=>T.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:[r.jsx(_a,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),r.jsx("p",{className:"text-white font-medium",children:l(u?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),r.jsx("input",{ref:T,type:"file",multiple:!0,accept:o,className:"hidden",onChange:M}),Z&&r.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(eo,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),r.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:g,onChange:oe=>w(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:b,onChange:oe=>x(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),Y&&r.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(hr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),r.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(ne||Z)&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(mu,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),r.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(Z&&!ne?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:S,onChange:oe=>k(oe.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((oe,Q)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[oe.isZip?r.jsx(eo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(NT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:oe.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(oe.file.size/1024/1024).toFixed(2)," MB",oe.isZip&&oe.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),oe.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:oe.extractedCount})]})]}),oe.status==="error"&&oe.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1 break-words",children:oe.error})]}),oe.status==="pending"&&r.jsx("button",{onClick:()=>L(Q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray"})}),oe.status==="uploading"&&r.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),oe.status==="success"&&r.jsx(xr,{className:"w-4 h-4 text-green-500"}),oe.status==="error"&&r.jsx("span",{title:oe.error,children:r.jsx($r,{className:"w-4 h-4 text-red-500"})})]},Q))}),C&&r.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx($r,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300",children:C})]})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,children:l("common.cancel")}),!ue&&r.jsx(je,{onClick:()=>I(c),disabled:ce===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ce>0?`(${ce})`:""]})})]})]})})}function HK(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ia(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const E7e=[["PA-CF","PA12-CF","PAHT-CF"]],Jie={};for(const t of E7e){const e=t[0];for(const n of t)Jie[n.toUpperCase()]=e.toUpperCase()}function wP(t){if(!t)return"";const e=t.toUpperCase();return Jie[e]??e}function p3(t,e){return wP(t)===wP(e)}function md(t,e,n=40){const a=Ia(t),i=Ia(e);if(!a||!i||a.length<6||i.length<6)return!1;const s=parseInt(a.substring(0,2),16),o=parseInt(a.substring(2,4),16),l=parseInt(a.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 u_(t,e,n,a){if(a)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`${i}${e+1}`}function Qg(t,e,n){return n?254+e:t>=128?t:t*4+e}function my(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function LN(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 qK(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function D7e(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let a=0;a<e.length;a++)n^=e.charCodeAt(a),n=Math.imul(n,16777619);return(n>>>0).toString(16).toUpperCase().padStart(8,"0")}function gm(t,e,n){return`${D7e(t)}${qK(e,4)}${qK(n,4)}`}function $K(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Yn(t)?.getTime()??0)>e}function F7e(t,e,n,a){let i=ese(e,t.nozzle_id);a&&(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)&&p3(c.type,t.type)&&Ia(c.color)===Ia(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type)&&md(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type));return s??o??l}function ese(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Ks(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function m_(t){const e=[],n=t?.ams_extruder_map,a=!!t?.nozzles?.[1]?.nozzle_diameter||n&&Object.keys(n).length>0||(t?.vt_tray?.length??0)>1;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=HK(o.tray_color);e.push({type:o.tray_type,color:l,colorName:fc(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:u_(i.id,o.id,s,!1),globalTrayId:Qg(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=HK(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:fc(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:a?255-o:void 0,remain:i.remain??-1})}return e}function VK(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const a=m_(e);if(a.length===0)return;const i=e?.fila_switch?.installed===!0,s=new Set,o=t.filaments.map(d=>{const u=d.tray_info_idx||"";let m=a.filter(x=>!s.has(x.globalTrayId));d.nozzle_id!=null&&!i&&(m=m.filter(x=>x.extruderId===d.nozzle_id)),n&&(m=[...m].sort((x,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));let p,f,g,w;if(u){const x=m.filter(S=>S.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(n&&x.sort((S,k)=>{const C=S.remain>=0?S.remain:101,P=k.remain>=0?k.remain:101;return C-P}),f=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(S.color)===Ia(d.color)),f||(g=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&md(S.color,d.color))),!f&&!g&&(w=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!g&&!w&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(x.color)===Ia(d.color)),f||(g=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&md(x.color,d.color))),!f&&!g&&(w=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const b=p||f||g||w||void 0;return b&&s.add(b.globalTrayId),{slot_id:d.slot_id,globalTrayId:b?.globalTrayId??-1}}),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}function L7e(t){return y.useMemo(()=>m_(t),[t])}function tse(t,e,n,a){const i=L7e(e),s=e?.fila_switch?.installed===!0,o=y.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const u=new Set(Object.values(n));return t.filaments.map(m=>{const p=m.slot_id||0;if(p>0&&n[p]!==void 0){const F=n[p],_=i.find(M=>M.globalTrayId===F);if(_){const M=_.type?.toUpperCase()===m.type?.toUpperCase(),H=Ia(_.color)===Ia(m.color)||md(_.color,m.color);let I;return M&&H?I="match":M?I="type_only":I="mismatch",{...m,loaded:_,hasFilament:!0,typeMatch:M,colorMatch:H,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let g=i.filter(F=>!u.has(F.globalTrayId));m.nozzle_id!=null&&!s&&(g=g.filter(F=>F.extruderId===m.nozzle_id)),a&&(g=[...g].sort((F,_)=>{const M=F.remain>=0?F.remain:101,H=_.remain>=0?_.remain:101;return M-H}));let w,b,x,S;if(f){const F=g.filter(_=>_.trayInfoIdx===f);F.length===1?w=F[0]:F.length>1&&(a&&F.sort((_,M)=>{const H=_.remain>=0?_.remain:101,I=M.remain>=0?M.remain:101;return H-I}),b=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(_.color)===Ia(m.color)),b||(x=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&md(_.color,m.color))),!b&&!x&&(S=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase())))}!w&&!b&&!x&&!S&&(b=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(F.color)===Ia(m.color)),b||(x=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&md(F.color,m.color))),!b&&!x&&(S=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase())));const k=w||b||x||S||void 0;k&&u.add(k.globalTrayId);const C=!!k,P=C,T=!!w||!!b||!!x;let A;return w||b||x?A="match":S?A="type_only":A="mismatch",{...m,loaded:k,hasFilament:C,typeMatch:P,colorMatch:T,status:A,isManual:!1}})},[t,i,n,a,s]),l=y.useMemo(()=>{if(o.length===0)return;const u=Math.max(...o.map(p=>p.slot_id||0));if(u<=0)return;const m=new Array(u).fill(-1);return o.forEach(p=>{p.slot_id&&p.slot_id>0&&(m[p.slot_id-1]=p.loaded?.globalTrayId??-1)}),m},[o]),c=o.some(u=>u.status==="mismatch"),d=o.some(u=>u.status==="type_only");return{loadedFilaments:i,filamentComparison:o,amsMapping:l,hasTypeMismatch:c,hasColorMismatch:d}}function R7e(t,e,n,a){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 x=n[m],S=e.find(k=>k.globalTrayId===x);if(S){const k=S.type?.toUpperCase()===u.type?.toUpperCase(),C=Ia(S.color)===Ia(u.color)||md(S.color,u.color);k&&C?i++:k?s++:o++;continue}}let p=e.filter(x=>!l.has(x.globalTrayId));if(u.nozzle_id!=null){const x=p.filter(S=>S.extruderId===u.nozzle_id);x.length>0&&(p=x)}a&&(p=[...p].sort((x,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&Ia(x.color)===Ia(u.color)),g=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&md(x.color,u.color)),w=f||g?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),b=f??g??w;b&&l.add(b.globalTrayId),f||g?i++:w?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 I7e(t,e,n,a){if(!t?.filaments||t.filaments.length===0)return;const i=m_(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(b=>!s.has(b.globalTrayId));if(d.nozzle_id!=null){const b=m.filter(x=>x.extruderId===d.nozzle_id);b.length>0&&(m=b)}a&&(m=[...m].sort((b,x)=>{const S=b.remain>=0?b.remain:101,k=x.remain>=0?x.remain:101;return S-k}));const p=m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(b.color)===Ia(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&md(b.color,d.color)),g=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),w=p??f??g;w&&s.add(w.globalTrayId),o.push({slot_id:u,globalTrayId:w?.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 GK={useDefault:!0,manualMappings:{},autoConfigured:!1};function O7e(t,e,n,a,i,s,o){const l=rf({queries:t.map(w=>({queryKey:["printer-status",w],queryFn:()=>ae.getPrinterStatus(w),enabled:t.length>0,staleTime:5e3}))}),c=y.useMemo(()=>t.map((w,b)=>{const x=l[b],S=x?.data,C=e?.find(H=>H.id===w)?.name||`Printer ${w}`,P=m_(S),T=i[w]||GK,A=VK(n,S,o),F=T.useDefault?a:T.manualMappings,_=I7e(n,S,F,o),M=R7e(n?.filaments,P,F,o);return{printerId:w,printerName:C,status:S,isLoading:x?.isLoading??!1,loadedFilaments:P,autoMapping:A,finalMapping:_,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:T}}),[t,l,e,n,i,a,o]),d=l.some(w=>w.isLoading),u=(w,b)=>{s(x=>({...x,[w]:{...x[w]||GK,...b}}))},m=w=>{const b=c.find(k=>k.printerId===w);if(!b||!b.status||!n?.filaments)return;const x=VK(n,b.status,o);if(!x)return;const S={};x.forEach((k,C)=>{k!==-1&&(S[C+1]=k)}),u(w,{useDefault:!1,manualMappings:S,autoConfigured:!0})},p=()=>{for(const w of t)m(w)},f=w=>c.find(x=>x.printerId===w)?.finalMapping,g=c.every(w=>w.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:g}}const nse={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$",BZD:"BZ$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function Ho(t){return nse[t.toUpperCase()]||t}const z7e=Object.entries(nse).map(([t,e])=>({code:t,label:`${t} (${e})`}));function U7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:a,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=_t(),c=tn(),[d,u]=y.useState(!1),[m,p]=y.useState(o),{data:f}=Xe({queryKey:["printer-status",t],queryFn:()=>ae.getPrinterStatus(t),enabled:!!t}),{data:g}=Xe({queryKey:["spool-assignments",t],queryFn:()=>ae.getAssignments(t),enabled:!!t}),{loadedFilaments:w,filamentComparison:b,hasTypeMismatch:x,hasColorMismatch:S}=tse(e,f,n),k=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne);L.set(Y,Z.spool?.cost_per_kg??null)}return L},[g]),C=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne),ce=Z.spool;if(!ce){L.set(Y,null);continue}L.set(Y,Math.max(0,Math.round((ce.label_weight??0)-(ce.weight_used??0))))}return L},[g]),P=y.useMemo(()=>{let L=0;for(const Z of b){const ne=Z.loaded?.globalTrayId;if(ne==null)continue;const ce=k.get(ne)??null??s;ce>0&&(L+=Z.used_grams/1e3*ce)}return L},[b,k,s]),T=y.useMemo(()=>Array.from(k.values()).some(L=>L!=null&&L>0),[k]),A=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(L=>L.nozzle_id!=null)??!1,_=f?.fila_switch?.installed===!0,M=L=>{const Z=f?.fila_switch;if(!Z?.installed)return null;const ne=Z.in_slots.indexOf(L);return ne<0?null:Z.out_extruders[ne]??null};if(!A||!f)return null;const H=x?"#f97316":S?"#facc15":"#00ae42",I=(L,Z)=>{if(L>0)if(Z===""){const ne={...n};delete ne[L],a(ne)}else a({...n,[L]:parseInt(Z,10)})},z=async()=>{u(!0);try{await ae.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return r.jsxs("div",{className:"mb-4",children:[r.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:[r.jsx(Mw,{className:"w-4 h-4",fill:H,stroke:"none"}),r.jsx("span",{children:l("printModal.filamentMapping")}),x?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):S?r.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):r.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?r.jsx(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{className:"w-4 h-4 ml-auto"})]}),m&&r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),r.jsxs("button",{type:"button",onClick:z,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:[r.jsx(tr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),b.map((L,Z)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${L.type} - ${fc(L.color)}`,children:r.jsx(Mw,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),r.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[F&&L.nozzle_id!=null&&r.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:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:ne=>I(L.slot_id||0,ne.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 ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),w.filter(ne=>L.nozzle_id==null||_||ne.extruderId===L.nozzle_id).map(ne=>{const Y=C.get(ne.globalTrayId),ce=Y!=null?l("printModal.slotRemainingShort",{grams:Y,defaultValue:` - ${Y}g left`}):"",ue=_?M(ne.globalTrayId):null,oe=ue==null?"":` [${l(ue===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:ne.globalTrayId,className:"bg-bambu-dark text-white",children:[ne.label,": ",ne.traySubBrands||ne.type," (",ne.colorName,")",ce,oe]},ne.globalTrayId)})]}),L.status==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},Z)),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",r.jsx("span",{className:"text-white",children:P>0||T?`${i}${P.toFixed(2)}`:"N/A"})]}),x&&r.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function B7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:a,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=_t(),l=y.useMemo(()=>{const u={};for(const m of e){const p=wP(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],a(p)}else{const[p,f]=m.split("|");a({...n,[u]:{type:p,color:f}})}};return r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:r.jsx("span",{children:o("printModal.filamentOverride")})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),r.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[wP(u.type)]||[],g=u.nozzle_id!=null?f.filter(w=>w.extruder_id==null||w.extruder_id===u.nozzle_id):f;return r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[r.jsx("span",{title:`${o("printModal.originalFilament")}: ${u.type} - ${fc(u.color)}`,children:r.jsx(Mw,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),r.jsxs("span",{className:"text-white truncate",children:[u.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:w=>d(u.slot_id,w.target.value),disabled:g.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:[r.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",u.type," (",fc(u.color),")"]}),g.map((w,b)=>r.jsxs("option",{value:`${w.type}|${w.color}`,className:"bg-bambu-dark text-white",children:[w.tray_sub_brands||w.type," (",fc(w.color),")"]},`${w.type}-${w.color}-${w.tray_sub_brands}-${b}`))]}),p?r.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:r.jsx(fs,{className:"w-3 h-3"})}):r.jsx("span",{className:"w-3"})]}),r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[r.jsx("input",{type:"checkbox",checked:i?.[u.slot_id]??!1,onChange:w=>s?.(u.slot_id,w.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(ES,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function H7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:a,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=_t();if(!e||t.length<=1)return null;const c=n.size===t.length;return r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx(ca,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&r.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[r.jsx(Nn,{className:"w-3 h-3"}),"Selection required"]}),o&&i&&s&&r.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})})]}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(d=>{const u=n.has(d.index);return r.jsxs("button",{type:"button",onClick:()=>a(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?r.jsx(gs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):r.jsx(ro,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?r.jsx("img",{src:La(d.thumbnail_url),alt:`Plate ${d.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(ca,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:d.name||`Plate ${d.index}`}),r.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?` • ${cs(d.print_time_seconds)}`:""]})]}),!o&&u&&r.jsx(Ar,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const q7e=new Set(["IDLE","FINISH","FAILED"]);function $7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const a=tn(),[i,s]=y.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 ae.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await a.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(w=>w.globalTrayId===m),f=!0;else{const w=new Set(Object.values(t.config.manualMappings)),b=a.getQueryData(["settings"]);p=F7e(d,t.loadedFilaments,w,b?.prefer_lowest_filament)}let g="mismatch";if(p){const w=p.type?.toUpperCase()===d.type?.toUpperCase(),b=Ia(p.color)===Ia(d.color)||md(p.color,d.color);w&&b?g="match":w&&(g="type_only")}return{req:d,loaded:p,status:g,isManual:f}});return r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),r.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:[r.jsx(tr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:m,isManual:p},f)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${d.type} - ${fc(d.color)}`,children:r.jsx(Mw,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),r.jsxs("span",{className:"text-white truncate",children:[d.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:u?.globalTrayId??"",onChange:g=>o(d.slot_id||0,g.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:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),ese(t.loadedFilaments,d.nozzle_id).map(g=>r.jsxs("option",{value:g.globalTrayId,className:"bg-bambu-dark text-white",children:[g.label,": ",g.traySubBrands||g.type," (",g.colorName,")"]},g.globalTrayId))]}),m==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function V7e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:a=!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:g,targetLocation:w,onTargetLocationChange:b,slicedForModel:x}){const[S,k]=y.useState(!1),C=s?t:t.filter(le=>le.is_active),P=rf({queries:C.map(le=>({queryKey:["printerStatus",le.id],queryFn:()=>ae.getPrinterStatus(le.id),staleTime:5e3}))}),T=y.useMemo(()=>{const le=new Map;return C.forEach((pe,he)=>{const we=P[he];we?.data&&le.set(pe.id,we.data)}),le},[C,P]),A=le=>{const pe=T.get(le);return pe?pe.connected?!q7e.has(pe.state??""):!0:!1},F=le=>{const pe=T.get(le);if(!pe)return null;if(!pe.connected)return"Offline";const he=pe.state;return he?he==="RUNNING"?pe.stg_cur_name||"Printing":he==="PREPARE"?"Preparing":he==="PAUSE"?"Paused":he==="IDLE"?"Idle":he==="FINISH"?"Finished":he==="FAILED"?"Failed":he:null},_=y.useMemo(()=>{if(m!=="printer"||!x||S)return C;const le=C.filter(pe=>pe.model===x);return le.length>0?le:C},[C,m,x,S]),M=C.length-_.length,H=y.useMemo(()=>{const le=C.map(pe=>pe.model).filter(pe=>!!pe);return[...new Set(le)].sort()},[C]),I=y.useMemo(()=>{if(!f)return[];const le=C.filter(pe=>pe.model===f&&pe.location).map(pe=>pe.location).filter(pe=>!!pe);return[...new Set(le)].sort()},[C,f]),z=p&&g&&H.length>0,L=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(a)return r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(_.length===0)return r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[r.jsx(Ha,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const Z=le=>{o&&A(le)||(i?e.includes(le)?n(e.filter(pe=>pe!==le)):n([...e,le]):n([le]))},ne=()=>{const le=o?_.filter(pe=>!A(pe.id)):_;n(le.map(pe=>pe.id))},Y=()=>{n([])},ce=(le,pe,he)=>{he.stopPropagation(),!(!d||!u)&&(pe?d(le):u(le,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},ue=le=>e.includes(le),oe=e.length,Q=le=>l?.find(pe=>pe.printerId===le);return r.jsxs("div",{className:"space-y-2 mb-6",children:[z&&r.jsxs("div",{className:"flex gap-2 mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>{p("printer"),g(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:[r.jsx(hr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const le=x&&H.includes(x)?x:H[0];g(le)},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:[r.jsx(bm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&z&&r.jsxs("div",{className:"space-y-3 mb-4",children:[!x&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),r.jsxs("select",{value:f||"",onChange:le=>{g(le.target.value||null),b&&b(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:[r.jsx("option",{value:"",children:"Select a model..."}),H.map(le=>r.jsx("option",{value:le,children:le},le))]})]}),f&&I.length>0&&b&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),r.jsxs("select",{value:w||"",onChange:le=>b(le.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:[r.jsx("option",{value:"",children:"Any location"}),I.map(le=>r.jsx("option",{value:le,children:le},le))]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",w?` in ${w}`:""]})]}),m==="printer"&&i&&_.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:oe===0?"Select printers":`${oe} printer${oe!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[oe<_.length&&r.jsx("button",{type:"button",onClick:ne,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),oe>0&&r.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&_.map(le=>{const pe=ue(le.id),he=Q(le.id),we=he&&!he.config.useDefault,$=A(le.id),J=o&&$,j=F(le.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>Z(le.id),disabled:J,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${J?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":pe?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${le.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${J?"bg-bambu-dark-tertiary":pe?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(hr,{className:`w-5 h-5 ${J?"text-bambu-gray/50":pe?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${J?"text-bambu-gray":"text-white"}`,children:[le.name,!le.is_active&&r.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[le.model||"Unknown model"," • ",le.ip_address]})]}),j&&r.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:j}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${J?"border-bambu-gray/30":pe?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:pe&&r.jsx(Ar,{className:"w-3 h-3 text-white"})})]}),pe&&L&&he&&r.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:E=>E.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:we,onChange:E=>ce(le.id,E.target.checked,E),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"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),r.jsxs("span",{className:`text-xs ml-2 ${he.matchStatus==="full"?"text-bambu-green":he.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",he.exactMatches,"/",he.totalSlots," matched)"]}),he.isLoading&&r.jsx(tr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),we&&r.jsxs("button",{type:"button",onClick:E=>{E.stopPropagation(),d(le.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:[r.jsx(YZ,{className:"w-3 h-3"}),"Auto"]})]}),we&&r.jsx($7e,{printerResult:he,filamentReqs:c.filaments,onUpdateConfig:E=>u(le.id,E)})]})]},le.id)}),m==="printer"&&M>0&&!S&&r.jsxs("button",{type:"button",onClick:()=>k(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"}),M," other printer",M>1?"s":""," hidden (different model) —",r.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&S&&x&&r.jsx("button",{type:"button",onClick:()=>k(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:r.jsxs("span",{className:"underline",children:["Show only ",x," printers"]})}),m==="printer"&&oe===0&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const G7e=[{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 W7e({options:t,onChange:e,defaultExpanded:n=!1}){const[a,i]=y.useState(n),s=o=>{e({...t,[o]:!t[o]})};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>i(!a),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(xy,{className:"w-4 h-4"}),r.jsx("span",{children:"Print Options"}),a?r.jsx(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{className:"w-4 h-4 ml-auto"})]}),a&&r.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:G7e.map(({key:o,label:l,desc:c})=>r.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:l}),r.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),r.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:r.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 K7e({options:t,onChange:e,dateFormat:n="system",timeFormat:a="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState(!0),[w,b]=y.useState(!0),x=y.useRef(null),S=y.useRef(!1);y.useEffect(()=>{if(t.scheduleType!=="scheduled"){S.current=!1;return}if(!S.current){S.current=!0;let _;t.scheduledTime?(_=new Date(t.scheduledTime),isNaN(_.getTime())&&(_=new Date,_.setHours(_.getHours()+1,0,0,0))):(_=new Date,_.setHours(_.getHours()+1,0,0,0),e({...t,scheduledTime:eL(_)})),u(JF(_,n)),p(k6(_,a)),g(!0),b(!0)}},[t.scheduleType,t.scheduledTime,n,a,e,t]);const k=_=>{e({...t,scheduleType:_})},C=(_,M)=>{const H=Zve(_,n),I=Jve(M);g(!!H),b(!!I),H&&I&&(H.setHours(I.hours,I.minutes,0,0),H>new Date&&e({...t,scheduledTime:eL(H)}))},P=_=>{u(_),C(_,m)},T=_=>{p(_),C(d,_)},A=_=>{const M=_.target.value;if(M){const H=new Date(M);isNaN(H.getTime())||(u(JF(H,n)),p(k6(H,a)),g(!0),b(!0),e({...t,scheduledTime:M}))}},F=()=>{x.current?.showPicker()};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),r.jsxs("div",{className:"flex gap-2",children:[r.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:()=>k("asap"),children:[r.jsx(Zn,{className:"w-4 h-4"}),"ASAP"]}),r.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:()=>k("scheduled"),children:[r.jsx(wa,{className:"w-4 h-4"}),"Scheduled"]}),r.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:()=>k("manual"),children:[r.jsx(UZ,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"flex-1 relative",children:[r.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:_=>P(_.target.value),placeholder:Qve(n)}),r.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:r.jsx(wa,{className:"w-4 h-4"})}),r.jsx("input",{ref:x,type:"datetime-local",className:"absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none",value:t.scheduledTime,onChange:A,tabIndex:-1})]}),r.jsx("div",{className:"w-32",children:r.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${w?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:_=>T(_.target.value),placeholder:Yve(a)})})]}),(!f||!w)&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:_=>e({...t,requirePreviousSuccess:_.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:_=>e({...t,autoOffAfter:_.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),r.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[r.jsx(_u,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),l&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjection",checked:t.gcodeInjection,onChange:_=>e({...t,gcodeInjection:_.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"gcodeInjection",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(Ky,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),s&&t.scheduleType!=="manual"&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"staggerEnabled",checked:t.staggerEnabled,onChange:_=>e({...t,staggerEnabled:_.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"staggerEnabled",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(ca,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),t.staggerEnabled&&r.jsxs("div",{className:"ml-6 space-y-3",children:[r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerGroupSize","Group size")}),r.jsx("input",{type:"number",min:1,max:o,value:t.staggerGroupSize,onChange:_=>e({...t,staggerGroupSize:Math.max(1,parseInt(_.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"})]}),r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerInterval","Interval (min)")}),r.jsx("input",{type:"number",min:1,max:60,value:t.staggerIntervalMinutes,onChange:_=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(_.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 _=Math.ceil(o/t.staggerGroupSize),M=o%t.staggerGroupSize,H=(_-1)*t.staggerIntervalMinutes;return r.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:_,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),M!==0&&t.staggerGroupSize<o?` (${c("printModal.staggerLastGroup","last group: {{count}}",{count:M})})`:"",_>1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:H})})`:""]})})()]})]}),r.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 ed={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},h3={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function bc({mode:t,archiveId:e,libraryFileId:n,archiveName:a,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=_t(),m=tn(),{showToast:p}=on(),{hasPermission:f}=dr(),g=!!n&&!e,[w,b]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[x,S]=y.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),k=x.size===1?[...x][0]:null,[C,P]=y.useState(1),[T,A]=y.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??ed.bed_levelling,flow_cali:i.flow_cali??ed.flow_cali,vibration_cali:i.vibration_cali??ed.vibration_cali,layer_inspect:i.layer_inspect??ed.layer_inspect,timelapse:i.timelapse??ed.timelapse}:ed),[F,_]=y.useState(()=>{if(t==="edit-queue-item"&&i){let ut="asap";i.manual_start?ut="manual":i.scheduled_time&&!$K(i.scheduled_time)&&(ut="scheduled");let Ct="";if(i.scheduled_time&&!$K(i.scheduled_time)){const Le=Yn(i.scheduled_time)??new Date;Ct=eL(Le)}return{scheduleType:ut,scheduledTime:Ct,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:h3.staggerGroupSize,staggerIntervalMinutes:h3.staggerIntervalMinutes}}return h3}),[M,H]=y.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ut={};return i.ams_mapping.forEach((Ct,Le)=>{Ct!==-1&&(ut[Le+1]=Ct)}),ut}return{}}),[I,z]=y.useState({}),[L,Z]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ne,Y]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[ce,ue]=y.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[oe,Q]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]={type:Ct.type,color:Ct.color};return ut}return{}}),[le,pe]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]=Ct.force_color_match===!0;return ut}return{}}),[he]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[we]=y.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,J]=y.useState(!1),[j,E]=y.useState({current:0,total:0}),[B,W]=y.useState(null),[O,ie]=y.useState(new Set),U=w.length,G=w.length>0?w[0]:null,{data:K}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),X=y.useRef(!1);y.useEffect(()=>{!K||X.current||t==="edit-queue-item"||(X.current=!0,A({bed_levelling:K.default_bed_levelling??ed.bed_levelling,flow_cali:K.default_flow_cali??ed.flow_cali,vibration_cali:K.default_vibration_cali??ed.vibration_cali,layer_inspect:K.default_layer_inspect??ed.layer_inspect,timelapse:K.default_timelapse??ed.timelapse}))},[K,t]);const se=y.useRef(!1);y.useEffect(()=>{!K||se.current||t==="edit-queue-item"||(se.current=!0,_(ut=>({...ut,staggerGroupSize:K.stagger_group_size??ut.staggerGroupSize,staggerIntervalMinutes:K.stagger_interval_minutes??ut.staggerIntervalMinutes})))},[K,t]);const te=Ho(K?.currency||"USD"),fe=K?.default_filament_cost??0,{data:de,isLoading:me}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:q}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&L==="printer"||g&&t==="reprint"}),{data:R}=Xe({queryKey:["archive",e],queryFn:()=>ae.getArchive(e),enabled:!!e&&!g}),{data:re}=Xe({queryKey:["library-file",n],queryFn:()=>ae.getLibraryFile(n),enabled:g&&!!n}),be=R?.sliced_for_model||re?.sliced_for_model||null,{data:ye,isError:_e}=Xe({queryKey:["archive-plates",e],queryFn:()=>ae.getArchivePlates(e),enabled:!!e&&!g,retry:!1}),{data:xe}=Xe({queryKey:["library-file-plates",n],queryFn:()=>ae.getLibraryFilePlates(n),enabled:g&&!!n}),ge=g?xe:ye,{data:Me,isError:Be}=Xe({queryKey:["archive-filaments",e,k],queryFn:()=>ae.getArchiveFilamentRequirements(e,k??void 0),enabled:!!e&&!g&&(k!==null||!ge?.is_multi_plate),retry:!1}),{data:Fe}=Xe({queryKey:["library-file-filaments",n,k],queryFn:()=>ae.getLibraryFileFilamentRequirements(n,k??void 0),enabled:g&&!!n&&(k!==null||!ge?.is_multi_plate)}),Oe=!g&&(_e||Be),Re=g?Fe:Me,We=y.useMemo(()=>{if(!(k===null||!ge?.plates?.length))return ge.plates.find(ut=>ut.index===k)?.name||void 0},[ge,k]),{data:ze}=Xe({queryKey:["available-filaments",ne,ce],queryFn:()=>ae.getAvailableFilaments(ne,ce??void 0),enabled:L==="model"&&!!ne}),{data:st}=Xe({queryKey:["printer-status",G],queryFn:()=>ae.getPrinterStatus(G),enabled:!!G}),{amsMapping:Ee}=tse(Re,st,M,K?.prefer_lowest_filament),it=O7e(w,de,Re,M,I,z,K?.prefer_lowest_filament);y.useEffect(()=>{ge?.plates&&ge.plates.length>=1&&x.size===0&&S(new Set([ge.plates[0].index]))},[ge,x.size]),y.useEffect(()=>{if(t==="edit-queue-item")return;const ut=de?.filter(Ct=>Ct.is_active)||[];ut.length===1&&w.length===0&&b([ut[0].id])},[t,de,w.length]),y.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(w.sort())!==JSON.stringify(he.sort())||k!==we)&&(H({}),z({}),ie(new Set)):(H({}),z({}),ie(new Set))},[t,w,k,he,we]);const[Ce,Ze]=y.useState(ne),[Ie,ke]=y.useState(k);y.useEffect(()=>{(ne!==Ce||k!==Ie)&&(Ze(ne),ke(k),(t!=="edit-queue-item"||Ce!==null)&&(Q({}),pe({})))},[ne,k,Ce,Ie,t]),y.useEffect(()=>{if(!K?.per_printer_mapping_expanded||w.length<=1)return;const ut=w.filter(Ct=>{if(O.has(Ct))return!1;const Le=it.printerResults.find(Ae=>Ae.printerId===Ct);return Le&&Le.status&&!Le.isLoading});ut.length>0&&(ie(Ct=>{const Le=new Set(Ct);return ut.forEach(Ae=>Le.add(Ae)),Le}),ut.forEach(Ct=>{it.autoConfigurePrinter(Ct)}))},[K?.per_printer_mapping_expanded,w,O,it]),y.useEffect(()=>{const ut=Ct=>{Ct.key==="Escape"&&!$&&o()};return window.addEventListener("keydown",ut),()=>window.removeEventListener("keydown",ut)},[o,$]);const Ve=ge?.is_multi_plate??!1,rt=ge?.plates??[],Qe=y.useMemo(()=>{const ut=new Map;return q&&q.forEach(Ct=>{const Le=Ct.ams_id===255,Ae=Qg(Ct.ams_id,Ct.tray_id,Le),Ge=ut.get(Ct.printer_id)??new Map;Ge.set(Ae,Ct),ut.set(Ct.printer_id,Ge)}),ut},[q]),Te=y.useMemo(()=>{if(!B||B.length===0)return"";const ut=B.map(Ct=>u("printModal.insufficientFilamentLine",{printer:Ct.printerName,slot:Ct.slotLabel,required:Math.round(Ct.requiredGrams),remaining:Math.round(Ct.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),...ut].join(`
  8153. `)},[B,u]),tt=lt({mutationFn:ut=>ae.addToQueue(ut)}),ot=lt({mutationFn:ut=>ae.updateQueueItem(i.id,ut),onSuccess:()=>{m.invalidateQueries({queryKey:["queue"]}),p("Queue item updated"),l?.(),o()},onError:ut=>{p(ut.message||"Failed to update queue item","error")}}),Tt=F.staggerEnabled&&w.length>1,Ut=async(ut,Ct)=>{if(ut?.preventDefault(),!Ct?.skipFilamentCheck&&!K?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&L==="printer"){const Ye=[],nt=Re?.filaments??[];if(nt.length>0&&Qe.size>0){const at=(et,vt)=>!Number.isFinite(et)||et<=0||!Number.isFinite(vt)||vt<0?null:Math.max(0,et-vt);for(const et of w){const vt=w.length>1?it.getFinalMapping(et):Ee;if(!vt)continue;const wt=w.length>1?it.printerResults.find(qe=>qe.printerId===et)?.status:st,Ue=m_(wt),He=new Map(Ue.map(qe=>[qe.globalTrayId,qe.label])),Dt=Qe.get(et),Rt=de?.find(qe=>qe.id===et)?.name??`Printer ${et}`;Dt&&nt.forEach(qe=>{if(!qe.slot_id||qe.slot_id<=0)return;const Ke=vt[qe.slot_id-1];if(!Number.isFinite(Ke)||Ke<0)return;const Qt=Dt.get(Ke)?.spool;if(!Qt)return;const dn=at(Qt.label_weight,Qt.weight_used);dn!==null&&(dn>=qe.used_grams||Ye.push({printerName:Rt,slotLabel:He.get(Ke)??`Slot ${qe.slot_id}`,requiredGrams:qe.used_grams,remainingGrams:dn}))})}}if(Ye.length>0){W(Ye);return}}if(L==="printer"&&w.length===0){p("Please select at least one printer","error");return}if(L==="model"&&!ne){p("Please select a target printer model","error");return}J(!0);const Le=x.size>1?rt.filter(Ye=>x.has(Ye.index)):[null],Ae=L==="model"?Le.length:w.length*Le.length;E({current:0,total:Ae});const Ge={success:0,failed:0,errors:[]},Je=Ye=>{if(w.length>1){const nt=I[Ye];if(nt&&!nt.useDefault)return it.getFinalMapping(Ye)}return Ee},mt=(()=>{const Ye=[];if(Re?.filaments)for(const nt of Re.filaments){const at=oe[nt.slot_id],et=le[nt.slot_id]??!1,vt=at?.type??nt.type,wt=at?.color??nt.color;(at||et)&&Ye.push({slot_id:nt.slot_id,type:vt,color:wt,color_name:fc(wt),force_color_match:et})}else for(const[nt,{type:at,color:et}]of Object.entries(oe)){const vt=parseInt(nt,10),wt=le[vt]??!1;Ye.push({slot_id:vt,type:at,color:et,color_name:fc(et),force_color_match:wt})}return Ye.length>0?Ye:void 0})(),Ne=(Ye,nt)=>({printer_id:L==="printer"?Ye:null,target_model:L==="model"?ne:null,target_location:L==="model"?ce:null,filament_overrides:L==="model"?mt:void 0,archive_id:g?void 0:e,library_file_id:g?n:void 0,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:Ye?Je(Ye):void 0,plate_id:nt!==void 0?nt:k,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():void 0,...T,project_id:c??void 0});if(L==="model"){if(t==="reprint"){p("Model-based assignment only works with queue mode","error"),J(!1);return}let Ye=0;for(const nt of Le){Ye++,E({current:Ye,total:Ae});const at=nt?nt.index:k;try{if(t==="edit-queue-item"&&!nt){const et={printer_id:null,target_model:ne,target_location:ce,filament_overrides:mt||null,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:void 0,plate_id:at,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await ot.mutateAsync(et)}else{const et=Ne(null,at);Zt>1&&(et.quantity=Zt),await tt.mutateAsync(et)}Ge.success++}catch(et){Ge.failed++;const vt=nt?nt.name||`Plate ${nt.index}`:"";Ge.errors.push(vt?`${vt}: ${et.message}`:et.message)}}}else{const Ye=F.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&w.length>1,nt=Ye?F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).getTime():Date.now():0;let at=0;for(const et of Le){const vt=et?et.index:k;for(let wt=0;wt<w.length;wt++){const Ue=w[wt];at++,E({current:at,total:Ae});try{if(t==="reprint"&&!Ye){const He=Je(Ue);if(g?await ae.printLibraryFile(n,Ue,{plate_id:k??void 0,plate_name:We,ams_mapping:He,...T,project_id:c,cleanup_library_after_dispatch:d}):await ae.reprintArchive(e,Ue,{plate_id:k??void 0,plate_name:We,ams_mapping:He,...T}),Zt>1){const Dt=Ne(Ue,vt);Dt.quantity=Zt-1,await tt.mutateAsync(Dt)}}else if(t==="edit-queue-item"&&at===1){const He=Je(Ue),Dt={printer_id:Ue,target_model:null,target_location:null,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:He,plate_id:vt,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await ot.mutateAsync(Dt)}else{const He=Ne(Ue,vt);if(Zt>1&&(He.quantity=Zt),Ye){const Dt=Math.floor(wt/F.staggerGroupSize);if(Dt>0){const Rt=Dt*F.staggerIntervalMinutes*6e4;He.scheduled_time=new Date(nt+Rt).toISOString()}}await tt.mutateAsync(He)}Ge.success++}catch(He){Ge.failed++;const Dt=de?.find(Ke=>Ke.id===Ue)?.name||`Printer ${Ue}`,Rt=et?et.name||`Plate ${et.index}`:"",qe=Rt?`${Dt} (${Rt})`:Dt;Ge.errors.push(`${qe}: ${He.message}`)}}}}J(!1),Ge.failed===0?(t==="reprint"&&Tt?p(u("queue.itemsQueued",{count:Ge.success})):t!=="reprint"&&(t==="edit-queue-item"?p("Queue item updated"):Ge.success===1?p(L==="model"?`Queued for any ${ne}`:u("queue.printQueued")):p(u("queue.itemsQueued",{count:Ge.success}))),m.invalidateQueries({queryKey:["queue"]}),l?.(),o()):Ge.success===0?p(`Failed: ${Ge.errors[0]}`,"error"):(p(`${Ge.success} succeeded, ${Ge.failed} failed`,"error"),m.invalidateQueries({queryKey:["queue"]}))},bt=$||ot.isPending,Wt=y.useMemo(()=>!(bt||L==="printer"&&w.length===0||L==="model"&&!ne||L==="model"&&t==="reprint"||Ve&&x.size===0),[w.length,L,ne,t,Ve,x.size,bt]),Zt=L==="printer"&&w.length>1?1:C,cn=(()=>{const ut=w.length;if(t==="reprint"){const Ct=Tt&&ut>1;let Le=Ct?u("printModal.staggerToPrinters",{count:ut,defaultValue:"Stagger to {{count}} printers"}):ut>1?u("queue.printToPrinters",{count:ut}):u("queue.print");return Zt>1&&(Le=`${Le} ×${Zt}`),{title:u(g?"queue.print":"queue.reprint"),icon:hr,submitText:Le,submitIcon:Ct?wa:hr,loadingText:j.total>1?u("queue.sendingProgress",{current:j.current,total:j.total}):u("queue.sending")}}if(t==="add-to-queue"){let Ct=u("queue.addToQueue");return x.size>1?Ct=u("queue.queueSelectedPlates",{count:x.size}):ut>1&&(Ct=u("queue.queueToPrinters",{count:ut})),Zt>1&&(Ct=`${Ct} ×${Zt}`),{title:u("queue.schedulePrint"),icon:wa,submitText:Ct,submitIcon:wa,loadingText:j.total>1?u("queue.addingProgress",{current:j.current,total:j.total}):u("queue.adding")}}return{title:u("queue.editQueueItem"),icon:mi,submitText:u("common.save"),submitIcon:mi,loadingText:j.total>1?u("queue.savingProgress",{current:j.current,total:j.total}):u("common.saving")}})(),ct=cn.icon,kt=cn.submitIcon,Nt=G&&x.size<=1&&(g||(Ve?k!==null:!0));return r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:$?void 0:o,children:[r.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:ut=>ut.stopPropagation(),children:r.jsxs(Et,{className:t==="reprint"?"":"p-0",children:[r.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ct,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:cn.title})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:o,disabled:$,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:Ut,className:t==="reprint"?"":"p-4 space-y-4",children:[r.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?r.jsxs(r.Fragment,{children:["Send ",r.jsx("span",{className:"text-white",children:a})," to"," ",s?.length===1&&de?r.jsx("span",{className:"text-white",children:de.find(ut=>ut.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),r.jsx("span",{className:"text-white font-medium truncate block",children:a})]})}),r.jsx(H7e,{plates:rt,isMultiPlate:Ve,selectedPlates:x,onToggle:ut=>{S(Ct=>{const Le=new Set(Ct);return t==="add-to-queue"?Le.has(ut)?Le.delete(ut):Le.add(ut):(Le.clear(),Le.add(ut)),Le})},onSelectAll:t==="add-to-queue"?()=>S(new Set(rt.map(ut=>ut.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>S(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&r.jsx(V7e,{printers:de||[],selectedPrinterIds:w,onMultiSelect:b,isLoading:me,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:it.printerResults,filamentReqs:Re,onAutoConfigurePrinter:it.autoConfigurePrinter,onUpdatePrinterConfig:it.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":L,onAssignmentModeChange:t!=="reprint"?Z:void 0,targetModel:ne,onTargetModelChange:t!=="reprint"?Y:void 0,targetLocation:ce,onTargetLocationChange:t!=="reprint"?ue:void 0,slicedForModel:be}),L==="model"&&ne&&Re&&ze&&ze.length>0&&r.jsx(B7e,{filamentReqs:Re,availableFilaments:ze,overrides:oe,onChange:Q,forceColorMatch:le,onForceColorMatchChange:(ut,Ct)=>pe(Le=>({...Le,[ut]:Ct}))}),be&&L==="printer"&&w.length===1&&(()=>{const ut=de?.find(Ct=>Ct.id===w[0]);return ut&&ut.model&&be!==ut.model?r.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),r.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",be,", but printing on ",ut.model]})]}):null})(),Oe&&r.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:[r.jsx(Ha,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Nt&&!Oe&&w.length===1&&r.jsx(U7e,{printerId:G,filamentReqs:Re,manualMappings:M,onManualMappingChange:H,defaultExpanded:!!s?.length||(K?.per_printer_mapping_expanded??!1),currencySymbol:te,defaultCostPerKg:fe}),(t==="reprint"||U>0||L==="model"&&ne)&&r.jsx(W7e,{options:T,onChange:A,defaultExpanded:!!s?.length}),t!=="edit-queue-item"&&(L==="model"||w.length<=1)&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("label",{htmlFor:"printQuantity",className:"text-sm text-bambu-gray whitespace-nowrap",children:u("queue.quantity","Quantity")}),r.jsx("input",{id:"printQuantity",type:"number",min:1,max:999,value:C,onChange:ut=>P(Math.max(1,Math.min(999,parseInt(ut.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&&r.jsx("span",{className:"text-xs text-bambu-gray",children:u("queue.quantityHint","Creates {{count}} queue items",{count:C})})]}),t==="reprint"&&L==="printer"&&w.length>1&&r.jsxs("div",{className:"space-y-2 pb-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"staggerEnabledReprint",checked:F.staggerEnabled,onChange:ut=>_({...F,staggerEnabled:ut.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"staggerEnabledReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(ca,{className:"w-3.5 h-3.5"}),u("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),F.staggerEnabled&&(()=>{const ut=F.staggerGroupSize,Ct=F.staggerIntervalMinutes,Le=Math.ceil(w.length/ut),Ae=(Le-1)*Ct;return r.jsxs("p",{className:"ml-6 text-xs text-bambu-gray",children:[u("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:w.length,groups:Le,size:ut,interval:Ct}),Le>1?` (${u("printModal.staggerTotal","total: {{minutes}} min",{minutes:Ae})})`:""]})})()]}),t!=="reprint"&&r.jsx(K7e,{options:F,onChange:_,dateFormat:K?.date_format||"system",timeFormat:K?.time_format||"system",canControlPrinter:f("printers:control"),showStagger:t==="add-to-queue"&&L==="printer"&&w.length>1,printerCount:w.length,hasGcodeSnippets:!!K?.gcode_snippets}),t==="reprint"&&!!K?.gcode_snippets&&Zt>1&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:F.gcodeInjection,onChange:ut=>_({...F,gcodeInjection:ut.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"gcodeInjectionReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(Ky,{className:"w-3.5 h-3.5"}),u("printModal.gcodeInjection","Inject auto-print G-code")]})]}),ot.isError&&r.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ot.error?.message||"Failed to complete operation"}),r.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[r.jsx(je,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:$,children:"Cancel"}),r.jsx(je,{type:"submit",disabled:!Wt,className:"flex-1",children:bt?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),cn.loadingText]}):r.jsxs(r.Fragment,{children:[r.jsx(kt,{className:"w-4 h-4"}),cn.submitText]})})]})]})]})}),B&&B.length>0&&r.jsx(wn,{title:u("printModal.insufficientFilamentTitle"),message:Te,confirmText:u("printModal.printAnyway"),cancelText:u("common.cancel"),variant:"warning",onConfirm:()=>{W(null),Ut(void 0,{skipFilamentCheck:!0})},onCancel:()=>W(null)})]})}function WK({value:t}){const{t:e}=_t(),[n,a]=y.useState(!1),i=async()=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s);try{if(s.select(),!document.execCommand("copy"))return}finally{document.body.removeChild(s)}}a(!0),setTimeout(()=>a(!1),2e3)}catch{}};return r.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?r.jsx(Ar,{className:"w-3.5 h-3.5 text-bambu-green"}):r.jsx(Ti,{className:"w-3.5 h-3.5"})})}function Q7e({printer:t,status:e,totalPrintHours:n,onClose:a}){const{t:i}=_t();y.useEffect(()=>{const o=l=>{l.key==="Escape"&&a()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[a]);const s=[];if(s.push({label:i("printers.model"),value:t.model??"—"}),s.push({label:i("common.status"),value:r.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:[r.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:r.jsxs("span",{className:"flex items-center",children:[r.jsx("span",{className:"font-mono",children:t.ip_address}),r.jsx(WK,{value:t.ip_address})]})}),s.push({label:i("printers.serialNumber"),value:r.jsxs("span",{className:"flex items-center",children:[r.jsx("span",{className:"font-mono truncate",children:t.serial_number}),r.jsx(WK,{value:t.serial_number})]})}),e?.wired_network)s.push({label:i("printers.networkLabel","Network"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(xO,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-bambu-green",children:i("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=Ree(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(VZ,{className:`w-4 h-4 ${o.color}`}),r.jsx("span",{className:o.color,children:i(o.labelKey)}),r.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:r.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}),s.push({label:i("printers.autoArchive"),value:r.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:Dg(t.created_at)}),r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:a,children:r.jsx(At,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:r.jsxs(Et,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),r.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"flex justify-center mb-4",children:r.jsx("img",{src:Lee(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),r.jsx("div",{className:"space-y-0",children:s.map((o,l)=>r.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[r.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),r.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),a=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*a)/255>.6}function f3({trayColor:t,trayType:e,isEmpty:n,emptyKind:a,slotNumber:i}){const s=a==="reset"?"#3d3d3d":"#666";return r.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?s:"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:r.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&Y7e(t)?"#000":"#fff"},children:i})})}function m5({summary:t,children:e,defaultOpen:n=!1,className:a="",summaryClassName:i="",open:s,onToggle:o}){const[l,c]=y.useState(n),d=s!==void 0,u=d?s:l,m=()=>{const p=!u;d||c(p),o?.(p)};return r.jsxs("div",{className:a,children:[r.jsxs("div",{role:"button",tabIndex:0,onClick:m,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),m())},className:`w-full flex items-center justify-between gap-2 text-left cursor-pointer ${i}`,"aria-expanded":u,children:[r.jsx("div",{className:"flex-1 min-w-0",children:t}),r.jsx(Ln,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${u?"rotate-180":""}`})]}),u&&r.jsx("div",{className:"mt-3",children:e})]})}const KK=240,QK=320;function g3(t){return(t??.02).toFixed(3)}function YK({side:t}){const{mode:e}=ob(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return r.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 rse(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 ase(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function ise({slot:t,index:e,activeStatus:n,filamentName:a,children:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState("top"),u=y.useRef(null),m=y.useRef(null),p=y.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,g=t.stat===1;y.useEffect(()=>{if(o&&u.current&&m.current){const C=u.current.getBoundingClientRect(),P=m.current.offsetHeight,A=C.top-56,F=window.innerHeight-C.bottom;A<P+12&&F>A?d("bottom"):d("top")}},[o]);const w=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},b=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};y.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const x=jO(t.filament_color),S=rse(t.nozzle_type,s),k=ase(t.nozzle_type,s);return r.jsxs("div",{ref:u,className:"relative",onMouseEnter:w,onMouseLeave:b,children:[i,o&&r.jsxs("div",{ref:m,className:`
  8154. absolute left-1/2 -translate-x-1/2 z-50
  8155. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8156. animate-in fade-in-0 zoom-in-95 duration-150
  8157. `,style:{maxWidth:"calc(100vw - 24px)"},children:[r.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?r.jsxs("div",{className:"px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap",children:["Slot ",e+1," — Empty"]}):r.jsxs("div",{className:"p-2.5 space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleDiameter")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.nozzle_diameter," mm"]})]}),S&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleType")}),r.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[100px]",children:S})]}),k&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFlow")}),r.jsx("span",{className:"text-xs text-white font-semibold",children:k})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleStatus")}),r.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${n||g?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(n?"printers.nozzleActive":g?"printers.nozzleMounted":"printers.nozzleDocked")})]}),t.wear!=null&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleWear")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.wear,"%"]})]}),t.max_temp>0&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleMaxTemp")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.max_temp,"°C"]})]}),t.serial_number&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleSerial")}),r.jsx("span",{className:"text-[10px] text-white font-mono truncate max-w-[80px]",children:t.serial_number})]}),(x||t.filament_type)&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFilament")}),r.jsxs("div",{className:"flex items-center gap-1",children:[x&&r.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:x}}),r.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:a||t.filament_type||t.filament_id||""})]})]})]})}),r.jsx("div",{className:`
  8158. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8159. border-l-[6px] border-l-transparent
  8160. border-r-[6px] border-r-transparent
  8161. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8162. `})]})]})}function X7e({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:a,children:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState("top"),u=y.useRef(null),m=y.useRef(null),p=y.useRef(null);y.useEffect(()=>{if(o&&u.current&&m.current){const b=u.current.getBoundingClientRect(),x=m.current.offsetHeight,k=b.top-56,C=window.innerHeight-b.bottom;k<x+12&&C>k?d("bottom"):d("top")}},[o]);const f=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};if(y.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]),!t&&!e)return r.jsx(r.Fragment,{children:i});const w=(b,x)=>{const S=n===x,k=rse(b.nozzle_type,s),C=ase(b.nozzle_type,s),P=jO(b.filament_color),T=b.filament_id?a?.[b.filament_id]?.name:void 0;return r.jsxs("div",{className:"flex-1 space-y-1.5",children:[r.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${S?"text-amber-400":"text-bambu-gray"}`,children:s(x==="L"?"common.left":"common.right")}),b.nozzle_diameter&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.nozzle_diameter," mm"]})]}),k&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),r.jsx("span",{className:"text-[10px] text-white font-semibold",children:k})]}),C&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),r.jsx("span",{className:"text-[10px] text-white font-semibold",children:C})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),r.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${S?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(S?"printers.nozzleActive":"printers.nozzleIdle")})]}),b.wear!=null&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.wear,"%"]})]}),x==="R"&&b.max_temp>0&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),r.jsxs("span",{className:"text-xs text-white font-semibold",children:[b.max_temp,"°C"]})]}),x==="R"&&b.serial_number&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),r.jsx("span",{className:"text-[10px] text-white font-mono",children:b.serial_number})]}),(P||b.filament_type||b.filament_id)&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),r.jsxs("div",{className:"flex items-center gap-1",children:[P&&r.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:P}}),r.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:T||b.filament_type||b.filament_id||""})]})]})]})};return r.jsxs("div",{ref:u,className:"relative flex-1",onMouseEnter:f,onMouseLeave:g,children:[i,o&&r.jsxs("div",{ref:m,className:`
  8163. absolute left-1/2 -translate-x-1/2 z-50
  8164. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8165. animate-in fade-in-0 zoom-in-95 duration-150
  8166. `,style:{maxWidth:"calc(100vw - 24px)"},children:[r.jsx("div",{className:"w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:r.jsxs("div",{className:"p-2.5 flex gap-3",children:[t&&w(t,"L"),t&&e&&r.jsx("div",{className:"w-px bg-bambu-dark-tertiary/50"}),e&&w(e,"R")]})}),r.jsx("div",{className:`
  8167. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8168. border-l-[6px] border-l-transparent
  8169. border-r-[6px] border-r-transparent
  8170. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8171. `})]})]})}function Z7e({slots:t,filamentInfo:e}){const{t:n}=_t(),a=t.filter(l=>l.id>=2),i=6,s=16,o=Array.from({length:i},(l,c)=>a.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 r.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:[r.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),r.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const d=!l.nozzle_diameter&&!l.nozzle_type,u=d?null:jO(l.filament_color),m=u?rJ(l.filament_color):!1;return r.jsx(ise,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:r.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:r.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 XK({className:t}){return r.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:r.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 J7e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 e9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 t9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function n9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),r.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 r9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),r.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 a9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("rect",{x:"9.2",y:"3.4",width:"5.6",height:"8.1"}),r.jsx("rect",{x:"6",y:"11.5",width:"12.1",height:"3.7"}),r.jsx("path",{d:"M 7.3 15.2 L 12.1 19.6 L 16.7 15.2"})]})}function b3({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?r.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),r.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"})]}):r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function ZK({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:a,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=XK:s<=l?u=J7e:u=e9e,r.jsxs("button",{type:"button",onClick:a,className:`flex items-center gap-1 ${a?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${d}${a?" (click for history)":""}`,children:[r.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function JK({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:a,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=t9e):t<=o?(l="#d4a017",c="Fair",d=n9e):(l="#c62828",c="Bad",d=r9e),r.jsxs("button",{type:"button",onClick:a,className:`flex items-center gap-1 ${a?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${a?" (click for history)":""}`,children:[r.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function Bo(t,e){const n=typeof t=="string"?parseInt(t,10):t,a=isNaN(n)?0:n,i=e===1,s=a>=128?a-128:a,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function x3(t){return t?.tray_type?null:t?.state===9||t?.state===10?"physical":"reset"}function i9e({url:t,printName:e}){const{t:n}=_t(),[a,i]=y.useState(!1),[s,o]=y.useState(!1),[l,c]=y.useState(!1),d=y.useMemo(()=>{if(!t)return null;const u=t.includes("?")?"&":"?";return La(`${t}${u}v=${encodeURIComponent(e||Date.now().toString())}`)},[t,e]);return y.useEffect(()=>{i(!1),o(!1)},[d]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&a?"cursor-pointer":""}`,onClick:()=>d&&a&&c(!0),children:d&&!s?r.jsxs(r.Fragment,{children:[r.jsx("img",{src:d,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${a?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!a&&r.jsx(Si,{className:"w-8 h-8 text-bambu-gray"})]}):r.jsx(Si,{className:"w-8 h-8 text-bambu-gray"})}),l&&d&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:r.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[r.jsx("img",{src:d,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&r.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function s9e({printers:t}){const{t:e}=_t(),n=tn(),[a,i]=y.useState(0);y.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}=y.useMemo(()=>{let c=0,d=0,u=0,m=0,p=0,f=0,g=0,w=null,b=null,x=0;return t?.forEach(S=>{const k=n.getQueryData(["printerStatus",S.id]);if(k===void 0)f++;else if(!k.connected)p++;else{const C=k.hms_errors?Dm(k.hms_errors).length:0;switch(C>0&&g++,k.state){case"RUNNING":c++,k.remaining_time!=null&&k.remaining_time>0&&(b===null||k.remaining_time<b)&&(b=k.remaining_time,w=S.name,x=k.progress||0);break;case"PAUSE":d++;break;case"FINISH":u++;break;case"FAILED":C>0||u++;break;default:m++;break}}}),{counts:{printing:c,paused:d,finished:u,idle:m,offline:p,loading:f,error:g,total:t?.length||0},nextFinish:w&&b?{name:w,remainingMin:b,progress:x}:null}},[t,n,a]);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 r.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray",children:[l.map(({count:c,dot:d,label:u})=>c>0&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${d}`}),r.jsxs("span",{className:"text-bambu-gray",children:[r.jsx("span",{className:"text-white font-medium",children:c})," ",u]})]},u)),o&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),r.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),r.jsx("span",{className:"text-white font-medium",children:o.name})]}),r.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[r.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:r.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),r.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",cs(o.remainingMin*60),")"]})]})]})]})]})}function y3({value:t,options:e,onChange:n,fullWidth:a=!1}){const[i,s]=y.useState(!1),o=e.find(l=>l.value===t)??e[0];return r.jsxs("div",{className:`relative ${a?"w-full min-w-0":""}`,children:[r.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:`h-8 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white text-sm font-medium transition-colors hover:bg-bambu-dark-tertiary focus:outline-none focus:border-bambu-green flex items-center justify-between gap-2 ${a?"w-full":"min-w-28"}`,children:[r.jsx("span",{className:"truncate",children:o?.label}),r.jsx(Ln,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),r.jsx("div",{className:"absolute left-0 top-full z-20 mt-1 min-w-full rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary py-1 shadow-xl",children:e.map(l=>r.jsx("button",{type:"button",onClick:()=>{n(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${l.value===t?"text-bambu-green":"text-white"}`,children:l.label},l.value))})]})]})}function v3({label:t,icon:e,children:n}){const[a,i]=y.useState(!1);return r.jsxs("div",{className:"relative",children:[r.jsx("button",{type:"button",onClick:()=>i(s=>!s),className:"h-8 w-8 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center","aria-label":t,title:t,children:e}),a&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>i(!1)}),r.jsx("div",{className:"absolute right-0 top-full z-20 mt-1 min-w-40 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-2 shadow-xl",children:n})]})]})}const o9e=["error","printing","paused","finished","idle","offline"],eQ={error:{labelKey:"printers.status.problem",dot:"bg-status-error"},printing:{labelKey:"printers.status.printing",dot:"bg-bambu-green animate-pulse"},paused:{labelKey:"printers.status.paused",dot:"bg-status-warning"},finished:{labelKey:"printers.status.finished",dot:"bg-blue-400"},idle:{labelKey:"printers.status.idle",dot:"bg-bambu-green"},offline:{labelKey:"printers.status.offline",dot:"bg-gray-400"}};function tQ(t){if(!t?.connected)return"offline";if((t.hms_errors?Dm(t.hms_errors):[]).length>0)return"error";switch(t.state){case"RUNNING":return"printing";case"PAUSE":return"paused";case"FINISH":return"finished";case"FAILED":return"finished";default:return"idle"}}function w3(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 ow(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",N6:"X2D",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",X2D:"X2D",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 nQ({ams:t,printerId:e,label:n,amsLabels:a,canEdit:i,onSaved:s,children:o}){const{t:l}=_t(),[c,d]=y.useState(!1),[u,m]=y.useState("top"),[p,f]=y.useState(""),[g,w]=y.useState(!1),[b,x]=y.useState(null),[S,k]=y.useState(!1),C=y.useRef(null),P=y.useRef(null),T=y.useRef(null);y.useEffect(()=>{c&&(f(a?.[t.id]??""),x(null),requestAnimationFrame(()=>{if(C.current&&P.current){const H=C.current.getBoundingClientRect(),I=H.top-56,z=window.innerHeight-H.bottom;m(I<P.current.offsetHeight+12&&z>I?"bottom":"top")}}))},[c,a,t.id]);const A=()=>{T.current&&clearTimeout(T.current),T.current=setTimeout(()=>d(!0),80)},F=()=>{T.current&&clearTimeout(T.current),S||(T.current=setTimeout(()=>d(!1),200))};y.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const _=async()=>{if(i){w(!0),x(null);try{const H=p.trim();H?await ae.saveAmsLabel(e,t.id,H,t.serial_number):await ae.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(H){x(H instanceof Error?H.message:String(H))}finally{w(!1)}}},M=async()=>{if(i){w(!0),x(null);try{await ae.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(H){x(H instanceof Error?H.message:String(H))}finally{w(!1)}}};return r.jsxs("div",{ref:C,className:"relative inline-block",onMouseEnter:A,onMouseLeave:F,children:[o,c&&r.jsx("div",{ref:P,className:`
  8172. absolute left-0 z-50
  8173. ${u==="top"?"bottom-full mb-2":"top-full mt-2"}
  8174. animate-in fade-in-0 zoom-in-95 duration-150
  8175. `,style:{maxWidth:"calc(100vw - 24px)"},onMouseEnter:A,onMouseLeave:F,children:r.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:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:n}),r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.serialNumber")}),r.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.serial_number||"—"})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-[10px] tracking-wide text-bambu-gray font-medium shrink-0",children:l("printers.amsPopup.firmwareVersion")}),r.jsx("span",{className:"text-[10px] text-white font-mono truncate",children:t.sw_ver||"—"})]}),r.jsx("div",{className:"h-px bg-bambu-dark-tertiary/50"}),r.jsxs("div",{className:"space-y-1",children:[r.jsx("span",{className:"text-[10px] text-bambu-gray font-medium block",children:l("printers.amsPopup.friendlyName")}),r.jsx("input",{type:"text",value:p,onChange:H=>i&&f(H.target.value),onKeyDown:H=>H.key==="Enter"&&_(),onFocus:()=>k(!0),onBlur:()=>{k(!1),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>d(!1),200)},placeholder:i?l("printers.amsPopup.friendlyNamePlaceholder"):a?.[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&&r.jsxs("div",{className:"space-y-1",children:[b&&r.jsx("p",{className:"text-[10px] text-red-400 break-words",children:b}),r.jsxs("div",{className:"flex gap-1 justify-end",children:[r.jsx("button",{onClick:_,disabled:g,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")}),a?.[t.id]&&r.jsx("button",{onClick:M,disabled:g,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 cI={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 rQ({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:a="expanded",cardSize:i=2,amsThresholds:s,spoolmanEnabled:o=!1,linkedSpools:l,spoolmanUrl:c,spoolmanSyncMode:d,onGetAssignment:u,onUnassignSpool:m,spoolmanSpools:p,spoolmanSlotAssignments:f,spoolmanLoading:g=!1,onUnassignSpoolmanSpool:w,timeFormat:b="system",cameraViewMode:x="window",onOpenEmbeddedCamera:S,checkPrinterFirmware:k=!0,dryingPresets:C=cI,requirePlateClear:P=!1,selectionMode:T=!1,isSelected:A=!1,onToggleSelect:F}){const{t:_}=_t(),M=tn(),H=ji(),{showToast:I}=on(),{hasPermission:z}=dr(),[L,Z]=y.useState(!1),[ne,Y]=y.useState(!1),[ce,ue]=y.useState(!0),[oe,Q]=y.useState(!1),[le,pe]=y.useState(!1),[he,we]=y.useState(!1),[$,J]=y.useState(!1),[j,E]=y.useState(!1),[B,W]=y.useState(null),[O,ie]=y.useState(!1),[U,G]=y.useState(!1),[K,X]=y.useState(!1),[se,te]=y.useState(null),[fe,de]=y.useState(null),[me,q]=y.useState(null),[R,re]=y.useState(10),[be,ye]=y.useState(null),[_e,xe]=y.useState(!1),[ge,Me]=y.useState(!1),[Be,Fe]=y.useState(!1),[Oe,Re]=y.useState(!1),We=y.useCallback(()=>Re(!1),[]),[ze,st]=y.useState(null),[Ee,it]=y.useState(null),[Ce,Ze]=y.useState("n3f"),[Ie,ke]=y.useState("PLA"),[Ve,rt]=y.useState(50),[Qe,Te]=y.useState(4),[tt,ot]=y.useState(!1),[Tt,Ut]=y.useState(null),[bt,Wt]=y.useState(!1),[Zt,ln]=y.useState(!1),cn=y.useRef(0),[ct,kt]=y.useState(null),[Nt,ut]=y.useState(null),[Ct,Le]=y.useState(null),[Ae,Ge]=y.useState(null),[Je,De]=y.useState(!1),[mt,Ne]=y.useState(null),[Ye,nt]=y.useState(!1),[at,et]=y.useState(!1),[vt,wt]=y.useState(null),[Ue,He]=y.useState(!1),[Dt,Rt]=y.useState(!1),{data:qe}=Xe({queryKey:["printerStatus",t.id],queryFn:()=>ae.getPrinterStatus(t.id),refetchInterval:3e4}),{data:Ke}=Xe({queryKey:["firmwareUpdate",t.id],queryFn:()=>yN.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:k&&z("firmware:read")}),Bt=y.useMemo(()=>{const dt=new Set;if(qe?.ams)for(const qt of qe.ams)for(const Xt of qt.tray||[])Xt.tray_info_idx&&dt.add(Xt.tray_info_idx);for(const qt of qe?.vt_tray??[])qt.tray_info_idx&&dt.add(qt.tray_info_idx);if(qe?.nozzle_rack)for(const qt of qe.nozzle_rack)qt.filament_id&&dt.add(qt.filament_id);return Array.from(dt)},[qe?.ams,qe?.vt_tray,qe?.nozzle_rack]),Qt=y.useMemo(()=>{const dt=new Set;if(qe?.ams)for(const qt of qe.ams)for(const Xt of qt.tray||[])Xt.tray_type&&dt.add(Xt.tray_type.toUpperCase());for(const qt of qe?.vt_tray??[])qt.tray_type&&dt.add(qt.tray_type.toUpperCase());return dt},[qe?.ams,qe?.vt_tray]),dn=y.useMemo(()=>{const dt=new Set;if(qe?.ams){for(const qt of qe.ams)for(const Xt of qt.tray||[])if(Xt.tray_type&&Xt.tray_color){const ht=Xt.tray_color.replace("#","").toLowerCase().slice(0,6);dt.add(`${Xt.tray_type.toUpperCase()}:${ht}`)}}for(const qt of qe?.vt_tray??[])if(qt.tray_type&&qt.tray_color){const Xt=qt.tray_color.replace("#","").toLowerCase().slice(0,6);dt.add(`${qt.tray_type.toUpperCase()}:${Xt}`)}return dt},[qe?.ams,qe?.vt_tray]),{data:nn}=Xe({queryKey:["filamentInfo",Bt],queryFn:()=>ae.getFilamentInfo(Bt),enabled:Bt.length>0,staleTime:300*1e3}),{data:rn}=Xe({queryKey:["slotPresets",t.id],queryFn:()=>ae.getSlotPresets(t.id),staleTime:120*1e3}),yn=qe?.state==="RUNNING"||qe?.state==="PAUSE"?qe?.current_archive_id??null:null,{data:Mn}=Xe({queryKey:["archive-plates",yn],queryFn:()=>ae.getArchivePlates(yn),enabled:yn!=null,staleTime:300*1e3}),or=!Mn?.is_multi_plate||qe?.current_plate_id==null?null:Mn.plates.find(qt=>qt.index===qe.current_plate_id)?.name||_("printers.plateNumber","Plate {{number}}",{number:qe.current_plate_id}),{data:Dr,refetch:Gn}=Xe({queryKey:["amsLabels",t.id],queryFn:()=>ae.getAmsLabels(t.id),staleTime:300*1e3}),[pi,Un]=y.useState(null);y.useEffect(()=>{qe?.wifi_signal!=null&&Un(qe.wifi_signal)},[qe?.wifi_signal]);const vr=qe?.wifi_signal??pi,ua=y.useRef(void 0);y.useEffect(()=>{qe?.connected!==void 0&&(ua.current=qe.connected)},[qe?.connected]);const Fr=qe?.connected??ua.current,ba=y.useRef({});y.useEffect(()=>{qe?.ams_extruder_map&&Object.keys(qe.ams_extruder_map).length>0&&(ba.current=qe.ams_extruder_map)},[qe?.ams_extruder_map]);const Mi=qe?.ams_extruder_map&&Object.keys(qe.ams_extruder_map).length>0?qe.ams_extruder_map:ba.current,Ki=y.useRef([]);y.useEffect(()=>{qe?.ams&&qe.ams.length>0&&(Ki.current=qe.ams)},[qe?.ams]);const wd=qe?.ams&&qe.ams.length>0?qe.ams:Ki.current,Mc=y.useRef(void 0),zs=qe?.tray_now;zs!==void 0&&zs!==255?Mc.current=zs:zs===255&&(Mc.current=void 0);const It=zs!==void 0&&zs!==255?zs:Mc.current,{data:_n}=Xe({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>ae.getSmartPlugByPrinter(t.id)}),{data:ur}=Xe({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>ae.getScriptPlugsByPrinter(t.id)}),{data:Kt}=Xe({queryKey:["smartPlugStatus",_n?.id],queryFn:()=>_n?ae.getSmartPlugStatus(_n.id):null,enabled:!!_n,refetchInterval:1e4}),{data:Ec}=Xe({queryKey:["queue",t.id,"pending"],queryFn:()=>ae.getQueue(t.id,"pending")}),Dc=y.useMemo(()=>Ec?.length?Iee(Ec,Qt,dn).length:0,[Ec,Qt,dn]),{data:Fc}=Xe({queryKey:["queue",t.id,"printing"],queryFn:()=>ae.getQueue(t.id,"printing"),enabled:qe?.state==="RUNNING"}),{data:Ei}=Xe({queryKey:["currentPrintUser",t.id],queryFn:()=>ae.getCurrentPrintUser(t.id),enabled:qe?.state==="RUNNING"}),cp=Fc?.[0]?.created_by_username||Ei?.username,{data:Tu}=Xe({queryKey:["archives",t.id,"last"],queryFn:()=>ae.getArchives(t.id,1,0),enabled:qe?.connected&&qe?.state!=="RUNNING"}),kr=Tu?.[0],Sd=qe?.state==="RUNNING"||qe?.state==="PAUSE",jo=P&&qe?.awaiting_plate_clear===!0,Us=qe?.connected&&jo&&!Sd,Lc=!P||!qe?.connected?null:Sd?{label:_("printers.plateStatus.inUse"),className:"bg-blue-500/20 text-blue-400"}:qe.awaiting_plate_clear?{label:_("printers.plateStatus.notCleared"),className:"bg-yellow-500/20 text-yellow-400"}:{label:_("printers.plateStatus.cleared"),className:"bg-status-ok/20 text-status-ok"},Ma=Lc?r.jsx("span",{className:`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${Lc.className}`,children:Lc.label}):null,dp=e&&Fr===!1,up=lt({mutationFn:dt=>ae.deletePrinter(t.id,dt.deleteArchives),onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),M.invalidateQueries({queryKey:["archives"]}),M.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:dt=>I(dt.message||_("printers.toast.failedToDelete"),"error")}),hi=lt({mutationFn:()=>ae.connectPrinter(t.id),onSuccess:()=>{M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),nl=lt({mutationFn:()=>ae.refreshPrinterStatus(t.id),onSuccess:()=>{M.invalidateQueries({queryKey:["printerStatus",t.id]}),I(_("printers.forceRefreshSuccess"),"success")},onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),Rc=lt({mutationFn:dt=>ae.unlinkSpool(dt),onSuccess:dt=>{I(_("spoolman.unlinkSuccess")||dt?.message,"success"),M.invalidateQueries({queryKey:["linked-spools"]}),M.invalidateQueries({queryKey:["unlinked-spools"]}),M.invalidateQueries({queryKey:["spoolman-slot-assignments"]})},onError:dt=>{I(dt.message||_("spoolman.unlinkFailed"),"error")}}),mp=lt({mutationFn:({amsId:dt,temp:qt,duration:Xt,filament:ht,rotateTray:In})=>ae.startDrying(t.id,dt,qt,Xt,ht,In),onSuccess:()=>{it(null),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),Ea=lt({mutationFn:dt=>ae.stopDrying(t.id,dt),onSuccess:()=>{M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),Mo=lt({mutationFn:dt=>_n?ae.controlSmartPlug(_n.id,dt):Promise.reject("No plug"),onSuccess:()=>{M.invalidateQueries({queryKey:["smartPlugStatus",_n?.id]})}}),Eo=lt({mutationFn:dt=>_n?ae.updateSmartPlug(_n.id,{auto_off:dt}):Promise.reject("No plug"),onSuccess:()=>{M.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),M.invalidateQueries({queryKey:["smart-plugs"]})}}),Ic=lt({mutationFn:({id:dt,action:qt})=>ae.controlSmartPlug(dt,qt),onSuccess:()=>{I(_("printers.toast.scriptTriggered"))},onError:dt=>I(dt.message||_("printers.toast.failedToRunScript"),"error")}),_d=lt({mutationFn:()=>ae.stopPrint(t.id),onSuccess:()=>{I(_("printers.toast.printStopped")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToStopPrint"),"error")}),kd=lt({mutationFn:()=>ae.pausePrint(t.id),onSuccess:()=>{I(_("printers.toast.printPaused")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToPausePrint"),"error")}),lo=lt({mutationFn:()=>ae.resumePrint(t.id),onSuccess:()=>{I(_("printers.toast.printResumed")),M.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToResumePrint"),"error")}),Bs=lt({mutationFn:()=>ae.clearPlate(t.id),onSuccess:()=>{I(_("queue.clearPlateSuccess")),M.setQueryData(["printerStatus",t.id],dt=>dt&&{...dt,awaiting_plate_clear:!1}),M.invalidateQueries({queryKey:["printerStatus",t.id]}),M.invalidateQueries({queryKey:["queue",t.id]})},onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),Au=lt({mutationFn:dt=>ae.setChamberLight(t.id,dt),onMutate:async dt=>{await M.cancelQueries({queryKey:["printerStatus",t.id]});const qt=M.getQueryData(["printerStatus",t.id]);return M.setQueryData(["printerStatus",t.id],Xt=>({...Xt,chamber_light:dt})),{previousStatus:qt}},onSuccess:(dt,qt)=>{I(`Chamber light ${qt?"on":"off"}`)},onError:(dt,qt,Xt)=>{Xt?.previousStatus&&M.setQueryData(["printerStatus",t.id],Xt.previousStatus),I(dt.message||_("printers.toast.failedToControlChamberLight"),"error")}}),hb=lt({mutationFn:dt=>ae.setPrintSpeed(t.id,dt),onMutate:async dt=>{await M.cancelQueries({queryKey:["printerStatus",t.id]});const qt=M.getQueryData(["printerStatus",t.id]);return M.setQueryData(["printerStatus",t.id],Xt=>({...Xt,speed_level:dt})),{previousStatus:qt}},onError:(dt,qt,Xt)=>{Xt?.previousStatus&&M.setQueryData(["printerStatus",t.id],Xt.previousStatus),I(dt.message||_("printers.toast.failedToSetSpeed"),"error")}}),fb=lt({mutationFn:dt=>ae.setAirductMode(t.id,dt),onMutate:async dt=>{await M.cancelQueries({queryKey:["printerStatus",t.id]});const qt=M.getQueryData(["printerStatus",t.id]);return M.setQueryData(["printerStatus",t.id],Xt=>({...Xt,airduct_mode:dt==="cooling"?0:1})),{previousStatus:qt}},onError:(dt,qt,Xt)=>{Xt?.previousStatus&&M.setQueryData(["printerStatus",t.id],Xt.previousStatus),I(dt.message||_("printers.toast.failedToSendCommand"),"error")}}),gb=lt({mutationFn:({distance:dt,force:qt})=>ae.bedJog(t.id,dt,qt??!1),onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),gv=lt({mutationFn:dt=>ae.homeAxes(t.id,dt),onSuccess:()=>{try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}I(_("printers.bedJog.homingStarted"))},onError:dt=>I(dt.message||_("printers.toast.failedToSendCommand"),"error")}),Oc=lt({mutationFn:dt=>ae.updatePrinter(t.id,{plate_detection_enabled:dt}),onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),I(Oc.variables?_("printers.toast.plateCheckEnabled"):_("printers.toast.plateCheckDisabled"))},onError:dt=>I(dt.message||_("printers.toast.failedToUpdateSetting"),"error")}),pp=(qe?.state==="RUNNING"||qe?.state==="PAUSE")&&(qe?.printable_objects_count??0)>=2,{data:Ml}=Xe({queryKey:["printableObjects",t.id],queryFn:()=>ae.getPrintableObjects(t.id),enabled:ge||pp,refetchInterval:ge?5e3:pp?3e4:!1}),[El,zc]=y.useState(null),Uc=y.useRef(!1),Qi=y.useRef(null),Nd=y.useRef(!1),ju=lt({mutationFn:({amsId:dt,slotId:qt})=>ae.refreshAmsSlot(t.id,dt,qt),onMutate:({amsId:dt,slotId:qt})=>{Qi.current&&clearTimeout(Qi.current),Uc.current=!1,Nd.current=!1,zc({amsId:dt,slotId:qt}),setTimeout(()=>{Nd.current=!0},2e3),Qi.current=setTimeout(()=>{zc(null)},3e4)},onSuccess:dt=>{I(dt.message||_("printers.toast.rfidRereadInitiated"))},onError:dt=>{I(dt.message||_("printers.toast.failedToRereadRfid"),"error"),Qi.current&&clearTimeout(Qi.current),zc(null)}}),hp=lt({mutationFn:({trayId:dt})=>ae.loadAmsTray(t.id,dt),onSuccess:dt=>{I(dt.message||_("printers.toast.loadInitiated"))},onError:dt=>{I(dt.message||_("printers.toast.failedToLoad"),"error")}}),Cd=lt({mutationFn:()=>ae.unloadAms(t.id),onSuccess:dt=>{I(dt.message||_("printers.toast.unloadInitiated"))},onError:dt=>{I(dt.message||_("printers.toast.failedToUnload"),"error")}}),[co,Cn]=y.useState(null),[Pd,Td]=y.useState(null),Ad=async()=>{try{const dt=await ae.getPlateReferences(t.id);Cn(dt)}catch{}},ff=()=>{Oc.mutate(!t.plate_detection_enabled)},bb=async()=>{nt(!0),Ne(null);const dt=qe?.chamber_light===!1;Rt(dt),dt&&(await ae.setChamberLight(t.id,!0),await new Promise(qt=>setTimeout(qt,2500)));try{const qt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});Ne(qt),Ad()}catch(qt){I(qt instanceof Error?qt.message:_("printers.toast.failedToCheckPlate"),"error"),dt&&(await ae.setChamberLight(t.id,!1),Rt(!1))}finally{nt(!1)}},Dl=y.useCallback(async()=>{Ne(null),Dt&&(await ae.setChamberLight(t.id,!1),Rt(!1))},[Dt,t.id]),gf=async dt=>{et(!0);try{const qt=await ae.calibratePlateDetection(t.id,{label:dt});if(qt.success){I(qt.message||_("printers.toast.calibrationSaved"),"success"),Ad();const Xt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});Ne(Xt)}else I(qt.message||_("printers.toast.calibrationFailed"),"error")}catch(qt){I(qt instanceof Error?qt.message:_("printers.toast.calibrationFailed"),"error")}finally{et(!1)}},fp=async(dt,qt)=>{try{await ae.updatePlateReferenceLabel(t.id,dt,qt),Td(null),Ad()}catch(Xt){I(Xt instanceof Error?Xt.message:_("printers.toast.failedToUpdateLabel"),"error")}},xb=async dt=>{try{await ae.deletePlateReference(t.id,dt),I(_("printers.toast.referenceDeleted"),"success"),Ad();const qt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});Ne(qt)}catch(qt){I(qt instanceof Error?qt.message:_("printers.toast.failedToDeleteReference"),"error")}},bv=async()=>{if(vt){He(!0);try{await ae.updatePrinter(t.id,{plate_detection_roi:vt}),I(_("printers.toast.detectionAreaSaved"),"success"),wt(null);const dt=await ae.checkPlateEmpty(t.id,{includeDebugImage:!0});Ne(dt)}catch(dt){I(dt instanceof Error?dt.message:_("printers.toast.failedToSaveDetectionArea"),"error")}finally{He(!1)}}};y.useEffect(()=>{const dt=qt=>{qt.key==="Escape"&&mt&&Dl()};return window.addEventListener("keydown",dt),()=>window.removeEventListener("keydown",dt)},[mt,Dl]);const Bc=y.useRef(null);y.useEffect(()=>{if(!El)return;const dt=qe?.ams_status_main??0;return dt!==0&&(Uc.current=!0,Bc.current&&(clearTimeout(Bc.current),Bc.current=null)),Uc.current&&dt===0&&(Nd.current?(Qi.current&&clearTimeout(Qi.current),zc(null)):Bc.current||(Bc.current=setTimeout(()=>{Qi.current&&clearTimeout(Qi.current),zc(null)},2e3))),()=>{Bc.current&&clearTimeout(Bc.current)}},[qe?.ams_status_main,El]);const[ys,Yi]=y.useState(null);if(dp)return null;const Fl=()=>{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"}},bf=()=>{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"}},yb=()=>{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"}},ve=Fr&&qe?.state!=="RUNNING"&&qe?.state!=="PAUSE"&&z("printers:control"),zt=dt=>{dt.preventDefault(),cn.current++,cn.current===1&&Wt(!0)},mn=dt=>{dt.preventDefault(),dt.dataTransfer.dropEffect=ve?"copy":"none"},An=dt=>{dt.preventDefault(),cn.current--,cn.current===0&&Wt(!1)},zn=async dt=>{if(dt.preventDefault(),cn.current=0,Wt(!1),!ve)return;const Xt=Array.from(dt.dataTransfer.files)[0];if(!Xt)return;const ht=Xt.name.toLowerCase();if(!ht.endsWith(".gcode")&&!ht.includes(".gcode.")){I(_("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed"),"error");return}ln(!0);try{const In=await ae.uploadLibraryFile(Xt,null),Nr=In.metadata?.sliced_for_model,Hn=ow(t.model);if(Nr&&Hn&&Nr.toLowerCase()!==Hn.toLowerCase()){await ae.deleteLibraryFile(In.id).catch(()=>{}),I(_("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Nr,printerModel:Hn}),"error");return}st({id:In.id,filename:In.filename})}catch{I(_("common.uploadFailed","Upload failed"),"error")}finally{ln(!1)}};return r.jsxs(At,{className:`relative ${A?"ring-2 ring-bambu-green":""} ${T?"cursor-pointer":""}`,onDragEnter:zt,onDragOver:mn,onDragLeave:An,onDrop:zn,children:[T&&r.jsx("div",{className:"absolute inset-0 z-20 flex items-start p-2",onClick:dt=>{dt.stopPropagation(),F?.(t.id)},children:A?r.jsx(gs,{className:"w-5 h-5 text-bambu-green"}):r.jsx(ro,{className:"w-5 h-5 text-bambu-gray"})}),(bt||Zt)&&r.jsx("div",{className:`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${Zt?"bg-bambu-green/10 border-bambu-green/50":ve?"bg-bambu-green/10 border-bambu-green":"bg-red-500/10 border-red-500/50"}`,children:r.jsx("div",{className:"text-center",children:Zt?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin"}),r.jsx("p",{className:"text-sm font-medium text-bambu-green",children:_("common.uploading","Uploading...")})]}):ve?r.jsxs(r.Fragment,{children:[r.jsx(hr,{className:"w-8 h-8 mx-auto mb-2 text-bambu-green"}),r.jsx("p",{className:"text-sm font-medium text-bambu-green",children:_("printers.dropToPrint","Drop to print")})]}):r.jsxs(r.Fragment,{children:[r.jsx(Vt,{className:"w-8 h-8 mx-auto mb-2 text-red-400"}),r.jsx("p",{className:"text-sm font-medium text-red-400",children:_("printers.cannotPrint","Printer busy")})]})})}),r.jsxs(Et,{className:i>=3?"p-5":"",children:[r.jsxs("div",{className:yb(),children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[r.jsx("img",{src:Lee(t.model),alt:t.model||_("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${Fl()}`}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-semibold text-white ${bf()}`,children:t.name}),a==="compact"&&(()=>{const dt=qe?.connected&&qe.hms_errors?Dm(qe.hms_errors):[],qt=dt.some(Nr=>Nr.severity<=2),Xt=dt.length>0,ht=qe?.connected?qt?"bg-status-error":Xt?"bg-status-warning":"bg-status-ok":"bg-status-error",In=qe?.connected?Xt?`${dt.length} HMS ${dt.length===1?"error":"errors"}`:_("printers.connection.connected"):_("printers.connection.offline");return r.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${ht}`,title:In})})()]}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",a==="expanded"&&qe?.nozzles&&qe.nozzles[0]?.nozzle_diameter&&r.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:qe.nozzles[0].nozzle_type||"Nozzle",children:["• ",qe.nozzles[0].nozzle_diameter,"mm"]}),a==="expanded"&&n&&n.total_print_hours>0&&r.jsxs("span",{className:"ml-2 text-bambu-gray",children:[r.jsx(Zn,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),r.jsxs("div",{className:"relative flex-shrink-0",children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>Z(!L),children:r.jsx(vm,{className:"w-4 h-4"})}),L&&r.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:[r.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${z("printers:update")?"hover:bg-bambu-dark-tertiary":"opacity-50 cursor-not-allowed"}`,onClick:()=>{z("printers:update")&&(Q(!0),Z(!1))},title:z("printers:update")?void 0:_("printers.permission.noEdit"),children:[r.jsx(mi,{className:"w-4 h-4"}),_("common.edit")]}),r.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{Re(!0),Z(!1)},children:[r.jsx(_i,{className:"w-4 h-4"}),_("printers.printerInformation")]}),r.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{hi.mutate(),Z(!1)},children:[r.jsx(tr,{className:"w-4 h-4"}),_("printers.reconnect")]}),r.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:nl.isPending,onClick:()=>{nl.mutate(),Z(!1)},children:[r.jsx(Dw,{className:`w-4 h-4 ${nl.isPending?"animate-spin":""}`}),_("printers.forceRefresh")]}),r.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{we(!0),Z(!1)},children:[r.jsx(QZ,{className:"w-4 h-4"}),_("printers.mqttDebug")]}),r.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${z("printers:delete")?"text-red-400 hover:bg-bambu-dark-tertiary":"text-red-400/50 cursor-not-allowed"}`,onClick:()=>{z("printers:delete")&&(Y(!0),Z(!1))},title:z("printers:delete")?void 0:_("printers.permission.noDelete"),children:[r.jsx(en,{className:"w-4 h-4"}),_("common.delete")]})]})]})]}),a==="expanded"&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[r.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${qe?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[qe?.connected?r.jsx(Qy,{className:"w-3 h-3"}):r.jsx(ou,{className:"w-3 h-3"}),qe?.connected?_("printers.connection.connected"):_("printers.connection.offline")]}),qe?.connected&&qe?.wired_network&&r.jsxs("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok",title:_("printers.connection.ethernet","Ethernet"),children:[r.jsx(xO,{className:"w-3 h-3"}),_("printers.connection.ethernet","Ethernet")]}),qe?.connected&&!qe?.wired_network&&vr!=null&&r.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${vr>=-50||vr>=-60?"bg-status-ok/20 text-status-ok":vr>=-70?"bg-status-warning/20 text-status-warning":vr>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${vr} dBm - ${_(Ree(vr).labelKey)}`,children:[r.jsx(VZ,{className:"w-3 h-3"}),vr,"dBm"]}),qe?.connected&&(()=>{const dt=qe.hms_errors?Dm(qe.hms_errors):[];return r.jsxs("button",{onClick:()=>ie(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${dt.length>0?dt.some(qt=>qt.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:_("printers.clickToViewHmsErrors"),children:[r.jsx(Nn,{className:"w-3 h-3"}),dt.length>0?dt.length:"OK"]})})(),n&&r.jsxs("button",{onClick:()=>H("/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`:_("printers.maintenanceUpToDate"),children:[r.jsx(Gh,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),Dc>0&&r.jsxs("button",{onClick:()=>H("/queue"),className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-indigo-500/20 text-indigo-400 hover:opacity-80 transition-opacity",title:_("printers.queue.inQueue",{count:Dc}),children:[r.jsx(ca,{className:"w-3 h-3"}),Dc]}),k&&Ke?.current_version&&Ke?.latest_version?r.jsxs("button",{onClick:()=>De(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${Ke.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:Ke.update_available?_("printers.firmwareUpdateAvailable",{current:Ke.current_version,latest:Ke.latest_version}):_("printers.firmwareUpToDate",{version:Ke.current_version}),children:[Ke.update_available?r.jsx(Zr,{className:"w-3 h-3"}):r.jsx(xr,{className:"w-3 h-3"}),Ke.current_version]}):qe?.firmware_version?r.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:qe.firmware_version}):null,qe?.connected&&["X1C","X1","X1E","X2D","P1S","P1P","P2S","H2D","H2D Pro","H2C","H2S"].includes(t.model??"")&&r.jsx("span",{className:`flex items-center px-2 py-1 rounded-full text-xs ${qe.door_open?"bg-yellow-500/20 text-yellow-400":"bg-status-ok/20 text-status-ok"}`,title:qe.door_open?_("printers.door.open"):_("printers.door.closed"),children:qe.door_open?r.jsx(tbe,{className:"w-3 h-3"}):r.jsx(Jge,{className:"w-3 h-3"})})]})]}),ne&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(At,{className:"w-full max-w-md mx-4",children:r.jsxs(Et,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:r.jsx(Nn,{className:"w-5 h-5 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:_("printers.confirm.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:_("printers.confirm.deleteMessage",{name:t.name})})]})]}),r.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:r.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:ce,onChange:dt=>ue(dt.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"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:_("printers.deleteArchives")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:_(ce?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{variant:"secondary",onClick:()=>{Y(!1),ue(!0)},children:_("common.cancel")}),r.jsx(je,{variant:"danger",onClick:()=>{up.mutate({deleteArchives:ce}),Y(!1),ue(!0)},children:"Delete"})]})]})})}),qe?.connected&&r.jsxs(r.Fragment,{children:[a==="compact"?r.jsx("div",{className:"mt-2",children:qe.state==="RUNNING"||qe.state==="PAUSE"?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:r.jsx("div",{className:`${qe.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-1.5 rounded-full transition-all`,style:{width:`${qe.progress||0}%`}})}),r.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[r.jsxs("span",{className:"text-xs text-white",children:[Math.round(qe.progress||0),"%"]}),Ma]})]}):r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-1.5",children:[r.jsx("p",{className:"min-w-0 truncate text-xs text-bambu-gray",children:w3(qe.state,qe.stg_cur_name)}),Ma]}),Us&&r.jsx("button",{type:"button",onClick:()=>Bs.mutate(),disabled:Bs.isPending||!z("printers:clear_plate"),"aria-label":_("printers.plateStatus.markCleared"),className:"inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50",title:z("printers:clear_plate")?_("printers.plateStatus.markCleared"):_("printers.permission.noControl"),children:Bs.isPending?r.jsx(ft,{className:"w-3 h-3 animate-spin"}):r.jsx(BK,{className:"w-3 h-3"})})]})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[r.jsxs("button",{onClick:()=>Me(!0),disabled:!(qe.state==="RUNNING"||qe.state==="PAUSE")||(qe.printable_objects_count??0)<2||!z("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(qe.state==="RUNNING"||qe.state==="PAUSE")&&(qe.printable_objects_count??0)>=2&&z("printers:control")?"text-bambu-gray hover:text-white hover:bg-white/10":"text-bambu-gray/30 cursor-not-allowed"}`,title:z("printers:control")?qe.state==="RUNNING"||qe.state==="PAUSE"?(qe.printable_objects_count??0)>=2?_("printers.skipObjects.tooltip"):_("printers.skipObjects.requiresMultiple"):_("printers.skipObjects.onlyWhilePrinting"):_("printers.permission.noControl"),children:[r.jsx(UT,{className:"w-4 h-4"}),Ml&&Ml.skipped_count>0&&r.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:Ml.skipped_count})]}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(i9e,{url:qe.state==="RUNNING"||qe.state==="PAUSE"?qe.cover_url:null,printName:(qe.state==="RUNNING"||qe.state==="PAUSE")&&C6(qe.subtask_name||qe.current_print||null,qe.gcode_file,_,or)||void 0}),r.jsx("div",{className:"flex-1 min-w-0",children:qe.current_print&&(qe.state==="RUNNING"||qe.state==="PAUSE")?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:w3(qe.state,qe.stg_cur_name)}),Ma]}),r.jsx("p",{className:"text-white text-sm mb-2 truncate",children:C6(qe.subtask_name||qe.current_print||null,qe.gcode_file,_,or)}),r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:r.jsx("div",{className:`${qe.state==="PAUSE"?"bg-status-warning":"bg-bambu-green"} h-2 rounded-full transition-all`,style:{width:`${qe.progress||0}%`}})}),r.jsxs("span",{className:"text-white",children:[Math.round(qe.progress||0),"%"]})]}),r.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[qe.remaining_time!=null&&qe.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),cs(qe.remaining_time*60)]}),r.jsxs("span",{className:"text-bambu-green font-medium",title:_("printers.estimatedCompletion"),children:["ETA ",MO(qe.remaining_time,b,_)]})]}),qe.layer_num!=null&&qe.total_layers!=null&&qe.total_layers>0&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(ca,{className:"w-3 h-3"}),qe.layer_num,"/",qe.total_layers]}),cp&&r.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${cp}`,children:[r.jsx(Gm,{className:"w-3 h-3"}),cp]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:_("printers.sort.status")}),r.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[r.jsx("p",{className:"text-white text-sm",children:w3(qe.state,qe.stg_cur_name)}),Ma]}),r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:r.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),r.jsx("span",{className:"text-bambu-gray",children:"—"})]}),kr?r.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:kr.print_name||kr.filename,children:["Last: ",kr.print_name||kr.filename,kr.completed_at&&r.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",Dg(kr.completed_at,{month:"short",day:"numeric"})]})]}):r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:_("printers.readyToPrint")})]})})]})]}),r.jsx(y2e,{printerId:t.id,printerModel:t.model,loadedFilamentTypes:Qt,loadedFilaments:dn})]}),qe.temperatures&&a==="expanded"&&(()=>{const dt=qe.temperatures.nozzle_heating||qe.temperatures.nozzle_2_heating||!1,qt=qe.temperatures.bed_heating||!1,Xt=qe.temperatures.chamber_heating||!1,ht=t.nozzle_count===2||qe.temperatures.nozzle_2!==void 0,In=qe.active_extruder===1?"L":"R",Nr=qe.nozzle_rack?.find(ya=>ya.id===1),Hn=qe.nozzle_rack?.find(ya=>ya.id===0),xa=Hn||Nr;return r.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[r.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:[r.jsx(b3,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:dt}),qe.temperatures.nozzle_2!==void 0?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),r.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(qe.temperatures.nozzle||0),"° / ",Math.round(qe.temperatures.nozzle_2||0),"°"]})]}):xa?r.jsx(ise,{slot:xa,index:0,activeStatus:!0,filamentName:xa.filament_id?nn?.[xa.filament_id]?.name:void 0,children:r.jsxs("div",{className:"cursor-default",children:[r.jsx("p",{className:"text-[9px] text-bambu-gray",children:_("printers.temperatures.nozzle")}),r.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(qe.temperatures.nozzle||0),"°C"]})]})}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-[9px] text-bambu-gray",children:_("printers.temperatures.nozzle")}),r.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(qe.temperatures.nozzle||0),"°C"]})]})]}),r.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:[r.jsx(b3,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:qt}),r.jsx("p",{className:"text-[9px] text-bambu-gray",children:_("printers.temperatures.bed")}),r.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(qe.temperatures.bed||0),"°C"]})]}),qe.temperatures.chamber!==void 0&&r.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:[r.jsx(b3,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:Xt}),r.jsx("p",{className:"text-[9px] text-bambu-gray",children:_("printers.temperatures.chamber")}),r.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(qe.temperatures.chamber||0),"°C"]})]}),ht&&r.jsx(X7e,{leftSlot:Nr,rightSlot:Hn,activeNozzle:In,filamentInfo:nn,children:r.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:_("printers.activeNozzle",{nozzle:_(In==="L"?"common.left":"common.right")}),children:[r.jsx(a9e,{className:"w-3.5 h-3.5 mb-0.5 text-amber-400"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:`text-[11px] font-bold ${In==="L"?"text-amber-400":"text-gray-500"}`,children:["L",Nr?.nozzle_diameter?` ${Nr.nozzle_diameter}`:""]}),r.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),r.jsxs("span",{className:`text-[11px] font-bold ${In==="R"?"text-amber-400":"text-gray-500"}`,children:["R",Hn?.nozzle_diameter?` ${Hn.nozzle_diameter}`:""]})]}),r.jsx("p",{className:"text-[9px] text-bambu-gray",children:_("printers.temperatures.nozzle")})]})}),qe.nozzle_rack&&qe.nozzle_rack.some(ya=>ya.id>=2)&&r.jsx(Z7e,{slots:qe.nozzle_rack,filamentInfo:nn})]})})(),a==="expanded"&&Us&&r.jsxs("button",{type:"button",onClick:()=>Bs.mutate(),disabled:Bs.isPending||!z("printers:clear_plate"),className:"mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-1.5 rounded-lg bg-yellow-500/20 border border-yellow-400/40 text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs font-medium disabled:opacity-50",title:z("printers:clear_plate")?_("printers.plateStatus.markCleared"):_("printers.permission.noControl"),children:[Bs.isPending?r.jsx(ft,{className:"w-3 h-3 animate-spin"}):r.jsx(BK,{className:"w-4 h-4"}),_("printers.plateStatus.markCleared")]}),a==="expanded"&&(()=>{const dt=qe.state==="RUNNING",qt=qe.state==="PAUSE",Xt=dt||qt,ht=_d.isPending||kd.isPending||lo.isPending,In=qe.cooling_fan_speed,Nr=qe.big_fan1_speed,Hn=qe.big_fan2_speed;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:_("printers.controls")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-2 gap-y-2",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1.5 min-w-0",children:[r.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${In&&In>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:_("printers.fans.partCooling"),children:[r.jsx(IZ,{className:`w-3.5 h-3.5 ${In&&In>0?"text-cyan-400":"text-bambu-gray/50"}`}),r.jsxs("span",{className:`text-[10px] ${In&&In>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[In??0,"%"]})]}),r.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${Nr&&Nr>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:_("printers.fans.auxiliary"),children:[r.jsx(ZZ,{className:`w-3.5 h-3.5 ${Nr&&Nr>0?"text-blue-400":"text-bambu-gray/50"}`}),r.jsxs("span",{className:`text-[10px] ${Nr&&Nr>0?"text-blue-400":"text-bambu-gray/50"}`,children:[Nr??0,"%"]})]}),r.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${Hn&&Hn>0?"bg-green-500/10":"bg-bambu-dark"}`,title:_("printers.fans.chamber"),children:[r.jsx(wfe,{className:`w-3.5 h-3.5 ${Hn&&Hn>0?"text-green-400":"text-bambu-gray/50"}`}),r.jsxs("span",{className:`text-[10px] ${Hn&&Hn>0?"text-green-400":"text-bambu-gray/50"}`,children:[Hn??0,"%"]})]}),r.jsx("div",{className:"w-px h-5 bg-bambu-gray/30"}),["P2S","X2D","H2D","H2C","H2S"].includes(t.model??"")&&(()=>{const xa=qe.airduct_mode===1,ya=xa?pm:f6,an=xa?"text-orange-400":"text-sky-400",Tn=xa?"bg-orange-500/10 hover:bg-orange-500/20":"bg-sky-500/10 hover:bg-sky-500/20";return r.jsxs("div",{className:"relative",children:[r.jsxs("button",{onClick:()=>de(fe===t.id?null:t.id),disabled:!z("printers:control"),className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${Tn} disabled:opacity-50 disabled:cursor-not-allowed`,title:_("printers.airduct.title"),children:[r.jsx(ya,{className:`w-3.5 h-3.5 ${an}`}),r.jsx("span",{className:`text-[10px] ${an}`,children:_(xa?"printers.airduct.heating":"printers.airduct.cooling")})]}),fe===t.id&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>de(null)}),r.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:_("printers.airduct.cooling"),modeId:0},{mode:"heating",label:_("printers.airduct.heating"),modeId:1}].map(({mode:ka,label:Ka,modeId:Di})=>r.jsxs("button",{onClick:()=>{fb.mutate(ka),de(null)},className:`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${qe.airduct_mode===Di?"text-bambu-green bg-bambu-green/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[ka==="heating"?r.jsx(pm,{className:"w-3 h-3"}):r.jsx(f6,{className:"w-3 h-3"}),Ka]},ka))})]})]})})(),(()=>{const ya={1:"50%",2:"100%",3:"124%",4:"166%"}[qe.speed_level]||"100%";return r.jsxs("div",{className:"relative",children:[r.jsxs("button",{onClick:()=>te(se===t.id?null:t.id),disabled:!Xt||!z("printers:control"),className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${Xt?"bg-amber-500/10 hover:bg-amber-500/20":"bg-bambu-dark cursor-not-allowed"}`,title:Xt?_("printers.speed.title"):void 0,children:[r.jsx(TS,{className:`w-3.5 h-3.5 ${Xt?"text-amber-400":"text-bambu-gray/50"}`}),r.jsx("span",{className:`text-[10px] ${Xt?"text-amber-400":"text-bambu-gray/50"}`,children:ya})]}),se===t.id&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>te(null)}),r.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:_("printers.speed.silent")},{mode:2,label:_("printers.speed.standard")},{mode:3,label:_("printers.speed.sport")},{mode:4,label:_("printers.speed.ludicrous")}].map(({mode:an,label:Tn})=>r.jsx("button",{onClick:()=>{hb.mutate(an),te(null)},className:`w-full text-left px-3 py-1.5 text-xs transition-colors ${qe.speed_level===an?"text-bambu-green bg-bambu-green/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:Tn},an))})]})]})})(),r.jsx("div",{className:"w-px h-5 bg-bambu-gray/30"}),(()=>{const xa=z("printers:control"),ya=Xt||!xa,an=Tn=>{const ka=Tn*R*1,Ka=`bambuddy.bedJog.warned.${t.id}`,Di=(()=>{try{return sessionStorage.getItem(Ka)==="1"}catch{return!1}})();q(null),Di?gb.mutate({distance:ka,force:!0}):ye({distance:ka})};return r.jsxs("div",{className:"relative",children:[r.jsxs("button",{onClick:()=>q(me===t.id?null:t.id),disabled:ya,className:`flex items-center gap-1 px-1.5 py-1 rounded transition-colors ${ya?"bg-bambu-dark cursor-not-allowed":"bg-indigo-500/10 hover:bg-indigo-500/20"}`,title:_(xa?Xt?"printers.bedJog.disabledWhilePrinting":"printers.bedJog.title":"printers.permission.noControl"),children:[r.jsx($xe,{className:`w-3.5 h-3.5 ${ya?"text-bambu-gray/50":"text-indigo-400"}`}),r.jsx("span",{className:`text-[10px] ${ya?"text-bambu-gray/50":"text-indigo-400"}`,children:_("printers.bedJog.bed")}),r.jsxs("span",{className:`text-[10px] tabular-nums opacity-70 ${ya?"text-bambu-gray/50":"text-indigo-400"}`,children:[R,"mm"]})]}),me===t.id&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>q(null)}),r.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg p-2 min-w-[140px]",children:[r.jsxs("div",{className:"flex items-center justify-between gap-1 mb-2",children:[r.jsx("button",{onClick:()=>an(-1),className:"flex-1 flex items-center justify-center py-1.5 rounded bg-indigo-500/15 hover:bg-indigo-500/30 text-indigo-300","aria-label":_("printers.bedJog.up"),children:r.jsx(qm,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>an(1),className:"flex-1 flex items-center justify-center py-1.5 rounded bg-indigo-500/15 hover:bg-indigo-500/30 text-indigo-300","aria-label":_("printers.bedJog.down"),children:r.jsx(qh,{className:"w-4 h-4"})})]}),r.jsx("div",{className:"text-[9px] uppercase tracking-wider text-bambu-gray/70 px-1 mb-1",children:_("printers.bedJog.step")}),r.jsx("div",{className:"flex gap-1",children:[1,10,50].map(Tn=>r.jsx("button",{onClick:()=>re(Tn),className:`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${R===Tn?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:Tn},Tn))})]})]})]})})()]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 max-[550px]:self-start",children:[r.jsxs("button",{onClick:()=>G(!0),disabled:!Xt||ht||!z("printers:control"),className:`
  8176. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  8177. transition-colors
  8178. ${Xt&&z("printers:control")?"bg-red-500/20 text-red-400 hover:bg-red-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}
  8179. `,title:z("printers:control")?_("printers.stop"):_("printers.permission.noControl"),children:[r.jsx(ro,{className:"w-3 h-3"}),_("printers.stop")]}),r.jsxs("button",{onClick:()=>qt?xe(!0):X(!0),disabled:!Xt||ht||!z("printers:control"),className:`
  8180. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  8181. transition-colors
  8182. ${Xt&&z("printers:control")?qt?"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"}
  8183. `,title:z("printers:control")?_(qt?"printers.resume":"printers.pause"):_("printers.permission.noControl"),children:[qt?r.jsx(hs,{className:"w-3 h-3"}):r.jsx(DS,{className:"w-3 h-3"}),_(qt?"printers.resume":"printers.pause")]})]})]})]})})(),(wd?.length>0||qe.vt_tray.length>0)&&a==="expanded"&&(()=>{const dt=wd.filter(ht=>ht.tray.length>1),qt=wd.filter(ht=>ht.tray.length===1),Xt=t.nozzle_count===2||qe?.temperatures?.nozzle_2!==void 0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:_("printers.filaments")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"space-y-3",children:[dt.length>0&&r.jsx("div",{className:"grid grid-cols-2 gap-3",children:dt.map(ht=>{const In=Mi[String(ht.id)],Nr=ht.id>=128?ht.id-128:ht.id,Hn=In!==void 0?In:Nr,xa=Hn===1,ya=Hn===0;return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(nQ,{ams:ht,printerId:t.id,label:Bo(ht.id,ht.tray.length),amsLabels:Dr,canEdit:z("printers:update"),onSaved:Gn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Dr?.[ht.id]||Bo(ht.id,ht.tray.length)})}),Xt&&(xa||ya)&&r.jsx(YK,{side:xa?"L":"R"})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ht.humidity!=null&&r.jsx(ZK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>kt({amsId:ht.id,amsLabel:Bo(ht.id,ht.tray.length),mode:"humidity"}),compact:!0}),ht.temp!=null&&r.jsx(JK,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>kt({amsId:ht.id,amsLabel:Bo(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&z("printers:control")&&r.jsx("button",{disabled:!!(ht.dry_sf_reason?.length&&ht.dry_time===0),onClick:an=>{if(ht.dry_time>0)Ea.mutate(ht.id);else if(Ee===ht.id)it(null);else{const ka=(ht.tray.find(Rl=>Rl.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Ka=C[ka]||C.PLA,Di=ht.module_type;ke(ka),rt(Ka[Di]||Ka.n3f),Te(Di==="n3s"?Ka.n3s_hours:Ka.n3f_hours),ot(!1),Ze(ht.module_type),it(ht.id);const Ll=an.currentTarget.getBoundingClientRect();Ut(P6({triggerRect:Ll,popoverWidth:KK,estimatedHeight:QK}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.dry_time>0?"bg-amber-500/20 text-amber-400":ht.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:ht.dry_time>0?_("printers.drying.stop"):ht.dry_sf_reason?.length?_("printers.drying.powerRequired"):_("printers.drying.start"),children:r.jsx(pm,{className:"w-3 h-3"})})]})]}),ht.dry_time>0&&r.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:[r.jsx(pm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-400 font-medium",children:_("printers.drying.active")}),r.jsx("span",{className:"text-amber-300/70",children:_("printers.drying.timeRemaining",{time:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`})}),r.jsx("button",{onClick:()=>Ea.mutate(ht.id),disabled:Ea.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:_("printers.drying.stop"),children:r.jsx(Vt,{className:"w-3 h-3"})})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(an=>{const Tn=ht.tray[an]||ht.tray.find(pn=>pn.id===an),ka=Tn?.tray_type&&Tn.remain>=0,Ka=!Tn?.tray_type,Di=x3(Tn),Ll=ht.id*4+an,Rl=It===Ll,Mu=Tn?.tray_info_idx?nn?.[Tn.tray_info_idx]:null,Wr=rn?.[Ll],Qa=(Tn?.tray_uuid||Tn?.tag_uid||gm(t.serial_number,ht.id,an))?.toUpperCase(),Il=Qa?l?.[Qa]:void 0,rl=LN(Il),Na=o&&!g?f?.find(pn=>pn.printer_id===t.id&&pn.ams_id===ht.id&&pn.tray_id===an):void 0,Br=Na?p?.find(pn=>pn.id===Na.spoolman_spool_id):void 0,Do=Br&&(Br.label_weight??0)>0?Math.round(Math.max(0,(Br.label_weight??0)-Br.weight_used)/(Br.label_weight??1)*100):null,uo=u?.(t.id,ht.id,an),Fi=(()=>{const pn=uo?.spool;return pn&&pn.label_weight>0&&pn.weight_used!=null?Math.round(Math.max(0,pn.label_weight-pn.weight_used)/pn.label_weight*100):null})(),Hc=Fi===0&&ka&&Tn.remain>0?null:Fi,Xi=rl??Do??Hc??(ka?Tn.remain:null),wr=rl!==null||Do!==null?"spoolman":Hc!==null?"inventory":ka?"ams":void 0,Mr=Tn?.tray_type?{vendor:Ks(Tn)?"Bambu Lab":"Generic",profile:Wr?.preset_name||(Br?[Br.brand,Br.slicer_filament_name?.split("@")[0].trim()||Br.material].filter(Boolean).join(" ").trim():null)||uo?.spool?.slicer_filament_name||Mu?.name||Tn.tray_sub_brands||Tn.tray_type,colorName:fc(Tn.tray_color||""),colorHex:Tn.tray_color||null,kFactor:g3(Tn.k),fillLevel:Xi,trayUuid:Tn.tray_uuid||null,tagUid:Tn.tag_uid||null,fillSource:wr}:null,Ya=El?.amsId===ht.id&&El?.slotId===an,qc=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ka?"opacity-50":""} ${Rl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(f3,{trayColor:Tn?.tray_color,trayType:Tn?.tray_type,isEmpty:Ka,emptyKind:Di,slotNumber:an+1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Tn?.tray_type||_("ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Xi!==null&&Xi>=0&&!Ka&&Tn&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Xi}%`,backgroundColor:my(Xi)}})})]});return r.jsxs("div",{className:"relative group",children:[Ya&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:pn=>{pn.stopPropagation(),Yi(ys?.amsId===ht.id&&ys?.slotId===an?null:{amsId:ht.id,slotId:an})},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:_("printers.slotOptions"),children:r.jsx(vm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&ys?.amsId===ht.id&&ys?.slotId===an&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:ams_rfid")&&(ju.mutate({amsId:ht.id,slotId:an}),Yi(null))},disabled:Ya||!z("printers:ams_rfid"),title:z("printers:ams_rfid")?void 0:_("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Ya?"animate-spin":""}`}),_("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:control")&&(hp.mutate({trayId:ht.id*4+an}),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(Z0,{className:"w-3 h-3"}),_("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:control")&&(Cd.mutate(),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(ty,{className:"w-3 h-3"}),_("printers.ams.unload")]})]}),Mr?r.jsx(d3,{data:Mr,spoolman:{enabled:o,linkedSpoolId:Na?.spoolman_spool_id??(Qa?l?.[Qa]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Na&&!uo?()=>{const pn=(Mr.trayUuid||Mr.tagUid||gm(t.serial_number,ht.id,an)).toUpperCase();ut({tagUid:Mr.tagUid||pn,trayUuid:Mr.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:an})}:void 0,onUnlinkSpool:Il?.id?()=>Rc.mutate(Il.id):void 0},inventory:(()=>{if(o){if(g)return;const xf=Na,Lr=Br;return{assignedSpool:Lr?{id:Lr.id,material:Lr.material,brand:Lr.brand??null,color_name:Lr.color_name??null,remainingWeightGrams:Lr.label_weight?Math.max(0,Math.round(Lr.label_weight-Lr.weight_used)):void 0}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:an,trayInfo:{type:Tn?.tray_type||Mr.profile,material:Tn?.tray_type??void 0,profile:Mr.profile,color:Mr.colorHex||"",location:`${Bo(ht.id,ht.tray.length)} Slot ${an+1}`}}),onUnassignSpool:Lr&&!Ks(Tn)?()=>w?.(Lr.id):void 0,isAssigned:!!xf||Ks(Tn)}}const pn=u?.(t.id,ht.id,an);return{assignedSpool:pn?.spool?{id:pn.spool.id,material:pn.spool.material,brand:pn.spool.brand,color_name:pn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(pn.spool.label_weight-pn.spool.weight_used))}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:an,trayInfo:{type:Tn?.tray_type||Mr.profile,material:Tn?.tray_type??void 0,profile:Mr.profile,color:Mr.colorHex||"",location:`${Bo(ht.id,ht.tray.length)} Slot ${an+1}`}}),onUnassignSpool:pn&&!Ks(Tn)?()=>m?.(t.id,ht.id,an):void 0,isAssigned:!!pn||Ks(Tn)}})(),configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:ht.id,trayId:an,trayCount:ht.tray.length,trayType:Tn?.tray_type||void 0,trayColor:Tn?.tray_color||void 0,traySubBrands:Tn?.tray_sub_brands||void 0,trayInfoIdx:Tn?.tray_info_idx||void 0,extruderId:In,caliIdx:Tn?.cali_idx,savedPresetId:Wr?.preset_id})},children:qc}):r.jsx(u3,{kind:Di??void 0,configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:ht.id,trayId:an,trayCount:ht.tray.length,extruderId:In})},onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:an,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`${Bo(ht.id,ht.tray.length)} Slot ${an+1}`}}),children:qc})]},an)})})]},ht.id)})}),(qt.length>0||qe.vt_tray.length>0)&&r.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[qt.map(ht=>{const In=Mi[String(ht.id)],Nr=ht.id>=128?ht.id-128:ht.id,Hn=In!==void 0?In:Nr,xa=Hn===1,ya=Hn===0,an=ht.tray[0],Tn=an?.tray_type&&an.remain>=0,ka=!an?.tray_type,Ka=x3(an),Di=Qg(ht.id,an?.id??0,!1),Ll=It===Di,Rl=an?.tray_info_idx?nn?.[an.tray_info_idx]:null,Mu=rn?.[Di],Wr=an?.id??0,Qa=(an?.tray_uuid||an?.tag_uid||gm(t.serial_number,ht.id,Wr))?.toUpperCase(),Il=Qa?l?.[Qa]:void 0,rl=LN(Il),Na=u?.(t.id,ht.id,Wr),Br=(()=>{const pn=Na?.spool;return pn&&pn.label_weight>0&&pn.weight_used!=null?Math.round(Math.max(0,pn.label_weight-pn.weight_used)/pn.label_weight*100):null})(),Do=Br===0&&Tn&&an.remain>0?null:Br,uo=o&&!g?f?.find(pn=>pn.printer_id===t.id&&pn.ams_id===ht.id&&pn.tray_id===Wr):void 0,Fi=uo?p?.find(pn=>pn.id===uo.spoolman_spool_id):void 0,Hc=Fi&&(Fi.label_weight??0)>0?Math.round(Math.max(0,(Fi.label_weight??0)-Fi.weight_used)/(Fi.label_weight??1)*100):null,Xi=rl??Hc??Do??(Tn?an.remain:null),wr=rl!==null||Hc!==null?"spoolman":Do!==null?"inventory":Tn?"ams":void 0,Mr=an?.tray_type?{vendor:Ks(an)?"Bambu Lab":"Generic",profile:Mu?.preset_name||(Fi?[Fi.brand,Fi.slicer_filament_name?.split("@")[0].trim()||Fi.material].filter(Boolean).join(" ").trim():null)||Na?.spool?.slicer_filament_name||Rl?.name||an.tray_sub_brands||an.tray_type,colorName:fc(an.tray_color||""),colorHex:an.tray_color||null,kFactor:g3(an.k),fillLevel:Xi,trayUuid:an.tray_uuid||null,tagUid:an.tag_uid||null,fillSource:wr}:null,Ya=El?.amsId===ht.id&&El?.slotId===Wr,qc=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${ka?"opacity-50":""} ${Ll?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(f3,{trayColor:an?.tray_color,trayType:an?.tray_type,isEmpty:ka,emptyKind:Ka,slotNumber:1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:an?.tray_type||_("ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Xi!==null&&Xi>=0&&!ka&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Xi}%`,backgroundColor:my(Xi)}})})]});return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[r.jsx(nQ,{ams:ht,printerId:t.id,label:Bo(ht.id,ht.tray.length),amsLabels:Dr,canEdit:z("printers:update"),onSaved:Gn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Dr?.[ht.id]||Bo(ht.id,ht.tray.length)})}),Xt&&(xa||ya)&&r.jsx(YK,{side:xa?"L":"R"}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&z("printers:control")&&r.jsx("div",{className:"relative ml-auto",children:r.jsx("button",{onClick:pn=>{if(ht.dry_time>0)Ea.mutate(ht.id);else if(Ee===ht.id)it(null);else{const Lr=(ht.tray.find(Eu=>Eu.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),$c=C[Lr]||C.PLA,vb=ht.module_type;ke(Lr),rt($c[vb]||$c.n3f),Te(vb==="n3s"?$c.n3s_hours:$c.n3f_hours),ot(!1),Ze(ht.module_type),it(ht.id);const v_=pn.currentTarget.getBoundingClientRect();Ut(P6({triggerRect:v_,popoverWidth:KK,estimatedHeight:QK}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.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:ht.dry_time>0?_("printers.drying.stop"):_("printers.drying.start"),children:r.jsx(pm,{className:"w-3 h-3"})})})]}),ht.dry_time>0&&r.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:[r.jsx(pm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`}),r.jsx("button",{onClick:()=>Ea.mutate(ht.id),disabled:Ea.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:_("printers.drying.stop"),children:r.jsx(Vt,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[r.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Ya&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:pn=>{pn.stopPropagation(),Yi(ys?.amsId===ht.id&&ys?.slotId===Wr?null:{amsId:ht.id,slotId:Wr})},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:_("printers.slotOptions"),children:r.jsx(vm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&ys?.amsId===ht.id&&ys?.slotId===Wr&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:ams_rfid")&&(ju.mutate({amsId:ht.id,slotId:Wr}),Yi(null))},disabled:Ya||!z("printers:ams_rfid"),title:z("printers:ams_rfid")?void 0:_("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Ya?"animate-spin":""}`}),_("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:control")&&(hp.mutate({trayId:ht.id*4+Wr}),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(Z0,{className:"w-3 h-3"}),_("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:pn=>{pn.stopPropagation(),z("printers:control")&&(Cd.mutate(),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(ty,{className:"w-3 h-3"}),_("printers.ams.unload")]})]}),Mr?r.jsx(d3,{data:Mr,spoolman:{enabled:o,linkedSpoolId:uo?.spoolman_spool_id??(Qa?l?.[Qa]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!uo&&!Na?()=>{const pn=(Mr.trayUuid||Mr.tagUid||gm(t.serial_number,ht.id,Wr)).toUpperCase();ut({tagUid:Mr.tagUid||pn,trayUuid:Mr.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:Wr})}:void 0,onUnlinkSpool:Il?.id?()=>Rc.mutate(Il.id):void 0},inventory:(()=>{if(o){if(g)return;const xf=uo,Lr=Fi;return{assignedSpool:Lr?{id:Lr.id,material:Lr.material,brand:Lr.brand??null,color_name:Lr.color_name??null,remainingWeightGrams:Lr.label_weight?Math.max(0,Math.round(Lr.label_weight-Lr.weight_used)):void 0}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:Wr,trayInfo:{type:an?.tray_type||Mr.profile,material:an?.tray_type??void 0,profile:Mr.profile,color:Mr.colorHex||"",location:Bo(ht.id,ht.tray.length)}}),onUnassignSpool:Lr&&!Ks(an)?()=>w?.(Lr.id):void 0,isAssigned:!!xf||Ks(an)}}const pn=u?.(t.id,ht.id,Wr);return{assignedSpool:pn?.spool?{id:pn.spool.id,material:pn.spool.material,brand:pn.spool.brand,color_name:pn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(pn.spool.label_weight-pn.spool.weight_used))}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:Wr,trayInfo:{type:an?.tray_type||Mr.profile,material:an?.tray_type??void 0,profile:Mr.profile,color:Mr.colorHex||"",location:Bo(ht.id,ht.tray.length)}}),onUnassignSpool:pn&&!Ks(an)?()=>m?.(t.id,ht.id,Wr):void 0,isAssigned:!!pn||Ks(an)}})(),configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:ht.id,trayId:Wr,trayCount:ht.tray.length,trayType:an?.tray_type||void 0,trayColor:an?.tray_color||void 0,traySubBrands:an?.tray_sub_brands||void 0,trayInfoIdx:an?.tray_info_idx||void 0,extruderId:In,caliIdx:an?.cali_idx,savedPresetId:Mu?.preset_id})},children:qc}):r.jsx(u3,{kind:Ka??void 0,configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:ht.id,trayId:Wr,trayCount:ht.tray.length,extruderId:In})},onAssignSpool:()=>Le({printerId:t.id,amsId:ht.id,trayId:Wr,trayInfo:{type:"",material:void 0,profile:"",color:"",location:Bo(ht.id,ht.tray.length)}}),children:qc})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ht.temp!=null&&r.jsx(JK,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>kt({amsId:ht.id,amsLabel:Bo(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),ht.humidity!=null&&r.jsx(ZK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>kt({amsId:ht.id,amsLabel:Bo(ht.id,ht.tray.length),mode:"humidity"}),compact:!0})]})]})]},ht.id)}),qe.vt_tray.length>0&&r.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${qe.vt_tray.length===1?"max-w-[50%]":""}`,children:[r.jsx("div",{className:"flex items-center gap-1 mb-2",children:r.jsx("span",{className:"text-[10px] text-white font-medium",children:_("printers.external")})}),r.jsx("div",{className:`grid ${qe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...qe.vt_tray].sort((ht,In)=>(ht.id??254)-(In.id??254)).map(ht=>{const In=ht.id??254,Nr=Xt&&It===254?In===254&&qe.active_extruder===1||In===255&&qe.active_extruder===0:It===In,Hn=In-254,xa=Xt?_(In===254?"printers.extL":"printers.extR"):"",ya=ht.tray_info_idx?nn?.[ht.tray_info_idx]:null,an=rn?.[1020+Hn],Tn=(ht.tray_uuid||ht.tag_uid||gm(t.serial_number,255,Hn))?.toUpperCase(),ka=Tn?l?.[Tn]:void 0,Ka=LN(ka),Di=u?.(t.id,255,Hn),Ll=(()=>{const wr=Di?.spool;return wr&&wr.label_weight>0&&wr.weight_used!=null?Math.round(Math.max(0,wr.label_weight-wr.weight_used)/wr.label_weight*100):null})(),Rl=ht.tray_type&&ht.remain>=0,Mu=Ll===0&&Rl&&ht.remain>0?null:Ll,Wr=o&&!g?f?.find(wr=>wr.printer_id===t.id&&wr.ams_id===255&&wr.tray_id===Hn):void 0,Qa=Wr?p?.find(wr=>wr.id===Wr.spoolman_spool_id):void 0,Il=Qa&&(Qa.label_weight??0)>0?Math.round(Math.max(0,(Qa.label_weight??0)-Qa.weight_used)/(Qa.label_weight??1)*100):null,rl=Ka??Il??Mu??(Rl?ht.remain:null),Na=Ka!==null||Il!==null?"spoolman":Mu!==null?"inventory":Rl?"ams":void 0,Br={vendor:Ks(ht)?"Bambu Lab":"Generic",profile:an?.preset_name||(Qa?[Qa.brand,Qa.slicer_filament_name?.split("@")[0].trim()||Qa.material].filter(Boolean).join(" ").trim():null)||Di?.spool?.slicer_filament_name||ya?.name||ht.tray_sub_brands||ht.tray_type||"Unknown",colorName:fc(ht.tray_color||""),colorHex:ht.tray_color||null,kFactor:g3(ht.k),fillLevel:rl,trayUuid:ht.tray_uuid||null,tagUid:ht.tag_uid||null,fillSource:Na},Do=!ht.tray_type,uo=x3(ht),Fi=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Do?"opacity-50":""} ${Nr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(f3,{trayColor:ht.tray_color,trayType:ht.tray_type,isEmpty:Do,emptyKind:uo,slotNumber:Hn+1}),r.jsx("div",{className:`text-[9px] font-bold truncate ${Do?"text-white/40":"text-white"}`,children:ht.tray_type||_("ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:rl!==null&&rl>=0&&!Do&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${rl}%`,backgroundColor:my(rl)}})}),xa&&r.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:xa})]}),Hc=2550+Hn,Xi=ys?.amsId===255&&ys?.slotId===Hc;return r.jsxs("div",{className:"relative group",children:[qe?.state!=="RUNNING"&&r.jsx("button",{onClick:wr=>{wr.stopPropagation(),Yi(Xi?null:{amsId:255,slotId:Hc})},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:_("printers.slotOptions"),children:r.jsx(vm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&Xi&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),z("printers:control")&&(hp.mutate({trayId:In}),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(Z0,{className:"w-3 h-3"}),_("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${z("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),z("printers:control")&&(Cd.mutate(),Yi(null))},disabled:!z("printers:control"),title:z("printers:control")?void 0:_("printers.permission.noControl"),children:[r.jsx(ty,{className:"w-3 h-3"}),_("printers.ams.unload")]})]}),Do?r.jsx(u3,{kind:uo??void 0,configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:255,trayId:Hn,trayCount:1,extruderId:Xt?In===254?1:0:void 0})},onAssignSpool:()=>Le({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`External Slot ${Hn+1}`}}),children:Fi}):r.jsx(d3,{data:Br,spoolman:{enabled:o,linkedSpoolId:Wr?.spoolman_spool_id??(Tn?l?.[Tn]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Wr&&!Di?()=>{const wr=(Br.trayUuid||Br.tagUid||gm(t.serial_number,255,Hn)).toUpperCase();ut({tagUid:Br.tagUid||wr,trayUuid:Br.trayUuid||"",printerId:t.id,amsId:255,trayId:Hn})}:void 0,onUnlinkSpool:ka?.id?()=>Rc.mutate(ka.id):void 0},inventory:(()=>{if(o){if(g)return;const Mr=Wr,Ya=Qa;return{assignedSpool:Ya?{id:Ya.id,material:Ya.material,brand:Ya.brand??null,color_name:Ya.color_name??null,remainingWeightGrams:Ya.label_weight?Math.max(0,Math.round(Ya.label_weight-Ya.weight_used)):void 0}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Br.profile,material:ht.tray_type??void 0,profile:Br.profile,color:Br.colorHex||"",location:xa||_("printers.external")}}),onUnassignSpool:Ya&&!Ks(ht)?()=>w?.(Ya.id):void 0,isAssigned:!!Mr||Ks(ht)}}const wr=u?.(t.id,255,Hn);return{assignedSpool:wr?.spool?{id:wr.spool.id,material:wr.spool.material,brand:wr.spool.brand,color_name:wr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(wr.spool.label_weight-wr.spool.weight_used))}:null,onAssignSpool:()=>Le({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Br.profile,material:ht.tray_type??void 0,profile:Br.profile,color:Br.colorHex||"",location:xa||_("printers.external")}}),onUnassignSpool:wr&&!Ks(ht)?()=>m?.(t.id,255,Hn):void 0,isAssigned:!!wr||Ks(ht)}})(),configureSlot:{enabled:z("printers:control"),onConfigure:()=>Ge({amsId:255,trayId:Hn,trayCount:1,trayType:ht.tray_type||void 0,trayColor:ht.tray_color||void 0,traySubBrands:ht.tray_sub_brands||void 0,trayInfoIdx:ht.tray_info_idx||void 0,extruderId:Xt?In===254?1:0:void 0,caliIdx:ht.cali_idx,savedPresetId:an?.preset_id})},children:Fi})]},In)})})]})]})]})]})})()]}),_n&&a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(wc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-sm text-white truncate",children:_n.name}),Kt&&r.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Kt.state==="ON"?"bg-bambu-green/20 text-bambu-green":Kt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Kt.state||"?",Kt.state==="ON"&&Kt.energy?.power!=null&&r.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Math.round(Kt.energy.power),"W"]})]})]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{onClick:()=>J(!0),disabled:Mo.isPending||Kt?.state==="ON"||!z("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${z("smart_plugs:control")?Kt?.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:z("smart_plugs:control")?void 0:_("printers.permission.noSmartPlugControl"),children:[r.jsx(_u,{className:"w-3 h-3"}),"On"]}),r.jsxs("button",{onClick:()=>E(!0),disabled:Mo.isPending||Kt?.state==="OFF"||!z("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${z("smart_plugs:control")?Kt?.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:z("smart_plugs:control")?void 0:_("printers.permission.noSmartPlugControl"),children:[r.jsx(FS,{className:"w-3 h-3"}),"Off"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx("span",{className:`text-xs hidden sm:inline ${_n.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:_n.auto_off_executed?"Auto-off done":"Auto-off"}),r.jsx("button",{onClick:()=>Eo.mutate(!_n.auto_off),disabled:Eo.isPending||_n.auto_off_executed||!z("smart_plugs:control"),title:z("smart_plugs:control")?_n.auto_off_executed?_("printers.autoOffExecuted"):_("printers.autoOffAfterPrint"):_("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${z("smart_plugs:control")?_n.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":_n.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:r.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${_n.auto_off||_n.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),ur&&ur.length>0&&r.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsx(AS,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:ur.map(dt=>{const qt=dt.ha_entity_id?.startsWith("script.");return r.jsxs("button",{onClick:()=>{qt?Ic.mutate({id:dt.id,action:"on"}):W(dt)},disabled:Ic.isPending,title:`${qt?"Run":"Toggle"} ${dt.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:[r.jsx(hs,{className:"w-2.5 h-2.5"}),dt.name]},dt.id)})})]})]}),a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>Au.mutate(!qe?.chamber_light),disabled:!qe?.connected||Au.isPending||!z("printers:control"),title:z("printers:control")?qe?.chamber_light?_("printers.chamberLightOff"):_("printers.chamberLightOn"):_("printers.permission.noControl"),className:qe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:r.jsx(s4,{on:qe?.chamber_light??!1,className:`w-4 h-4 ${qe?.chamber_light?"text-yellow-400":""}`})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>{if(x==="embedded"&&S)S(t.id,t.name);else{const dt=localStorage.getItem("cameraWindowState"),qt=dt?JSON.parse(dt):{width:640,height:400},Xt=[`width=${qt.width}`,`height=${qt.height}`,qt.left!==void 0?`left=${qt.left}`:"",qt.top!==void 0?`top=${qt.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Xt)}},disabled:!qe?.connected||!z("camera:view"),title:z("camera:view")?_(x==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):_("printers.permission.noCamera"),children:r.jsx(oC,{className:"w-4 h-4"})}),r.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:ff,disabled:!qe?.connected||Oc.isPending||!z("printers:update"),title:z("printers:update")?t.plate_detection_enabled?_("printers.plateDetection.enabledClick"):_("printers.plateDetection.disabledClick"):_("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:Oc.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(iC,{className:"w-4 h-4"})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:bb,disabled:!qe?.connected||Ye||!z("printers:update"),title:z("printers:update")?_("printers.plateDetection.manageCalibration"):_("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:Ye?r.jsx(ft,{className:"w-3 h-3 animate-spin"}):r.jsx(Ln,{className:"w-3 h-3"})})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>pe(!0),disabled:!Fr||!z("printers:files"),title:z("printers:files")?_("printers.browseFiles"):_("printers.permission.noFiles"),children:[r.jsx(ib,{className:"w-4 h-4"}),_("printers.files")]}),Fr&&qe?.state!=="RUNNING"&&qe?.state!=="PAUSE"&&r.jsxs(je,{size:"sm",onClick:()=>Fe(!0),disabled:!z("printers:control"),title:z("printers:control")?_("common.print"):_("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[r.jsx(hr,{className:"w-4 h-4"}),_("common.print")]})]})]}),le&&r.jsx(d2e,{printerId:t.id,printerName:t.name,onClose:()=>pe(!1)}),Be&&r.jsx(Zie,{folderId:null,onClose:()=>Fe(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:dt=>{const qt=dt.name.toLowerCase();if(!qt.endsWith(".gcode")&&!qt.includes(".gcode."))return _("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:dt=>{const qt=dt.metadata?.sliced_for_model,Xt=ow(t.model);if(qt&&Xt&&qt.toLowerCase()!==Xt.toLowerCase())return ae.deleteLibraryFile(dt.id).catch(()=>{}),_("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:qt,printerModel:Xt});st({id:dt.id,filename:dt.filename})}}),ze&&r.jsx(bc,{mode:"reprint",libraryFileId:ze.id,archiveName:ze.filename,initialSelectedPrinterIds:[t.id],onClose:()=>st(null),onSuccess:()=>st(null),cleanupLibraryAfterDispatch:!0}),he&&r.jsx(x2e,{printerId:t.id,printerName:t.name,onClose:()=>we(!1)}),Oe&&r.jsx(Q7e,{printer:t,status:qe,totalPrintHours:n?.total_print_hours,onClose:We}),mt&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Dl(),children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:dt=>dt.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[mt.needs_calibration?r.jsx(iC,{className:"w-5 h-5 text-blue-500"}):mt.is_empty?r.jsx(xr,{className:"w-5 h-5 text-green-500"}):r.jsx($r,{className:"w-5 h-5 text-yellow-500"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),mt.reference_count!==void 0&&mt.max_references&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[mt.reference_count,"/",mt.max_references," refs"]})]}),r.jsx("button",{onClick:()=>Dl(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[mt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[r.jsx("p",{className:"font-medium text-blue-400",children:_("printers.plateDetection.calibrationRequired")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:_("printers.plateDetection.calibrationInstructions")}})]}),r.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[r.jsx("p",{children:_("printers.plateDetection.calibrationDescription")}),r.jsx("p",{dangerouslySetInnerHTML:{__html:_("printers.plateDetection.calibrationTip")}})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`p-3 rounded-lg ${mt.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[r.jsx("p",{className:`font-medium ${mt.is_empty?"text-green-400":"text-yellow-400"}`,children:mt.is_empty?_("printers.plateDetection.plateEmpty"):_("printers.plateDetection.objectsDetected")}),r.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[_("printers.plateDetection.confidence"),": ",Math.round(mt.confidence*100),"% | ",_("printers.plateDetection.difference"),": ",mt.difference_percent.toFixed(1),"%"]})]}),mt.debug_image_url&&r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:_("printers.plateDetection.analysisPreview")}),r.jsx("img",{src:mt.debug_image_url,alt:_("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:_("printers.plateDetection.analysisLegend")})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:mt.message})]}),co&&co.references.length>0&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:_("printers.plateDetection.savedReferences",{count:co.references.length,max:co.max_references})}),r.jsx("div",{className:"grid grid-cols-5 gap-2",children:co.references.map(dt=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ae.getPlateReferenceThumbnailUrl(t.id,dt.index),alt:dt.label||`Reference ${dt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),r.jsx("button",{onClick:()=>xb(dt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:_("printers.plateDetection.deleteReference"),children:r.jsx(Vt,{className:"w-3 h-3 text-white"})}),Pd?.index===dt.index?r.jsx("input",{type:"text",value:Pd.label,onChange:qt=>Td({...Pd,label:qt.target.value}),onBlur:()=>fp(dt.index,Pd.label),onKeyDown:qt=>{qt.key==="Enter"&&fp(dt.index,Pd.label),qt.key==="Escape"&&Td(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:_("printers.plateDetection.labelPlaceholder")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Td({index:dt.index,label:dt.label}),title:dt.label?_("printers.plateDetection.clickToEdit",{label:dt.label}):_("printers.plateDetection.clickToAddLabel"),children:dt.label||r.jsx("span",{className:"italic opacity-50",children:_("printers.noLabel")})}),r.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:dt.timestamp?Yn(dt.timestamp)?.toLocaleDateString()??"":""})]},dt.index))})]}),!mt.needs_calibration&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:_("printers.roi.title")}),vt?r.jsxs("div",{className:"flex gap-1",children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>wt(null),disabled:Ue,children:_("common.cancel")}),r.jsx(je,{size:"sm",onClick:bv,disabled:Ue,children:Ue?r.jsx(ft,{className:"w-3 h-3 animate-spin"}):_("common.save")})]}):r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>wt(mt.roi||{x:.15,y:.35,w:.7,h:.55}),children:[r.jsx(mi,{className:"w-3 h-3 mr-1"}),_("common.edit")]})]}),vt?r.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:_("printers.roi.xStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:vt.x,onChange:dt=>wt({...vt,x:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(vt.x*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:_("printers.roi.yStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:vt.y,onChange:dt=>wt({...vt,y:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(vt.y*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:_("printers.width")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:vt.w,onChange:dt=>wt({...vt,w:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(vt.w*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:_("printers.height")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:vt.h,onChange:dt=>wt({...vt,h:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(vt.h*100),"%"]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:_("printers.roi.instruction")})]}):r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((mt.roi?.x||.15)*100),"%, Y=",Math.round((mt.roi?.y||.35)*100),"%, W=",Math.round((mt.roi?.w||.7)*100),"%, H=",Math.round((mt.roi?.h||.55)*100),"%"]})]})]}),r.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:mt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsx(je,{variant:"ghost",onClick:()=>Dl(),children:_("common.cancel")}),r.jsx(je,{onClick:()=>gf(),disabled:at,children:at?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):r.jsxs(r.Fragment,{children:[r.jsx(je,{variant:"ghost",onClick:()=>gf(),disabled:at,children:at?"Adding...":`Add Reference (${co?.references.length||0}/${co?.max_references||5})`}),r.jsx(je,{onClick:()=>Dl(),children:"Close"})]})})]})}),$&&_n&&r.jsx(wn,{title:_("printers.confirm.powerOnTitle"),message:_("printers.confirm.powerOnMessage",{name:t.name}),confirmText:_("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Mo.mutate("on"),J(!1)},onCancel:()=>J(!1)}),j&&_n&&r.jsx(wn,{title:_("printers.confirm.powerOffTitle"),message:qe?.state==="RUNNING"?_("printers.confirm.powerOffWarning",{name:t.name}):_("printers.confirm.powerOffMessage",{name:t.name}),confirmText:_("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Mo.mutate("off"),E(!1)},onCancel:()=>E(!1)}),B&&r.jsx(wn,{title:_("printers.confirm.haToggleTitle",{name:B.name}),message:qe?.state==="RUNNING"?_("printers.confirm.haToggleWarning",{name:t.name,entity:B.ha_entity_id||B.name}):_("printers.confirm.haToggleMessage",{entity:B.ha_entity_id||B.name}),confirmText:_("printers.confirm.haToggleButton"),variant:qe?.state==="RUNNING"?"danger":"default",onConfirm:()=>{Ic.mutate({id:B.id,action:"toggle"}),W(null)},onCancel:()=>W(null)}),U&&r.jsx(wn,{title:_("printers.confirm.stopTitle"),message:_("printers.confirm.stopMessage",{name:t.name}),confirmText:_("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{_d.mutate(),G(!1)},onCancel:()=>G(!1)}),K&&r.jsx(wn,{title:_("printers.confirm.pauseTitle"),message:_("printers.confirm.pauseMessage",{name:t.name}),confirmText:_("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{kd.mutate(),X(!1)},onCancel:()=>X(!1)}),_e&&r.jsx(wn,{title:_("printers.confirm.resumeTitle"),message:_("printers.confirm.resumeMessage",{name:t.name}),confirmText:_("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{lo.mutate(),xe(!1)},onCancel:()=>xe(!1)}),be&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:_("printers.bedJog.notHomedTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:_("printers.bedJog.notHomedMessage")})]})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("button",{onClick:()=>{gv.mutate("all"),ye(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:_("printers.bedJog.homeZ")}),r.jsx("button",{onClick:()=>{const dt=be.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}gb.mutate({distance:dt,force:!0}),ye(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:_("printers.bedJog.moveAnyway")}),r.jsx("button",{onClick:()=>ye(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:_("common.cancel")})]})]})}),r.jsx(o4,{printerId:t.id,isOpen:ge,onClose:()=>Me(!1)}),O&&r.jsx(m0e,{printerName:t.name,errors:qe?.hms_errors||[],onClose:()=>ie(!1),printerId:t.id,hasPermission:z}),ct&&r.jsx(P7e,{isOpen:!!ct,onClose:()=>kt(null),printerId:t.id,printerName:t.name,amsId:ct.amsId,amsLabel:ct.amsLabel,initialMode:ct.mode,thresholds:s}),Nt&&r.jsx(Qie,{isOpen:!!Nt,onClose:()=>ut(null),tagUid:Nt.tagUid,trayUuid:Nt.trayUuid,printerId:Nt.printerId,amsId:Nt.amsId,trayId:Nt.trayId}),Ct&&r.jsx(Yie,{isOpen:!!Ct,onClose:()=>Le(null),printerId:Ct.printerId,amsId:Ct.amsId,trayId:Ct.trayId,trayInfo:Ct.trayInfo,spoolmanEnabled:!!o}),Ae&&r.jsx(Xie,{isOpen:!!Ae,onClose:()=>Ge(null),printerId:t.id,slotInfo:Ae,printerModel:ow(t.model)||void 0,onSuccess:()=>{M.invalidateQueries({queryKey:["slotPresets",t.id]}),M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),oe&&r.jsx(d9e,{printer:t,onClose:()=>Q(!1)}),Je&&Ke&&r.jsx(c9e,{printer:t,firmwareInfo:Ke,onClose:()=>De(!1)}),ys&&r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Yi(null)}),Ee!==null&&Tt&&(()=>{const dt=Ce==="n3s"?85:65,qt=35,Xt=dt+10;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>it(null)}),r.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:Tt.top,left:Tt.left},onClick:ht=>ht.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[r.jsx(pm,{className:"w-3.5 h-3.5 text-amber-400"}),r.jsx("span",{className:"text-xs text-white font-medium",children:_("printers.drying.start")})]}),r.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:_("printers.filaments")}),r.jsx("select",{value:Ie,onChange:ht=>{const In=ht.target.value;ke(In);const Nr=C[In];Nr&&(rt(Nr[Ce==="n3s"?"n3s":"n3f"]),Te(Ce==="n3s"?Nr.n3s_hours:Nr.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(C).map(ht=>r.jsx("option",{value:ht,children:ht},ht))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:_("printers.drying.temperature")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:45,max:dt,value:Ve,onChange:ht=>rt(Math.min(dt,Math.max(45,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),r.jsx("input",{type:"range",min:qt,max:Xt,value:Ve,onChange:ht=>rt(Math.min(dt,Math.max(45,Number(ht.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"45°C"}),r.jsxs("span",{children:[dt,"°C"]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:_("printers.drying.duration")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:Qe,onChange:ht=>Te(Math.min(24,Math.max(1,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:_("printers.drying.hours")})]})]}),r.jsx("input",{type:"range",min:1,max:24,value:Qe,onChange:ht=>Te(Number(ht.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"1h"}),r.jsx("span",{children:"24h"})]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:tt,onChange:ht=>ot(ht.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),r.jsx("span",{className:"text-[11px] text-bambu-gray",children:_("printers.drying.rotateTray")})]})]}),r.jsx("div",{className:"px-3 pb-3",children:r.jsx("button",{onClick:()=>{Ee!==null&&mp.mutate({amsId:Ee,temp:Ve,duration:Qe,filament:Ie,rotateTray:tt})},disabled:mp.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:mp.isPending?_("printers.drying.startingDrying"):_("printers.drying.start")})})]})]})})()]})}function l9e({onClose:t,onAdd:e,existingSerials:n}){const{t:a}=_t(),[i,s]=y.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=y.useState(!1),[c,d]=y.useState([]),[u,m]=y.useState(""),[p,f]=y.useState(!1),[g,w]=y.useState(!1),[b,x]=y.useState([]),[S,k]=y.useState(""),[C,P]=y.useState({scanned:0,total:0});y.useEffect(()=>{Fd.getInfo().then(_=>{w(_.is_docker),_.subnets.length>0&&(x(_.subnets),k(_.subnets[0]))}).catch(()=>{})},[]);const T=c.filter(_=>!n.includes(_.serial)),A=async()=>{m(""),d([]),l(!0),f(!1),P({scanned:0,total:0});try{if(g){await Fd.startSubnetScan(S);const _=setInterval(async()=>{try{const M=await Fd.getScanStatus();P({scanned:M.scanned,total:M.total});const H=await Fd.getDiscoveredPrinters();d(H),M.running||(clearInterval(_),l(!1),f(!0))}catch(M){console.error("Failed to get scan status:",M)}},500)}else{await Fd.startDiscovery(10);const _=setInterval(async()=>{try{const M=await Fd.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get discovered printers:",M)}},1e3);setTimeout(async()=>{clearInterval(_);try{await Fd.stopDiscovery()}catch{}l(!1),f(!0);try{const M=await Fd.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get final discovered printers:",M)}},1e4)}}catch(_){console.error("Failed to start discovery:",_),m(_ instanceof Error?_.message:a("printers.discovery.failedToStart")),l(!1),f(!0)}},F=_=>{const M=_.serial.startsWith("unknown-")?"":_.serial;s({...i,name:_.name||"",serial_number:M,ip_address:_.ip_address,model:ow(_.model)}),d([])};return y.useEffect(()=>()=>{Fd.stopDiscovery().catch(()=>{}),Fd.stopSubnetScan().catch(()=>{})},[]),y.useEffect(()=>{const _=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[t]),r.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:r.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:_=>_.stopPropagation(),children:r.jsxs(Et,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:a("printers.addPrinter")}),r.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[g&&r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.discovery.subnetToScan")}),b.length>0?r.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:S,onChange:_=>k(_.target.value),disabled:o,children:b.map(_=>r.jsx("option",{value:_,children:_},_))}):r.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:S,onChange:_=>k(_.target.value),placeholder:"192.168.1.0/24",disabled:o}),r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:a("printers.discovery.dockerNote")})]}),r.jsx(je,{type:"button",variant:"secondary",onClick:A,disabled:o,className:"w-full",children:o?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),g&&C.total>0?a("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):a("printers.discovery.scanning")]}):r.jsxs(r.Fragment,{children:[r.jsx(yr,{className:"w-4 h-4"}),a(g?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&r.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),T.length>0&&r.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:T.map(_=>r.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(_),children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-white text-sm truncate",children:_.name||_.serial}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[ow(_.model)||a("printers.discovery.unknown")," • ",_.ip_address,_.serial.startsWith("unknown-")&&r.jsxs("span",{className:"text-yellow-500",children:[" • ",a("printers.discovery.serialRequired")]})]})]}),r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},_.serial))}),o&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(g?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(g?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&T.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a("printers.discovery.allConfigured")})]}),r.jsxs("form",{onSubmit:_=>{_.preventDefault(),e(i)},className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.name")}),r.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:_=>s({...i,name:_.target.value}),placeholder:a("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.ipAddress")}),r.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:_=>s({...i,ip_address:_.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.serialNumber")}),r.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:_=>s({...i,serial_number:_.target.value}),placeholder:"01P00A000000000"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.accessCode")}),r.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:_=>s({...i,access_code:_.target.value}),placeholder:a("printers.modal.fromPrinterSettings")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.modelOptional")}),r.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:_=>s({...i,model:_.target.value}),children:[r.jsx("option",{value:"",children:a("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.locationGroup")}),r.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:_=>s({...i,location:_.target.value}),placeholder:a("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:_=>s({...i,auto_archive:_.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:a("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsx(je,{type:"submit",className:"flex-1",children:a("printers.addPrinter")})]})]})]})})})}function c9e({printer:t,firmwareInfo:e,onClose:n}){const{t:a}=_t(),i=tn(),{showToast:s}=on(),{hasPermission:o}=dr(),l=o("firmware:update"),[c,d]=y.useState(null),[u,m]=y.useState(!1),[p,f]=y.useState(null),[g,w]=y.useState(e.update_available?e.latest_version:null),{data:b,isLoading:x}=Xe({queryKey:["firmwarePrepare",t.id,g],queryFn:()=>yN.prepareUpload(t.id,g??void 0),staleTime:3e4,enabled:!!g&&l&&!u}),S=lt({mutationFn:()=>yN.startUpload(t.id,g??void 0),onSuccess:()=>{m(!0);const C=setInterval(async()=>{try{const P=await yN.getUploadStatus(t.id);d(P),(P.status==="complete"||P.status==="error")&&(clearInterval(C),f(null),m(!1),P.status==="complete"&&(s(a("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(C)},onError:C=>{s(a("printers.firmwareModal.uploadFailed",{error:C.message}),"error"),m(!1)}});y.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const k=()=>{d(null),S.mutate()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(At,{className:"w-full max-w-md mx-4",children:r.jsxs(Et,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?r.jsx(Zr,{className:"w-5 h-5 text-orange-400"}):r.jsx(xr,{className:"w-5 h-5 text-status-ok"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?a("printers.firmwareModal.title"):a("printers.firmwareModal.titleUpToDate")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const C=g?e.available_versions?.find(F=>F.version===g):null,P=g??e.latest_version,T=C?.release_notes??e.release_notes,A=!!P&&P!==e.current_version;return r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.currentVersion")}),r.jsx("span",{className:`font-mono ${A?"text-white":"text-status-ok"}`,children:e.current_version||a("common.unknown")})]}),A&&r.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.latestVersion")}),r.jsx("span",{className:"text-orange-400 font-mono",children:P})]}),T&&r.jsxs("details",{className:"mt-3 text-sm",open:!A,children:[r.jsx("summary",{className:`cursor-pointer hover:underline ${A?"text-orange-400":"text-status-ok"}`,children:a("printers.firmwareModal.releaseNotes")}),r.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:T})]},P??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:a("printers.firmwareModal.availableVersions")}),r.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(C=>{const P=e.current_version===C.version,T=g===C.version,A=e.current_version?c0e(C.version,e.current_version):0,F=P?a("printers.firmwareModal.currentBadge"):A>0?a("printers.firmwareModal.newerBadge"):a("printers.firmwareModal.olderBadge"),_=P?"text-bambu-gray":A>0?"text-orange-400":"text-blue-400";return r.jsxs("button",{type:"button",disabled:!C.file_available||!l||P,onClick:()=>w(C.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${T?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!C.file_available||!l||P?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono text-white",children:C.version}),r.jsx("span",{className:`text-xs ${_}`,children:F})]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${P?"bg-blue-500/15 text-blue-400 border border-blue-500/30":C.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:P?a("printers.firmwareModal.installed"):C.file_available?a("printers.firmwareModal.usable"):a("printers.firmwareModal.unavailable")})]},C.version)})})]}),g?x?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),a("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?r.jsx("div",{className:"mb-4",children:b.can_proceed?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[r.jsx(Si,{className:"w-4 h-4"}),a("printers.firmwareModal.sdCardReady")]}):r.jsx("div",{className:"space-y-1",children:b.errors.map((C,P)=>r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(Ha,{className:"w-4 h-4 flex-shrink-0"}),C]},P))})}):null:null,(u||c)&&c&&r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),r.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.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}%`}})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&r.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:a("printers.firmwareModal.uploadedSuccess")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("printers.firmwareModal.applyInstructions")}),r.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step1")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step2")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step3")}}),r.jsx("li",{children:a("printers.firmwareModal.step4")})]})]}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(je,{variant:"secondary",onClick:n,children:c?.status==="complete"?a("printers.firmwareModal.done"):a("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&r.jsx(je,{onClick:k,disabled:S.isPending,children:S.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),a("printers.firmwareModal.starting")]}):r.jsxs(r.Fragment,{children:[r.jsx(Zr,{className:"w-4 h-4 mr-2"}),a("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function d9e({printer:t,onClose:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),[s,o]=y.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=lt({mutationFn:d=>ae.updatePrinter(t.id,d),onSuccess:()=>{a.invalidateQueries({queryKey:["printers"]}),a.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});y.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 r.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:r.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:r.jsxs(Et,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),r.jsxs("form",{onSubmit:c,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),r.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),r.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}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),r.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:[r.jsx("option",{value:"",children:n("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),r.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")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.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"}),r.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),r.jsx(je,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function u9e(t){const{data:e}=Xe({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function m9e({printer:t,plug:e,onPowerOn:n,isPowering:a}){const i=u9e(t.id),{data:s}=Xe({queryKey:["smartPlugStatus",e.id],queryFn:()=>ae.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&r.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||"?"})]}),r.jsxs("button",{onClick:()=>n(e.id),disabled:a||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:[r.jsx(_u,{className:"w-3 h-3"}),a?"...":"On"]})]}):null}function p9e(){const{t}=_t(),[e,n]=y.useState(!1),[a,i]=y.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=y.useState(!1),[l,c]=y.useState(null),[d,u]=y.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=y.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,g]=y.useState(()=>{const ct=localStorage.getItem("printerCardSize");return ct?parseInt(ct,10):2}),w=f===1?"compact":"expanded",[b,x]=y.useState(""),[S,k]=y.useState("all"),[C,P]=y.useState("all"),[T,A]=y.useState(0),[F,_]=y.useState(()=>{try{const ct=localStorage.getItem("printerCollapsedSections");return ct?JSON.parse(ct):{}}catch{return{}}}),M=tn(),{showToast:H}=on(),{hasPermission:I}=dr(),[z,L]=y.useState(()=>{const ct=localStorage.getItem("openEmbeddedCameras");if(ct)try{const kt=JSON.parse(ct);return new Map(kt.map(Nt=>[Nt.id,Nt]))}catch{return new Map}return new Map});y.useEffect(()=>{const ct=Array.from(z.values());ct.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ct)):localStorage.removeItem("openEmbeddedCameras")},[z]);const{data:Z,isLoading:ne}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:Y}=Xe({queryKey:["ui-preferences"],queryFn:ae.getUiPreferences}),ce=y.useMemo(()=>{if(Y?.drying_presets)try{const ct=JSON.parse(Y.drying_presets);if(typeof ct=="object"&&ct!==null&&Object.keys(ct).length>0)return{...cI,...ct}}catch{}return cI},[Y?.drying_presets]);y.useEffect(()=>{Y?.camera_view_mode==="window"&&z.size>0&&L(new Map)},[Y?.camera_view_mode,z.size]);const{data:ue}=Xe({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:oe}=Xe({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview,staleTime:60*1e3}),{data:Q}=Xe({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,staleTime:60*1e3}),le=Q?.enabled&&Q?.connected,{data:pe}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings,enabled:!!le,staleTime:60*1e3}),he=pe?.spoolman_sync_mode,{data:we}=Xe({queryKey:["unlinked-spools"],queryFn:ae.getUnlinkedSpools,enabled:!!le,staleTime:30*1e3}),$=we&&we.length>0,{data:J}=Xe({queryKey:["linked-spools"],queryFn:ae.getLinkedSpools,enabled:!!le,staleTime:30*1e3}),j=J?.linked,{data:E}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),enabled:I("inventory:view_assignments"),staleTime:30*1e3}),B=lt({mutationFn:({printerId:ct,amsId:kt,trayId:Nt})=>ae.unassignSpool(ct,kt,Nt),onSuccess:()=>{M.invalidateQueries({queryKey:["spool-assignments"]})}}),{data:W,isLoading:O}=Xe({queryKey:["spoolman-inventory-spools"],queryFn:()=>ae.getSpoolmanInventorySpools(!1),enabled:!!le,staleTime:30*1e3}),{data:ie,isLoading:U}=Xe({queryKey:["spoolman-slot-assignments"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:!!le,staleTime:30*1e3}),G=lt({mutationFn:ct=>ae.unassignSpoolmanSlot(ct),onSuccess:()=>{M.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),M.invalidateQueries({queryKey:["spoolman-slot-assignments"]})}}),K=(ct,kt,Nt)=>E?.find(ut=>ut.printer_id===ct&&ut.ams_id===Number(kt)&&ut.tray_id===Number(Nt)),X=oe?.reduce((ct,kt)=>(ct[kt.printer_id]={due_count:kt.due_count,warning_count:kt.warning_count,total_print_hours:kt.total_print_hours},ct),{})||{},se=ue?.reduce((ct,kt)=>(kt.printer_id&&(ct[kt.printer_id]=kt),ct),{})||{},te=lt({mutationFn:ae.createPrinter,onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),M.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:ct=>{if(ct instanceof rs&&ct.code==="printer_connection_failed"){H(t("printers.toast.connectionFailedNotAdded"),"error");return}H(ct.message||t("printers.toast.failedToAdd"),"error")}}),fe=lt({mutationFn:ct=>ae.controlSmartPlug(ct,"on"),onSuccess:()=>{M.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[de,me]=y.useState(new Set),[q,R]=y.useState(!1),[re,be]=y.useState(null),[ye,_e]=y.useState(!1),xe=q||de.size>0,ge=y.useCallback(ct=>{me(kt=>{const Nt=new Set(kt);return Nt.has(ct)?Nt.delete(ct):Nt.add(ct),Nt})},[]),Me=y.useCallback(()=>{me(new Set),R(!1)},[]);y.useEffect(()=>{const ct=kt=>{kt.key==="Escape"&&xe&&Me()};return window.addEventListener("keydown",ct),()=>window.removeEventListener("keydown",ct)},[xe,Me]);const Be=y.useCallback(async ct=>{_e(!0);const Nt=Array.from(de).filter(Ge=>{const Je=M.getQueryData(["printerStatus",Ge]);if(!Je?.connected)return!1;switch(ct){case"stop":return Je.state==="RUNNING"||Je.state==="PAUSE";case"pause":return Je.state==="RUNNING";case"resume":return Je.state==="PAUSE";case"clearPlate":return!!Je.awaiting_plate_clear;case"clearHMS":return Je.hms_errors&&Dm(Je.hms_errors).length>0;default:return!1}});if(Nt.length===0){H(t("printers.bulk.noneApplicable"),"error"),_e(!1),be(null);return}const ut={stop:ae.stopPrint,pause:ae.pausePrint,resume:ae.resumePrint,clearPlate:ae.clearPlate,clearHMS:ae.clearHMSErrors}[ct],Ct=await Promise.allSettled(Nt.map(Ge=>ut(Ge))),Le=Ct.filter(Ge=>Ge.status==="fulfilled").length,Ae=Ct.filter(Ge=>Ge.status==="rejected").length;Ae===0?H(t("printers.bulk.success",{action:t(`printers.bulk.actions.${ct}`),count:Le})):H(t("printers.bulk.partial",{succeeded:Le,failed:Ae}),"error"),Nt.forEach(Ge=>{M.invalidateQueries({queryKey:["printerStatus",Ge]})}),_e(!1),be(null)},[de,M,H,t]),Fe=y.useCallback(ct=>{ct==="stop"||ct==="pause"||ct==="clearPlate"?be(ct):Be(ct)},[Be]),Oe=()=>{const ct=!a;i(ct),localStorage.setItem("hideDisconnectedPrinters",String(ct))},Re=ct=>{u(ct),localStorage.setItem("printerSortBy",ct)},We=()=>{const ct=!m;p(ct),localStorage.setItem("printerSortAsc",String(ct))},ze=()=>{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"}},st=["S","M","L","XL"];y.useEffect(()=>M.getQueryCache().subscribe(kt=>{kt.type==="updated"&&Array.isArray(kt.query.queryKey)&&kt.query.queryKey[0]==="printerStatus"&&A(Nt=>Nt+1)}),[M]);const Ee=y.useMemo(()=>{if(!Z)return[];let ct=Z;if(b.trim()){const kt=b.trim().toLowerCase();ct=ct.filter(Nt=>Nt.name.toLowerCase().includes(kt)||(Nt.model||"").toLowerCase().includes(kt)||(Nt.location||"").toLowerCase().includes(kt)||(Nt.serial_number||"").toLowerCase().includes(kt))}return C!=="all"&&(ct=ct.filter(kt=>(kt.location||"")===C)),S!=="all"&&(ct=ct.filter(kt=>{const Nt=M.getQueryData(["printerStatus",kt.id]);if(!Nt?.connected)return S==="offline";const ut=Nt.hms_errors?Dm(Nt.hms_errors):[];switch(S){case"printing":return Nt.state==="RUNNING";case"paused":return Nt.state==="PAUSE";case"finished":return Nt.state==="FINISH";case"error":return Nt.state==="FAILED"||ut.length>0;case"idle":return Nt.state!=="RUNNING"&&Nt.state!=="PAUSE"&&Nt.state!=="FINISH"&&Nt.state!=="FAILED"&&ut.length===0;case"offline":return!1;default:return!0}})),ct},[Z,b,S,C,M,T]),it=y.useMemo(()=>Z?[...new Set(Z.map(ct=>ct.location||"").filter(Boolean))].sort():[],[Z]),Ce=y.useMemo(()=>{const ct=[...Ee];switch(d){case"name":ct.sort((kt,Nt)=>kt.name.localeCompare(Nt.name));break;case"model":ct.sort((kt,Nt)=>(kt.model||"").localeCompare(Nt.model||""));break;case"location":ct.sort((kt,Nt)=>{const ut=kt.location||"",Ct=Nt.location||"";return!ut&&Ct?1:ut&&!Ct?-1:ut.localeCompare(Ct)||kt.name.localeCompare(Nt.name)});break;case"status":ct.sort((kt,Nt)=>{const ut=M.getQueryData(["printerStatus",kt.id]),Ct=M.getQueryData(["printerStatus",Nt.id]),Le=Ae=>Ae?.connected?(Ae.hms_errors?Dm(Ae.hms_errors):[]).length>0?0:Ae.state==="RUNNING"?1:2:3;return Le(ut)-Le(Ct)});break}return m||ct.reverse(),ct},[Ee,d,m,M]),Ze=y.useCallback(()=>{me(new Set(Ce.map(ct=>ct.id))),R(!0)},[Ce]),Ie=y.useCallback(ct=>{me(kt=>{const Nt=new Set(kt);return Ce.forEach(ut=>{const Ct=M.getQueryData(["printerStatus",ut.id]);tQ(Ct)===ct&&Nt.add(ut.id)}),Nt}),R(!0)},[Ce,M]),ke=y.useCallback(ct=>{me(kt=>{const Nt=new Set(kt);return Ce.filter(ut=>(ut.location||"")===ct).forEach(ut=>Nt.add(ut.id)),Nt}),R(!0)},[Ce]),Ve=y.useCallback(ct=>{me(kt=>{const Nt=new Set(kt);return Ce.filter(ut=>(ut.model||"Unknown")===ct).forEach(ut=>Nt.add(ut.id)),Nt}),R(!0)},[Ce]),rt=y.useCallback(ct=>{_(kt=>{const Nt={...kt,[ct]:!kt[ct]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(Nt))}catch{}return Nt})},[]),Qe=y.useMemo(()=>{if(d==="name")return null;const ct={};return d==="location"?Ce.forEach(kt=>{const Nt=kt.location||"Ungrouped";ct[Nt]||(ct[Nt]=[]),ct[Nt].push(kt)}):d==="model"?Ce.forEach(kt=>{const Nt=kt.model||"Unknown";ct[Nt]||(ct[Nt]=[]),ct[Nt].push(kt)}):d==="status"&&Ce.forEach(kt=>{const Nt=M.getQueryData(["printerStatus",kt.id]),ut=tQ(Nt);ct[ut]||(ct[ut]=[]),ct[ut].push(kt)}),ct},[d,Ce,M,T]),Te=y.useRef(null),tt=y.useRef(null),ot=y.useRef(0),[Tt,Ut]=y.useState(!1),bt=y.useCallback(()=>{const ct=Te.current;if(!ct)return;const kt=tt.current?.offsetWidth;kt&&(ot.current=kt);const Ct=ot.current>0&&ct.clientWidth<ot.current+220+8;Ut(Le=>Le===Ct?Le:Ct)},[]),Wt=Object.keys(se).length;y.useLayoutEffect(()=>{bt();const ct=Te.current;if(!ct)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",bt),()=>window.removeEventListener("resize",bt);const kt=new ResizeObserver(()=>bt());return kt.observe(ct),window.addEventListener("resize",bt),()=>{kt.disconnect(),window.removeEventListener("resize",bt)}},[bt,Z?.length,it.length,a,Wt]);const Zt=(ct=!1)=>r.jsxs(r.Fragment,{children:[Z&&Z.length>0&&r.jsx(y3,{value:S,onChange:k,fullWidth:ct,options:[{value:"all",label:t("printers.filter.allStatuses")},{value:"printing",label:t("printers.status.printing")},{value:"paused",label:t("printers.status.paused")},{value:"idle",label:t("printers.status.idle")},{value:"finished",label:t("printers.status.finished")},{value:"error",label:t("printers.status.error")},{value:"offline",label:t("printers.status.offline")}]}),Z&&Z.length>0&&it.length>0&&r.jsx(y3,{value:C,onChange:P,fullWidth:ct,options:[{value:"all",label:t("printers.filter.allLocations")},...it.map(kt=>({value:kt,label:kt}))]}),r.jsx("button",{type:"button",onClick:Oe,"aria-pressed":a,className:`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${ct?"w-full":""} ${a?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:t("printers.hideOffline")})]}),ln=(ct=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center gap-1 ${ct?"w-full":""}`,children:[r.jsx(y3,{value:d,onChange:Re,fullWidth:ct,options:[{value:"name",label:t("printers.sort.name")},{value:"status",label:t("printers.sort.status")},{value:"model",label:t("printers.sort.model")},{value:"location",label:t("printers.sort.location")}]}),r.jsx("button",{onClick:We,className:"h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?r.jsx(qm,{className:"w-4 h-4 text-white"}):r.jsx(qh,{className:"w-4 h-4 text-white"})})]}),r.jsx("div",{className:`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${ct?"w-full":""}`,children:st.map((kt,Nt)=>{const ut=Nt+1,Ct=f===ut;return r.jsx("button",{onClick:()=>{g(ut),localStorage.setItem("printerCardSize",String(ut))},className:`h-full px-2 text-xs font-medium transition-colors ${ct?"flex-1":""} ${Nt===0?"rounded-l-lg":""} ${Nt===st.length-1?"rounded-r-lg":""} ${Ct?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,title:t(kt==="S"?"printers.cardSize.small":kt==="M"?"printers.cardSize.medium":kt==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:kt},kt)})})]}),cn=(ct=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>{xe?Me():R(!0)},className:`h-8 px-2 rounded-lg border transition-colors ${ct?"w-full justify-center gap-1.5 text-sm font-medium flex items-center":""} ${xe?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,title:t("printers.bulk.select"),disabled:!I("printers:control"),children:[r.jsx(gs,{className:"w-4 h-4"}),ct&&r.jsx("span",{children:t("printers.bulk.select")})]}),a&&Object.keys(se).length>0&&r.jsxs("div",{className:`relative ${ct?"w-full":""}`,children:[r.jsxs("button",{onClick:()=>o(!s),className:`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${ct?"w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(_u,{className:"w-4 h-4"}),t("printers.powerOn")]}),r.jsx(Ln,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),r.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:[r.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")}),Z?.filter(kt=>se[kt.id]).map(kt=>r.jsx(m9e,{printer:kt,plug:se[kt.id],onPowerOn:Nt=>{c(Nt),fe.mutate(Nt)},isPowering:l===se[kt.id]?.id},kt.id)),Z?.filter(kt=>se[kt.id]).length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),r.jsxs(je,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),className:`!h-8 !min-h-8 px-2 py-0 ${ct?"w-full":""}`,children:[r.jsx(er,{className:"w-4 h-4"}),t("printers.addPrinter")]})]});return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"space-y-3 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(hr,{className:"w-7 h-7 text-bambu-green"}),t("printers.title")]}),r.jsx(s9e,{printers:Z})]}),r.jsxs("div",{ref:Te,className:"relative flex items-center gap-2",children:[Z&&Z.length>0&&r.jsxs("div",{className:"relative min-w-0 flex-1",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:b,onChange:ct=>x(ct.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full h-8 pl-9 pr-8 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"}),b&&r.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>x(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{ref:tt,"aria-hidden":Tt,inert:Tt,className:`${Tt?"absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0":"flex"} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`,children:[r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:Zt()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:ln()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:cn()})]}),Tt&&r.jsxs("div",{className:"ml-auto flex items-center justify-end gap-1",children:[r.jsx(v3,{label:t("printers.toolbar.filters","Filters"),icon:r.jsx(PS,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:Zt(!0)})}),r.jsx(v3,{label:t("printers.toolbar.view","View"),icon:r.jsx(Iye,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:ln(!0)})}),r.jsx(v3,{label:t("printers.toolbar.actions","Actions"),icon:r.jsx(obe,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:cn(!0)})})]})]})]}),ne?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Z?.length===0?r.jsx(At,{children:r.jsxs(Et,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),r.jsxs(je,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),children:[r.jsx(er,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Ce.length===0&&(b.trim()||S!=="all"||C!=="all")?r.jsx(At,{children:r.jsx(Et,{className:"text-center py-12",children:r.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Qe?r.jsx("div",{className:"space-y-6",children:(()=>{const ct=d==="status"?o9e.filter(kt=>Qe[kt]?.length>0):Object.keys(Qe);return m?ct:[...ct].reverse()})().map(ct=>{const kt=Qe[ct],Nt=`${d}:${ct}`,ut=!F[Nt],Ct=d==="status"&&eQ[ct]?.dot||"bg-bambu-green",Le=d==="status"?t(eQ[ct]?.labelKey||ct):ct;return r.jsx(m5,{open:ut,onToggle:()=>rt(Nt),summaryClassName:"py-1",summary:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${Ct}`}),Le,r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",kt.length,")"]}),xe&&r.jsx("button",{onClick:Ae=>{Ae.stopPropagation(),d==="location"?ke(ct==="Ungrouped"?"":ct):d==="status"?Ie(ct):d==="model"&&Ve(ct)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:kt.map(Ae=>r.jsx(rQ,{printer:Ae,hideIfDisconnected:a,maintenanceInfo:X[Ae.id],viewMode:w,cardSize:f,amsThresholds:Y?{humidityGood:Number(Y.ams_humidity_good)||40,humidityFair:Number(Y.ams_humidity_fair)||60,tempGood:Number(Y.ams_temp_good)||28,tempFair:Number(Y.ams_temp_fair)||35}:void 0,spoolmanEnabled:le,hasUnlinkedSpools:$,linkedSpools:j,spoolmanUrl:Q?.url,spoolmanSyncMode:he,onGetAssignment:K,onUnassignSpool:(Ge,Je,De)=>B.mutate({printerId:Ge,amsId:Je,trayId:De}),spoolmanSpools:W,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:Ge=>G.mutate(Ge),timeFormat:Y?.time_format||"system",cameraViewMode:Y?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ge,Je)=>L(De=>new Map(De).set(Ge,{id:Ge,name:Je})),checkPrinterFirmware:Y?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:Y?.require_plate_clear===!0,selectionMode:xe,isSelected:de.has(Ae.id),onToggleSelect:ge},Ae.id))})},ct)})}):r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:Ce.map(ct=>r.jsx(rQ,{printer:ct,hideIfDisconnected:a,maintenanceInfo:X[ct.id],viewMode:w,cardSize:f,spoolmanEnabled:le,hasUnlinkedSpools:$,linkedSpools:j,spoolmanUrl:Q?.url,spoolmanSyncMode:he,onGetAssignment:K,onUnassignSpool:(kt,Nt,ut)=>B.mutate({printerId:kt,amsId:Nt,trayId:ut}),spoolmanSpools:W,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:kt=>G.mutate(kt),amsThresholds:Y?{humidityGood:Number(Y.ams_humidity_good)||40,humidityFair:Number(Y.ams_humidity_fair)||60,tempGood:Number(Y.ams_temp_good)||28,tempFair:Number(Y.ams_temp_fair)||35}:void 0,timeFormat:Y?.time_format||"system",cameraViewMode:Y?.camera_view_mode||"window",onOpenEmbeddedCamera:(kt,Nt)=>L(ut=>new Map(ut).set(kt,{id:kt,name:Nt})),checkPrinterFirmware:Y?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:Y?.require_plate_clear===!0,selectionMode:xe,isSelected:de.has(ct.id),onToggleSelect:ge},ct.id))}),e&&r.jsx(l9e,{onClose:()=>n(!1),onAdd:ct=>te.mutate(ct),existingSerials:Z?.map(ct=>ct.serial_number)||[]}),xe&&Z&&r.jsx(h0e,{selectedIds:de,printers:Z,onClose:Me,onSelectAll:Ze,onSelectByLocation:ke,onSelectByState:Ie,onAction:Fe,actionPending:ye}),re==="stop"&&r.jsx(wn,{title:t("printers.bulk.confirm.stopTitle",{count:de.size}),message:t("printers.bulk.confirm.stopMessage",{count:de.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:ye,onConfirm:()=>Be("stop"),onCancel:()=>be(null)}),re==="pause"&&r.jsx(wn,{title:t("printers.bulk.confirm.pauseTitle",{count:de.size}),message:t("printers.bulk.confirm.pauseMessage",{count:de.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:ye,onConfirm:()=>Be("pause"),onCancel:()=>be(null)}),re==="clearPlate"&&r.jsx(wn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:de.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:de.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:ye,onConfirm:()=>Be("clearPlate"),onCancel:()=>be(null)}),Array.from(z.values()).map((ct,kt)=>r.jsx(b2e,{printerId:ct.id,printerName:ct.name,viewerIndex:kt,onClose:()=>L(Nt=>{const ut=new Map(Nt);return ut.delete(ct.id),ut})},ct.id))]})}const sse=y.createContext(null),h9e=1500,f9e=1e3,S3=t=>`slice-job-${t}`;function G1(t){try{return decodeURIComponent(t)}catch{return t}}function g9e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function b9e({children:t}){const{t:e}=_t(),{showToast:n,showPersistentToast:a,dismissToast:i}=on(),s=tn(),[o,l]=y.useState([]),c=y.useRef([]);c.current=o;const d=y.useRef(new Map),u=y.useRef(new Map),m=y.useRef(new Map),p=y.useCallback(w=>{const b=d.current.get(w.id);if(b==null)return;const x=(Date.now()-b)/1e3,S=u.current.get(w.id)??"pending",k=g9e(x),C=m.current.get(w.id)??null,P=C&&C.stage&&C.total_percent>0;if(S==="running"&&P){a(S3(w.id),e("slice.runningWithProgress","{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:G1(w.sourceName),stage:C.stage,percent:Math.min(100,Math.max(0,Math.round(C.total_percent))),elapsed:k}),"loading");return}const T=S==="pending"?"slice.queuedToast":"slice.runningToast",A=S==="pending"?"Queued: {{name}} — {{elapsed}}":"Slicing {{name}} — {{elapsed}}";a(S3(w.id),e(T,A,{name:G1(w.sourceName),elapsed:k}),"loading")},[a,e]),f=y.useCallback((w,b,x)=>{l(S=>S.some(k=>k.id===w)?S:[...S,{id:w,kind:b,sourceName:x}]),d.current.set(w,Date.now()),u.current.set(w,"pending"),m.current.set(w,null),p({id:w,kind:b,sourceName:x})},[p]),g=y.useCallback((w,b)=>{if(l(x=>x.filter(S=>S.id!==w.id)),d.current.delete(w.id),u.current.delete(w.id),m.current.delete(w.id),i(S3(w.id)),b.status==="completed")n(e("slice.completedToast","Sliced {{name}}",{name:G1(w.sourceName)}),"success");else if(b.status==="failed"){const x=b.error_detail||e("slice.failed");n(e("slice.failedToast","Slicing {{name}} failed: {{detail}}",{name:G1(w.sourceName),detail:x}),"error")}s.invalidateQueries({queryKey:["library-files"]}),s.invalidateQueries({queryKey:["archives"]})},[i,s,n,e]);return y.useEffect(()=>{if(o.length===0)return;let w=!1;const b=setInterval(async()=>{if(w)return;const x=[...c.current];for(const S of x)try{const k=await ae.getSliceJob(S.id);u.current.set(S.id,k.status),k.progress&&m.current.set(S.id,k.progress),(k.status==="completed"||k.status==="failed")&&g(S,k)}catch{}},h9e);return()=>{w=!0,clearInterval(b)}},[o.length,g]),y.useEffect(()=>{if(o.length===0)return;const w=setInterval(()=>{for(const b of c.current)p(b)},f9e);return()=>clearInterval(w)},[o.length,p]),r.jsx(sse.Provider,{value:{trackJob:f,activeJobs:o},children:t})}function x9e(){const t=y.useContext(sse);if(!t)throw new Error("useSliceJobTracker must be used inside SliceJobTrackerProvider");return t}function p5({plates:t,onSelect:e,onClose:n}){const{t:a}=_t();return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:n,children:r.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"text-white font-medium",children:a("archives.platePicker.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("archives.platePicker.hint")})]}),r.jsx("button",{onClick:n,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors","aria-label":a("common.close","Close"),children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:t.map(i=>r.jsxs("button",{type:"button",onClick:()=>e(i.index),className:"flex items-center gap-2 p-2 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray transition-colors text-left",children:[i.has_thumbnail&&i.thumbnail_url!=null?r.jsx("img",{src:La(i.thumbnail_url),alt:`Plate ${i.index}`,className:"w-12 h-12 rounded object-cover bg-bambu-dark-tertiary flex-shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center flex-shrink-0",children:r.jsx(ca,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name?`${a("archives.platePicker.plateLabel",{index:i.index})} — ${i.name}`:a("archives.platePicker.plateLabel",{index:i.index})}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"…":""):i.object_count!=null&&i.object_count>0?a("archives.platePicker.objectCount",{count:i.object_count}):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${cs(i.print_time_seconds)}`:""]})]})]},i.index))})})]})})}const ose=["local","cloud","standard"];function dI(t,e){for(const n of ose){const a=t[n][e];if(a.length>0)return{source:a[0].source,id:a[0].id}}return null}const y9e={local:1.5,cloud:1,standard:.5};function v9e(t,e){const n=e.type.trim().toUpperCase(),a=Ia(e.color);let i=null;for(const s of ose)for(const o of t[s].filament){let l=0;const c=(o.filament_type??"").trim().toUpperCase(),d=Ia(o.filament_colour??"");n&&c&&n===c&&(l+=10),a&&d&&(d===a?l+=5:md(o.filament_colour??"",e.color)&&(l+=2)),l+=y9e[s],(i==null||l>i.score)&&(i={ref:{source:o.source,id:o.id},score:l})}return i==null?dI(t,"filament"):i.ref}function w9e(t){return t?`${t.source}:${t.id}`:""}function S9e(t){if(!t)return null;const e=t.indexOf(":");if(e<0)return null;const n=t.slice(0,e),a=t.slice(e+1);return n!=="cloud"&&n!=="local"&&n!=="standard"?null:{source:n,id:a}}function _9e({requestId:t,sourceName:e}){const{t:n}=_t(),{showPersistentToast:a,dismissToast:i}=on(),[s,o]=y.useState(0),[l,c]=y.useState(null);let d=e;try{d=decodeURIComponent(e)}catch{}y.useEffect(()=>{const g=Date.now(),w=setInterval(()=>o(Math.floor((Date.now()-g)/1e3)),1e3);return()=>clearInterval(w)},[]),y.useEffect(()=>{let g=!1;const w=setInterval(async()=>{if(g)return;const b=await ae.getPreviewSliceProgress(t);!g&&b&&c(b)},1e3);return()=>{g=!0,clearInterval(w)}},[t]);const u=`slice-preview-${t}`;y.useEffect(()=>{const g=l&&l.stage&&l.total_percent>0,w=k9e(s);return g?a(u,n("slice.previewWithProgress","Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:d,stage:l.stage,percent:Math.min(100,Math.max(0,Math.round(l.total_percent))),elapsed:w}),"loading"):a(u,n("slice.previewToast",{name:d,elapsed:w}),"loading"),()=>{i(u)}},[s,l,d,a,i,n,u]);const m=l?.stage,p=l?.total_percent,f=m&&typeof p=="number"&&p>0?`${m} (${Math.min(100,Math.max(0,Math.round(p)))}%)`:n("slice.analyzingPlateFilaments");return r.jsxs("div",{className:"flex flex-col gap-1 text-bambu-gray text-sm py-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),f,r.jsxs("span",{className:"text-xs tabular-nums",children:[s,"s"]})]}),s>=5&&r.jsx("div",{className:"text-xs text-bambu-gray/70 pl-6",children:n("slice.analyzingPlateFilamentsHint","Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.")})]})}function k9e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function RA({source:t,onClose:e}){const{t:n}=_t(),{trackJob:a}=x9e(),[i,s]=y.useState(null),[o,l]=y.useState(null),[c,d]=y.useState([]),[u,m]=y.useState(null),[p,f]=y.useState(null),[g,w]=y.useState([]),[b,x]=y.useState(null),[S,k]=y.useState(null),[C,P]=y.useState(null),T=Xe({queryKey:["slicePlates",t.kind,t.id],queryFn:async()=>t.kind==="libraryFile"?ae.getLibraryFilePlates(t.id):ae.getArchivePlates(t.id),staleTime:6e4}),F=!!T.data?.is_multi_plate&&(T.data?.plates?.length??0)>1&&S==null,_=S??1,M=y.useMemo(()=>{const oe=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${t.kind}-${t.id}-p${_}-${oe}`},[t.kind,t.id,_]),H=Xe({queryKey:["sliceFilamentReqs",t.kind,t.id,_],queryFn:async()=>t.kind==="libraryFile"?ae.getLibraryFileFilamentRequirements(t.id,_,M):ae.getArchiveFilamentRequirements(t.id,_,M),enabled:!F,staleTime:6e4}),I=y.useMemo(()=>{const oe=H.data?.filaments??[];return oe.length>0?oe:[{slot_id:1,type:"",color:"",used_grams:0,used_meters:0}]},[H.data]),z=Xe({queryKey:["slicerPresets"],queryFn:()=>ae.getSlicerPresets(),staleTime:6e4,enabled:!T.isLoading&&!F}),L=Xe({queryKey:["slicerBundles"],queryFn:ae.listSlicerBundles,staleTime:6e4,enabled:!T.isLoading&&!F,retry:!1}),Z=y.useMemo(()=>!u||!L.data?null:L.data.find(oe=>oe.id===u)??null,[u,L.data]),ne=Z!=null;y.useEffect(()=>{z.data&&(i==null&&s(dI(z.data,"printer")),o==null&&l(dI(z.data,"process")))},[z.data]),y.useEffect(()=>{if(!z.data)return;const oe=z.data;d(Q=>Q.length===I.length&&Q.every(le=>le!=null)?Q:I.map(le=>v9e(oe,{type:le.type,color:le.color})))},[z.data,I]),y.useEffect(()=>{if(!Z){f(null),w([]);return}f(oe=>oe&&Z.process.includes(oe)?oe:Z.process[0]??null),w(oe=>{if(oe.length===I.length&&oe.every(le=>le!=null))return oe;const Q=Z.filament[0]??null;return I.map((le,pe)=>oe[pe]??Q)})},[Z,I]);const Y=lt({mutationFn:async()=>{let oe;if(ne){if(!Z||!p||g.length===0||g.some(le=>le==null))throw new Error(n("slice.bundleAllRequired"));oe={bundle:{bundle_id:Z.id,printer_name:Z.printer[0]??Z.printer_preset_name,process_name:p,filament_names:g},...S!=null?{plate:S}:{},...C!=null?{bed_type:C}:{}}}else{if(!i||!o||c.length===0||c.some(Q=>Q==null))throw new Error(n("slice.allPresetsRequired"));oe={printer_preset:i,process_preset:o,filament_preset:c[0],filament_presets:c,...S!=null?{plate:S}:{},...C!=null?{bed_type:C}:{}}}return t.kind==="libraryFile"?ae.sliceLibraryFile(t.id,oe):ae.sliceArchive(t.id,oe)},onSuccess:oe=>{a(oe.job_id,t.kind,t.filename),e()},onError:oe=>{const Q=oe instanceof Error?oe.message:String(oe);x(Q)}}),ce=ne?Z!=null&&p!=null&&H.isSuccess&&g.length>0&&g.every(oe=>oe!=null):i!=null&&o!=null&&H.isSuccess&&c.length>0&&c.every(oe=>oe!=null),ue=Y.isPending;return F&&T.data?r.jsx(p5,{plates:T.data.plates,onSelect:oe=>k(oe),onClose:e}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:()=>{ue||e()},children:r.jsxs("div",{className:"w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:oe=>oe.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("h3",{className:"text-white font-medium flex items-center gap-2",children:[r.jsx(uu,{className:"w-4 h-4"}),n("slice.title")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1 truncate",title:t.filename,children:[t.filename,S!=null?` • ${n("archives.platePicker.plateLabel",{index:S})}`:""]})]}),r.jsx("button",{onClick:e,disabled:ue,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50","aria-label":n("common.close"),children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[(T.isLoading||z.isLoading)&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("slice.loadingPresets")]}),z.isError&&r.jsx("div",{className:"text-sm text-red-400",role:"alert",children:n("slice.presetsLoadFailed","Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.")}),z.data&&r.jsxs(r.Fragment,{children:[r.jsx(N9e,{status:z.data.cloud_status}),L.data&&L.data.length>0&&r.jsx(T9e,{bundles:L.data,selectedId:u,onChange:m,disabled:ue}),!ne&&r.jsxs(r.Fragment,{children:[r.jsx(_3,{label:n("slice.printer"),slot:"printer",data:z.data,value:i,onChange:s,disabled:ue}),r.jsx(_3,{label:n("slice.process"),slot:"process",data:z.data,value:o,onChange:l,disabled:ue})]}),ne&&Z&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("slice.printer")}),r.jsx("div",{className:"px-3 py-2 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary text-white text-sm",children:Z.printer_preset_name})]}),r.jsx(aQ,{label:n("slice.process"),options:Z.process,value:p,onChange:f,disabled:ue})]}),r.jsx(P9e,{value:C,onChange:P,disabled:ue}),H.isLoading?r.jsx(_9e,{requestId:M,sourceName:t.filename}):ne&&Z?I.map((oe,Q)=>{const le=oe.used_in_plate!==!1,pe=I.length>1?n("slice.filamentSlot",{index:Q+1,type:oe.type}):n("slice.filament"),he=le?pe:`${pe} ${n("slice.notUsedByPlate")}`;return r.jsx(aQ,{label:he,options:Z.filament,value:g[Q]??null,onChange:we=>w($=>{const J=$.length===I.length?[...$]:I.map((j,E)=>$[E]??null);return J[Q]=we,J}),disabled:ue||!le,swatchColor:I.length>1?oe.color:void 0},`bundle-filament-${Q}`)}):I.map((oe,Q)=>{const le=oe.used_in_plate!==!1,pe=I.length>1?n("slice.filamentSlot",{index:Q+1,type:oe.type}):n("slice.filament"),he=le?pe:`${pe} ${n("slice.notUsedByPlate")}`;return r.jsx(_3,{label:he,slot:"filament",data:z.data,value:c[Q]??null,onChange:we=>d($=>{const J=$.length===I.length?[...$]:I.map((j,E)=>$[E]??null);return J[Q]=we,J}),disabled:ue||!le,swatchColor:I.length>1?oe.color:void 0},`filament-${Q}`)})]}),b&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2",role:"alert",children:b})]}),r.jsxs("div",{className:"flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40",children:[r.jsx("button",{type:"button",onClick:e,disabled:ue,className:"px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50",children:n("common.cancel")}),r.jsx("button",{type:"button",onClick:()=>{x(null),Y.mutate()},disabled:!ce||ue,className:"px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:ue?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("slice.enqueuing")]}):n("slice.action")})]})]})})}function N9e({status:t}){const{t:e}=_t();if(t==="ok")return null;const n={not_authenticated:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:$h,key:"slice.cloud.notAuthenticated",fallback:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets."},expired:{tone:"border-amber-700/40 bg-amber-900/20 text-amber-200",icon:$F,key:"slice.cloud.expired",fallback:"Bambu Cloud session expired — sign in again to refresh your cloud presets."},unreachable:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:$F,key:"slice.cloud.unreachable",fallback:"Bambu Cloud is unreachable right now. Local and standard presets still work."}},{tone:a,icon:i,key:s,fallback:o}=n[t];return r.jsxs("div",{className:`flex items-start gap-2 text-xs rounded-md border p-2 ${a}`,role:"status",children:[r.jsx(i,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),r.jsx("span",{children:e(s,o)})]})}const C9e=[{value:"Cool Plate",labelKey:"slice.bedType.coolPlate",fallback:"Cool Plate"},{value:"Cool Plate (SuperTack)",labelKey:"slice.bedType.coolPlateSuperTack",fallback:"Cool Plate SuperTack"},{value:"Engineering Plate",labelKey:"slice.bedType.engineering",fallback:"Engineering Plate"},{value:"High Temp Plate",labelKey:"slice.bedType.highTemp",fallback:"High Temp Plate"},{value:"Textured PEI Plate",labelKey:"slice.bedType.texturedPEI",fallback:"Textured PEI Plate"},{value:"Smooth PEI Plate",labelKey:"slice.bedType.smoothPEI",fallback:"Smooth PEI Plate"}];function P9e({value:t,onChange:e,disabled:n}){const{t:a}=_t();return r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"block text-xs text-bambu-gray mb-1",children:a("slice.bedType.label")}),r.jsxs("select",{value:t??"",onChange:i=>e(i.target.value===""?null:i.target.value),disabled:n,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:a("slice.bedType.auto")}),C9e.map(i=>r.jsx("option",{value:i.value,children:a(i.labelKey,i.fallback)},i.value))]})]})}function _3({label:t,slot:e,data:n,value:a,onChange:i,disabled:s,swatchColor:o}){const{t:l}=_t(),c=y.useMemo(()=>[{key:"local",tier:"local",label:"slice.tier.local",fallback:"Imported"},{key:"cloud",tier:"cloud",label:"slice.tier.cloud",fallback:"Cloud"},{key:"standard",tier:"standard",label:"slice.tier.standard",fallback:"Standard"}].map(({key:m,label:p,fallback:f})=>({tierLabel:l(p,f),entries:n[m][e]})).filter(m=>m.entries.length>0),[n,e,l]),d=c.reduce((u,m)=>u+m.entries.length,0);return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"flex items-center gap-2 text-xs text-bambu-gray mb-1",children:[o&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary",style:{backgroundColor:o||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:w9e(a),onChange:u=>i(S9e(u.target.value)),disabled:s||d===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:l(d===0?"slice.noPresetsForSlot":"slice.selectPreset")}),c.map(u=>r.jsx("optgroup",{label:u.tierLabel,children:u.entries.map(m=>r.jsx("option",{value:`${m.source}:${m.id}`,children:m.name},`${m.source}:${m.id}`))},u.tierLabel))]})]})}function T9e({bundles:t,selectedId:e,onChange:n,disabled:a}){const{t:i}=_t();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),i("slice.bundle")]}),r.jsxs("select",{value:e??"",onChange:s=>n(s.target.value||null),disabled:a,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:i("slice.bundleNone")}),t.map(s=>r.jsx("option",{value:s.id,children:s.printer_preset_name},s.id))]})]})}function aQ({label:t,options:e,value:n,onChange:a,disabled:i,swatchColor:s}){const{t:o}=_t();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[s&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-sm border border-black/20",style:{backgroundColor:s||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:n??"",onChange:l=>a(l.target.value||null),disabled:i||e.length===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:e.length===0?o("slice.noPresetsForSlot"):o("slice.selectPreset")}),e.map(l=>r.jsx("option",{value:l,children:l},l))]})]})}function A9e(){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 jm(t,e="bambu_studio"){let n;const a=encodeURIComponent(t);e==="orcaslicer"?n=`orcaslicer://open?file=${a}`:A9e()==="macos"?n=`bambustudioopen://${a}`:n=`bambustudio://open?file=${a}`;const i=document.createElement("a");i.href=n,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const Bd="/img/bed",j9e={"cool plate":{icon:`${Bd}/bed_cool.png`,label:"Cool Plate"},"pc plate":{icon:`${Bd}/bed_cool.png`,label:"Cool Plate"},"cool plate (supertack)":{icon:`${Bd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"supertack plate":{icon:`${Bd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"bambu cool plate supertack":{icon:`${Bd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"engineering plate":{icon:`${Bd}/bed_engineering.png`,label:"Engineering Plate"},"high temp plate":{icon:`${Bd}/bed_high_templ.png`,label:"High Temp Plate"},"textured pei plate":{icon:`${Bd}/bed_pei.png`,label:"Textured PEI Plate"},"pei plate":{icon:`${Bd}/bed_pei.png`,label:"PEI Plate"},"smooth pei plate":{icon:`${Bd}/bed_pei_cool.png`,label:"Smooth PEI Plate"}};function lse(t){return t?j9e[t.trim().toLowerCase()]??null:null}const iQ=768;function cse(){const[t,e]=y.useState(()=>typeof window<"u"?window.innerWidth<iQ:!1);return y.useEffect(()=>{const n=window.matchMedia(`(max-width: ${iQ-1}px)`),a=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[]),t}function M9e({onClose:t,initialFiles:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),s=y.useRef(null),[o,l]=y.useState(()=>e?.filter(P=>P.name.endsWith(".3mf")).map(P=>({file:P,status:"pending"}))||[]),[c,d]=y.useState(!1),[u,m]=y.useState(null);y.useEffect(()=>{const P=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]);const p=lt({mutationFn:P=>ae.uploadArchivesBulk(P),onSuccess:P=>{m(P),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(A=>{const F=P.results.find(M=>M.filename===A.file.name),_=P.errors.find(M=>M.filename===A.file.name);return F?{...A,status:"success",archiveId:F.id}:_?{...A,status:"error",error:_.error}:A})),P.failed===0?i(`${P.uploaded} file${P.uploaded!==1?"s":""} uploaded`):P.uploaded===0?i(`Failed to upload ${P.failed} file${P.failed!==1?"s":""}`,"error"):i(`${P.uploaded} uploaded, ${P.failed} failed`,"warning")},onError:()=>{l(P=>P.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=y.useCallback(P=>{P.preventDefault(),d(!0)},[]),g=y.useCallback(P=>{P.preventDefault(),d(!1)},[]),w=y.useCallback(P=>{P.preventDefault(),d(!1);const T=Array.from(P.dataTransfer.files).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))])},[]),b=y.useCallback(P=>{const T=Array.from(P.target.files||[]).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),x=y.useCallback(P=>{l(T=>T.filter((A,F)=>F!==P))},[]),S=()=>{if(o.length===0)return;const P=o.filter(T=>T.status==="pending");P.length!==0&&(l(T=>T.map(A=>A.status==="pending"?{...A,status:"uploading"}:A)),p.mutate(P.map(T=>T.file)))},k=o.filter(P=>P.status==="pending").length,C=p.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:r.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4",children:r.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:g,onDrop:w,children:[r.jsx(_a,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),r.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),r.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),r.jsx(je,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),r.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),r.jsx("div",{className:"px-4 pb-4",children:r.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&r.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:r.jsx("div",{className:"space-y-2",children:o.map((P,T)=>r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(NT,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"flex-1 text-white text-sm truncate",children:P.file.name}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[(P.file.size/(1024*1024)).toFixed(1)," MB"]}),P.status==="pending"&&r.jsx("button",{onClick:()=>x(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:r.jsx(Vt,{className:"w-4 h-4"})}),P.status==="uploading"&&r.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),P.status==="success"&&r.jsx(xr,{className:"w-4 h-4 text-bambu-green"}),P.status==="error"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-red-400",children:P.error}),r.jsx(Ha,{className:"w-4 h-4 text-red-400"})]})]},`${P.file.name}-${T}`))})}),u&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&r.jsxs(r.Fragment,{children:[", ",r.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&r.jsx(je,{onClick:S,disabled:k===0||C,className:"flex-1",children:C?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-4 h-4"}),n("uploadModal.upload")," ",k>0&&`(${k})`]})})]})]})})})}const E9e=365;function D9e({onClose:t,initialDays:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),[s,o]=y.useState(e??E9e),[l,c]=y.useState(!1),[d,u]=y.useState(s);y.useEffect(()=>{const x=window.setTimeout(()=>u(s),300);return()=>window.clearTimeout(x)},[s]);const m=Xe({queryKey:["archive-purge-preview",d,l],queryFn:()=>ae.previewArchivePurge(d,l),enabled:d>=1}),p=lt({mutationFn:()=>ae.executeArchivePurge(s,l),onSuccess:x=>{i(n("archivePurge.toast.success",{count:x.deleted}),"success"),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archive-stats"]}),t()},onError:x=>i(x.message||n("archivePurge.toast.failed"),"error")});y.useEffect(()=>{const x=S=>{S.key==="Escape"&&!p.isPending&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,p.isPending]);const f=m.data,g=f?.count??0,w=f?.total_bytes??0,b=g>0&&!p.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(en,{className:"w-5 h-5"}),n("archivePurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":n("common.close"),disabled:p.isPending,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"archive-purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:n("archivePurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"archive-purge-days",type:"number",min:1,max:3650,value:s,onChange:x=>o(Math.max(1,Math.min(3650,parseInt(x.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.days")})]})]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:n("archivePurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:n("archivePurge.effect1")}),r.jsx("li",{children:n("archivePurge.effect2")}),r.jsx("li",{children:n("archivePurge.effect3")}),r.jsx("li",{children:n("archivePurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:m.isLoading||m.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"})," ",n("archivePurge.previewLoading")]}):m.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:m.error?.message??n("archivePurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:n("archivePurge.previewSummary",{count:g,size:ls(w)})}),f?.sample_filenames&&f.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[f.sample_filenames.map(x=>r.jsx("li",{className:"truncate",children:x},x)),g>f.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:n("archivePurge.andMore",{count:g-f.sample_filenames.length})})]})]})}),r.jsxs("label",{className:"flex gap-2 items-start rounded border border-gray-200 dark:border-gray-700 px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("input",{type:"checkbox",checked:l,onChange:x=>c(x.target.checked),disabled:p.isPending,className:"mt-0.5 shrink-0"}),r.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300",children:[r.jsx("span",{className:"font-medium block mb-0.5",children:n("archivePurge.purgeStatsLabel")}),r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:n("archivePurge.purgeStatsHint")})]})]}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:n("archivePurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(je,{variant:"secondary",onClick:t,disabled:p.isPending,children:n("common.cancel")}),r.jsx(je,{variant:"danger",disabled:!b,onClick:()=>p.mutate(),children:p.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin mr-1"}),n("archivePurge.purging")]}):n("archivePurge.confirmCta",{count:g})})]})]})})}function F9e(t){if(!t||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 L9e(t){return t?new Date(t).toLocaleString():"—"}function dse({archiveId:t}){const{t:e}=_t(),{data:n,isLoading:a}=Xe({queryKey:["archive-runs",t],queryFn:()=>ae.getArchiveRuns(t)});if(a)return r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ft,{className:"w-5 h-5 text-bambu-gray animate-spin"})});const i=n?.items||[];return i.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:e("archives.runLog.empty")}):r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-xs",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.date")}),r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.status")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.duration")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.filament")}),r.jsx("th",{className:"text-right py-1.5 font-medium",children:e("archives.runLog.col.cost")})]})}),r.jsx("tbody",{children:i.map(s=>{const o=s.status==="completed"?"text-bambu-green":s.status==="failed"?"text-red-400":"text-bambu-gray";return r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/40 last:border-0",children:[r.jsx("td",{className:"py-1.5 pr-2 text-bambu-gray-light",children:L9e(s.started_at||s.created_at)}),r.jsxs("td",{className:`py-1.5 pr-2 font-medium ${o}`,children:[e(`archives.runLog.status.${s.status}`,{defaultValue:s.status}),s.failure_reason&&r.jsx("span",{className:"block text-[10px] text-bambu-gray font-normal",children:s.failure_reason})]}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:F9e(s.duration_seconds)}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:s.filament_used_grams!=null?`${s.filament_used_grams.toFixed(1)} g`:"—"}),r.jsx("td",{className:"py-1.5 text-right text-bambu-gray-light",children:s.cost!=null?s.cost.toFixed(2):"—"})]},s.id)})})]})})}const R9e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],I9e=["completed","failed","aborted","printing"];function use({archive:t,onClose:e,existingTags:n=[]}){const{t:a}=_t();y.useEffect(()=>{const E=B=>{B.key==="Escape"&&e()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[e]);const i=tn(),[s,o]=y.useState(t.print_name||""),[l,c]=y.useState(t.printer_id),[d,u]=y.useState(t.project_id??null),[m,p]=y.useState(t.notes||""),[f,g]=y.useState(t.tags||""),[w,b]=y.useState(t.failure_reason||""),[x,S]=y.useState(t.status),[k,C]=y.useState(t.quantity??1),[P,T]=y.useState(t.photos||[]),[A,F]=y.useState(t.external_url||""),[_,M]=y.useState(!1),[H,I]=y.useState(!1),z=y.useRef(null),L=y.useRef(null),Z=y.useRef(null),{data:ne}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:Y}=Xe({queryKey:["projects"],queryFn:()=>ae.getProjects(),select:E=>[...E].sort((B,W)=>B.name.localeCompare(W.name))}),{data:ce}=Xe({queryKey:["tags"],queryFn:ae.getTags,enabled:n.length===0}),ue=n.length>0?n:ce?.map(E=>E.name)||[],oe=f.split(",").map(E=>E.trim()).filter(Boolean),Q=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),le=ue.filter(E=>!oe.includes(E)&&(Q===""||E.toLowerCase().includes(Q))),pe=E=>{let B;if(Q&&!ue.includes(Q)?B=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(W=>W.trim()).filter(Boolean):[]:B=oe,!B.includes(E)){const W=[...B,E].join(", ");g(W)}Z.current!==null&&clearTimeout(Z.current),z.current?.focus()},he=E=>{const B=oe.filter(W=>W!==E).join(", ");g(B)},we=lt({mutationFn:E=>ae.updateArchive(t.id,E),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async E=>{const B=E.target.files?.[0];if(B){M(!0);try{const W=await ae.uploadArchivePhoto(t.id,B);T(W.photos),i.invalidateQueries({queryKey:["archives"]})}catch(W){console.error("Failed to upload photo:",W)}finally{M(!1),L.current&&(L.current.value="")}}},J=async E=>{try{const B=await ae.deleteArchivePhoto(t.id,E);T(B.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(B){console.error("Failed to delete photo:",B)}},j=E=>{E.preventDefault();const B={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:k,external_url:A||null};x!==t.status&&(B.status=x),x==="failed"||x==="aborted"?B.failure_reason=w||void 0:(t.status==="failed"||t.status==="aborted")&&(B.failure_reason=null),we.mutate(B)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.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:E=>E.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("editArchive.title")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:j,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("archives.runLog.title")}),r.jsx(dse,{archiveId:t.id})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.name")}),r.jsx("input",{type:"text",value:s,onChange:E=>o(E.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:a("editArchive.namePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.printer")}),r.jsxs("select",{value:l??"",onChange:E=>c(E.target.value?Number(E.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:[r.jsx("option",{value:"",children:a("editArchive.noPrinter")}),ne?.map(E=>r.jsx("option",{value:E.id,children:E.name},E.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(to,{className:"w-4 h-4 inline mr-1"}),a("editArchive.project")]}),r.jsxs("select",{value:d??"",onChange:E=>u(E.target.value?Number(E.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:[r.jsx("option",{value:"",children:a("editArchive.noProject")}),Y?.map(E=>r.jsx("option",{value:E.id,children:E.name},E.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Qbe,{className:"w-4 h-4 inline mr-1"}),a("editArchive.itemsPrinted")]}),r.jsx("input",{type:"number",min:1,value:k,onChange:E=>C(Math.max(1,parseInt(E.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.itemsPrintedHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.notes")}),r.jsx("textarea",{value:m,onChange:E=>p(E.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:a("editArchive.notesPlaceholder")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Qy,{className:"w-4 h-4 inline mr-1"}),a("editArchive.externalLink")]}),r.jsx("input",{type:"url",value:A,onChange:E=>F(E.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/..."}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.externalLinkHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.tags")}),oe.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(E=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[r.jsx(Vm,{className:"w-3 h-3"}),E,r.jsx("button",{type:"button",onClick:()=>he(E),className:"ml-0.5 text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-3 h-3"})})]},E))}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:z,type:"text",value:f,onChange:E=>g(E.target.value),onFocus:()=>{Z.current!==null&&clearTimeout(Z.current),I(!0)},onBlur:()=>{Z.current=window.setTimeout(()=>I(!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?a("editArchive.addMoreTags"):a("editArchive.tagsPlaceholder")}),H&&le.length>0&&r.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:[r.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[Q?a("editArchive.matchingTags",{query:Q}):a("editArchive.existingTags")," ",a("editArchive.clickToAdd")]}),r.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:le.map(E=>r.jsx("button",{type:"button",onClick:()=>pe(E),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:E},E))})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.status")}),r.jsx("select",{value:x,onChange:E=>{S(E.target.value),E.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:I9e.map(E=>r.jsx("option",{value:E,children:a(`editArchive.statuses.${E}`)},E))})]}),(x==="failed"||x==="aborted")&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.failureReason")}),r.jsxs("select",{value:w,onChange:E=>b(E.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:[r.jsx("option",{value:"",children:a("editArchive.selectReason")}),R9e.map(E=>r.jsx("option",{value:a(`editArchive.failureReasons.${E}`),children:a(`editArchive.failureReasons.${E}`)},E))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(by,{className:"w-4 h-4 inline mr-1"}),a("editArchive.photos")]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[P.map(E=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ae.getArchivePhotoUrl(t.id,E),alt:a("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:()=>J(E),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(en,{className:"w-3 h-3 text-white"})})]},E)),r.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:[r.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:_}),_?r.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):r.jsx(er,{className:"w-6 h-6 text-bambu-gray"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("editArchive.photosHelp")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("common.cancel")}),r.jsxs(je,{type:"submit",disabled:we.isPending,className:"flex-1",children:[r.jsx(ds,{className:"w-4 h-4"}),we.isPending?a("common.saving"):a("common.save")]})]})]})]})})}function mse({archiveId:t,archiveName:e,onClose:n}){const{t:a}=_t();return y.useEffect(()=>{const i=s=>{s.key==="Escape"&&n()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[n]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-2xl max-h-[85vh] flex flex-col",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Vh,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsx("h2",{className:"text-lg font-semibold text-white truncate",title:e||"",children:a("archives.runLog.modalTitle",{name:e||a("archives.runLog.modalTitleFallback")})})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:a("common.close"),children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-6 overflow-y-auto flex-1",children:r.jsx(dse,{archiveId:t})})]})})}function O9e({items:t,searchPlaceholder:e,onClose:n,className:a,onMouseEnter:i,onMouseLeave:s}){const[o,l]=y.useState(""),c=y.useRef(null);y.useEffect(()=>{if(e){const m=window.setTimeout(()=>c.current?.focus(),0);return()=>window.clearTimeout(m)}},[e]);const d=o.trim().toLowerCase(),u=e&&d?t.filter(m=>m.label.toLowerCase().includes(d)):t;return r.jsxs("div",{className:a,onMouseEnter:i,onMouseLeave:s,children:[e&&r.jsx("div",{className:"sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none"}),r.jsx("input",{ref:c,type:"text",value:o,onChange:m=>l(m.target.value),onKeyDown:m=>{if(m.key==="Enter"){const p=u.find(f=>!f.disabled);p&&(p.onClick(),n())}},placeholder:e,className:"w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})}),u.map((m,p)=>r.jsxs("button",{onClick:()=>{m.disabled||(m.onClick(),n())},disabled:m.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${m.disabled?"text-bambu-gray cursor-not-allowed":m.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[m.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:m.icon}),r.jsx("span",{className:"flex-1 truncate",children:m.label})]},p)),e&&u.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray text-center italic",children:"—"})]})}function pse({x:t,y:e,items:n,onClose:a}){const i=y.useRef(null),[s,o]=y.useState(null),l=y.useRef(null),[c,d]=y.useState({x:t,y:e,visible:!1}),[u,m]=y.useState(!1),[p,f]=y.useState({});y.useEffect(()=>{const b=k=>{i.current&&!i.current.contains(k.target)&&a()},x=k=>{k.key==="Escape"&&a()},S=k=>{i.current&&i.current.contains(k.target)||a()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",x),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",x),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[a]),y.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),x=window.innerWidth,S=window.innerHeight,k=8;let C=t,P=e;t+b.width>x-k&&(C=Math.max(k,x-b.width-k)),C<k&&(C=k),e+b.height>S-k&&(P=Math.max(k,S-b.height-k)),P<k&&(P=k);const T=180,A=x-C-b.width,F=C;m(A<T&&F>T),d({x:C,y:P,visible:!0})}},[t,e]);const g=(b,x)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=x.getBoundingClientRect(),k=window.innerHeight,C=300,A=k-S.top-8<C&&S.top>C;f(F=>({...F,[b]:A?"bottom":"top"})),o(b)},w=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return r.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((b,x)=>{if(b.divider)return r.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},x);const S=b.submenu&&b.submenu.length>0;return r.jsxs("div",{className:"relative",onMouseEnter:k=>S&&g(x,k.currentTarget),onMouseLeave:()=>S&&w(),children:[r.jsxs("button",{onMouseEnter:k=>S&&g(x,k.currentTarget.parentElement),onClick:()=>{S?o(s===x?null:x):b.disabled||(b.onClick(),a())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===x?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),r.jsx("span",{className:"flex-1",children:b.label}),S&&r.jsx(qa,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===x&&r.jsx(O9e,{items:b.submenu,searchPlaceholder:b.submenuSearchPlaceholder,onClose:a,className:`absolute min-w-[200px] 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[x]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>w()})]},x)})})}function z9e({selectedIds:t,existingTags:e,onClose:n}){const a=tn(),{showToast:i}=on(),[s,o]=y.useState(""),[l,c]=y.useState(new Set),[d,u]=y.useState("add");y.useEffect(()=>{const w=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[n]);const m=lt({mutationFn:async()=>{const w=Array.from(l);let b=0;for(const x of t)try{const S=await ae.getArchive(x),k=S.tags?S.tags.split(",").map(P=>P.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...k,...w])]:C=k.filter(P=>!l.has(P)),await ae.updateArchive(x,{tags:C.join(", ")}),b++}catch(S){throw console.error(`Failed to update archive ${x}:`,S),new Error(`Failed on archive ${x}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:b,mode:d,tags:w}},onSuccess:({count:w,mode:b,tags:x})=>{a.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${x.length} tag${x.length!==1?"s":""} ${b==="add"?"to":"from"} ${w} archive${w!==1?"s":""}`),n()},onError:w=>{i(w.message||"Failed to update tags","error")}}),p=w=>{c(b=>{const x=new Set(b);return x.has(w)?x.delete(w):x.add(w),x})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(w=>new Set([...w,s.trim()])),o(""))},g=w=>{w.key==="Enter"&&(w.preventDefault(),f())};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-md",children:r.jsxs(Et,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Vm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),r.jsx(je,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&r.jsxs("div",{className:"flex gap-2",children:[r.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:w=>o(w.target.value),onKeyDown:g}),r.jsx(je,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:r.jsx(er,{className:"w-4 h-4"})})]}),e.length>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(w=>r.jsx("button",{onClick:()=>p(w),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(w)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:w},w))})]}),l.size>0&&r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(w=>r.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:[w,r.jsx("button",{onClick:()=>p(w),className:"hover:opacity-70",children:r.jsx(Vt,{className:"w-3 h-3"})})]},w))})]})]}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(je,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),r.jsx(je,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx(Vm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function U9e({selectedIds:t,onClose:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),[s,o]=y.useState(""),{data:l,isLoading:c}=Xe({queryKey:["projects"],queryFn:()=>ae.getProjects()}),d=y.useMemo(()=>l?[...l].sort((x,S)=>x.name.localeCompare(S.name)):void 0,[l]),u=s.trim().toLowerCase(),m=u?d?.filter(x=>x.name.toLowerCase().includes(u)):d,p=(d?.length??0)>5;y.useEffect(()=>{const x=S=>{S.key==="Escape"&&e()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e]);const f=()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),a.invalidateQueries({queryKey:["project"]}),a.invalidateQueries({queryKey:["project-archives"]})},g=lt({mutationFn:async x=>(await ae.addArchivesToProject(x,t),x),onSuccess:x=>{const S=l?.find(k=>k.id===x);f(),i(`Added ${t.length} archive${t.length!==1?"s":""} to "${S?.name}"`),e()},onError:()=>{i("Failed to assign project","error")}}),w=lt({mutationFn:async()=>{for(const x of t)await ae.updateArchive(x,{project_id:null});return t.length},onSuccess:x=>{f(),i(`Removed ${x} archive${x!==1?"s":""} from project`),e()},onError:()=>{i("Failed to remove from project","error")}}),b=g.isPending||w.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:r.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(to,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:b,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),c?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("button",{onClick:()=>w.mutate(),disabled:b,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:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:r.jsx($r,{className:"w-4 h-4 text-red-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),r.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),w.isPending&&r.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),d&&d.length>0&&r.jsxs("div",{className:"flex items-center gap-2 py-2",children:[r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),p&&r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:s,onChange:x=>o(x.target.value),placeholder:n("archives.menu.searchProjects"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-sm focus:border-bambu-green focus:outline-none"})]}),m?.map(x=>r.jsxs("button",{onClick:()=>g.mutate(x.id),disabled:b,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:[r.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:x.color?`${x.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:r.jsx(to,{className:"w-4 h-4",style:{color:x.color||"rgb(var(--bambu-green))"}})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium truncate",children:x.name}),r.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[x.archive_count," archive",x.archive_count!==1?"s":"",x.status&&` • ${x.status}`]})]}),g.isPending&&g.variables===x.id&&r.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},x.id)),(!d||d.length===0)&&r.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."}),d&&d.length>0&&m?.length===0&&r.jsx("p",{className:"text-center text-bambu-gray text-sm py-4",children:"—"})]})]}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:r.jsx(je,{variant:"secondary",onClick:e,className:"flex-1",disabled:b,children:"Cancel"})})]})})})}function B9e(t,e){return new Date(t,e+1,0).getDate()}function H9e(t,e){return new Date(t,e,1).getDay()}const q9e=["January","February","March","April","May","June","July","August","September","October","November","December"],$9e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function V9e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const a=new Date,[i,s]=y.useState(a.getMonth()),[o,l]=y.useState(a.getFullYear()),[c,d]=y.useState(null),[u,m]=y.useState(null),p=y.useMemo(()=>{const P=new Map;return t.forEach(T=>{const A=Yn(T.completed_at||T.created_at)||new Date,F=`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`,_=P.get(F)||[];_.push(T),P.set(F,_)}),P},[t]),f=B9e(o,i),g=H9e(o,i),w=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},x=()=>{s(a.getMonth()),l(a.getFullYear())},S=[];for(let P=0;P<g;P++)S.push(null);for(let P=1;P<=f;P++)S.push(P);const k=c?p.get(c)||[]:[],C=P=>{P!==c&&m(null),d(P)};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("button",{onClick:w,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Xo,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:[q9e[i]," ",o]}),r.jsx("button",{onClick:x,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"})]}),r.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(qa,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:$9e.map(P=>r.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:P},P))}),r.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((P,T)=>{if(P===null)return r.jsx("div",{className:"aspect-square"},`empty-${T}`);const A=`${o}-${String(i+1).padStart(2,"0")}-${String(P).padStart(2,"0")}`,F=p.get(A)||[],_=F.length>0,M=P===a.getDate()&&i===a.getMonth()&&o===a.getFullYear(),H=A===c,I=F.filter(L=>L.status==="completed").length,z=F.filter(L=>L.status==="failed").length;return r.jsxs("button",{onClick:()=>C(H?null:A),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":M?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":_?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[r.jsx("span",{className:`text-sm font-medium ${M&&!H?"text-bambu-green":""}`,children:P}),_&&r.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${z>0&&I===0?"bg-red-400":z>0?"bg-yellow-400":"bg-green-400"}`}),r.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},P)})}),r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(P=>{const T=Yn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(P=>{const T=Yn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="completed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(P=>{const T=Yn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="failed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),r.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?r.jsxs(r.Fragment,{children:[r.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"})}),k.length>0?r.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:k.map(P=>{const T=P.id===u||P.id===n;return r.jsxs("button",{onClick:()=>{m(P.id),e?.(P)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[P.thumbnail_path?r.jsx("img",{src:ae.getArchiveThumbnail(P.id),alt:"",className:"w-12 h-12 rounded object-cover"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:P.print_name||P.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:P.status==="failed"?"text-red-400":"text-green-400",children:P.status==="failed"?"Failed":"Completed"}),P.filament_color&&r.jsx("div",{className:"flex gap-0.5",children:P.filament_color.split(",").map((A,F)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:A}},F))})]})]})]},P.id)})}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function hse({archiveId:t,archiveName:e,onClose:n}){const a=ae.getArchiveQRCodeUrl(t,300);y.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=a,s.download=`${e}_qrcode.png`,s.click()};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 flex flex-col items-center",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),r.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:r.jsx("img",{src:a,alt:"QR Code",className:"w-64 h-64"})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),r.jsxs(je,{onClick:i,className:"w-full",children:[r.jsx(Zr,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function fse({archiveId:t,archiveName:e,photos:n,onClose:a,onDelete:i}){const[s,o]=y.useState(0),[l,c]=y.useState(!1);if(y.useEffect(()=>{const f=g=>{g.key==="Escape"&&a(),g.key==="ArrowLeft"&&o(w=>Math.max(0,w-1)),g.key==="ArrowRight"&&o(w=>Math.min(n.length-1,w+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,n.length]),y.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return a(),null;const d=n[s],u=ae.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 r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:a,children:[r.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:m,children:[r.jsx(Zr,{className:"w-4 h-4"}),"Download"]}),i&&r.jsx(je,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:r.jsx(en,{className:"w-4 h-4"})}),r.jsx("button",{onClick:a,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-6 h-6"})})]})]}),r.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&r.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:r.jsx(Xo,{className:"w-8 h-8 text-white"})}),r.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&&r.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:r.jsx(qa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&r.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,g)=>r.jsx("button",{onClick:()=>o(g),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${g===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:r.jsx("img",{src:ae.getArchivePhotoUrl(t,f),alt:`Thumbnail ${g+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&r.jsx(wn,{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:gse,setPrototypeOf:sQ,isFrozen:G9e,getPrototypeOf:W9e,getOwnPropertyDescriptor:K9e}=Object;let{freeze:No,seal:Pc,create:B0}=Object,{apply:uI,construct:mI}=typeof Reflect<"u"&&Reflect;No||(No=function(e){return e});Pc||(Pc=function(e){return e});uI||(uI=function(e,n){for(var a=arguments.length,i=new Array(a>2?a-2:0),s=2;s<a;s++)i[s-2]=arguments[s];return e.apply(n,i)});mI||(mI=function(e){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i<n;i++)a[i-1]=arguments[i];return new e(...a)});const _0=Co(Array.prototype.forEach),Q9e=Co(Array.prototype.lastIndexOf),oQ=Co(Array.prototype.pop),k0=Co(Array.prototype.push),Y9e=Co(Array.prototype.splice),RN=Co(String.prototype.toLowerCase),k3=Co(String.prototype.toString),N3=Co(String.prototype.match),Dx=Co(String.prototype.replace),X9e=Co(String.prototype.indexOf),Z9e=Co(String.prototype.trim),td=Co(Object.prototype.hasOwnProperty),ho=Co(RegExp.prototype.test),N0=J9e(TypeError);function Co(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i<n;i++)a[i-1]=arguments[i];return uI(t,e,a)}}function J9e(t){return function(){for(var e=arguments.length,n=new Array(e),a=0;a<e;a++)n[a]=arguments[a];return mI(t,n)}}function mr(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:RN;sQ&&sQ(t,null);let a=e.length;for(;a--;){let i=e[a];if(typeof i=="string"){const s=n(i);s!==i&&(G9e(e)||(e[a]=s),i=s)}t[i]=!0}return t}function eWe(t){for(let e=0;e<t.length;e++)td(t,e)||(t[e]=null);return t}function qd(t){const e=B0(null);for(const[n,a]of gse(t))td(t,n)&&(Array.isArray(a)?e[n]=eWe(a):a&&typeof a=="object"&&a.constructor===Object?e[n]=qd(a):e[n]=a);return e}function C0(t,e){for(;t!==null;){const a=K9e(t,e);if(a){if(a.get)return Co(a.get);if(typeof a.value=="function")return Co(a.value)}t=W9e(t)}function n(){return null}return n}const lQ=No(["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"]),C3=No(["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"]),P3=No(["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"]),tWe=No(["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"]),T3=No(["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"]),nWe=No(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),cQ=No(["#text"]),dQ=No(["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"]),A3=No(["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"]),uQ=No(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","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"]),W1=No(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),rWe=Pc(/\{\{[\w\W]*|[\w\W]*\}\}/gm),aWe=Pc(/<%[\w\W]*|[\w\W]*%>/gm),iWe=Pc(/\$\{[\w\W]*/gm),sWe=Pc(/^data-[\-\w.\u00B7-\uFFFF]+$/),oWe=Pc(/^aria-[\-\w]+$/),bse=Pc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),lWe=Pc(/^(?:\w+script|data):/i),cWe=Pc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xse=Pc(/^html$/i),dWe=Pc(/^[a-z][.\w]*(-[.\w]+)+$/i);var mQ=Object.freeze({__proto__:null,ARIA_ATTR:oWe,ATTR_WHITESPACE:cWe,CUSTOM_ELEMENT:dWe,DATA_ATTR:sWe,DOCTYPE_NAME:xse,ERB_EXPR:aWe,IS_ALLOWED_URI:bse,IS_SCRIPT_OR_DATA:lWe,MUSTACHE_EXPR:rWe,TMPLIT_EXPR:iWe});const P0={element:1,text:3,progressingInstruction:7,comment:8,document:9},uWe=function(){return typeof window>"u"?null:window},mWe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let a=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(a=n.getAttribute(i));const s="dompurify"+(a?"#"+a:"");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}},pQ=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function yse(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:uWe();const e=Je=>yse(Je);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==P0.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const a=n,i=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,g=c.prototype,w=C0(g,"cloneNode"),b=C0(g,"remove"),x=C0(g,"nextSibling"),S=C0(g,"childNodes"),k=C0(g,"parentNode");if(typeof o=="function"){const Je=n.createElement("template");Je.content&&Je.content.ownerDocument&&(n=Je.content.ownerDocument)}let C,P="";const{implementation:T,createNodeIterator:A,createDocumentFragment:F,getElementsByTagName:_}=n,{importNode:M}=a;let H=pQ();e.isSupported=typeof gse=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:z,TMPLIT_EXPR:L,DATA_ATTR:Z,ARIA_ATTR:ne,IS_SCRIPT_OR_DATA:Y,ATTR_WHITESPACE:ce,CUSTOM_ELEMENT:ue}=mQ;let{IS_ALLOWED_URI:oe}=mQ,Q=null;const le=mr({},[...lQ,...C3,...P3,...T3,...cQ]);let pe=null;const he=mr({},[...dQ,...A3,...uQ,...W1]);let we=Object.seal(B0(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,J=null;const j=Object.seal(B0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let E=!0,B=!0,W=!1,O=!0,ie=!1,U=!0,G=!1,K=!1,X=!1,se=!1,te=!1,fe=!1,de=!0,me=!1;const q="user-content-";let R=!0,re=!1,be={},ye=null;const _e=mr({},["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 xe=null;const ge=mr({},["audio","video","img","source","image","track"]);let Me=null;const Be=mr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Fe="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let We=Re,ze=!1,st=null;const Ee=mr({},[Fe,Oe,Re],k3);let it=mr({},["mi","mo","mn","ms","mtext"]),Ce=mr({},["annotation-xml"]);const Ze=mr({},["title","style","font","a","script"]);let Ie=null;const ke=["application/xhtml+xml","text/html"],Ve="text/html";let rt=null,Qe=null;const Te=n.createElement("form"),tt=function(De){return De instanceof RegExp||De instanceof Function},ot=function(){let De=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Qe&&Qe===De)){if((!De||typeof De!="object")&&(De={}),De=qd(De),Ie=ke.indexOf(De.PARSER_MEDIA_TYPE)===-1?Ve:De.PARSER_MEDIA_TYPE,rt=Ie==="application/xhtml+xml"?k3:RN,Q=td(De,"ALLOWED_TAGS")?mr({},De.ALLOWED_TAGS,rt):le,pe=td(De,"ALLOWED_ATTR")?mr({},De.ALLOWED_ATTR,rt):he,st=td(De,"ALLOWED_NAMESPACES")?mr({},De.ALLOWED_NAMESPACES,k3):Ee,Me=td(De,"ADD_URI_SAFE_ATTR")?mr(qd(Be),De.ADD_URI_SAFE_ATTR,rt):Be,xe=td(De,"ADD_DATA_URI_TAGS")?mr(qd(ge),De.ADD_DATA_URI_TAGS,rt):ge,ye=td(De,"FORBID_CONTENTS")?mr({},De.FORBID_CONTENTS,rt):_e,$=td(De,"FORBID_TAGS")?mr({},De.FORBID_TAGS,rt):qd({}),J=td(De,"FORBID_ATTR")?mr({},De.FORBID_ATTR,rt):qd({}),be=td(De,"USE_PROFILES")?De.USE_PROFILES:!1,E=De.ALLOW_ARIA_ATTR!==!1,B=De.ALLOW_DATA_ATTR!==!1,W=De.ALLOW_UNKNOWN_PROTOCOLS||!1,O=De.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=De.SAFE_FOR_TEMPLATES||!1,U=De.SAFE_FOR_XML!==!1,G=De.WHOLE_DOCUMENT||!1,se=De.RETURN_DOM||!1,te=De.RETURN_DOM_FRAGMENT||!1,fe=De.RETURN_TRUSTED_TYPE||!1,X=De.FORCE_BODY||!1,de=De.SANITIZE_DOM!==!1,me=De.SANITIZE_NAMED_PROPS||!1,R=De.KEEP_CONTENT!==!1,re=De.IN_PLACE||!1,oe=De.ALLOWED_URI_REGEXP||bse,We=De.NAMESPACE||Re,it=De.MATHML_TEXT_INTEGRATION_POINTS||it,Ce=De.HTML_INTEGRATION_POINTS||Ce,we=De.CUSTOM_ELEMENT_HANDLING||B0(null),De.CUSTOM_ELEMENT_HANDLING&&tt(De.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(we.tagNameCheck=De.CUSTOM_ELEMENT_HANDLING.tagNameCheck),De.CUSTOM_ELEMENT_HANDLING&&tt(De.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(we.attributeNameCheck=De.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),De.CUSTOM_ELEMENT_HANDLING&&typeof De.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(we.allowCustomizedBuiltInElements=De.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(B=!1),te&&(se=!0),be&&(Q=mr({},cQ),pe=B0(null),be.html===!0&&(mr(Q,lQ),mr(pe,dQ)),be.svg===!0&&(mr(Q,C3),mr(pe,A3),mr(pe,W1)),be.svgFilters===!0&&(mr(Q,P3),mr(pe,A3),mr(pe,W1)),be.mathMl===!0&&(mr(Q,T3),mr(pe,uQ),mr(pe,W1))),j.tagCheck=null,j.attributeCheck=null,De.ADD_TAGS&&(typeof De.ADD_TAGS=="function"?j.tagCheck=De.ADD_TAGS:(Q===le&&(Q=qd(Q)),mr(Q,De.ADD_TAGS,rt))),De.ADD_ATTR&&(typeof De.ADD_ATTR=="function"?j.attributeCheck=De.ADD_ATTR:(pe===he&&(pe=qd(pe)),mr(pe,De.ADD_ATTR,rt))),De.ADD_URI_SAFE_ATTR&&mr(Me,De.ADD_URI_SAFE_ATTR,rt),De.FORBID_CONTENTS&&(ye===_e&&(ye=qd(ye)),mr(ye,De.FORBID_CONTENTS,rt)),De.ADD_FORBID_CONTENTS&&(ye===_e&&(ye=qd(ye)),mr(ye,De.ADD_FORBID_CONTENTS,rt)),R&&(Q["#text"]=!0),G&&mr(Q,["html","head","body"]),Q.table&&(mr(Q,["tbody"]),delete $.tbody),De.TRUSTED_TYPES_POLICY){if(typeof De.TRUSTED_TYPES_POLICY.createHTML!="function")throw N0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof De.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw N0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=De.TRUSTED_TYPES_POLICY,P=C.createHTML("")}else C===void 0&&(C=mWe(f,i)),C!==null&&typeof P=="string"&&(P=C.createHTML(""));No&&No(De),Qe=De}},Tt=mr({},[...C3,...P3,...tWe]),Ut=mr({},[...T3,...nWe]),bt=function(De){let mt=k(De);(!mt||!mt.tagName)&&(mt={namespaceURI:We,tagName:"template"});const Ne=RN(De.tagName),Ye=RN(mt.tagName);return st[De.namespaceURI]?De.namespaceURI===Oe?mt.namespaceURI===Re?Ne==="svg":mt.namespaceURI===Fe?Ne==="svg"&&(Ye==="annotation-xml"||it[Ye]):!!Tt[Ne]:De.namespaceURI===Fe?mt.namespaceURI===Re?Ne==="math":mt.namespaceURI===Oe?Ne==="math"&&Ce[Ye]:!!Ut[Ne]:De.namespaceURI===Re?mt.namespaceURI===Oe&&!Ce[Ye]||mt.namespaceURI===Fe&&!it[Ye]?!1:!Ut[Ne]&&(Ze[Ne]||!Tt[Ne]):!!(Ie==="application/xhtml+xml"&&st[De.namespaceURI]):!1},Wt=function(De){k0(e.removed,{element:De});try{k(De).removeChild(De)}catch{b(De)}},Zt=function(De,mt){try{k0(e.removed,{attribute:mt.getAttributeNode(De),from:mt})}catch{k0(e.removed,{attribute:null,from:mt})}if(mt.removeAttribute(De),De==="is")if(se||te)try{Wt(mt)}catch{}else try{mt.setAttribute(De,"")}catch{}},ln=function(De){let mt=null,Ne=null;if(X)De="<remove></remove>"+De;else{const at=N3(De,/^[\r\n\t ]+/);Ne=at&&at[0]}Ie==="application/xhtml+xml"&&We===Re&&(De='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+De+"</body></html>");const Ye=C?C.createHTML(De):De;if(We===Re)try{mt=new p().parseFromString(Ye,Ie)}catch{}if(!mt||!mt.documentElement){mt=T.createDocument(We,"template",null);try{mt.documentElement.innerHTML=ze?P:Ye}catch{}}const nt=mt.body||mt.documentElement;return De&&Ne&&nt.insertBefore(n.createTextNode(Ne),nt.childNodes[0]||null),We===Re?_.call(mt,G?"html":"body")[0]:G?mt.documentElement:nt},cn=function(De){return A.call(De.ownerDocument||De,De,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},ct=function(De){return De instanceof m&&(typeof De.nodeName!="string"||typeof De.textContent!="string"||typeof De.removeChild!="function"||!(De.attributes instanceof u)||typeof De.removeAttribute!="function"||typeof De.setAttribute!="function"||typeof De.namespaceURI!="string"||typeof De.insertBefore!="function"||typeof De.hasChildNodes!="function")},kt=function(De){return typeof l=="function"&&De instanceof l};function Nt(Je,De,mt){_0(Je,Ne=>{Ne.call(e,De,mt,Qe)})}const ut=function(De){let mt=null;if(Nt(H.beforeSanitizeElements,De,null),ct(De))return Wt(De),!0;const Ne=rt(De.nodeName);if(Nt(H.uponSanitizeElement,De,{tagName:Ne,allowedTags:Q}),U&&De.hasChildNodes()&&!kt(De.firstElementChild)&&ho(/<[/\w!]/g,De.innerHTML)&&ho(/<[/\w!]/g,De.textContent)||U&&De.namespaceURI===Re&&Ne==="style"&&kt(De.firstElementChild)||De.nodeType===P0.progressingInstruction||U&&De.nodeType===P0.comment&&ho(/<[/\w]/g,De.data))return Wt(De),!0;if($[Ne]||!(j.tagCheck instanceof Function&&j.tagCheck(Ne))&&!Q[Ne]){if(!$[Ne]&&Le(Ne)&&(we.tagNameCheck instanceof RegExp&&ho(we.tagNameCheck,Ne)||we.tagNameCheck instanceof Function&&we.tagNameCheck(Ne)))return!1;if(R&&!ye[Ne]){const Ye=k(De)||De.parentNode,nt=S(De)||De.childNodes;if(nt&&Ye){const at=nt.length;for(let et=at-1;et>=0;--et){const vt=w(nt[et],!0);vt.__removalCount=(De.__removalCount||0)+1,Ye.insertBefore(vt,x(De))}}}return Wt(De),!0}return De instanceof c&&!bt(De)||(Ne==="noscript"||Ne==="noembed"||Ne==="noframes")&&ho(/<\/no(script|embed|frames)/i,De.innerHTML)?(Wt(De),!0):(ie&&De.nodeType===P0.text&&(mt=De.textContent,_0([I,z,L],Ye=>{mt=Dx(mt,Ye," ")}),De.textContent!==mt&&(k0(e.removed,{element:De.cloneNode()}),De.textContent=mt)),Nt(H.afterSanitizeElements,De,null),!1)},Ct=function(De,mt,Ne){if(J[mt]||de&&(mt==="id"||mt==="name")&&(Ne in n||Ne in Te))return!1;if(!(B&&!J[mt]&&ho(Z,mt))){if(!(E&&ho(ne,mt))){if(!(j.attributeCheck instanceof Function&&j.attributeCheck(mt,De))){if(!pe[mt]||J[mt]){if(!(Le(De)&&(we.tagNameCheck instanceof RegExp&&ho(we.tagNameCheck,De)||we.tagNameCheck instanceof Function&&we.tagNameCheck(De))&&(we.attributeNameCheck instanceof RegExp&&ho(we.attributeNameCheck,mt)||we.attributeNameCheck instanceof Function&&we.attributeNameCheck(mt,De))||mt==="is"&&we.allowCustomizedBuiltInElements&&(we.tagNameCheck instanceof RegExp&&ho(we.tagNameCheck,Ne)||we.tagNameCheck instanceof Function&&we.tagNameCheck(Ne))))return!1}else if(!Me[mt]){if(!ho(oe,Dx(Ne,ce,""))){if(!((mt==="src"||mt==="xlink:href"||mt==="href")&&De!=="script"&&X9e(Ne,"data:")===0&&xe[De])){if(!(W&&!ho(Y,Dx(Ne,ce,"")))){if(Ne)return!1}}}}}}}return!0},Le=function(De){return De!=="annotation-xml"&&N3(De,ue)},Ae=function(De){Nt(H.beforeSanitizeAttributes,De,null);const{attributes:mt}=De;if(!mt||ct(De))return;const Ne={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Ye=mt.length;for(;Ye--;){const nt=mt[Ye],{name:at,namespaceURI:et,value:vt}=nt,wt=rt(at),Ue=vt;let He=at==="value"?Ue:Z9e(Ue);if(Ne.attrName=wt,Ne.attrValue=He,Ne.keepAttr=!0,Ne.forceKeepAttr=void 0,Nt(H.uponSanitizeAttribute,De,Ne),He=Ne.attrValue,me&&(wt==="id"||wt==="name")&&(Zt(at,De),He=q+He),U&&ho(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,He)){Zt(at,De);continue}if(wt==="attributename"&&N3(He,"href")){Zt(at,De);continue}if(Ne.forceKeepAttr)continue;if(!Ne.keepAttr){Zt(at,De);continue}if(!O&&ho(/\/>/i,He)){Zt(at,De);continue}ie&&_0([I,z,L],Rt=>{He=Dx(He,Rt," ")});const Dt=rt(De.nodeName);if(!Ct(Dt,wt,He)){Zt(at,De);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!et)switch(f.getAttributeType(Dt,wt)){case"TrustedHTML":{He=C.createHTML(He);break}case"TrustedScriptURL":{He=C.createScriptURL(He);break}}if(He!==Ue)try{et?De.setAttributeNS(et,at,He):De.setAttribute(at,He),ct(De)?Wt(De):oQ(e.removed)}catch{Zt(at,De)}}Nt(H.afterSanitizeAttributes,De,null)},Ge=function(De){let mt=null;const Ne=cn(De);for(Nt(H.beforeSanitizeShadowDOM,De,null);mt=Ne.nextNode();)Nt(H.uponSanitizeShadowNode,mt,null),ut(mt),Ae(mt),mt.content instanceof s&&Ge(mt.content);Nt(H.afterSanitizeShadowDOM,De,null)};return e.sanitize=function(Je){let De=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},mt=null,Ne=null,Ye=null,nt=null;if(ze=!Je,ze&&(Je="<!-->"),typeof Je!="string"&&!kt(Je))if(typeof Je.toString=="function"){if(Je=Je.toString(),typeof Je!="string")throw N0("dirty is not a string, aborting")}else throw N0("toString is not a function");if(!e.isSupported)return Je;if(K||ot(De),e.removed=[],typeof Je=="string"&&(re=!1),re){if(Je.nodeName){const vt=rt(Je.nodeName);if(!Q[vt]||$[vt])throw N0("root node is forbidden and cannot be sanitized in-place")}}else if(Je instanceof l)mt=ln("<!---->"),Ne=mt.ownerDocument.importNode(Je,!0),Ne.nodeType===P0.element&&Ne.nodeName==="BODY"||Ne.nodeName==="HTML"?mt=Ne:mt.appendChild(Ne);else{if(!se&&!ie&&!G&&Je.indexOf("<")===-1)return C&&fe?C.createHTML(Je):Je;if(mt=ln(Je),!mt)return se?null:fe?P:""}mt&&X&&Wt(mt.firstChild);const at=cn(re?Je:mt);for(;Ye=at.nextNode();)ut(Ye),Ae(Ye),Ye.content instanceof s&&Ge(Ye.content);if(re)return Je;if(se){if(ie){mt.normalize();let vt=mt.innerHTML;_0([I,z,L],wt=>{vt=Dx(vt,wt," ")}),mt.innerHTML=vt}if(te)for(nt=F.call(mt.ownerDocument);mt.firstChild;)nt.appendChild(mt.firstChild);else nt=mt;return(pe.shadowroot||pe.shadowrootmode)&&(nt=M.call(a,nt,!0)),nt}let et=G?mt.outerHTML:mt.innerHTML;return G&&Q["!doctype"]&&mt.ownerDocument&&mt.ownerDocument.doctype&&mt.ownerDocument.doctype.name&&ho(xse,mt.ownerDocument.doctype.name)&&(et="<!DOCTYPE "+mt.ownerDocument.doctype.name+`>
  8184. `+et),ie&&_0([I,z,L],vt=>{et=Dx(et,vt," ")}),C&&fe?C.createHTML(et):et},e.setConfig=function(){let Je=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ot(Je),K=!0},e.clearConfig=function(){Qe=null,K=!1},e.isValidAttribute=function(Je,De,mt){Qe||ot({});const Ne=rt(Je),Ye=rt(De);return Ct(Ne,Ye,mt)},e.addHook=function(Je,De){typeof De=="function"&&k0(H[Je],De)},e.removeHook=function(Je,De){if(De!==void 0){const mt=Q9e(H[Je],De);return mt===-1?void 0:Y9e(H[Je],mt,1)[0]}return oQ(H[Je])},e.removeHooks=function(Je){H[Je]=[]},e.removeAllHooks=function(){H=pQ()},e}var h5=yse();function Ts(t){this.content=t}Ts.prototype={constructor:Ts,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 a=n&&n!=t?this.remove(n):this,i=a.find(t),s=a.content.slice();return i==-1?s.push(n||t,e):(s[i+1]=e,n&&(s[i]=n)),new Ts(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 Ts(n)},addToStart:function(t,e){return new Ts([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Ts(n)},addBefore:function(t,e,n){var a=this.remove(e),i=a.content.slice(),s=a.find(t);return i.splice(s==-1?i.length:s,0,e,n),new Ts(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=Ts.from(t),t.size?new Ts(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=Ts.from(t),t.size?new Ts(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Ts.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}};Ts.from=function(t){if(t instanceof Ts)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ts(e)};function vse(t,e,n){for(let a=0;;a++){if(a==t.childCount||a==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(a),s=e.child(a);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=vse(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function wse(t,e,n,a){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:a};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,a-=c;continue}if(!o.sameMarkup(l))return{a:n,b:a};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--,a--;return{a:n,b:a}}if(o.content.size||l.content.size){let d=wse(o.content,l.content,n-1,a-1);if(d)return d}n-=c,a-=c}}class Yt{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let a=0;a<e.length;a++)this.size+=e[a].nodeSize}nodesBetween(e,n,a,i=0,s){for(let o=0,l=0;l<n;o++){let c=this.content[o],d=l+c.nodeSize;if(d>e&&a(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),a,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,a,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)&&a&&(o?o=!1:s+=a),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,a=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(a)&&(i[i.length-1]=n.withText(n.text+a.text),s=1);s<e.content.length;s++)i.push(e.content[s]);return new Yt(i,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let a=[],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))),a.push(l),i+=l.nodeSize),o=c}return new Yt(a,i)}cutByIndex(e,n){return e==n?Yt.empty:e==0&&n==this.content.length?this:new Yt(this.content.slice(e,n))}replaceChild(e,n){let a=this.content[e];if(a==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-a.nodeSize;return i[e]=n,new Yt(i,s)}addToStart(e){return new Yt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Yt(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,a=0;n<this.content.length;n++){let i=this.content[n];e(i,a,n),a+=i.nodeSize}}findDiffStart(e,n=0){return vse(this,e,n)}findDiffEnd(e,n=this.size,a=e.size){return wse(this,e,n,a)}findIndex(e){if(e==0)return K1(0,e);if(e==this.size)return K1(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,a=0;;n++){let i=this.child(n),s=a+i.nodeSize;if(s>=e)return s==e?K1(n+1,s):K1(n,a);a=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 Yt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Yt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Yt.empty;let n,a=0;for(let i=0;i<e.length;i++){let s=e[i];a+=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 Yt(n||e,a)}static from(e){if(!e)return Yt.empty;if(e instanceof Yt)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Yt([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}Yt.empty=new Yt([],0);const j3={index:0,offset:0};function K1(t,e){return j3.index=t,j3.offset=e,j3}function SP(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 a=0;a<t.length;a++)if(!SP(t[a],e[a]))return!1}else{for(let a in t)if(!(a in e)||!SP(t[a],e[a]))return!1;for(let a in e)if(!(a in t))return!1}return!0}let ha=class pI{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,a=!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;!a&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,i)),n.push(this),a=!0),n&&n.push(s)}}return n||(n=e.slice()),a||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&&SP(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 a=e.marks[n.type];if(!a)throw new RangeError(`There is no mark type ${n.type} in this schema`);let i=a.create(n.attrs);return a.checkAttrs(i.attrs),i}static sameSet(e,n){if(e==n)return!0;if(e.length!=n.length)return!1;for(let a=0;a<e.length;a++)if(!e[a].eq(n[a]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return pI.none;if(e instanceof pI)return[e];let n=e.slice();return n.sort((a,i)=>a.type.rank-i.type.rank),n}};ha.none=[];class _P extends Error{}class gn{constructor(e,n,a){this.content=e,this.openStart=n,this.openEnd=a}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let a=_se(this.content,e+this.openStart,n);return a&&new gn(a,this.openStart,this.openEnd)}removeBetween(e,n){return new gn(Sse(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 gn.empty;let a=n.openStart||0,i=n.openEnd||0;if(typeof a!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new gn(Yt.fromJSON(e,n.content),a,i)}static maxOpen(e,n=!0){let a=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)a++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new gn(e,a,i)}}gn.empty=new gn(Yt.empty,0,0);function Sse(t,e,n){let{index:a,offset:i}=t.findIndex(e),s=t.maybeChild(a),{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(a!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(a,s.copy(Sse(s.content,e-i-1,n-i-1)))}function _se(t,e,n,a){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return a&&!a.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=_se(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function pWe(t,e,n){if(n.openStart>t.depth)throw new _P("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new _P("Inconsistent open depths");return kse(t,e,n,0)}function kse(t,e,n,a){let i=t.index(a),s=t.node(a);if(i==e.index(a)&&a<t.depth-n.openStart){let o=kse(t,e,n,a+1);return s.copy(s.content.replaceChild(i,o))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&t.depth==a&&e.depth==a){let o=t.parent,l=o.content;return _g(o,l.cut(0,t.parentOffset).append(n.content).append(l.cut(e.parentOffset)))}else{let{start:o,end:l}=hWe(n,t);return _g(s,Cse(t,o,l,e,a))}else return _g(s,kP(t,e,a))}function Nse(t,e){if(!e.type.compatibleContent(t.type))throw new _P("Cannot join "+e.type.name+" onto "+t.type.name)}function hI(t,e,n){let a=t.node(n);return Nse(a,e.node(n)),a}function Sg(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 lw(t,e,n,a){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&&(Sg(t.nodeAfter,a),s++));for(let l=s;l<o;l++)Sg(i.child(l),a);e&&e.depth==n&&e.textOffset&&Sg(e.nodeBefore,a)}function _g(t,e){return t.type.checkContent(e),t.copy(e)}function Cse(t,e,n,a,i){let s=t.depth>i&&hI(t,e,i+1),o=a.depth>i&&hI(n,a,i+1),l=[];return lw(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Nse(s,o),Sg(_g(s,Cse(t,e,n,a,i+1)),l)):(s&&Sg(_g(s,kP(t,e,i+1)),l),lw(e,n,i,l),o&&Sg(_g(o,kP(n,a,i+1)),l)),lw(a,null,i,l),new Yt(l)}function kP(t,e,n){let a=[];if(lw(null,t,n,a),t.depth>n){let i=hI(t,e,n+1);Sg(_g(i,kP(t,e,n+1)),a)}return lw(e,null,n,a),new Yt(a)}function hWe(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(Yt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class lS{constructor(e,n,a){this.pos=e,this.path=n,this.parentOffset=a,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 a=this.pos-this.path[this.path.length-1],i=e.child(n);return a?e.child(n).cut(a):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 a=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)i+=a.child(s).nodeSize;return i}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return ha.none;if(this.textOffset)return e.child(n).marks;let a=e.maybeChild(n-1),i=e.maybeChild(n);if(!a){let l=a;a=i,i=l}let s=a.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 a=n.marks,i=e.parent.maybeChild(e.index());for(var s=0;s<a.length;s++)a[s].type.spec.inclusive===!1&&(!i||!a[s].isInSet(i.marks))&&(a=a[s--].removeFromSet(a));return a}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 a=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);a>=0;a--)if(e.pos<=this.end(a)&&(!n||n(this.node(a))))return new NP(this,e,a);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 a=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(a.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new lS(n,a,s)}static resolveCached(e,n){let a=hQ.get(e);if(a)for(let s=0;s<a.elts.length;s++){let o=a.elts[s];if(o.pos==n)return o}else hQ.set(e,a=new fWe);let i=a.elts[a.i]=lS.resolve(e,n);return a.i=(a.i+1)%gWe,i}}class fWe{constructor(){this.elts=[],this.i=0}}const gWe=12,hQ=new WeakMap;class NP{constructor(e,n,a){this.$from=e,this.$to=n,this.depth=a}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 bWe=Object.create(null);class pd{constructor(e,n,a,i=ha.none){this.type=e,this.attrs=n,this.marks=i,this.content=a||Yt.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,a,i=0){this.content.nodesBetween(e,n,a,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,a,i){return this.content.textBetween(e,n,a,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,a){return this.type==e&&SP(this.attrs,n||e.defaultAttrs||bWe)&&ha.sameSet(this.marks,a||ha.none)}copy(e=null){return e==this.content?this:new pd(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new pd(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,a=!1){if(e==n)return gn.empty;let i=this.resolve(e),s=this.resolve(n),o=a?0:i.sharedDepth(n),l=i.start(o),d=i.node(o).content.cut(i.pos-l,s.pos-l);return new gn(d,i.depth-o,s.depth-o)}replace(e,n,a){return pWe(this.resolve(e),this.resolve(n),a)}nodeAt(e){for(let n=this;;){let{index:a,offset:i}=n.content.findIndex(e);if(n=n.maybeChild(a),!n)return null;if(i==e||n.isText)return n;e-=i+1}}childAfter(e){let{index:n,offset:a}=this.content.findIndex(e);return{node:this.content.maybeChild(n),index:n,offset:a}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:n,offset:a}=this.content.findIndex(e);if(a<e)return{node:this.content.child(n),index:n,offset:a};let i=this.content.child(n-1);return{node:i,index:n-1,offset:a-i.nodeSize}}resolve(e){return lS.resolveCached(this,e)}resolveNoCache(e){return lS.resolve(this,e)}rangeHasMark(e,n,a){let i=!1;return n>e&&this.nodesBetween(e,n,s=>(a.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()+")"),Pse(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,a=Yt.empty,i=0,s=a.childCount){let o=this.contentMatchAt(e).matchFragment(a,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(a.child(c).marks))return!1;return!0}canReplaceWith(e,n,a,i){if(i&&!this.type.allowsMarks(i))return!1;let s=this.contentMatchAt(e).matchType(a),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=ha.none;for(let n=0;n<this.marks.length;n++){let a=this.marks[n];a.type.checkAttrs(a.attrs),e=a.addToSet(e)}if(!ha.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 a;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");a=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,a)}let i=Yt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,a);return s.type.checkAttrs(s.attrs),s}}pd.prototype.text=void 0;class CP extends pd{constructor(e,n,a,i){if(super(e,n,null,i),!a)throw new RangeError("Empty text nodes are not allowed");this.text=a}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Pse(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 CP(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new CP(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 Pse(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Yg{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let a=new xWe(e,n);if(a.next==null)return Yg.empty;let i=Tse(a);a.next&&a.err("Unexpected trailing text");let s=NWe(kWe(i));return CWe(s,a),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,a=e.childCount){let i=this;for(let s=n;i&&s<a;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 a=0;a<e.next.length;a++)if(this.next[n].type==e.next[a].type)return!0;return!1}fillBefore(e,n=!1,a=0){let i=[this];function s(o,l){let c=o.matchFragment(e,a);if(c&&(!n||c.validEnd))return Yt.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 a=0;a<this.wrapCache.length;a+=2)if(this.wrapCache[a]==e)return this.wrapCache[a+1];let n=this.computeWrapping(e);return this.wrapCache.push(e,n),n}computeWrapping(e){let n=Object.create(null),a=[{match:this,type:null,via:null}];for(;a.length;){let i=a.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)&&(a.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(a){e.push(a);for(let i=0;i<a.next.length;i++)e.indexOf(a.next[i].next)==-1&&n(a.next[i].next)}return n(this),e.map((a,i)=>{let s=i+(a.validEnd?"*":" ")+" ";for(let o=0;o<a.next.length;o++)s+=(o?", ":"")+a.next[o].type.name+"->"+e.indexOf(a.next[o].next);return s}).join(`
  8185. `)}}Yg.empty=new Yg(!0);class xWe{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 Tse(t){let e=[];do e.push(yWe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function yWe(t){let e=[];do e.push(vWe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function vWe(t){let e=_We(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=wWe(t,e);else break;return e}function fQ(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function wWe(t,e){let n=fQ(t),a=n;return t.eat(",")&&(t.next!="}"?a=fQ(t):a=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:a,expr:e}}function SWe(t,e){let n=t.nodeTypes,a=n[e];if(a)return[a];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 _We(t){if(t.eat("(")){let e=Tse(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=SWe(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 kWe(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function a(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 a(l,c),i(s(o.expr,c),c),[a(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[a(c)]}else{if(o.type=="opt")return[a(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();a(c,u),i(s(o.expr,c),u),c=u}return[a(c)]}else{if(o.type=="name")return[a(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function Ase(t,e){return e-t}function gQ(t,e){let n=[];return a(e),n.sort(Ase);function a(i){let s=t[i];if(s.length==1&&!s[0].term)return a(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&&a(c)}}}function NWe(t){let e=Object.create(null);return n(gQ(t,0));function n(a){let i=[];a.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]);gQ(t,c).forEach(u=>{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[a.join(",")]=new Yg(a.indexOf(t.length-1)>-1);for(let o=0;o<i.length;o++){let l=i[o][1].sort(Ase);s.next.push({type:i[o][0],next:e[l.join(",")]||n(l)})}return s}}function CWe(t,e){for(let n=0,a=[t];n<a.length;n++){let i=a[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),a.indexOf(d)==-1&&a.push(d)}s&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function jse(t){let e=Object.create(null);for(let n in t){let a=t[n];if(!a.hasDefault)return null;e[n]=a.default}return e}function Mse(t,e){let n=Object.create(null);for(let a in t){let i=e&&e[a];if(i===void 0){let s=t[a];if(s.hasDefault)i=s.default;else throw new RangeError("No value supplied for attribute "+a)}n[a]=i}return n}function Ese(t,e,n,a){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 Dse(t,e){let n=Object.create(null);if(e)for(let a in e)n[a]=new TWe(t,a,e[a]);return n}let bQ=class Fse{constructor(e,n,a){this.name=e,this.schema=n,this.spec=a,this.markSet=null,this.groups=a.group?a.group.split(" "):[],this.attrs=Dse(e,a.attrs),this.defaultAttrs=jse(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(a.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Yg.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:Mse(this.attrs,e)}create(e=null,n,a){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new pd(this,this.computeAttrs(e),Yt.from(n),ha.setFrom(a))}createChecked(e=null,n,a){return n=Yt.from(n),this.checkContent(n),new pd(this,this.computeAttrs(e),n,ha.setFrom(a))}createAndFill(e=null,n,a){if(e=this.computeAttrs(e),n=Yt.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(Yt.empty,!0);return s?new pd(this,e,n.append(s),ha.setFrom(a)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let a=0;a<e.childCount;a++)if(!this.allowsMarks(e.child(a).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){Ese(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 a=0;a<e.length;a++)this.allowsMarkType(e[a].type)?n&&n.push(e[a]):n||(n=e.slice(0,a));return n?n.length?n:ha.none:e}static compile(e,n){let a=Object.create(null);e.forEach((s,o)=>a[s]=new Fse(s,n,o));let i=n.spec.topNode||"doc";if(!a[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!a.text)throw new RangeError("Every schema needs a 'text' type");for(let s in a.text.attrs)throw new RangeError("The text node type should not have attributes");return a}};function PWe(t,e,n){let a=n.split("|");return i=>{let s=i===null?"null":typeof i;if(a.indexOf(s)<0)throw new RangeError(`Expected value of type ${a} for attribute ${e} on type ${t}, got ${s}`)}}class TWe{constructor(e,n,a){this.hasDefault=Object.prototype.hasOwnProperty.call(a,"default"),this.default=a.default,this.validate=typeof a.validate=="string"?PWe(e,n,a.validate):a.validate}get isRequired(){return!this.hasDefault}}class IA{constructor(e,n,a,i){this.name=e,this.rank=n,this.schema=a,this.spec=i,this.attrs=Dse(e,i.attrs),this.excluded=null;let s=jse(this.attrs);this.instance=s?new ha(this,s):null}create(e=null){return!e&&this.instance?this.instance:new ha(this,Mse(this.attrs,e))}static compile(e,n){let a=Object.create(null),i=0;return e.forEach((s,o)=>a[s]=new IA(s,i++,n,o)),a}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){Ese(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class Lse{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=Ts.from(e.nodes),n.marks=Ts.from(e.marks||{}),this.nodes=bQ.compile(this.spec.nodes,this),this.marks=IA.compile(this.spec.marks,this);let a=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=a[o]||(a[o]=Yg.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?xQ(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==""?[]:xQ(this,o.split(" "))}this.nodeFromJSON=i=>pd.fromJSON(this,i),this.markFromJSON=i=>ha.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,a,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof bQ){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,a,i)}text(e,n){let a=this.nodes.text;return new CP(a,a.defaultAttrs,e,ha.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 xQ(t,e){let n=[];for(let a=0;a<e.length;a++){let i=e[a],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[a]+"'")}return n}function AWe(t){return t.tag!=null}function jWe(t){return t.style!=null}let cw=class fI{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let a=this.matchedStyles=[];n.forEach(i=>{if(AWe(i))this.tags.push(i);else if(jWe(i)){let s=/[^=]*/.exec(i.style)[0];a.indexOf(s)<0&&a.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 a=new vQ(this,n,!1);return a.addAll(e,ha.none,n.from,n.to),a.finish()}parseSlice(e,n={}){let a=new vQ(this,n,!0);return a.addAll(e,ha.none,n.from,n.to),gn.maxOpen(a.finish())}matchTag(e,n,a){for(let i=a?this.tags.indexOf(a)+1:0;i<this.tags.length;i++){let s=this.tags[i];if(DWe(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,a,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&&!a.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 a(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=>{a(o=wQ(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=>{a(o=wQ(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new fI(e,fI.schemaRules(e)))}};const Rse={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},MWe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Ise={ol:!0,ul:!0},cS=1,gI=2,dw=4;function yQ(t,e,n){return e!=null?(e?cS:0)|(e==="full"?gI:0):t&&t.whitespace=="pre"?cS|gI:n&~dw}class Q1{constructor(e,n,a,i,s,o){this.type=e,this.attrs=n,this.marks=a,this.solid=i,this.options=o,this.content=[],this.activeMarks=ha.none,this.match=s||(o&dw?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Yt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let a=this.type.contentMatch,i;return(i=a.findWrapping(e.type))?(this.match=a,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&cS)){let a=this.content[this.content.length-1],i;if(a&&a.isText&&(i=/[ \t\r\n\u000c]+$/.exec(a.text))){let s=a;a.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=Yt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Yt.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&&!Rse.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class vQ{constructor(e,n,a){this.parser=e,this.options=n,this.isOpen=a,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=yQ(null,n.preserveWhitespace,0)|(a?dw:0);i?s=new Q1(i.type,i.attrs,ha.none,!0,n.topMatch||i.type.contentMatch,o):a?s=new Q1(null,null,ha.none,!0,null,o):s=new Q1(e.schema.topNodeType,null,ha.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 a=e.nodeValue,i=this.top,s=i.options&gI?"full":this.localPreserveWS||(i.options&cS)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(a)){if(s)if(s==="full")a=a.replace(/\r\n?/g,`
  8186. `);else if(o.linebreakReplacement&&/[\r\n]/.test(a)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=a.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]));a=""}else a=a.replace(/\r?\n|\r/g," ");else if(a=a.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(a)&&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))&&(a=a.slice(1))}a&&this.insertNode(o.text(a),n,!/\S/.test(a)),this.findInText(e)}else this.findInside(e)}addElement(e,n,a){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;Ise.hasOwnProperty(o)&&this.parser.normalizeLists&&EWe(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(l=this.parser.matchTag(e,this,a));e:if(c?c.ignore:MWe.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(Rse.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(`
  8187. `),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 a=e.style;if(a&&a.length)for(let i=0;i<this.parser.matchedStyles.length;i++){let s=this.parser.matchedStyles[i],o=a.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,a,i){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),a,e.nodeName=="BR")||this.leafFallback(e,a);else{let c=this.enter(o,n.attrs||null,a,n.preserveWhitespace);c&&(s=!0,a=c)}else{let c=this.parser.schema.marks[n.mark];a=a.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,a,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,a,!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,a),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,a,i){let s=a||0;for(let o=a?e.childNodes[a]: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,a){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(a)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,a){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,a);if(i){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let o=ha.none;for(let l of i.concat(e.marks))(s.type?s.type.allowsMarkType(l.type):SQ(l.type,e.type))&&(o=l.addToSet(o));return s.content.push(e.mark(o)),!0}return!1}enter(e,n,a,i){let s=this.findPlace(e.create(n),a,!1);return s&&(s=this.enterInner(e,n,a,!0,i)),s}enterInner(e,n,a,i=!1,s){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(e);let l=yQ(e,s,o.options);o.options&dw&&o.content.length==0&&(l|=dw);let c=ha.none;return a=a.filter(d=>(o.type?o.type.allowsMarkType(d.type):SQ(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Q1(e,n,c,i,null,l)),this.open++,a}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|=cS)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let a=this.nodes[n].content;for(let i=a.length-1;i>=0;i--)e+=a[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let a=0;a<this.find.length;a++)this.find[a].node==e&&this.find[a].offset==n&&(this.find[a].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,a){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)&(a?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("/"),a=this.options.context,i=!this.isOpen&&(!a||a.parent.type==this.nodes[0].type),s=-(a?a.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:a&&c>=s?a.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 a=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(a&&a.isTextblock&&a.defaultAttrs)return a}for(let n in this.parser.schema.nodes){let a=this.parser.schema.nodes[n];if(a.isTextblock&&a.defaultAttrs)return a}}}function EWe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let a=e.nodeType==1?e.nodeName.toLowerCase():null;a&&Ise.hasOwnProperty(a)&&n?(n.appendChild(e),e=n):a=="li"?n=e:a&&(n=null)}}function DWe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function wQ(t){let e={};for(let n in t)e[n]=t[n];return e}function SQ(t,e){let n=e.schema.nodes;for(let a in n){let i=n[a];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 mb{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},a){a||(a=M3(n).createDocumentFragment());let i=a,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))}),a}serializeNodeInner(e,n){let{dom:a,contentDOM:i}=IN(M3(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 a}serializeNode(e,n={}){let a=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(a),a=s.dom)}return a}serializeMark(e,n,a={}){let i=this.marks[e.type.name];return i&&IN(M3(a),i(e,n),null,e.attrs)}static renderSpec(e,n,a=null,i){return IN(e,n,a,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new mb(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=_Q(e.nodes);return n.text||(n.text=a=>a.text),n}static marksFromSchema(e){return _Q(e.marks)}}function _Q(t){let e={};for(let n in t){let a=t[n].spec.toDOM;a&&(e[n]=a)}return e}function M3(t){return t.document||window.document}const kQ=new WeakMap;function FWe(t){let e=kQ.get(t);return e===void 0&&kQ.set(t,e=LWe(t)),e}function LWe(t){let e=null;function n(a){if(a&&typeof a=="object")if(Array.isArray(a))if(typeof a[0]=="string")e||(e=[]),e.push(a);else for(let i=0;i<a.length;i++)n(a[i]);else for(let i in a)n(a[i])}return n(t),e}function IN(t,e,n,a){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(a&&(s=FWe(a))&&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:g}=IN(t,p,n,a);if(c.appendChild(f),g){if(l)throw new RangeError("Multiple content holes");l=g}}}return{dom:c,contentDOM:l}}const Ose=65535,zse=Math.pow(2,16);function RWe(t,e){return t+e*zse}function NQ(t){return t&Ose}function IWe(t){return(t-(t&Ose))/zse}const Use=1,Bse=2,ON=4,Hse=8;class bI{constructor(e,n,a){this.pos=e,this.delInfo=n,this.recover=a}get deleted(){return(this.delInfo&Hse)>0}get deletedBefore(){return(this.delInfo&(Use|ON))>0}get deletedAfter(){return(this.delInfo&(Bse|ON))>0}get deletedAcross(){return(this.delInfo&ON)>0}}class xl{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&xl.empty)return xl.empty}recover(e){let n=0,a=NQ(e);if(!this.inverted)for(let i=0;i<a;i++)n+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[a*3]+n+IWe(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,a){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(a)return f;let g=e==(n<0?c:m)?null:RWe(l/3,e-c),w=e==c?Bse:e==m?Use:ON;return(n<0?e!=c:e!=m)&&(w|=Hse),new bI(f,w,g)}i+=u-d}return a?e+i:new bI(e+i,0,null)}touches(e,n){let a=0,i=NQ(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?a:0);if(c>e)break;let d=this.ranges[l+s],u=c+d;if(e<=u&&l==i*3)return!0;a+=this.ranges[l+o]-d}return!1}forEach(e){let n=this.inverted?2:1,a=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+a];e(l,l+d,c,c+u),s+=u-d}}invert(){return new xl(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?xl.empty:new xl(e<0?[0,-e,0]:[0,0,e])}}xl.empty=new xl([]);class dS{constructor(e,n,a=0,i=e?e.length:0){this.mirror=n,this.from=a,this.to=i,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new dS(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,a=this._maps.length;n<e._maps.length;n++){let i=e.getMirror(n);this.appendMap(e._maps[n],i!=null&&i<n?a+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,a=this._maps.length+e._maps.length;n>=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?a-i-1:void 0)}}invert(){let e=new dS;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let a=this.from;a<this.to;a++)e=this._maps[a].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,a){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 a?e:new bI(e,i,null)}}const E3=Object.create(null);class oo{getMap(){return xl.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let a=E3[n.stepType];if(!a)throw new RangeError(`No step type ${n.stepType} defined`);return a.fromJSON(e,n)}static jsonID(e,n){if(e in E3)throw new RangeError("Duplicate use of step JSON ID "+e);return E3[e]=n,n.prototype.jsonID=e,n}}class Ni{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new Ni(e,null)}static fail(e){return new Ni(null,e)}static fromReplace(e,n,a,i){try{return Ni.ok(e.replace(n,a,i))}catch(s){if(s instanceof _P)return Ni.fail(s.message);throw s}}}function f5(t,e,n){let a=[];for(let i=0;i<t.childCount;i++){let s=t.child(i);s.content.size&&(s=s.copy(f5(s.content,e,s))),s.isInline&&(s=e(s,n,i)),a.push(s)}return Yt.fromArray(a)}class Sh extends oo{constructor(e,n,a){super(),this.from=e,this.to=n,this.mark=a}apply(e){let n=e.slice(this.from,this.to),a=e.resolve(this.from),i=a.node(a.sharedDepth(this.to)),s=new gn(f5(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 Ni.fromReplace(e,this.from,this.to,s)}invert(){return new dd(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),a=e.mapResult(this.to,-1);return n.deleted&&a.deleted||n.pos>=a.pos?null:new Sh(n.pos,a.pos,this.mark)}merge(e){return e instanceof Sh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Sh(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 Sh(n.from,n.to,e.markFromJSON(n.mark))}}oo.jsonID("addMark",Sh);class dd extends oo{constructor(e,n,a){super(),this.from=e,this.to=n,this.mark=a}apply(e){let n=e.slice(this.from,this.to),a=new gn(f5(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return Ni.fromReplace(e,this.from,this.to,a)}invert(){return new Sh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),a=e.mapResult(this.to,-1);return n.deleted&&a.deleted||n.pos>=a.pos?null:new dd(n.pos,a.pos,this.mark)}merge(e){return e instanceof dd&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new dd(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 dd(n.from,n.to,e.markFromJSON(n.mark))}}oo.jsonID("removeMark",dd);class _h extends oo{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Ni.fail("No node at mark step's position");let a=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Ni.fromReplace(e,this.pos,this.pos+1,new gn(Yt.from(a),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let a=this.mark.addToSet(n.marks);if(a.length==n.marks.length){for(let i=0;i<n.marks.length;i++)if(!n.marks[i].isInSet(a))return new _h(this.pos,n.marks[i]);return new _h(this.pos,this.mark)}}return new Xg(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new _h(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 _h(n.pos,e.markFromJSON(n.mark))}}oo.jsonID("addNodeMark",_h);class Xg extends oo{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return Ni.fail("No node at mark step's position");let a=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Ni.fromReplace(e,this.pos,this.pos+1,new gn(Yt.from(a),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new _h(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Xg(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 Xg(n.pos,e.markFromJSON(n.mark))}}oo.jsonID("removeNodeMark",Xg);class ss extends oo{constructor(e,n,a,i=!1){super(),this.from=e,this.to=n,this.slice=a,this.structure=i}apply(e){return this.structure&&xI(e,this.from,this.to)?Ni.fail("Structure replace would overwrite content"):Ni.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new xl([this.from,this.to-this.from,this.slice.size])}invert(e){return new ss(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.from,1),a=e.mapResult(this.to,-1);return n.deletedAcross&&a.deletedAcross?null:new ss(n.pos,Math.max(n.pos,a.pos),this.slice,this.structure)}merge(e){if(!(e instanceof ss)||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?gn.empty:new gn(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new ss(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?gn.empty:new gn(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new ss(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 ss(n.from,n.to,gn.fromJSON(e,n.slice),!!n.structure)}}oo.jsonID("replace",ss);class ms extends oo{constructor(e,n,a,i,s,o,l=!1){super(),this.from=e,this.to=n,this.gapFrom=a,this.gapTo=i,this.slice=s,this.insert=o,this.structure=l}apply(e){if(this.structure&&(xI(e,this.from,this.gapFrom)||xI(e,this.gapTo,this.to)))return Ni.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Ni.fail("Gap is not a flat range");let a=this.slice.insertAt(this.insert,n.content);return a?Ni.fromReplace(e,this.from,this.to,a):Ni.fail("Content does not fit in gap")}getMap(){return new xl([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 ms(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),a=e.mapResult(this.to,-1),i=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?a.pos:e.map(this.gapTo,1);return n.deletedAcross&&a.deletedAcross||i<n.pos||s>a.pos?null:new ms(n.pos,a.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 ms(n.from,n.to,n.gapFrom,n.gapTo,gn.fromJSON(e,n.slice),n.insert,!!n.structure)}}oo.jsonID("replaceAround",ms);function xI(t,e,n){let a=t.resolve(e),i=n-e,s=a.depth;for(;i>0&&s>0&&a.indexAfter(s)==a.node(s).childCount;)s--,i--;if(i>0){let o=a.node(s).maybeChild(a.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function OWe(t,e,n,a){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let m=c.marks;if(!a.isInSet(m)&&u.type.allowsMarkType(a.type)){let p=Math.max(d,e),f=Math.min(d+c.nodeSize,n),g=a.addToSet(m);for(let w=0;w<m.length;w++)m[w].isInSet(g)||(o&&o.to==p&&o.mark.eq(m[w])?o.to=f:i.push(o=new dd(p,f,m[w])));l&&l.to==p?l.to=f:s.push(l=new Sh(p,f,a))}}),i.forEach(c=>t.step(c)),s.forEach(c=>t.step(c))}function zWe(t,e,n,a){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(a instanceof IA){let d=o.marks,u;for(;u=a.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else a?a.isInSet(o.marks)&&(c=[a]):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 g=i[f];g.step==s-1&&m.eq(i[f].style)&&(p=g)}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 dd(o.from,o.to,o.style)))}function g5(t,e,n,a=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=a.matchType(d.type);if(!m)o.push(new ss(l,u,gn.empty));else{a=m;for(let p=0;p<d.marks.length;p++)n.allowsMarkType(d.marks[p].type)||t.step(new dd(l,u,d.marks[p]));if(i&&d.isText&&n.whitespace!="pre"){let p,f=/\r?\n|\r/g,g;for(;p=f.exec(d.text);)g||(g=new gn(Yt.from(n.schema.text(" ",n.allowedMarks(d.marks))),0,0)),o.push(new ss(l+p.index,l+p.index+p[0].length,g))}}l=u}if(!a.validEnd){let c=a.fillBefore(Yt.empty,!0);t.replace(l,l,new gn(c,0,0))}for(let c=o.length-1;c>=0;c--)t.step(o[c])}function UWe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function mv(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let a=t.depth,i=0,s=0;;--a){let o=t.$from.node(a),l=t.$from.index(a)+i,c=t.$to.indexAfter(a)-s;if(a<t.depth&&o.canReplace(l,c,n))return a;if(a==0||o.type.spec.isolating||!UWe(o,l,c))break;l&&(i=1),c<o.childCount&&(s=1)}return null}function BWe(t,e,n){let{$from:a,$to:i,depth:s}=e,o=a.before(s+1),l=i.after(s+1),c=o,d=l,u=Yt.empty,m=0;for(let g=s,w=!1;g>n;g--)w||a.index(g)>0?(w=!0,u=Yt.from(a.node(g).copy(u)),m++):c--;let p=Yt.empty,f=0;for(let g=s,w=!1;g>n;g--)w||i.after(g+1)<i.end(g)?(w=!0,p=Yt.from(i.node(g).copy(p)),f++):d++;t.step(new ms(c,d,o,l,new gn(u.append(p),m,f),u.size-m,!0))}function b5(t,e,n=null,a=t){let i=HWe(t,e),s=i&&qWe(a,e);return s?i.map(CQ).concat({type:e,attrs:n}).concat(s.map(CQ)):null}function CQ(t){return{type:t,attrs:null}}function HWe(t,e){let{parent:n,startIndex:a,endIndex:i}=t,s=n.contentMatchAt(a).findWrapping(e);if(!s)return null;let o=s.length?s[0]:e;return n.canReplaceWith(a,i,o)?s:null}function qWe(t,e){let{parent:n,startIndex:a,endIndex:i}=t,s=n.child(a),o=e.contentMatch.findWrapping(s.type);if(!o)return null;let c=(o.length?o[o.length-1]:e).contentMatch;for(let d=a;c&&d<i;d++)c=c.matchType(n.child(d).type);return!c||!c.validEnd?null:o}function $We(t,e,n){let a=Yt.empty;for(let o=n.length-1;o>=0;o--){if(a.size){let l=n[o].type.contentMatch.matchFragment(a);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}a=Yt.from(n[o].type.create(n[o].attrs,a))}let i=e.start,s=e.end;t.step(new ms(i,s,i,s,new gn(a,0,0),n.length,!0))}function VWe(t,e,n,a,i){if(!a.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(a,c)&&GWe(t.doc,t.mapping.slice(s).map(l),a)){let d=null;if(a.schema.linebreakReplacement){let f=a.whitespace=="pre",g=!!a.contentMatch.matchType(a.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&$se(t,o,l,s),g5(t,t.mapping.slice(s).map(l,1),a,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 ms(m,p,m+1,p-1,new gn(Yt.from(a.create(c,null,o.marks)),0,0),1,!0)),d===!0&&qse(t,o,l,s),!1}})}function qse(t,e,n,a){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(a).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function $se(t,e,n,a){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(a).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(`
  8188. `))}})}function GWe(t,e,n){let a=t.resolve(e),i=a.index();return a.parent.canReplaceWith(i,i+1,n)}function WWe(t,e,n,a,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(a,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 ms(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new gn(Yt.from(o),0,0),1,!0))}function zm(t,e,n=1,a){let i=t.resolve(e),s=i.depth-n,o=a&&a[a.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),g=a&&a[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let w=a&&a[u]||m;if(!m.canReplace(p+1,m.childCount)||!w.type.validContent(f))return!1}let l=i.indexAfter(s),c=a&&a[0];return i.node(s).canReplaceWith(l,l,c?c.type:i.node(s+1).type)}function KWe(t,e,n=1,a){let i=t.doc.resolve(e),s=Yt.empty,o=Yt.empty;for(let l=i.depth,c=i.depth-n,d=n-1;l>c;l--,d--){s=Yt.from(i.node(l).copy(s));let u=a&&a[d];o=Yt.from(u?u.type.create(u.attrs,o):i.node(l).copy(o))}t.step(new ss(e,e,new gn(s.append(o),n,n),!0))}function uf(t,e){let n=t.resolve(e),a=n.index();return Vse(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(a,a+1)}function QWe(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:a}=t.type.schema;for(let i=0;i<e.childCount;i++){let s=e.child(i),o=s.type==a?t.type.schema.nodes.text:s.type;if(n=n.matchType(o),!n||!t.type.allowsMarks(s.marks))return!1}return n.validEnd}function Vse(t,e){return!!(t&&e&&!t.isLeaf&&QWe(t,e))}function OA(t,e,n=-1){let a=t.resolve(e);for(let i=a.depth;;i--){let s,o,l=a.index(i);if(i==a.depth?(s=a.nodeBefore,o=a.nodeAfter):n>0?(s=a.node(i+1),l++,o=a.node(i).maybeChild(l)):(s=a.node(i).maybeChild(l-1),o=a.node(i+1)),s&&!s.isTextblock&&Vse(s,o)&&a.node(i).canReplace(l,l+1))return e;if(i==0)break;e=n<0?a.before(i):a.after(i)}}function YWe(t,e,n){let a=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?a=!1:!u&&m&&(a=!0)}let l=t.steps.length;if(a===!1){let u=t.doc.resolve(e+n);$se(t,u.node(),u.before(),l)}o.inlineContent&&g5(t,e+n-1,o,s.node().contentMatchAt(s.index()),a==null);let c=t.mapping.slice(l),d=c.map(e-n);if(t.step(new ss(d,c.map(e+n,-1),gn.empty,!0)),a===!0){let u=t.doc.resolve(d);qse(t,u.node(),u.before(),t.steps.length)}return t}function XWe(t,e,n){let a=t.resolve(e);if(a.parent.canReplaceWith(a.index(),a.index(),n))return e;if(a.parentOffset==0)for(let i=a.depth-1;i>=0;i--){let s=a.index(i);if(a.node(i).canReplaceWith(s,s,n))return a.before(i+1);if(s>0)return null}if(a.parentOffset==a.parent.content.size)for(let i=a.depth-1;i>=0;i--){let s=a.indexAfter(i);if(a.node(i).canReplaceWith(s,s,n))return a.after(i+1);if(s<a.node(i).childCount)return null}return null}function Gse(t,e,n){let a=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=a.depth;o>=0;o--){let l=o==a.depth?0:a.pos<=(a.start(o+1)+a.end(o+1))/2?-1:1,c=a.index(o)+(l>0?1:0),d=a.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?a.pos:l<0?a.before(o+1):a.after(o+1)}return null}function zA(t,e,n=e,a=gn.empty){if(e==n&&!a.size)return null;let i=t.resolve(e),s=t.resolve(n);return Wse(i,s,a)?new ss(e,n,a):new ZWe(i,s,a).fit()}function Wse(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class ZWe{constructor(e,n,a){this.$from=e,this.$to=n,this.unplaced=a,this.frontier=[],this.placed=Yt.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=Yt.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,a=this.$from,i=this.close(e<0?this.$to:a.doc.resolve(e));if(!i)return null;let s=this.placed,o=a.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new gn(s,o,l);return e>-1?new ms(a.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||a.pos!=this.$to.pos?new ss(a.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,a=0,i=this.unplaced.openEnd;a<e;a++){let s=n.firstChild;if(n.childCount>1&&(i=0),s.type.spec.isolating&&i<=a){e=a;break}n=s.content}for(let n=1;n<=2;n++)for(let a=n==1?e:this.unplaced.openStart;a>=0;a--){let i,s=null;a?(s=D3(this.unplaced.content,a-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(Yt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:a,frontierDepth:l,parent:s,inject:m};if(n==2&&o&&(u=d.findWrapping(o.type)))return{sliceDepth:a,frontierDepth:l,parent:s,wrap:u};if(s&&d.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:a}=this.unplaced,i=D3(e,n);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new gn(e,n+1,Math.max(a,i.size+n>=e.size-a?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:a}=this.unplaced,i=D3(e,n);if(i.childCount<=1&&n>0){let s=e.size-n<=n+i.size;this.unplaced=new gn(H0(e,n-1,1),n-1,s?n-1:a)}else this.unplaced=new gn(H0(e,n,1),n,a)}placeNodes({sliceDepth:e,frontierDepth:n,parent:a,inject:i,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let w=0;w<s.length;w++)this.openFrontierNode(s[w]);let o=this.unplaced,l=a?a.content:o.content,c=o.openStart-e,d=0,u=[],{match:m,type:p}=this.frontier[n];if(i){for(let w=0;w<i.childCount;w++)u.push(i.child(w));m=m.matchFragment(i)}let f=l.size+e-(o.content.size-o.openEnd);for(;d<l.childCount;){let w=l.child(d),b=m.matchType(w.type);if(!b)break;d++,(d>1||c==0||w.content.size)&&(m=b,u.push(Kse(w.mark(p.allowedMarks(w.marks)),d==1?c:0,d==l.childCount?f:-1)))}let g=d==l.childCount;g||(f=-1),this.placed=q0(this.placed,n,Yt.from(u)),this.frontier[n].match=m,g&&f<0&&a&&a.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let w=0,b=l;w<f;w++){let x=b.lastChild;this.frontier.push({type:x.type,match:x.contentMatchAt(x.childCount)}),b=x.content}this.unplaced=g?e==0?gn.empty:new gn(H0(o.content,e-1,1),e-1,f<0?o.openEnd:e-1):new gn(H0(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||!F3(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:a}=this.$to,i=this.$to.after(a);for(;a>1&&i==this.$to.end(--a);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:a,type:i}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),o=F3(e,n,i,a,s);if(o){for(let l=n-1;l>=0;l--){let{match:c,type:d}=this.frontier[l],u=F3(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=q0(this.placed,n.depth,n.fit)),e=n.move;for(let a=n.depth+1;a<=e.depth;a++){let i=e.node(a),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(a));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,a){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=q0(this.placed,this.depth,Yt.from(e.create(n,a))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Yt.empty,!0);n.childCount&&(this.placed=q0(this.placed,this.frontier.length,n))}}function H0(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(H0(t.firstChild.content,e-1,n)))}function q0(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(q0(t.lastChild.content,e-1,n)))}function D3(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function Kse(t,e,n){if(e<=0)return t;let a=t.content;return e>1&&(a=a.replaceChild(0,Kse(a.firstChild,e-1,a.childCount==1?n-1:0))),e>0&&(a=t.type.contentMatch.fillBefore(a).append(a),n<=0&&(a=a.append(t.type.contentMatch.matchFragment(a).fillBefore(Yt.empty,!0)))),t.copy(a)}function F3(t,e,n,a,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=a.fillBefore(s.content,!0,o);return l&&!JWe(n,s.content,o)?l:null}function JWe(t,e,n){for(let a=n;a<e.childCount;a++)if(!t.allowsMarks(e.child(a).marks))return!0;return!1}function eKe(t){return t.spec.defining||t.spec.definingForContent}function tKe(t,e,n,a){if(!a.size)return t.deleteRange(e,n);let i=t.doc.resolve(e),s=t.doc.resolve(n);if(Wse(i,s,a))return t.step(new ss(e,n,a));let o=Yse(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 g=i.node(p).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;o.indexOf(p)>-1?l=p:i.before(p)==f&&o.splice(1,0,-p)}let c=o.indexOf(l),d=[],u=a.openStart;for(let p=a.content,f=0;;f++){let g=p.firstChild;if(d.push(g),f==a.openStart)break;p=g.content}for(let p=u-1;p>=0;p--){let f=d[p],g=eKe(f.type);if(g&&!f.sameMarkup(i.node(Math.abs(l)-1)))u=p;else if(g||!f.type.isTextblock)break}for(let p=a.openStart;p>=0;p--){let f=(p+u+1)%(a.openStart+1),g=d[f];if(g)for(let w=0;w<o.length;w++){let b=o[(w+c)%o.length],x=!0;b<0&&(x=!1,b=-b);let S=i.node(b-1),k=i.index(b-1);if(S.canReplaceWith(k,k,g.type,g.marks))return t.replace(i.before(b),x?s.after(b):n,new gn(Qse(a.content,0,a.openStart,f),f,a.openEnd))}}let m=t.steps.length;for(let p=o.length-1;p>=0&&(t.replace(e,n,a),!(t.steps.length>m));p--){let f=o[p];f<0||(e=i.before(f),n=s.after(f))}}function Qse(t,e,n,a,i){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(Qse(s.content,e+1,n,a,s)))}if(e>a){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Yt.empty,!0))}return t}function nKe(t,e,n,a){if(!a.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=XWe(t.doc,e,a.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new gn(Yt.from(a),0,0))}function rKe(t,e,n){let a=t.doc.resolve(e),i=t.doc.resolve(n),s=Yse(a,i);for(let o=0;o<s.length;o++){let l=s[o],c=o==s.length-1;if(c&&l==0||a.node(l).type.contentMatch.validEnd)return t.delete(a.start(l),i.end(l));if(l>0&&(c||a.node(l-1).canReplace(a.index(l-1),i.indexAfter(l-1))))return t.delete(a.before(l),i.after(l))}for(let o=1;o<=a.depth&&o<=i.depth;o++)if(e-a.start(o)==a.depth-o&&n>a.end(o)&&i.end(o)-n!=i.depth-o&&a.start(o-1)==i.start(o-1)&&a.node(o-1).canReplace(a.index(o-1),i.index(o-1)))return t.delete(a.before(o),n);t.delete(e,n)}function Yse(t,e){let n=[],a=Math.min(t.depth,e.depth);for(let i=a;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 py extends oo{constructor(e,n,a){super(),this.pos=e,this.attr=n,this.value=a}apply(e){let n=e.nodeAt(this.pos);if(!n)return Ni.fail("No node at attribute step's position");let a=Object.create(null);for(let s in n.attrs)a[s]=n.attrs[s];a[this.attr]=this.value;let i=n.type.create(a,null,n.marks);return Ni.fromReplace(e,this.pos,this.pos+1,new gn(Yt.from(i),0,n.isLeaf?0:1))}getMap(){return xl.empty}invert(e){return new py(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 py(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 py(n.pos,n.attr,n.value)}}oo.jsonID("attr",py);class uS extends oo{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 a=e.type.create(n,e.content,e.marks);return Ni.ok(a)}getMap(){return xl.empty}invert(e){return new uS(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 uS(n.attr,n.value)}}oo.jsonID("docAttr",uS);let Ry=class extends Error{};Ry=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Ry.prototype=Object.create(Error.prototype);Ry.prototype.constructor=Ry;Ry.prototype.name="TransformError";class Xse{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new dS}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Ry(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 a=0;a<this.mapping.maps.length;a++){let i=this.mapping.maps[a];a&&(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,a=gn.empty){let i=zA(this.doc,e,n,a);return i&&this.step(i),this}replaceWith(e,n,a){return this.replace(e,n,new gn(Yt.from(a),0,0))}delete(e,n){return this.replace(e,n,gn.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,a){return tKe(this,e,n,a),this}replaceRangeWith(e,n,a){return nKe(this,e,n,a),this}deleteRange(e,n){return rKe(this,e,n),this}lift(e,n){return BWe(this,e,n),this}join(e,n=1){return YWe(this,e,n),this}wrap(e,n){return $We(this,e,n),this}setBlockType(e,n=e,a,i=null){return VWe(this,e,n,a,i),this}setNodeMarkup(e,n,a=null,i){return WWe(this,e,n,a,i),this}setNodeAttribute(e,n,a){return this.step(new py(e,n,a)),this}setDocAttribute(e,n){return this.step(new uS(e,n)),this}addNodeMark(e,n){return this.step(new _h(e,n)),this}removeNodeMark(e,n){let a=this.doc.nodeAt(e);if(!a)throw new RangeError("No node at position "+e);if(n instanceof ha)n.isInSet(a.marks)&&this.step(new Xg(e,n));else{let i=a.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new Xg(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,a){return KWe(this,e,n,a),this}addMark(e,n,a){return OWe(this,e,n,a),this}removeMark(e,n,a){return zWe(this,e,n,a),this}clearIncompatible(e,n,a){return g5(this,e,n,a),this}}const L3=Object.create(null);class sr{constructor(e,n,a){this.$anchor=e,this.$head=n,this.ranges=a||[new aKe(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=gn.empty){let a=n.content.lastChild,i=null;for(let l=0;l<n.openEnd;l++)i=a,a=a.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?gn.empty:n),l==0&&AQ(e,s,(a?a.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,n){let a=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(a),d=c.map(o.pos),u=c.map(l.pos);s?e.deleteRange(d,u):(e.replaceRangeWith(d,u,n),AQ(e,a,n.isInline?-1:1))}}static findFrom(e,n,a=!1){let i=e.parent.inlineContent?new Vn(e):Hx(e.node(0),e.parent,e.pos,e.index(),n,a);if(i)return i;for(let s=e.depth-1;s>=0;s--){let o=n<0?Hx(e.node(0),e.node(s),e.before(s+1),e.index(s),n,a):Hx(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,a);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new Nl(e.node(0))}static atStart(e){return Hx(e,e,0,0,1)||new Nl(e)}static atEnd(e){return Hx(e,e,e.content.size,e.childCount,-1)||new Nl(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let a=L3[n.type];if(!a)throw new RangeError(`No selection type ${n.type} defined`);return a.fromJSON(e,n)}static jsonID(e,n){if(e in L3)throw new RangeError("Duplicate use of selection JSON ID "+e);return L3[e]=n,n.prototype.jsonID=e,n}getBookmark(){return Vn.between(this.$anchor,this.$head).getBookmark()}}sr.prototype.visible=!0;class aKe{constructor(e,n){this.$from=e,this.$to=n}}let PQ=!1;function TQ(t){!PQ&&!t.parent.inlineContent&&(PQ=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class Vn extends sr{constructor(e,n=e){TQ(e),TQ(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let a=e.resolve(n.map(this.head));if(!a.parent.inlineContent)return sr.near(a);let i=e.resolve(n.map(this.anchor));return new Vn(i.parent.inlineContent?i:a,a)}replace(e,n=gn.empty){if(super.replace(e,n),n==gn.empty){let a=this.$from.marksAcross(this.$to);a&&e.ensureMarks(a)}}eq(e){return e instanceof Vn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new UA(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 Vn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,a=n){let i=e.resolve(n);return new this(i,a==n?i:e.resolve(a))}static between(e,n,a){let i=e.pos-n.pos;if((!a||i)&&(a=i>=0?1:-1),!n.parent.inlineContent){let s=sr.findFrom(n,a,!0)||sr.findFrom(n,-a,!0);if(s)n=s.$head;else return sr.near(n,a)}return e.parent.inlineContent||(i==0?e=n:(e=(sr.findFrom(e,-a,!0)||sr.findFrom(e,a,!0)).$anchor,e.pos<n.pos!=i<0&&(e=n))),new Vn(e,n)}}sr.jsonID("text",Vn);class UA{constructor(e,n){this.anchor=e,this.head=n}map(e){return new UA(e.map(this.anchor),e.map(this.head))}resolve(e){return Vn.between(e.resolve(this.anchor),e.resolve(this.head))}}class Rn extends sr{constructor(e){let n=e.nodeAfter,a=e.node(0).resolve(e.pos+n.nodeSize);super(e,a),this.node=n}map(e,n){let{deleted:a,pos:i}=n.mapResult(this.anchor),s=e.resolve(i);return a?sr.near(s):new Rn(s)}content(){return new gn(Yt.from(this.node),0,0)}eq(e){return e instanceof Rn&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new x5(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Rn(e.resolve(n.anchor))}static create(e,n){return new Rn(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}Rn.prototype.visible=!1;sr.jsonID("node",Rn);class x5{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:a}=e.mapResult(this.anchor);return n?new UA(a,a):new x5(a)}resolve(e){let n=e.resolve(this.anchor),a=n.nodeAfter;return a&&Rn.isSelectable(a)?new Rn(n):sr.near(n)}}class Nl extends sr{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=gn.empty){if(n==gn.empty){e.delete(0,e.doc.content.size);let a=sr.atStart(e.doc);a.eq(e.selection)||e.setSelection(a)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new Nl(e)}map(e){return new Nl(e)}eq(e){return e instanceof Nl}getBookmark(){return iKe}}sr.jsonID("all",Nl);const iKe={map(){return this},resolve(t){return new Nl(t)}};function Hx(t,e,n,a,i,s=!1){if(e.inlineContent)return Vn.create(t,n);for(let o=a-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&Rn.isSelectable(l))return Rn.create(t,n-(i<0?l.nodeSize:0))}else{let c=Hx(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function AQ(t,e,n){let a=t.steps.length-1;if(a<e)return;let i=t.steps[a];if(!(i instanceof ss||i instanceof ms))return;let s=t.mapping.maps[a],o;s.forEach((l,c,d,u)=>{o==null&&(o=u)}),t.setSelection(sr.near(t.doc.resolve(o),n))}const jQ=1,Y1=2,MQ=4;class sKe extends Xse{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|jQ)&~Y1,this.storedMarks=null,this}get selectionSet(){return(this.updated&jQ)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Y1,this}ensureMarks(e){return ha.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&Y1)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Y1,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let a=this.selection;return n&&(e=e.mark(this.storedMarks||(a.empty?a.$from.marks():a.$from.marksAcross(a.$to)||ha.none))),a.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,a){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(a==null&&(a=n),!e)return this.deleteRange(n,a);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=a==n?o.marks():o.marksAcross(this.doc.resolve(a))}return this.replaceRangeWith(n,a,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(sr.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|=MQ,this}get scrolledIntoView(){return(this.updated&MQ)>0}}function EQ(t,e){return!e||!t?t:t.bind(e)}class $0{constructor(e,n,a){this.name=e,this.init=EQ(n.init,a),this.apply=EQ(n.apply,a)}}const oKe=[new $0("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new $0("selection",{init(t,e){return t.selection||sr.atStart(e.doc)},apply(t){return t.selection}}),new $0("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,a){return a.selection.$cursor?t.storedMarks:null}}),new $0("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class R3{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=oKe.slice(),n&&n.forEach(a=>{if(this.pluginsByKey[a.key])throw new RangeError("Adding different instances of a keyed plugin ("+a.key+")");this.plugins.push(a),this.pluginsByKey[a.key]=a,a.spec.state&&this.fields.push(new $0(a.key,a.spec.state,a))})}}class Jx{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 a=0;a<this.config.plugins.length;a++)if(a!=n){let i=this.config.plugins[a];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],a=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,a);if(u&&a.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:a,n:n.length}:{state:this,n:0})}n.push(u),a=a.applyInner(u),s=!0}i&&(i[o]={state:a,n:n.length})}}if(!s)return{state:a,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new Jx(this.config),a=this.config.fields;for(let i=0;i<a.length;i++){let s=a[i];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new sKe(this)}static create(e){let n=new R3(e.doc?e.doc.type.schema:e.schema,e.plugins),a=new Jx(n);for(let i=0;i<n.fields.length;i++)a[n.fields[i].name]=n.fields[i].init(e,a);return a}reconfigure(e){let n=new R3(this.schema,e.plugins),a=n.fields,i=new Jx(n);for(let s=0;s<a.length;s++){let o=a[s].name;i[o]=this.hasOwnProperty(o)?this[o]:a[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(a=>a.toJSON())),e&&typeof e=="object")for(let a in e){if(a=="doc"||a=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[a],s=i.spec.state;s&&s.toJSON&&(n[a]=s.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,a){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new R3(e.schema,e.plugins),s=new Jx(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=pd.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=sr.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(a)for(let l in a){let c=a[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 Zse(t,e,n){for(let a in t){let i=t[a];i instanceof Function?i=i.bind(e):a=="handleDOMEvents"&&(i=Zse(i,e,{})),n[a]=i}return n}class Wa{constructor(e){this.spec=e,this.props={},e.props&&Zse(e.props,this,this.props),this.key=e.key?e.key.key:Jse("plugin")}getState(e){return e[this.key]}}const I3=Object.create(null);function Jse(t){return t in I3?t+"$"+ ++I3[t]:(I3[t]=0,t+"$")}class Wi{constructor(e="key"){this.key=Jse(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const y5=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function eoe(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const toe=(t,e,n)=>{let a=eoe(t,n);if(!a)return!1;let i=v5(a);if(!i){let o=a.blockRange(),l=o&&mv(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(doe(t,i,e,-1))return!0;if(a.parent.content.size==0&&(Iy(s,"end")||Rn.isSelectable(s)))for(let o=a.depth;;o--){let l=zA(t.doc,a.before(o),a.after(o),gn.empty);if(l&&l.slice.size<l.to-l.from){if(e){let c=t.tr.step(l);c.setSelection(Iy(s,"end")?sr.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):Rn.create(c.doc,i.pos-s.nodeSize)),e(c.scrollIntoView())}return!0}if(o==1||a.node(o-1).childCount>1)break}return s.isAtom&&i.depth==a.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},lKe=(t,e,n)=>{let a=eoe(t,n);if(!a)return!1;let i=v5(a);return i?noe(t,i,e):!1},cKe=(t,e,n)=>{let a=aoe(t,n);if(!a)return!1;let i=w5(a);return i?noe(t,i,e):!1};function noe(t,e,n){let a=e.nodeBefore,i=a,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=zA(t.doc,s,c,gn.empty);if(!d||d.from!=s||d instanceof ss&&d.slice.size>=c-s)return!1;if(n){let u=t.tr.step(d);u.setSelection(Vn.create(u.doc,s)),n(u.scrollIntoView())}return!0}function Iy(t,e,n=!1){for(let a=t;a;a=e=="start"?a.firstChild:a.lastChild){if(a.isTextblock)return!0;if(n&&a.childCount!=1)return!1}return!1}const roe=(t,e,n)=>{let{$head:a,empty:i}=t.selection,s=a;if(!i)return!1;if(a.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):a.parentOffset>0)return!1;s=v5(a)}let o=s&&s.nodeBefore;return!o||!Rn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Rn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function v5(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 aoe(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const ioe=(t,e,n)=>{let a=aoe(t,n);if(!a)return!1;let i=w5(a);if(!i)return!1;let s=i.nodeAfter;if(doe(t,i,e,1))return!0;if(a.parent.content.size==0&&(Iy(s,"start")||Rn.isSelectable(s))){let o=zA(t.doc,a.before(),a.after(),gn.empty);if(o&&o.slice.size<o.to-o.from){if(e){let l=t.tr.step(o);l.setSelection(Iy(s,"start")?sr.findFrom(l.doc.resolve(l.mapping.map(i.pos)),1):Rn.create(l.doc,l.mapping.map(i.pos))),e(l.scrollIntoView())}return!0}}return s.isAtom&&i.depth==a.depth-1?(e&&e(t.tr.delete(i.pos,i.pos+s.nodeSize).scrollIntoView()),!0):!1},soe=(t,e,n)=>{let{$head:a,empty:i}=t.selection,s=a;if(!i)return!1;if(a.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):a.parentOffset<a.parent.content.size)return!1;s=w5(a)}let o=s&&s.nodeAfter;return!o||!Rn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(Rn.create(t.doc,s.pos)).scrollIntoView()),!0)};function w5(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 dKe=(t,e)=>{let n=t.selection,a=n instanceof Rn,i;if(a){if(n.node.isTextblock||!uf(t.doc,n.from))return!1;i=n.from}else if(i=OA(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);a&&s.setSelection(Rn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},uKe=(t,e)=>{let n=t.selection,a;if(n instanceof Rn){if(n.node.isTextblock||!uf(t.doc,n.to))return!1;a=n.to}else if(a=OA(t.doc,n.to,1),a==null)return!1;return e&&e(t.tr.join(a).scrollIntoView()),!0},mKe=(t,e)=>{let{$from:n,$to:a}=t.selection,i=n.blockRange(a),s=i&&mv(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},ooe=(t,e)=>{let{$head:n,$anchor:a}=t.selection;return!n.parent.type.spec.code||!n.sameParent(a)?!1:(e&&e(t.tr.insertText(`
  8189. `).scrollIntoView()),!0)};function S5(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 pKe=(t,e)=>{let{$head:n,$anchor:a}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(a))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=S5(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(sr.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},loe=(t,e)=>{let n=t.selection,{$from:a,$to:i}=n;if(n instanceof Nl||a.parent.inlineContent||i.parent.inlineContent)return!1;let s=S5(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!a.parentOffset&&i.index()<i.parent.childCount?a:i).pos,l=t.tr.insert(o,s.createAndFill());l.setSelection(Vn.create(l.doc,o+1)),e(l.scrollIntoView())}return!0},coe=(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(zm(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let a=n.blockRange(),i=a&&mv(a);return i==null?!1:(e&&e(t.tr.lift(a,i).scrollIntoView()),!0)};function hKe(t){return(e,n)=>{let{$from:a,$to:i}=e.selection;if(e.selection instanceof Rn&&e.selection.node.isBlock)return!a.parentOffset||!zm(e.doc,a.pos)?!1:(n&&n(e.tr.split(a.pos).scrollIntoView()),!0);if(!a.depth)return!1;let s=[],o,l,c=!1,d=!1;for(let f=a.depth;;f--)if(a.node(f).isBlock){c=a.end(f)==a.pos+(a.depth-f),d=a.start(f)==a.pos-(a.depth-f),l=S5(a.node(f-1).contentMatchAt(a.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 Vn||e.selection instanceof Nl)&&u.deleteSelection();let m=u.mapping.map(a.pos),p=zm(u.doc,m,s.length,s);if(p||(s[0]=l?{type:l}:null,p=zm(u.doc,m,s.length,s)),!p)return!1;if(u.split(m,s.length,s),!c&&d&&a.node(o).type!=l){let f=u.mapping.map(a.before(o)),g=u.doc.resolve(f);l&&a.node(o-1).canReplaceWith(g.index(),g.index()+1,l)&&u.setNodeMarkup(u.mapping.map(a.before(o)),l)}return n&&n(u.scrollIntoView()),!0}}const fKe=hKe(),gKe=(t,e)=>{let{$from:n,to:a}=t.selection,i,s=n.sharedDepth(a);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(Rn.create(t.doc,i))),!0)};function bKe(t,e,n){let a=e.nodeBefore,i=e.nodeAfter,s=e.index();return!a||!i||!a.type.compatibleContent(i.type)?!1:!a.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-a.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||uf(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function doe(t,e,n,a){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&bKe(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,g=Yt.empty;for(let x=o.length-1;x>=0;x--)g=Yt.from(o[x].create(null,g));g=Yt.from(i.copy(g));let w=t.tr.step(new ms(e.pos-1,f,e.pos,f,new gn(g,1,0),o.length,!0)),b=w.doc.resolve(f+2*o.length);b.nodeAfter&&b.nodeAfter.type==i.type&&uf(w.doc,b.pos)&&w.join(b.pos),n(w.scrollIntoView())}return!0}let u=s.type.spec.isolating||a>0&&c?null:sr.findFrom(e,1),m=u&&u.$from.blockRange(u.$to),p=m&&mv(m);if(p!=null&&p>=e.depth)return n&&n(t.tr.lift(m,p).scrollIntoView()),!0;if(d&&Iy(s,"start",!0)&&Iy(i,"end")){let f=i,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let w=s,b=1;for(;!w.isTextblock;w=w.firstChild)b++;if(f.canReplace(f.childCount,f.childCount,w.content)){if(n){let x=Yt.empty;for(let k=g.length-1;k>=0;k--)x=Yt.from(g[k].copy(x));let S=t.tr.step(new ms(e.pos-g.length,e.pos+s.nodeSize,e.pos+b,e.pos+s.nodeSize-b,new gn(x,g.length,0),0,!0));n(S.scrollIntoView())}return!0}}return!1}function uoe(t){return function(e,n){let a=e.selection,i=t<0?a.$from:a.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection(Vn.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const xKe=uoe(-1),yKe=uoe(1);function vKe(t,e=null){return function(n,a){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&b5(o,t,e);return l?(a&&a(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function DQ(t,e=null){return function(n,a){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(a){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)}a(s.scrollIntoView())}return!0}}function _5(...t){return function(e,n,a){for(let i=0;i<t.length;i++)if(t[i](e,n,a))return!0;return!1}}_5(y5,toe,roe);_5(y5,ioe,soe);_5(ooe,loe,coe,fKe);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function wKe(t,e=null){return function(n,a){let{$from:i,$to:s}=n.selection,o=i.blockRange(s);if(!o)return!1;let l=a?n.tr:null;return SKe(l,o,t,e)?(a&&a(l.scrollIntoView()),!0):!1}}function SKe(t,e,n,a=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 NP(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new NP(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let l=b5(s,n,a,e);return l?(t&&_Ke(t,e,l,i,n),!0):!1}function _Ke(t,e,n,a,i){let s=Yt.empty;for(let u=n.length-1;u>=0;u--)s=Yt.from(n[u].type.create(n[u].attrs,s));t.step(new ms(e.start-(a?2:0),e.end,e.start,e.end,new gn(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-(a?2:0),d=e.parent;for(let u=e.startIndex,m=e.endIndex,p=!0;u<m;u++,p=!1)!p&&zm(t.doc,c,l)&&(t.split(c,l),c+=2*l),c+=d.child(u).nodeSize;return t}function kKe(t){return function(e,n){let{$from:a,$to:i}=e.selection,s=a.blockRange(i,o=>o.childCount>0&&o.firstChild.type==t);return s?n?a.node(s.depth-1).type==t?NKe(e,n,t,s):CKe(e,n,s):!0:!1}}function NKe(t,e,n,a){let i=t.tr,s=a.end,o=a.$to.end(a.depth);s<o&&(i.step(new ms(s-1,o,s,o,new gn(Yt.from(n.create(null,a.parent.copy())),1,0),1,!0)),a=new NP(i.doc.resolve(a.$from.pos),i.doc.resolve(o),a.depth));const l=mv(a);if(l==null)return!1;i.lift(a,l);let c=i.doc.resolve(i.mapping.map(s,-1)-1);return uf(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&i.join(c.pos),e(i.scrollIntoView()),!0}function CKe(t,e,n){let a=t.tr,i=n.parent;for(let f=n.end,g=n.endIndex-1,w=n.startIndex;g>w;g--)f-=i.child(g).nodeSize,a.delete(f-1,f+1);let s=a.doc.resolve(n.start),o=s.nodeAfter;if(a.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?Yt.empty:Yt.from(i))))return!1;let m=s.pos,p=m+o.nodeSize;return a.step(new ms(m-(l?1:0),p+(c?1:0),m+1,p-1,new gn((l?Yt.empty:Yt.from(i.copy(Yt.empty))).append(c?Yt.empty:Yt.from(i.copy(Yt.empty))),l?0:1,c?0:1),l?0:1)),e(a.scrollIntoView()),!0}function PKe(t){return function(e,n){let{$from:a,$to:i}=e.selection,s=a.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=Yt.from(d?t.create():null),m=new gn(Yt.from(t.create(null,Yt.from(l.type.create(null,u)))),d?3:1,0),p=s.start,f=s.end;n(e.tr.step(new ms(p-(d?3:1),f,p,f,m,1,!0)).scrollIntoView())}return!0}}const Fs=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Oy=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let yI=null;const hm=function(t,e,n){let a=yI||(yI=document.createRange());return a.setEnd(t,n??t.nodeValue.length),a.setStart(t,e||0),a},TKe=function(){yI=null},Zg=function(t,e,n,a){return n&&(FQ(t,e,n,a,-1)||FQ(t,e,n,a,1))},AKe=/^(img|br|input|textarea|hr)$/i;function FQ(t,e,n,a,i){for(var s;;){if(t==n&&e==a)return!0;if(e==(i<0?0:lc(t))){let o=t.parentNode;if(!o||o.nodeType!=1||p_(t)||AKe.test(t.nodeName)||t.contentEditable=="false")return!1;e=Fs(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?lc(t):0}else return!1}}function lc(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function jKe(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=lc(t)}else if(t.parentNode&&!p_(t))e=Fs(t),t=t.parentNode;else return null}}function MKe(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&&!p_(t))e=Fs(t)+1,t=t.parentNode;else return null}}function EKe(t,e,n){for(let a=e==0,i=e==lc(t);a||i;){if(t==n)return!0;let s=Fs(t);if(t=t.parentNode,!t)return!1;a=a&&s==0,i=i&&s==lc(t)}}function p_(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 BA=function(t){return t.focusNode&&Zg(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function rg(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function DKe(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function FKe(t,e,n){if(t.caretPositionFromPoint)try{let a=t.caretPositionFromPoint(e,n);if(a)return{node:a.offsetNode,offset:Math.min(lc(a.offsetNode),a.offset)}}catch{}if(t.caretRangeFromPoint){let a=t.caretRangeFromPoint(e,n);if(a)return{node:a.startContainer,offset:Math.min(lc(a.startContainer),a.startOffset)}}}const vu=typeof navigator<"u"?navigator:null,LQ=typeof document<"u"?document:null,mf=vu&&vu.userAgent||"",vI=/Edge\/(\d+)/.exec(mf),moe=/MSIE \d/.exec(mf),wI=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(mf),Yo=!!(moe||wI||vI),Uh=moe?document.documentMode:wI?+wI[1]:vI?+vI[1]:0,xc=!Yo&&/gecko\/(\d+)/i.test(mf);xc&&+(/Firefox\/(\d+)/.exec(mf)||[0,0])[1];const SI=!Yo&&/Chrome\/(\d+)/.exec(mf),Is=!!SI,poe=SI?+SI[1]:0,ao=!Yo&&!!vu&&/Apple Computer/.test(vu.vendor),zy=ao&&(/Mobile\/\w+/.test(mf)||!!vu&&vu.maxTouchPoints>2),tc=zy||(vu?/Mac/.test(vu.platform):!1),hoe=vu?/Win/.test(vu.platform):!1,Mm=/Android \d/.test(mf),h_=!!LQ&&"webkitFontSmoothing"in LQ.documentElement.style,LKe=h_?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function RKe(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 sm(t,e){return typeof t=="number"?t:t[e]}function IKe(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,a=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*a}}function RQ(t,e,n){let a=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=Oy(o);continue}let l=o,c=l==s.body,d=c?RKe(s):IKe(l),u=0,m=0;if(e.top<d.top+sm(a,"top")?m=-(d.top-e.top+sm(i,"top")):e.bottom>d.bottom-sm(a,"bottom")&&(m=e.bottom-e.top>d.bottom-d.top?e.top+sm(i,"top")-d.top:e.bottom-d.bottom+sm(i,"bottom")),e.left<d.left+sm(a,"left")?u=-(d.left-e.left+sm(i,"left")):e.right>d.right-sm(a,"right")&&(u=e.right-d.right+sm(i,"right")),u||m)if(c)s.defaultView.scrollBy(u,m);else{let f=l.scrollLeft,g=l.scrollTop;m&&(l.scrollTop+=m),u&&(l.scrollLeft+=u);let w=l.scrollLeft-f,b=l.scrollTop-g;e={left:e.left-w,top:e.top-b,right:e.right-w,bottom:e.bottom-b}}let p=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(p))break;o=p=="absolute"?o.offsetParent:Oy(o)}}function OKe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),a,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){a=l,i=c.top;break}}return{refDOM:a,refTop:i,stack:foe(t.dom)}}function foe(t){let e=[],n=t.ownerDocument;for(let a=t;a&&(e.push({dom:a,top:a.scrollTop,left:a.scrollLeft}),t!=n);a=Oy(a));return e}function zKe({refDOM:t,refTop:e,stack:n}){let a=t?t.getBoundingClientRect().top:0;goe(n,a==0?0:a-e)}function goe(t,e){for(let n=0;n<t.length;n++){let{dom:a,top:i,left:s}=t[n];a.scrollTop!=i+e&&(a.scrollTop=i+e),a.scrollLeft!=s&&(a.scrollLeft=s)}}let Fx=null;function UKe(t){if(t.setActive)return t.setActive();if(Fx)return t.focus(Fx);let e=foe(t);t.focus(Fx==null?{get preventScroll(){return Fx={preventScroll:!0},!0}}:void 0),Fx||(Fx=!1,goe(e,0))}function boe(t,e){let n,a=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=hm(u).getClientRects();else continue;for(let f=0;f<p.length;f++){let g=p[f];if(g.top<=o&&g.bottom>=l){o=Math.max(g.bottom,o),l=Math.min(g.top,l);let w=g.left>e.left?g.left-e.left:g.right<e.left?e.left-g.right:0;if(w<a){n=u,a=w,i=w&&n.nodeType==3?{left:g.right<e.left?g.right:g.left,top:e.top}:e,u.nodeType==1&&w&&(s=m+(e.left>=(g.left+g.right)/2?1:0));continue}}else g.top>e.top&&!c&&g.left<=e.left&&g.right>=e.left&&(c=u,d={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top});!n&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom)&&(s=m+1)}}return!n&&c&&(n=c,i=d,a=0),n&&n.nodeType==3?BKe(n,i):!n||a&&n.nodeType==1?{node:t,offset:s}:boe(n,i)}function BKe(t,e){let n=t.nodeValue.length,a=document.createRange(),i;for(let s=0;s<n;s++){a.setEnd(t,s+1),a.setStart(t,s);let o=th(a,1);if(o.top!=o.bottom&&k5(e,o)){i={node:t,offset:s+(e.left>=(o.left+o.right)/2?1:0)};break}}return a.detach(),i||{node:t,offset:0}}function k5(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function HKe(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function qKe(t,e,n){let{node:a,offset:i}=boe(e,n),s=-1;if(a.nodeType==1&&!a.firstChild){let o=a.getBoundingClientRect();s=o.left!=o.right&&n.left>(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(a,i,s)}function $Ke(t,e,n,a){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>a.left||c.top>a.top?i=l.posBefore:(!o&&c.right<a.left||c.bottom<a.top)&&(i=l.posAfter),o=!0),!l.contentDOM&&i<0&&!l.node.isText))return(l.node.isBlock?a.top<(c.top+c.bottom)/2:a.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 xoe(t,e,n){let a=t.childNodes.length;if(a&&n.top<n.bottom)for(let i=Math.max(0,Math.min(a-1,Math.floor(a*(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(k5(e,d))return xoe(o,e,d)}}if((s=(s+1)%a)==i)break}return t}function VKe(t,e){let n=t.dom.ownerDocument,a,i=0,s=FKe(n,e.left,e.top);s&&({node:a,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(!k5(e,d)||(o=xoe(t.dom,e,d),!o))return null}if(ao)for(let d=o;a&&d;d=Oy(d))d.draggable&&(a=void 0);if(o=HKe(o,e),a){if(xc&&a.nodeType==1&&(i=Math.min(i,a.childNodes.length),i<a.childNodes.length)){let u=a.childNodes[i],m;u.nodeName=="IMG"&&(m=u.getBoundingClientRect()).right<=e.left&&m.bottom>e.top&&i++}let d;h_&&i&&a.nodeType==1&&(d=a.childNodes[i-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top&&i--,a==t.dom&&i==a.childNodes.length-1&&a.lastChild.nodeType==1&&e.top>a.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||a.nodeType!=1||a.childNodes[i-1].nodeName!="BR")&&(l=$Ke(t,a,i,e))}l==null&&(l=qKe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function IQ(t){return t.top<t.bottom||t.left<t.right}function th(t,e){let n=t.getClientRects();if(n.length){let a=n[e<0?0:n.length-1];if(IQ(a))return a}return Array.prototype.find.call(n,IQ)||t.getBoundingClientRect()}const GKe=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function yoe(t,e,n){let{node:a,offset:i,atom:s}=t.docView.domFromPos(e,n<0?-1:1),o=h_||xc;if(a.nodeType==3)if(o&&(GKe.test(a.nodeValue)||(n<0?!i:i==a.nodeValue.length))){let c=th(hm(a,i,i),n);if(xc&&i&&/\s/.test(a.nodeValue[i-1])&&i<a.nodeValue.length){let d=th(hm(a,i-1,i-1),-1);if(d.top==c.top){let u=th(hm(a,i,i+1),-1);if(u.top!=c.top)return T0(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==a.nodeValue.length?(c--,u=1):n<0?c--:d++,T0(th(hm(a,c,d),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==lc(a))){let c=a.childNodes[i-1];if(c.nodeType==1)return O3(c.getBoundingClientRect(),!1)}if(s==null&&i<lc(a)){let c=a.childNodes[i];if(c.nodeType==1)return O3(c.getBoundingClientRect(),!0)}return O3(a.getBoundingClientRect(),n>=0)}if(s==null&&i&&(n<0||i==lc(a))){let c=a.childNodes[i-1],d=c.nodeType==3?hm(c,lc(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return T0(th(d,1),!1)}if(s==null&&i<lc(a)){let c=a.childNodes[i];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let d=c?c.nodeType==3?hm(c,0,o?0:1):c.nodeType==1?c:null:null;if(d)return T0(th(d,-1),!0)}return T0(th(a.nodeType==3?hm(a):a,-n),n>=0)}function T0(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 O3(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 voe(t,e,n){let a=t.state,i=t.root.activeElement;a!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{a!=e&&t.updateState(a),i!=t.dom&&i&&i.focus()}}function WKe(t,e,n){let a=e.selection,i=n=="up"?a.$from:a.$to;return voe(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=yoe(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=hm(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 KKe=/[\u0590-\u08ac]/;function QKe(t,e,n){let{$head:a}=e.selection;if(!a.parent.isTextblock)return!1;let i=a.parentOffset,s=!i,o=i==a.parent.content.size,l=t.domSelection();return l?!KKe.test(a.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:voe(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:m}=t.domSelectionRange(),p=l.caretBidiLevel;l.modify("move",n,"character");let f=a.depth?t.docView.domAfterPos(a.before()):t.dom,{focusNode:g,focusOffset:w}=t.domSelectionRange(),b=g&&!f.contains(g.nodeType==1?g:g.parentNode)||c==g&&d==w;try{l.collapse(u,m),c&&(c!=u||d!=m)&&l.extend&&l.extend(c,d)}catch{}return p!=null&&(l.caretBidiLevel=p),b}):a.pos==a.start()||a.pos==a.end()}let OQ=null,zQ=null,UQ=!1;function YKe(t,e,n){return OQ==e&&zQ==n?UQ:(OQ=e,zQ=n,UQ=n=="up"||n=="down"?WKe(t,e,n):QKe(t,e,n))}const yc=0,BQ=1,dg=2,wu=3;class f_{constructor(e,n,a,i){this.parent=e,this.children=n,this.dom=a,this.contentDOM=i,this.dirty=yc,a.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,a){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,a=this.posAtStart;;n++){let i=this.children[n];if(i==e)return a;a+=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,a){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(a<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>Fs(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??a>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let a=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!n||s.node))if(a&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))a=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let a=n;a;a=a.parent)if(a==this)return n}posFromDOM(e,n,a){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,a)}return-1}descAt(e){for(let n=0,a=0;n<this.children.length;n++){let i=this.children[n],s=a+i.size;if(a==e&&s!=a){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-a-i.border);a=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let a=0,i=0;for(let s=0;a<this.children.length;a++){let o=this.children[a],l=s+o.size;if(l>e||o instanceof Soe){i=e-s;break}s=l}if(i)return this.children[a].domFromPos(i-this.children[a].border,n);for(let s;a&&!(s=this.children[a-1]).size&&s instanceof woe&&s.side>=0;a--);if(n<=0){let s,o=!0;for(;s=a?this.children[a-1]:null,!(!s||s.dom.parentNode==this.contentDOM);a--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?Fs(s.dom)+1:0}}else{let s,o=!0;for(;s=a<this.children.length?this.children[a]:null,!(!s||s.dom.parentNode==this.contentDOM);a++,o=!1);return s&&o&&!s.border&&!s.domAtom?s.domFromPos(0,n):{node:this.contentDOM,offset:s?Fs(s.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,a=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=a,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=Fs(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=Fs(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:a}=this.domFromPos(e,0);if(n.nodeType!=1||a==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[a]}setSelection(e,n,a,i=!1){let s=Math.min(e,n),o=Math.max(e,n);for(let f=0,g=0;f<this.children.length;f++){let w=this.children[f],b=g+w.size;if(s>g&&o<b)return w.setSelection(e-g-w.border,n-g-w.border,a,i);g=b}let l=this.domFromPos(e,e?-1:1),c=n==e?l:this.domFromPos(n,n?-1:1),d=a.root.getSelection(),u=a.domSelectionRange(),m=!1;if((xc||ao)&&e==n){let{node:f,offset:g}=l;if(f.nodeType==3){if(m=!!(g&&f.nodeValue[g-1]==`
  8190. `),m&&g==f.nodeValue.length)for(let w=f,b;w;w=w.parentNode){if(b=w.nextSibling){b.nodeName=="BR"&&(l=c={node:b.parentNode,offset:Fs(b)+1});break}let x=w.pmViewDesc;if(x&&x.node&&x.node.isBlock)break}}else{let w=f.childNodes[g-1];m=w&&(w.nodeName=="BR"||w.contentEditable=="false")}}if(xc&&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&&ao)&&Zg(l.node,l.offset,u.anchorNode,u.anchorOffset)&&Zg(c.node,c.offset,u.focusNode,u.focusOffset))return;let p=!1;if((d.extend||e==n)&&!(m&&xc)){d.collapse(l.node,l.offset);try{e!=n&&d.extend(c.node,c.offset),p=!0}catch{}}if(!p){if(e>n){let g=l;l=c,c=g}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 a=0,i=0;i<this.children.length;i++){let s=this.children[i],o=a+s.size;if(a==o?e<=o&&n>=a:e<o&&n>a){let l=a+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==a||n==o?dg:BQ,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=wu:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?dg:wu}a=o}this.dirty=dg}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let a=e==1?dg:BQ;n.dirty<a&&(n.dirty=a)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class woe extends f_{constructor(e,n,a,i){let s,o=n.type.toDOM;if(typeof o=="function"&&(o=o(a,()=>{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==yc&&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 XKe extends f_{constructor(e,n,a,i){super(e,[],n,null),this.textDOM=a,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 Jg extends f_{constructor(e,n,a,i,s){super(e,[],a,i),this.mark=n,this.spec=s}static create(e,n,a,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,a);return(!o||!o.dom)&&(o=mb.renderSpec(document,n.type.spec.toDOM(n,a),null,n.attrs)),new Jg(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&wu||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=wu&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=yc){let a=this.parent;for(;!a.node;)a=a.parent;a.dirty<this.dirty&&(a.dirty=this.dirty),this.dirty=yc}}slice(e,n,a){let i=Jg.create(this.parent,this.mark,!0,a),s=this.children,o=this.size;n<o&&(s=kI(s,n,o,a)),e>0&&(s=kI(s,0,e,a));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 Bh extends f_{constructor(e,n,a,i,s,o,l,c,d){super(e,[],s,o),this.node=n,this.outerDeco=a,this.innerDeco=i,this.nodeDOM=l}static create(e,n,a,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)},a,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}=mb.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=Noe(u,a,n),d?c=new ZKe(e,n,a,i,u,m||null,p,d,s,o+1):n.isText?new HA(e,n,a,i,u,p,s):new Bh(e,n,a,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 a=this.children[n];if(this.dom.contains(a.dom.parentNode)){e.contentElement=a.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Yt.empty)}return e}matchesNode(e,n,a){return this.dirty==yc&&e.eq(this.node)&&PP(n,this.outerDeco)&&a.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let a=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 eQe(this,o&&o.node,e);rQe(this.node,this.innerDeco,(d,u,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,a,e,u):d.type.side>=0&&!m&&c.syncToMarks(u==this.node.childCount?ha.none:this.node.child(u).marks,a,e,u),c.placeWidget(d,e,i)},(d,u,m,p)=>{c.syncToMarks(d.marks,a,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([],a,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==dg)&&(o&&this.protectLocalComposition(e,o),_oe(this.contentDOM,this.children,e),zy&&aQe(this.dom))}localCompositionInfo(e,n){let{from:a,to:i}=e.state.selection;if(!(e.state.selection instanceof Vn)||a<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=iQe(this.node.content,o,a-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:a,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 XKe(this,s,n,i);e.input.compositionNodes.push(o),this.children=kI(this.children,a,a+i.length,e,o)}update(e,n,a,i){return this.dirty==wu||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,a,i),!0)}updateInner(e,n,a,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=a,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=yc}updateOuterDeco(e){if(PP(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,a=this.dom;this.dom=koe(this.dom,this.nodeDOM,_I(this.outerDeco,this.node,n),_I(e,this.node,n)),this.dom!=a&&(a.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 HQ(t,e,n,a,i){Noe(a,e,t);let s=new Bh(void 0,t,e,n,a,a,a,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class HA extends Bh{constructor(e,n,a,i,s,o,l){super(e,n,a,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,a,i){return this.dirty==wu||this.dirty!=yc&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=yc||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=yc,!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,a){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,a)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,a){let i=this.node.cut(e,n),s=document.createTextNode(i.text);return new HA(this.parent,i,this.outerDeco,this.innerDeco,s,s,a)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=wu)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Soe extends f_{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==yc&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ZKe extends Bh{constructor(e,n,a,i,s,o,l,c,d,u){super(e,n,a,i,s,o,l,d,u),this.spec=c}update(e,n,a,i){if(this.dirty==wu)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,a);return s&&this.updateInner(e,n,a,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,a,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,a,i){this.spec.setSelection?this.spec.setSelection(e,n,a.root):super.setSelection(e,n,a,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 _oe(t,e,n){let a=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!=a;)a=qQ(a),i=!0;a=a.nextSibling}else i=!0,t.insertBefore(l,a);if(o instanceof Jg){let c=a?a.previousSibling:t.lastChild;_oe(o.contentDOM,o.children,n),a=c?c.nextSibling:t.firstChild}}for(;a;)a=qQ(a),i=!0;i&&n.trackWrites==t&&(n.trackWrites=null)}const uw=function(t){t&&(this.nodeName=t)};uw.prototype=Object.create(null);const ug=[new uw];function _I(t,e,n){if(t.length==0)return ug;let a=n?ug[0]:new uw,i=[a];for(let s=0;s<t.length;s++){let o=t[s].type.attrs;if(o){o.nodeName&&i.push(a=new uw(o.nodeName));for(let l in o){let c=o[l];c!=null&&(n&&i.length==1&&i.push(a=new uw(e.isInline?"span":"div")),l=="class"?a.class=(a.class?a.class+" ":"")+c:l=="style"?a.style=(a.style?a.style+";":"")+c:l!="nodeName"&&(a[l]=c))}}}return i}function koe(t,e,n,a){if(n==ug&&a==ug)return e;let i=e;for(let s=0;s<a.length;s++){let o=a[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=ug[0]),i=c}JKe(i,l||ug[0],o)}return i}function JKe(t,e,n){for(let a in e)a!="class"&&a!="style"&&a!="nodeName"&&!(a in n)&&t.removeAttribute(a);for(let a in n)a!="class"&&a!="style"&&a!="nodeName"&&n[a]!=e[a]&&t.setAttribute(a,n[a]);if(e.class!=n.class){let a=e.class?e.class.split(" ").filter(Boolean):[],i=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<a.length;s++)i.indexOf(a[s])==-1&&t.classList.remove(a[s]);for(let s=0;s<i.length;s++)a.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 a=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;for(;i=a.exec(e.style);)t.style.removeProperty(i[1])}n.style&&(t.style.cssText+=n.style)}}function Noe(t,e,n){return koe(t,t,ug,_I(e,n,t.nodeType!=1))}function PP(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 qQ(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class eQe{constructor(e,n,a){this.lock=n,this.view=a,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=tQe(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let a=e;a<n;a++)this.top.children[a].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,a,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=yc,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=Jg.create(this.top,e[o],n,a);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,a,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,a))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,a)&&!this.preMatch.matched.has(d)){s=l;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,a,i,s){let o=this.top.children[i];return o.dirty==wu&&o.dom==o.contentDOM&&(o.dirty=dg),o.update(e,n,a,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 a=e.pmViewDesc;if(a){for(let i=this.index;i<this.top.children.length;i++)if(this.top.children[i]==a)return i}return-1}e=n}}updateNextNode(e,n,a,i,s,o){for(let l=this.index;l<this.top.children.length;l++){let c=this.top.children[l];if(c instanceof Bh){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!=wu&&PP(n,c.outerDeco));if(!p&&c.update(e,n,a,i))return this.destroyBetween(this.index,l),c.dom!=u&&(this.changed=!0),this.index++,!0;if(!p&&(m=this.recreateWrapper(c,e,n,a,i,o)))return this.destroyBetween(this.index,l),this.top.children[this.index]=m,m.contentDOM&&(m.dirty=dg,m.updateChildren(i,o+1),m.dirty=yc),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,a,i,s,o){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!PP(a,e.outerDeco)||!i.eq(e.innerDeco))return null;let l=Bh.create(this.top,n,a,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,a,i,s){let o=Bh.create(this.top,e,n,a,i,s);o.contentDOM&&o.updateChildren(i,s+1),this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(e,n,a){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 woe(this.top,e,n,a);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 Jg;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof HA)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((ao||Is)&&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 a=document.createElement(e);e=="IMG"&&(a.className="ProseMirror-separator",a.alt=""),e=="BR"&&(a.className="ProseMirror-trailingBreak");let i=new Soe(this.top,[],a,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 tQe(t,e){let n=e,a=n.children.length,i=t.childCount,s=new Map,o=[];e:for(;i>0;){let l;for(;;)if(a){let d=n.children[a-1];if(d instanceof Jg)n=d,a=d.children.length;else{l=d,a--;break}}else{if(n==e)break e;a=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 nQe(t,e){return t.type.side-e.type.side}function rQe(t,e,n,a){let i=e.locals(t),s=0;if(i.length==0){for(let d=0;d<t.childCount;d++){let u=t.child(d);a(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 b=i[o++];b.widget&&(u?(m||(m=[u])).push(b):u=b)}if(u)if(m){m.sort(nQe);for(let b=0;b<m.length;b++)n(m[b],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 b=0;b<l.length;b++)l[b].to<=s&&l.splice(b--,1);for(;o<i.length&&i[o].from<=s&&i[o].to>s;)l.push(i[o++]);let g=s+p.nodeSize;if(p.isText){let b=g;o<i.length&&i[o].from<b&&(b=i[o].from);for(let x=0;x<l.length;x++)l[x].to<b&&(b=l[x].to);b<g&&(c=p.cut(b-s),p=p.cut(0,b-s),g=b,f=-1)}else for(;o<i.length&&i[o].to<g;)o++;let w=p.isInline&&!p.isLeaf?l.filter(b=>!b.inline):l.slice();a(p,w,e.forChild(s,p),f),s=g}}function aQe(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 iQe(t,e,n,a){for(let i=0,s=0;i<t.childCount&&s<=a;){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>=a&&c.slice(a-e.length-l,a-l)==e)return a-e.length;let d=l<a?c.lastIndexOf(e,a-l-1):-1;if(d>=0&&d+e.length+l>=n)return l+d;if(n==a&&c.length>=a+e.length-l&&c.slice(a-l,a-l+e.length)==e)return a}}return-1}function kI(t,e,n,a,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,a)),i&&(s.push(i),i=void 0),u>n&&s.push(c.slice(n-d,c.size,a)))}return s}function N5(t,e=null){let n=t.domSelectionRange(),a=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=a.resolve(o),c,d;if(BA(n)){for(c=o;i&&!i.node;)i=i.parent;let m=i.node;if(i&&m.isAtom&&Rn.isSelectable(m)&&i.parent&&!(m.isInline&&EKe(n.focusNode,n.focusOffset,i.dom))){let p=i.posBefore;d=new Rn(o==p?l:a.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 g=n.getRangeAt(f);m=Math.min(m,t.docView.posFromDOM(g.startContainer,g.startOffset,1)),p=Math.max(p,t.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(m<0)return null;[c,o]=p==t.state.selection.anchor?[p,m]:[m,p],l=a.resolve(o)}else c=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let u=a.resolve(c);if(!d){let m=e=="pointer"||t.state.selection.head<l.pos&&!s?1:-1;d=C5(t,u,l,m)}return d}function Coe(t){return t.editable?t.hasFocus():Toe(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Um(t,e=!1){let n=t.state.selection;if(Poe(t,n),!!Coe(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&Is){let a=t.domSelectionRange(),i=t.domObserver.currentSelection;if(a.anchorNode&&i.anchorNode&&Zg(a.anchorNode,a.anchorOffset,i.anchorNode,i.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)oQe(t);else{let{anchor:a,head:i}=n,s,o;$Q&&!(n instanceof Vn)&&(n.$from.parent.inlineContent||(s=VQ(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(o=VQ(t,n.to))),t.docView.setSelection(a,i,t,e),$Q&&(s&&GQ(s),o&&GQ(o)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&sQe(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const $Q=ao||Is&&poe<63;function VQ(t,e){let{node:n,offset:a}=t.docView.domFromPos(e,0),i=a<n.childNodes.length?n.childNodes[a]:null,s=a?n.childNodes[a-1]:null;if(ao&&i&&i.contentEditable=="false")return z3(i);if((!i||i.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(i)return z3(i);if(s)return z3(s)}}function z3(t){return t.contentEditable="true",ao&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function GQ(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function sQe(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),a=n.anchorNode,i=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=a||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Coe(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function oQe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,a=n.nodeName=="IMG";a?e.collapse(n.parentNode,Fs(n)+1):e.collapse(n,0),!a&&!t.state.selection.visible&&Yo&&Uh<=11&&(n.disabled=!0,n.disabled=!1)}function Poe(t,e){if(e instanceof Rn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(WQ(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else WQ(t)}function WQ(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function C5(t,e,n,a){return t.someProp("createSelectionBetween",i=>i(t,e,n))||Vn.between(e,n,a)}function KQ(t){return t.editable&&!t.hasFocus()?!1:Toe(t)}function Toe(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 lQe(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Zg(e.node,e.offset,n.anchorNode,n.anchorOffset)}function NI(t,e){let{$anchor:n,$head:a}=t.selection,i=e>0?n.max(a):n.min(a),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&sr.findFrom(s,e)}function oh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function QQ(t,e,n){let a=t.state.selection;if(a instanceof Vn)if(n.indexOf("s")>-1){let{$head:i}=a,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 oh(t,new Vn(a.$anchor,o))}else if(a.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=NI(t.state,e);return i&&i instanceof Rn?oh(t,i):!1}else if(!(tc&&n.indexOf("m")>-1)){let i=a.$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?Rn.isSelectable(s)?oh(t,new Rn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):h_?oh(t,new Vn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(a instanceof Rn&&a.node.isInline)return oh(t,new Vn(e>0?a.$to:a.$from));{let i=NI(t.state,e);return i?oh(t,i):!1}}}function TP(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function mw(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Lx(t,e){return e<0?cQe(t):dQe(t)}function cQe(t){let e=t.domSelectionRange(),n=e.focusNode,a=e.focusOffset;if(!n)return;let i,s,o=!1;for(xc&&n.nodeType==1&&a<TP(n)&&mw(n.childNodes[a],-1)&&(o=!0);;)if(a>0){if(n.nodeType!=1)break;{let l=n.childNodes[a-1];if(mw(l,-1))i=n,s=--a;else if(l.nodeType==3)n=l,a=n.nodeValue.length;else break}}else{if(Aoe(n))break;{let l=n.previousSibling;for(;l&&mw(l,-1);)i=n.parentNode,s=Fs(l),l=l.previousSibling;if(l)n=l,a=TP(n);else{if(n=n.parentNode,n==t.dom)break;a=0}}}o?CI(t,n,a):i&&CI(t,i,s)}function dQe(t){let e=t.domSelectionRange(),n=e.focusNode,a=e.focusOffset;if(!n)return;let i=TP(n),s,o;for(;;)if(a<i){if(n.nodeType!=1)break;let l=n.childNodes[a];if(mw(l,1))s=n,o=++a;else break}else{if(Aoe(n))break;{let l=n.nextSibling;for(;l&&mw(l,1);)s=l.parentNode,o=Fs(l)+1,l=l.nextSibling;if(l)n=l,a=0,i=TP(n);else{if(n=n.parentNode,n==t.dom)break;a=i=0}}}s&&CI(t,s,o)}function Aoe(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function uQe(t,e){for(;t&&e==t.childNodes.length&&!p_(t);)e=Fs(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 mQe(t,e){for(;t&&!e&&!p_(t);)e=Fs(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 CI(t,e,n){if(e.nodeType!=3){let s,o;(o=uQe(e,n))?(e=o,n=0):(s=mQe(e,n))&&(e=s,n=s.nodeValue.length)}let a=t.domSelection();if(!a)return;if(BA(a)){let s=document.createRange();s.setEnd(e,n),s.setStart(e,n),a.removeAllRanges(),a.addRange(s)}else a.extend&&a.extend(e,n);t.domObserver.setCurSelection();let{state:i}=t;setTimeout(()=>{t.state==i&&Um(t)},50)}function YQ(t,e){let n=t.state.doc.resolve(e);if(!(Is||hoe)&&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 XQ(t,e,n){let a=t.state.selection;if(a instanceof Vn&&!a.empty||n.indexOf("s")>-1||tc&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=a;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=NI(t.state,e);if(o&&o instanceof Rn)return oh(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=a instanceof Nl?sr.near(o,e):sr.findFrom(o,e);return l?oh(t,l):!1}return!1}function ZQ(t,e){if(!(t.state.selection instanceof Vn))return!0;let{$head:n,$anchor:a,empty:i}=t.state.selection;if(!n.sameParent(a))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 JQ(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function pQe(t){if(!ao||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 a=e.firstChild;JQ(t,a,"true"),setTimeout(()=>JQ(t,a,"false"),20)}return!1}function hQe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function fQe(t,e){let n=e.keyCode,a=hQe(e);if(n==8||tc&&n==72&&a=="c")return ZQ(t,-1)||Lx(t,-1);if(n==46&&!e.shiftKey||tc&&n==68&&a=="c")return ZQ(t,1)||Lx(t,1);if(n==13||n==27)return!0;if(n==37||tc&&n==66&&a=="c"){let i=n==37?YQ(t,t.state.selection.from)=="ltr"?-1:1:-1;return QQ(t,i,a)||Lx(t,i)}else if(n==39||tc&&n==70&&a=="c"){let i=n==39?YQ(t,t.state.selection.from)=="ltr"?1:-1:1;return QQ(t,i,a)||Lx(t,i)}else{if(n==38||tc&&n==80&&a=="c")return XQ(t,-1,a)||Lx(t,-1);if(n==40||tc&&n==78&&a=="c")return pQe(t)||XQ(t,1,a)||Lx(t,1);if(a==(tc?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function P5(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:a,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&a.childCount==1&&a.firstChild.childCount==1;){i--,s--;let f=a.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),a=f.content}let o=t.someProp("clipboardSerializer")||mb.fromSchema(t.state.schema),l=Loe(),c=l.createElement("div");c.appendChild(o.serializeFragment(a,{document:l}));let d=c.firstChild,u,m=0;for(;d&&d.nodeType==1&&(u=Foe[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=l.createElement(u[f]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),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,`
  8191. `);return{dom:c,text:p,slice:e}}function joe(t,e,n,a,i){let s=i.parent.type.spec.code,o,l;if(!n&&!e)return null;let c=!!e&&(a||s||!n);if(c){if(t.someProp("transformPastedText",p=>{e=p(e,s||a,t)}),s)return l=new gn(Yt.from(t.state.schema.text(e.replace(/\r\n?/g,`
  8192. `))),0,0),t.someProp("transformPasted",p=>{l=p(l,t,!0)}),l;let m=t.someProp("clipboardTextParser",p=>p(e,i,a,t));if(m)l=m;else{let p=i.marks(),{schema:f}=t.state,g=mb.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(w=>{let b=o.appendChild(document.createElement("p"));w&&b.appendChild(g.serializeNode(f.text(w,p)))})}}else t.someProp("transformPastedHTML",m=>{n=m(n,t)}),o=yQe(n),h_&&vQe(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")||cw.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:i,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!gQe.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)l=wQe(eY(l,+u[1],+u[2]),u[4]);else if(l=gn.maxOpen(bQe(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=eY(l,m,p)}return t.someProp("transformPasted",m=>{l=m(l,t,c)}),l}const gQe=/^(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 bQe(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&&Eoe(c,s,l,o[o.length-1],0))o[o.length-1]=d;else{o.length&&(o[o.length-1]=Doe(o[o.length-1],s.length));let u=Moe(l,c);o.push(u),i=i.matchType(u.type),s=c}}),o)return Yt.from(o)}return t}function Moe(t,e,n=0){for(let a=e.length-1;a>=n;a--)t=e[a].create(null,Yt.from(t));return t}function Eoe(t,e,n,a,i){if(i<t.length&&i<e.length&&t[i]==e[i]){let s=Eoe(t,e,n,a.lastChild,i+1);if(s)return a.copy(a.content.replaceChild(a.childCount-1,s));if(a.contentMatchAt(a.childCount).matchType(i==t.length-1?n.type:t[i+1]))return a.copy(a.content.append(Yt.from(Moe(n,t,i+1))))}}function Doe(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Doe(t.lastChild,e-1)),a=t.contentMatchAt(t.childCount).fillBefore(Yt.empty,!0);return t.copy(n.append(a))}function PI(t,e,n,a,i,s){let o=e<0?t.firstChild:t.lastChild,l=o.content;return t.childCount>1&&(s=0),i<a-1&&(l=PI(l,e,n,a,i+1,s)),i>=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(Yt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function eY(t,e,n){return e<t.openStart&&(t=new gn(PI(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new gn(PI(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Foe={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 tY=null;function Loe(){return tY||(tY=document.implementation.createHTMLDocument("title"))}let U3=null;function xQe(t){let e=window.trustedTypes;return e?(U3||(U3=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),U3.createHTML(t)):t}function yQe(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Loe().createElement("div"),a=/<([a-z][^>\s]+)/i.exec(t),i;if((i=a&&Foe[a[1].toLowerCase()])&&(t=i.map(s=>"<"+s+">").join("")+t+i.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=xQe(t),i)for(let s=0;s<i.length;s++)n=n.querySelector(i[s])||n;return n}function vQe(t){let e=t.querySelectorAll(Is?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let a=e[n];a.childNodes.length==1&&a.textContent==" "&&a.parentNode&&a.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),a)}}function wQe(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,a;try{a=JSON.parse(e)}catch{return t}let{content:i,openStart:s,openEnd:o}=t;for(let l=a.length-2;l>=0;l-=2){let c=n.nodes[a[l]];if(!c||c.hasRequiredAttrs())break;i=Yt.from(c.create(a[l+1],i)),s++,o++}return new gn(i,s,o)}const Po={},To={},SQe={touchstart:!0,touchmove:!0};class _Qe{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 kQe(t){for(let e in Po){let n=Po[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=a=>{CQe(t,a)&&!T5(t,a)&&(t.editable||!(a.type in To))&&n(t,a)},SQe[e]?{passive:!0}:void 0)}ao&&t.dom.addEventListener("input",()=>null),TI(t)}function kh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function NQe(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 TI(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=a=>T5(t,a))})}function T5(t,e){return t.someProp("handleDOMEvents",n=>{let a=n[e.type];return a?a(t,e)||e.defaultPrevented:!1})}function CQe(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 PQe(t,e){!T5(t,e)&&Po[e.type]&&(t.editable||!(e.type in To))&&Po[e.type](t,e)}To.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Ioe(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Mm&&Is&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),zy&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let a=Date.now();t.input.lastIOSEnter=a,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==a&&(t.someProp("handleKeyDown",i=>i(t,rg(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",a=>a(t,n))||fQe(t,n)?n.preventDefault():kh(t,"key")};To.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};To.keypress=(t,e)=>{let n=e;if(Ioe(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||tc&&n.metaKey)return;if(t.someProp("handleKeyPress",i=>i(t,n))){n.preventDefault();return}let a=t.state.selection;if(!(a instanceof Vn)||!a.$from.sameParent(a.$to)){let i=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!t.someProp("handleTextInput",o=>o(t,a.$from.pos,a.$to.pos,i,s))&&t.dispatch(s()),n.preventDefault()}};function qA(t){return{left:t.clientX,top:t.clientY}}function TQe(t,e){let n=e.x-t.clientX,a=e.y-t.clientY;return n*n+a*a<100}function A5(t,e,n,a,i){if(a==-1)return!1;let s=t.state.doc.resolve(a);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 hy(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let a=t.state.tr.setSelection(e);a.setMeta("pointer",!0),t.dispatch(a)}function AQe(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),a=n.nodeAfter;return a&&a.isAtom&&Rn.isSelectable(a)?(hy(t,new Rn(n)),!0):!1}function jQe(t,e){if(e==-1)return!1;let n=t.state.selection,a,i;n instanceof Rn&&(a=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(Rn.isSelectable(l)){a&&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?(hy(t,Rn.create(t.state.doc,i)),!0):!1}function MQe(t,e,n,a,i){return A5(t,"handleClickOn",e,n,a)||t.someProp("handleClick",s=>s(t,e,a))||(i?jQe(t,n):AQe(t,n))}function EQe(t,e,n,a){return A5(t,"handleDoubleClickOn",e,n,a)||t.someProp("handleDoubleClick",i=>i(t,e,a))}function DQe(t,e,n,a){return A5(t,"handleTripleClickOn",e,n,a)||t.someProp("handleTripleClick",i=>i(t,e,a))||FQe(t,n,a)}function FQe(t,e,n){if(n.button!=0)return!1;let a=t.state.doc;if(e==-1)return a.inlineContent?(hy(t,Vn.create(a,0,a.content.size)),!0):!1;let i=a.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)hy(t,Vn.create(a,l+1,l+1+o.content.size));else if(Rn.isSelectable(o))hy(t,Rn.create(a,l));else continue;return!0}}function j5(t){return AP(t)}const Roe=tc?"metaKey":"ctrlKey";Po.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let a=j5(t),i=Date.now(),s="singleClick";i-t.input.lastClick.time<500&&TQe(n,t.input.lastClick)&&!n[Roe]&&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(qA(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new LQe(t,o,n,!!a)):(s=="doubleClick"?EQe:DQe)(t,o.pos,o.inside,n)?n.preventDefault():kh(t,"pointer"))};class LQe{constructor(e,n,a,i){this.view=e,this.pos=n,this.event=a,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!a[Roe],this.allowDefault=a.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:a.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=e.state;(a.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||d instanceof Rn&&d.from<=o&&d.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&xc&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),kh(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Um(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(qA(e))),this.updateAllowDefault(e),this.allowDefault||!n?kh(this.view,"pointer"):MQe(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||ao&&this.mightDrag&&!this.mightDrag.node.isAtom||Is&&!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)?(hy(this.view,sr.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):kh(this.view,"pointer")}move(e){this.updateAllowDefault(e),kh(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}Po.touchstart=t=>{t.input.lastTouch=Date.now(),j5(t),kh(t,"pointer")};Po.touchmove=t=>{t.input.lastTouch=Date.now(),kh(t,"pointer")};Po.contextmenu=t=>j5(t);function Ioe(t,e){return t.composing?!0:ao&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const RQe=Mm?5e3:-1;To.compositionstart=To.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof Vn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(a=>a.type.spec.inclusive===!1)||Is&&hoe&&IQe(t)))t.markCursor=t.state.storedMarks||n.marks(),AP(t,!0),t.markCursor=null;else if(AP(t,!e.selection.empty),xc&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let a=t.domSelectionRange();for(let i=a.focusNode,s=a.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}Ooe(t,RQe)};function IQe(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let a=e.childNodes[n];return a.nodeType==1&&a.contentEditable=="false"}To.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++,Ooe(t,20))};function Ooe(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>AP(t),e))}function zoe(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=zQe());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function OQe(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=jKe(e.focusNode,e.focusOffset),a=MKe(e.focusNode,e.focusOffset);if(n&&a&&n!=a){let i=a.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||a==s)return s;if(!i||!i.isText(a.nodeValue))return a;if(t.input.compositionNode==a){let o=n.pmViewDesc;if(!(!o||!o.isText(n.nodeValue)))return a}}return n||a}function zQe(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function AP(t,e=!1){if(!(Mm&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),zoe(t),e||t.docView&&t.docView.dirty){let n=N5(t),a=t.state.selection;return n&&!n.eq(a)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!a.$from.node(a.$from.sharedDepth(a.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function UQe(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 a=getSelection(),i=document.createRange();i.selectNodeContents(e),t.dom.blur(),a.removeAllRanges(),a.addRange(i),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const mS=Yo&&Uh<15||zy&&LKe<604;Po.copy=To.cut=(t,e)=>{let n=e,a=t.state.selection,i=n.type=="cut";if(a.empty)return;let s=mS?null:n.clipboardData,o=a.content(),{dom:l,text:c}=P5(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):UQe(t,l),i&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function BQe(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function HQe(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,a=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(a.contentEditable="true"),a.style.cssText="position: fixed; left: -10000px; top: 10px",a.focus();let i=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),a.parentNode&&a.parentNode.removeChild(a),n?pS(t,a.value,null,i,e):pS(t,a.textContent,a.innerHTML,i,e)},50)}function pS(t,e,n,a,i){let s=joe(t,e,n,a,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,i,s||gn.empty)))return!0;if(!s)return!1;let o=BQe(s),l=o?t.state.tr.replaceSelectionWith(o,a):t.state.tr.replaceSelection(s);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Uoe(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," "):""}To.paste=(t,e)=>{let n=e;if(t.composing&&!Mm)return;let a=mS?null:n.clipboardData,i=t.input.shiftKey&&t.input.lastKeyCode!=45;a&&pS(t,Uoe(a),a.getData("text/html"),i,n)?n.preventDefault():HQe(t,n)};class Boe{constructor(e,n,a){this.slice=e,this.move=n,this.node=a}}const qQe=tc?"altKey":"ctrlKey";function Hoe(t,e){let n=t.someProp("dragCopies",a=>!a(e));return n??!e[qQe]}Po.dragstart=(t,e)=>{let n=e,a=t.input.mouseDown;if(a&&a.done(),!n.dataTransfer)return;let i=t.state.selection,s=i.empty?null:t.posAtCoords(qA(n)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof Rn?i.to-1:i.to))){if(a&&a.mightDrag)o=Rn.create(t.state.doc,a.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=Rn.create(t.state.doc,m.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:d,slice:u}=P5(t,l);(!n.dataTransfer.files.length||!Is||poe>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(mS?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",mS||n.dataTransfer.setData("text/plain",d),t.dragging=new Boe(u,Hoe(t,n),o)};Po.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};To.dragover=To.dragenter=(t,e)=>e.preventDefault();To.drop=(t,e)=>{try{$Qe(t,e,t.dragging)}finally{t.dragging=null}};function $Qe(t,e,n){if(!e.dataTransfer)return;let a=t.posAtCoords(qA(e));if(!a)return;let i=t.state.doc.resolve(a.pos),s=n&&n.slice;s?t.someProp("transformPasted",f=>{s=f(s,t,!1)}):s=joe(t,Uoe(e.dataTransfer),mS?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(n&&Hoe(t,e));if(t.someProp("handleDrop",f=>f(t,e,s||gn.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Gse(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&&Rn.isSelectable(s.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new Rn(p));else{let f=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((g,w,b,x)=>f=x),c.setSelection(C5(t,p,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Po.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())&&Um(t)},20))};Po.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)};Po.beforeinput=(t,e)=>{if(Is&&Mm&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:a}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=a||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,rg(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 To)Po[t]=To[t];function hS(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 jP{constructor(e,n){this.toDOM=e,this.spec=n||kg,this.side=this.spec.side||0}map(e,n,a,i){let{pos:s,deleted:o}=e.mapResult(n.from+i,this.side<0?-1:1);return o?null:new vo(s-a,s-a,this)}valid(){return!0}eq(e){return this==e||e instanceof jP&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&hS(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Hh{constructor(e,n){this.attrs=e,this.spec=n||kg}map(e,n,a,i){let s=e.map(n.from+i,this.spec.inclusiveStart?-1:1)-a,o=e.map(n.to+i,this.spec.inclusiveEnd?1:-1)-a;return s>=o?null:new vo(s,o,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof Hh&&hS(this.attrs,e.attrs)&&hS(this.spec,e.spec)}static is(e){return e.type instanceof Hh}destroy(){}}class M5{constructor(e,n){this.attrs=e,this.spec=n||kg}map(e,n,a,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 vo(s.pos-a,o.pos-a,this)}valid(e,n){let{index:a,offset:i}=e.content.findIndex(n.from),s;return i==n.from&&!(s=e.child(a)).isText&&i+s.nodeSize==n.to}eq(e){return this==e||e instanceof M5&&hS(this.attrs,e.attrs)&&hS(this.spec,e.spec)}destroy(){}}class vo{constructor(e,n,a){this.from=e,this.to=n,this.type=a}copy(e,n){return new vo(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,a){return this.type.map(e,this,n,a)}static widget(e,n,a){return new vo(e,e,new jP(n,a))}static inline(e,n,a,i){return new vo(e,n,new Hh(a,i))}static node(e,n,a,i){return new vo(e,n,new M5(a,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof Hh}get widget(){return this.type instanceof jP}}const qx=[],kg={};class Ba{constructor(e,n){this.local=e.length?e:qx,this.children=n.length?n:qx}static create(e,n){return n.length?MP(n,e,0,kg):Ys}find(e,n,a){let i=[];return this.findInner(e??0,n??1e9,i,0,a),i}findInner(e,n,a,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))&&a.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,a,i+l,s)}}map(e,n,a){return this==Ys||e.maps.length==0?this:this.mapInner(e,n,0,0,a||kg)}mapInner(e,n,a,i,s){let o;for(let l=0;l<this.local.length;l++){let c=this.local[l].map(e,a,i);c&&c.type.valid(n,c)?(o||(o=[])).push(c):s.onRemove&&s.onRemove(this.local[l].spec)}return this.children.length?VQe(this.children,o||[],e,n,a,i,s):o?new Ba(o.sort(Ng),qx):Ys}add(e,n){return n.length?this==Ys?Ba.create(e,n):this.addInner(e,n,0):this}addInner(e,n,a){let i,s=0;e.forEach((l,c)=>{let d=c+a,u;if(u=$oe(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,MP(u,l,d+1,kg)),s+=3}});let o=qoe(s?Voe(n):n,-a);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||o.splice(l--,1);return new Ba(o.length?this.local.concat(o).sort(Ng):this.local,i||this.children)}remove(e){return e.length==0||this==Ys?this:this.removeInner(e,0)}removeInner(e,n){let a=this.children,i=this.local;for(let s=0;s<a.length;s+=3){let o,l=a[s]+n,c=a[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;a==this.children&&(a=this.children.slice());let d=a[s+2].removeInner(o,l+1);d!=Ys?a[s+2]=d:(a.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 a==this.children&&i==this.local?this:i.length||a.length?new Ba(i,a):Ys}forChild(e,n){if(this==Ys)return this;if(n.isLeaf)return Ba.empty;let a,i;for(let l=0;l<this.children.length;l+=3)if(this.children[l]>=e){this.children[l]==e&&(a=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 Hh){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 Ba(i.sort(Ng),qx);return a?new ph([l,a]):l}return a||Ys}eq(e){if(this==e)return!0;if(!(e instanceof Ba)||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 E5(this.localsInner(e))}localsInner(e){if(this==Ys)return qx;if(e.inlineContent||!this.local.some(Hh.is))return this.local;let n=[];for(let a=0;a<this.local.length;a++)this.local[a].type instanceof Hh||n.push(this.local[a]);return n}forEachSet(e){e(this)}}Ba.empty=new Ba([],[]);Ba.removeOverlap=E5;const Ys=Ba.empty;class ph{constructor(e){this.members=e}map(e,n){const a=this.members.map(i=>i.map(e,n,kg));return ph.from(a)}forChild(e,n){if(n.isLeaf)return Ba.empty;let a=[];for(let i=0;i<this.members.length;i++){let s=this.members[i].forChild(e,n);s!=Ys&&(s instanceof ph?a=a.concat(s.members):a.push(s))}return ph.from(a)}eq(e){if(!(e instanceof ph)||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,a=!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{a&&(n=n.slice(),a=!1);for(let o=0;o<s.length;o++)n.push(s[o])}}return n?E5(a?n:n.sort(Ng)):qx}static from(e){switch(e.length){case 0:return Ys;case 1:return e[0];default:return new ph(e.every(n=>n instanceof Ba)?e:e.reduce((n,a)=>n.concat(a instanceof Ba?a:a.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function VQe(t,e,n,a,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,g,w)=>{let b=w-g-(f-p);for(let x=0;x<l.length;x+=3){let S=l[x+1];if(S<0||p>S+u-m)continue;let k=l[x]+u-m;f>=k?l[x+1]=p<=k?-2:-1:p>=u&&b&&(l[x]+=b,l[x+1]+=b)}m+=b}),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>=a.content.size){c=!0;continue}let p=n.map(t[d+1]+s,-1),f=p-i,{index:g,offset:w}=a.content.findIndex(m),b=a.maybeChild(g);if(b&&w==m&&w+b.nodeSize==f){let x=l[d+2].mapInner(n,b,u+1,t[d]+s+1,o);x!=Ys?(l[d]=m,l[d+1]=f,l[d+2]=x):(l[d+1]=-2,c=!0)}else c=!0}if(c){let d=GQe(l,t,e,n,i,s,o),u=MP(d,a,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 Ba(e.sort(Ng),l)}function qoe(t,e){if(!e||!t.length)return t;let n=[];for(let a=0;a<t.length;a++){let i=t[a];n.push(new vo(i.from+e,i.to+e,i.type))}return n}function GQe(t,e,n,a,i,s,o){function l(c,d){for(let u=0;u<c.local.length;u++){let m=c.local[u].map(a,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 $oe(t,e,n){if(e.isLeaf)return null;let a=n+e.nodeSize,i=null;for(let s=0,o;s<t.length;s++)(o=t[s])&&o.from>n&&o.to<a&&((i||(i=[])).push(o),t[s]=null);return i}function Voe(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function MP(t,e,n,a){let i=[],s=!1;e.forEach((l,c)=>{let d=$oe(t,l,c+n);if(d){s=!0;let u=MP(d,l,n+c+1,a);u!=Ys&&i.push(c,c+l.nodeSize,u)}});let o=qoe(s?Voe(t):t,-n).sort(Ng);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||(a.onRemove&&a.onRemove(o[l].spec),o.splice(l--,1));return o.length||i.length?new Ba(o,i):Ys}function Ng(t,e){return t.from-e.from||t.to-e.to}function E5(t){let e=t;for(let n=0;n<e.length-1;n++){let a=e[n];if(a.from!=a.to)for(let i=n+1;i<e.length;i++){let s=e[i];if(s.from==a.from){s.to!=a.to&&(e==t&&(e=t.slice()),e[i]=s.copy(s.from,a.to),nY(e,i+1,s.copy(a.to,s.to)));continue}else{s.from<a.to&&(e==t&&(e=t.slice()),e[n]=a.copy(a.from,s.from),nY(e,i,a.copy(s.from,a.to)));break}}}return e}function nY(t,e,n){for(;e<t.length&&Ng(n,t[e])>0;)e++;t.splice(e,0,n)}function B3(t){let e=[];return t.someProp("decorations",n=>{let a=n(t.state);a&&a!=Ys&&e.push(a)}),t.cursorWrapper&&e.push(Ba.create(t.state.doc,[t.cursorWrapper.deco])),ph.from(e)}const WQe={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},KQe=Yo&&Uh<=11;class QQe{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 YQe{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new QQe,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(a=>{for(let i=0;i<a.length;i++)this.queue.push(a[i]);Yo&&Uh<=11&&a.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():ao&&e.composing&&a.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),KQe&&(this.onCharData=a=>{this.queue.push({target:a.target,type:"characterData",oldValue:a.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,WQe)),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(KQ(this.view)){if(this.suppressingSelectionUpdates)return Um(this.view);if(Yo&&Uh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Zg(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,a;for(let s=e.focusNode;s;s=Oy(s))n.add(s);for(let s=e.anchorNode;s;s=Oy(s))if(n.has(s)){a=s;break}let i=a&&this.view.docView.nearestDesc(a);if(i&&i.ignoreMutation({type:"selection",target:a.nodeType==3?a.parentNode:a}))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 a=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(a)&&KQ(e)&&!this.ignoreSelectionChange(a),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(xc&&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||JQe(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&&BA(a)&&(d=N5(e))&&d.eq(sr.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Um(e),this.currentSelection.set(a),e.scrollToSelection()):(s>-1||i)&&(s>-1&&(e.docView.markDirty(s,o),XQe(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,eYe(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(a)||Um(e),this.currentSelection.set(a))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let a=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(a==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!a||a.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(a.contentDOM&&a.contentDOM!=a.dom&&!a.contentDOM.contains(e.target))return{from:a.posBefore,to:a.posAfter};let i=e.previousSibling,s=e.nextSibling;if(Yo&&Uh<=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?Fs(i)+1:0,l=a.localPosFromDOM(e.target,o,-1),c=s&&s.parentNode==e.target?Fs(s):e.target.childNodes.length,d=a.localPosFromDOM(e.target,c,1);return{from:l,to:d}}else return e.type=="attributes"?{from:a.posAtStart-a.border,to:a.posAtEnd+a.border}:(this.lastChangedTextNode=e.target,{from:a.posAtStart,to:a.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let rY=new WeakMap,aY=!1;function XQe(t){if(!rY.has(t)&&(rY.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=xc,aY)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."),aY=!0}}function iY(t,e){let n=e.startContainer,a=e.startOffset,i=e.endContainer,s=e.endOffset,o=t.domAtPos(t.state.selection.anchor);return Zg(o.node,o.offset,i,s)&&([n,a,i,s]=[i,s,n,a]),{anchorNode:n,anchorOffset:a,focusNode:i,focusOffset:s}}function ZQe(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return iY(t,i)}let n;function a(i){i.preventDefault(),i.stopImmediatePropagation(),n=i.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",a,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",a,!0),n?iY(t,n):null}function JQe(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let a=t.docView.nearestDesc(n,!0);if(a&&a.node.isBlock)return n}return null}function eYe(t,e){var n;let{focusNode:a,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),a==s&&t.domSelection().collapse(s,i)}else s.parentNode.removeChild(s)}}function tYe(t,e,n){let{node:a,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}],BA(c)||d.push({node:c.focusNode,offset:c.focusOffset})),Is&&t.input.lastKeyCode===8)for(let b=s;b>i;b--){let x=a.childNodes[b-1],S=x.pmViewDesc;if(x.nodeName=="BR"&&!S){s=b;break}if(!S||S.size)break}let m=t.state.doc,p=t.someProp("domParser")||cw.fromSchema(t.state.schema),f=m.resolve(o),g=null,w=p.parse(a,{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:nYe,context:f});if(d&&d[0].pos!=null){let b=d[0].pos,x=d[1]&&d[1].pos;x==null&&(x=b),g={anchor:b+o,head:x+o}}return{doc:w,sel:g,from:o,to:l}}function nYe(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(ao&&/^(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||ao&&/^(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 rYe=/^(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 aYe(t,e,n,a,i){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let A=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,F=N5(t,A);if(F&&!t.state.selection.eq(F)){if(Is&&Mm&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",M=>M(t,rg(13,"Enter"))))return;let _=t.state.tr.setSelection(F);A=="pointer"?_.setMeta("pointer",!0):A=="key"&&_.scrollIntoView(),s&&_.setMeta("composition",s),t.dispatch(_)}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=tYe(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 g=oYe(m.content,d.doc.content,d.from,p,f);if(g&&t.input.domChangeCount++,(zy&&t.input.lastIOSEnter>Date.now()-225||Mm)&&i.some(A=>A.nodeType==1&&!rYe.test(A.nodeName))&&(!g||g.endA>=g.endB)&&t.someProp("handleKeyDown",A=>A(t,rg(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!g)if(a&&c instanceof Vn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let A=sY(t,t.state.doc,d.sel);if(A&&!A.eq(t.state.selection)){let F=t.state.tr.setSelection(A);s&&F.setMeta("composition",s),t.dispatch(F)}}return}t.state.selection.from<t.state.selection.to&&g.start==g.endB&&t.state.selection instanceof Vn&&(g.start>t.state.selection.from&&g.start<=t.state.selection.from+2&&t.state.selection.from>=d.from?g.start=t.state.selection.from:g.endA<t.state.selection.to&&g.endA>=t.state.selection.to-2&&t.state.selection.to<=d.to&&(g.endB+=t.state.selection.to-g.endA,g.endA=t.state.selection.to)),Yo&&Uh<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let w=d.doc.resolveNoCache(g.start-d.from),b=d.doc.resolveNoCache(g.endB-d.from),x=u.resolve(g.start),S=w.sameParent(b)&&w.parent.inlineContent&&x.end()>=g.endA;if((zy&&t.input.lastIOSEnter>Date.now()-225&&(!S||i.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!S&&w.pos<d.doc.content.size&&(!w.sameParent(b)||!w.parent.inlineContent)&&w.pos<b.pos&&!/\S/.test(d.doc.textBetween(w.pos,b.pos,"","")))&&t.someProp("handleKeyDown",A=>A(t,rg(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>g.start&&sYe(u,g.start,g.endA,w,b)&&t.someProp("handleKeyDown",A=>A(t,rg(8,"Backspace")))){Mm&&Is&&t.domObserver.suppressSelectionUpdates();return}Is&&g.endB==g.start&&(t.input.lastChromeDelete=Date.now()),Mm&&!S&&w.start()!=b.start()&&b.parentOffset==0&&w.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,b=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(A){return A(t,rg(13,"Enter"))})},20));let k=g.start,C=g.endA,P=A=>{let F=A||t.state.tr.replace(k,C,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let _=sY(t,F.doc,d.sel);_&&!(Is&&t.composing&&_.empty&&(g.start!=g.endB||t.input.lastChromeDelete<Date.now()-100)&&(_.head==k||_.head==F.mapping.map(C)-1)||Yo&&_.empty&&_.head==k)&&F.setSelection(_)}return s&&F.setMeta("composition",s),F.scrollIntoView()},T;if(S)if(w.pos==b.pos){Yo&&Uh<=11&&w.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Um(t),20));let A=P(t.state.tr.delete(k,C)),F=u.resolve(g.start).marksAcross(u.resolve(g.endA));F&&A.ensureMarks(F),t.dispatch(A)}else if(g.endA==g.endB&&(T=iYe(w.parent.content.cut(w.parentOffset,b.parentOffset),x.parent.content.cut(x.parentOffset,g.endA-x.start())))){let A=P(t.state.tr);T.type=="add"?A.addMark(k,C,T.mark):A.removeMark(k,C,T.mark),t.dispatch(A)}else if(w.parent.child(w.index()).isText&&w.index()==b.index()-(b.textOffset?0:1)){let A=w.parent.textBetween(w.parentOffset,b.parentOffset),F=()=>P(t.state.tr.insertText(A,k,C));t.someProp("handleTextInput",_=>_(t,k,C,A,F))||t.dispatch(F())}else t.dispatch(P());else t.dispatch(P())}function sY(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:C5(t,e.resolve(n.anchor),e.resolve(n.head))}function iYe(t,e){let n=t.firstChild.marks,a=e.firstChild.marks,i=n,s=a,o,l,c;for(let u=0;u<a.length;u++)i=a[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(Yt.from(d).eq(t))return{mark:l,type:o}}function sYe(t,e,n,a,i){if(n-e<=i.pos-a.pos||H3(a,!0,!1)<i.pos)return!1;let s=t.resolve(e);if(!a.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(H3(s,!0,!0));return!o.parent.isTextblock||o.pos>n||H3(o,!0,!1)<n?!1:a.parent.content.cut(a.parentOffset).eq(o.parent.content)}function H3(t,e,n){let a=t.depth,i=e?t.end():t.pos;for(;a>0&&(e||t.indexAfter(a)==t.node(a).childCount);)a--,i++,e=!1;if(n){let s=t.node(a).maybeChild(t.indexAfter(a));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function oYe(t,e,n,a,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));a-=o+c-s}if(o<s&&t.size<e.size){let c=a<=s&&a>=o?s-a:0;s-=c,s&&s<e.size&&oY(e.textBetween(s-1,s+1))&&(s+=c?1:-1),l=s+(l-o),o=s}else if(l<s){let c=a<=s&&a>=l?s-a:0;s-=c,s&&s<t.size&&oY(t.textBetween(s-1,s+1))&&(s+=c?1:-1),o=s+(o-l),l=s}return{start:s,endA:o,endB:l}}function oY(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 Goe{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 _Qe,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(mY),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=dY(this),cY(this),this.nodeViews=uY(this),this.docView=HQ(this.state.doc,lY(this),B3(this),this.dom,this),this.domObserver=new YQe(this,(a,i,s,o)=>aYe(this,a,i,s,o)),this.domObserver.start(),kQe(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&&TI(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(mY),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let a in this._props)n[a]=this._props[a];n.state=this.state;for(let a in e)n[a]=e[a];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var a;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(zoe(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=uY(this);cYe(f,this.nodeViews)&&(this.nodeViews=f,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&TI(this),this.editable=dY(this),cY(this);let c=B3(this),d=lY(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&&OKe(this);if(o){this.domObserver.stop();let f=m&&(Yo||Is)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&lYe(i.selection,e.selection);if(m){let g=Is?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=OQe(this)),(s||!this.docView.update(e.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=HQ(e.doc,d,c,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&lQe(this))?Um(this,f):(Poe(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((a=this.dragging)===null||a===void 0)&&a.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():p&&zKe(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 Rn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&RQ(this,n.getBoundingClientRect(),e)}else RQ(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 a=this.directPlugins[n];a.spec.view&&this.pluginViews.push(a.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let a=this.state.plugins[n];a.spec.view&&this.pluginViews.push(a.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let a=this.pluginViews[n];a.update&&a.update(this,e)}}updateDraggedNode(e,n){let a=e.node,i=-1;if(this.state.doc.nodeAt(a.from)==a.node)i=a.from;else{let s=a.from+(this.state.doc.content.size-n.doc.content.size);(s>0&&this.state.doc.nodeAt(s))==a.node&&(i=s)}this.dragging=new Boe(e.slice,e.move,i<0?void 0:Rn.create(this.state.doc,i))}someProp(e,n){let a=this._props&&this._props[e],i;if(a!=null&&(i=n?n(a):a))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(Yo){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&&UKe(this.dom),Um(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 VKe(this,e)}coordsAtPos(e,n=1){return yoe(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,a=-1){let i=this.docView.posFromDOM(e,n,a);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,n){return YKe(this,n||this.state,e)}pasteHTML(e,n){return pS(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return pS(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return P5(this,e)}destroy(){this.docView&&(NQe(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],B3(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,TKe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return PQe(this,e)}domSelectionRange(){let e=this.domSelection();return e?ao&&this.root.nodeType===11&&DKe(this.dom.ownerDocument)==this.dom&&ZQe(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Goe.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function lY(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 a in n)a=="class"?e.class+=" "+n[a]:a=="style"?e.style=(e.style?e.style+";":"")+n[a]:!e[a]&&a!="contenteditable"&&a!="nodeName"&&(e[a]=String(n[a]))}),e.translate||(e.translate="no"),[vo.node(0,t.state.doc.content.size,e)]}function cY(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:vo.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function dY(t){return!t.someProp("editable",e=>e(t.state)===!1)}function lYe(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 uY(t){let e=Object.create(null);function n(a){for(let i in a)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=a[i])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function cYe(t,e){let n=0,a=0;for(let i in t){if(t[i]!=e[i])return!0;n++}for(let i in e)a++;return n!=a}function mY(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 ef={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:"'"},EP={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},dYe=typeof navigator<"u"&&/Mac/.test(navigator.platform),uYe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Ls=0;Ls<10;Ls++)ef[48+Ls]=ef[96+Ls]=String(Ls);for(var Ls=1;Ls<=24;Ls++)ef[Ls+111]="F"+Ls;for(var Ls=65;Ls<=90;Ls++)ef[Ls]=String.fromCharCode(Ls+32),EP[Ls]=String.fromCharCode(Ls);for(var q3 in ef)EP.hasOwnProperty(q3)||(EP[q3]=ef[q3]);function mYe(t){var e=dYe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||uYe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?EP:ef)[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 pYe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),hYe=typeof navigator<"u"&&/Win/.test(navigator.platform);function fYe(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let a,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))a=!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))pYe?o=!0:i=!0;else throw new Error("Unrecognized modifier name: "+c)}return a&&(n="Alt-"+n),i&&(n="Ctrl-"+n),o&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function gYe(t){let e=Object.create(null);for(let n in t)e[fYe(n)]=t[n];return e}function $3(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 bYe(t){return new Wa({props:{handleKeyDown:Woe(t)}})}function Woe(t){let e=gYe(t);return function(n,a){let i=mYe(a),s,o=e[$3(i,a)];if(o&&o(n.state,n.dispatch,n))return!0;if(i.length==1&&i!=" "){if(a.shiftKey){let l=e[$3(i,a,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((a.altKey||a.metaKey||a.ctrlKey)&&!(hYe&&a.ctrlKey&&a.altKey)&&(s=ef[a.keyCode])&&s!=i){let l=e[$3(s,a)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var xYe=Object.defineProperty,D5=(t,e)=>{for(var n in e)xYe(t,n,{get:e[n],enumerable:!0})};function $A(t){const{state:e,transaction:n}=t;let{selection:a}=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 a},get doc(){return i},get tr(){return a=n.selection,i=n.doc,s=n.storedMarks,n}}}var VA=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:a}=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&&a.dispatch(i),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:a,state:i}=this,{view:s}=a,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,(...g)=>{const w=this.buildProps(c,e),b=p(...g)(w);return o.push(b),u}])),run:d};return u}createCan(t){const{rawCommands:e,state:n}=this,a=!1,i=t||n.tr,s=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...d)=>c(...d)({...s,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,e=!0){const{rawCommands:n,editor:a,state:i}=this,{view:s}=a,o={tr:t,editor:a,view:s,state:$A({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}},Koe={};D5(Koe,{blur:()=>yYe,clearContent:()=>vYe,clearNodes:()=>wYe,command:()=>SYe,createParagraphNear:()=>_Ye,cut:()=>kYe,deleteCurrentNode:()=>NYe,deleteNode:()=>CYe,deleteRange:()=>PYe,deleteSelection:()=>TYe,enter:()=>AYe,exitCode:()=>jYe,extendMarkRange:()=>MYe,first:()=>EYe,focus:()=>FYe,forEach:()=>LYe,insertContent:()=>RYe,insertContentAt:()=>zYe,joinBackward:()=>HYe,joinDown:()=>BYe,joinForward:()=>qYe,joinItemBackward:()=>$Ye,joinItemForward:()=>VYe,joinTextblockBackward:()=>GYe,joinTextblockForward:()=>WYe,joinUp:()=>UYe,keyboardShortcut:()=>QYe,lift:()=>YYe,liftEmptyBlock:()=>XYe,liftListItem:()=>ZYe,newlineInCode:()=>JYe,resetAttributes:()=>eXe,scrollIntoView:()=>tXe,selectAll:()=>nXe,selectNodeBackward:()=>rXe,selectNodeForward:()=>aXe,selectParentNode:()=>iXe,selectTextblockEnd:()=>sXe,selectTextblockStart:()=>oXe,setContent:()=>lXe,setMark:()=>TXe,setMeta:()=>AXe,setNode:()=>jXe,setNodeSelection:()=>MXe,setTextDirection:()=>EXe,setTextSelection:()=>DXe,sinkListItem:()=>FXe,splitBlock:()=>LXe,splitListItem:()=>RXe,toggleList:()=>IXe,toggleMark:()=>OXe,toggleNode:()=>zXe,toggleWrap:()=>UXe,undoInputRule:()=>BXe,unsetAllMarks:()=>HXe,unsetMark:()=>qXe,unsetTextDirection:()=>$Xe,updateAttributes:()=>VXe,wrapIn:()=>GXe,wrapInList:()=>WXe});var yYe=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),vYe=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),wYe=()=>({state:t,tr:e,dispatch:n})=>{const{selection:a}=e,{ranges:i}=a;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 g=mv(f);if(l.type.isTextblock){const{defaultType:w}=m.parent.contentMatchAt(m.index());e.setNodeMarkup(f.start,w)}(g||g===0)&&e.lift(f,g)})}),!0},SYe=t=>e=>t(e),_Ye=()=>({state:t,dispatch:e})=>loe(t,e),kYe=(t,e)=>({editor:n,tr:a})=>{const{state:i}=n,s=i.doc.slice(t.from,t.to);a.deleteRange(t.from,t.to);const o=a.mapping.map(e);return a.insert(o,s.content),a.setSelection(new Vn(a.doc.resolve(Math.max(o-1,0)))),!0},NYe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,a=n.$anchor.node();if(a.content.size>0)return!1;const i=t.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===a.type){if(e){const l=i.before(s),c=i.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function Ai(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 CYe=t=>({tr:e,state:n,dispatch:a})=>{const i=Ai(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(a){const c=s.before(o),d=s.after(o);e.delete(c,d).scrollIntoView()}return!0}return!1},PYe=t=>({tr:e,dispatch:n})=>{const{from:a,to:i}=t;return n&&e.delete(a,i),!0},TYe=()=>({state:t,dispatch:e})=>y5(t,e),AYe=()=>({commands:t})=>t.keyboardShortcut("Enter"),jYe=()=>({state:t,dispatch:e})=>pKe(t,e);function F5(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function DP(t,e,n={strict:!0}){const a=Object.keys(e);return a.length?a.every(i=>n.strict?e[i]===t[i]:F5(e[i])?e[i].test(t[i]):e[i]===t[i]):!0}function Qoe(t,e,n={}){return t.find(a=>a.type===e&&DP(Object.fromEntries(Object.keys(n).map(i=>[i,a.attrs[i]])),n))}function pY(t,e,n={}){return!!Qoe(t,e,n)}function L5(t,e,n){var a;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||((a=i.node.marks[0])==null?void 0:a.attrs),!Qoe([...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&&pY([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c<t.parent.childCount&&pY([...t.parent.child(c).marks],e,n);)d+=t.parent.child(c).nodeSize,c+=1;return{from:l,to:d}}function lp(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 MYe=(t,e={})=>({tr:n,state:a,dispatch:i})=>{const s=lp(t,a.schema),{doc:o,selection:l}=n,{$from:c,from:d,to:u}=l;if(i){const m=L5(c,s,e);if(m&&m.from<=d&&m.to>=u){const p=Vn.create(o,m.from,m.to);n.setSelection(p)}}return!0},EYe=t=>e=>{const n=typeof t=="function"?t(e):t;for(let a=0;a<n.length;a+=1)if(n[a](e))return!0;return!1};function Yoe(t){return t instanceof Vn}function mg(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function Xoe(t,e=null){if(!e)return null;const n=sr.atStart(t),a=sr.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return a;const i=n.from,s=a.to;return e==="all"?Vn.create(t,mg(0,i,s),mg(t.content.size,i,s)):Vn.create(t,mg(e,i,s),mg(e,i,s))}function hY(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function FP(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function DYe(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var FYe=(t=null,e={})=>({editor:n,view:a,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(FP()||hY())&&a.dom.focus(),DYe()&&!FP()&&!hY()&&a.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(a.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(a.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!Yoe(n.state.selection))return o(),!0;const l=Xoe(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},LYe=(t,e)=>n=>t.every((a,i)=>e(a,{...n,index:i})),RYe=(t,e)=>({tr:n,commands:a})=>a.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Zoe=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.nodeType===3&&a.nodeValue&&/^(\n\s\s|\n)$/.test(a.nodeValue)?t.removeChild(a):a.nodeType===1&&Zoe(a)}return t};function X1(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 Zoe(n)}function fS(t,e,n){if(t instanceof pd||t instanceof Yt)return t;n={slice:!0,parseOptions:{},...n};const a=typeof t=="object"&&t!==null,i=typeof t=="string";if(a)try{if(Array.isArray(t)&&t.length>0)return Yt.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),fS("",e,n)}if(i){if(n.errorOnInvalidContent){let o=!1,l="";const c=new Lse({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?cw.fromSchema(c).parseSlice(X1(t),n.parseOptions):cw.fromSchema(c).parse(X1(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=cw.fromSchema(e);return n.slice?s.parseSlice(X1(t),n.parseOptions).content:s.parse(X1(t),n.parseOptions)}return fS("",e,n)}function IYe(t,e,n){const a=t.steps.length-1;if(a<e)return;const i=t.steps[a];if(!(i instanceof ss||i instanceof ms))return;const s=t.mapping.maps[a];let o=0;s.forEach((l,c,d,u)=>{o===0&&(o=u)}),t.setSelection(sr.near(t.doc.resolve(o),n))}var OYe=t=>!("type"in t),zYe=(t,e,n)=>({tr:a,dispatch:i,editor:s})=>{var o;if(i){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=b=>{s.emit("contentError",{editor:s,error:b,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{fS(e,s.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{l=fS(e,s.schema,{parseOptions:d,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(b){return c(b),!1}let{from:u,to:m}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},p=!0,f=!0;if((OYe(l)?l:[l]).forEach(b=>{b.check(),p=p?b.isText&&b.marks.length===0:!1,f=f?b.isBlock:!1}),u===m&&f){const{parent:b}=a.doc.resolve(u);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(u-=1,m+=1)}let w;if(p){if(Array.isArray(e))w=e.map(b=>b.text||"").join("");else if(e instanceof Yt){let b="";e.forEach(x=>{x.text&&(b+=x.text)}),w=b}else typeof e=="object"&&e&&e.text?w=e.text:w=e;a.insertText(w,u,m)}else{w=l;const b=a.doc.resolve(u),x=b.node(),S=b.parentOffset===0,k=x.isText||x.isTextblock,C=x.content.size>0;S&&k&&C&&(u=Math.max(0,u-1)),a.replaceWith(u,m,w)}n.updateSelection&&IYe(a,a.steps.length-1,-1),n.applyInputRules&&a.setMeta("applyInputRules",{from:u,text:w}),n.applyPasteRules&&a.setMeta("applyPasteRules",{from:u,text:w})}return!0},UYe=()=>({state:t,dispatch:e})=>dKe(t,e),BYe=()=>({state:t,dispatch:e})=>uKe(t,e),HYe=()=>({state:t,dispatch:e})=>toe(t,e),qYe=()=>({state:t,dispatch:e})=>ioe(t,e),$Ye=()=>({state:t,dispatch:e,tr:n})=>{try{const a=OA(t.doc,t.selection.$from.pos,-1);return a==null?!1:(n.join(a,2),e&&e(n),!0)}catch{return!1}},VYe=()=>({state:t,dispatch:e,tr:n})=>{try{const a=OA(t.doc,t.selection.$from.pos,1);return a==null?!1:(n.join(a,2),e&&e(n),!0)}catch{return!1}},GYe=()=>({state:t,dispatch:e})=>lKe(t,e),WYe=()=>({state:t,dispatch:e})=>cKe(t,e);function Joe(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function KYe(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let a,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))a=!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))FP()||Joe()?o=!0:i=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return a&&(n=`Alt-${n}`),i&&(n=`Ctrl-${n}`),o&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var QYe=t=>({editor:e,view:n,tr:a,dispatch:i})=>{const s=KYe(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(a.mapping);u&&i&&a.maybeStep(u)}),!0};function tf(t,e,n={}){const{from:a,to:i,empty:s}=t.selection,o=e?Ai(e,t.schema):null,l=[];t.doc.nodesBetween(a,i,(m,p)=>{if(m.isText)return;const f=Math.max(a,p),g=Math.min(i,p+m.nodeSize);l.push({node:m,from:f,to:g})});const c=i-a,d=l.filter(m=>o?o.name===m.node.type.name:!0).filter(m=>DP(m.node.attrs,n,{strict:!1}));return s?!!d.length:d.reduce((m,p)=>m+p.to-p.from,0)>=c}var YYe=(t,e={})=>({state:n,dispatch:a})=>{const i=Ai(t,n.schema);return tf(n,i,e)?mKe(n,a):!1},XYe=()=>({state:t,dispatch:e})=>coe(t,e),ZYe=t=>({state:e,dispatch:n})=>{const a=Ai(t,e.schema);return kKe(a)(e,n)},JYe=()=>({state:t,dispatch:e})=>ooe(t,e);function GA(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function fY(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((a,i)=>(n.includes(i)||(a[i]=t[i]),a),{})}var eXe=(t,e)=>({tr:n,state:a,dispatch:i})=>{let s=null,o=null;const l=GA(typeof t=="string"?t:t.name,a.schema);if(!l)return!1;l==="node"&&(s=Ai(t,a.schema)),l==="mark"&&(o=lp(t,a.schema));let c=!1;return n.selection.ranges.forEach(d=>{a.doc.nodesBetween(d.$from.pos,d.$to.pos,(u,m)=>{s&&s===u.type&&(c=!0,i&&n.setNodeMarkup(m,void 0,fY(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(fY(p.attrs,e))))})})}),c},tXe=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),nXe=()=>({tr:t,dispatch:e})=>{if(e){const n=new Nl(t.doc);t.setSelection(n)}return!0},rXe=()=>({state:t,dispatch:e})=>roe(t,e),aXe=()=>({state:t,dispatch:e})=>soe(t,e),iXe=()=>({state:t,dispatch:e})=>gKe(t,e),sXe=()=>({state:t,dispatch:e})=>yKe(t,e),oXe=()=>({state:t,dispatch:e})=>xKe(t,e);function AI(t,e,n={},a={}){return fS(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:a.errorOnInvalidContent})}var lXe=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:a={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(a.preserveWhitespace!=="full"){const d=AI(t,i.schema,a,{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:a,errorOnInvalidContent:e??i.options.enableContentCheck})};function ele(t,e){const n=lp(e,t.schema),{from:a,to:i,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(a,i,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function tle(t,e){const n=new Xse(t);return e.forEach(a=>{a.steps.forEach(i=>{n.step(i)})}),n}function cXe(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 dXe(t,e,n){const a=[];return t.nodesBetween(e.from,e.to,(i,s)=>{n(i)&&a.push({node:i,pos:s})}),a}function uXe(t,e){for(let n=t.depth;n>0;n-=1){const a=t.node(n);if(e(a))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:a}}}function WA(t){return e=>uXe(e.$from,t)}function Dn(t,e,n){return t.config[e]===void 0&&t.parent?Dn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?Dn(t.parent,e,n):null}):t.config[e]}function R5(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},a=Dn(e,"addExtensions",n);return a?[e,...R5(a())]:e}).flat(10)}function I5(t,e){const n=mb.fromSchema(e).serializeFragment(t),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(n),i.innerHTML}function nle(t){return typeof t=="function"}function Yr(t,e=void 0,...n){return nle(t)?e?t.bind(e)(...n):t(...n):t}function mXe(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Uy(t){const e=t.filter(i=>i.type==="extension"),n=t.filter(i=>i.type==="node"),a=t.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:a}}function rle(t){const e=[],{nodeExtensions:n,markExtensions:a}=Uy(t),i=[...n,...a],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=Dn(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=Dn(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 si(...t){return t.filter(e=>!!e).reduce((e,n)=>{const a={...e};return Object.entries(n).forEach(([i,s])=>{if(!a[i]){a[i]=s;return}if(i==="class"){const l=s?String(s).split(" "):[],c=a[i]?a[i].split(" "):[],d=l.filter(u=>!c.includes(u));a[i]=[...c,...d].join(" ")}else if(i==="style"){const l=s?s.split(";").map(u=>u.trim()).filter(Boolean):[],c=a[i]?a[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)}),a[i]=Array.from(d.entries()).map(([u,m])=>`${u}: ${m}`).join("; ")}else a[i]=s}),a},{})}function gS(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,a)=>si(n,a),{})}function pXe(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function gY(t,e){return"style"in t?t:{...t,getAttrs:n=>{const a=t.getAttrs?t.getAttrs(n):t.attrs;if(a===!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{...a,...i}}}}function bY(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&mXe(n)?!1:n!=null))}function xY(t){var e,n;const a={};return!((e=t?.attribute)!=null&&e.isRequired)&&"default"in(t?.attribute||{})&&(a.default=t.attribute.default),((n=t?.attribute)==null?void 0:n.validate)!==void 0&&(a.validate=t.attribute.validate),[t.name,a]}function hXe(t,e){var n;const a=rle(t),{nodeExtensions:i,markExtensions:s}=Uy(t),o=(n=i.find(d=>Dn(d,"topNode")))==null?void 0:n.name,l=Object.fromEntries(i.map(d=>{const u=a.filter(x=>x.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((x,S)=>{const k=Dn(S,"extendNodeSchema",m);return{...x,...k?k(d):{}}},{}),f=bY({...p,content:Yr(Dn(d,"content",m)),marks:Yr(Dn(d,"marks",m)),group:Yr(Dn(d,"group",m)),inline:Yr(Dn(d,"inline",m)),atom:Yr(Dn(d,"atom",m)),selectable:Yr(Dn(d,"selectable",m)),draggable:Yr(Dn(d,"draggable",m)),code:Yr(Dn(d,"code",m)),whitespace:Yr(Dn(d,"whitespace",m)),linebreakReplacement:Yr(Dn(d,"linebreakReplacement",m)),defining:Yr(Dn(d,"defining",m)),isolating:Yr(Dn(d,"isolating",m)),attrs:Object.fromEntries(u.map(xY))}),g=Yr(Dn(d,"parseHTML",m));g&&(f.parseDOM=g.map(x=>gY(x,u)));const w=Dn(d,"renderHTML",m);w&&(f.toDOM=x=>w({node:x,HTMLAttributes:gS(x,u)}));const b=Dn(d,"renderText",m);return b&&(f.toText=b),[d.name,f]})),c=Object.fromEntries(s.map(d=>{const u=a.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:e},p=t.reduce((b,x)=>{const S=Dn(x,"extendMarkSchema",m);return{...b,...S?S(d):{}}},{}),f=bY({...p,inclusive:Yr(Dn(d,"inclusive",m)),excludes:Yr(Dn(d,"excludes",m)),group:Yr(Dn(d,"group",m)),spanning:Yr(Dn(d,"spanning",m)),code:Yr(Dn(d,"code",m)),attrs:Object.fromEntries(u.map(xY))}),g=Yr(Dn(d,"parseHTML",m));g&&(f.parseDOM=g.map(b=>gY(b,u)));const w=Dn(d,"renderHTML",m);return w&&(f.toDOM=b=>w({mark:b,HTMLAttributes:gS(b,u)})),[d.name,f]}));return new Lse({topNode:o,nodes:l,marks:c})}function fXe(t){const e=t.filter((n,a)=>t.indexOf(n)!==a);return Array.from(new Set(e))}function LP(t){return t.sort((n,a)=>{const i=Dn(n,"priority")||100,s=Dn(a,"priority")||100;return i>s?-1:i<s?1:0})}function ale(t){const e=LP(R5(t)),n=fXe(e.map(a=>a.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),e}function ile(t,e,n){const{from:a,to:i}=e,{blockSeparator:s=`
  8193. `,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(a,i,(c,d,u,m)=>{var p;c.isBlock&&d>a&&(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(a,d)-d,i-d))}),l}function gXe(t,e){const n={from:0,to:t.content.size};return ile(t,n,e)}function sle(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function bXe(t,e){const n=Ai(e,t.schema),{from:a,to:i}=t.selection,s=[];t.doc.nodesBetween(a,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function ole(t,e){const n=GA(typeof e=="string"?e:e.name,t.schema);return n==="node"?bXe(t,e):n==="mark"?ele(t,e):{}}function xXe(t,e=JSON.stringify){const n={};return t.filter(a=>{const i=e(a);return Object.prototype.hasOwnProperty.call(n,i)?!1:n[i]=!0})}function yXe(t){const e=xXe(t);return e.length===1?e:e.filter((n,a)=>!e.filter((s,o)=>o!==a).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 lle(t){const{mapping:e,steps:n}=t,a=[];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);a.push({oldRange:{from:m,to:p},newRange:{from:d,to:u}})})}),yXe(a)}function O5(t,e,n){const a=[];return t===e?n.resolve(t).marks().forEach(i=>{const s=n.resolve(t),o=L5(s,i.type);o&&a.push({mark:i,...o})}):n.nodesBetween(t,e,(i,s)=>{!i||i?.nodeSize===void 0||a.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),a}var vXe=(t,e,n,a=20)=>{const i=t.doc.resolve(n);let s=a,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function Z1(t,e){return e.nodes[t]||e.marks[t]||null}function zN(t,e,n){return Object.fromEntries(Object.entries(n).filter(([a])=>{const i=t.find(s=>s.type===e&&s.name===a);return i?i.attribute.keepOnSplit:!1}))}var wXe=(t,e=500)=>{let n="";const a=t.parentOffset;return t.parent.nodesBetween(Math.max(0,a-e),a,(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,a-s))}),n};function jI(t,e,n={}){const{empty:a,ranges:i}=t.selection,s=e?lp(e,t.schema):null;if(a)return!!(t.storedMarks||t.selection.$from.marks()).filter(m=>s?s.name===m.type.name:!0).find(m=>DP(m.attrs,n,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:m,$to:p})=>{const f=m.pos,g=p.pos;t.doc.nodesBetween(f,g,(w,b)=>{if(!w.isText&&!w.marks.length)return;const x=Math.max(f,b),S=Math.min(g,b+w.nodeSize),k=S-x;o+=k,l.push(...w.marks.map(C=>({mark:C,from:x,to:S})))})}),o===0)return!1;const c=l.filter(m=>s?s.name===m.mark.type.name:!0).filter(m=>DP(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 SXe(t,e,n={}){if(!e)return tf(t,null,n)||jI(t,null,n);const a=GA(e,t.schema);return a==="node"?tf(t,e,n):a==="mark"?jI(t,e,n):!1}var _Xe=(t,e)=>{const{$from:n,$to:a,$anchor:i}=t.selection;if(e){const s=WA(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!(a.parentOffset<a.parent.nodeSize-2||n.pos!==a.pos)},kXe=t=>{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function yY(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function vY(t,e){const{nodeExtensions:n}=Uy(e),a=n.find(o=>o.name===t);if(!a)return!1;const i={name:a.name,options:a.options,storage:a.storage},s=Yr(Dn(a,"group",i));return typeof s!="string"?!1:s.split(" ").includes("list")}function KA(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var a;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((a=t.text)!=null?a:"")}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&&(KA(s,{ignoreWhitespace:n,checkChildren:e})||(i=!1))}),i}return!1}function cle(t){return t instanceof Rn}var dle=class ule{constructor(e){this.position=e}static fromJSON(e){return new ule(e.position)}toJSON(){return{position:this.position}}};function NXe(t,e){const n=e.mapping.mapResult(t.position);return{position:new dle(n.pos),mapResult:n}}function CXe(t){return new dle(t)}function PXe(t,e,n){var a;const{selection:i}=e;let s=null;if(Yoe(i)&&(s=i.$cursor),s){const l=(a=t.storedMarks)!=null?a: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),g=!!n.isInSet(u.marks)||!u.marks.some(w=>w.type.excludes(n));d=f&&g}return!d}),d})}var TXe=(t,e={})=>({tr:n,state:a,dispatch:i})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=lp(t,a.schema);if(i)if(o){const d=ele(a,c);n.addStoredMark(c.create({...d,...e}))}else l.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;a.doc.nodesBetween(u,m,(p,f)=>{const g=Math.max(f,u),w=Math.min(f+p.nodeSize,m);p.marks.find(x=>x.type===c)?p.marks.forEach(x=>{c===x.type&&n.addMark(g,w,c.create({...x.attrs,...e}))}):n.addMark(g,w,c.create(e))})});return PXe(a,n,c)},AXe=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),jXe=(t,e={})=>({state:n,dispatch:a,chain:i})=>{const s=Ai(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})=>DQ(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>DQ(s,{...o,...e})(l,a)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},MXe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:a}=e,i=mg(t,0,a.content.size),s=Rn.create(a,i);e.setSelection(s)}return!0},EXe=(t,e)=>({tr:n,state:a,dispatch:i})=>{const{selection:s}=a;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},DXe=t=>({tr:e,dispatch:n})=>{if(n){const{doc:a}=e,{from:i,to:s}=typeof t=="number"?{from:t,to:t}:t,o=Vn.atStart(a).from,l=Vn.atEnd(a).to,c=mg(i,o,l),d=mg(s,o,l),u=Vn.create(a,c,d);e.setSelection(u)}return!0},FXe=t=>({state:e,dispatch:n})=>{const a=Ai(t,e.schema);return PKe(a)(e,n)};function wY(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const a=n.filter(i=>e?.includes(i.type.name));t.tr.ensureMarks(a)}}var LXe=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:a,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,d=i.extensionManager.attributes,u=zN(d,l.node().type.name,l.node().attrs);if(s instanceof Rn&&s.node.isBlock)return!l.parentOffset||!zm(o,l.pos)?!1:(a&&(t&&wY(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:cXe(l.node(-1).contentMatchAt(l.indexAfter(-1)));let f=m&&p?[{type:p,attrs:u}]:void 0,g=zm(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!g&&zm(e.doc,e.mapping.map(l.pos),1,p?[{type:p}]:void 0)&&(g=!0,f=p?[{type:p,attrs:u}]:void 0),a){if(g&&(s instanceof Vn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),p&&!m&&!l.parentOffset&&l.parent.type!==p)){const w=e.mapping.map(l.before()),b=e.doc.resolve(w);l.node(-1).canReplaceWith(b.index(),b.index()+1,p)&&e.setNodeMarkup(e.mapping.map(l.before()),p)}t&&wY(n,i.extensionManager.splittableMarks),e.scrollIntoView()}return g},RXe=(t,e={})=>({tr:n,state:a,dispatch:i,editor:s})=>{var o;const l=Ai(t,a.schema),{$from:c,$to:d}=a.selection,u=a.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 x=Yt.empty;const S=c.index(-1)?1:c.index(-2)?2:3;for(let F=c.depth-S;F>=c.depth-3;F-=1)x=Yt.from(c.node(F).copy(x));const k=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,C={...zN(p,c.node().type.name,c.node().attrs),...e},P=((o=l.contentMatch.defaultType)==null?void 0:o.createAndFill(C))||void 0;x=x.append(Yt.from(l.createAndFill(null,P)||void 0));const T=c.before(c.depth-(S-1));n.replace(T,c.after(-k),new gn(x,4-S,0));let A=-1;n.doc.nodesBetween(T,n.doc.content.size,(F,_)=>{if(A>-1)return!1;F.isTextblock&&F.content.size===0&&(A=_+1)}),A>-1&&n.setSelection(Vn.near(n.doc.resolve(A))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,g={...zN(p,m.type.name,m.attrs),...e},w={...zN(p,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,d.pos);const b=f?[{type:l,attrs:g},{type:f,attrs:w}]:[{type:l,attrs:g}];if(!zm(n.doc,c.pos,2))return!1;if(i){const{selection:x,storedMarks:S}=a,{splittableMarks:k}=s.extensionManager,C=S||x.$to.parentOffset&&x.$from.marks();if(n.split(c.pos,2,b).scrollIntoView(),!C||!i)return!0;const P=C.filter(T=>k.includes(T.type.name));n.ensureMarks(P)}return!0},V3=(t,e)=>{const n=WA(o=>o.type===e)(t.selection);if(!n)return!0;const a=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(a===void 0)return!0;const i=t.doc.nodeAt(a);return n.node.type===i?.type&&uf(t.doc,n.pos)&&t.join(n.pos),!0},G3=(t,e)=>{const n=WA(o=>o.type===e)(t.selection);if(!n)return!0;const a=t.doc.resolve(n.start).after(n.depth);if(a===void 0)return!0;const i=t.doc.nodeAt(a);return n.node.type===i?.type&&uf(t.doc,a)&&t.join(a),!0},IXe=(t,e,n,a={})=>({editor:i,tr:s,state:o,dispatch:l,chain:c,commands:d,can:u})=>{const{extensions:m,splittableMarks:p}=i.extensionManager,f=Ai(t,o.schema),g=Ai(e,o.schema),{selection:w,storedMarks:b}=o,{$from:x,$to:S}=w,k=x.blockRange(S),C=b||w.$to.parentOffset&&w.$from.marks();if(!k)return!1;const P=WA(T=>vY(T.type.name,m))(w);if(k.depth>=1&&P&&k.depth-P.depth<=1){if(P.node.type===f)return d.liftListItem(g);if(vY(P.node.type.name,m)&&f.validContent(P.node.content)&&l)return c().command(()=>(s.setNodeMarkup(P.pos,f),!0)).command(()=>V3(s,f)).command(()=>G3(s,f)).run()}return!n||!C||!l?c().command(()=>u().wrapInList(f,a)?!0:d.clearNodes()).wrapInList(f,a).command(()=>V3(s,f)).command(()=>G3(s,f)).run():c().command(()=>{const T=u().wrapInList(f,a),A=C.filter(F=>p.includes(F.type.name));return s.ensureMarks(A),T?!0:d.clearNodes()}).wrapInList(f,a).command(()=>V3(s,f)).command(()=>G3(s,f)).run()},OXe=(t,e={},n={})=>({state:a,commands:i})=>{const{extendEmptyMarkRange:s=!1}=n,o=lp(t,a.schema);return jI(a,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},zXe=(t,e,n={})=>({state:a,commands:i})=>{const s=Ai(t,a.schema),o=Ai(e,a.schema),l=tf(a,s,n);let c;return a.selection.$anchor.sameParent(a.selection.$head)&&(c=a.selection.$anchor.parent.attrs),l?i.setNode(o,c):i.setNode(s,{...c,...n})},UXe=(t,e={})=>({state:n,commands:a})=>{const i=Ai(t,n.schema);return tf(n,i,e)?a.lift(i):a.wrapIn(i,e)},BXe=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let a=0;a<n.length;a+=1){const i=n[a];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},HXe=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:a,ranges:i}=n;return a||e&&i.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},qXe=(t,e={})=>({tr:n,state:a,dispatch:i})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=lp(t,a.schema),{$from:d,empty:u,ranges:m}=l;if(!i)return!0;if(u&&o){let{from:p,to:f}=l;const g=(s=d.marks().find(b=>b.type===c))==null?void 0:s.attrs,w=L5(d,c,g);w&&(p=w.from,f=w.to),n.removeMark(p,f,c)}else m.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},$Xe=t=>({tr:e,state:n,dispatch:a})=>{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),a&&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},VXe=(t,e={})=>({tr:n,state:a,dispatch:i})=>{let s=null,o=null;const l=GA(typeof t=="string"?t:t.name,a.schema);if(!l)return!1;l==="node"&&(s=Ai(t,a.schema)),l==="mark"&&(o=lp(t,a.schema));let c=!1;return n.selection.ranges.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;let p,f,g,w;n.selection.empty?a.doc.nodesBetween(u,m,(b,x)=>{s&&s===b.type&&(c=!0,g=Math.max(x,u),w=Math.min(x+b.nodeSize,m),p=x,f=b)}):a.doc.nodesBetween(u,m,(b,x)=>{x<u&&s&&s===b.type&&(c=!0,g=Math.max(x,u),w=Math.min(x+b.nodeSize,m),p=x,f=b),x>=u&&x<=m&&(s&&s===b.type&&(c=!0,i&&n.setNodeMarkup(x,void 0,{...b.attrs,...e})),o&&b.marks.length&&b.marks.forEach(S=>{if(o===S.type&&(c=!0,i)){const k=Math.max(x,u),C=Math.min(x+b.nodeSize,m);n.addMark(k,C,o.create({...S.attrs,...e}))}}))}),f&&(p!==void 0&&i&&n.setNodeMarkup(p,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(b=>{o===b.type&&i&&n.addMark(g,w,o.create({...b.attrs,...e}))}))}),c},GXe=(t,e={})=>({state:n,dispatch:a})=>{const i=Ai(t,n.schema);return vKe(i,e)(n,a)},WXe=(t,e={})=>({state:n,dispatch:a})=>{const i=Ai(t,n.schema);return wKe(i,e)(n,a)},KXe=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(a=>a.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(a=>a!==e):delete this.callbacks[t]),this}once(t,e){const n=(...a)=>{this.off(t,n),e.apply(this,a)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},QA=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},QXe=(t,e)=>{if(F5(e))return e.exec(t);const n=e(t);if(!n)return null;const a=[n.text];return a.index=n.index,a.input=t,a.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),a.push(n.replaceWith)),a};function J1(t){var e;const{editor:n,from:a,to:i,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(a);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=wXe(d)+s;return o.forEach(p=>{if(u)return;const f=QXe(m,p.find);if(!f)return;const g=c.state.tr,w=$A({state:c.state,transaction:g}),b={from:a-(f[0].length-s.length),to:i},{commands:x,chain:S,can:k}=new VA({editor:n,state:w});p.handler({state:w,range:b,match:f,commands:x,chain:S,can:k})===null||!g.steps.length||(p.undoable&&g.setMeta(l,{transform:g,from:a,to:i,text:s}),c.dispatch(g),u=!0)}),u}function YXe(t){const{editor:e,rules:n}=t,a=new Wa({state:{init(){return null},apply(i,s,o){const l=i.getMeta(a);if(l)return l;const c=i.getMeta("applyInputRules");return c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=I5(Yt.from(u),o.schema);const{from:m}=c,p=m+u.length;J1({editor:e,from:m,to:p,text:u,rules:n,plugin:a})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return J1({editor:e,from:s,to:o,text:l,rules:n,plugin:a})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&J1({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:a})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?J1({editor:e,from:o.pos,to:o.pos,text:`
  8194. `,rules:n,plugin:a}):!1}},isInputRules:!0});return a}function XXe(t){return Object.prototype.toString.call(t).slice(8,-1)}function eN(t){return XXe(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function mle(t,e){const n={...t};return eN(t)&&eN(e)&&Object.keys(e).forEach(a=>{eN(e[a])&&eN(t[a])?n[a]=mle(t[a],e[a]):n[a]=e[a]}),n}var z5=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{...Yr(Dn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Yr(Dn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>mle(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}},pf=class ple extends z5{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new ple(n)}static handleExit({editor:e,mark:n}){const{tr:a}=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&&a.removeStoredMark(c),a.insertText(" ",i.pos),e.view.dispatch(a),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function ZXe(t){return typeof t=="number"}var JXe=class{constructor(t){this.find=t.find,this.handler=t.handler}},eZe=(t,e,n)=>{if(F5(e))return[...t.matchAll(e)];const a=e(t,n);return a?a.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 tZe(t){const{editor:e,state:n,from:a,to:i,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:d,can:u}=new VA({editor:e,state:n}),m=[];return n.doc.nodesBetween(a,i,(f,g)=>{var w,b,x,S,k;if((b=(w=f.type)==null?void 0:w.spec)!=null&&b.code||!(f.isText||f.isTextblock||f.isInline))return;const C=(k=(S=(x=f.content)==null?void 0:x.size)!=null?S:f.nodeSize)!=null?k:0,P=Math.max(a,g),T=Math.min(i,g+C);if(P>=T)return;const A=f.isText?f.text||"":f.textBetween(P-g,T-g,void 0,"");eZe(A,s.find,o).forEach(_=>{if(_.index===void 0)return;const M=P+_.index+1,H=M+_[0].length,I={from:n.tr.mapping.map(M),to:n.tr.mapping.map(H)},z=s.handler({state:n,range:I,match:_,commands:c,chain:d,can:u,pasteEvent:o,dropEvent:l});m.push(z)})}),m.every(f=>f!==null)}var tN=null,nZe=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function rZe(t){const{editor:e,rules:n}=t;let a=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:g})=>{const w=u.tr,b=$A({state:u,transaction:w});if(!(!tZe({editor:e,state:b,from:Math.max(m-1,0),to:p.b-1,rule:f,pasteEvent:g,dropEvent:l})||!w.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,w}};return n.map(u=>new Wa({view(m){const p=g=>{var w;a=(w=m.dom.parentElement)!=null&&w.contains(g.target)?m.dom.parentElement:null,a&&(tN=e)},f=()=>{tN&&(tN=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=a===m.dom.parentElement,l=p,!s){const f=tN;f?.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(m,p)=>{var f;const g=(f=p.clipboardData)==null?void 0:f.getData("text/html");return o=p,i=!!g?.includes("data-pm-slice"),!1}}},appendTransaction:(m,p,f)=>{const g=m[0],w=g.getMeta("uiEvent")==="paste"&&!i,b=g.getMeta("uiEvent")==="drop"&&!s,x=g.getMeta("applyPasteRules"),S=!!x;if(!w&&!b&&!S)return;if(S){let{text:P}=x;typeof P=="string"?P=P:P=I5(Yt.from(P),f.schema);const{from:T}=x,A=T+P.length,F=nZe(P);return c({rule:u,state:f,from:T,to:{b:A},pasteEvt:F})}const k=p.doc.content.findDiffStart(f.doc.content),C=p.doc.content.findDiffEnd(f.doc.content);if(!(!ZXe(k)||!C||k===C.b))return c({rule:u,state:f,from:k,to:C,pasteEvt:o})}}))}var YA=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=ale(t),this.schema=hXe(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:Z1(e.name,this.schema)},a=Dn(e,"addCommands",n);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this;return LP([...this.extensions].reverse()).flatMap(a=>{const i={name:a.name,options:a.options,storage:this.editor.extensionStorage[a.name],editor:t,type:Z1(a.name,this.schema)},s=[],o=Dn(a,"addKeyboardShortcuts",i);let l={};if(a.type==="mark"&&Dn(a,"exitable",i)&&(l.ArrowRight=()=>pf.handleExit({editor:t,mark:a})),o){const p=Object.fromEntries(Object.entries(o()).map(([f,g])=>[f,()=>g({editor:t})]));l={...l,...p}}const c=bYe(l);s.push(c);const d=Dn(a,"addInputRules",i);if(yY(a,t.options.enableInputRules)&&d){const p=d();if(p&&p.length){const f=YXe({editor:t,rules:p}),g=Array.isArray(f)?f:[f];s.push(...g)}}const u=Dn(a,"addPasteRules",i);if(yY(a,t.options.enablePasteRules)&&u){const p=u();if(p&&p.length){const f=rZe({editor:t,rules:p});s.push(...f)}}const m=Dn(a,"addProseMirrorPlugins",i);if(m){const p=m();s.push(...p)}return s})}get attributes(){return rle(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Uy(this.extensions);return Object.fromEntries(e.filter(n=>!!Dn(n,"addNodeView")).map(n=>{const a=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Ai(n.name,this.schema)},s=Dn(n,"addNodeView",i);if(!s)return[];const o=s();if(!o)return[];const l=(c,d,u,m,p)=>{const f=gS(c,a);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 LP([...this.extensions].reverse()).reduceRight((a,i)=>{const s={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:Z1(i.name,this.schema)},o=Dn(i,"dispatchTransaction",s);return o?l=>{o.call(s,{transaction:l,next:a})}:a},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Uy(this.extensions);return Object.fromEntries(e.filter(n=>!!Dn(n,"addMarkView")).map(n=>{const a=this.attributes.filter(l=>l.type===n.name),i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:lp(n.name,this.schema)},s=Dn(n,"addMarkView",i);if(!s)return[];const o=(l,c,d)=>{const u=gS(l,a);return s()({mark:l,view:c,inline:d,editor:t,extension:n,HTMLAttributes:u,updateAttributes:m=>{xZe(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 a={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Z1(e.name,this.schema)};e.type==="mark"&&((n=Yr(Dn(e,"keepOnSplit",a)))==null||n)&&this.splittableMarks.push(e.name);const i=Dn(e,"onBeforeCreate",a),s=Dn(e,"onCreate",a),o=Dn(e,"onUpdate",a),l=Dn(e,"onSelectionUpdate",a),c=Dn(e,"onTransaction",a),d=Dn(e,"onFocus",a),u=Dn(e,"onBlur",a),m=Dn(e,"onDestroy",a);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)})}};YA.resolve=ale;YA.sort=LP;YA.flatten=R5;var aZe={};D5(aZe,{ClipboardTextSerializer:()=>fle,Commands:()=>gle,Delete:()=>ble,Drop:()=>xle,Editable:()=>yle,FocusEvents:()=>wle,Keymap:()=>Sle,Paste:()=>_le,Tabindex:()=>kle,TextDirection:()=>Nle,focusEventsPluginKey:()=>vle});var da=class hle extends z5{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new hle(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},fle=da.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Wa({key:new Wi("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:a,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=sle(n);return ile(a,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),gle=da.create({name:"commands",addCommands(){return{...Koe}}}),ble=da.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,a,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=tle(t.before,[t,...e]);lle(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,(g,w)=>{const b=w+g.nodeSize-2,x=f.oldRange.from<=w&&b<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:g,from:w,to:b,newFrom:u.mapping.map(w),newTo:u.mapping.map(b),deletedRange:f.oldRange,newRange:f.newRange,partial:!x,editor:this.editor,transaction:t,combinedTransform:u})})});const p=u.mapping;u.steps.forEach((f,g)=>{var w,b;if(f instanceof dd){const x=p.slice(g).map(f.from,-1),S=p.slice(g).map(f.to),k=p.invert().map(x,-1),C=p.invert().map(S),P=(w=u.doc.nodeAt(x-1))==null?void 0:w.marks.some(A=>A.eq(f.mark)),T=(b=u.doc.nodeAt(S))==null?void 0:b.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:k,to:C},newRange:{from:x,to:S},partial:!!(T||P),editor:this.editor,transaction:t,combinedTransform:u})}})};(i=(a=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:a.async)==null||i?setTimeout(s,0):s()}}),xle=da.create({name:"drop",addProseMirrorPlugins(){return[new Wa({key:new Wi("tiptapDrop"),props:{handleDrop:(t,e,n,a)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:a})}}})]}}),yle=da.create({name:"editable",addProseMirrorPlugins(){return[new Wa({key:new Wi("editable"),props:{editable:()=>this.editor.options.editable}})]}}),vle=new Wi("focusEvents"),wle=da.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new Wa({key:vle,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const a=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(a),!1},blur:(e,n)=>{t.isFocused=!1;const a=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(a),!1}}}})]}}),Sle=da.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,g=m.parent.isTextblock&&p>0?l.doc.resolve(p-1):m,w=g.parent.type.spec.isolating,b=m.pos-m.parentOffset,x=w&&g.parent.childCount===1?b===m.pos:sr.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!x||x&&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()]),a={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={...a},s={...a,"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 FP()||Joe()?s:i},addProseMirrorPlugins(){return[new Wa({key:new Wi("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(w=>w.getMeta("composition")))return;const a=t.some(w=>w.docChanged)&&!e.doc.eq(n.doc),i=t.some(w=>w.getMeta("preventClearDocument"));if(!a||i)return;const{empty:s,from:o,to:l}=e.selection,c=sr.atStart(e.doc).from,d=sr.atEnd(e.doc).to;if(s||!(o===c&&l===d)||!KA(n.doc))return;const p=n.tr,f=$A({state:n,transaction:p}),{commands:g}=new VA({editor:this.editor,state:f});if(g.clearNodes(),!!p.steps.length)return p}})]}}),_le=da.create({name:"paste",addProseMirrorPlugins(){return[new Wa({key:new Wi("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),kle=da.create({name:"tabindex",addProseMirrorPlugins(){return[new Wa({key:new Wi("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Nle=da.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Uy(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 Wa({key:new Wi("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),iZe=class V0{constructor(e,n,a=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=a,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,a=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,a=this.to-1}this.editor.commands.insertContentAt({from:n,to:a},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 V0(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 V0(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 V0(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,a)=>{const i=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=n.isInline,l=this.pos+a+(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 V0(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 a=null,i=this.parent;for(;i&&!a;){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 a=i;i=i.parent}return a}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},a=!1){let i=[];if(!this.children||this.children.length===0)return i;const s=Object.keys(n);return this.children.forEach(o=>{a&&i.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&i.push(o),!(a&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,n,a))))}),i}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},sZe=`.ProseMirror {
  8195. position: relative;
  8196. }
  8197. .ProseMirror {
  8198. word-wrap: break-word;
  8199. white-space: pre-wrap;
  8200. white-space: break-spaces;
  8201. -webkit-font-variant-ligatures: none;
  8202. font-variant-ligatures: none;
  8203. font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
  8204. }
  8205. .ProseMirror [contenteditable="false"] {
  8206. white-space: normal;
  8207. }
  8208. .ProseMirror [contenteditable="false"] [contenteditable="true"] {
  8209. white-space: pre-wrap;
  8210. }
  8211. .ProseMirror pre {
  8212. white-space: pre-wrap;
  8213. }
  8214. img.ProseMirror-separator {
  8215. display: inline !important;
  8216. border: none !important;
  8217. margin: 0 !important;
  8218. width: 0 !important;
  8219. height: 0 !important;
  8220. }
  8221. .ProseMirror-gapcursor {
  8222. display: none;
  8223. pointer-events: none;
  8224. position: absolute;
  8225. margin: 0;
  8226. }
  8227. .ProseMirror-gapcursor:after {
  8228. content: "";
  8229. display: block;
  8230. position: absolute;
  8231. top: -2px;
  8232. width: 20px;
  8233. border-top: 1px solid black;
  8234. animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
  8235. }
  8236. @keyframes ProseMirror-cursor-blink {
  8237. to {
  8238. visibility: hidden;
  8239. }
  8240. }
  8241. .ProseMirror-hideselection *::selection {
  8242. background: transparent;
  8243. }
  8244. .ProseMirror-hideselection *::-moz-selection {
  8245. background: transparent;
  8246. }
  8247. .ProseMirror-hideselection * {
  8248. caret-color: transparent;
  8249. }
  8250. .ProseMirror-focused .ProseMirror-gapcursor {
  8251. display: block;
  8252. }`;function oZe(t,e,n){const a=document.querySelector("style[data-tiptap-style]");if(a!==null)return a;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 lZe=class extends KXe{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:a})=>{throw a},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:NXe,createMappablePosition:CXe},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:a,slice:i,moved:s})=>this.options.onDrop(a,i,s)),this.on("paste",({event:a,slice:i})=>this.options.onPaste(a,i)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=Xoe(e,this.options.autofocus);this.editorState=Jx.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=oZe(sZe,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=nle(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}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 a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}createExtensionManager(){var t,e;const a=[...this.options.enableCoreExtensions?[yle,fle.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),gle,wle,Sle,kle,xle,_le,ble,Nle.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 YA(a,this)}createCommandManager(){this.commandManager=new VA({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=AI(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=AI(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,a=e.dispatchTransaction||this.dispatchTransaction.bind(this),i=n?this.extensionManager.dispatchTransaction(a):a;this.editorView=new Goe(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),a=!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)}),a&&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 ole(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,a=typeof t=="string"?e:t;return SXe(this.state,n,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return I5(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=`
  8253. `,textSerializers:n={}}=t||{};return gXe(this.state.doc,{blockSeparator:e,textSerializers:{...sle(this.schema),...n}})}get isEmpty(){return KA(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 iZe(e,this)}get $doc(){return this.$pos(0)}};function By(t){return new QA({find:t.find,handler:({state:e,range:n,match:a})=>{const i=Yr(t.getAttributes,void 0,a);if(i===!1||i===null)return null;const{tr:s}=e,o=a[a.length-1],l=a[0];if(o){const c=l.search(/\S/),d=n.from+l.indexOf(o),u=d+o.length;if(O5(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(w=>w===t.type&&w!==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 Cle(t){return new QA({find:t.find,handler:({state:e,range:n,match:a})=>{const i=Yr(t.getAttributes,void 0,a)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(i);if(a[1]){const d=a[0].lastIndexOf(a[1]);let u=o+d;u>l?u=l:l=u+a[1].length;const m=a[0][a[0].length-1];s.insertText(m,o+a[0].length-1),s.replaceWith(u,l,c)}else if(a[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 MI(t){return new QA({find:t.find,handler:({state:e,range:n,match:a})=>{const i=e.doc.resolve(n.from),s=Yr(t.getAttributes,void 0,a)||{};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 Hy(t){return new QA({find:t.find,handler:({state:e,range:n,match:a,chain:i})=>{const s=Yr(t.getAttributes,void 0,a)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),d=c&&b5(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,g=p||m.$to.parentOffset&&m.$from.marks();if(g){const w=g.filter(b=>f.includes(b.type.name));o.ensureMarks(w)}}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&&uf(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(a,u))&&o.join(n.from-1)},undoable:t.undoable})}var cZe=t=>"touches"in t,dZe=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,a,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),(a=t?.options)!=null&&a.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"),a=e.includes("bottom"),i=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),a&&(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,cZe(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:a,height:i}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(a,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 a=this.startWidth,i=this.startHeight;const s=t.includes("right"),o=t.includes("left"),l=t.includes("bottom"),c=t.includes("top");return s?a=this.startWidth+e:o&&(a=this.startWidth-e),l?i=this.startHeight+n:c&&(i=this.startHeight-n),(t==="right"||t==="left")&&(a=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(i=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(a,i,t):{width:a,height:i}}applyConstraints(t,e,n){var a,i,s,o;if(!n){let d=Math.max(this.minSize.width,t),u=Math.max(this.minSize.height,e);return(a=this.maxSize)!=null&&a.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 a=n==="left"||n==="right",i=n==="top"||n==="bottom";return a?{width:t,height:t/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function uZe(t,e){const{selection:n}=t,{$from:a}=n;if(n instanceof Rn){const s=a.index();return a.parent.canReplaceWith(s,s+1,e)}let i=a.depth;for(;i>=0;){const s=a.index(i);if(a.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}var mZe={};D5(mZe,{createAtomBlockMarkdownSpec:()=>pZe,createBlockMarkdownSpec:()=>hZe,createInlineMarkdownSpec:()=>bZe,parseAttributes:()=>U5,parseIndentedBlocks:()=>EI,renderNestedMarkdownContent:()=>H5,serializeAttributes:()=>B5});function U5(t){if(!t?.trim())return{};const e={},n=[],a=t.replace(/["']([^"']*)["']/g,d=>(n.push(d),`__QUOTED_${n.length-1}__`)),i=a.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const d=i.map(u=>u.trim().slice(1));e.class=d.join(" ")}const s=a.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(a.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=a.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 B5(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(a=>e.push(`.${a}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,a])=>{n==="class"||n==="id"||(a===!0?e.push(n):a!==!1&&a!=null&&e.push(`${n}="${String(a)}"`))}),e.join(" ")}function pZe(t){const{nodeName:e,name:n,parseAttributes:a=U5,serializeAttributes:i=B5,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|$)`),g=u.match(f);if(!g)return;const w=g[1]||"",b=a(w);if(!o.find(S=>!(S in b)))return{type:e,raw:g[0],attributes:b}}},renderMarkdown:u=>{const m=d(u.attrs||{}),p=i(m),f=p?` {${p}}`:"";return`:::${c}${f} :::`}}}function hZe(t){const{nodeName:e,name:n,getContent:a,parseAttributes:i=U5,serializeAttributes:s=B5,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(a){const w=a(m);f=typeof w=="string"?[{type:"text",text:w}]:w}else l==="block"?f=p.parseChildren(m.tokens||[]):f=p.parseInline(m.tokens||[]);const g={...o,...m.attributes};return p.createNode(e,g,f)},markdownTokenizer:{name:e,level:"block",start(m){var p;const f=new RegExp(`^:::${d}`,"m"),g=(p=m.match(f))==null?void 0:p.index;return g!==void 0?g:-1},tokenize(m,p,f){var g;const w=new RegExp(`^:::${d}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),b=m.match(w);if(!b)return;const[x,S=""]=b,k=i(S);let C=1;const P=x.length;let T="";const A=/^:::([\w-]*)(\s.*)?/gm,F=m.slice(P);for(A.lastIndex=0;;){const _=A.exec(F);if(_===null)break;const M=_.index,H=_[1];if(!((g=_[2])!=null&&g.endsWith(":::"))){if(H)C+=1;else if(C-=1,C===0){const I=F.slice(0,M);T=I.trim();const z=m.slice(0,P+M+_[0].length);let L=[];if(T)if(l==="block")for(L=f.blockTokens(I),L.forEach(Z=>{Z.text&&(!Z.tokens||Z.tokens.length===0)&&(Z.tokens=f.inlineTokens(Z.text))});L.length>0;){const Z=L[L.length-1];if(Z.type==="paragraph"&&(!Z.text||Z.text.trim()===""))L.pop();else break}else L=f.inlineTokens(T);return{type:e,raw:z,attributes:k,content:T,tokens:L}}}}}},renderMarkdown:(m,p)=>{const f=u(m.attrs||{}),g=s(f),w=g?` {${g}}`:"",b=p.renderChildren(m.content||[],`
  8254. `);return`:::${d}${w}
  8255. ${b}
  8256. :::`}}}function fZe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let a=n.exec(t);for(;a!==null;){const[,i,s,o]=a;e[i]=s||o,a=n.exec(t)}return e}function gZe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function bZe(t){const{nodeName:e,name:n,getContent:a,parseAttributes:i=fZe,serializeAttributes:s=gZe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,d=n||e,u=p=>{if(!c)return p;const f={};return c.forEach(g=>{const w=typeof g=="string"?g:g.name,b=typeof g=="string"?void 0:g.skipIfDefault;if(w in p){const x=p[w];if(b!==void 0&&x===b)return;f[w]=x}}),f},m=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(p,f)=>{const g={...o,...p.attributes};if(l)return f.createNode(e,g);const w=a?a(p):p.content||"";return w?f.createNode(e,g,[f.createTextNode(w)]):f.createNode(e,g,[])},markdownTokenizer:{name:e,level:"inline",start(p){const f=l?new RegExp(`\\[${m}\\s*[^\\]]*\\]`):new RegExp(`\\[${m}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${m}\\]`),g=p.match(f),w=g?.index;return w!==void 0?w:-1},tokenize(p,f,g){const w=l?new RegExp(`^\\[${m}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${m}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${m}\\]`),b=p.match(w);if(!b)return;let x="",S="";if(l){const[,C]=b;S=C}else{const[,C,P]=b;S=C,x=P||""}const k=i(S.trim());return{type:e,raw:b[0],content:x.trim(),attributes:k}}},renderMarkdown:p=>{let f="";a?f=a(p):p.content&&p.content.length>0&&(f=p.content.filter(x=>x.type==="text").map(x=>x.text).join(""));const g=u(p.attrs||{}),w=s(g),b=w?` ${w}`:"";return l?`[${d}${b}]`:`[${d}${b}]${f}[/${d}]`}}}function EI(t,e,n){var a,i,s,o;const l=t.split(`
  8257. `),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}
  8258. `;continue}else return}const g=e.extractItemData(f),{indentLevel:w,mainContent:b}=g;d=`${d}${p}
  8259. `;const x=[b];for(u+=1;u<l.length;){const P=l[u];if(P.trim()===""){const A=l.slice(u+1).findIndex(M=>M.trim()!=="");if(A===-1)break;if((((i=(a=l[u+1+A].match(/^(\s*)/))==null?void 0:a[1])==null?void 0:i.length)||0)>w){x.push(P),d=`${d}${P}
  8260. `,u+=1;continue}else break}if((((o=(s=P.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:o.length)||0)>w)x.push(P),d=`${d}${P}
  8261. `,u+=1;else break}let S;const k=x.slice(1);if(k.length>0){const P=k.map(T=>T.slice(w+m)).join(`
  8262. `);P.trim()&&(e.customNestedParser?S=e.customNestedParser(P):S=n.blockTokens(P))}const C=e.createToken(g,S);c.push(C)}if(c.length!==0)return{items:c,raw:d}}function H5(t,e,n,a){if(!t||!Array.isArray(t.content))return"";const i=typeof n=="function"?n(a):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(`
  8263. `).map(p=>p?e.indent(p):"").join(`
  8264. `);c.push(m)}}),c.join(`
  8265. `)}function xZe(t,e,n={}){const{state:a}=e,{doc:i,tr:s}=a,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 el=class Ple extends z5{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Ple(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function eb(t){return new JXe({find:t.find,handler:({state:e,range:n,match:a,pasteEvent:i})=>{const s=Yr(t.getAttributes,void 0,a,i);if(s===!1||s===null)return null;const{tr:o}=e,l=a[a.length-1],c=a[0];let d=n.to;if(l){const u=c.search(/\S/),m=n.from+c.indexOf(l),p=m+l.length;if(O5(n.from,n.to,e.doc).filter(g=>g.mark.type.excluded.find(b=>b===t.type&&b!==g.mark.type)).filter(g=>g.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:yZe,getOwnPropertySymbols:vZe}=Object,{hasOwnProperty:wZe}=Object.prototype;function W3(t,e){return function(a,i,s){return t(a,i,s)&&e(a,i,s)}}function nN(t){return function(n,a,i){if(!n||!a||typeof n!="object"||typeof a!="object")return t(n,a,i);const{cache:s}=i,o=s.get(n),l=s.get(a);if(o&&l)return o===a&&l===n;s.set(n,a),s.set(a,n);const c=t(n,a,i);return s.delete(n),s.delete(a),c}}function SZe(t){return t?.[Symbol.toStringTag]}function SY(t){return yZe(t).concat(vZe(t))}const _Ze=Object.hasOwn||((t,e)=>wZe.call(t,e));function pb(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const kZe="__v",NZe="__o",CZe="_owner",{getOwnPropertyDescriptor:_Y,keys:kY}=Object;function PZe(t,e){return t.byteLength===e.byteLength&&RP(new Uint8Array(t),new Uint8Array(e))}function TZe(t,e,n){let a=t.length;if(e.length!==a)return!1;for(;a-- >0;)if(!n.equals(t[a],e[a],a,a,t,e,n))return!1;return!0}function AZe(t,e){return t.byteLength===e.byteLength&&RP(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function jZe(t,e){return pb(t.getTime(),e.getTime())}function MZe(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function EZe(t,e){return t===e}function NY(t,e,n){const a=t.size;if(a!==e.size)return!1;if(!a)return!0;const i=new Array(a),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 DZe=pb;function FZe(t,e,n){const a=kY(t);let i=a.length;if(kY(e).length!==i)return!1;for(;i-- >0;)if(!Tle(t,e,n,a[i]))return!1;return!0}function A0(t,e,n){const a=SY(t);let i=a.length;if(SY(e).length!==i)return!1;let s,o,l;for(;i-- >0;)if(s=a[i],!Tle(t,e,n,s)||(o=_Y(t,s),l=_Y(e,s),(o||l)&&(!o||!l||o.configurable!==l.configurable||o.enumerable!==l.enumerable||o.writable!==l.writable)))return!1;return!0}function LZe(t,e){return pb(t.valueOf(),e.valueOf())}function RZe(t,e){return t.source===e.source&&t.flags===e.flags}function CY(t,e,n){const a=t.size;if(a!==e.size)return!1;if(!a)return!0;const i=new Array(a),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 RP(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 IZe(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 Tle(t,e,n,a){return(a===CZe||a===NZe||a===kZe)&&(t.$$typeof||e.$$typeof)?!0:_Ze(e,a)&&n.equals(t[a],e[a],a,a,t,e,n)}const OZe="[object ArrayBuffer]",zZe="[object Arguments]",UZe="[object Boolean]",BZe="[object DataView]",HZe="[object Date]",qZe="[object Error]",$Ze="[object Map]",VZe="[object Number]",GZe="[object Object]",WZe="[object RegExp]",KZe="[object Set]",QZe="[object String]",YZe={"[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},XZe="[object URL]",ZZe=Object.prototype.toString;function JZe({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:a,areErrorsEqual:i,areFunctionsEqual:s,areMapsEqual:o,areNumbersEqual:l,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:m,areTypedArraysEqual:p,areUrlsEqual:f,unknownTagComparators:g}){return function(b,x,S){if(b===x)return!0;if(b==null||x==null)return!1;const k=typeof b;if(k!==typeof x)return!1;if(k!=="object")return k==="number"?l(b,x,S):k==="function"?s(b,x,S):!1;const C=b.constructor;if(C!==x.constructor)return!1;if(C===Object)return c(b,x,S);if(Array.isArray(b))return e(b,x,S);if(C===Date)return a(b,x,S);if(C===RegExp)return u(b,x,S);if(C===Map)return o(b,x,S);if(C===Set)return m(b,x,S);const P=ZZe.call(b);if(P===HZe)return a(b,x,S);if(P===WZe)return u(b,x,S);if(P===$Ze)return o(b,x,S);if(P===KZe)return m(b,x,S);if(P===GZe)return typeof b.then!="function"&&typeof x.then!="function"&&c(b,x,S);if(P===XZe)return f(b,x,S);if(P===qZe)return i(b,x,S);if(P===zZe)return c(b,x,S);if(YZe[P])return p(b,x,S);if(P===OZe)return t(b,x,S);if(P===BZe)return n(b,x,S);if(P===UZe||P===VZe||P===QZe)return d(b,x,S);if(g){let T=g[P];if(!T){const A=SZe(b);A&&(T=g[A])}if(T)return T(b,x,S)}return!1}}function eJe({circular:t,createCustomConfig:e,strict:n}){let a={areArrayBuffersEqual:PZe,areArraysEqual:n?A0:TZe,areDataViewsEqual:AZe,areDatesEqual:jZe,areErrorsEqual:MZe,areFunctionsEqual:EZe,areMapsEqual:n?W3(NY,A0):NY,areNumbersEqual:DZe,areObjectsEqual:n?A0:FZe,arePrimitiveWrappersEqual:LZe,areRegExpsEqual:RZe,areSetsEqual:n?W3(CY,A0):CY,areTypedArraysEqual:n?W3(RP,A0):RP,areUrlsEqual:IZe,unknownTagComparators:void 0};if(e&&(a=Object.assign({},a,e(a))),t){const i=nN(a.areArraysEqual),s=nN(a.areMapsEqual),o=nN(a.areObjectsEqual),l=nN(a.areSetsEqual);a=Object.assign({},a,{areArraysEqual:i,areMapsEqual:s,areObjectsEqual:o,areSetsEqual:l})}return a}function tJe(t){return function(e,n,a,i,s,o,l){return t(e,n,l)}}function nJe({circular:t,comparator:e,createState:n,equals:a,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:a,meta:u,strict:i})};if(t)return function(l,c){return e(l,c,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};const s={cache:void 0,equals:a,meta:void 0,strict:i};return function(l,c){return e(l,c,s)}}const rJe=hf();hf({strict:!0});hf({circular:!0});hf({circular:!0,strict:!0});hf({createInternalComparator:()=>pb});hf({strict:!0,createInternalComparator:()=>pb});hf({circular:!0,createInternalComparator:()=>pb});hf({circular:!0,createInternalComparator:()=>pb,strict:!0});function hf(t={}){const{circular:e=!1,createInternalComparator:n,createState:a,strict:i=!1}=t,s=eJe(t),o=JZe(s),l=n?n(o):tJe(o);return nJe({circular:e,comparator:o,createState:a,equals:l,strict:i})}var aJe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},iJe=({contentComponent:t})=>{const e=rO.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return r.jsx(r.Fragment,{children:Object.values(e)})};function sJe(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,a){e={...e,[n]:zhe.createPortal(a.reactElement,a.element,n)},t.forEach(i=>i())},removeRenderer(n){const a={...e};delete a[n],e=a,t.forEach(i=>i())}}}var oJe=class extends pa.Component{constructor(t){var e;super(t),this.editorContentRef=pa.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=sJe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(a=>a.hasContentComponentInitialized?a:{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 r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:aJe(e,this.editorContentRef),...n}),t?.contentComponent&&r.jsx(iJe,{contentComponent:t.contentComponent})]})}},lJe=y.forwardRef((t,e)=>{const n=pa.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return pa.createElement(oJe,{key:n,innerRef:e,...t})}),Ale=pa.memo(lJe),cJe=typeof window<"u"?y.useLayoutEffect:y.useEffect,dJe=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(a=>a())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function uJe(t){var e;const[n]=y.useState(()=>new dJe(t.editor)),a=xte.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:rJe);return cJe(()=>n.watch(t.editor),[t.editor,n]),y.useDebugValue(a),a}var mJe=!1,DI=typeof window>"u",pJe=DI||!!(typeof window<"u"&&window.next),hJe=class jle{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?DI||pJe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...a)=>{var i,s;return(s=(i=this.options.current).onBeforeCreate)==null?void 0:s.call(i,...a)},onBlur:(...a)=>{var i,s;return(s=(i=this.options.current).onBlur)==null?void 0:s.call(i,...a)},onCreate:(...a)=>{var i,s;return(s=(i=this.options.current).onCreate)==null?void 0:s.call(i,...a)},onDestroy:(...a)=>{var i,s;return(s=(i=this.options.current).onDestroy)==null?void 0:s.call(i,...a)},onFocus:(...a)=>{var i,s;return(s=(i=this.options.current).onFocus)==null?void 0:s.call(i,...a)},onSelectionUpdate:(...a)=>{var i,s;return(s=(i=this.options.current).onSelectionUpdate)==null?void 0:s.call(i,...a)},onTransaction:(...a)=>{var i,s;return(s=(i=this.options.current).onTransaction)==null?void 0:s.call(i,...a)},onUpdate:(...a)=>{var i,s;return(s=(i=this.options.current).onUpdate)==null?void 0:s.call(i,...a)},onContentError:(...a)=>{var i,s;return(s=(i=this.options.current).onContentError)==null?void 0:s.call(i,...a)},onDrop:(...a)=>{var i,s;return(s=(i=this.options.current).onDrop)==null?void 0:s.call(i,...a)},onPaste:(...a)=>{var i,s;return(s=(i=this.options.current).onPaste)==null?void 0:s.call(i,...a)},onDelete:(...a)=>{var i,s;return(s=(i=this.options.current).onDelete)==null?void 0:s.call(i,...a)}};return new lZe(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(a=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(a)?!0:a==="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[a]===n[a])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?jle.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((a,i)=>a===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 fJe(t={},e=[]){const n=y.useRef(t);n.current=t;const[a]=y.useState(()=>new hJe(n)),i=rO.useSyncExternalStore(a.subscribe,a.getEditor,a.getServerSnapshot);return y.useDebugValue(i),y.useEffect(a.onRender(e)),uJe({editor:i,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),i}var Mle=y.createContext({editor:null});Mle.Consumer;var gJe=y.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),bJe=()=>y.useContext(gJe);pa.forwardRef((t,e)=>{const{onDragStart:n}=bJe(),a=t.as||"div";return r.jsx(a,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});pa.createContext({markViewContentRef:()=>{}});var q5=y.createContext({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}});q5.displayName="TiptapContext";var xJe=()=>y.useContext(q5);function Ele({editor:t,instance:e,children:n}){const a=t??e;if(!a)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const i=y.useMemo(()=>({editor:a}),[a]),s=y.useMemo(()=>({editor:a}),[a]);return r.jsx(Mle.Provider,{value:s,children:r.jsx(q5.Provider,{value:i,children:n})})}Ele.displayName="Tiptap";function Dle({...t}){const{editor:e}=xJe();return r.jsx(Ale,{editor:e,...t})}Dle.displayName="Tiptap.Content";Object.assign(Ele,{Content:Dle});var IP=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...a}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,a,n]},yJe=/^\s*>\s$/,vJe=el.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return IP("blockquote",{...si(this.options.HTMLAttributes,t),children:IP("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",a=[];return t.content.forEach(i=>{const l=e.renderChildren([i]).split(`
  8266. `).map(c=>c.trim()===""?n:`${n} ${c}`);a.push(l.join(`
  8267. `))}),a.join(`
  8268. ${n}
  8269. `)},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[Hy({find:yJe,type:this.type})]}}),wJe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,SJe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,_Je=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,kJe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,NJe=pf.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 IP("strong",{...si(this.options.HTMLAttributes,t),children:IP("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[By({find:wJe,type:this.type}),By({find:_Je,type:this.type})]},addPasteRules(){return[eb({find:SJe,type:this.type}),eb({find:kJe,type:this.type})]}}),CJe=/(^|[^`])`([^`]+)`(?!`)$/,PJe=/(^|[^`])`([^`]+)`(?!`)/g,TJe=pf.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",si(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[By({find:CJe,type:this.type})]},addPasteRules(){return[eb({find:PJe,type:this.type})]}}),K3=4,AJe=/^```([a-z]+)?[\s\n]$/,jJe=/^~~~([a-z]+)?[\s\n]$/,MJe=el.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:K3,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",si(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 a="";const i=((n=t.attrs)==null?void 0:n.language)||"";return t.content?a=[`\`\`\`${i}`,e.renderChildren(t.content),"```"].join(`
  8270. `):a=`\`\`\`${i}
  8271. \`\`\``,a},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:K3,{state:a}=t,{selection:i}=a,{$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=a.doc.textBetween(d,u,`
  8272. `,`
  8273. `).split(`
  8274. `).map(g=>l+g).join(`
  8275. `);return c.replaceWith(d,u,a.schema.text(f)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:K3,{state:a}=t,{selection:i}=a,{$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=a.doc.textBetween(u,m,`
  8276. `,`
  8277. `).split(`
  8278. `);let g=0,w=0;const b=d-u;for(let T=0;T<f.length;T+=1){if(w+f[T].length>=b){g=T;break}w+=f[T].length+1}const S=((c=f[g].match(/^ */))==null?void 0:c[0])||"",k=Math.min(S.length,n);if(k===0)return!0;let C=u;for(let T=0;T<g;T+=1)C+=f[T].length+1;return l.delete(C,C+k),d-C<=k&&l.setSelection(Vn.create(l.doc,C)),!0}):t.commands.command(({tr:l})=>{const{from:c,to:d}=i,p=a.doc.textBetween(c,d,`
  8279. `,`
  8280. `).split(`
  8281. `).map(f=>{var g;const w=((g=f.match(/^ */))==null?void 0:g[0])||"",b=Math.min(w.length,n);return f.slice(b)}).join(`
  8282. `);return l.replaceWith(c,d,a.schema.text(p)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type)return!1;const s=a.parentOffset===a.parent.nodeSize-2,o=a.parent.textContent.endsWith(`
  8283. `);return!s||!o?!1:t.chain().command(({tr:l})=>(l.delete(a.pos-2,a.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:a}=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:a.nodeAt(l)?t.commands.command(({tr:d})=>(d.setSelection(sr.near(a.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[MI({find:AJe,type:this.type,getAttributes:t=>({language:t[1]})}),MI({find:jJe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new Wa({key:new Wi("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),a=e.clipboardData.getData("vscode-editor-data"),i=a?JSON.parse(a):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,`
  8284. `));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(Vn.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),EJe=el.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8285. `):""}),DJe=el.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",si(this.options.HTMLAttributes,t)]},renderText(){return`
  8286. `},renderMarkdown:()=>`
  8287. `,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:a})=>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}=a.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()}}}),FJe=el.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]}`,si(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 a=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,i="#".repeat(a);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=>MI({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),LJe=el.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",si(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!uZe(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:a}=n,i=t();return cle(n)?i.insertContentAt(a.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(Vn.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(Rn.create(o.doc,c.pos)):o.setSelection(Vn.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(Vn.create(o.doc,d+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Cle({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),RJe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,IJe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,OJe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,zJe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,UJe=pf.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",si(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[By({find:RJe,type:this.type}),By({find:OJe,type:this.type})]},addPasteRules(){return[eb({find:IJe,type:this.type}),eb({find:zJe,type:this.type})]}});const BJe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",HJe="ελ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",FI="numeric",LI="ascii",RI="alpha",pw="asciinumeric",G0="alphanumeric",II="domain",Fle="emoji",qJe="scheme",$Je="slashscheme",Q3="whitespace";function VJe(t,e){return t in e||(e[t]=[]),e[t]}function pg(t,e,n){e[FI]&&(e[pw]=!0,e[G0]=!0),e[LI]&&(e[pw]=!0,e[RI]=!0),e[pw]&&(e[G0]=!0),e[RI]&&(e[G0]=!0),e[G0]&&(e[II]=!0),e[Fle]&&(e[II]=!0);for(const a in e){const i=VJe(a,n);i.indexOf(t)<0&&i.push(t)}}function GJe(t,e){const n={};for(const a in e)e[a].indexOf(t)>=0&&(n[a]=!0);return n}function $o(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}$o.groups={};$o.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let a=0;a<e.jr.length;a++){const i=e.jr[a][0],s=e.jr[a][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,a){for(let i=0;i<t.length;i++)this.tt(t[i],e,n,a)},tr(t,e,n,a){a=a||$o.groups;let i;return e&&e.j?i=e:(i=new $o(e),n&&a&&pg(e,n,a)),this.jr.push([t,i]),i},ts(t,e,n,a){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,a)},tt(t,e,n,a){a=a||$o.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 $o,Object.assign(o.j,l.j),o.jr.push.apply(o.jr,l.jr),o.jd=l.jd,o.t=l.t):o=new $o,s){if(a)if(o.t&&typeof o.t=="string"){const c=Object.assign(GJe(o.t,a),n);pg(s,c,a)}else n&&pg(s,n,a);o.t=s}return i.j[t]=o,o}};const nr=(t,e,n,a,i)=>t.ta(e,n,a,i),Ja=(t,e,n,a,i)=>t.tr(e,n,a,i),PY=(t,e,n,a,i)=>t.ts(e,n,a,i),Jt=(t,e,n,a,i)=>t.tt(e,n,a,i),mm="WORD",OI="UWORD",Lle="ASCIINUMERICAL",Rle="ALPHANUMERICAL",bS="LOCALHOST",zI="TLD",UI="UTLD",UN="SCHEME",$x="SLASH_SCHEME",$5="NUM",BI="WS",V5="NL",hw="OPENBRACE",fw="CLOSEBRACE",OP="OPENBRACKET",zP="CLOSEBRACKET",UP="OPENPAREN",BP="CLOSEPAREN",HP="OPENANGLEBRACKET",qP="CLOSEANGLEBRACKET",$P="FULLWIDTHLEFTPAREN",VP="FULLWIDTHRIGHTPAREN",GP="LEFTCORNERBRACKET",WP="RIGHTCORNERBRACKET",KP="LEFTWHITECORNERBRACKET",QP="RIGHTWHITECORNERBRACKET",YP="FULLWIDTHLESSTHAN",XP="FULLWIDTHGREATERTHAN",ZP="AMPERSAND",JP="APOSTROPHE",eT="ASTERISK",lh="AT",tT="BACKSLASH",nT="BACKTICK",rT="CARET",hh="COLON",G5="COMMA",aT="DOLLAR",$d="DOT",iT="EQUALS",W5="EXCLAMATION",Jl="HYPHEN",gw="PERCENT",sT="PIPE",oT="PLUS",lT="POUND",bw="QUERY",K5="QUOTE",Ile="FULLWIDTHMIDDLEDOT",Q5="SEMI",Vd="SLASH",xw="TILDE",cT="UNDERSCORE",Ole="EMOJI",dT="SYM";var zle=Object.freeze({__proto__:null,ALPHANUMERICAL:Rle,AMPERSAND:ZP,APOSTROPHE:JP,ASCIINUMERICAL:Lle,ASTERISK:eT,AT:lh,BACKSLASH:tT,BACKTICK:nT,CARET:rT,CLOSEANGLEBRACKET:qP,CLOSEBRACE:fw,CLOSEBRACKET:zP,CLOSEPAREN:BP,COLON:hh,COMMA:G5,DOLLAR:aT,DOT:$d,EMOJI:Ole,EQUALS:iT,EXCLAMATION:W5,FULLWIDTHGREATERTHAN:XP,FULLWIDTHLEFTPAREN:$P,FULLWIDTHLESSTHAN:YP,FULLWIDTHMIDDLEDOT:Ile,FULLWIDTHRIGHTPAREN:VP,HYPHEN:Jl,LEFTCORNERBRACKET:GP,LEFTWHITECORNERBRACKET:KP,LOCALHOST:bS,NL:V5,NUM:$5,OPENANGLEBRACKET:HP,OPENBRACE:hw,OPENBRACKET:OP,OPENPAREN:UP,PERCENT:gw,PIPE:sT,PLUS:oT,POUND:lT,QUERY:bw,QUOTE:K5,RIGHTCORNERBRACKET:WP,RIGHTWHITECORNERBRACKET:QP,SCHEME:UN,SEMI:Q5,SLASH:Vd,SLASH_SCHEME:$x,SYM:dT,TILDE:xw,TLD:zI,UNDERSCORE:cT,UTLD:UI,UWORD:OI,WORD:mm,WS:BI});const om=/[a-z]/,j0=new RegExp("\\p{L}","u"),Y3=new RegExp("\\p{Emoji}","u"),lm=/\d/,X3=/\s/,TY="\r",Z3=`
  8288. `,WJe="️",KJe="‍",J3="";let rN=null,aN=null;function QJe(t=[]){const e={};$o.groups=e;const n=new $o;rN==null&&(rN=AY(BJe)),aN==null&&(aN=AY(HJe)),Jt(n,"'",JP),Jt(n,"{",hw),Jt(n,"}",fw),Jt(n,"[",OP),Jt(n,"]",zP),Jt(n,"(",UP),Jt(n,")",BP),Jt(n,"<",HP),Jt(n,">",qP),Jt(n,"(",$P),Jt(n,")",VP),Jt(n,"「",GP),Jt(n,"」",WP),Jt(n,"『",KP),Jt(n,"』",QP),Jt(n,"<",YP),Jt(n,">",XP),Jt(n,"&",ZP),Jt(n,"*",eT),Jt(n,"@",lh),Jt(n,"`",nT),Jt(n,"^",rT),Jt(n,":",hh),Jt(n,",",G5),Jt(n,"$",aT),Jt(n,".",$d),Jt(n,"=",iT),Jt(n,"!",W5),Jt(n,"-",Jl),Jt(n,"%",gw),Jt(n,"|",sT),Jt(n,"+",oT),Jt(n,"#",lT),Jt(n,"?",bw),Jt(n,'"',K5),Jt(n,"/",Vd),Jt(n,";",Q5),Jt(n,"~",xw),Jt(n,"_",cT),Jt(n,"\\",tT),Jt(n,"・",Ile);const a=Ja(n,lm,$5,{[FI]:!0});Ja(a,lm,a);const i=Ja(a,om,Lle,{[pw]:!0}),s=Ja(a,j0,Rle,{[G0]:!0}),o=Ja(n,om,mm,{[LI]:!0});Ja(o,lm,i),Ja(o,om,o),Ja(i,lm,i),Ja(i,om,i);const l=Ja(n,j0,OI,{[RI]:!0});Ja(l,om),Ja(l,lm,s),Ja(l,j0,l),Ja(s,lm,s),Ja(s,om),Ja(s,j0,s);const c=Jt(n,Z3,V5,{[Q3]:!0}),d=Jt(n,TY,BI,{[Q3]:!0}),u=Ja(n,X3,BI,{[Q3]:!0});Jt(n,J3,u),Jt(d,Z3,c),Jt(d,J3,u),Ja(d,X3,u),Jt(u,TY),Jt(u,Z3),Ja(u,X3,u),Jt(u,J3,u);const m=Ja(n,Y3,Ole,{[Fle]:!0});Jt(m,"#"),Ja(m,Y3,m),Jt(m,WJe,m);const p=Jt(m,KJe);Jt(p,"#"),Ja(p,Y3,m);const f=[[om,o],[lm,i]],g=[[om,null],[j0,l],[lm,s]];for(let w=0;w<rN.length;w++)Xp(n,rN[w],zI,mm,f);for(let w=0;w<aN.length;w++)Xp(n,aN[w],UI,OI,g);pg(zI,{tld:!0,ascii:!0},e),pg(UI,{utld:!0,alpha:!0},e),Xp(n,"file",UN,mm,f),Xp(n,"mailto",UN,mm,f),Xp(n,"http",$x,mm,f),Xp(n,"https",$x,mm,f),Xp(n,"ftp",$x,mm,f),Xp(n,"ftps",$x,mm,f),pg(UN,{scheme:!0,ascii:!0},e),pg($x,{slashscheme:!0,ascii:!0},e),t=t.sort((w,b)=>w[0]>b[0]?1:-1);for(let w=0;w<t.length;w++){const b=t[w][0],S=t[w][1]?{[qJe]:!0}:{[$Je]:!0};b.indexOf("-")>=0?S[II]=!0:om.test(b)?lm.test(b)?S[pw]=!0:S[LI]=!0:S[FI]=!0,PY(n,b,b,S)}return PY(n,"localhost",bS,{ascii:!0}),n.jd=new $o(dT),{start:n,tokens:Object.assign({groups:e},zle)}}function Ule(t,e){const n=YJe(e.replace(/[A-Z]/g,l=>l.toLowerCase())),a=n.length,i=[];let s=0,o=0;for(;o<a;){let l=t,c=null,d=0,u=null,m=-1,p=-1;for(;o<a&&(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 YJe(t){const e=[],n=t.length;let a=0;for(;a<n;){let i=t.charCodeAt(a),s,o=i<55296||i>56319||a+1===n||(s=t.charCodeAt(a+1))<56320||s>57343?t[a]:t.slice(a,a+2);e.push(o),a+=o.length}return e}function Xp(t,e,n,a,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 $o(a),s.jr=i.slice(),t.j[c]=s),t=s}return s=new $o(n),s.jr=i.slice(),t.j[e[o-1]]=s,s}function AY(t){const e=[],n=[];let a=0,i="0123456789";for(;a<t.length;){let s=0;for(;i.indexOf(t[a+s])>=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(a,a+s),10);o>0;o--)n.pop();a+=s}else n.push(t[a]),a++}return e}const xS={defaultProtocol:"http",events:null,format:jY,formatHref:jY,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Y5(t,e=null){let n=Object.assign({},xS);t&&(n=Object.assign(n,t instanceof Y5?t.o:t));const a=n.ignoreTags,i=[];for(let s=0;s<a.length;s++)i.push(a[s].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=i}Y5.prototype={o:xS,ignoreTags:[],defaultRender(t){return t},check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const a=e!=null;let i=this.o[t];return i&&(typeof i=="object"?(i=n.t in i?i[n.t]:xS[t],typeof i=="function"&&a&&(i=i(e,n))):typeof i=="function"&&a&&(i=i(e,n.t,n)),i)},getObj(t,e,n){let a=this.o[t];return typeof a=="function"&&e!=null&&(a=a(e,n.t,n)),a},render(t){const e=t.render(this);return(this.get("render",null,t)||this.defaultRender)(e,t.t,t)}};function jY(t){return t}function Ble(t,e){this.t="token",this.v=t,this.tk=e}Ble.prototype={isLink:!1,toString(){return this.v},toHref(t){return this.toString()},toFormattedString(t){const e=this.toString(),n=t.get("truncate",e,this),a=t.get("format",e,this);return n&&a.length>n?a.substring(0,n)+"…":a},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=xS.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")),a=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=a,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 XA(t,e){class n extends Ble{constructor(i,s){super(i,s),this.t=t}}for(const a in e)n.prototype[a]=e[a];return n.t=t,n}const MY=XA("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),EY=XA("text"),XJe=XA("nl"),iN=XA("url",{isLink:!0,toHref(t=xS.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==bS&&t[1].t===hh}}),Yl=t=>new $o(t);function ZJe({groups:t}){const e=t.domain.concat([ZP,eT,lh,tT,nT,rT,aT,iT,Jl,$5,gw,sT,oT,lT,Vd,dT,xw,cT]),n=[JP,hh,G5,$d,W5,gw,bw,K5,Q5,HP,qP,hw,fw,zP,OP,UP,BP,$P,VP,GP,WP,KP,QP,YP,XP],a=[ZP,JP,eT,tT,nT,rT,aT,iT,Jl,hw,fw,gw,sT,oT,lT,bw,Vd,dT,xw,cT],i=Yl(),s=Jt(i,xw);nr(s,a,s),nr(s,t.domain,s);const o=Yl(),l=Yl(),c=Yl();nr(i,t.domain,o),nr(i,t.scheme,l),nr(i,t.slashscheme,c),nr(o,a,s),nr(o,t.domain,o);const d=Jt(o,lh);Jt(s,lh,d),Jt(l,lh,d),Jt(c,lh,d);const u=Jt(s,$d);nr(u,a,s),nr(u,t.domain,s);const m=Yl();nr(d,t.domain,m),nr(m,t.domain,m);const p=Jt(m,$d);nr(p,t.domain,m);const f=Yl(MY);nr(p,t.tld,f),nr(p,t.utld,f),Jt(d,bS,f);const g=Jt(m,Jl);Jt(g,Jl,g),nr(g,t.domain,m),nr(f,t.domain,m),Jt(f,$d,p),Jt(f,Jl,g);const w=Jt(f,hh);nr(w,t.numeric,MY);const b=Jt(o,Jl),x=Jt(o,$d);Jt(b,Jl,b),nr(b,t.domain,o),nr(x,a,s),nr(x,t.domain,o);const S=Yl(iN);nr(x,t.tld,S),nr(x,t.utld,S),nr(S,t.domain,o),nr(S,a,s),Jt(S,$d,x),Jt(S,Jl,b),Jt(S,lh,d);const k=Jt(S,hh),C=Yl(iN);nr(k,t.numeric,C);const P=Yl(iN),T=Yl();nr(P,e,P),nr(P,n,T),nr(T,e,P),nr(T,n,T),Jt(S,Vd,P),Jt(C,Vd,P);const A=Jt(l,hh),F=Jt(c,hh),_=Jt(F,Vd),M=Jt(_,Vd);nr(l,t.domain,o),Jt(l,$d,x),Jt(l,Jl,b),nr(c,t.domain,o),Jt(c,$d,x),Jt(c,Jl,b),nr(A,t.domain,P),Jt(A,Vd,P),Jt(A,bw,P),nr(M,t.domain,P),nr(M,e,P),Jt(M,Vd,P);const H=[[hw,fw],[OP,zP],[UP,BP],[HP,qP],[$P,VP],[GP,WP],[KP,QP],[YP,XP]];for(let I=0;I<H.length;I++){const[z,L]=H[I],Z=Jt(P,z);Jt(T,z,Z),Jt(Z,L,P);const ne=Yl(iN);nr(Z,e,ne);const Y=Yl();nr(Z,n),nr(ne,e,ne),nr(ne,n,Y),nr(Y,e,ne),nr(Y,n,Y),Jt(ne,L,P),Jt(Y,L,P)}return Jt(i,bS,S),Jt(i,V5,XJe),{start:i,tokens:zle}}function JJe(t,e,n){let a=n.length,i=0,s=[],o=[];for(;i<a;){let l=t,c=null,d=null,u=0,m=null,p=-1;for(;i<a&&!(c=l.go(n[i].t));)o.push(n[i++]);for(;i<a&&(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<a&&(o.push(n[i]),i++);else{o.length>0&&(s.push(eF(EY,e,o)),o=[]),i-=p,u-=p;const f=m.t,g=n.slice(i-u,i);s.push(eF(f,e,g))}}return o.length>0&&s.push(eF(EY,e,o)),s}function eF(t,e,n){const a=n[0].s,i=n[n.length-1].e,s=e.slice(a,i);return new t(s,n)}const eet=typeof console<"u"&&console&&console.warn||(()=>{}),tet="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Aa={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function net(){return $o.groups={},Aa.scanner=null,Aa.parser=null,Aa.tokenQueue=[],Aa.pluginQueue=[],Aa.customSchemes=[],Aa.initialized=!1,Aa}function DY(t,e=!1){if(Aa.initialized&&eet(`linkifyjs: already initialized - will not register custom scheme "${t}" ${tet}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format.
  8289. 1. Must only contain digits, lowercase ASCII letters or "-"
  8290. 2. Cannot start or end with "-"
  8291. 3. "-" cannot repeat`);Aa.customSchemes.push([t,e])}function ret(){Aa.scanner=QJe(Aa.customSchemes);for(let t=0;t<Aa.tokenQueue.length;t++)Aa.tokenQueue[t][1]({scanner:Aa.scanner});Aa.parser=ZJe(Aa.scanner.tokens);for(let t=0;t<Aa.pluginQueue.length;t++)Aa.pluginQueue[t][1]({scanner:Aa.scanner,parser:Aa.parser});return Aa.initialized=!0,Aa}function X5(t){return Aa.initialized||ret(),JJe(Aa.parser.start,t,Ule(Aa.scanner.start,t))}X5.scan=Ule;function Hle(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 a=new Y5(n),i=X5(t),s=[];for(let o=0;o<i.length;o++){const l=i[o];l.isLink&&(!e||l.t===e)&&a.check(l)&&s.push(l.toFormattedObject(a))}return s}var Z5="[\0-   ᠎ -\u2029  ]",aet=new RegExp(Z5),iet=new RegExp(`${Z5}$`),set=new RegExp(Z5,"g");function oet(t){return t.length===1?t[0].isLink:t.length===3&&t[1].isLink?["()","[]"].includes(t[0].value+t[2].value):!1}function cet(t){return new Wa({key:new Wi("autolink"),appendTransaction:(e,n,a)=>{const i=e.some(d=>d.docChanged)&&!n.doc.eq(a.doc),s=e.some(d=>d.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=a,l=tle(n.doc,[...e]);if(lle(l).forEach(({newRange:d})=>{const u=dXe(a.doc,d,f=>f.isTextblock);let m,p;if(u.length>1)m=u[0],p=a.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(u.length){const f=a.doc.textBetween(d.from,d.to," "," ");if(!iet.test(f))return;m=u[0],p=a.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&p){const f=p.split(aet).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],w=m.pos+p.lastIndexOf(g);if(!g)return!1;const b=X5(g).map(x=>x.toObject(t.defaultProtocol));if(!oet(b))return!1;b.filter(x=>x.isLink).map(x=>({...x,from:w+x.start+1,to:w+x.end+1})).filter(x=>a.schema.marks.code?!a.doc.rangeHasMark(x.from,x.to,a.schema.marks.code):!0).filter(x=>t.validate(x.value)).filter(x=>t.shouldAutoLink(x.value)).forEach(x=>{O5(x.from,x.to,a.doc).some(S=>S.mark.type===t.type)||o.addMark(x.from,x.to,t.type.create({href:x.href}))})}}),!!o.steps.length)return o}})}function det(t){return new Wa({key:new Wi("handleClickLink"),props:{handleClick:(e,n,a)=>{var i,s;if(a.button!==0||!e.editable)return!1;let o=null;if(a.target instanceof HTMLAnchorElement)o=a.target;else{const c=a.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=ole(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 uet(t){return new Wa({key:new Wi("handlePasteLink"),props:{handlePaste:(e,n,a)=>{const{shouldAutoLink:i}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";a.content.forEach(u=>{c+=u.textContent});const d=Hle(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 $f(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(a=>{const i=typeof a=="string"?a:a.scheme;i&&n.push(i)}),!t||t.replace(set,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var qle=pf.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"){DY(t);return}DY(t.scheme,t.optionalSlashes)})},onDestroy(){net()},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)=>!!$f(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=>!!$f(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=>!!$f(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",si(this.options.HTMLAttributes,t),0]:["a",si(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,a,i,s;const o=(a=(n=t.attrs)==null?void 0:n.href)!=null?a:"",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:a=>!!$f(a,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:a=>!!$f(a,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[eb({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:a}=this.options,i=Hle(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!$f(o,n),protocols:n,defaultProtocol:a}));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(cet({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:a=>this.options.isAllowedUri(a,{defaultValidate:i=>!!$f(i,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(det({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(uet({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),met=qle,pet=Object.defineProperty,het=(t,e)=>{for(var n in e)pet(t,n,{get:e[n],enumerable:!0})},fet="listItem",FY="textStyle",LY=/^\s*([-+*])\s$/,$le=el.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",si(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,`
  8292. `):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(fet,this.editor.getAttributes(FY)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=Hy({find:LY,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Hy({find:LY,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(FY),editor:this.editor})),[t]}}),Vle=el.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",si(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)=>H5(t,e,a=>{var i,s;return a.parentType==="bulletList"?"- ":a.parentType==="orderedList"?`${(((s=(i=a.meta)==null?void 0:i.parentAttrs)==null?void 0:s.start)||1)+a.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)}}}),get={};het(get,{findListItemPos:()=>g_,getNextListDepth:()=>J5,handleBackspace:()=>HI,handleDelete:()=>qI,hasListBefore:()=>Gle,hasListItemAfter:()=>bet,hasListItemBefore:()=>Wle,listItemHasSubList:()=>Kle,nextListIsDeeper:()=>Qle,nextListIsHigher:()=>Yle});var g_=(t,e)=>{const{$from:n}=e.selection,a=Ai(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===a?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},J5=(t,e)=>{const n=g_(t,e);if(!n)return!1;const[,a]=vXe(e,t,n.$pos.pos+4);return a},Gle=(t,e,n)=>{const{$anchor:a}=t.selection,i=Math.max(0,a.pos-2),s=t.doc.resolve(i).node();return!(!s||!n.includes(s.type.name))},Wle=(t,e)=>{var n;const{$anchor:a}=e.selection,i=e.doc.resolve(a.pos-2);return!(i.index()===0||((n=i.nodeBefore)==null?void 0:n.type.name)!==t)},Kle=(t,e,n)=>{if(!n)return!1;const a=Ai(t,e.schema);let i=!1;return n.descendants(s=>{s.type===a&&(i=!0)}),i},HI=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!tf(t.state,e)&&Gle(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(!tf(t.state,e)||!kXe(t.state))return!1;const a=g_(e,t.state);if(!a)return!1;const s=t.state.doc.resolve(a.$pos.pos-2).node(a.depth),o=Kle(e,t.state,s);return Wle(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},Qle=(t,e)=>{const n=J5(t,e),a=g_(t,e);return!a||!n?!1:n>a.depth},Yle=(t,e)=>{const n=J5(t,e),a=g_(t,e);return!a||!n?!1:n<a.depth},qI=(t,e)=>{if(!tf(t.state,e)||!_Xe(t.state,e))return!1;const{selection:n}=t.state,{$from:a,$to:i}=n;return!n.empty&&a.sameParent(i)?!1:Qle(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():Yle(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},bet=(t,e)=>{var n;const{$anchor:a}=e.selection,i=e.doc.resolve(a.pos-a.parentOffset-2);return!(i.index()===i.parent.childCount-1||((n=i.nodeAfter)==null?void 0:n.type.name)!==t)},Xle=da.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&&qI(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&&qI(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:a})=>{t.state.schema.nodes[n]!==void 0&&HI(t,n,a)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:a})=>{t.state.schema.nodes[n]!==void 0&&HI(t,n,a)&&(e=!0)}),e}}}}),RY=/^(\s*)(\d+)\.\s+(.*)$/,xet=/^\s/;function yet(t){const e=[];let n=0,a=0;for(;n<t.length;){const i=t[n],s=i.match(RY);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(RY))break;if(f.trim()==="")p.push(f),u+=`
  8293. `,m+=1;else if(f.match(xet))p.push(f),u+=`
  8294. ${f.slice(d+2)}`,m+=1;else break}e.push({indent:d,number:parseInt(l,10),content:u.trim(),raw:p.join(`
  8295. `)}),a=m,n=m}return[e,a]}function Zle(t,e,n){var a;const i=[];let s=0;for(;s<t.length;){const o=t[s];if(o.indent===e){const l=o.content.split(`
  8296. `),c=((a=l[0])==null?void 0:a.trim())||"",d=[];c&&d.push({type:"paragraph",raw:c,tokens:n.inlineTokens(c)});const u=l.slice(1).join(`
  8297. `).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(w=>w.indent)),g=Zle(p,f,n);d.push({type:"list",ordered:!0,start:p[0].number,items:g,raw:p.map(w=>w.raw).join(`
  8298. `)})}i.push({type:"list_item",raw:o.raw,tokens:d}),s=m}else s+=1}return i}function vet(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const a=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")a.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);a.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&a.push(...s)}}),{type:"listItem",content:a}})}var wet="listItem",IY="textStyle",OY=/^(\d+)\.\s$/,Jle=el.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",si(this.options.HTMLAttributes,n),0]:["ol",si(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,a=t.items?vet(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:a}:{type:"orderedList",content:a}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8299. `):"",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 a;const i=t.split(`
  8300. `),[s,o]=yet(i);if(s.length===0)return;const l=Zle(s,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((a=s[0])==null?void 0:a.number)||1,items:l,raw:i.slice(0,o).join(`
  8301. `)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(wet,this.editor.getAttributes(IY)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=Hy({find:OY,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=Hy({find:OY,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(IY)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),_et=/^\s*(\[([( |x])?\])\s$/,ket=el.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",si(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 a=e.parseChildren(t.nestedTokens);n.push(...a)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const i=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return H5(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:a})=>{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(!a.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:p}=m.target;a.isEditable&&typeof n=="function"&&a.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const g=n();if(typeof g!="number")return!1;const w=f.doc.nodeAt(g);return f.setNodeMarkup(g,void 0,{...w?.attrs,checked:p}),!0}).run(),!a.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=a.extensionManager.attributes,f=gS(m,p),g=new Set(Object.keys(f)),w=this.options.HTMLAttributes;return u.forEach(b=>{g.has(b)||(b in w?i.setAttribute(b,w[b]):i.removeAttribute(b))}),Object.entries(f).forEach(([b,x])=>{x==null?b in w?i.setAttribute(b,w[b]):i.removeAttribute(b):i.setAttribute(b,x)}),u=g,!0}}}},addInputRules(){return[Hy({find:_et,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),Net=el.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",si(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,`
  8302. `):"",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 a=s=>{const o=EI(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:a},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(s)},i=EI(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:a},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()}}});da.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push($le.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(Vle.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(Xle.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(Jle.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(ket.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(Net.configure(this.options.taskList)),t}});var zY="&nbsp;",Cet=" ",Pet=el.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",si(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 a=e.parseInline(n);return a.length===1&&a[0].type==="text"&&(a[0].text===zY||a[0].text===Cet)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,a)},renderMarkdown:(t,e)=>{if(!t)return"";const n=Array.isArray(t.content)?t.content:[];return n.length===0?zY:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Tet=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Aet=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,jet=pf.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",si(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[By({find:Tet,type:this.type})]},addPasteRules(){return[eb({find:Aet,type:this.type})]}}),Met=el.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),ece=pf.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",si(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()}}}),Eet=ece;function Det(t={}){return new Wa({view(e){return new Fet(e,t)}})}class Fet{constructor(e,n){var a;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(a=n.width)!==null&&a!==void 0?a: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,a,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 g=f.getBoundingClientRect(),w=m?g.bottom:g.top;m&&p&&(w=(w+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*l;a={left:g.left,right:g.right,top:w-b,bottom:w+b}}}}if(!a){let m=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*o;a={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=(a.left-d)/o+"px",this.element.style.top=(a.top-u)/l+"px",this.element.style.width=(a.right-a.left)/o+"px",this.element.style.height=(a.bottom-a.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}),a=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),i=a&&a.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=Gse(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 ri extends sr{constructor(e){super(e,e)}map(e,n){let a=e.resolve(n.map(this.head));return ri.valid(a)?new ri(a):sr.near(a)}content(){return gn.empty}eq(e){return e instanceof ri&&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 ri(e.resolve(n.pos))}getBookmark(){return new eU(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!Let(e)||!Ret(e))return!1;let a=n.type.spec.allowGapCursor;if(a!=null)return a;let i=n.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,n,a=!1){e:for(;;){if(!a&&ri.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(ri.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!Rn.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*n),a=!1;continue e}break}s=o,i+=n;let l=e.doc.resolve(i);if(ri.valid(l))return l}return null}}}ri.prototype.visible=!1;ri.findFrom=ri.findGapCursorFrom;sr.jsonID("gapcursor",ri);class eU{constructor(e){this.pos=e}map(e){return new eU(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ri.valid(n)?new ri(n):sr.near(n)}}function tce(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function Let(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),a=t.node(e);if(n==0){if(a.type.spec.isolating)return!0;continue}for(let i=a.child(n-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||tce(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Ret(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),a=t.node(e);if(n==a.childCount){if(a.type.spec.isolating)return!0;continue}for(let i=a.child(n);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||tce(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Iet(){return new Wa({props:{decorations:Bet,createSelectionBetween(t,e,n){return e.pos==n.pos&&ri.valid(n)?new ri(n):null},handleClick:zet,handleKeyDown:Oet,handleDOMEvents:{beforeinput:Uet}}})}const Oet=Woe({ArrowLeft:sN("horiz",-1),ArrowRight:sN("horiz",1),ArrowUp:sN("vert",-1),ArrowDown:sN("vert",1)});function sN(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(a,i,s){let o=a.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof Vn){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=a.doc.resolve(e>0?l.after():l.before())}let d=ri.findGapCursorFrom(l,e,c);return d?(i&&i(a.tr.setSelection(new ri(d))),!0):!1}}function zet(t,e,n){if(!t||!t.editable)return!1;let a=t.state.doc.resolve(e);if(!ri.valid(a))return!1;let i=t.posAtCoords({left:n.clientX,top:n.clientY});return i&&i.inside>-1&&Rn.isSelectable(t.state.doc.nodeAt(i.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ri(a))),!0)}function Uet(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ri))return!1;let{$from:n}=t.state.selection,a=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!a)return!1;let i=Yt.empty;for(let o=a.length-1;o>=0;o--)i=Yt.from(a[o].createAndFill(null,i));let s=t.state.tr.replace(n.pos,n.pos,new gn(i,0,0));return s.setSelection(Vn.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function Bet(t){if(!(t.selection instanceof ri))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Ba.create(t.doc,[vo.widget(t.selection.head,e,{key:"gapcursor"})])}var uT=200,ps=function(){};ps.prototype.append=function(e){return e.length?(e=ps.from(e),!this.length&&e||e.length<uT&&this.leafAppend(e)||this.length<uT&&e.leafPrepend(this)||this.appendInner(e)):this};ps.prototype.prepend=function(e){return e.length?ps.from(e).append(this):this};ps.prototype.appendInner=function(e){return new Het(this,e)};ps.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?ps.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};ps.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};ps.prototype.forEach=function(e,n,a){n===void 0&&(n=0),a===void 0&&(a=this.length),n<=a?this.forEachInner(e,n,a,0):this.forEachInvertedInner(e,n,a,0)};ps.prototype.map=function(e,n,a){n===void 0&&(n=0),a===void 0&&(a=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},n,a),i};ps.from=function(e){return e instanceof ps?e:e&&e.length?new nce(e):ps.empty};var nce=(function(t){function e(a){t.call(this),this.values=a}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<=uT)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=uT)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})(ps);ps.empty=new nce([]);var Het=(function(t){function e(n,a){t.call(this),this.left=n,this.right=a,this.length=n.length+a.length,this.depth=Math.max(n.depth,a.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(a){return a<this.left.length?this.left.get(a):this.right.get(a-this.left.length)},e.prototype.forEachInner=function(a,i,s,o){var l=this.left.length;if(i<l&&this.left.forEachInner(a,i,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(a,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(a,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(a,i-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(a,Math.min(i,l),s,o)===!1)return!1},e.prototype.sliceInner=function(a,i){if(a==0&&i==this.length)return this;var s=this.left.length;return i<=s?this.left.slice(a,i):a>=s?this.right.slice(a-s,i-s):this.left.slice(a,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(a){var i=this.right.leafAppend(a);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(a){var i=this.left.leafPrepend(a);if(i)return new e(i,this.right)},e.prototype.appendInner=function(a){return this.left.depth>=Math.max(this.right.depth,a.depth)+1?new e(this.left,new e(this.right,a)):new e(this,a)},e})(ps);const qet=500;class od{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let a=this.items.length;for(;;a--)if(this.items.get(a-1).selection){--a;break}let i,s;n&&(i=this.remapping(a,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(a,p+1),s=i.maps.length),s--,u.push(m);return}if(i){u.push(new Gd(m.map));let f=m.step.map(i.slice(s)),g;f&&o.maybeStep(f).doc&&(g=o.mapping.maps[o.mapping.maps.length-1],d.push(new Gd(g,void 0,void 0,d.length+u.length))),s--,g&&i.appendMap(g,s)}else o.maybeStep(m.step);if(m.selection)return l=i?m.selection.map(i.slice(s)):m.selection,c=new od(this.items.slice(0,a).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,a,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 Gd(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-a.depth;return d>Vet&&(l=$et(l,d),o-=d),new od(l.append(s),o)}remapping(e,n){let a=new dS;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?a.maps.length-i.mirrorOffset:void 0;a.appendMap(i.map,o)},e,n),a}addMaps(e){return this.eventCount==0?this:new od(this.items.append(e.map(n=>new Gd(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let a=[],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 g=s.maps[f];if(p.step){let w=e.steps[f].invert(e.docs[f]),b=p.selection&&p.selection.map(s.slice(c+1,f));b&&l++,a.push(new Gd(g,w,b))}else a.push(new Gd(g))},i);let d=[];for(let p=n;p<o;p++)d.push(new Gd(s.maps[p]));let u=this.items.slice(0,i).append(d).append(a),m=new od(u,l);return m.emptyItemCount()>qet&&(m=m.compress(this.items.length-a.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),a=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(a)),d=c&&c.getMap();if(a--,d&&n.appendMap(d,a),c){let u=o.selection&&o.selection.map(n.slice(a));u&&s++;let m=new Gd(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&&a--},this.items.length,0),new od(ps.from(i.reverse()),s)}}od.empty=new od(ps.empty,0);function $et(t,e){let n;return t.forEach((a,i)=>{if(a.selection&&e--==0)return n=i,!1}),t.slice(n)}class Gd{constructor(e,n,a,i){this.map=e,this.step=n,this.selection=a,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new Gd(n.getMap().invert(),n,this.selection)}}}class ch{constructor(e,n,a,i,s){this.done=e,this.undone=n,this.prevRanges=a,this.prevTime=i,this.prevComposition=s}}const Vet=20;function Get(t,e,n,a){let i=n.getMeta(Cg),s;if(i)return i.historyState;n.getMeta(Qet)&&(t=new ch(t.done,t.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(o&&o.getMeta(Cg))return o.getMeta(Cg).redo?new ch(t.done.addTransform(n,void 0,a,BN(e)),t.undone,UY(n.mapping.maps),t.prevTime,t.prevComposition):new ch(t.done,t.undone.addTransform(n,void 0,a,BN(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)-a.newGroupDelay||!Wet(n,t.prevRanges)),d=o?tF(t.prevRanges,n.mapping):UY(n.mapping.maps);return new ch(t.done.addTransform(n,c?e.selection.getBookmark():void 0,a,BN(e)),od.empty,d,n.time,l??t.prevComposition)}else return(s=n.getMeta("rebased"))?new ch(t.done.rebased(n,s),t.undone.rebased(n,s),tF(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new ch(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),tF(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function Wet(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((a,i)=>{for(let s=0;s<e.length;s+=2)a<=e[s+1]&&i>=e[s]&&(n=!0)}),n}function UY(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((a,i,s,o)=>e.push(s,o));return e}function tF(t,e){if(!t)return null;let n=[];for(let a=0;a<t.length;a+=2){let i=e.map(t[a],1),s=e.map(t[a+1],-1);i<=s&&n.push(i,s)}return n}function Ket(t,e,n){let a=BN(e),i=Cg.get(e).spec.config,s=(n?t.undone:t.done).popEvent(e,a);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,a),c=new ch(n?l:s.remaining,n?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(Cg,{redo:n,historyState:c})}let nF=!1,BY=null;function BN(t){let e=t.plugins;if(BY!=e){nF=!1,BY=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){nF=!0;break}}return nF}const Cg=new Wi("history"),Qet=new Wi("closeHistory");function Yet(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new Wa({key:Cg,state:{init(){return new ch(od.empty,od.empty,null,0,-1)},apply(e,n,a){return Get(n,a,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let a=n.inputType,i=a=="historyUndo"?ace:a=="historyRedo"?ice:null;return!i||!e.editable?!1:(n.preventDefault(),i(e.state,e.dispatch))}}}})}function rce(t,e){return(n,a)=>{let i=Cg.getState(n);if(!i||(t?i.undone:i.done).eventCount==0)return!1;if(a){let s=Ket(i,n,t);s&&a(e?s.scrollIntoView():s)}return!0}}const ace=rce(!1,!0),ice=rce(!0,!0);da.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 a=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(a)}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 Wa({key:new Wi("characterCount"),appendTransaction:(e,n,a)=>{if(t)return;const i=this.options.limit;if(i==null||i===0){t=!0;return}const s=this.storage.characters({node:a.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=a.tr.deleteRange(l,c);return t=!0,d}t=!0},filterTransaction:(e,n)=>{const a=this.options.limit;if(!e.docChanged||a===0||a===null||a===void 0)return!0;const i=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=a||i>a&&s>a&&s<=i)return!0;if(i>a&&s>a&&s>i||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-a,d=l-c,u=l;return e.deleteRange(d,u),!(this.storage.characters({node:e.doc})>a)}})]}});var Xet=da.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Det(this.options)]}});da.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Wa({key:new Wi("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:a}=this.editor,{anchor:i}=e,s=[];if(!n||!a)return Ba.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(vo.node(d,d+c.nodeSize,{class:this.options.className}))}),Ba.create(t,s)}}})]}});var Zet=da.create({name:"gapCursor",addProseMirrorPlugins(){return[Iet()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Yr(Dn(t,"allowGapCursor",n)))!=null?e:null}}}),HY="placeholder";function Jet(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}da.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:HY,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${Jet(this.options.dataAttribute)}`:`data-${HY}`;return[new Wa({key:new Wi("placeholder"),props:{decorations:({doc:e,selection:n})=>{const a=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:i}=n,s=[];if(!a)return null;const o=this.editor.isEmpty;return e.descendants((l,c)=>{const d=i>=c&&i<=c+l.nodeSize,u=!l.isLeaf&&KA(l);if((d||!this.options.showOnlyCurrent)&&u){const m=[this.options.emptyNodeClass];o&&m.push(this.options.emptyEditorClass);const p=vo.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}),Ba.create(e,s)}}})]}});da.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new Wa({key:new Wi("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||cle(n.selection)||t.view.dragging?null:Ba.create(n.doc,[vo.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function qY({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var ett=da.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Wi(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",a=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(n).includes(i.name));return[new Wa({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!qY({node:o,types:a})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!qY({node:o,types:a})}}})]}}),ttt=da.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>ace(t,e),redo:()=>({state:t,dispatch:e})=>ice(t,e)}},addProseMirrorPlugins(){return[Yet(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()}}}),ntt=da.create({name:"starterKit",addExtensions(){var t,e,n,a;const i=[];return this.options.bold!==!1&&i.push(NJe.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(vJe.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push($le.configure(this.options.bulletList)),this.options.code!==!1&&i.push(TJe.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(MJe.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(EJe.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(Xet.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(Zet.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(DJe.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(FJe.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(ttt.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(LJe.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(UJe.configure(this.options.italic)),this.options.listItem!==!1&&i.push(Vle.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(Xle.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&i.push(qle.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(Jle.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(Pet.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(jet.configure(this.options.strike)),this.options.text!==!1&&i.push(Met.configure(this.options.text)),this.options.underline!==!1&&i.push(ece.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&i.push(ett.configure((a=this.options)==null?void 0:a.trailingNode)),i}}),rtt=ntt,att=da.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")}}}),itt=att,stt=20,sce=(t,e=0)=>{const n=[];return!t.children.length||e>stt||Array.from(t.children).forEach(a=>{a.tagName==="SPAN"?n.push(a):a.children.length&&n.push(...sce(a,e+1))}),n},ott=t=>{if(!t.children.length)return;const e=sce(t);e&&e.forEach(n=>{var a,i;const s=n.getAttribute("style"),o=(i=(a=n.parentElement)==null?void 0:a.closest("span"))==null?void 0:i.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},oce=pf.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&ott(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",si(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,a)=>{if(n.isTextblock)return!0;n.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(s=>!!s))||t.removeMark(a,a+n.nodeSize,this.type)}),!0}}}}),ltt=da.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 a=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=a.length-1;i>=0;i-=1){const s=a[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()}}}),lce=da.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 a=n.split(";").map(i=>i.trim()).filter(Boolean);for(let i=a.length-1;i>=0;i-=1){const s=a[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()}}}),ctt=da.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()}}}),dtt=da.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()}}}),utt=da.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()}}});da.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(ltt.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(lce.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(ctt.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(dtt.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(utt.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(oce.configure(this.options.textStyle)),t}});var mtt=lce,ptt=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,htt=el.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",si(this.options.HTMLAttributes,t)]},parseMarkdown:(t,e)=>e.createNode("image",{src:t.href,title:t.title,alt:t.text}),renderMarkdown:t=>{var e,n,a,i,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(i=(a=t.attrs)==null?void 0:a.alt)!=null?i:"",d=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return d?`![${c}](${l} "${d}")`:`![${c}](${l})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u")return null;const{directions:t,minWidth:e,minHeight:n,alwaysPreserveAspectRatio:a}=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 dZe({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:a===!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[Cle({find:ptt,type:this.type,getAttributes:t=>{const[,,e,n,a]=t;return{src:n,alt:e,title:a}}})]}}),ftt=htt;function $I({content:t,onChange:e,placeholder:n}){const{t:a}=_t(),i=fJe({extensions:[rtt.configure({heading:!1,codeBlock:!1,code:!1}),Eet,met.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),itt.configure({types:["paragraph"]}),oce,mtt,ftt.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})=>r.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 r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[r.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[r.jsx(s,{onClick:()=>i.chain().focus().toggleBold().run(),isActive:i.isActive("bold"),title:a("richTextEditor.bold"),children:r.jsx(Ofe,{className:"w-4 h-4"})}),r.jsx(s,{onClick:()=>i.chain().focus().toggleItalic().run(),isActive:i.isActive("italic"),title:a("richTextEditor.italic"),children:r.jsx(cxe,{className:"w-4 h-4"})}),r.jsx(s,{onClick:()=>i.chain().focus().toggleUnderline().run(),isActive:i.isActive("underline"),title:a("richTextEditor.underline"),children:r.jsx(gve,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),r.jsx(s,{onClick:()=>i.chain().focus().toggleBulletList().run(),isActive:i.isActive("bulletList"),title:a("richTextEditor.bulletList"),children:r.jsx(MS,{className:"w-4 h-4"})}),r.jsx(s,{onClick:()=>i.chain().focus().toggleOrderedList().run(),isActive:i.isActive("orderedList"),title:a("richTextEditor.numberedList"),children:r.jsx(Ew,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),r.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("left").run(),isActive:i.isActive({textAlign:"left"}),title:a("richTextEditor.alignLeft"),children:r.jsx(lve,{className:"w-4 h-4"})}),r.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("center").run(),isActive:i.isActive({textAlign:"center"}),title:a("richTextEditor.alignCenter"),children:r.jsx(ave,{className:"w-4 h-4"})}),r.jsx(s,{onClick:()=>i.chain().focus().setTextAlign("right").run(),isActive:i.isActive({textAlign:"right"}),title:a("richTextEditor.alignRight"),children:r.jsx(sve,{className:"w-4 h-4"})}),r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),r.jsx(s,{onClick:o,isActive:i.isActive("link"),title:a("richTextEditor.addLink"),children:r.jsx(Qy,{className:"w-4 h-4"})}),i.isActive("link")&&r.jsx(s,{onClick:()=>i.chain().focus().unsetLink().run(),title:a("richTextEditor.removeLink"),children:r.jsx(ou,{className:"w-4 h-4"})})]}),r.jsx(Ale,{editor:i})]})}function cce({archiveId:t,archiveName:e,onClose:n}){const a=tn(),[i,s]=y.useState(!1),[o,l]=y.useState(null),[c,d]=y.useState({}),{data:u,isLoading:m,error:p}=Xe({queryKey:["archive-project-page",t],queryFn:()=>ae.getArchiveProjectPage(t)}),f=lt({mutationFn:P=>ae.updateArchiveProjectPage(t,P),onSuccess:()=>{a.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),d({})}});y.useEffect(()=>{const P=T=>{T.key==="Escape"&&(o!==null?l(null):i?x():n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[o,i,n]);const g=[...u?.model_pictures||[],...u?.profile_pictures||[]],w=()=>{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)},b=()=>{f.mutate(c)},x=()=>{s(!1),d({})},S=P=>h5.sanitize(P,{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"]}),k=u&&(u.title||u.description||u.designer||u.profile_title||g.length>0),C=P=>{P.target===P.currentTarget&&n()};return r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:C,children:[r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Rs,{className:"w-5 h-5 text-bambu-green"}),r.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&r.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[!i&&k&&r.jsxs(je,{variant:"ghost",size:"sm",onClick:w,children:[r.jsx(jg,{className:"w-4 h-4 mr-1"}),"Edit"]}),i&&r.jsxs(r.Fragment,{children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:x,children:"Cancel"}),r.jsxs(je,{variant:"primary",size:"sm",onClick:b,disabled:f.isPending,children:[r.jsx(ds,{className:"w-4 h-4 mr-1"}),"Save"]})]}),r.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[m&&r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),p&&r.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),u&&!k&&r.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[r.jsx(Rs,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),r.jsx("p",{children:"No project page data found in this 3MF file."}),r.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),u&&k&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{className:"space-y-4",children:[i?r.jsx("input",{type:"text",value:c.title||"",onChange:P=>d({...c,title:P.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&&r.jsx("h3",{className:"text-xl font-semibold text-white",children:u.title}),r.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[i?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Gm,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c.designer||"",onChange:P=>d({...c,designer:P.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.designer&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx(Gm,{className:"w-4 h-4"}),r.jsx("span",{children:u.designer}),u.designer_user_id&&r.jsx("a",{href:`https://makerworld.com/en/@${u.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:r.jsx(zr,{className:"w-3 h-3"})})]}),u.creation_date&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx(wa,{className:"w-4 h-4"}),r.jsx("span",{children:u.creation_date})]}),i?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Rs,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c.license||"",onChange:P=>d({...c,license:P.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):u.license&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx(Rs,{className:"w-4 h-4"}),r.jsx("span",{children:u.license})]}),u.origin&&r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:u.origin})]})]}),(u.description||i)&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),i?r.jsx($I,{content:c.description||"",onChange:P=>d({...c,description:P}),placeholder:"Enter description..."}):r.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(u.description||"")}})]}),(u.profile_title||u.profile_description||i)&&r.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),i?r.jsxs("div",{className:"space-y-2",children:[r.jsx("input",{type:"text",value:c.profile_title||"",onChange:P=>d({...c,profile_title:P.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),r.jsx($I,{content:c.profile_description||"",onChange:P=>d({...c,profile_description:P}),placeholder:"Profile description..."})]}):r.jsxs(r.Fragment,{children:[u.profile_title&&r.jsx("p",{className:"text-white font-medium",children:u.profile_title}),u.profile_description&&r.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:S(u.profile_description)}}),u.profile_user_name&&r.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",u.profile_user_name]})]})]}),g.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[r.jsx(mu,{className:"w-4 h-4"}),"Images (",g.length,")"]}),r.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:g.map((P,T)=>r.jsx("button",{onClick:()=>l(T),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:r.jsx("img",{src:P.url,alt:P.name,className:"w-full h-full object-cover"})},P.path))})]}),u.design_model_id&&r.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:r.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:[r.jsx(zr,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&g[o]&&r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[r.jsx("button",{onClick:P=>{P.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:r.jsx(Xo,{className:"w-6 h-6 text-white"})}),r.jsx("img",{src:g[o].url,alt:g[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:P=>P.stopPropagation()}),r.jsx("button",{onClick:P=>{P.stopPropagation(),l(Math.min(g.length-1,o+1))},disabled:o===g.length-1,className:"absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:r.jsx(qa,{className:"w-6 h-6 text-white"})}),r.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:r.jsx(Vt,{className:"w-6 h-6 text-white"})}),r.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",g.length]})]})]})}const gtt=[.25,.5,.75,1,1.5,2,3,4];function btt({archiveId:t,timelapseSrc:e,onClose:n,onSave:a}){const{showToast:i}=on(),s=y.useRef(null),o=y.useRef(null),[l,c]=y.useState(!1),[d,u]=y.useState(0),[m,p]=y.useState(0),[f,g]=y.useState(0),[w,b]=y.useState(0),[x,S]=y.useState(1),[k,C]=y.useState(null),[P,T]=y.useState(null),[A,F]=y.useState(.8),[_,M]=y.useState(!1),{data:H,isLoading:I}=Xe({queryKey:["timelapse-info",t],queryFn:()=>ae.getTimelapseInfo(t)}),{data:z}=Xe({queryKey:["timelapse-thumbnails",t],queryFn:()=>ae.getTimelapseThumbnails(t,15)}),L=lt({mutationFn:()=>ae.processTimelapse(t,{trimStart:f,trimEnd:w,speed:x,saveMode:"replace"},k||void 0),onSuccess:Q=>{i(Q.message,"success"),a?.(),n()},onError:Q=>{i(Q.message||"Processing failed","error")}});y.useEffect(()=>{H?.duration&&w===0&&b(H.duration)},[H?.duration,w]),y.useEffect(()=>{const Q=le=>{le.key==="Escape"&&n()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[n]),y.useEffect(()=>{const Q=s.current;if(!Q)return;const le=()=>{const $=Q.currentTime;u($),$>=w&&(Q.currentTime=f)},pe=()=>{p(Q.duration),w===0&&b(Q.duration)},he=()=>c(!0),we=()=>c(!1);return Q.addEventListener("timeupdate",le),Q.addEventListener("durationchange",pe),Q.addEventListener("play",he),Q.addEventListener("pause",we),()=>{Q.removeEventListener("timeupdate",le),Q.removeEventListener("durationchange",pe),Q.removeEventListener("play",he),Q.removeEventListener("pause",we)}},[f,w]),y.useEffect(()=>{const Q=o.current,le=s.current;!Q||!le||!P||(Q.currentTime=le.currentTime,Q.playbackRate=le.playbackRate,l&&!_?Q.play().catch(()=>{}):Q.pause())},[l,P,_]),y.useEffect(()=>{o.current&&(o.current.volume=_?0:A)},[A,_]),y.useEffect(()=>{s.current&&(s.current.playbackRate=x),o.current&&(o.current.playbackRate=x)},[x]);const Z=y.useCallback(()=>{const Q=s.current;Q&&(l?Q.pause():(Q.currentTime<f&&(Q.currentTime=f),Q.play()))},[l,f]),ne=Q=>{const le=s.current;le&&(le.currentTime=Math.max(f,Math.min(w,Q)))},Y=Q=>{const le=Q.target.files?.[0];le&&(P&&URL.revokeObjectURL(P),C(le),T(URL.createObjectURL(le)))},ce=()=>{P&&URL.revokeObjectURL(P),C(null),T(null)};y.useEffect(()=>()=>{P&&URL.revokeObjectURL(P)},[P]);const ue=w-f,oe=ue/x;return I?r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:r.jsxs("div",{className:"flex items-center gap-3 text-white",children:[r.jsx(ft,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(je,{variant:"primary",size:"sm",onClick:()=>L.mutate(),disabled:L.isPending,children:L.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx(ds,{className:"w-4 h-4"}),"Save"]})}),r.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[r.jsxs("div",{className:"relative",children:[r.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:Z,muted:!!P}),!l&&r.jsx("button",{onClick:Z,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:r.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:r.jsx(hs,{className:"w-8 h-8 text-white"})})}),P&&r.jsx("audio",{ref:o,src:P,loop:!0})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(vye,{className:"w-4 h-4"}),r.jsx("span",{children:"Trim"}),r.jsxs("span",{className:"ml-auto",children:[nh(f)," - ",nh(w)," (",nh(ue),")"]})]}),r.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[r.jsx("div",{className:"absolute inset-0 flex",children:z?.thumbnails.map((Q,le)=>r.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${Q})`}},le))}),r.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${f/m*100}%`}}),r.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(m-w)/m*100}%`}}),r.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${f/m*100}%`,right:`${(m-w)/m*100}%`}}),r.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${d/m*100}%`}}),r.jsx("input",{type:"range",min:0,max:m,step:.1,value:f,onChange:Q=>{const le=parseFloat(Q.target.value);le<w-1&&(g(le),s.current&&s.current.currentTime<le&&(s.current.currentTime=le))},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 50% 0 0)"}}),r.jsx("input",{type:"range",min:0,max:m,step:.1,value:w,onChange:Q=>{const le=parseFloat(Q.target.value);le>f+1&&b(le)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),r.jsx("input",{type:"range",min:0,max:m,step:.1,value:d,onChange:Q=>ne(parseFloat(Q.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8303. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8304. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8305. [&::-webkit-slider-thumb]:cursor-pointer`}),r.jsx("div",{className:"flex items-center justify-center gap-2",children:r.jsx("button",{onClick:Z,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?r.jsx(DS,{className:"w-5 h-5 text-white"}):r.jsx(hs,{className:"w-5 h-5 text-white"})})})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(TS,{className:"w-4 h-4"}),r.jsx("span",{children:"Speed"}),r.jsxs("span",{className:"ml-auto",children:[x,"x (output: ",nh(oe),")"]})]}),r.jsx("div",{className:"flex gap-1",children:gtt.map(Q=>r.jsxs("button",{onClick:()=>S(Q),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${x===Q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[Q,"x"]},Q))})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(KF,{className:"w-4 h-4"}),r.jsx("span",{children:"Music Overlay"})]}),k?r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(KF,{className:"w-5 h-5 text-bambu-green"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:k.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(k.size/1024/1024).toFixed(1)," MB"]})]}),r.jsx("button",{onClick:()=>M(!_),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:_?r.jsx(Nve,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(_ve,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("input",{type:"range",min:0,max:1,step:.1,value:A,onChange:Q=>F(parseFloat(Q.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8306. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8307. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),r.jsx("button",{onClick:ce,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:r.jsx(en,{className:"w-4 h-4 text-red-400"})})]}):r.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:[r.jsx(_a,{className:"w-8 h-8 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),r.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),r.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:Y,className:"hidden"})]})]}),r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[r.jsxs("p",{className:"text-bambu-gray",children:[r.jsx("span",{className:"text-white",children:"Original:"})," ",nh(m)," @ ",H?.width,"x",H?.height]}),r.jsxs("p",{className:"text-bambu-gray",children:[r.jsx("span",{className:"text-white",children:"Output:"})," ",nh(oe)," @ ",x,"x speed",k&&" + music overlay"]})]})]}),L.isPending&&r.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[r.jsx(ft,{className:"w-12 h-12 text-bambu-green animate-spin"}),r.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),r.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const xtt=[.25,.5,.75,1,1.5,2,3,4];function dce({src:t,title:e,downloadFilename:n,archiveId:a,onClose:i,onEdit:s}){const o=y.useRef(null),[l,c]=y.useState(!0),[d,u]=y.useState(1),[m,p]=y.useState(0),[f,g]=y.useState(0),[w,b]=y.useState(!1);y.useEffect(()=>{const T=o.current;T&&(T.playbackRate=d)},[d]),y.useEffect(()=>{const T=A=>{A.key==="Escape"&&i()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[i]),y.useEffect(()=>{const T=o.current;if(!T)return;const A=()=>p(T.currentTime),F=()=>g(T.duration),_=()=>c(!0),M=()=>c(!1);return T.addEventListener("timeupdate",A),T.addEventListener("durationchange",F),T.addEventListener("play",_),T.addEventListener("pause",M),()=>{T.removeEventListener("timeupdate",A),T.removeEventListener("durationchange",F),T.removeEventListener("play",_),T.removeEventListener("pause",M)}},[]);const x=()=>{const T=o.current;T&&(l?T.pause():T.play())},S=T=>{const A=o.current;A&&(A.currentTime=parseFloat(T.target.value))},k=()=>{const T=o.current;T&&(T.currentTime=Math.max(0,T.currentTime-5))},C=()=>{const T=o.current;T&&(T.currentTime=Math.min(f,T.currentTime+5))},P=()=>{const T=document.createElement("a");T.href=t,T.download=n,T.click()};return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[r.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),e]}),r.jsxs("div",{className:"flex items-center gap-2",children:[a&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>b(!0),children:[r.jsx(mi,{className:"w-4 h-4"}),"Edit"]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:P,children:[r.jsx(Zr,{className:"w-4 h-4"}),"Download"]}),r.jsx("button",{onClick:i,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),r.jsxs("div",{className:"p-4",children:[r.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:x}),r.jsxs("div",{className:"mt-4 space-y-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:nh(m)}),r.jsx("input",{type:"range",min:0,max:f||100,value:m,onChange:S,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8308. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8309. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8310. [&::-webkit-slider-thumb]:cursor-pointer`}),r.jsx("span",{className:"text-xs text-bambu-gray w-12",children:nh(f)})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{onClick:k,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:r.jsx(Fye,{className:"w-5 h-5 text-bambu-gray"})}),r.jsx("button",{onClick:x,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?r.jsx(DS,{className:"w-5 h-5 text-white"}):r.jsx(hs,{className:"w-5 h-5 text-white"})}),r.jsx("button",{onClick:C,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:r.jsx(PT,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),r.jsx("div",{className:"flex gap-1",children:xtt.map(T=>r.jsxs("button",{onClick:()=>u(T),className:`px-2 py-1 text-xs rounded transition-colors ${d===T?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[T,"x"]},T))})]})]})]})]})]}),w&&a&&r.jsx(btt,{archiveId:a,timelapseSrc:t,onClose:()=>b(!1),onSave:s})]})}function ytt({archiveIds:t,onClose:e}){y.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:a,error:i}=Xe({queryKey:["archive-comparison",t],queryFn:()=>ae.compareArchives(t)});return r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:a?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i?r.jsxs("div",{className:"text-center py-12 text-red-400",children:[r.jsx(Nn,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),r.jsx("p",{children:"Failed to load comparison"}),r.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:i instanceof Error?i.message:"Unknown error"})]}):n?r.jsx(vtt,{comparison:n}):null}),r.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:r.jsx(je,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function vtt({comparison:t}){return r.jsxs("div",{className:"space-y-6",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.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=>r.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[r.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),r.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))]})}),r.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>r.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[r.jsx("td",{className:"py-2 pr-4 text-sm",children:r.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&r.jsx(Nn,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),r.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,a)=>r.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??r.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&r.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},a))]},e.field))})]})}),t.differences.length>0&&r.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[r.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[r.jsx(Nn,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),r.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>r.jsxs("li",{children:[r.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&r.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[r.jsx(Ar,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[r.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),r.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?r.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>r.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[r.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",r.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):r.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:r.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function wtt(t){const e=new Date(t),a=new Date().getTime()-e.getTime(),i=Math.floor(a/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 Stt({upload:t,projects:e,onArchive:n,onDiscard:a,isArchiving:i,isDiscarding:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(t.tags||""),[u,m]=y.useState(t.notes||""),[p,f]=y.useState(t.project_id),[g,w]=y.useState(!1);return r.jsx(At,{children:r.jsxs(Et,{className:"py-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Ph,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",title:t.filename,children:t.display_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[r.jsx("span",{children:ls(t.file_size)}),r.jsx("span",{children:"·"}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),wtt(t.uploaded_at)]}),t.source_ip&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"·"}),r.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?r.jsx(Zo,{className:"w-5 h-5"}):r.jsx(Ln,{className:"w-5 h-5"})}),r.jsx(je,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:u,project_id:p||void 0}),disabled:i,children:i?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsxs(r.Fragment,{children:[r.jsx(eo,{className:"w-4 h-4"}),"Archive"]})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>w(!0),disabled:s,children:s?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4 text-red-400"})})]})]}),g&&r.jsx(wn,{title:"Discard Upload",message:`Are you sure you want to discard "${t.filename}"? This cannot be undone.`,confirmText:"Discard",variant:"danger",onConfirm:()=>{a(t.id),w(!1)},onCancel:()=>w(!1)}),o&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),r.jsx("input",{type:"text",value:c,onChange:b=>d(b.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),r.jsx("textarea",{value:u,onChange:b=>m(b.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),r.jsxs("select",{value:p||"",onChange:b=>f(b.target.value?Number(b.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:[r.jsx("option",{value:"",children:"No project"}),e.map(b=>r.jsx("option",{value:b.id,children:b.name},b.id))]})]})]})]})})}function _tt(){const t=tn(),{showToast:e}=on(),[n,a]=y.useState(!1),[i,s]=y.useState(!1),[o,l]=y.useState(new Set),[c,d]=y.useState(new Set),{data:u,isLoading:m}=Xe({queryKey:["pending-uploads"],queryFn:Ox.list,refetchInterval:1e4}),{data:p}=Xe({queryKey:["projects"],queryFn:()=>ae.getProjects(),select:x=>[...x].sort((S,k)=>S.name.localeCompare(k.name))}),f=lt({mutationFn:({id:x,data:S})=>Ox.archive(x,S),onMutate:({id:x})=>{l(S=>new Set(S).add(x))},onSettled:(x,S,{id:k})=>{l(C=>{const P=new Set(C);return P.delete(k),P})},onSuccess:x=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${x.print_name}`)},onError:x=>{e(x.message||"Failed to archive","error")}}),g=lt({mutationFn:x=>Ox.discard(x),onMutate:x=>{d(S=>new Set(S).add(x))},onSettled:(x,S,k)=>{d(C=>{const P=new Set(C);return P.delete(k),P})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:x=>{e(x.message||"Failed to discard","error")}}),w=lt({mutationFn:Ox.archiveAll,onSuccess:x=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${x.archived} files${x.failed>0?`, ${x.failed} failed`:""}`)},onError:x=>{e(x.message||"Failed to archive all","error")}}),b=lt({mutationFn:Ox.discardAll,onSuccess:x=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${x.discarded} files`)},onError:x=>{e(x.message||"Failed to discard all","error")}});return m?r.jsx(At,{children:r.jsx(Et,{className:"py-8 flex justify-center",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!u||u.length===0?null:r.jsxs("div",{className:"mb-6",children:[r.jsxs(At,{className:"border-l-4 border-l-yellow-500",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(_a,{className:"w-5 h-5 text-yellow-500"}),r.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",u.length,")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(je,{variant:"primary",size:"sm",onClick:()=>a(!0),disabled:w.isPending,children:w.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsxs(r.Fragment,{children:[r.jsx(eo,{className:"w-4 h-4"}),"Archive All"]})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:b.isPending,children:b.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsxs(r.Fragment,{children:[r.jsx(en,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),r.jsxs(Et,{children:[r.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."}),r.jsx("div",{className:"space-y-3",children:u.map(x=>r.jsx(Stt,{upload:x,projects:p||[],onArchive:(S,k)=>f.mutate({id:S,data:k}),onDiscard:S=>g.mutate(S),isArchiving:o.has(x.id),isDiscarding:c.has(x.id)},x.id))})]})]}),n&&r.jsx(wn,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${u.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{w.mutate(),a(!1)},onCancel:()=>a(!1)}),i&&r.jsx(wn,{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:()=>{b.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function ktt({onClose:t}){const e=tn(),{showToast:n}=on(),[a,i]=y.useState(""),[s,o]=y.useState(null),[l,c]=y.useState(""),[d,u]=y.useState(null),[m,p]=y.useState("count");y.useEffect(()=>{const _=M=>{M.key==="Escape"&&(s?o(null):d?u(null):t())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[t,s,d]);const{data:f,isLoading:g}=Xe({queryKey:["tags"],queryFn:ae.getTags}),w=lt({mutationFn:({oldName:_,newName:M})=>ae.renameTag(_,M),onSuccess:(_,{oldName:M,newName:H})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${M}" to "${H}" in ${_.affected} archive${_.affected!==1?"s":""}`),o(null)},onError:_=>{n(_.message||"Failed to rename tag","error")}}),b=lt({mutationFn:_=>ae.deleteTag(_),onSuccess:(_,M)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${M}" from ${_.affected} archive${_.affected!==1?"s":""}`),u(null)},onError:_=>{n(_.message||"Failed to delete tag","error")}}),x=_=>{o(_.name),c(_.name),u(null)},S=()=>{o(null),c("")},k=()=>{if(!s||!l.trim())return;const _=l.trim();if(_===s){S();return}w.mutate({oldName:s,newName:_})},C=_=>{_.key==="Enter"?(_.preventDefault(),k()):_.key==="Escape"&&(_.preventDefault(),S())},P=_=>{u(_),o(null)},T=()=>{d&&b.mutate(d)},A=f?.filter(_=>_.name.toLowerCase().includes(a.toLowerCase())).sort((_,M)=>m==="count"&&M.count-_.count||_.name.localeCompare(M.name)),F=f?.reduce((_,M)=>_+M.count,0)||0;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:r.jsxs(Et,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Vm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.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:a,onChange:_=>i(_.target.value)})]}),r.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:_=>p(_.target.value),children:[r.jsx("option",{value:"count",children:"Sort by Count"}),r.jsx("option",{value:"name",children:"Sort by Name"})]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[f.length," tag",f.length!==1?"s":""," across ",F," usage",F!==1?"s":""]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:g?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):A?.length?r.jsx("div",{className:"space-y-2",children:A.map(_=>r.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===_.name?r.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[r.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:M=>c(M.target.value),onKeyDown:C,autoFocus:!0}),r.jsx(je,{size:"sm",variant:"primary",onClick:k,disabled:!l.trim()||w.isPending,className:"p-1.5",children:w.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Ar,{className:"w-4 h-4"})}),r.jsx(je,{size:"sm",variant:"ghost",onClick:S,className:"p-1.5",children:r.jsx(Vt,{className:"w-4 h-4"})})]}):d===_.name?r.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),r.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',_.name,'" from ',_.count," archive",_.count!==1?"s":"","?"]}),r.jsx(je,{size:"sm",variant:"danger",onClick:T,disabled:b.isPending,className:"p-1.5",children:b.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"})}),r.jsx(je,{size:"sm",variant:"ghost",onClick:()=>u(null),className:"p-1.5",children:r.jsx(Vt,{className:"w-4 h-4"})})]}):r.jsxs(r.Fragment,{children:[r.jsx(Vm,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-white flex-1 truncate",children:_.name}),r.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:_.count}),r.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[r.jsx("button",{onClick:()=>x(_),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>P(_.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:r.jsx(en,{className:"w-4 h-4"})})]})]})},_.name))}):r.jsx("div",{className:"text-center py-8 text-bambu-gray",children:a?"No tags match your search":"No tags found"})}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function fh(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)}async function gh(t,e,n,a){try{if(n==="source"){const{token:i}=await ae.createSourceSlicerToken(t),s=ae.getSourceSlicerDownloadUrl(t,i,e);jm(`${window.location.origin}${s}`,a)}else{const{token:i}=await ae.createArchiveSlicerToken(t),s=ae.getArchiveSlicerDownloadUrl(t,i,e);jm(`${window.location.origin}${s}`,a)}}catch{const i=n==="source"?ae.getSource3mfForSlicer(t,e):ae.getArchiveForSlicer(t,e);jm(`${window.location.origin}${i}`,a)}}function Ntt({archive:t,printerName:e,isSelected:n,onSelect:a,selectionMode:i,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",useSlicerApi:d=!1,currency:u,t:m,onNavigateToArchive:p}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const f=tn(),{showToast:g}=on(),{hasPermission:w,canModify:b}=dr(),x=cse(),S=ji(),[k,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState(!1),[z,L]=y.useState(!1),[Z,ne]=y.useState(!1),[Y,ce]=y.useState(!1),[ue,oe]=y.useState([]),[Q,le]=y.useState(!1),[pe,he]=y.useState(!1),[we,$]=y.useState(!1),[J,j]=y.useState(!1),[E,B]=y.useState(!1),[W,O]=y.useState(!1),[ie,U]=y.useState(!1),[G,K]=y.useState(null),[X,se]=y.useState(null),[te,fe]=y.useState(!1),[de,me]=y.useState(null),q=y.useRef(null),R=y.useRef(null),re=y.useRef(null),{data:be}=Xe({queryKey:["archive-plates",t.id],queryFn:()=>ae.getArchivePlates(t.id),enabled:te,staleTime:300*1e3}),ye=t.duplicate_sequence??0,_e=t.original_archive_id??null,xe=be?.plates??[],ge=be?.is_multi_plate??!1,Me=X??0,Be=async()=>{try{const Te=await ae.getArchivePlates(t.id);if(Te.has_gcode===!1){g(m("archives.platePicker.noGcode"),"info");return}if(Te.is_multi_plate&&Te.plates.length>1){me(Te.plates);return}}catch{}S(`/gcode-viewer?archive=${t.id}`)},Fe=lt({mutationFn:()=>ae.deleteArchiveTimelapse(t.id),onSuccess:()=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.timelapseRemoved"))},onError:Te=>{g(Te.message||m("archives.toast.failedRemoveTimelapse"),"error")}}),Oe=lt({mutationFn:Te=>ae.uploadArchiveTimelapse(t.id,Te),onSuccess:Te=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.timelapseUploaded",{filename:Te.filename}))},onError:Te=>{g(Te.message||m("archives.toast.failedUploadTimelapse"),"error")}}),Re=lt({mutationFn:Te=>ae.uploadSource3mf(t.id,Te),onSuccess:Te=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.source3mfAttached",{filename:Te.filename}))},onError:Te=>{g(Te.message||m("archives.toast.failedUploadSource3mf"),"error")}}),We=lt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.source3mfRemoved"))},onError:Te=>{g(Te.message||m("archives.toast.failedRemoveSource3mf"),"error")}}),ze=lt({mutationFn:Te=>ae.uploadF3d(t.id,Te),onSuccess:Te=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.f3dAttached",{filename:Te.filename}))},onError:Te=>{g(Te.message||m("archives.toast.failedUploadF3d"),"error")}}),st=lt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.f3dRemoved"))},onError:Te=>{g(Te.message||m("archives.toast.failedRemoveF3d"),"error")}}),Ee=lt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:Te=>{Te.status==="attached"?(f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.timelapseAttached",{filename:Te.filename}))):Te.status==="exists"?g(m("archives.toast.timelapseAlreadyAttached")):Te.status==="not_found"&&Te.available_files&&Te.available_files.length>0?(oe(Te.available_files),ce(!0)):g(Te.message||m("archives.toast.noMatchingTimelapse"),"warning")},onError:Te=>{g(Te.message||m("archives.toast.failedScanTimelapse"),"error")}}),it=lt({mutationFn:Te=>ae.selectArchiveTimelapse(t.id,Te),onSuccess:Te=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.timelapseAttached",{filename:Te.filename})),ce(!1),oe([])},onError:Te=>{g(Te.message||m("archives.toast.failedAttachTimelapse"),"error")}}),Ce=lt({mutationFn:Te=>ae.deleteArchive(t.id,Te),onSuccess:()=>{f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.archiveDeleted"))},onError:()=>{g(m("archives.toast.failedDeleteArchive"),"error")}}),Ze=lt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:Te=>{f.invalidateQueries({queryKey:["archives"]}),g(Te.is_favorite?m("archives.toast.addedToFavorites"):m("archives.toast.removedFromFavorites"))}}),{data:Ie}=Xe({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),ke=lt({mutationFn:Te=>ae.updateArchive(t.id,{project_id:Te}),onSuccess:()=>{f.invalidateQueries({queryKey:["archives"]}),f.invalidateQueries({queryKey:["projects"]}),g(m("archives.toast.projectUpdated"))},onError:()=>{g(m("archives.toast.failedUpdateProject"),"error")}}),Ve=Te=>{Te.preventDefault(),K({x:Te.clientX,y:Te.clientY})},Qe=[...fh(t)?[{label:m("archives.menu.print"),icon:r.jsx(hr,{className:"w-4 h-4"}),onClick:()=>C(!0),disabled:!t.file_path||!b("archives","reprint",t.created_by_id),title:t.file_path?b("archives","reprint",t.created_by_id)?void 0:m("archives.permission.noReprint"):m("archives.card.noFileForReprint")},{label:m("archives.menu.schedule"),icon:r.jsx(wa,{className:"w-4 h-4"}),onClick:()=>j(!0),disabled:!t.file_path||!w("queue:create"),title:t.file_path?w("queue:create")?void 0:m("archives.permission.noAddToQueue"):m("archives.card.noFileForReprint")},{label:m("archives.menu.openInBambuStudio"),icon:r.jsx(zr,{className:"w-4 h-4"}),onClick:()=>{const Te=t.print_name||t.filename||"model";gh(t.id,Te,"file",c)},disabled:!t.file_path,title:t.file_path?void 0:m("archives.card.noFileForReprint")}]:[{label:m("archives.menu.slice"),icon:d?r.jsx(uu,{className:"w-4 h-4"}):r.jsx(zr,{className:"w-4 h-4"}),onClick:()=>{if(d)T(!0);else{const Te=t.print_name||t.filename||"model";gh(t.id,Te,"file",c)}}}],{label:t.external_url?m("archives.menu.externalLink"):m("archives.menu.viewOnMakerWorld"),icon:r.jsx(Js,{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:m("archives.menu.preview3d"),icon:r.jsx(Si,{className:"w-4 h-4"}),onClick:()=>{Be()}},{label:m("archives.menu.viewTimelapse"),icon:r.jsx(Th,{className:"w-4 h-4"}),onClick:()=>ne(!0),disabled:!t.timelapse_path},{label:m("archives.menu.scanForTimelapse"),icon:r.jsx(iC,{className:"w-4 h-4"}),onClick:()=>Ee.mutate(),disabled:!t.printer_id||!!t.timelapse_path||Ee.isPending||!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},{label:m("archives.menu.uploadTimelapse"),icon:r.jsx(_a,{className:"w-4 h-4"}),onClick:()=>re.current?.click(),disabled:!!t.timelapse_path||!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:m("archives.menu.removeTimelapse"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>U(!0),danger:!0,disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?m("archives.menu.downloadSource3mf"):m("archives.menu.uploadSource3mf"),icon:r.jsx(eC,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(Te=>{console.error("Source 3MF download failed:",Te)}):q.current?.click()},disabled:!t.source_3mf_path&&!b("archives","update",t.created_by_id),title:!t.source_3mf_path&&!b("archives","update",t.created_by_id)?m("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:m("archives.menu.replaceSource3mf"),icon:r.jsx(_a,{className:"w-4 h-4"}),onClick:()=>q.current?.click(),disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},{label:m("archives.menu.removeSource3mf"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>B(!0),danger:!0,disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?m("archives.menu.replaceF3d"):m("archives.menu.uploadF3d"),icon:r.jsx(Si,{className:"w-4 h-4"}),onClick:()=>R.current?.click(),disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:m("archives.menu.downloadF3d"),icon:r.jsx(Zr,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(Te=>{console.error("F3D download failed:",Te)})}},{label:m("archives.menu.removeF3d"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>O(!0),danger:!0,disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:m("archives.menu.download"),icon:r.jsx(Zr,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(Te=>{console.error("Archive download failed:",Te)})},disabled:!w("archives:read"),title:w("archives:read")?void 0:m("archives.permission.noDownload")},{label:m("archives.menu.copyDownloadLink"),icon:r.jsx(Ti,{className:"w-4 h-4"}),onClick:()=>{const Te=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(Te).then(()=>{g(m("archives.toast.linkCopied"))}).catch(()=>{g(m("archives.toast.failedCopyLink"),"error")})},disabled:!w("archives:read"),title:w("archives:read")?void 0:m("archives.permission.noCopyLink")},{label:m("archives.menu.qrCode"),icon:r.jsx(HZ,{className:"w-4 h-4"}),onClick:()=>le(!0)},{label:t.photos?.length?m("archives.menu.viewPhotosCount",{count:t.photos.length}):m("archives.menu.viewPhotos"),icon:r.jsx(by,{className:"w-4 h-4"}),onClick:()=>he(!0),disabled:!t.photos?.length},{label:m("archives.menu.projectPage"),icon:r.jsx(Rs,{className:"w-4 h-4"}),onClick:()=>$(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?m("archives.menu.removeFromFavorites"):m("archives.menu.addToFavorites"),icon:r.jsx(Eg,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Ze.mutate(),disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},{label:m("archives.menu.edit"),icon:r.jsx(mi,{className:"w-4 h-4"}),onClick:()=>I(!0),disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives")},{label:m("archives.menu.printLog"),icon:r.jsx(Vh,{className:"w-4 h-4"}),onClick:()=>L(!0)},...t.project_id&&t.project_name?[{label:m("archives.menu.goToProject",{name:t.project_name}),icon:r.jsx(to,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:m("archives.menu.addToProject"),icon:r.jsx(to,{className:"w-4 h-4"}),onClick:()=>{},disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?void 0:m("archives.permission.noUpdateArchives"),submenuSearchPlaceholder:(s?.filter(Te=>Te.status==="active").length??0)>5?m("archives.menu.searchProjects"):void 0,submenu:(()=>{const Te=[];if(t.project_id&&Te.push({label:m("archives.menu.removeFromProject"),icon:r.jsx(Vt,{className:"w-4 h-4"}),onClick:()=>ke.mutate(null),disabled:!b("archives","update",t.created_by_id)}),!s)Te.push({label:m("archives.menu.loading"),icon:r.jsx(ft,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const tt=s.filter(ot=>ot.status==="active").sort((ot,Tt)=>ot.name.localeCompare(Tt.name));tt.length===0?Te.push({label:m("archives.menu.noProjectsAvailable"),icon:r.jsx(to,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):tt.forEach(ot=>{Te.push({label:ot.name,icon:r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:ot.color||"#888"}}),onClick:()=>ke.mutate(ot.id),disabled:t.project_id===ot.id||!b("archives","update",t.created_by_id)})})}return Te})()},{label:m(n?"archives.menu.deselect":"archives.menu.select"),icon:n?r.jsx(gs,{className:"w-4 h-4"}):r.jsx(ro,{className:"w-4 h-4"}),onClick:()=>a(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:m("archives.menu.delete"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>F(!0),danger:!0,disabled:!b("archives","delete",t.created_by_id),title:b("archives","delete",t.created_by_id)?void 0:m("archives.permission.noDelete")}];return r.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:Ve,onClick:i?()=>a(t.id):void 0,children:[i&&r.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(),a(t.id)},children:n?r.jsx(gs,{className:"w-5 h-5 text-bambu-green"}):r.jsx(ro,{className:"w-5 h-5 text-white"})}),r.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>fe(!0),onMouseLeave:()=>fe(!1),children:[t.thumbnail_path?r.jsx("img",{src:X!==null&&xe.length>0?ae.getArchivePlateThumbnail(t.id,xe[Me]?.index??0):ae.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(mu,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),ge&&xe.length>1&&r.jsxs(r.Fragment,{children:[r.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 ${x?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:Te=>{Te.stopPropagation(),se(tt=>{const ot=tt??0;return ot>0?ot-1:xe.length-1})},title:m("archives.card.previousPlate"),children:r.jsx(Xo,{className:"w-4 h-4 text-white"})}),r.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 ${x?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:Te=>{Te.stopPropagation(),se(tt=>{const ot=tt??0;return ot<xe.length-1?ot+1:0})},title:m("archives.card.nextPlate"),children:r.jsx(qa,{className:"w-4 h-4 text-white"})}),r.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 ${x?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:xe.map((Te,tt)=>r.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${tt===Me?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:ot=>{ot.stopPropagation(),se(tt)},title:Te.name||m("archives.card.plateNumber",{index:Te.index})},Te.index))})]}),r.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${x?"opacity-100":"opacity-0 group-hover:opacity-100"} ${i?"left-10":""}`,onClick:Te=>{Te.stopPropagation();const tt=Te.currentTarget.getBoundingClientRect();K({x:tt.left,y:tt.bottom+4})},title:m("archives.card.moreOptions"),children:r.jsx(vm,{className:"w-5 h-5 text-white"})}),r.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${b("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:Te=>{Te.stopPropagation(),b("archives","update",t.created_by_id)&&Ze.mutate()},disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?t.is_favorite?m("archives.card.removeFromFavorites"):m("archives.card.addToFavorites"):m("archives.permission.noUpdateArchives"),children:r.jsx(Eg,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${b("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&r.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"?m("archives.card.cancelled"):m("archives.card.failed")}),t.duplicate_count>0&&ye>0&&_e&&r.jsxs("button",{onClick:Te=>{Te.stopPropagation(),p?.(_e)},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:m("archives.viewOriginalPrint",{id:_e}),children:[r.jsx(Ti,{className:"w-3 h-3"}),"#",ye]}),t.duplicate_count>0&&ye===0&&r.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:[r.jsx(zZ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.source_3mf_path&&r.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 tt=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source";gh(t.id,tt,"source",c)},title:m("archives.card.openSource3mf"),children:r.jsx(eC,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&r.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(),ae.downloadF3d(t.id).catch(tt=>{console.error("F3D download failed:",tt)})},title:m("archives.card.downloadF3d"),children:r.jsx(Si,{className:"w-4 h-4 text-cyan-400"})}),r.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(),Be()},title:m("archives.card.preview3d"),children:r.jsx(ca,{className:"w-4 h-4 text-white"})}),t.timelapse_path&&r.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(),ne(!0)},title:m("archives.card.viewTimelapse"),children:r.jsx(Th,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&r.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(),he(!0)},title:t.photos.length===1?m("archives.card.viewPhoto"):m("archives.card.viewPhotos",{count:t.photos.length}),children:[r.jsx(by,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&r.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})]}),Ie&&Ie.length>0&&r.jsx(Es,{to:`/files?folder=${Ie[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:Te=>Te.stopPropagation(),title:m("archives.card.openFolder",{name:Ie[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:r.jsx(Pl,{className:"w-4 h-4 text-yellow-400"})})]}),r.jsxs(Et,{className:"p-4 flex-1 flex flex-col",children:[r.jsxs("p",{className:"text-[10px] text-bambu-gray/70 mb-1",children:["#",t.id]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[r.jsx("h3",{className:"min-w-0 font-medium text-white truncate",children:t.print_name||t.filename}),r.jsx(je,{variant:"ghost",size:"sm",className:"p-1 sm:p-1.5 shrink-0",onClick:()=>I(!0),disabled:!b("archives","update",t.created_by_id),title:b("archives","update",t.created_by_id)?m("archives.card.edit"):m("archives.card.noPermissionEdit"),children:r.jsx(mi,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:e}),(()=>{const Te=lse(t.bed_type);return Te?r.jsx("img",{src:Te.icon,alt:Te.label,title:Te.label,className:"w-4 h-4 flex-shrink-0"}):null})(),r.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${fh(t)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:fh(t)?m("archives.card.slicedFile"):m("archives.card.sourceFile"),children:fh(t)?m("archives.card.gcode"):m("archives.card.source")}),t.content_hash&&r.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&&r.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:m("archives.card.project",{name:t.project_name}),children:t.project_name}),t.run_count>1&&r.jsx("button",{className:"text-[10px] px-1.5 py-0.5 rounded font-medium bg-bambu-orange/20 text-bambu-orange hover:bg-bambu-orange/30 transition-colors cursor-pointer",onClick:Te=>{Te.stopPropagation(),L(!0)},title:m("archives.card.runsBadgeTitle",{count:t.run_count,successful:t.successful_run_count,failed:t.failed_run_count}),children:m("archives.card.runsBadge",{count:t.run_count})})]}),r.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)&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${cs(t.print_time_seconds||0)}
  8311. Actual: ${cs(t.actual_time_seconds||0)}
  8312. Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${cs(t.actual_time_seconds)}`:`Estimated: ${cs(t.print_time_seconds||0)}`,children:[r.jsx(Zn,{className:"w-3 h-3"}),cs(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&r.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&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(Vr,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),(t.cost!=null||t.energy_cost!=null)&&r.jsxs("div",{className:"flex items-center gap-3 text-bambu-gray",children:[t.cost!=null&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(Rge,{className:"w-3 h-3"}),u,t.cost.toFixed(2)]}),t.energy_cost!=null&&r.jsxs("div",{className:"flex items-center gap-1.5",title:`${m("stats.energyUsed")}: ${t.energy_kwh?.toFixed(3)||"N/A"} kWh`,children:[r.jsx(wc,{className:"w-3 h-3"}),u,t.energy_cost.toFixed(2)]})]}),(t.layer_height||t.total_layers)&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ca,{className:"w-3 h-3"}),t.total_layers&&r.jsx("span",{children:t.total_layers===1?m("archives.card.layer",{count:t.total_layers}):m("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&r.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&r.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?m("archives.card.object",{count:t.object_count}):m("archives.card.objects",{count:t.object_count}),children:[r.jsx(Si,{className:"w-3 h-3"}),t.object_count===1?m("archives.card.object",{count:t.object_count}):m("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:m("archives.card.slicedFor",{model:t.sliced_for_model}),children:[r.jsx(hr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&r.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[r.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&r.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((Te,tt)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:Te},title:Te},tt))})]})]}),(t.tags||t.notes)&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&r.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:r.jsx(WZ,{className:"w-3 h-3"})}),t.tags?.split(",").map((Te,tt)=>r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:Te.trim()},tt))]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("span",{children:Fg(t.created_at,l)}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&r.jsxs("span",{className:"flex items-center gap-1",title:m("archives.card.uploadedBy",{name:t.created_by_username}),children:[r.jsx(Gm,{className:"w-3 h-3"}),t.created_by_username]}),r.jsx("span",{children:ls(t.file_size)})]})]}),r.jsxs("div",{className:"flex gap-1 mt-3",children:[fh(t)?r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>C(!0),disabled:!t.file_path||!b("archives","reprint",t.created_by_id),title:t.file_path?b("archives","reprint",t.created_by_id)?void 0:m("archives.card.noPermissionReprint"):m("archives.card.noFileForReprint"),children:[r.jsx(hr,{className:"w-3 h-3 flex-shrink-0"}),r.jsx("span",{className:"hidden xl:inline truncate",children:m("archives.card.reprint")})]}),r.jsxs(je,{variant:"secondary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>j(!0),disabled:!t.file_path||!w("queue:create"),title:t.file_path?w("queue:create")?m("archives.card.schedulePrint"):m("archives.permission.noAddToQueue"):m("archives.card.noFileForReprint"),children:[r.jsx(wa,{className:"w-3 h-3 flex-shrink-0"}),r.jsx("span",{className:"hidden xl:inline truncate",children:m("archives.card.schedule")})]}),r.jsx(je,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const Te=t.print_name||t.filename||"model";gh(t.id,Te,"file",c)},title:m("archives.card.openInBambuStudio"),children:r.jsx(zr,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):r.jsxs(je,{variant:"primary",size:"sm",className:"flex-1 min-w-0 overflow-hidden",onClick:()=>{if(d)T(!0);else{const Te=t.print_name||t.filename||"model";gh(t.id,Te,"file",c)}},title:m(d?"slice.title":"archives.card.openInBambuStudioToSlice"),children:[d?r.jsx(uu,{className:"w-3 h-3 flex-shrink-0"}):r.jsx(zr,{className:"w-3 h-3 flex-shrink-0"}),r.jsx("span",{className:"hidden xl:inline truncate",children:m("archives.card.slice")})]}),r.jsx(je,{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?m("archives.card.externalLink"):t.makerworld_url?m("archives.card.makerWorld",{designer:t.designer||m("archives.card.viewProject")}):m("archives.card.noExternalLink"),children:r.jsx(Js,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),r.jsx(je,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(Te=>{console.error("Archive download failed:",Te)})},title:m("archives.card.download"),children:r.jsx(Zr,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>F(!0),disabled:!b("archives","delete",t.created_by_id),title:b("archives","delete",t.created_by_id)?m("archives.card.delete"):m("archives.card.noPermissionDelete"),children:r.jsx(en,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),H&&r.jsx(use,{archive:t,onClose:()=>I(!1)}),z&&r.jsx(mse,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>L(!1)}),de&&r.jsx(p5,{plates:de,onSelect:Te=>{me(null),S(`/gcode-viewer?archive=${t.id}&plate=${Te}`)},onClose:()=>me(null)}),k&&r.jsx(bc,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>C(!1)}),P&&r.jsx(RA,{source:{kind:"archive",id:t.id,filename:t.print_name||t.filename||"model"},onClose:()=>T(!1)}),A&&r.jsx(wn,{title:m("archives.modal.deleteArchive"),message:m("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:m("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Ce.mutate(_),F(!1),M(!1)},onCancel:()=>{F(!1),M(!1)},children:r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer text-sm text-bambu-gray",children:[r.jsx("input",{type:"checkbox",className:"mt-0.5 accent-red-500",checked:_,onChange:Te=>M(Te.target.checked)}),r.jsx("span",{children:m("archives.modal.deletePurgeStats")})]})}),E&&r.jsx(wn,{title:m("archives.modal.removeSource3mf"),message:m("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:m("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{We.mutate(),B(!1)},onCancel:()=>B(!1)}),W&&r.jsx(wn,{title:m("archives.modal.removeF3d"),message:m("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:m("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{st.mutate(),O(!1)},onCancel:()=>O(!1)}),ie&&r.jsx(wn,{title:m("archives.modal.removeTimelapse"),message:m("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:m("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Fe.mutate(),U(!1)},onCancel:()=>U(!1)}),G&&r.jsx(pse,{x:G.x,y:G.y,items:Qe,onClose:()=>K(null)}),Z&&t.timelapse_path&&r.jsx(dce,{src:ae.getArchiveTimelapse(t.id),title:m("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>ne(!1),onEdit:()=>{f.invalidateQueries({queryKey:["archives"]}),ne(!1)}}),Y&&ue.length>0&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:m("archives.modal.selectTimelapse")}),r.jsx("p",{className:"text-sm text-gray-400 mt-1",children:m("archives.modal.selectTimelapseDesc")})]}),r.jsx("button",{onClick:()=>{ce(!1),oe([])},className:"text-gray-400 hover:text-white p-1",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:ue.map(Te=>r.jsxs("button",{onClick:()=>it.mutate(Te.name),disabled:it.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:[r.jsx(Th,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-white font-medium truncate",children:Te.name}),r.jsxs("p",{className:"text-sm text-gray-400",children:[ls(Te.size),Te.mtime&&` • ${Fg(Te.mtime,l)}`]})]})]},Te.name))}),r.jsx("div",{className:"p-4 border-t border-gray-700",children:r.jsx(je,{variant:"secondary",onClick:()=>{ce(!1),oe([])},className:"w-full",children:"Cancel"})})]})}),Q&&r.jsx(hse,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>le(!1)}),pe&&t.photos&&t.photos.length>0&&r.jsx(fse,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>he(!1),onDelete:async Te=>{try{await ae.deleteArchivePhoto(t.id,Te),f.invalidateQueries({queryKey:["archives"]}),g(m("archives.toast.photoDeleted"))}catch{g(m("archives.toast.failedDeletePhoto"),"error")}}}),we&&r.jsx(cce,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>$(!1)}),J&&r.jsx(bc,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>j(!1)}),r.jsx("input",{ref:q,type:"file",accept:".3mf",className:"hidden",onChange:Te=>{const tt=Te.target.files?.[0];tt&&Re.mutate(tt),Te.target.value=""}}),r.jsx("input",{ref:R,type:"file",accept:".f3d",className:"hidden",onChange:Te=>{const tt=Te.target.files?.[0];tt&&ze.mutate(tt),Te.target.value=""}}),r.jsx("input",{ref:re,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:Te=>{const tt=Te.target.files?.[0];tt&&Oe.mutate(tt),Te.target.value=""}})]})}function Ctt({archive:t,printerName:e,isSelected:n,onSelect:a,selectionMode:i,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",useSlicerApi:c=!1,t:d,onNavigateToArchive:u}){const m=tn(),{showToast:p}=on(),{hasPermission:f,canModify:g}=dr(),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[k,C]=y.useState(!1),[P,T]=y.useState(!1),A=ji(),[F,_]=y.useState(!1),[M,H]=y.useState(!1),[I,z]=y.useState(!1),[L,Z]=y.useState(!1),[ne,Y]=y.useState(!1),[ce,ue]=y.useState([]),[oe,Q]=y.useState(!1),[le,pe]=y.useState(!1),[he,we]=y.useState(!1),[$,J]=y.useState(!1),[j,E]=y.useState(!1),[B,W]=y.useState(!1),[O,ie]=y.useState(null),U=y.useRef(null),G=y.useRef(null),K=y.useRef(null),[X,se]=y.useState(null),te=t.duplicate_sequence??0,fe=t.original_archive_id??null,de=async()=>{try{const ze=await ae.getArchivePlates(t.id);if(ze.is_multi_plate&&ze.plates.length>1){se(ze.plates);return}}catch{}A(`/gcode-viewer?archive=${t.id}`)},me=lt({mutationFn:()=>ae.deleteArchiveTimelapse(t.id),onSuccess:()=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.timelapseRemoved"))},onError:ze=>{p(ze.message||d("archives.toast.failedRemoveTimelapse"),"error")}}),q=lt({mutationFn:ze=>ae.uploadArchiveTimelapse(t.id,ze),onSuccess:ze=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.timelapseUploaded",{filename:ze.filename}))},onError:ze=>{p(ze.message||d("archives.toast.failedUploadTimelapse"),"error")}}),R=lt({mutationFn:ze=>ae.uploadSource3mf(t.id,ze),onSuccess:ze=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.source3mfAttached",{filename:ze.filename}))},onError:ze=>{p(ze.message||d("archives.toast.failedUploadSource3mf"),"error")}}),re=lt({mutationFn:()=>ae.deleteSource3mf(t.id),onSuccess:()=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.source3mfRemoved"))},onError:ze=>{p(ze.message||d("archives.toast.failedRemoveSource3mf"),"error")}}),be=lt({mutationFn:ze=>ae.uploadF3d(t.id,ze),onSuccess:ze=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.f3dAttached",{filename:ze.filename}))},onError:ze=>{p(ze.message||d("archives.toast.failedUploadF3d"),"error")}}),ye=lt({mutationFn:()=>ae.deleteF3d(t.id),onSuccess:()=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.f3dRemoved"))},onError:ze=>{p(ze.message||d("archives.toast.failedRemoveF3d"),"error")}}),_e=lt({mutationFn:()=>ae.scanArchiveTimelapse(t.id),onSuccess:ze=>{ze.status==="attached"?(m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.timelapseAttached",{filename:ze.filename}))):ze.status==="exists"?p(d("archives.toast.timelapseAlreadyAttached")):ze.status==="not_found"&&ze.available_files&&ze.available_files.length>0?(ue(ze.available_files),Y(!0)):p(ze.message||d("archives.toast.noMatchingTimelapse"),"warning")},onError:ze=>{p(ze.message||d("archives.toast.failedScanTimelapse"),"error")}}),xe=lt({mutationFn:ze=>ae.selectArchiveTimelapse(t.id,ze),onSuccess:ze=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.timelapseAttached",{filename:ze.filename})),Y(!1),ue([])},onError:ze=>{p(ze.message||d("archives.toast.failedAttachTimelapse"),"error")}}),ge=lt({mutationFn:ze=>ae.deleteArchive(t.id,ze),onSuccess:()=>{m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.archiveDeleted"))},onError:()=>{p(d("archives.toast.failedDeleteArchive"),"error")}}),Me=lt({mutationFn:()=>ae.toggleFavorite(t.id),onSuccess:ze=>{m.invalidateQueries({queryKey:["archives"]}),p(ze.is_favorite?d("archives.toast.addedToFavorites"):d("archives.toast.removedFromFavorites"))}}),{data:Be}=Xe({queryKey:["archive-folders",t.id],queryFn:()=>ae.getLibraryFoldersByArchive(t.id)}),Fe=lt({mutationFn:ze=>ae.updateArchive(t.id,{project_id:ze}),onSuccess:()=>{m.invalidateQueries({queryKey:["archives"]}),m.invalidateQueries({queryKey:["projects"]}),p(d("archives.toast.projectUpdated"))},onError:()=>{p(d("archives.toast.failedUpdateProject"),"error")}}),Oe=ze=>{ze.preventDefault(),ie({x:ze.clientX,y:ze.clientY})},We=[...fh(t)?[{label:d("archives.menu.print"),icon:r.jsx(hr,{className:"w-4 h-4"}),onClick:()=>_(!0),disabled:!t.file_path||!g("archives","reprint",t.created_by_id),title:t.file_path?g("archives","reprint",t.created_by_id)?void 0:d("archives.permission.noReprint"):d("archives.card.noFileForReprint")},{label:d("archives.menu.schedule"),icon:r.jsx(wa,{className:"w-4 h-4"}),onClick:()=>z(!0),disabled:!t.file_path||!f("queue:create"),title:t.file_path?f("queue:create")?void 0:d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint")},{label:d("archives.menu.openInBambuStudio"),icon:r.jsx(zr,{className:"w-4 h-4"}),onClick:()=>{const ze=t.print_name||t.filename||"model";gh(t.id,ze,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:d("archives.card.noFileForReprint")}]:[{label:d("archives.menu.slice"),icon:c?r.jsx(uu,{className:"w-4 h-4"}):r.jsx(zr,{className:"w-4 h-4"}),onClick:()=>{if(c)H(!0);else{const ze=t.print_name||t.filename||"model";gh(t.id,ze,"file",l)}}}],{label:t.external_url?d("archives.menu.externalLink"):d("archives.menu.viewOnMakerWorld"),icon:r.jsx(Js,{className:"w-4 h-4"}),onClick:()=>{const ze=t.external_url||t.makerworld_url;ze&&window.open(ze,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.preview3d"),icon:r.jsx(Si,{className:"w-4 h-4"}),onClick:()=>{de()}},{label:d("archives.menu.viewTimelapse"),icon:r.jsx(Th,{className:"w-4 h-4"}),onClick:()=>Z(!0),disabled:!t.timelapse_path},{label:d("archives.menu.scanForTimelapse"),icon:r.jsx(iC,{className:"w-4 h-4"}),onClick:()=>_e.mutate(),disabled:!t.printer_id||!!t.timelapse_path||_e.isPending||!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.uploadTimelapse"),icon:r.jsx(_a,{className:"w-4 h-4"}),onClick:()=>K.current?.click(),disabled:!!t.timelapse_path||!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:d("archives.menu.removeTimelapse"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>W(!0),danger:!0,disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?d("archives.menu.downloadSource3mf"):d("archives.menu.uploadSource3mf"),icon:r.jsx(eC,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ae.downloadSource3mf(t.id).catch(ze=>{console.error("Source 3MF download failed:",ze)}):U.current?.click()},disabled:!t.source_3mf_path&&!g("archives","update",t.created_by_id),title:!t.source_3mf_path&&!g("archives","update",t.created_by_id)?d("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:d("archives.menu.replaceSource3mf"),icon:r.jsx(_a,{className:"w-4 h-4"}),onClick:()=>U.current?.click(),disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.removeSource3mf"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>J(!0),danger:!0,disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?d("archives.menu.replaceF3d"):d("archives.menu.uploadF3d"),icon:r.jsx(Si,{className:"w-4 h-4"}),onClick:()=>G.current?.click(),disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:d("archives.menu.downloadF3d"),icon:r.jsx(Zr,{className:"w-4 h-4"}),onClick:()=>{ae.downloadF3d(t.id).catch(ze=>{console.error("F3D download failed:",ze)})}},{label:d("archives.menu.removeF3d"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>E(!0),danger:!0,disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.download"),icon:r.jsx(Zr,{className:"w-4 h-4"}),onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ze=>{console.error("Archive download failed:",ze)})},disabled:!f("archives:read"),title:f("archives:read")?void 0:d("archives.permission.noDownload")},{label:d("archives.menu.copyDownloadLink"),icon:r.jsx(Ti,{className:"w-4 h-4"}),onClick:()=>{const ze=`${window.location.origin}${ae.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ze).then(()=>{p(d("archives.toast.linkCopied"))}).catch(()=>{p(d("archives.toast.failedCopyLink"),"error")})},disabled:!f("archives:read"),title:f("archives:read")?void 0:d("archives.permission.noCopyLink")},{label:d("archives.menu.qrCode"),icon:r.jsx(HZ,{className:"w-4 h-4"}),onClick:()=>Q(!0)},{label:t.photos?.length?d("archives.menu.viewPhotosCount",{count:t.photos.length}):d("archives.menu.viewPhotos"),icon:r.jsx(by,{className:"w-4 h-4"}),onClick:()=>pe(!0),disabled:!t.photos?.length},{label:d("archives.menu.projectPage"),icon:r.jsx(Rs,{className:"w-4 h-4"}),onClick:()=>we(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?d("archives.menu.removeFromFavorites"):d("archives.menu.addToFavorites"),icon:r.jsx(Eg,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Me.mutate(),disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.edit"),icon:r.jsx(mi,{className:"w-4 h-4"}),onClick:()=>b(!0),disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.printLog"),icon:r.jsx(Vh,{className:"w-4 h-4"}),onClick:()=>S(!0)},...t.project_id&&t.project_name?[{label:d("archives.menu.goToProject",{name:t.project_name}),icon:r.jsx(to,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:d("archives.menu.addToProject"),icon:r.jsx(to,{className:"w-4 h-4"}),onClick:()=>{},submenuSearchPlaceholder:(s?.filter(ze=>ze.status==="active").length??0)>5?d("archives.menu.searchProjects"):void 0,submenu:(()=>{const ze=[];if(t.project_id&&ze.push({label:d("archives.menu.removeFromProject"),icon:r.jsx(Vt,{className:"w-4 h-4"}),onClick:()=>Fe.mutate(null)}),!s)ze.push({label:d("archives.menu.loading"),icon:r.jsx(ft,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const st=s.filter(Ee=>Ee.status==="active").sort((Ee,it)=>Ee.name.localeCompare(it.name));st.length===0?ze.push({label:d("archives.menu.noProjectsAvailable"),icon:r.jsx(to,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):st.forEach(Ee=>{ze.push({label:Ee.name,icon:r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:Ee.color||"#888"}}),onClick:()=>Fe.mutate(Ee.id),disabled:t.project_id===Ee.id})})}return ze})()},{label:d(n?"archives.menu.deselect":"archives.menu.select"),icon:n?r.jsx(gs,{className:"w-4 h-4"}):r.jsx(ro,{className:"w-4 h-4"}),onClick:()=>a(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.delete"),icon:r.jsx(en,{className:"w-4 h-4"}),onClick:()=>C(!0),danger:!0,disabled:!g("archives","delete",t.created_by_id),title:g("archives","delete",t.created_by_id)?void 0:d("archives.permission.noDelete")}];return r.jsxs(r.Fragment,{children:[r.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:Oe,children:[r.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[i&&r.jsx("button",{onClick:()=>a(t.id),children:n?r.jsx(gs,{className:"w-4 h-4 text-bambu-green"}):r.jsx(ro,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?r.jsx("img",{src:ae.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):r.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:r.jsx(mu,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),r.jsxs("div",{className:"col-span-4",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&r.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"?d("archives.card.cancelled"):d("archives.card.failed")}),t.duplicate_count>0&&te>0&&fe&&r.jsxs("button",{onClick:ze=>{ze.stopPropagation(),u?.(fe)},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:d("archives.viewOriginalPrint",{id:fe}),children:[r.jsx(Ti,{className:"w-3 h-3"}),"#",te]}),t.duplicate_count>0&&te===0&&r.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:[r.jsx(zZ,{className:"w-3 h-3"}),"+",t.duplicate_count]}),t.timelapse_path&&r.jsx("span",{title:d("archives.list.hasTimelapse"),children:r.jsx(Th,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),Be&&Be.length>0&&r.jsx(Es,{to:`/files?folder=${Be[0].id}`,className:"flex-shrink-0",title:d("archives.card.openFolder",{name:Be[0].name}),onClick:ze=>ze.stopPropagation(),children:r.jsx(Pl,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&r.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&r.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:d("archives.card.slicedFor",{model:t.sliced_for_model}),children:[r.jsx(hr,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),(()=>{const ze=lse(t.bed_type);return ze?r.jsx("img",{src:ze.icon,alt:ze.label,title:ze.label,className:"w-3.5 h-3.5 flex-shrink-0"}):null})(),t.sliced_for_model&&t.filament_type&&r.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&r.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&r.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ze,st)=>r.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-black/20",style:{backgroundColor:ze},title:ze},st))})]})]}),r.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),r.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[r.jsx("div",{children:Dg(t.created_at)}),t.created_by_username&&r.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:d("archives.card.uploadedBy",{name:t.created_by_username}),children:[r.jsx(Gm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:ls(t.file_size)}),r.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[fh(t)&&r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>_(!0),disabled:!g("archives","reprint",t.created_by_id),title:g("archives","reprint",t.created_by_id)?d("archives.card.reprint"):d("archives.card.noPermissionReprint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:r.jsx(hs,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{const ze=t.print_name||t.filename||"model";gh(t.id,ze,"file",l)},title:d("archives.card.openInBambuStudio"),children:r.jsx(zr,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?d("archives.card.externalLink"):"MakerWorld",children:r.jsx(Js,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{ae.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ze=>{console.error("Archive download failed:",ze)})},title:d("archives.card.download"),children:r.jsx(Zr,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>b(!0),disabled:!g("archives","update",t.created_by_id),title:g("archives","update",t.created_by_id)?d("archives.card.edit"):d("archives.card.noPermissionEdit"),children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>C(!0),disabled:!g("archives","delete",t.created_by_id),title:g("archives","delete",t.created_by_id)?d("archives.card.delete"):d("archives.card.noPermissionDelete"),children:r.jsx(en,{className:"w-4 h-4 text-red-400"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:ze=>{const st=ze.currentTarget.getBoundingClientRect();ie({x:st.left,y:st.bottom+4})},title:d("archives.card.moreOptions"),children:r.jsx(vm,{className:"w-4 h-4"})})]})]}),w&&r.jsx(use,{archive:t,onClose:()=>b(!1)}),x&&r.jsx(mse,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>S(!1)}),X&&r.jsx(p5,{plates:X,onSelect:ze=>{se(null),A(`/gcode-viewer?archive=${t.id}&plate=${ze}`)},onClose:()=>se(null)}),F&&r.jsx(bc,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>_(!1)}),M&&r.jsx(RA,{source:{kind:"archive",id:t.id,filename:t.print_name||t.filename||"model"},onClose:()=>H(!1)}),k&&r.jsx(wn,{title:d("archives.modal.deleteArchive"),message:d("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{ge.mutate(P),C(!1),T(!1)},onCancel:()=>{C(!1),T(!1)},children:r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer text-sm text-bambu-gray",children:[r.jsx("input",{type:"checkbox",className:"mt-0.5 accent-red-500",checked:P,onChange:ze=>T(ze.target.checked)}),r.jsx("span",{children:d("archives.modal.deletePurgeStats")})]})}),$&&r.jsx(wn,{title:d("archives.modal.removeSource3mf"),message:d("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{re.mutate(),J(!1)},onCancel:()=>J(!1)}),j&&r.jsx(wn,{title:d("archives.modal.removeF3d"),message:d("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ye.mutate(),E(!1)},onCancel:()=>E(!1)}),B&&r.jsx(wn,{title:d("archives.modal.removeTimelapse"),message:d("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{me.mutate(),W(!1)},onCancel:()=>W(!1)}),O&&r.jsx(pse,{x:O.x,y:O.y,items:We,onClose:()=>ie(null)}),L&&t.timelapse_path&&r.jsx(dce,{src:ae.getArchiveTimelapse(t.id),title:d("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>Z(!1),onEdit:()=>{m.invalidateQueries({queryKey:["archives"]}),Z(!1)}}),ne&&ce.length>0&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:d("archives.modal.selectTimelapse")}),r.jsx("p",{className:"text-sm text-gray-400 mt-1",children:d("archives.modal.selectTimelapseDesc")})]}),r.jsx("button",{onClick:()=>{Y(!1),ue([])},className:"text-gray-400 hover:text-white p-1",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:ce.map(ze=>r.jsxs("button",{onClick:()=>xe.mutate(ze.name),disabled:xe.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[r.jsx("div",{className:"font-medium text-white",children:ze.name}),r.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[r.jsx("span",{children:ls(ze.size)}),ze.mtime&&r.jsx("span",{children:Dg(ze.mtime)})]})]},ze.name))})]})}),oe&&r.jsx(hse,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>Q(!1)}),le&&t.photos&&r.jsx(fse,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>pe(!1),onDelete:async ze=>{try{await ae.deleteArchivePhoto(t.id,ze),m.invalidateQueries({queryKey:["archives"]}),p(d("archives.toast.photoDeleted"))}catch{p(d("archives.toast.failedDeletePhoto"),"error")}}}),he&&r.jsx(cce,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>we(!1)}),I&&r.jsx(bc,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>z(!1)}),r.jsx("input",{ref:U,type:"file",accept:".3mf",className:"hidden",onChange:ze=>{const st=ze.target.files?.[0];st&&R.mutate(st),ze.target.value=""}}),r.jsx("input",{ref:G,type:"file",accept:".f3d",className:"hidden",onChange:ze=>{const st=ze.target.files?.[0];st&&be.mutate(st),ze.target.value=""}}),r.jsx("input",{ref:K,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ze=>{const st=ze.target.files?.[0];st&&q.mutate(st),ze.target.value=""}})]})}const Ptt=["completed","failed","aborted","cancelled","stopped"],Ttt=[{id:"all",label:"All Archives",icon:r.jsx(Pl,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:r.jsx(Zn,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:r.jsx(wa,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:r.jsx(wa,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:r.jsx(Eg,{className:"w-4 h-4"})},{id:"not-printed",label:"Not Printed",icon:r.jsx(_a,{className:"w-4 h-4"})},{id:"printed",label:"Printed",icon:r.jsx(hr,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:r.jsx(Ha,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:r.jsx(Ti,{className:"w-4 h-4"})}];function Att(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a,hasAnyPermission:i}=dr(),s=y.useRef(null),[o,l]=y.useState(""),[c,d]=y.useState(()=>{const Ke=localStorage.getItem("archiveFilterPrinter");return Ke?Number(Ke):null}),[u,m]=y.useState(()=>localStorage.getItem("archiveFilterMaterial")),[p,f]=y.useState(()=>{const Ke=localStorage.getItem("archiveFilterColors");return Ke?new Set(JSON.parse(Ke)):new Set}),[g,w]=y.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[b,x]=y.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[S,k]=y.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[C,P]=y.useState(()=>localStorage.getItem("archiveHideDuplicates")==="true"),[T,A]=y.useState(()=>localStorage.getItem("archiveFilterTag")),[F,_]=y.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[M,H]=y.useState(!1),[I,z]=y.useState([]),[L,Z]=y.useState(!1),[ne,Y]=y.useState(new Set),[ce,ue]=y.useState(!1),[oe,Q]=y.useState(!1),[le,pe]=y.useState(!1),[he,we]=y.useState(!1),[$,J]=y.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[j,E]=y.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[B,W]=y.useState(()=>localStorage.getItem("archiveCollection")||"all"),[O,ie]=y.useState(0),[U,G]=y.useState(()=>{try{const Ke=localStorage.getItem("archivePageSize");return Ke?Number(Ke):50}catch{return 50}}),[K,X]=y.useState(!1),[se,te]=y.useState(!1),[fe,de]=y.useState(!1),[me,q]=y.useState(!1),[R,re]=y.useState(!1),[be,ye]=y.useState(null),[_e,xe]=y.useState(null),[ge,Me]=y.useState(()=>localStorage.getItem("logFilterUser")||null),[Be,Fe]=y.useState(()=>localStorage.getItem("logFilterStatus")),[Oe,Re]=y.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[We,ze]=y.useState(()=>localStorage.getItem("logFilterDateTo")||""),[st,Ee]=y.useState(()=>{const Ke=localStorage.getItem("logOffset");return Ke?Number(Ke):0}),[it,Ce]=y.useState(!1),[Ze,Ie]=y.useState(()=>{const Ke=localStorage.getItem("logPageSize");return Ke?Number(Ke):25}),ke=y.useCallback(Ke=>{xe(Ke),ye(Ke)},[]);y.useEffect(()=>{if(be){const Ke=setTimeout(()=>{const Qt=document.querySelector(`[data-archive-id="${be}"]`);Qt?Qt.scrollIntoView({behavior:"smooth",block:"center"}):_e===be&&n(t("archives.originalPrintNotVisible"),"warning"),_e===be&&xe(null)},100),Bt=setTimeout(()=>ye(null),5e3);return()=>{clearTimeout(Ke),clearTimeout(Bt)}}},[be,_e,n,t]);const{data:Ve,isLoading:rt}=Xe({queryKey:["archives",c],queryFn:()=>ae.getArchives(c||void 0)}),{data:Qe}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:Te}=Xe({queryKey:["projects"],queryFn:()=>ae.getProjects()}),{data:tt}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:ot}=Xe({queryKey:["users"],queryFn:ae.getUsers,enabled:$==="log"}),{data:Tt,isLoading:Ut}=Xe({queryKey:["print-log",c,ge,Be,Oe,We,o,st,Ze],queryFn:()=>ae.getPrintLog({search:o||void 0,printerId:c||void 0,username:ge||void 0,status:Be||void 0,dateFrom:Oe||void 0,dateTo:We||void 0,limit:Ze,offset:st}),enabled:$==="log"}),bt=tt?.time_format||"system",Wt=tt?.preferred_slicer||"bambu_studio",Zt=tt?.use_slicer_api??!1,ln=Ho(tt?.currency||"USD"),cn=lt({mutationFn:async Ke=>(await Promise.all(Ke.map(Bt=>ae.deleteArchive(Bt))),Ke.length),onSuccess:Ke=>{e.invalidateQueries({queryKey:["archives"]}),Y(new Set),n(`${Ke} archive${Ke!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),ct=lt({mutationFn:()=>ae.clearPrintLog(),onSuccess:Ke=>{e.invalidateQueries({queryKey:["print-log"]}),Ee(0),n(t("archives.log.cleared",{count:Ke.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});y.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),y.useEffect(()=>{u?localStorage.setItem("archiveFilterMaterial",u):localStorage.removeItem("archiveFilterMaterial")},[u]),y.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...p]))},[p]),y.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",g)},[g]),y.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",b.toString())},[b]),y.useEffect(()=>{localStorage.setItem("archiveHideFailed",S.toString())},[S]),y.useEffect(()=>{localStorage.setItem("archiveHideDuplicates",C.toString())},[C]),y.useEffect(()=>{T?localStorage.setItem("archiveFilterTag",T):localStorage.removeItem("archiveFilterTag")},[T]),y.useEffect(()=>{localStorage.setItem("archiveFilterFileType",F)},[F]),y.useEffect(()=>{ie(0)},[o,c,u,p,g,b,S,C,T,F,j,B]),y.useEffect(()=>{try{localStorage.setItem("archivePageSize",String(U))}catch{}},[U]),y.useEffect(()=>{localStorage.setItem("archiveViewMode",$)},[$]),y.useEffect(()=>{localStorage.setItem("archiveSortBy",j)},[j]),y.useEffect(()=>{localStorage.setItem("archiveCollection",B)},[B]),y.useEffect(()=>{ge?localStorage.setItem("logFilterUser",ge):localStorage.removeItem("logFilterUser")},[ge]),y.useEffect(()=>{Be?localStorage.setItem("logFilterStatus",Be):localStorage.removeItem("logFilterStatus")},[Be]),y.useEffect(()=>{Oe?localStorage.setItem("logFilterDateFrom",Oe):localStorage.removeItem("logFilterDateFrom")},[Oe]),y.useEffect(()=>{We?localStorage.setItem("logFilterDateTo",We):localStorage.removeItem("logFilterDateTo")},[We]),y.useEffect(()=>{localStorage.setItem("logOffset",st.toString())},[st]),y.useEffect(()=>{localStorage.setItem("logPageSize",Ze.toString())},[Ze]);const kt=new Map(Qe?.map(Ke=>[Ke.id,Ke.name])||[]),Nt=[...new Set(Ve?.flatMap(Ke=>Ke.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),ut=[...new Set(Ve?.flatMap(Ke=>Ke.filament_color?.split(",")||[]).filter(Boolean)||[])],Ct=[...new Set(Ve?.flatMap(Ke=>Ke.tags?.split(",").map(Bt=>Bt.trim())||[]).filter(Boolean)||[])].sort(),Le=Ve?.filter(Ke=>{const Bt=new Date,Qt=Yn(Ke.created_at)||new Date(0);let dn=!0;switch(B){case"recent":dn=Bt.getTime()-Qt.getTime()<1440*60*1e3;break;case"this-week":dn=Bt.getTime()-Qt.getTime()<10080*60*1e3;break;case"this-month":dn=Qt.getMonth()===Bt.getMonth()&&Qt.getFullYear()===Bt.getFullYear();break;case"favorites":dn=Ke.is_favorite===!0;break;case"not-printed":dn=Ke.status==="archived";break;case"printed":dn=Ptt.includes(Ke.status);break;case"failed":dn=Ke.status==="failed"||Ke.status==="aborted";break;case"duplicates":dn=Ke.duplicate_count>0;break}const nn=(Ke.print_name||Ke.filename).toLowerCase().includes(o.toLowerCase()),rn=!u||Ke.filament_type?.split(", ").includes(u),yn=Ke.filament_color?.split(",")||[],Mn=p.size===0||(g==="or"?yn.some(Fr=>p.has(Fr)):[...p].every(Fr=>yn.includes(Fr))),or=B==="favorites"||!b||Ke.is_favorite,Dr=B==="failed"||!S||Ke.status!=="failed"&&Ke.status!=="aborted",Gn=B==="duplicates"||!C||Ke.duplicate_count===0||Ke.duplicate_sequence===0,pi=Ke.tags?.split(",").map(Fr=>Fr.trim())||[],Un=!T||pi.includes(T),vr=fh(Ke);return dn&&nn&&rn&&Mn&&or&&Dr&&Gn&&Un&&(F==="all"||F==="gcode"&&vr||F==="source"&&!vr)}).sort((Ke,Bt)=>{switch(j){case"date-desc":return(Yn(Bt.created_at)?.getTime()||0)-(Yn(Ke.created_at)?.getTime()||0);case"date-asc":return(Yn(Ke.created_at)?.getTime()||0)-(Yn(Bt.created_at)?.getTime()||0);case"name-asc":return(Ke.print_name||Ke.filename).localeCompare(Bt.print_name||Bt.filename);case"name-desc":return(Bt.print_name||Bt.filename).localeCompare(Ke.print_name||Ke.filename);case"size-desc":return Bt.file_size-Ke.file_size;case"size-asc":return Ke.file_size-Bt.file_size;default:return 0}}),Ae=Le?.length||0,Ge=U===-1,Je=Ge?Ae||1:U,De=Math.max(1,Math.ceil(Ae/Je)),mt=Ge?Le:Le?.slice(O*Je,(O+1)*Je);y.useEffect(()=>{if(be&&Le&&!Ge){const Ke=Le.findIndex(Bt=>Bt.id===be);if(Ke>=0){const Bt=Math.floor(Ke/Je);Bt!==O&&ie(Bt)}}},[be]);const Ne=ce||ne.size>0,Ye=Ke=>{Y(Bt=>{const Qt=new Set(Bt);return Qt.has(Ke)?Qt.delete(Ke):Qt.add(Ke),Qt})},nt=()=>{Le&&Y(new Set(Le.map(Ke=>Ke.id)))},at=()=>{Y(new Set),ue(!1)},et=Ke=>{f(Bt=>{const Qt=new Set(Bt);return Qt.has(Ke)?Qt.delete(Ke):Qt.add(Ke),Qt})},vt=()=>{f(new Set)},wt=()=>{l(""),d(null),m(null),x(!1),k(!1),P(!1),A(null),_("all")},Ue=o||c||u||b||S||C||T||F!=="all",He=y.useCallback(Ke=>{Ke.preventDefault(),Ke.dataTransfer.types.includes("Files")&&Z(!0)},[]),Dt=y.useCallback(Ke=>{Ke.preventDefault(),Ke.currentTarget===Ke.target&&Z(!1)},[]),Rt=y.useCallback(Ke=>{Ke.preventDefault(),Z(!1);const Bt=Array.from(Ke.dataTransfer.files).filter(Qt=>Qt.name.endsWith(".3mf"));Bt.length>0?(z(Bt),H(!0)):Ke.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),qe=y.useCallback(Ke=>{const Bt=Ke.target;if(Bt.tagName==="INPUT"||Bt.tagName==="TEXTAREA"||Bt.isContentEditable){Ke.key==="Escape"&&Bt.blur();return}switch(Ke.key){case"/":Ke.preventDefault(),s.current?.focus();break;case"u":case"U":!Ke.metaKey&&!Ke.ctrlKey&&(Ke.preventDefault(),H(!0));break;case"Escape":Ne&&at();break}},[Ne]);return y.useEffect(()=>(document.addEventListener("keydown",qe),()=>document.removeEventListener("keydown",qe)),[qe]),r.jsxs("div",{className:"p-4 md:p-8 relative",onDragOver:He,onDragLeave:Dt,onDrop:Rt,children:[L&&r.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:r.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[r.jsx(_a,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),r.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),r.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),Ne&&r.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:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:at,children:[r.jsx(Vt,{className:"w-4 h-4"}),"Close"]}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsxs("span",{className:"text-white font-medium",children:[ne.size," selected"]}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsx(je,{variant:"secondary",size:"sm",onClick:nt,children:"Select All"}),r.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>pe(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[r.jsx(Vm,{className:"w-4 h-4"}),"Tags"]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>we(!0),disabled:!i("archives:update_own","archives:update_all"),title:i("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[r.jsx(to,{className:"w-4 h-4"}),"Project"]}),r.jsxs(je,{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 Ke=Array.from(ne);Promise.all(Ke.map(Bt=>ae.toggleFavorite(Bt))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${Ke.length} archive${Ke.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[r.jsx(Eg,{className:"w-4 h-4"}),"Favorite"]}),r.jsxs(je,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>Q(!0),disabled:!i("archives:delete_own","archives:delete_all"),title:i("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[r.jsx(en,{className:"w-4 h-4"}),"Delete"]})]}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[r.jsx("div",{children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(eo,{className:"w-7 h-7 text-bambu-green"}),"Archives"]}),r.jsxs("p",{className:"text-bambu-gray mt-1",children:[Le?.length||0," of ",Ve?.length||0," prints"]})]}),r.jsx("select",{className:"mt-0.5 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:B,onChange:Ke=>W(Ke.target.value),children:Ttt.map(Ke=>r.jsx("option",{value:Ke.id,children:Ke.label},Ke.id))})]})}),r.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",onClick:()=>X(!K),disabled:se,children:[se?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tC,{className:"w-4 h-4"}),"Export"]}),K&&r.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:[r.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()=>{X(!1),te(!0);try{const{blob:Ke,filename:Bt}=await ae.exportArchives({format:"csv",printerId:c||void 0,status:B==="failed"?"failed":void 0,search:o||void 0}),Qt=URL.createObjectURL(Ke),dn=document.createElement("a");dn.href=Qt,dn.download=Bt,dn.click(),URL.revokeObjectURL(Qt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{te(!1)}},children:[r.jsx(Rs,{className:"w-4 h-4"}),"Export as CSV"]}),r.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()=>{X(!1),te(!0);try{const{blob:Ke,filename:Bt}=await ae.exportArchives({format:"xlsx",printerId:c||void 0,status:B==="failed"?"failed":void 0,search:o||void 0}),Qt=URL.createObjectURL(Ke),dn=document.createElement("a");dn.href=Qt,dn.download=Bt,dn.click(),URL.revokeObjectURL(Qt),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{te(!1)}},children:[r.jsx(tC,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),ne.size>=2&&ne.size<=5&&r.jsxs(je,{variant:"secondary",onClick:()=>de(!0),children:[r.jsx(ey,{className:"w-4 h-4"}),"Compare (",ne.size,")"]}),!Ne&&r.jsxs(je,{variant:"secondary",onClick:()=>ue(!0),children:[r.jsx(gs,{className:"w-4 h-4"}),"Select"]}),r.jsxs(je,{onClick:()=>H(!0),disabled:!a("archives:create"),title:a("archives:create")?void 0:t("archives.permission.noCreate"),children:[r.jsx(_a,{className:"w-4 h-4"}),"Upload 3MF"]}),a("archives:purge")&&r.jsxs(je,{variant:"secondary",onClick:()=>re(!0),title:t("archivePurge.headerTooltip"),children:[r.jsx(en,{className:"w-4 h-4 mr-2"}),t("archivePurge.headerButton")]})]})]}),r.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[r.jsx("button",{className:`p-2 ${$==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>J("grid"),title:t("archives.gridView"),children:r.jsx(jS,{className:"w-4 h-4"})}),r.jsx("button",{className:`p-2 ${$==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>J("list"),title:t("archives.listView"),children:r.jsx(MS,{className:"w-4 h-4"})}),r.jsx("button",{className:`p-2 ${$==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>J("calendar"),title:t("archives.calendarView"),children:r.jsx(Yfe,{className:"w-4 h-4"})}),r.jsx("button",{className:`p-2 ${$==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>J("log"),title:t("archives.logView"),children:r.jsx(Cge,{className:"w-4 h-4"})})]}),$!=="log"&&r.jsx(At,{className:"mb-6",children:r.jsxs(Et,{className:"py-4",children:[r.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[r.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.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:Ke=>l(Ke.target.value)})]}),r.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:[r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx(PS,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),r.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:Ke=>d(Ke.target.value?Number(Ke.target.value):null),children:[r.jsx("option",{value:"",children:"All Printers"}),Qe?.map(Ke=>r.jsx("option",{value:Ke.id,children:Ke.name},Ke.id))]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx(Vr,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),r.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:Ke=>m(Ke.target.value||null),children:[r.jsx("option",{value:"",children:"All Materials"}),Nt.map(Ke=>r.jsx("option",{value:Ke,children:Ke},Ke))]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx(eC,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),r.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:Ke=>_(Ke.target.value),children:[r.jsx("option",{value:"all",children:"All Files"}),r.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),r.jsx("option",{value:"source",children:"Source Only"})]})]}),r.jsxs("button",{onClick:()=>x(!b),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${b?"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(b?"archives.showAll":"archives.showFavoritesOnly"),children:[r.jsx(Eg,{className:`w-4 h-4 ${b?"fill-yellow-400":""}`}),r.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),r.jsxs("button",{onClick:()=>k(!S),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${S?"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(S?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[r.jsx(Ha,{className:"w-4 h-4 "}),r.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),r.jsxs("button",{onClick:()=>P(!C),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${C?"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:[r.jsx(Ti,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm hidden md:inline",children:t("archives.hideDuplicates")})]}),Ct.length>0&&r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx(Vm,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),r.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:T||"",onChange:Ke=>A(Ke.target.value||null),children:[r.jsx("option",{value:"",children:"All Tags"}),Ct.map(Ke=>r.jsx("option",{value:Ke,children:Ke},Ke))]}),r.jsx("button",{onClick:()=>q(!0),className:"p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",title:t("archives.manageTags"),children:r.jsx(xy,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx(_T,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),r.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:j,onChange:Ke=>E(Ke.target.value),children:[r.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),r.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),r.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),r.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),r.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),r.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),Ue&&r.jsxs(je,{variant:"ghost",size:"sm",onClick:wt,className:"text-bambu-gray hover:text-white",children:[r.jsx(Vt,{className:"w-4 h-4"}),"Reset"]})]}),ut.length>0&&r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),p.size>1&&r.jsx("button",{onClick:()=>w(Ke=>Ke==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${g==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:g==="or"?"Match ANY selected color":"Match ALL selected colors",children:g.toUpperCase()}),r.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:ut.map(Ke=>r.jsx("button",{onClick:()=>et(Ke),className:`w-6 h-6 rounded-full border-2 transition-all ${p.has(Ke)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:Ke},title:Ke},Ke))}),p.size>0&&r.jsxs("button",{onClick:vt,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[r.jsx(Vt,{className:"w-3 h-3"}),"Clear"]})]})]})}),r.jsx(_tt,{}),rt?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):Le?.length===0?r.jsx(At,{children:r.jsxs(Et,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):$==="calendar"?r.jsx(At,{className:"p-6",children:r.jsx(V9e,{archives:Le||[],onArchiveClick:Ke=>{l(""),J("grid"),ye(Ke.id)},highlightedArchiveId:be})}):$==="grid"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:mt?.map(Ke=>r.jsx(Ntt,{archive:Ke,printerName:Ke.printer_id?kt.get(Ke.printer_id)||"Unknown":Ke.sliced_for_model||"No Printer",isSelected:ne.has(Ke.id),onSelect:Ye,selectionMode:Ne,projects:Te,isHighlighted:Ke.id===be,timeFormat:bt,preferredSlicer:Wt,useSlicerApi:Zt,currency:ln,t,onNavigateToArchive:ke},Ke.id))}),r.jsx($Y,{pageIndex:O,pageSize:U,totalRows:Ae,totalPages:De,onPageChange:ie,onPageSizeChange:Ke=>{G(Ke),ie(0)},t})]}):$==="list"?r.jsxs(r.Fragment,{children:[r.jsx(At,{children:r.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[r.jsx("div",{className:"col-span-1"}),r.jsx("div",{className:"col-span-4",children:"Name"}),r.jsx("div",{className:"col-span-2",children:"Printer"}),r.jsx("div",{className:"col-span-2",children:"Date"}),r.jsx("div",{className:"col-span-1",children:"Size"}),r.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),mt?.map(Ke=>r.jsx(Ctt,{archive:Ke,printerName:Ke.printer_id?kt.get(Ke.printer_id)||"Unknown":Ke.sliced_for_model||"No Printer",isSelected:ne.has(Ke.id),onSelect:Ye,selectionMode:Ne,projects:Te,isHighlighted:Ke.id===be,preferredSlicer:Wt,useSlicerApi:Zt,t,onNavigateToArchive:ke},Ke.id))]})}),r.jsx($Y,{pageIndex:O,pageSize:U,totalRows:Ae,totalPages:De,onPageChange:ie,onPageSizeChange:Ke=>{G(Ke),ie(0)},t})]}):$==="log"?r.jsxs("div",{className:"space-y-4",children:[r.jsx(At,{children:r.jsx(Et,{className:"py-3",children:r.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[r.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.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:Ke=>{l(Ke.target.value),Ee(0)}})]}),r.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:Ke=>{d(Ke.target.value?Number(Ke.target.value):null),Ee(0)},children:[r.jsx("option",{value:"",children:t("archives.log.allPrinters")}),Qe?.map(Ke=>r.jsx("option",{value:Ke.id,children:Ke.name},Ke.id))]}),r.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:ge||"",onChange:Ke=>{Me(Ke.target.value||null),Ee(0)},children:[r.jsx("option",{value:"",children:t("archives.log.allUsers")}),ot?.map(Ke=>r.jsx("option",{value:Ke.username,children:Ke.username},Ke.id))]}),r.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:Be||"",onChange:Ke=>{Fe(Ke.target.value||null),Ee(0)},children:[r.jsx("option",{value:"",children:t("archives.log.allStatuses")}),r.jsx("option",{value:"completed",children:t("archives.status.completed")}),r.jsx("option",{value:"failed",children:t("archives.status.failed")}),r.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),r.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),r.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),r.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:Oe,onChange:Ke=>{Re(Ke.target.value),Ee(0)}})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),r.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:We,onChange:Ke=>{ze(Ke.target.value),Ee(0)}})]}),r.jsx("div",{className:"ml-auto",children:r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>Ce(!0),disabled:!a("archives:delete_all")||ct.isPending,children:[r.jsx(en,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),r.jsx(At,{children:Ut?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):Tt?.items.length?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),r.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:Tt.items.map(Ke=>r.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[r.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Fg(Ke.started_at||Ke.created_at,bt)}),r.jsx("td",{className:"px-4 py-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[Ke.thumbnail_path&&r.jsx("img",{src:ae.getPrintLogThumbnail(Ke.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:Bt=>{Bt.target.style.display="none"}}),r.jsx("span",{className:"text-white break-words",title:Ke.print_name||"",children:Ke.print_name||"—"})]})}),r.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Ke.printer_name||"—"}),r.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Ke.created_by_username||"—"}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Ke.status==="completed"?"bg-green-500/20 text-green-400":Ke.status==="failed"?"bg-red-500/20 text-red-400":Ke.status==="stopped"?"bg-yellow-500/20 text-yellow-400":Ke.status==="cancelled"?"bg-orange-500/20 text-orange-400":Ke.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:Ke.status})}),r.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:Ke.duration_seconds?cs(Ke.duration_seconds):"—"}),r.jsx("td",{className:"px-4 py-3",children:r.jsxs("div",{className:"flex items-center gap-1.5",children:[Ke.filament_color&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:Ke.filament_color.startsWith("#")?Ke.filament_color:void 0}}),r.jsx("span",{className:"text-bambu-gray-light text-xs",children:Ke.filament_type||"—"})]})})]},Ke.id))})]})}),r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(st+Ze,Tt.total),total:Tt.total})}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),r.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:Ze,onChange:Ke=>{Ie(Number(Ke.target.value)),Ee(0)},children:[r.jsx("option",{value:10,children:"10"}),r.jsx("option",{value:25,children:"25"}),r.jsx("option",{value:50,children:"50"}),r.jsx("option",{value:100,children:"100"})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(st/Ze)+1," / ",Math.max(1,Math.ceil(Tt.total/Ze))]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>Ee(Math.max(0,st-Ze)),disabled:st===0,children:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>Ee(st+Ze),disabled:st+Ze>=Tt.total,children:r.jsx(qa,{className:"w-4 h-4"})})]})]})]}):r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,M&&r.jsx(M9e,{onClose:()=>{H(!1),z([])},initialFiles:I}),R&&r.jsx(D9e,{onClose:()=>re(!1)}),oe&&r.jsx(wn,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:ne.size}),confirmText:t("archives.modal.deleteCount",{count:ne.size}),variant:"danger",onConfirm:()=>{cn.mutate(Array.from(ne)),Q(!1)},onCancel:()=>Q(!1)}),le&&r.jsx(z9e,{selectedIds:Array.from(ne),existingTags:Ct,onClose:()=>pe(!1)}),he&&r.jsx(U9e,{selectedIds:Array.from(ne),onClose:()=>we(!1)}),fe&&ne.size>=2&&ne.size<=5&&r.jsx(ytt,{archiveIds:Array.from(ne),onClose:()=>{de(!1),Y(new Set),ue(!1)}}),me&&r.jsx(ktt,{onClose:()=>q(!1)}),it&&r.jsx(wn,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{ct.mutate(),Ce(!1)},onCancel:()=>Ce(!1)})]})}function $Y({pageIndex:t,pageSize:e,totalRows:n,totalPages:a,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(a<=1&&!l)return null;const c=l?n||1:e;return r.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o("archives.prints")}`:r.jsxs(r.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")]})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-bambu-gray",children:o("archives.pagination.show")}),r.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=>r.jsx("option",{value:d,children:d},d)),r.jsx("option",{value:-1,children:o("archives.pagination.all")})]}),!l&&r.jsxs(r.Fragment,{children:[r.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:r.jsx(yO,{className:"w-4 h-4"})}),r.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:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("archives.pagination.page")," ",t+1," ",o("archives.pagination.of")," ",a]}),r.jsx("button",{onClick:()=>i(Math.min(a-1,t+1)),disabled:t>=a-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(qa,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>i(a-1),disabled:t>=a-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(vO,{className:"w-4 h-4"})})]})]})]})}function jtt(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return y.useMemo(()=>a=>{e.forEach(i=>i(a))},e)}const ZA=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function pv(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function tU(t){return"nodeType"in t}function tl(t){var e,n;return t?pv(t)?t:tU(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function nU(t){const{Document:e}=tl(t);return t instanceof e}function b_(t){return pv(t)?!1:t instanceof tl(t).HTMLElement}function uce(t){return t instanceof tl(t).SVGElement}function hv(t){return t?pv(t)?t.document:tU(t)?nU(t)?t:b_(t)||uce(t)?t.ownerDocument:document:document:document}const Su=ZA?y.useLayoutEffect:y.useEffect;function rU(t){const e=y.useRef(t);return Su(()=>{e.current=t}),y.useCallback(function(){for(var n=arguments.length,a=new Array(n),i=0;i<n;i++)a[i]=arguments[i];return e.current==null?void 0:e.current(...a)},[])}function Mtt(){const t=y.useRef(null),e=y.useCallback((a,i)=>{t.current=setInterval(a,i)},[]),n=y.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function yS(t,e){e===void 0&&(e=[t]);const n=y.useRef(t);return Su(()=>{n.current!==t&&(n.current=t)},e),n}function x_(t,e){const n=y.useRef();return y.useMemo(()=>{const a=t(n.current);return n.current=a,a},[...e])}function mT(t){const e=rU(t),n=y.useRef(null),a=y.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,a]}function VI(t){const e=y.useRef();return y.useEffect(()=>{e.current=t},[t]),e.current}let rF={};function y_(t,e){return y.useMemo(()=>{if(e)return e;const n=rF[t]==null?0:rF[t]+1;return rF[t]=n,t+"-"+n},[t,e])}function mce(t){return function(e){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i<n;i++)a[i-1]=arguments[i];return a.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 fy=mce(1),vS=mce(-1);function Ett(t){return"clientX"in t&&"clientY"in t}function aU(t){if(!t)return!1;const{KeyboardEvent:e}=tl(t.target);return e&&t instanceof e}function Dtt(t){if(!t)return!1;const{TouchEvent:e}=tl(t.target);return e&&t instanceof e}function GI(t){if(Dtt(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 Ett(t)?{x:t.clientX,y:t.clientY}:null}const qy=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[qy.Translate.toString(t),qy.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:a}=t;return e+" "+n+"ms "+a}}}),VY="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Ftt(t){return t.matches(VY)?t:t.querySelector(VY)}const Ltt={display:"none"};function Rtt(t){let{id:e,value:n}=t;return pa.createElement("div",{id:e,style:Ltt},n)}function Itt(t){let{id:e,announcement:n,ariaLiveType:a="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 pa.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},n)}function Ott(){const[t,e]=y.useState("");return{announce:y.useCallback(a=>{a!=null&&e(a)},[]),announcement:t}}const pce=y.createContext(null);function ztt(t){const e=y.useContext(pce);y.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function Utt(){const[t]=y.useState(()=>new Set),e=y.useCallback(a=>(t.add(a),()=>t.delete(a)),[t]);return[y.useCallback(a=>{let{type:i,event:s}=a;t.forEach(o=>{var l;return(l=o[i])==null?void 0:l.call(o,s)})},[t]),e]}const Btt={draggable:`
  8313. To pick up a draggable item, press the space bar.
  8314. While dragging, use the arrow keys to move the item.
  8315. Press space again to drop the item in its new position, or press escape to cancel.
  8316. `},Htt={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 qtt(t){let{announcements:e=Htt,container:n,hiddenTextDescribedById:a,screenReaderInstructions:i=Btt}=t;const{announce:s,announcement:o}=Ott(),l=y_("DndLiveRegion"),[c,d]=y.useState(!1);if(y.useEffect(()=>{d(!0)},[]),ztt(y.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=pa.createElement(pa.Fragment,null,pa.createElement(Rtt,{id:a,value:i.draggable}),pa.createElement(Itt,{id:l,announcement:o}));return n?cc.createPortal(u,n):u}var Oi;(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"})(Oi||(Oi={}));function pT(){}function hT(t,e){return y.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function hce(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return y.useMemo(()=>[...e].filter(a=>a!=null),[...e])}const gd=Object.freeze({x:0,y:0});function fce(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function gce(t,e){let{data:{value:n}}=t,{data:{value:a}}=e;return n-a}function $tt(t,e){let{data:{value:n}}=t,{data:{value:a}}=e;return a-n}function GY(t){let{left:e,top:n,height:a,width:i}=t;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+a},{x:e+i,y:n+a}]}function bce(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function WY(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 xce=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=t;const i=WY(e,e.left,e.top),s=[];for(const o of a){const{id:l}=o,c=n.get(l);if(c){const d=fce(WY(c),i);s.push({id:l,data:{droppableContainer:o,value:d}})}}return s.sort(gce)},Vtt=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=t;const i=GY(e),s=[];for(const o of a){const{id:l}=o,c=n.get(l);if(c){const d=GY(c),u=i.reduce((p,f,g)=>p+fce(d[g],f),0),m=Number((u/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:m}})}}return s.sort(gce)};function Gtt(t,e){const n=Math.max(e.top,t.top),a=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-a,l=s-n;if(a<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 Wtt=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=t;const i=[];for(const s of a){const{id:o}=s,l=n.get(o);if(l){const c=Gtt(l,e);c>0&&i.push({id:o,data:{droppableContainer:s,value:c}})}}return i.sort($tt)};function Ktt(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function yce(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:gd}function Qtt(t){return function(n){for(var a=arguments.length,i=new Array(a>1?a-1:0),s=1;s<a;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 Ytt=Qtt(1);function Xtt(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 Ztt(t,e,n){const a=Xtt(e);if(!a)return t;const{scaleX:i,scaleY:s,x:o,y:l}=a,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 Jtt={ignoreTransform:!1};function fv(t,e){e===void 0&&(e=Jtt);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:d,transformOrigin:u}=tl(t).getComputedStyle(t);d&&(n=Ztt(n,d,u))}const{top:a,left:i,width:s,height:o,bottom:l,right:c}=n;return{top:a,left:i,width:s,height:o,bottom:l,right:c}}function KY(t){return fv(t,{ignoreTransform:!0})}function ent(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function tnt(t,e){return e===void 0&&(e=tl(t).getComputedStyle(t)),e.position==="fixed"}function nnt(t,e){e===void 0&&(e=tl(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 JA(t,e){const n=[];function a(i){if(e!=null&&n.length>=e||!i)return n;if(nU(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!b_(i)||uce(i)||n.includes(i))return n;const s=tl(t).getComputedStyle(i);return i!==t&&nnt(i,s)&&n.push(i),tnt(i,s)?n:a(i.parentNode)}return t?a(t):n}function vce(t){const[e]=JA(t,1);return e??null}function aF(t){return!ZA||!t?null:pv(t)?t:tU(t)?nU(t)||t===hv(t).scrollingElement?window:b_(t)?t:null:null}function wce(t){return pv(t)?t.scrollX:t.scrollLeft}function Sce(t){return pv(t)?t.scrollY:t.scrollTop}function WI(t){return{x:wce(t),y:Sce(t)}}var is;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(is||(is={}));function _ce(t){return!ZA||!t?!1:t===document.scrollingElement}function kce(t){const e={x:0,y:0},n=_ce(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},a={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},i=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=a.y,l=t.scrollLeft>=a.x;return{isTop:i,isLeft:s,isBottom:o,isRight:l,maxScroll:a,minScroll:e}}const rnt={x:.2,y:.2};function ant(t,e,n,a,i){let{top:s,left:o,right:l,bottom:c}=n;a===void 0&&(a=10),i===void 0&&(i=rnt);const{isTop:d,isBottom:u,isLeft:m,isRight:p}=kce(t),f={x:0,y:0},g={x:0,y:0},w={height:e.height*i.y,width:e.width*i.x};return!d&&s<=e.top+w.height?(f.y=is.Backward,g.y=a*Math.abs((e.top+w.height-s)/w.height)):!u&&c>=e.bottom-w.height&&(f.y=is.Forward,g.y=a*Math.abs((e.bottom-w.height-c)/w.height)),!p&&l>=e.right-w.width?(f.x=is.Forward,g.x=a*Math.abs((e.right-w.width-l)/w.width)):!m&&o<=e.left+w.width&&(f.x=is.Backward,g.x=a*Math.abs((e.left+w.width-o)/w.width)),{direction:f,speed:g}}function int(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:a,bottom:i}=t.getBoundingClientRect();return{top:e,left:n,right:a,bottom:i,width:t.clientWidth,height:t.clientHeight}}function Nce(t){return t.reduce((e,n)=>fy(e,WI(n)),gd)}function snt(t){return t.reduce((e,n)=>e+wce(n),0)}function ont(t){return t.reduce((e,n)=>e+Sce(n),0)}function lnt(t,e){if(e===void 0&&(e=fv),!t)return;const{top:n,left:a,bottom:i,right:s}=e(t);vce(t)&&(i<=0||s<=0||n>=window.innerHeight||a>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const cnt=[["x",["left","right"],snt],["y",["top","bottom"],ont]];class iU{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 a=JA(n),i=Nce(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of cnt)for(const c of o)Object.defineProperty(this,c,{get:()=>{const d=l(a),u=i[s]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class yw{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...n)})},this.target=e}add(e,n,a){var i;(i=this.target)==null||i.addEventListener(e,n,a),this.listeners.push([e,n,a])}}function dnt(t){const{EventTarget:e}=tl(t);return t instanceof e?t:hv(t)}function iF(t,e){const n=Math.abs(t.x),a=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+a**2)>e:"x"in e&&"y"in e?n>e.x&&a>e.y:"x"in e?n>e.x:"y"in e?a>e.y:!1}var nc;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(nc||(nc={}));function QY(t){t.preventDefault()}function unt(t){t.stopPropagation()}var Tr;(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"})(Tr||(Tr={}));const Cce={start:[Tr.Space,Tr.Enter],cancel:[Tr.Esc],end:[Tr.Space,Tr.Enter,Tr.Tab]},mnt=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case Tr.Right:return{...n,x:n.x+25};case Tr.Left:return{...n,x:n.x-25};case Tr.Down:return{...n,y:n.y+25};case Tr.Up:return{...n,y:n.y-25}}};class ej{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 yw(hv(n)),this.windowListeners=new yw(tl(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(nc.Resize,this.handleCancel),this.windowListeners.add(nc.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(nc.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,a=e.node.current;a&&lnt(a),n(gd)}handleKeyDown(e){if(aU(e)){const{active:n,context:a,options:i}=this.props,{keyboardCodes:s=Cce,coordinateGetter:o=mnt,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}=a.current,u=d?{x:d.left,y:d.top}:gd;this.referenceCoordinates||(this.referenceCoordinates=u);const m=o(e,{active:n,context:a.current,currentCoordinates:u});if(m){const p=vS(m,u),f={x:0,y:0},{scrollableAncestors:g}=a.current;for(const w of g){const b=e.code,{isTop:x,isRight:S,isLeft:k,isBottom:C,maxScroll:P,minScroll:T}=kce(w),A=int(w),F={x:Math.min(b===Tr.Right?A.right-A.width/2:A.right,Math.max(b===Tr.Right?A.left:A.left+A.width/2,m.x)),y:Math.min(b===Tr.Down?A.bottom-A.height/2:A.bottom,Math.max(b===Tr.Down?A.top:A.top+A.height/2,m.y))},_=b===Tr.Right&&!S||b===Tr.Left&&!k,M=b===Tr.Down&&!C||b===Tr.Up&&!x;if(_&&F.x!==m.x){const H=w.scrollLeft+p.x,I=b===Tr.Right&&H<=P.x||b===Tr.Left&&H>=T.x;if(I&&!p.y){w.scrollTo({left:H,behavior:l});return}I?f.x=w.scrollLeft-H:f.x=b===Tr.Right?w.scrollLeft-P.x:w.scrollLeft-T.x,f.x&&w.scrollBy({left:-f.x,behavior:l});break}else if(M&&F.y!==m.y){const H=w.scrollTop+p.y,I=b===Tr.Down&&H<=P.y||b===Tr.Up&&H>=T.y;if(I&&!p.x){w.scrollTo({top:H,behavior:l});return}I?f.y=w.scrollTop-H:f.y=b===Tr.Down?w.scrollTop-P.y:w.scrollTop-T.y,f.y&&w.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(e,fy(vS(m,this.referenceCoordinates),f))}}}handleMove(e,n){const{onMove:a}=this.props;e.preventDefault(),a(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()}}ej.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:a=Cce,onActivation:i}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(a.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),i?.({event:t.nativeEvent}),!0)}return!1}}];function YY(t){return!!(t&&"distance"in t)}function XY(t){return!!(t&&"delay"in t)}class sU{constructor(e,n,a){var i;a===void 0&&(a=dnt(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=hv(o),this.documentListeners=new yw(this.document),this.listeners=new yw(a),this.windowListeners=new yw(tl(o)),this.initialCoordinates=(i=GI(s))!=null?i:gd,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:a}}}=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(nc.Resize,this.handleCancel),this.windowListeners.add(nc.DragStart,QY),this.windowListeners.add(nc.VisibilityChange,this.handleCancel),this.windowListeners.add(nc.ContextMenu,QY),this.documentListeners.add(nc.Keydown,this.handleKeydown),n){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(XY(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(YY(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:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(nc.Click,unt,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(nc.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:a,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!i)return;const c=(n=GI(e))!=null?n:gd,d=vS(i,c);if(!a&&l){if(YY(l)){if(l.tolerance!=null&&iF(d,l.tolerance))return this.handleCancel();if(iF(d,l.distance))return this.handleStart()}if(XY(l)&&iF(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===Tr.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const pnt={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class tj extends sU{constructor(e){const{event:n}=e,a=hv(n.target);super(e,pnt,a)}}tj.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:a}=e;return!n.isPrimary||n.button!==0?!1:(a?.({event:n}),!0)}}];const hnt={move:{name:"mousemove"},end:{name:"mouseup"}};var KI;(function(t){t[t.RightClick=2]="RightClick"})(KI||(KI={}));class fnt extends sU{constructor(e){super(e,hnt,hv(e.event.target))}}fnt.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:a}=e;return n.button===KI.RightClick?!1:(a?.({event:n}),!0)}}];const sF={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class gnt extends sU{constructor(e){super(e,sF)}static setup(){return window.addEventListener(sF.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(sF.move.name,e)};function e(){}}}gnt.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:a}=e;const{touches:i}=n;return i.length>1?!1:(a?.({event:n}),!0)}}];var vw;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(vw||(vw={}));var fT;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(fT||(fT={}));function bnt(t){let{acceleration:e,activator:n=vw.Pointer,canScroll:a,draggingRect:i,enabled:s,interval:o=5,order:l=fT.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:m,threshold:p}=t;const f=ynt({delta:m,disabled:!s}),[g,w]=Mtt(),b=y.useRef({x:0,y:0}),x=y.useRef({x:0,y:0}),S=y.useMemo(()=>{switch(n){case vw.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case vw.DraggableRect:return i}},[n,i,c]),k=y.useRef(null),C=y.useCallback(()=>{const T=k.current;if(!T)return;const A=b.current.x*x.current.x,F=b.current.y*x.current.y;T.scrollBy(A,F)},[]),P=y.useMemo(()=>l===fT.TreeOrder?[...d].reverse():d,[l,d]);y.useEffect(()=>{if(!s||!d.length||!S){w();return}for(const T of P){if(a?.(T)===!1)continue;const A=d.indexOf(T),F=u[A];if(!F)continue;const{direction:_,speed:M}=ant(T,F,S,e,p);for(const H of["x","y"])f[H][_[H]]||(M[H]=0,_[H]=0);if(M.x>0||M.y>0){w(),k.current=T,g(C,o),b.current=M,x.current=_;return}}b.current={x:0,y:0},x.current={x:0,y:0},w()},[e,C,a,w,s,o,JSON.stringify(S),JSON.stringify(f),g,d,P,u,JSON.stringify(p)])}const xnt={x:{[is.Backward]:!1,[is.Forward]:!1},y:{[is.Backward]:!1,[is.Forward]:!1}};function ynt(t){let{delta:e,disabled:n}=t;const a=VI(e);return x_(i=>{if(n||!a||!i)return xnt;const s={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[is.Backward]:i.x[is.Backward]||s.x===-1,[is.Forward]:i.x[is.Forward]||s.x===1},y:{[is.Backward]:i.y[is.Backward]||s.y===-1,[is.Forward]:i.y[is.Forward]||s.y===1}}},[n,e,a])}function vnt(t,e){const n=e!=null?t.get(e):void 0,a=n?n.node.current:null;return x_(i=>{var s;return e==null?null:(s=a??i)!=null?s:null},[a,e])}function wnt(t,e){return y.useMemo(()=>t.reduce((n,a)=>{const{sensor:i}=a,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,a)}));return[...n,...s]},[]),[t,e])}var wS;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(wS||(wS={}));var QI;(function(t){t.Optimized="optimized"})(QI||(QI={}));const ZY=new Map;function Snt(t,e){let{dragging:n,dependencies:a,config:i}=e;const[s,o]=y.useState(null),{frequency:l,measure:c,strategy:d}=i,u=y.useRef(t),m=b(),p=yS(m),f=y.useCallback(function(x){x===void 0&&(x=[]),!p.current&&o(S=>S===null?x:S.concat(x.filter(k=>!S.includes(k))))},[p]),g=y.useRef(null),w=x_(x=>{if(m&&!n)return ZY;if(!x||x===ZY||u.current!==t||s!=null){const S=new Map;for(let k of t){if(!k)continue;if(s&&s.length>0&&!s.includes(k.id)&&k.rect.current){S.set(k.id,k.rect.current);continue}const C=k.node.current,P=C?new iU(c(C),C):null;k.rect.current=P,P&&S.set(k.id,P)}return S}return x},[t,s,n,m,c]);return y.useEffect(()=>{u.current=t},[t]),y.useEffect(()=>{m||f()},[n,m]),y.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),y.useEffect(()=>{m||typeof l!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},l))},[l,m,f,...a]),{droppableRects:w,measureDroppableContainers:f,measuringScheduled:s!=null};function b(){switch(d){case wS.Always:return!1;case wS.BeforeDragging:return n;default:return!n}}}function Pce(t,e){return x_(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function _nt(t,e){return Pce(t,e)}function knt(t){let{callback:e,disabled:n}=t;const a=rU(e),i=y.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(a)},[a,n]);return y.useEffect(()=>()=>i?.disconnect(),[i]),i}function nj(t){let{callback:e,disabled:n}=t;const a=rU(e),i=y.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(a)},[n]);return y.useEffect(()=>()=>i?.disconnect(),[i]),i}function Nnt(t){return new iU(fv(t),t)}function JY(t,e,n){e===void 0&&(e=Nnt);const[a,i]=y.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=knt({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=nj({callback:s});return Su(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),a}function Cnt(t){const e=Pce(t);return yce(t,e)}const eX=[];function Pnt(t){const e=y.useRef(t),n=x_(a=>t?a&&a!==eX&&t&&e.current&&t.parentNode===e.current.parentNode?a:JA(t):eX,[t]);return y.useEffect(()=>{e.current=t},[t]),n}function Tnt(t){const[e,n]=y.useState(null),a=y.useRef(t),i=y.useCallback(s=>{const o=aF(s.target);o&&n(l=>l?(l.set(o,WI(o)),new Map(l)):null)},[]);return y.useEffect(()=>{const s=a.current;if(t!==s){o(s);const l=t.map(c=>{const d=aF(c);return d?(d.addEventListener("scroll",i,{passive:!0}),[d,WI(d)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),a.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(c=>{const d=aF(c);d?.removeEventListener("scroll",i)})}},[i,t]),y.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>fy(s,o),gd):Nce(t):gd,[t,e])}function tX(t,e){e===void 0&&(e=[]);const n=y.useRef(null);return y.useEffect(()=>{n.current=null},e),y.useEffect(()=>{const a=t!==gd;a&&!n.current&&(n.current=t),!a&&n.current&&(n.current=null)},[t]),n.current?vS(t,n.current):gd}function Ant(t){y.useEffect(()=>{if(!ZA)return;const e=t.map(n=>{let{sensor:a}=n;return a.setup==null?void 0:a.setup()});return()=>{for(const n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function jnt(t,e){return y.useMemo(()=>t.reduce((n,a)=>{let{eventName:i,handler:s}=a;return n[i]=o=>{s(o,e)},n},{}),[t,e])}function Tce(t){return y.useMemo(()=>t?ent(t):null,[t])}const nX=[];function Mnt(t,e){e===void 0&&(e=fv);const[n]=t,a=Tce(n?tl(n):null),[i,s]=y.useState(nX);function o(){s(()=>t.length?t.map(c=>_ce(c)?a:new iU(e(c),c)):nX)}const l=nj({callback:o});return Su(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),i}function Ent(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return b_(e)?e:t}function Dnt(t){let{measure:e}=t;const[n,a]=y.useState(null),i=y.useCallback(d=>{for(const{target:u}of d)if(b_(u)){a(m=>{const p=e(u);return m?{...m,width:p.width,height:p.height}:p});break}},[e]),s=nj({callback:i}),o=y.useCallback(d=>{const u=Ent(d);s?.disconnect(),u&&s?.observe(u),a(u?e(u):null)},[e,s]),[l,c]=mT(o);return y.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const Fnt=[{sensor:tj,options:{}},{sensor:ej,options:{}}],Lnt={current:{}},HN={draggable:{measure:KY},droppable:{measure:KY,strategy:wS.WhileDragging,frequency:QI.Optimized},dragOverlay:{measure:fv}};class ww 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,a;return(n=(a=this.get(e))==null?void 0:a.node.current)!=null?n:void 0}}const Rnt={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new ww,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:pT},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:HN,measureDroppableContainers:pT,windowRect:null,measuringScheduled:!1},Int={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:pT,draggableNodes:new Map,over:null,measureDroppableContainers:pT},rj=y.createContext(Int),Ace=y.createContext(Rnt);function Ont(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new ww}}}function znt(t,e){switch(e.type){case Oi.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Oi.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 Oi.DragEnd:case Oi.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Oi.RegisterDroppable:{const{element:n}=e,{id:a}=n,i=new ww(t.droppable.containers);return i.set(a,n),{...t,droppable:{...t.droppable,containers:i}}}case Oi.SetDroppableDisabled:{const{id:n,key:a,disabled:i}=e,s=t.droppable.containers.get(n);if(!s||a!==s.key)return t;const o=new ww(t.droppable.containers);return o.set(n,{...s,disabled:i}),{...t,droppable:{...t.droppable,containers:o}}}case Oi.UnregisterDroppable:{const{id:n,key:a}=e,i=t.droppable.containers.get(n);if(!i||a!==i.key)return t;const s=new ww(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function Unt(t){let{disabled:e}=t;const{active:n,activatorEvent:a,draggableNodes:i}=y.useContext(rj),s=VI(a),o=VI(n?.id);return y.useEffect(()=>{if(!e&&!a&&s&&o!=null){if(!aU(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=Ftt(u);if(m){m.focus();break}}})}},[a,e,i,o,s]),null}function Bnt(t,e){let{transform:n,...a}=e;return t!=null&&t.length?t.reduce((i,s)=>s({transform:i,...a}),n):n}function Hnt(t){return y.useMemo(()=>({draggable:{...HN.draggable,...t?.draggable},droppable:{...HN.droppable,...t?.droppable},dragOverlay:{...HN.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function qnt(t){let{activeNode:e,measure:n,initialRect:a,config:i=!0}=t;const s=y.useRef(!1),{x:o,y:l}=typeof i=="boolean"?{x:i,y:i}:i;Su(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!a)return;const d=e?.node.current;if(!d||d.isConnected===!1)return;const u=n(d),m=yce(u,a);if(o||(m.x=0),l||(m.y=0),s.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const p=vce(d);p&&p.scrollBy({top:m.y,left:m.x})}},[e,o,l,a,n])}const jce=y.createContext({...gd,scaleX:1,scaleY:1});var dh;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(dh||(dh={}));const Mce=y.memo(function(e){var n,a,i,s;let{id:o,accessibility:l,autoScroll:c=!0,children:d,sensors:u=Fnt,collisionDetection:m=Wtt,measuring:p,modifiers:f,...g}=e;const w=y.useReducer(znt,void 0,Ont),[b,x]=w,[S,k]=Utt(),[C,P]=y.useState(dh.Uninitialized),T=C===dh.Initialized,{draggable:{active:A,nodes:F,translate:_},droppable:{containers:M}}=b,H=A!=null?F.get(A):null,I=y.useRef({initial:null,translated:null}),z=y.useMemo(()=>{var Ze;return A!=null?{id:A,data:(Ze=H?.data)!=null?Ze:Lnt,rect:I}:null},[A,H]),L=y.useRef(null),[Z,ne]=y.useState(null),[Y,ce]=y.useState(null),ue=yS(g,Object.values(g)),oe=y_("DndDescribedBy",o),Q=y.useMemo(()=>M.getEnabled(),[M]),le=Hnt(p),{droppableRects:pe,measureDroppableContainers:he,measuringScheduled:we}=Snt(Q,{dragging:T,dependencies:[_.x,_.y],config:le.droppable}),$=vnt(F,A),J=y.useMemo(()=>Y?GI(Y):null,[Y]),j=Ce(),E=_nt($,le.draggable.measure);qnt({activeNode:A!=null?F.get(A):null,config:j.layoutShiftCompensation,initialRect:E,measure:le.draggable.measure});const B=JY($,le.draggable.measure,E),W=JY($?$.parentElement:null),O=y.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:pe,draggableNodes:F,draggingNode:null,draggingNodeRect:null,droppableContainers:M,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ie=M.getNodeFor((n=O.current.over)==null?void 0:n.id),U=Dnt({measure:le.dragOverlay.measure}),G=(a=U.nodeRef.current)!=null?a:$,K=T?(i=U.rect)!=null?i:B:null,X=!!(U.nodeRef.current&&U.rect),se=Cnt(X?null:B),te=Tce(G?tl(G):null),fe=Pnt(T?ie??$:null),de=Mnt(fe),me=Bnt(f,{transform:{x:_.x-se.x,y:_.y-se.y,scaleX:1,scaleY:1},activatorEvent:Y,active:z,activeNodeRect:B,containerNodeRect:W,draggingNodeRect:K,over:O.current.over,overlayNodeRect:U.rect,scrollableAncestors:fe,scrollableAncestorRects:de,windowRect:te}),q=J?fy(J,_):null,R=Tnt(fe),re=tX(R),be=tX(R,[B]),ye=fy(me,re),_e=K?Ytt(K,me):null,xe=z&&_e?m({active:z,collisionRect:_e,droppableRects:pe,droppableContainers:Q,pointerCoordinates:q}):null,ge=bce(xe,"id"),[Me,Be]=y.useState(null),Fe=X?me:fy(me,be),Oe=Ktt(Fe,(s=Me?.rect)!=null?s:null,B),Re=y.useRef(null),We=y.useCallback((Ze,Ie)=>{let{sensor:ke,options:Ve}=Ie;if(L.current==null)return;const rt=F.get(L.current);if(!rt)return;const Qe=Ze.nativeEvent,Te=new ke({active:L.current,activeNode:rt,event:Qe,options:Ve,context:O,onAbort(ot){if(!F.get(ot))return;const{onDragAbort:Ut}=ue.current,bt={id:ot};Ut?.(bt),S({type:"onDragAbort",event:bt})},onPending(ot,Tt,Ut,bt){if(!F.get(ot))return;const{onDragPending:Zt}=ue.current,ln={id:ot,constraint:Tt,initialCoordinates:Ut,offset:bt};Zt?.(ln),S({type:"onDragPending",event:ln})},onStart(ot){const Tt=L.current;if(Tt==null)return;const Ut=F.get(Tt);if(!Ut)return;const{onDragStart:bt}=ue.current,Wt={activatorEvent:Qe,active:{id:Tt,data:Ut.data,rect:I}};cc.unstable_batchedUpdates(()=>{bt?.(Wt),P(dh.Initializing),x({type:Oi.DragStart,initialCoordinates:ot,active:Tt}),S({type:"onDragStart",event:Wt}),ne(Re.current),ce(Qe)})},onMove(ot){x({type:Oi.DragMove,coordinates:ot})},onEnd:tt(Oi.DragEnd),onCancel:tt(Oi.DragCancel)});Re.current=Te;function tt(ot){return async function(){const{active:Ut,collisions:bt,over:Wt,scrollAdjustedTranslate:Zt}=O.current;let ln=null;if(Ut&&Zt){const{cancelDrop:cn}=ue.current;ln={activatorEvent:Qe,active:Ut,collisions:bt,delta:Zt,over:Wt},ot===Oi.DragEnd&&typeof cn=="function"&&await Promise.resolve(cn(ln))&&(ot=Oi.DragCancel)}L.current=null,cc.unstable_batchedUpdates(()=>{x({type:ot}),P(dh.Uninitialized),Be(null),ne(null),ce(null),Re.current=null;const cn=ot===Oi.DragEnd?"onDragEnd":"onDragCancel";if(ln){const ct=ue.current[cn];ct?.(ln),S({type:cn,event:ln})}})}}},[F]),ze=y.useCallback((Ze,Ie)=>(ke,Ve)=>{const rt=ke.nativeEvent,Qe=F.get(Ve);if(L.current!==null||!Qe||rt.dndKit||rt.defaultPrevented)return;const Te={active:Qe};Ze(ke,Ie.options,Te)===!0&&(rt.dndKit={capturedBy:Ie.sensor},L.current=Ve,We(ke,Ie))},[F,We]),st=wnt(u,ze);Ant(u),Su(()=>{B&&C===dh.Initializing&&P(dh.Initialized)},[B,C]),y.useEffect(()=>{const{onDragMove:Ze}=ue.current,{active:Ie,activatorEvent:ke,collisions:Ve,over:rt}=O.current;if(!Ie||!ke)return;const Qe={active:Ie,activatorEvent:ke,collisions:Ve,delta:{x:ye.x,y:ye.y},over:rt};cc.unstable_batchedUpdates(()=>{Ze?.(Qe),S({type:"onDragMove",event:Qe})})},[ye.x,ye.y]),y.useEffect(()=>{const{active:Ze,activatorEvent:Ie,collisions:ke,droppableContainers:Ve,scrollAdjustedTranslate:rt}=O.current;if(!Ze||L.current==null||!Ie||!rt)return;const{onDragOver:Qe}=ue.current,Te=Ve.get(ge),tt=Te&&Te.rect.current?{id:Te.id,rect:Te.rect.current,data:Te.data,disabled:Te.disabled}:null,ot={active:Ze,activatorEvent:Ie,collisions:ke,delta:{x:rt.x,y:rt.y},over:tt};cc.unstable_batchedUpdates(()=>{Be(tt),Qe?.(ot),S({type:"onDragOver",event:ot})})},[ge]),Su(()=>{O.current={activatorEvent:Y,active:z,activeNode:$,collisionRect:_e,collisions:xe,droppableRects:pe,draggableNodes:F,draggingNode:G,draggingNodeRect:K,droppableContainers:M,over:Me,scrollableAncestors:fe,scrollAdjustedTranslate:ye},I.current={initial:K,translated:_e}},[z,$,xe,_e,F,G,K,pe,M,Me,fe,ye]),bnt({...j,delta:_,draggingRect:_e,pointerCoordinates:q,scrollableAncestors:fe,scrollableAncestorRects:de});const Ee=y.useMemo(()=>({active:z,activeNode:$,activeNodeRect:B,activatorEvent:Y,collisions:xe,containerNodeRect:W,dragOverlay:U,draggableNodes:F,droppableContainers:M,droppableRects:pe,over:Me,measureDroppableContainers:he,scrollableAncestors:fe,scrollableAncestorRects:de,measuringConfiguration:le,measuringScheduled:we,windowRect:te}),[z,$,B,Y,xe,W,U,F,M,pe,Me,he,fe,de,le,we,te]),it=y.useMemo(()=>({activatorEvent:Y,activators:st,active:z,activeNodeRect:B,ariaDescribedById:{draggable:oe},dispatch:x,draggableNodes:F,over:Me,measureDroppableContainers:he}),[Y,st,z,B,x,oe,F,Me,he]);return pa.createElement(pce.Provider,{value:k},pa.createElement(rj.Provider,{value:it},pa.createElement(Ace.Provider,{value:Ee},pa.createElement(jce.Provider,{value:Oe},d)),pa.createElement(Unt,{disabled:l?.restoreFocus===!1})),pa.createElement(qtt,{...l,hiddenTextDescribedById:oe}));function Ce(){const Ze=Z?.autoScrollEnabled===!1,Ie=typeof c=="object"?c.enabled===!1:c===!1,ke=T&&!Ze&&!Ie;return typeof c=="object"?{...c,enabled:ke}:{enabled:ke}}}),$nt=y.createContext(null),rX="button",Vnt="Draggable";function Gnt(t){let{id:e,data:n,disabled:a=!1,attributes:i}=t;const s=y_(Vnt),{activators:o,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:m,over:p}=y.useContext(rj),{role:f=rX,roleDescription:g="draggable",tabIndex:w=0}=i??{},b=c?.id===e,x=y.useContext(b?jce:$nt),[S,k]=mT(),[C,P]=mT(),T=jnt(o,e),A=yS(n);Su(()=>(m.set(e,{id:e,key:s,node:S,activatorNode:C,data:A}),()=>{const _=m.get(e);_&&_.key===s&&m.delete(e)}),[m,e]);const F=y.useMemo(()=>({role:f,tabIndex:w,"aria-disabled":a,"aria-pressed":b&&f===rX?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[a,f,w,b,g,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:F,isDragging:b,listeners:a?void 0:T,node:S,over:p,setNodeRef:k,setActivatorNodeRef:P,transform:x}}function Wnt(){return y.useContext(Ace)}const Knt="Droppable",Qnt={timeout:25};function Ynt(t){let{data:e,disabled:n=!1,id:a,resizeObserverConfig:i}=t;const s=y_(Knt),{active:o,dispatch:l,over:c,measureDroppableContainers:d}=y.useContext(rj),u=y.useRef({disabled:n}),m=y.useRef(!1),p=y.useRef(null),f=y.useRef(null),{disabled:g,updateMeasurementsFor:w,timeout:b}={...Qnt,...i},x=yS(w??a),S=y.useCallback(()=>{if(!m.current){m.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(x.current)?x.current:[x.current]),f.current=null},b)},[b]),k=nj({callback:S,disabled:g||!o}),C=y.useCallback((F,_)=>{k&&(_&&(k.unobserve(_),m.current=!1),F&&k.observe(F))},[k]),[P,T]=mT(C),A=yS(e);return y.useEffect(()=>{!k||!P.current||(k.disconnect(),m.current=!1,k.observe(P.current))},[P,k]),y.useEffect(()=>(l({type:Oi.RegisterDroppable,element:{id:a,key:s,disabled:n,node:P,rect:p,data:A}}),()=>l({type:Oi.UnregisterDroppable,key:s,id:a})),[a]),y.useEffect(()=>{n!==u.current.disabled&&(l({type:Oi.SetDroppableDisabled,id:a,key:s,disabled:n}),u.current.disabled=n)},[a,s,n,l]),{active:o,rect:p,isOver:c?.id===a,node:P,over:c,setNodeRef:T}}function aj(t,e,n){const a=t.slice();return a.splice(n<0?a.length+n:n,0,a.splice(e,1)[0]),a}function Xnt(t,e){return t.reduce((n,a,i)=>{const s=e.get(a);return s&&(n[i]=s),n},Array(t.length))}function oN(t){return t!==null&&t>=0}function Znt(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 Jnt(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const oU=t=>{let{rects:e,activeIndex:n,overIndex:a,index:i}=t;const s=aj(e,a,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}},lN={scaleX:1,scaleY:1},ert=t=>{var e;let{activeIndex:n,activeNodeRect:a,index:i,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:a;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,...lN}:null}const c=trt(s,i,n);return i>n&&i<=o?{x:0,y:-l.height-c,...lN}:i<n&&i>=o?{x:0,y:l.height+c,...lN}:{x:0,y:0,...lN}};function trt(t,e,n){const a=t[e],i=t[e-1],s=t[e+1];return a?n<e?i?a.top-(i.top+i.height):s?s.top-(a.top+a.height):0:s?s.top-(a.top+a.height):i?a.top-(i.top+i.height):0:0}const Ece="Sortable",Dce=pa.createContext({activeIndex:-1,containerId:Ece,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:oU,disabled:{draggable:!1,droppable:!1}});function Fce(t){let{children:e,id:n,items:a,strategy:i=oU,disabled:s=!1}=t;const{active:o,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=Wnt(),m=y_(Ece,n),p=l.rect!==null,f=y.useMemo(()=>a.map(T=>typeof T=="object"&&"id"in T?T.id:T),[a]),g=o!=null,w=o?f.indexOf(o.id):-1,b=d?f.indexOf(d.id):-1,x=y.useRef(f),S=!Znt(f,x.current),k=b!==-1&&w===-1||S,C=Jnt(s);Su(()=>{S&&g&&u(f)},[S,f,g,u]),y.useEffect(()=>{x.current=f},[f]);const P=y.useMemo(()=>({activeIndex:w,containerId:m,disabled:C,disableTransforms:k,items:f,overIndex:b,useDragOverlay:p,sortedRects:Xnt(f,c),strategy:i}),[w,m,C.draggable,C.droppable,k,f,b,c,p,i]);return pa.createElement(Dce.Provider,{value:P},e)}const nrt=t=>{let{id:e,items:n,activeIndex:a,overIndex:i}=t;return aj(n,a,i).indexOf(e)},rrt=t=>{let{containerId:e,isSorting:n,wasDragging:a,index:i,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:d}=t;return!d||!a||l!==s&&i===o?!1:n?!0:o!==i&&e===c},art={duration:200,easing:"ease"},Lce="transform",irt=qy.Transition.toString({property:Lce,duration:0,easing:"linear"}),srt={roleDescription:"sortable"};function ort(t){let{disabled:e,index:n,node:a,rect:i}=t;const[s,o]=y.useState(null),l=y.useRef(n);return Su(()=>{if(!e&&n!==l.current&&a.current){const c=i.current;if(c){const d=fv(a.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,a,i]),y.useEffect(()=>{s&&o(null)},[s]),s}function Rce(t){let{animateLayoutChanges:e=rrt,attributes:n,disabled:a,data:i,getNewIndex:s=nrt,id:o,strategy:l,resizeObserverConfig:c,transition:d=art}=t;const{items:u,containerId:m,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:w,overIndex:b,useDragOverlay:x,strategy:S}=y.useContext(Dce),k=lrt(a,f),C=u.indexOf(o),P=y.useMemo(()=>({sortable:{containerId:m,index:C,items:u},...i}),[m,i,C,u]),T=y.useMemo(()=>u.slice(u.indexOf(o)),[u,o]),{rect:A,node:F,isOver:_,setNodeRef:M}=Ynt({id:o,data:P,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:T,...c}}),{active:H,activatorEvent:I,activeNodeRect:z,attributes:L,setNodeRef:Z,listeners:ne,isDragging:Y,over:ce,setActivatorNodeRef:ue,transform:oe}=Gnt({id:o,data:P,attributes:{...srt,...n},disabled:k.draggable}),Q=jtt(M,Z),le=!!H,pe=le&&!g&&oN(p)&&oN(b),he=!x&&Y,we=he&&pe?oe:null,J=pe?we??(l??S)({rects:w,activeNodeRect:z,activeIndex:p,overIndex:b,index:C}):null,j=oN(p)&&oN(b)?s({id:o,items:u,activeIndex:p,overIndex:b}):C,E=H?.id,B=y.useRef({activeId:E,items:u,newIndex:j,containerId:m}),W=u!==B.current.items,O=e({active:H,containerId:m,isDragging:Y,isSorting:le,id:o,index:C,items:u,newIndex:B.current.newIndex,previousItems:B.current.items,previousContainerId:B.current.containerId,transition:d,wasDragging:B.current.activeId!=null}),ie=ort({disabled:!O,index:C,node:F,rect:A});return y.useEffect(()=>{le&&B.current.newIndex!==j&&(B.current.newIndex=j),m!==B.current.containerId&&(B.current.containerId=m),u!==B.current.items&&(B.current.items=u)},[le,j,m,u]),y.useEffect(()=>{if(E===B.current.activeId)return;if(E!=null&&B.current.activeId==null){B.current.activeId=E;return}const G=setTimeout(()=>{B.current.activeId=E},50);return()=>clearTimeout(G)},[E]),{active:H,activeIndex:p,attributes:L,data:P,rect:A,index:C,newIndex:j,items:u,isOver:_,isSorting:le,isDragging:Y,listeners:ne,node:F,overIndex:b,over:ce,setNodeRef:Q,setActivatorNodeRef:ue,setDroppableNodeRef:M,setDraggableNodeRef:Z,transform:ie??J,transition:U()};function U(){if(ie||W&&B.current.newIndex===C)return irt;if(!(he&&!aU(I)||!d)&&(le||O))return qy.Transition.toString({...d,property:Lce})}}function lrt(t,e){var n,a;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(a=t?.droppable)!=null?a:e.droppable}}function gT(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 crt=[Tr.Down,Tr.Right,Tr.Up,Tr.Left],Ice=(t,e)=>{let{context:{active:n,collisionRect:a,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(crt.includes(t.code)){if(t.preventDefault(),!n||!a)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 Tr.Down:a.top<p.top&&c.push(m);break;case Tr.Up:a.top>p.top&&c.push(m);break;case Tr.Left:a.left>p.left&&c.push(m);break;case Tr.Right:a.left<p.left&&c.push(m);break}});const d=Vtt({collisionRect:a,droppableRects:i,droppableContainers:c});let u=bce(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,g=p?.node.current;if(g&&f&&m&&p){const b=JA(g).some((T,A)=>l[A]!==T),x=Oce(m,p),S=drt(m,p),k=b||!x?{x:0,y:0}:{x:S?a.width-f.width:0,y:S?a.height-f.height:0},C={x:f.left,y:f.top};return k.x&&k.y?C:vS(C,k)}}}};function Oce(t,e){return!gT(t)||!gT(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function drt(t,e){return!gT(t)||!gT(e)||!Oce(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}function urt(t){return t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function mrt({activeCount:t,pendingCount:e,totalTime:n,totalWeight:a,historyCount:i,t:s}){const o=[{icon:hs,value:t,label:s("queue.summary.printing"),color:"text-blue-400"},{icon:Zn,value:e,label:s("queue.summary.queued"),color:"text-yellow-400"},{icon:Zd,value:cs(n),label:s("queue.summary.totalTime"),color:"text-bambu-green"},{icon:XZ,value:urt(a),label:s("queue.summary.totalWeight"),color:"text-purple-400"},{icon:xr,value:i,label:s("queue.summary.history"),color:"text-bambu-gray"}];return r.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)=>r.jsxs("div",{className:"flex items-center gap-3",children:[c>0&&r.jsx("span",{className:"hidden sm:block text-bambu-dark-tertiary",children:"|"}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(l.icon,{className:`w-4 h-4 ${l.color}`}),r.jsx("span",{className:"text-sm font-semibold text-white",children:l.value}),r.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:l.label})]})]},c))})}const aX={completed:{icon:xr,color:"text-emerald-400",border:"border-l-emerald-500"},failed:{icon:$r,color:"text-red-400",border:"border-l-red-500"},skipped:{icon:PT,color:"text-orange-400",border:"border-l-gray-500"},cancelled:{icon:Vt,color:"text-gray-400",border:"border-l-gray-500"}};function prt({item:t,onRequeue:e,onRemove:n,timeFormat:a="system",hasPermission:i,canModify:s,t:o}){const l=aX[t.status]||aX.cancelled,c=l.icon,d=t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,u=t.archive_thumbnail?ae.getArchiveThumbnail(t.archive_id):t.library_file_thumbnail?ae.getLibraryFileThumbnailUrl(t.library_file_id):null,m=t.completed_at||t.created_at;return r.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:[r.jsx(c,{className:`w-4 h-4 shrink-0 ${l.color}`}),r.jsx("div",{className:"w-8 h-8 shrink-0 bg-bambu-dark rounded overflow-hidden",children:u?r.jsx("img",{src:u,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(ca,{className:"w-4 h-4"})})}),r.jsx("span",{className:"text-sm text-white font-medium truncate min-w-0 flex-1",children:d}),t.printer_name&&r.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[r.jsx(hr,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate max-w-[100px]",children:t.printer_name})]}),t.print_time_seconds&&r.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zd,{className:"w-3 h-3"}),cs(t.print_time_seconds)]}),r.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:Eh(m,a,o)}),r.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[r.jsx(je,{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:r.jsx(tr,{className:"w-3.5 h-3.5"})}),r.jsx(je,{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:r.jsx(en,{className:"w-3.5 h-3.5"})})]})]})}function M0(t){const e=new Date(t);return e.setHours(0,0,0,0),e}function hrt(t){return t.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}function frt(t){return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function grt(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 a=Math.floor(n/60),i=n%60;return i===0?e("queue.timeline.time.hoursLeft",{hours:a}):e("queue.timeline.time.hoursMinutesLeft",{hours:a,minutes:i})}function brt(t){const e=new Date;return e.setHours(t,0,0,0),e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function xrt({event:t,now:e,onItemClick:n,t:a}){const i=t.item,s=i.archive_name||i.library_file_name||a("common.unknown"),o=i.printer_name||(i.target_model?`${a("queue.filter.any")} ${i.target_model}`:a("queue.timeline.unassigned")),l=t.type==="printing",c=t.estimatedEnd.getTime()-e.getTime(),d=i.archive_thumbnail?ae.getArchiveThumbnail(i.archive_id):i.library_file_thumbnail?ae.getLibraryFileThumbnailUrl(i.library_file_id):null;return r.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
  8317. ${l?"border-blue-500/30":"border-bambu-dark-tertiary"}`,onClick:()=>n(i),children:[r.jsx("div",{className:`w-1 self-stretch rounded-full shrink-0 ${l?"bg-blue-500":"bg-bambu-green/40"}`}),r.jsx("div",{className:"w-10 h-10 shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:d?r.jsx("img",{src:d,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(ca,{className:"w-5 h-5"})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:s}),r.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[r.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",children:[r.jsx(hr,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:o})]}),i.print_time_seconds&&r.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray",children:cs(i.print_time_seconds)})]}),l&&t.progress!=null&&r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[r.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:r.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all",style:{width:`${t.progress}%`}})}),r.jsxs("span",{className:"text-xs text-blue-400 shrink-0",children:[Math.round(t.progress),"%"]})]})]}),r.jsxs("div",{className:"text-right shrink-0",children:[r.jsx("p",{className:"text-sm text-white font-medium",children:frt(t.estimatedEnd)}),r.jsx("p",{className:`text-xs mt-0.5 ${l?"text-blue-400":"text-bambu-gray"}`,children:grt(c,a)})]})]})}function yrt({queueItems:t,printerStatuses:e,onItemClick:n,t:a}){const[i,s]=y.useState(()=>M0(new Date)),[o,l]=y.useState(()=>new Date),[c,d]=y.useState("all");y.useEffect(()=>{const F=setInterval(()=>l(new Date),6e4);return()=>clearInterval(F)},[]);const u=o.getTime(),m=M0(new Date).getTime()===M0(i).getTime(),p=y.useMemo(()=>{const F=[],_=new Map;for(const M of t)if(M.status==="printing"){const H=M.printer_id!=null?e[M.printer_id]:void 0,I=Yn(M.started_at)||new Date;let z;if(H?.remaining_time!=null&&H.remaining_time>0)z=new Date(u+H.remaining_time*60*1e3);else if(M.print_time_seconds){const L=H?.progress||0,Z=Math.max(0,1-L/100);z=new Date(u+M.print_time_seconds*Z*1e3)}else z=new Date(u+36e5);F.push({item:M,estimatedStart:I,estimatedEnd:z,progress:H?.progress??void 0,type:"printing"})}else if(M.status==="pending"){const H=M.printer_id;_.has(H)||_.set(H,[]),_.get(H).push(M)}for(const[M,H]of _){H.sort((z,L)=>z.position-L.position);let I=u;for(const z of F)z.item.printer_id===M&&z.type==="printing"&&(I=Math.max(I,z.estimatedEnd.getTime()));for(const z of H){const L=Yn(z.scheduled_time);if(L){const ce=Date.now()+15552e6;L.getTime()<=ce&&(I=Math.max(I,L.getTime()))}const Z=(z.print_time_seconds||3600)*1e3,ne=new Date(I),Y=new Date(I+Z);F.push({item:z,estimatedStart:ne,estimatedEnd:Y,type:"queued"}),I=Y.getTime()}}return F.sort((M,H)=>M.estimatedEnd.getTime()-H.estimatedEnd.getTime()),F},[t,e,u]),f=M0(i).getTime(),g=f+1440*60*1e3-1,w=y.useMemo(()=>p.filter(F=>{const _=F.estimatedEnd.getTime();return _<f||_>g?!1:c==="printing"?F.type==="printing":c==="queued"?F.type==="queued":!0}),[p,f,g,c]),b=y.useMemo(()=>{const F=new Map;for(const _ of w){const M=_.estimatedEnd.getHours();F.has(M)||F.set(M,[]),F.get(M).push(_)}return Array.from(F.entries()).sort(([_],[M])=>_-M)},[w]),x=p.filter(F=>F.type==="printing"&&F.estimatedEnd.getTime()>=f&&F.estimatedEnd.getTime()<=g).length,S=p.filter(F=>F.type==="queued"&&F.estimatedEnd.getTime()>=f&&F.estimatedEnd.getTime()<=g).length,k=y.useMemo(()=>{let F=0;for(const _ of p)F=Math.max(F,_.estimatedEnd.getTime());return F>0?new Date(F):null},[p]),C=()=>s(M0(new Date)),P=()=>{const F=new Date(i);F.setDate(F.getDate()-1),s(F)},T=()=>{const F=new Date(i);F.setDate(F.getDate()+1),s(F)},A=[{key:"all",label:a("queue.timeline.filterAll"),count:x+S},{key:"printing",label:a("queue.timeline.filterPrinting"),count:x},{key:"queued",label:a("queue.timeline.filterQueued"),count:S}];return r.jsxs("div",{children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:P,className:"p-1.5",children:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsx("span",{className:"text-sm font-medium text-white min-w-[140px] text-center",children:hrt(i)}),r.jsx(je,{variant:"ghost",size:"sm",onClick:T,className:"p-1.5",children:r.jsx(qa,{className:"w-4 h-4"})}),!m&&r.jsx(je,{variant:"ghost",size:"sm",onClick:C,className:"text-xs text-bambu-green",children:a("queue.timeline.day.today")})]}),k&&r.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1.5",children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),a("queue.timeline.allDoneBy",{time:k.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]})]}),r.jsx("div",{className:"flex gap-2 mb-5",children:A.map(F=>r.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&&r.jsx("span",{className:`ml-1.5 text-xs ${c===F.key?"text-white/70":"text-bambu-gray"}`,children:F.count})]},F.key))}),b.length>0?r.jsx("div",{className:"space-y-6",children:b.map(([F,_])=>r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[r.jsx("span",{className:"text-xs font-medium text-bambu-gray w-14 shrink-0",children:brt(F)}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),r.jsx("div",{className:"space-y-2 sm:ml-[68px]",children:_.map(M=>r.jsx(xrt,{event:M,now:o,onItemClick:n,t:a},M.item.id))})]},F))}):r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(ca,{className:"w-12 h-12 mb-3 opacity-30"}),r.jsx("p",{className:"text-sm",children:a("queue.timeline.noData")})]})]})}function vrt(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function wrt({status:t,waitingReason:e,printerState:n,t:a}){if(t==="pending"&&e)return r.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:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),a("queue.status.waiting")]});if(t==="printing"&&n==="PAUSE")return r.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:[r.jsx(DS,{className:"w-3.5 h-3.5"}),a("queue.status.paused")]});const i={pending:{icon:Zn,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:a("queue.status.pending")},printing:{icon:hs,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:a("queue.status.printing")},completed:{icon:xr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:a("queue.status.completed")},failed:{icon:$r,color:"text-status-error bg-status-error/10 border-status-error/20",label:a("queue.status.failed")},skipped:{icon:PT,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:a("queue.status.skipped")},cancelled:{icon:Vt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:a("queue.status.cancelled")}},{icon:s,color:o,label:l}=i[t];return r.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[r.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function Srt({selectedCount:t,printers:e,onSave:n,onClose:a,isSaving:i,canControlPrinter:s,t:o}){const[l,c]=y.useState("unchanged"),[d,u]=y.useState("unchanged"),[m,p]=y.useState("unchanged"),[f,g]=y.useState("unchanged"),[w,b]=y.useState("unchanged"),[x,S]=y.useState("unchanged"),[k,C]=y.useState("unchanged"),[P,T]=y.useState("unchanged"),[A,F]=y.useState("unchanged"),[_,M]=y.useState("unchanged"),H=()=>{const z={};l!=="unchanged"&&(z.printer_id=l),d!=="unchanged"&&(z.manual_start=d),m!=="unchanged"&&(z.auto_off_after=m),f!=="unchanged"&&(z.require_previous_success=f),w!=="unchanged"&&(z.bed_levelling=w),x!=="unchanged"&&(z.flow_cali=x),k!=="unchanged"&&(z.vibration_cali=k),P!=="unchanged"&&(z.layer_inspect=P),A!=="unchanged"&&(z.timelapse=A),_!=="unchanged"&&(z.use_ams=_),n(z)},I=l!=="unchanged"||d!=="unchanged"||m!=="unchanged"||f!=="unchanged"||w!=="unchanged"||x!=="unchanged"||k!=="unchanged"||P!=="unchanged"||A!=="unchanged"||_!=="unchanged";return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("queue.bulkEdit.title",{count:t})}),r.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:o("queue.bulkEdit.description")}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printer")}),r.jsxs("select",{value:l===null?"null":l==="unchanged"?"unchanged":String(l),onChange:z=>{const L=z.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:[r.jsx("option",{value:"unchanged",children:o("queue.bulkEdit.noChange")}),r.jsx("option",{value:"null",children:o("queue.filter.unassigned")}),e.map(z=>r.jsx("option",{value:z.id,children:z.name},z.id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.queueOptions")}),r.jsxs("div",{className:"space-y-2",children:[r.jsx(cm,{label:o("queue.bulkEdit.staged"),value:d,onChange:u,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.autoPowerOff"),value:m,onChange:p,disabled:!s,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.requirePrevious"),value:f,onChange:g,t:o})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:o("queue.bulkEdit.printOptions")}),r.jsxs("div",{className:"space-y-2",children:[r.jsx(cm,{label:o("queue.bulkEdit.bedLevelling"),value:w,onChange:b,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.flowCalibration"),value:x,onChange:S,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.vibrationCalibration"),value:k,onChange:C,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.layerInspection"),value:P,onChange:T,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.timelapse"),value:A,onChange:F,t:o}),r.jsx(cm,{label:o("queue.bulkEdit.useAms"),value:_,onChange:M,t:o})]})]})]}),r.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(je,{variant:"secondary",onClick:a,children:o("common.cancel")}),r.jsx(je,{onClick:H,disabled:!I||i,children:o(i?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function cm({label:t,value:e,onChange:n,disabled:a,t:i}){return r.jsxs("div",{className:`flex items-center justify-between py-1 ${a?"opacity-50":""}`,children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:t}),r.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[r.jsx("button",{onClick:()=>n("unchanged"),disabled:a,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:"—"}),r.jsx("button",{onClick:()=>n(!1),disabled:a,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")}),r.jsx("button",{onClick:()=>n(!0),disabled:a,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 iX({item:t,position:e,onEdit:n,onCancel:a,onRemove:i,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:d=!1,onToggleSelect:u,hasPermission:m,canModify:p,printerState:f,t:g}){const{data:w}=Xe({queryKey:["printerStatus",t.printer_id],queryFn:()=>ae.getPrinterStatus(t.printer_id),refetchInterval:3e4,enabled:t.printer_id!=null&&f==="printing"}),b=!!t.library_file_id&&!t.archive_id,{data:x}=Xe({queryKey:["archive-plates",t.archive_id],queryFn:()=>ae.getArchivePlates(t.archive_id),enabled:!!t.archive_id&&!b&&!t.archive_deleted}),{data:S}=Xe({queryKey:["library-file-plates",t.library_file_id],queryFn:()=>ae.getLibraryFilePlates(t.library_file_id),enabled:b&&!!t.library_file_id}),k=b?S:x,C=k?.plates??[],P=m("queue:reorder"),{attributes:T,listeners:A,setNodeRef:F,transform:_,transition:M,isDragging:H}=Rce({id:t.id,disabled:t.status!=="pending"||!P}),I={transform:qy.Transform.toString(_),transition:M},z=t.status==="printing",L=t.status==="pending",Z=["completed","failed","skipped","cancelled"].includes(t.status),ne=L&&u;return r.jsxs("div",{ref:F,style:I,className:`
  8318. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  8319. border-l-[3px] ${z?"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"}
  8320. ${H?"opacity-50 scale-[1.02] shadow-xl z-50":""}
  8321. ${z?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""}
  8322. ${d&&ne?"sm:border-bambu-dark-tertiary border-bambu-green/40":""}
  8323. ${!d&&!z?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""}
  8324. ${ne?"sm:cursor-default":""}
  8325. `,onClick:ne?()=>{window.innerWidth<640&&u()}:void 0,children:[ne&&d&&r.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),r.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[L&&u&&r.jsx("button",{onClick:Y=>{Y.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&&r.jsx(Ar,{className:"w-4 h-4"})}),L?r.jsx("div",{...T,...A,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:r.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?r.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]}):r.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),r.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?r.jsx("img",{src:t.plate_id!=null?ae.getArchivePlateThumbnail(t.archive_id,t.plate_id):ae.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?r.jsx("img",{src:t.plate_id!=null?ae.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ae.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(ca,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.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}`,(k?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${C.find(Y=>Y.index===t.plate_id)?.name||g("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?r.jsx(Es,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:g("queue.viewArchive"),children:r.jsx(zr,{className:"w-3.5 h-3.5"})}):t.library_file_id?r.jsx(Es,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:g("queue.viewInFileManager"),children:r.jsx(zr,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&r.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})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[r.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:[r.jsx(hr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),r.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${g("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?g("queue.filter.unassigned"):t.printer_name||`${g("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[r.jsx(Zd,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),cs(t.print_time_seconds)]}),t.filament_used_grams&&r.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[r.jsx(XZ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),vrt(t.filament_used_grams)]}),t.created_by_username&&r.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:g("queue.addedBy",{name:t.created_by_username}),children:[r.jsx(Gm,{className:"w-3.5 h-3.5"}),t.created_by_username]}),L&&!t.manual_start&&r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Yn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?g?.("queue.time.overdue")??"Overdue":Eh(t.scheduled_time,c,g):g?.("queue.time.asap")??"ASAP"]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&r.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:[r.jsx(UZ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.staged")]}),t.require_previous_success&&r.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:g("queue.badges.requiresPrevious")}),t.auto_off_after&&r.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:[r.jsx(_u,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.autoPowerOff")]}),t.gcode_injection&&r.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:[r.jsx(Ky,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.gcodeInjection")]})]}),z&&w&&(()=>{const Y=w.state==="RUNNING"||w.state==="PAUSE",ce=Y&&w.progress||0,ue=Y?w.remaining_time:null,oe=Y?w.layer_num:null,Q=Y?w.total_layers:null;return r.jsxs("div",{className:"mt-2 sm:mt-3",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[r.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:r.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${ce}%`}})}),r.jsxs("span",{className:"text-white",children:[Math.round(ce),"%"]})]}),r.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:[ue!=null&&ue>0&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),cs(ue*60)]}),r.jsxs("span",{className:"text-bambu-green font-medium",title:g("printers.estimatedCompletion"),children:["ETA ",MO(ue,c,g)]})]}),oe!=null&&Q!=null&&Q>0&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(ca,{className:"w-3 h-3"}),oe,"/",Q]})]})]})})(),t.waiting_reason&&t.status==="pending"&&r.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[r.jsx(Ha,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),r.jsx("span",{children:t.waiting_reason})]}),t.error_message&&r.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),t.error_message]})]}),r.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:Y=>Y.stopPropagation(),children:[r.jsx(wrt,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:g}),r.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[z&&r.jsx(je,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?g("queue.actions.stopPrint"):g("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:r.jsx(Sge,{className:"w-4 h-4"})}),L&&r.jsxs(r.Fragment,{children:[t.manual_start&&r.jsx(je,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?g("queue.actions.startPrint"):g("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:r.jsx(hs,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?g("common.edit"):g("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:a,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?g("common.cancel"):g("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),Z&&r.jsxs(r.Fragment,{children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?g("queue.actions.requeue"):g("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:r.jsx(tr,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?g("common.remove"):g("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:r.jsx(en,{className:"w-4 h-4"})})]})]})]})]})]})}function _rt(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a,hasAnyPermission:i,canModify:s}=dr(),[o,l]=y.useState(null),[c,d]=y.useState(""),[u,m]=y.useState(""),[p,f]=y.useState(!1),[g,w]=y.useState(null),[b,x]=y.useState(null),[S,k]=y.useState(null),[C,P]=y.useState([]),[T,A]=y.useState(!1),[F,_]=y.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[M,H]=y.useState(()=>{const xe=localStorage.getItem("queue.historySortAsc");return xe!==null?xe==="true":!1}),[I,z]=y.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,Z]=y.useState(()=>{const xe=localStorage.getItem("queue.pendingSortAsc");return xe!==null?xe==="true":!0}),[ne,Y]=y.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[ce,ue]=y.useState(()=>localStorage.getItem("queue.viewMode")||"list");y.useEffect(()=>{localStorage.setItem("queue.historySortBy",F)},[F]),y.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(M))},[M]),y.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",I)},[I]),y.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),y.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ne))},[ne]),y.useEffect(()=>{localStorage.setItem("queue.viewMode",ce)},[ce]);const oe=hce(hT(tj,{activationConstraint:{distance:8}}),hT(ej,{coordinateGetter:Ice})),{data:Q}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),le=Q?.time_format||"system",{data:pe,isLoading:he}=Xe({queryKey:["queue",o,c],queryFn:()=>ae.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:we}=Xe({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),$=lt({mutationFn:xe=>ae.updateSettings({queue_shortest_first:xe}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),J=lt({mutationFn:xe=>ae.cancelQueueItem(xe),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),j=lt({mutationFn:xe=>ae.removeFromQueue(xe),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),E=lt({mutationFn:xe=>ae.stopQueueItem(xe),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),B=lt({mutationFn:xe=>ae.startQueueItem(xe),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),W=lt({mutationFn:xe=>ae.reorderQueue(xe),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),O=lt({mutationFn:async()=>{const xe=pe?.filter(ge=>["completed","failed","skipped","cancelled"].includes(ge.status))||[];for(const ge of xe)await ae.removeFromQueue(ge.id);return xe.length},onSuccess:xe=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:xe}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),ie=lt({mutationFn:xe=>ae.bulkUpdateQueue(xe),onSuccess:xe=>{e.invalidateQueries({queryKey:["queue"]}),P([]),A(!1),n(xe.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),U=lt({mutationFn:async xe=>{for(const ge of xe)await ae.cancelQueueItem(ge);return xe.length},onSuccess:xe=>{e.invalidateQueries({queryKey:["queue"]}),P([]),n(t("queue.toast.bulkCancelled",{count:xe}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=xe=>{P(ge=>ge.includes(xe)?ge.filter(Me=>Me!==xe):[...ge,xe])},K=y.useMemo(()=>{const xe=new Set;return we?.forEach(ge=>{ge.location&&xe.add(ge.location)}),pe?.forEach(ge=>{ge.target_location&&xe.add(ge.target_location)}),Array.from(xe).sort()},[we,pe]),X=y.useCallback(xe=>u?xe.target_location?xe.target_location===u:xe.printer_id?we?.find(Me=>Me.id===xe.printer_id)?.location===u:!1:!0,[u,we]),se=y.useMemo(()=>{let xe=pe?.filter(Me=>Me.status==="pending")||[];u&&(xe=xe.filter(X));const ge=Me=>{if(!Me.scheduled_time)return 0;const Be=Yn(Me.scheduled_time)?.getTime()??0,Fe=Date.now()+4320*60*60*1e3;return Be>Fe?0:Be};return Q?.queue_shortest_first?[...xe].sort((Me,Be)=>{const Fe=Me.printer_id??-(Me.target_model?.charCodeAt(0)??0),Oe=Be.printer_id??-(Be.target_model?.charCodeAt(0)??0);if(Fe!==Oe)return Fe-Oe;const Re=Me.been_jumped?1:0,We=Be.been_jumped?1:0;if(Re!==We)return We-Re;const ze=Me.print_time_seconds??1/0,st=Be.print_time_seconds??1/0;return ze!==st?ze-st:Me.position-Be.position}):[...xe].sort((Me,Be)=>{let Fe;if(I==="name"){const Oe=Me.archive_name||Me.library_file_name||"",Re=Be.archive_name||Be.library_file_name||"";Fe=Oe.localeCompare(Re)}else I==="printer"?Fe=(Me.printer_name||"").localeCompare(Be.printer_name||""):I==="time"?Fe=ge(Me)-ge(Be):Fe=Me.position-Be.position;return L?Fe:-Fe})},[pe,I,L,X,u,Q?.queue_shortest_first]),te=()=>{const xe=se.map(ge=>ge.id);C.length===xe.length?P([]):P(xe)},fe=y.useMemo(()=>{let xe=pe?.filter(ge=>ge.status==="printing")||[];return u&&(xe=xe.filter(X)),xe},[pe,u,X]),de=y.useMemo(()=>{const xe=new Set;return fe.forEach(ge=>{ge.printer_id&&xe.add(ge.printer_id)}),Array.from(xe)},[fe]),me=rf({queries:de.map(xe=>({queryKey:["printerStatus",xe],queryFn:()=>ae.getPrinterStatus(xe),refetchInterval:5e3}))}),q=y.useMemo(()=>{const xe={};return de.forEach((ge,Me)=>{const Be=me[Me];Be?.data?.state&&(xe[ge]=Be.data.state)}),xe},[de,me]),R=y.useMemo(()=>{const xe={};return de.forEach((ge,Me)=>{const Be=me[Me];Be?.data&&(xe[ge]={progress:Be.data.progress??void 0,remaining_time:Be.data.remaining_time??void 0,state:Be.data.state??void 0})}),xe},[de,me]),re=y.useMemo(()=>{let xe=pe?.filter(ge=>["completed","failed","skipped","cancelled"].includes(ge.status))||[];return u&&(xe=xe.filter(X)),[...xe].sort((ge,Me)=>{let Be;if(F==="name"){const Fe=ge.archive_name||ge.library_file_name||"",Oe=Me.archive_name||Me.library_file_name||"";Be=Fe.localeCompare(Oe)}else F==="printer"?Be=(ge.printer_name||"").localeCompare(Me.printer_name||""):Be=(Yn(Me.completed_at||Me.created_at)?.getTime()??0)-(Yn(ge.completed_at||ge.created_at)?.getTime()??0);return M?-Be:Be})},[pe,F,M,X,u]),be=y.useMemo(()=>se.reduce((xe,ge)=>xe+(ge.print_time_seconds||0),0),[se]),ye=y.useMemo(()=>se.reduce((xe,ge)=>xe+(ge.filament_used_grams||0),0),[se]),_e=xe=>{const{active:ge,over:Me}=xe;if(!Me||ge.id===Me.id)return;const Be=se.findIndex(Oe=>Oe.id===ge.id),Fe=se.findIndex(Oe=>Oe.id===Me.id);if(Be!==-1&&Fe!==-1){const Re=aj(se,Be,Fe).map((We,ze)=>({id:We.id,position:ze+1}));W.mutate(Re)}};return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsx("div",{className:"flex items-center justify-between mb-8",children:r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Ew,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),r.jsx(mrt,{activeCount:fe.length,pendingCount:se.length,totalTime:be,totalWeight:ye,historyCount:re.length,t}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[r.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:xe=>{const ge=xe.target.value;l(ge==="unassigned"?-1:ge===""?null:Number(ge))},children:[r.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),r.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),we?.map(xe=>r.jsx("option",{value:xe.id,children:xe.name},xe.id))]}),r.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:xe=>d(xe.target.value),children:[r.jsx("option",{value:"",children:t("queue.filter.allStatus")}),r.jsx("option",{value:"pending",children:t("queue.status.pending")}),r.jsx("option",{value:"printing",children:t("queue.status.printing")}),r.jsx("option",{value:"completed",children:t("queue.status.completed")}),r.jsx("option",{value:"failed",children:t("queue.status.failed")}),r.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),r.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),K.length>0&&r.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:xe=>m(xe.target.value),children:[r.jsx("option",{value:"",children:t("queue.filter.allLocations")}),K.map(xe=>r.jsx("option",{value:xe,children:xe},xe))]}),r.jsx("div",{className:"hidden sm:block flex-1"}),re.length>0&&r.jsxs(je,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!a("queue:delete_all"),title:a("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[r.jsx(en,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),r.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[r.jsxs("div",{className:"hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsx("button",{className:`p-2 transition-colors ${ce==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ue("list"),title:t("queue.timeline.listView"),children:r.jsx(MS,{className:"w-4 h-4"})}),r.jsx("button",{className:`p-2 transition-colors ${ce==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ue("timeline"),title:t("queue.timeline.timelineView"),children:r.jsx(ige,{className:"w-4 h-4"})})]}),r.jsxs("button",{onClick:()=>{const xe=!(Q?.queue_shortest_first??!1);$.mutate(xe)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${Q?.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:[r.jsx(Bye,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Q?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]})]}),he?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):pe?.length===0?r.jsxs(At,{className:"p-12 text-center border-dashed",children:[r.jsx(wa,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),r.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),r.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):ce==="timeline"?r.jsx(yrt,{queueItems:pe||[],printerStatuses:R,onItemClick:xe=>{["completed","failed","skipped","cancelled"].includes(xe.status)?x(xe):xe.status==="pending"?w(xe):xe.status==="printing"&&k({type:"stop",item:xe})},t}):r.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[fe.length>0&&r.jsxs("div",{children:[r.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),r.jsx("div",{className:"space-y-2 sm:space-y-3",children:fe.map(xe=>r.jsx(iX,{item:xe,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>k({type:"stop",item:xe}),onRequeue:()=>{},onStart:()=>{},timeFormat:le,hasPermission:a,canModify:s,printerState:xe.printer_id?q[xe.printer_id]:null,t},xe.id))})]}),se.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[r.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Zn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),r.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:se.length}),")"]}),r.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.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:I,onChange:xe=>z(xe.target.value),children:[r.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),r.jsx("option",{value:"name",children:t("queue.sort.byName")}),r.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),r.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>Z(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?r.jsx(qm,{className:"w-4 h-4"}):r.jsx(qh,{className:"w-4 h-4"})})]})]}),r.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:[r.jsxs(je,{variant:"ghost",size:"sm",onClick:te,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[C.length===se.length&&se.length>0?r.jsx(gs,{className:"w-4 h-4 text-bambu-green"}):r.jsx(ro,{className:"w-4 h-4"}),C.length===se.length&&se.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),C.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:C.length})}),r.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>A(!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:[r.jsx(mi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>U.mutate(C),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:U.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:[r.jsx(Vt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),r.jsx(Mce,{sensors:oe,collisionDetection:xce,onDragEnd:_e,children:r.jsx(Fce,{items:se.map(xe=>xe.id),strategy:ert,children:r.jsx("div",{className:"space-y-2 sm:space-y-3",children:se.map((xe,ge)=>r.jsx(iX,{item:xe,position:ge+1,onEdit:()=>w(xe),onCancel:()=>k({type:"cancel",item:xe}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>B.mutate(xe.id),timeFormat:le,isSelected:C.includes(xe.id),onToggleSelect:()=>G(xe.id),hasPermission:a,canModify:s,t},xe.id))})})})]}),re.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[r.jsxs("button",{onClick:()=>Y(!ne),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ne?r.jsx(qa,{className:"w-4 h-4 sm:w-5 sm:h-5"}):r.jsx(Ln,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),r.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:re.length}),")"]})]}),!ne&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.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:xe=>_(xe.target.value),children:[r.jsx("option",{value:"date",children:t("queue.sort.byDate")}),r.jsx("option",{value:"name",children:t("queue.sort.byName")}),r.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>H(!M),title:t(M?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:M?r.jsx(qm,{className:"w-4 h-4"}):r.jsx(qh,{className:"w-4 h-4"})})]})]}),!ne&&r.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:re.slice(0,50).map(xe=>r.jsx(prt,{item:xe,onRemove:()=>k({type:"remove",item:xe}),onRequeue:()=>x(xe),timeFormat:le,hasPermission:a,canModify:s,t},xe.id))})]})]}),g&&r.jsx(bc,{mode:"edit-queue-item",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}`,queueItem:g,onClose:()=>w(null)}),b&&r.jsx(bc,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>x(null)}),S&&r.jsx(wn,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?J.mutate(S.item.id):S.type==="stop"?E.mutate(S.item.id):j.mutate(S.item.id),k(null)},onCancel:()=>k(null)}),p&&r.jsx(wn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:re.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{O.mutate(),f(!1)},onCancel:()=>f(!1)}),T&&r.jsx(Srt,{selectedCount:C.length,printers:we?.map(xe=>({id:xe.id,name:xe.name}))||[],onSave:xe=>{Object.keys(xe).length>0&&ie.mutate({item_ids:C,...xe})},onClose:()=>A(!1),isSaving:ie.isPending,canControlPrinter:a("printers:control"),t})]})}function krt({printDates:t,months:e=3}){const n=y.useRef(null),[a,i]=y.useState(0);y.useEffect(()=>{const S=n.current;if(!S)return;const k=new ResizeObserver(C=>{const P=C[0]?.contentRect.width||0;i(P)});return k.observe(S),()=>k.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=y.useMemo(()=>{const S={};t.forEach(H=>{const I=dE(H);I&&(S[I]=(S[I]||0)+1)});const k=new Date,C=new Date(k);C.setMonth(C.getMonth()-e),C.setDate(C.getDate()-C.getDay());const P=[],T=[];let A=[],F=-1;const _=new Date(C);let M=0;for(;_<=k;)_.getDay()===0&&A.length>0&&(P.push(A),A=[],M++),_.getMonth()!==F&&(T.push({month:_.toLocaleDateString("en-US",{month:"short"}),weekIndex:M}),F=_.getMonth()),A.push(new Date(_)),_.setDate(_.getDate()+1);return A.length>0&&P.push(A),{weeks:P,monthLabels:T,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),d=S=>{if(S===0)return"bg-bambu-dark";const k=S/c;return k<=.25?"bg-bambu-green/30":k<=.5?"bg-bambu-green/50":k<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,g=a-p-16,w=m>0?Math.floor((g-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,w)),x=b<=10?10:12;return r.jsx("div",{ref:n,className:"w-full flex justify-center",children:a>0&&r.jsxs("div",{children:[r.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:k},C)=>r.jsx("div",{className:"text-bambu-gray",style:{fontSize:x,marginLeft:C===0?0:`${(k-(o[C-1]?.weekIndex||0))*(b+f)-24}px`},children:S},C))}),r.jsxs("div",{className:"flex",style:{gap:f},children:[r.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((S,k)=>r.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:x,visibility:k%2===1?"visible":"hidden"},children:S},S))}),s.map((S,k)=>r.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(C=>{const P=S.find(_=>_.getDay()===C);if(!P)return r.jsx("div",{style:{width:b,height:b}},C);const T=dE(P),A=l[T]||0,F=T===dE(new Date);return r.jsx("div",{className:`rounded-sm ${d(A)} ${F?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${P.toLocaleDateString()}: ${A} print${A!==1?"s":""}`},C)})},k))]}),r.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:x},children:[r.jsx("span",{children:"Less"}),r.jsxs("div",{className:"flex",style:{gap:f},children:[r.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),r.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),r.jsx("span",{children:"More"})]})]})})}const sX=["weight","prints","time"];function bT({value:t,onChange:e,exclude:n}){const{t:a}=_t(),i={weight:a("stats.filamentByWeight"),prints:a("stats.filamentByPrints"),time:a("stats.filamentByTime")},s=n?sX.filter(o=>!n.includes(o)):sX;return r.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>r.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 bh(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 cN=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Nrt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],oX=["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 Crt({archives:t,currency:e="$",dateFrom:n,dateTo:a}){const{t:i}=_t(),[s,o]=y.useState("weight"),[l,c]=y.useState("weight"),d=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{const M=Yn(_.completed_at||_.created_at)||new Date,H=`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}-${String(M.getDate()).padStart(2,"0")}`,I=F.get(H)||{date:H,filament:0,cost:0,prints:0};I.filament+=_.filament_used_grams||0,I.cost+=_.cost||0,I.prints+=_.quantity||1,F.set(H,I)}),Array.from(F.values()).sort((_,M)=>_.date.localeCompare(M.date)).map(_=>({..._,dateLabel:new Date(_.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=y.useMemo(()=>{if(n&&a)return Math.max((new Date(a).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(_=>new Date(_.completed_at||_.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,n,a]),m=y.useMemo(()=>{if(u>7)return[];const F=new Map,_=u>1;return t.forEach(M=>{const H=Yn(M.completed_at||M.created_at)||new Date,I=H.getHours(),z=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,L=F.get(z)||{date:z,filament:0,cost:0,prints:0};L.filament+=M.filament_used_grams||0,L.cost+=M.cost||0,L.prints+=M.quantity||1,F.set(z,L)}),Array.from(F.values()).sort((M,H)=>M.date.localeCompare(H.date)).map(M=>{const[H,I]=M.date.split("T"),z=new Date(H),L=parseInt(I,10),Z=_?`${Nrt[z.getDay()]} ${oX[L]}`:oX[L];return{...M,dateLabel:Z}})},[t,u]),p=y.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(_=>{const M=new Date(_.date),H=new Date(M);H.setDate(M.getDate()-M.getDay());const I=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}`,z=F.get(I)||{week:I,filament:0,cost:0,prints:0};z.filament+=_.filament,z.cost+=_.cost,z.prints+=_.prints,F.set(I,z)}),Array.from(F.values()).sort((_,M)=>_.week.localeCompare(M.week)).map(_=>({date:_.week,dateLabel:`Week of ${new Date(_.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,..._}))},[d]),f=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{const H=(_.filament_type||"Unknown").split(", ");H.forEach(I=>{const z=(_.filament_used_grams||0)/H.length;F.set(I,(F.get(I)||0)+z)})}),Array.from(F.entries()).map(([_,M])=>({name:_,value:Math.round(M)})).sort((_,M)=>M.value-_.value)},[t]),g=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{(_.filament_type||"Unknown").split(", ").forEach(I=>{F.set(I,(F.get(I)||0)+1)})}),Array.from(F.entries()).map(([_,M])=>({name:_,value:M})).sort((_,M)=>M.value-_.value)},[t]),w=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{const H=(_.filament_type||"Unknown").split(", "),I=(_.actual_time_seconds||_.print_time_seconds||0)/H.length;H.forEach(z=>{F.set(z,(F.get(z)||0)+I)})}),Array.from(F.entries()).map(([_,M])=>({name:_,value:Math.round(M/3600*10)/10})).sort((_,M)=>M.value-_.value)},[t]),b=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{if(_.status!=="completed"&&_.status!=="failed")return;(_.filament_type||"Unknown").split(", ").forEach(H=>{const I=F.get(H)||{completed:0,failed:0};_.status==="completed"?I.completed++:I.failed++,F.set(H,I)})}),Array.from(F.entries()).filter(([,_])=>_.completed+_.failed>=2).map(([_,M])=>{const H=M.completed+M.failed,I=Math.round(M.completed/H*100);return{name:_,rate:I,total:H}}).sort((_,M)=>M.rate-_.rate)},[t]),x=y.useMemo(()=>{const F=new Map;return t.forEach(_=>{if(!_.filament_color)return;const M=_.filament_color.split(",").map(I=>I.trim()),H=(_.filament_used_grams||0)/M.length;M.forEach(I=>{const z=F.get(I)||{count:0,weight:0};z.count++,z.weight+=H,F.set(I,z)})}),Array.from(F.entries()).map(([_,M])=>({hex:_,value:l==="prints"?M.count:Math.round(M.weight)})).sort((_,M)=>M.value-_.value)},[t,l]),S=s==="weight"?f:s==="prints"?g:w,k=u<=7&&m.length>0?m:p,C=t.reduce((F,_)=>F+(_.filament_used_grams||0),0),P=t.reduce((F,_)=>F+(_.cost||0),0),T=t.reduce((F,_)=>F+(_.quantity||1),0),A=new Set(t.map(F=>F.printer_id).filter(Boolean)).size;return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),r.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:bh(C)})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[A," ",i("nav.printers").toLowerCase()]})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),r.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,P.toFixed(2)]})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("common.prints")]})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),r.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[T>0?(C/T).toFixed(0):0,"g"]})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,T>0?(P/T).toFixed(2):"0.00"," avg"]})]})]}),k.length>0?r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),r.jsx(nu,{width:"100%",height:250,children:r.jsxs(u5,{data:k,children:[r.jsx("defs",{children:r.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),r.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),r.jsx(Tm,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),r.jsx(Am,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),r.jsx(au,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),r.jsx(LA,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):r.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),r.jsx(bT,{value:s,onChange:o})]}),S.length>0?r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(nu,{width:160,height:160,children:r.jsxs(FK,{children:[r.jsx(XR,{data:S,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:S.map((F,_)=>r.jsx(Ly,{fill:cN[_%cN.length]},`cell-${_}`))}),r.jsx(au,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?bh(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),r.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:S.map((F,_)=>{const M=S.reduce((I,z)=>I+z.value,0),H=M>0?(F.value/M*100).toFixed(0):0;return r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:cN[_%cN.length]}}),r.jsx("span",{className:"text-white truncate flex-1",children:F.name}),r.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?bh(F.value):s==="time"?`${F.value}h`:F.value," · ",H,"%"]})]},F.name)})})]}):r.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?r.jsx("div",{className:"space-y-1.5",children:b.map(F=>r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:F.name}),r.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:r.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}%`}})}),r.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,"%"]}),r.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.name))}):r.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),r.jsx(bT,{value:l,onChange:c,exclude:["time"]})]}),x.length>0?(()=>{const F=x.reduce((_,M)=>_+M.value,0);return r.jsxs("div",{children:[r.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[r.jsx(nu,{width:"100%",height:"100%",children:r.jsxs(FK,{children:[r.jsx(XR,{data:x,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:x.map((_,M)=>r.jsx(Ly,{fill:_.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${M}`))}),r.jsx(au,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:_=>[l==="weight"?bh(Number(_??0)):`${_??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),r.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[r.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?bh(F):F}),r.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[x.length," ",x.length===1?"color":"colors"]})]})]}),r.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:x.slice(0,8).map(_=>{const M=F>0?(_.value/F*100).toFixed(0):0;return r.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[r.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:_.hex}}),r.jsxs("span",{className:"text-bambu-gray truncate",children:[M,"%"]})]},_.hex)})}),x.length>8&&r.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",x.length-8," more"]})]})})():r.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function Prt({id:t,title:e,component:n,isHidden:a,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=Rce({id:t}),g={transform:qy.Transform.toString(m),transition:p,opacity:f?.5:1};return a?null:r.jsxs("div",{ref:u,style:{...g,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:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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:r.jsx(Ah,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),r.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.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?r.jsx(_O,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):r.jsx(CT,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),r.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:r.jsx(ab,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),r.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function Trt({widgets:t,storageKey:e,columns:n=4,stackBelow:a,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(_=>{F[_.id]=_.defaultSize||4}),F},[c,d]=y.useState(()=>{const F=localStorage.getItem(e);if(F)try{const _=JSON.parse(F);if(!_.sizes)_.sizes=l();else{const M=l();for(const H in M)H in _.sizes||(_.sizes[H]=M[H])}return _}catch{}return{order:t.map(_=>_.id),hidden:t.filter(_=>_.defaultVisible===!1).map(_=>_.id),sizes:l()}}),[u,m]=y.useState(!1),[p,f]=y.useState(!1);y.useEffect(()=>{if(!a)return;const F=window.matchMedia(`(max-width: ${a}px)`),_=H=>{f(H.matches)};_(F);const M=H=>_(H);return F.addEventListener?F.addEventListener("change",M):F.addListener(M),()=>{F.removeEventListener?F.removeEventListener("change",M):F.removeListener(M)}},[a]);const g=a&&p?1:n;y.useEffect(()=>{const F=()=>m(_=>!_);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),y.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),y.useEffect(()=>{const _=t.map(M=>M.id).filter(M=>!c.order.includes(M));_.length>0&&d(M=>({...M,order:[...M.order,..._]}))},[t,c.order]);const w=hce(hT(tj,{activationConstraint:{distance:8}}),hT(ej,{coordinateGetter:Ice})),b=F=>{const{active:_,over:M}=F;M&&_.id!==M.id&&d(H=>{const I=H.order.indexOf(_.id),z=H.order.indexOf(M.id);return{...H,order:aj(H.order,I,z)}})},x=F=>{d(_=>({..._,hidden:_.hidden.includes(F)?_.hidden.filter(M=>M!==F):[..._.hidden,F]}))},S=F=>{d(_=>{const M=_.sizes[F]||4,H=M===1?2:M===2?4:1;return{..._,sizes:{..._.sizes,[F]:H}}})},k=()=>{const F={order:t.map(_=>_.id),hidden:t.filter(_=>_.defaultVisible===!1).map(_=>_.id),sizes:l()};d(F),s?.()},C=c.order.map(F=>t.find(_=>_.id===F)).filter(Boolean),P=C.filter(F=>!c.hidden.includes(F.id)),T=C.filter(F=>c.hidden.includes(F.id)),A=o?.({hiddenCount:T.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:k});return r.jsxs("div",{className:"space-y-4",children:[A,!i&&!o&&r.jsxs("div",{className:"flex items-center justify-end gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:k,children:[r.jsx(fs,{className:"w-4 h-4"}),"Reset Layout"]}),T.length>0&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[r.jsx(Cl,{className:"w-4 h-4"}),T.length," Hidden"]})]}),u&&T.length>0&&r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(F=>r.jsxs("button",{onClick:()=>x(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:[r.jsx(Cl,{className:"w-3 h-3"}),F.title]},F.id))})]}),r.jsx(Mce,{sensors:w,collisionDetection:xce,onDragEnd:b,children:r.jsx(Fce,{items:P.map(F=>F.id),strategy:oU,children:r.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${g}, minmax(0, 1fr))`},children:P.map(F=>{const _=c.sizes[F.id]||2,M=Math.min(_,g);return r.jsx(Prt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:_,columnSpan:M,onToggleVisibility:()=>x(F.id),onToggleSize:()=>S(F.id)},F.id)})})})}),P.length===0&&r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx("p",{children:"All widgets are hidden."}),r.jsx(je,{className:"mt-4",onClick:k,children:"Reset Layout"})]})]})}function Art(t){const e=new Date,n=e.getUTCFullYear(),a=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,a,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(n,a,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(n,a,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(n,a,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(n,a,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 jrt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],Mrt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],YI=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],oF=[{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}],dN={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function Ert({stats:t,currency:e}){const{t:n}=_t(),a=t?.energy_data_warming_up===!0,i=a?n("stats.energyWarmingUpTooltip"):void 0,s=[{icon:Vr,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Zn,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Vr,color:"text-orange-400",label:n("stats.filamentUsed"),value:bh(t?.total_filament_grams||0)},{icon:JN,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:wc,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:a,tooltip:i},{icon:JN,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:a,tooltip:i}];return r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>r.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:r.jsx(o.icon,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&r.jsx(Nn,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),r.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function Drt({stats:t,printerMap:e,size:n=1}){const{t:a}=_t(),i=t?.total_prints?Math.round((t.successful_prints||0)/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return r.jsxs("div",{className:"flex items-center gap-6",children:[r.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[r.jsxs("svg",{className:"w-full h-full -rotate-90",children:[r.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),r.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(xr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:a("stats.successful")}),r.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($r,{className:"w-4 h-4 text-status-error flex-shrink-0"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:a("stats.failed")}),r.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&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:a("stats.printsByPrinter")}),r.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,d])=>r.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[r.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${a("common.printer")} ${c}`}),r.jsx("span",{className:"text-white font-medium",children:d})]},c))})]})]})]})}function Frt({stats:t,printerMap:e,size:n=1}){const{t:a}=_t(),i=t?.average_time_accuracy;if(i==null)return r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(w=>w>=95&&w<=105?"#00ae42":w>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,g=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return r.jsxs("div",{className:"flex items-center gap-6",children:[r.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[r.jsxs("svg",{className:"w-full h-full -rotate-90",children:[r.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),r.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),r.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[r.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),r.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[r.jsx(KZ,{className:"w-3 h-3 flex-shrink-0"}),r.jsx("span",{children:a("stats.perfectEstimate")})]}),g.length>0&&r.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:g.map(([w,b])=>r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(w)||`${a("common.printer")} ${w}`}),r.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},w))})]})]})}function Lrt({printDates:t,dateFrom:e,dateTo:n}){const{days:a,hourlyCounts:i,maxCount:s}=y.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(n+"T00:00:00"),p=[],f=x=>`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,g=new Date(u);for(;g<=m;)p.push({key:f(g),label:g.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),g.setDate(g.getDate()+1);const w={};let b=0;return t.forEach(x=>{const S=Yn(x);if(!S)return;const C=`${`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}-${String(S.getDate()).padStart(2,"0")}`}-${S.getHours()}`;w[C]=(w[C]||0)+1,w[C]>b&&(b=w[C])}),{days:p,hourlyCounts:w,maxCount:Math.max(1,b)}},[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 r.jsxs("div",{className:"w-full overflow-x-auto",children:[r.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[r.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:YI.map((u,m)=>r.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),a.map(u=>r.jsxs("div",{className:"flex items-center",style:{gap:c},children:[r.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 r.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${YI[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),r.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[r.jsx("span",{children:"Less"}),r.jsxs("div",{className:"flex",style:{gap:c},children:[r.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),r.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),r.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),r.jsx("span",{children:"More"})]})]})}function Rrt({printDates:t,size:e=2,dateFrom:n,dateTo:a}){const i=y.useMemo(()=>n&&a?Math.max((new Date(a).getTime()-new Date(n).getTime())/864e5,0)+1:n?Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1:1/0,[n,a]);if(i<=7&&n&&a)return r.jsx(Lrt,{printDates:t,dateFrom:n,dateTo:a});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return r.jsx(krt,{printDates:t,months:o})}function Irt({stats:t,archives:e,printerMap:n}){const{t:a}=_t(),[i,s]=y.useState("weight"),[o,l]=y.useState("weight"),c=y.useMemo(()=>{const x=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([S,k])=>{const C=x.get(S)||{prints:0,weight:0,time:0};C.prints=k,x.set(S,C)}),e.forEach(S=>{if(!S.printer_id)return;const k=String(S.printer_id),C=x.get(k)||{prints:0,weight:0,time:0};C.weight+=S.filament_used_grams||0,C.time+=S.actual_time_seconds||S.print_time_seconds||0,t?.prints_by_printer||C.prints++,x.set(k,C)}),Array.from(x.entries()).map(([S,k])=>({name:n.get(S)||`${a("common.printer")} ${S}`,value:i==="prints"?k.prints:i==="weight"?Math.round(k.weight):Math.round(k.time/3600*10)/10})).sort((S,k)=>k.value-S.value)},[t,e,n,i,a]),d=y.useMemo(()=>{const x=Array.from({length:24},(S,k)=>({hour:k,label:YI[k],total:0,failures:0}));return e.forEach(S=>{if(!S.started_at)return;const k=Yn(S.started_at);if(!k)return;const C=k.getHours();x[C].total++,S.status==="failed"&&x[C].failures++}),x},[e]),u=y.useMemo(()=>{const x=oF.map(S=>({name:S.key,count:0}));return e.forEach(S=>{const k=S.actual_time_seconds||S.print_time_seconds;if(!(!k||k<=0)){for(let C=0;C<oF.length;C++)if(k<=oF[C].max){x[C].count++;break}}}),x},[e]),m=y.useMemo(()=>{const x=[0,0,0,0,0,0,0],S=new Set;e.forEach(C=>{const P=Yn(C.created_at)||new Date(C.created_at);let T=P.getDay()-1;T<0&&(T=6),o==="prints"?x[T]++:o==="weight"?x[T]+=C.filament_used_grams||0:x[T]+=(C.actual_time_seconds||C.print_time_seconds||0)/3600;const A=new Date(P);A.setDate(P.getDate()-(P.getDay()+6)%7),S.add(`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`)});const k=Math.max(S.size,1);return Mrt.map((C,P)=>({name:C,avg:Math.round(x[P]/k*10)/10}))},[e,o]),p=x=>({unit:x==="weight"?"g":x==="time"?"h":"",color:x==="weight"?"#00ae42":x==="time"?"#3b82f6":"#f59e0b"}),f=p(i),g=a(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),w=p(o),b=a(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:a("stats.printsByPrinter")}),r.jsx(bT,{value:i,onChange:s})]}),c.length>0?r.jsx(nu,{width:"100%",height:Math.max(140,c.length*40),children:r.jsxs(V1,{data:c,layout:"vertical",margin:{left:10},children:[r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),r.jsx(Tm,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),r.jsx(Am,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),r.jsx(au,{contentStyle:dN,formatter:x=>[i==="weight"?bh(Number(x??0)):`${x??0}${f.unit}`,g]}),r.jsx(Bx,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):r.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noPrinterData")})]}),r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:a("stats.printDuration")}),e.length>0?r.jsx(nu,{width:"100%",height:160,children:r.jsxs(V1,{data:u,children:[r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),r.jsx(Tm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),r.jsx(Am,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),r.jsx(au,{contentStyle:dN}),r.jsx(Bx,{dataKey:"count",name:a("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):r.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noArchiveData")})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:a("stats.printHabits")}),r.jsx(bT,{value:o,onChange:l})]}),e.length>0?r.jsx(nu,{width:"100%",height:160,children:r.jsxs(V1,{data:m,children:[r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),r.jsx(Tm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),r.jsx(Am,{stroke:"#9ca3af",tick:{fontSize:11},unit:w.unit}),r.jsx(au,{contentStyle:dN,formatter:x=>[`${x??0}${w.unit}`,b]}),r.jsx(Bx,{dataKey:"avg",fill:w.color,radius:[4,4,0,0]})]})}):r.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noArchiveData")})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[r.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:a("stats.printTimeOfDay")}),e.length>0?r.jsx(nu,{width:"100%",height:160,children:r.jsxs(V1,{data:d,children:[r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),r.jsx(Tm,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),r.jsx(Am,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),r.jsx(au,{contentStyle:dN}),r.jsx(Bx,{dataKey:"total",name:a("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),r.jsx(Bx,{dataKey:"failures",name:a("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):r.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noArchiveData")})]})]})]})}function Ort({archives:t,currency:e,dateFrom:n,dateTo:a}){const{t:i}=_t();return!t||t.length===0?r.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):r.jsx(Crt,{archives:t,currency:e,dateFrom:n,dateTo:a})}function zrt({size:t=1,dateFrom:e,dateTo:n,createdById:a}){const{t:i}=_t(),s=!!(e||n),{data:o,isLoading:l}=Xe({queryKey:["failureAnalysis",e,n,a??"all"],queryFn:()=>ae.getFailureAnalysis({...s?{dateFrom:e,dateTo:n}:{days:30},createdById:a})});if(l)return r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return r.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 r.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[r.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[r.jsx("div",{className:"flex items-center gap-4",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Nn,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),r.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),r.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&&r.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(IS,{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"}`}),r.jsx("span",{className:"text-bambu-gray",children:i("stats.lastWeekRate",{rate:o.trend[o.trend.length-1].failure_rate.toFixed(1)})})]})})]}),u.length>0&&r.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[r.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),r.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),r.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function Urt({archives:t,currency:e}){const{t:n}=_t(),a=y.useMemo(()=>{const i=[];if(t.length===0)return i;const s=g=>{let w=null,b=0;return t.forEach(x=>{const S=g(x);S&&S>b&&(b=S,w=x)}),{archive:w,value:b}},o=s(g=>g.status==="completed"?g.actual_time_seconds:null);o.archive&&i.push({icon:Zn,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:cs(o.value),detail:o.archive.print_name||null});const l=s(g=>g.filament_used_grams);l.archive&&i.push({icon:Vr,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:bh(l.value),detail:l.archive.print_name||null});const c=s(g=>g.cost);c.archive&&i.push({icon:JN,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(g=>{const w=Yn(g.created_at)||new Date(g.created_at),b=`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}-${String(w.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((g,w)=>{g>m&&(m=g,u=w)}),m>1&&i.push({icon:wa,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[g,w,b]=u.split("-").map(Number);return new Date(g,w-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(g=>g.status==="completed"||g.status==="failed").sort((g,w)=>new Date(w.completed_at||w.created_at).getTime()-new Date(g.completed_at||g.created_at).getTime());let f=0;for(const g of p)if(g.status==="completed")f++;else break;return f>0&&i.push({icon:wc,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 a.length===0?r.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noArchiveData")}):r.jsx("div",{className:"space-y-3",children:a.map((i,s)=>r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:r.jsx(i.icon,{className:"w-4 h-4"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&r.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function Brt(){const{t}=_t(),{showToast:e}=on(),{hasPermission:n,authEnabled:a}=dr(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(0),[u,m]=y.useState(0),[p,f]=y.useState(!1),[g,w]=y.useState(null),[b,x]=y.useState(!1),S=a&&n("stats:filter_by_user"),[k,C]=y.useState(()=>{try{const J=localStorage.getItem("bambusy-stats-timeframe");if(J){const j=JSON.parse(J);if(j.preset)return j}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[P,T]=y.useState(!1);y.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(k))},[k]);const A=y.useMemo(()=>k.preset==="custom"?{dateFrom:k.dateFrom,dateTo:k.dateTo}:Art(k.preset),[k]);y.useEffect(()=>{const J=()=>{try{const E=localStorage.getItem("bambusy-dashboard-layout-v2");if(E){const B=JSON.parse(E);m(B.hidden?.length||0)}}catch{m(0)}};J(),window.addEventListener("storage",J);const j=setInterval(J,2e3);return()=>{window.removeEventListener("storage",J),clearInterval(j)}},[c]);const F=g!==null?g:void 0,{data:_,isLoading:M,isFetching:H,refetch:I}=Xe({queryKey:["archiveStats",A.dateFrom,A.dateTo,F??"all"],queryFn:()=>ae.getArchiveStats({dateFrom:A.dateFrom,dateTo:A.dateTo,createdById:F})}),{data:z}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:L,isFetching:Z,refetch:ne}=Xe({queryKey:["archivesSlim",A.dateFrom,A.dateTo,F??"all"],queryFn:()=>ae.getArchivesSlim(A.dateFrom,A.dateTo,F)}),{data:Y}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:ce}=Xe({queryKey:["users"],queryFn:ae.getUsers,enabled:S}),ue=y.useMemo(()=>g===null?t("stats.allUsers","All Users"):g===-1?t("stats.noUser","No User (System)"):ce?.find(J=>J.id===g)?.username??"?",[g,ce,t]),oe=async J=>{l(!1),s(!0);try{const{blob:j,filename:E}=await ae.exportStats({format:J,days:90,createdById:F}),B=URL.createObjectURL(j),W=document.createElement("a");W.href=B,W.download=E,W.click(),URL.revokeObjectURL(B),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},Q=async()=>{f(!0);try{const J=await ae.recalculateCosts();await Promise.all([I(),ne()]),e(t("stats.recalculatedCosts",{count:J.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},le=(H||Z)&&!M,pe=Ho(Y?.currency||"USD"),he=new Map(z?.map(J=>[String(J.id),J.name])||[]),we=y.useMemo(()=>L?.map(J=>J.created_at)||[],[L]);if(M)return r.jsx("div",{className:"p-4 md:p-8",children:r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const $=[{id:"quick-stats",title:t("stats.quickStats"),component:r.jsx(Ert,{stats:_,currency:pe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:J=>r.jsx(Drt,{stats:_,printerMap:he,size:J}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:J=>r.jsx(Frt,{stats:_,printerMap:he,size:J}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:J=>r.jsx(zrt,{size:J,dateFrom:A.dateFrom,dateTo:A.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:J=>r.jsx(Rrt,{printDates:we,size:J,dateFrom:A.dateFrom,dateTo:A.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:r.jsx(Urt,{archives:L||[],currency:pe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:r.jsx(Irt,{stats:_,archives:L||[],printerMap:he}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:r.jsx(Ort,{archives:L||[],currency:pe,dateFrom:A.dateFrom,dateTo:A.dateTo}),defaultSize:4}];return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(RZ,{className:"w-7 h-7 text-bambu-green"}),t("stats.title")]}),le&&r.jsx(ft,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("stats.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&r.jsxs(je,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[r.jsx(Cl,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),r.jsxs(je,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(J=>J+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[r.jsx(fs,{className:"w-4 h-4"}),t("stats.resetLayout")]}),r.jsxs(je,{variant:"secondary",onClick:Q,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Kfe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tC,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&r.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:[r.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:[r.jsx(Rs,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),r.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:[r.jsx(tC,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),S&&ce&&ce.length>0&&r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",onClick:()=>x(!b),children:[r.jsx(bm,{className:"w-4 h-4"}),ue,r.jsx(Ln,{className:"w-3 h-3"})]}),b&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),r.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:[r.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(null),x(!1)},children:t("stats.allUsers","All Users")}),r.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(-1),x(!1)},children:t("stats.noUser","No User (System)")}),r.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),ce.map(J=>r.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===J.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(J.id),x(!1)},children:J.username},J.id))]})]})]}),r.jsxs("div",{className:"relative",children:[r.jsxs(je,{variant:"secondary",onClick:()=>T(!P),children:[r.jsx(wa,{className:"w-4 h-4"}),t(`stats.timeframe.${k.preset}`),r.jsx(Ln,{className:"w-3 h-3"})]}),P&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>T(!1)}),r.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:[jrt.map(J=>r.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset===J?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{C({preset:J,dateFrom:void 0,dateTo:void 0}),T(!1)},children:t(`stats.timeframe.${J}`)},J)),r.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),r.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>C(J=>({...J,preset:"custom"})),children:t("stats.timeframe.custom")}),k.preset==="custom"&&r.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),r.jsx("input",{type:"date",value:k.dateFrom||"",max:k.dateTo||new Date().toISOString().split("T")[0],onChange:J=>C(j=>({...j,dateFrom:J.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]"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),r.jsx("input",{type:"date",value:k.dateTo||"",min:k.dateFrom,max:new Date().toISOString().split("T")[0],onChange:J=>C(j=>({...j,dateTo:J.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]"})]}),r.jsx(je,{variant:"primary",onClick:()=>T(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),r.jsx(Trt,{widgets:$,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function uN(t){return t.length<8?"tooShort":/[A-Z]/.test(t)?/[a-z]/.test(t)?/\d/.test(t)?/[^A-Za-z0-9]/.test(t)?null:"needsSpecial":"needsDigit":"needsLowercase":"needsUppercase"}function Hrt(){const{t}=_t(),e=tn(),{showToast:n}=on(),a=y.useRef(null),[i,s]=y.useState(null),{data:o,isLoading:l}=Xe({queryKey:["slicer-bundles"],queryFn:ae.listSlicerBundles}),c=lt({mutationFn:m=>ae.importSlicerBundle(m),onSuccess:m=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),n(t("settings.slicerBundles.uploadSuccess",{defaultValue:"Imported {{name}}",name:m.printer_preset_name}),"success"),a.current&&(a.current.value="")},onError:m=>{n(t("settings.slicerBundles.uploadError",{defaultValue:"Bundle upload failed: {{message}}",message:m.message}),"error"),a.current&&(a.current.value="")}}),d=lt({mutationFn:m=>ae.deleteSlicerBundle(m),onSuccess:()=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),s(null),n(t("settings.slicerBundles.deleteSuccess",{defaultValue:"Bundle removed"}),"success")},onError:m=>{n(t("settings.slicerBundles.deleteError",{defaultValue:"Bundle delete failed: {{message}}",message:m.message}),"error"),s(null)}}),u=m=>{const p=m.target.files?.[0];p&&c.mutate(p)};return r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(Vr,{className:"w-4 h-4 text-bambu-green"}),t("settings.slicerBundles.title",{defaultValue:"Slicer Bundles"})]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.slicerBundles.description",{defaultValue:'Import a Printer Preset Bundle (.bbscfg) exported from BambuStudio (File → Export → Export Preset Bundle → "Printer preset bundle"). Once imported, slice requests can pick presets from the bundle by name without re-uploading the JSON profile triplet.'})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{ref:a,type:"file",accept:".bbscfg,.zip,application/zip",onChange:u,className:"hidden",disabled:c.isPending}),r.jsx(je,{variant:"primary",onClick:()=>a.current?.click(),disabled:c.isPending,children:c.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.uploading",{defaultValue:"Uploading…"})]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-4 h-4"}),t("settings.slicerBundles.uploadButton",{defaultValue:"Upload bundle"})]})})]}),l?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.loading",{defaultValue:"Loading bundles…"})]}):o&&o.length>0?r.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg",children:o.map(m=>r.jsxs("li",{className:"flex items-center justify-between px-3 py-2 hover:bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:m.printer_preset_name}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-0.5",children:[t("settings.slicerBundles.summary",{defaultValue:"{{processCount}} process · {{filamentCount}} filament presets",processCount:m.process.length,filamentCount:m.filament.length}),m.version&&` · v${m.version}`]})]}),r.jsx("button",{type:"button",onClick:()=>s(m),disabled:d.isPending,className:"ml-3 p-1.5 text-bambu-gray hover:text-red-400 disabled:opacity-40","aria-label":t("settings.slicerBundles.delete",{defaultValue:"Delete"}),children:r.jsx(en,{className:"w-4 h-4"})})]},m.id))}):r.jsx("p",{className:"text-sm text-bambu-gray italic",children:t("settings.slicerBundles.empty",{defaultValue:"No bundles imported yet."})})]}),i&&r.jsx(wn,{title:t("settings.slicerBundles.confirmDeleteTitle",{defaultValue:"Remove this bundle?"}),message:t("settings.slicerBundles.confirmDeleteMessage",{defaultValue:'Slice requests that reference "{{name}}" will fail until the bundle is re-imported.',name:i.printer_preset_name}),confirmText:t("common.delete",{defaultValue:"Delete"}),variant:"danger",isLoading:d.isPending,onConfirm:()=>d.mutate(i.id),onCancel:()=>s(null)})]})}const lX=90,cX=365;function lF(t){return t?new Date(t).toLocaleString():"—"}function qrt(t){return new Date(t).getTime()<Date.now()}function $rt({onCreated:t}){const{t:e}=_t(),{showToast:n}=on(),[a,i]=y.useState(""),[s,o]=y.useState(lX),[l,c]=y.useState(!1),d=async u=>{if(u.preventDefault(),!!a.trim()){c(!0);try{const m=await ae.createLongLivedCameraToken({name:a.trim(),expires_in_days:s});t(m),i(""),o(lX),n(e("cameraTokens.toast.created","Token created"))}catch(m){n(m instanceof Error?m.message:e("cameraTokens.toast.createFailed","Failed to create token"),"error")}finally{c(!1)}}};return r.jsxs("form",{onSubmit:d,className:"bg-bambu-dark-secondary rounded-lg p-4 mb-6 border border-bambu-dark-tertiary",children:[r.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:e("cameraTokens.create.title","Create new token")}),r.jsxs("div",{className:"grid gap-3 md:grid-cols-[1fr_140px_auto]",children:[r.jsx("input",{type:"text",maxLength:100,required:!0,value:a,onChange:u=>i(u.target.value),placeholder:e("cameraTokens.create.namePlaceholder","e.g. Home Assistant"),className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.nameLabel","Token name")}),r.jsx("input",{type:"number",min:1,max:cX,required:!0,value:s,onChange:u=>{const m=Number(u.target.value);o(Math.min(Math.max(m,1),cX))},className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.daysLabel","Days until expiry")}),r.jsxs("button",{type:"submit",disabled:l||!a.trim(),className:"flex items-center gap-2 px-4 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90 disabled:opacity-50 disabled:cursor-not-allowed",children:[r.jsx(er,{className:"w-4 h-4"}),e("cameraTokens.create.submit","Create")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("cameraTokens.create.hint","Maximum lifetime is 365 days. The token value is shown only once on creation — copy it now.")})]})}function Vrt({token:t,onConfirm:e,onCancel:n}){const{t:a}=_t();return r.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full border border-red-500/40",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(Nn,{className:"w-6 h-6 text-red-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("cameraTokens.confirmRevoke.title","Revoke this token?")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("cameraTokens.confirmRevoke.body",'Any device using "{{name}}" will lose access immediately. This cannot be undone.',{name:t.name})})]})]}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:n,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:a("cameraTokens.confirmRevoke.cancel","Cancel")}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600",children:a("cameraTokens.confirmRevoke.confirm","Revoke")})]})]})})}function Grt({token:t,onClose:e}){const{t:n}=_t(),{showToast:a}=on(),i=t.token??"",s=async()=>{if(i)try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(i);else{const o=document.createElement("textarea");o.value=i,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o);try{o.select(),document.execCommand("copy")}finally{document.body.removeChild(o)}}a(n("cameraTokens.toast.copied","Copied to clipboard"))}catch{a(n("cameraTokens.toast.copyFailed","Copy failed — select and copy manually"),"error")}};return r.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-2xl w-full border border-bambu-green/40",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(Nn,{className:"w-6 h-6 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("cameraTokens.created.title","Token created — copy it now")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("cameraTokens.created.warning","This is the only time this token will be visible. After you close this dialog you can never view it again.")})]})]}),r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx("code",{className:"flex-1 px-3 py-2 bg-bambu-dark rounded-md text-bambu-green text-xs break-all font-mono select-all",children:i}),r.jsxs("button",{type:"button",onClick:s,className:"flex items-center gap-2 px-3 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90",children:[r.jsx(Ti,{className:"w-4 h-4"}),n("cameraTokens.created.copy","Copy")]})]}),r.jsx("div",{className:"flex justify-end",children:r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:n("cameraTokens.created.dismiss","I've saved it")})})]})})}function Wrt({token:t,showOwner:e,ownerLabel:n,onRevoke:a}){const{t:i}=_t(),s=qrt(t.expires_at);return r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary last:border-b-0",children:[r.jsx("td",{className:"py-3 px-3 text-white",children:t.name}),e&&r.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:n}),r.jsxs("td",{className:"py-3 px-3 text-bambu-gray font-mono text-xs",children:[t.lookup_prefix,"…"]}),r.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:lF(t.created_at)}),r.jsxs("td",{className:`py-3 px-3 ${s?"text-red-400":"text-bambu-gray"}`,children:[lF(t.expires_at),s&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs bg-red-500/20 text-red-300 rounded",children:i("cameraTokens.list.expired","Expired")})]}),r.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:lF(t.last_used_at)}),r.jsx("td",{className:"py-3 px-3 text-right",children:r.jsxs("button",{type:"button",onClick:()=>a(t.id),className:"inline-flex items-center gap-1 px-2 py-1 text-sm text-red-400 hover:text-red-300",title:i("cameraTokens.list.revoke","Revoke"),children:[r.jsx(en,{className:"w-4 h-4"}),i("cameraTokens.list.revoke","Revoke")]})})]})}function dX({tokens:t,showOwner:e,userIdToName:n,onRevoke:a,emptyMessage:i}){const{t:s}=_t();return t.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic",children:i}):r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"text-bambu-gray text-left border-b border-bambu-dark-tertiary",children:r.jsxs("tr",{children:[r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.name","Name")}),e&&r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.owner","Owner")}),r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.prefix","Prefix")}),r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.created","Created")}),r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.expires","Expires")}),r.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.lastUsed","Last used")}),r.jsx("th",{className:"py-2 px-3"})]})}),r.jsx("tbody",{children:t.map(o=>r.jsx(Wrt,{token:o,showOwner:e,ownerLabel:n?.get(o.user_id)??`#${o.user_id}`,onRevoke:a},o.id))})]})})}function Krt(){const{t}=_t(),{user:e,isAdmin:n}=dr(),{showToast:a}=on(),[i,s]=y.useState([]),[o,l]=y.useState([]),[c,d]=y.useState(new Map),[u,m]=y.useState(!0),[p,f]=y.useState(null),[g,w]=y.useState(null),b=async()=>{m(!0);try{const C=await ae.listMyLongLivedCameraTokens();if(s(C),n){const P=await ae.listAllLongLivedCameraTokens();l(P);try{const T=await ae.getUsers();d(new Map(T.map(A=>[A.id,A.username])))}catch{d(new Map)}}}catch(C){a(C instanceof Error?C.message:t("cameraTokens.toast.loadFailed","Failed to load tokens"),"error")}finally{m(!1)}};y.useEffect(()=>{b()},[n]);const x=async C=>{const P=[...i,...o].find(T=>T.id===C);P&&w(P)},S=async()=>{if(!g)return;const C=g.id;w(null);try{await ae.revokeLongLivedCameraToken(C),a(t("cameraTokens.toast.revoked","Token revoked")),await b()}catch(P){a(P instanceof Error?P.message:t("cameraTokens.toast.revokeFailed","Failed to revoke token"),"error")}},k=y.useMemo(()=>o.filter(C=>C.user_id!==e?.id),[o,e?.id]);return r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("cameraTokens.description","Long-lived tokens for embedding the camera stream into Home Assistant, Frigate, kiosks, or any other tool that needs a stable URL. Each token is camera-stream-only and can be revoked at any time.")}),r.jsx($rt,{onCreated:C=>{f(C),b()}}),r.jsxs("div",{className:"mb-6",children:[r.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.myTitle","My tokens")}),u?r.jsx("p",{className:"text-sm text-bambu-gray",children:t("cameraTokens.loading","Loading…")}):r.jsx(dX,{tokens:i,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),n&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.allTitle","All users (admin view)")}),r.jsx(dX,{tokens:k,showOwner:!0,userIdToName:c,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),p&&r.jsx(Grt,{token:p,onClose:()=>f(null)}),g&&r.jsx(Vrt,{token:g,onConfirm:()=>{S()},onCancel:()=>w(null)})]})}function Qrt({plug:t,onEdit:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),[s,o]=y.useState(!1),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),{data:f,isLoading:g}=Xe({queryKey:["smart-plug-status",t.id],queryFn:()=>ae.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:w}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),b=w?.find(M=>M.id===t.printer_id),x=lt({mutationFn:M=>ae.controlSmartPlug(t.id,M),onMutate:async M=>{await a.cancelQueries({queryKey:["smart-plug-status",t.id]});const H=a.getQueryData(["smart-plug-status",t.id]),I=M==="on"?"ON":M==="off"||f?.state==="ON"?"OFF":"ON";return a.setQueryData(["smart-plug-status",t.id],z=>({...z,state:I})),{previousStatus:H}},onError:(M,H,I)=>{I?.previousStatus&&a.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(n("smartPlugs.failedToTurn",{action:H,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{a.invalidateQueries({queryKey:["smart-plug-status",t.id]}),a.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=lt({mutationFn:M=>ae.updateSmartPlug(t.id,M),onSuccess:()=>{a.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(a.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),a.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),k=lt({mutationFn:()=>ae.deleteSmartPlug(t.id),onSuccess:()=>{a.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&a.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),C=f?.state==="ON",P=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,T=(f?.reachable??!1)||P,A=x.isPending,_=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const M=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${M}/`:`http://${M}/`})();return r.jsxs(r.Fragment,{children:[r.jsx(At,{className:"relative",children:r.jsxs(Et,{className:"p-4",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[r.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?T?"bg-teal-500/20":"bg-red-500/20":T?C?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?r.jsx(NO,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?r.jsx(AS,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?r.jsx(Js,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):r.jsx(hc,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),r.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})]})]}),r.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[g?r.jsx(ft,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?r.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[r.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"}),T&&r.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?r.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[r.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),r.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":n("smartPlugs.offline")})]}):t.plug_type==="rest"?r.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[r.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),r.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":n("smartPlugs.offline")})]}):T?r.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[r.jsx(Mh,{className:"w-4 h-4 text-status-ok"}),r.jsx("span",{className:C?"text-status-ok":"text-bambu-gray",children:f?.state||n("smartPlugs.unknown")})]}):r.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[r.jsx(hu,{className:"w-4 h-4"}),r.jsx("span",{children:n("smartPlugs.offline")})]}),_&&r.jsxs("a",{href:_,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:[r.jsx(zr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&r.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[r.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("smartPlugs.linkedTo")," "]}),r.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&r.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:[r.jsx(Cl,{className:"w-3 h-3"}),n("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&r.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:[r.jsx(Ch,{className:"w-3 h-3"}),n("smartPlugs.alerts")]}),t.schedule_enabled&&r.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:[r.jsx(wa,{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"&&r.jsxs("div",{className:"flex gap-2 mb-3",children:[r.jsxs(je,{size:"sm",variant:C?"primary":"secondary",disabled:!T||A,onClick:()=>c(!0),className:"flex-1",children:[A?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(_u,{className:"w-4 h-4"}),n("smartPlugs.on")]}),r.jsxs(je,{size:"sm",variant:C?"secondary":"primary",disabled:!T||A,onClick:()=>u(!0),className:"flex-1",children:[A?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(FS,{className:"w-4 h-4"}),n("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&r.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&&r.jsxs("div",{className:"flex-1 text-center",children:[r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&r.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.kwhToday")})]})]}),r.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:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(pu,{className:"w-4 h-4"}),t.plug_type==="mqtt"?n("smartPlugs.settings"):n("smartPlugs.automationSettings")]}),r.jsx("span",{children:m?"-":"+"})]}),m&&r.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(jS,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.showInSwitchbar")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:M=>S.mutate({show_in_switchbar:M.target.checked}),className:"sr-only peer"}),r.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"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.enabled")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.enableAutomation")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.enabled,onChange:M=>S.mutate({enabled:M.target.checked}),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOn")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOnDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:M=>S.mutate({auto_on:M.target.checked}),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOff")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:M=>S.mutate({auto_off:M.target.checked}),className:"sr-only peer"}),r.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&&r.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffPersistent")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffPersistentDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:M=>S.mutate({auto_off_persistent:M.target.checked}),className:"sr-only peer"}),r.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&&r.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white mb-2",children:n("smartPlugs.turnOffDelayMode")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>S.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:[r.jsx(Zn,{className:"w-4 h-4"}),n("smartPlugs.time")]}),r.jsxs("button",{onClick:()=>S.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:[r.jsx(RS,{className:"w-4 h-4"}),n("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayMinutes")}),r.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:M=>S.mutate({off_delay_minutes:parseInt(M.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"})]}):r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.tempThreshold")}),r.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:M=>S.mutate({off_temp_threshold:parseInt(M.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.tempThresholdDescription")})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffAfterDrying")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffAfterDryingDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.auto_off_after_drying,onChange:M=>S.mutate({auto_off_after_drying:M.target.checked}),className:"sr-only peer"}),r.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_after_drying&&r.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayAfterDryingMinutes")}),r.jsx("input",{type:"number",min:"0",max:"120",value:t.off_delay_after_drying_minutes,onChange:M=>S.mutate({off_delay_after_drying_minutes:parseInt(M.target.value)||10}),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"})]})]}),r.jsxs("div",{className:"flex gap-2 pt-2",children:[r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[r.jsx(uc,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:r.jsx(en,{className:"w-4 h-4"})})]})]})]})}),s&&r.jsx(wn,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{k.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&r.jsx(wn,{title:n("smartPlugs.turnOnSmartPlug"),message:n("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{x.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&r.jsx(wn,{title:n("smartPlugs.turnOffSmartPlug"),message:n("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{x.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function Yrt({plug:t,onClose:e}){const{t:n}=_t(),a=tn(),i=!!t,[s,o]=y.useState(t?.plug_type||"tasmota"),[l,c]=y.useState(t?.name||""),[d,u]=y.useState(t?.ip_address||""),[m,p]=y.useState(t?.username||""),[f,g]=y.useState(t?.password||""),[w,b]=y.useState(t?.ha_entity_id||""),[x,S]=y.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[k,C]=y.useState(t?.mqtt_power_path||""),[P,T]=y.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[A,F]=y.useState(t?.mqtt_energy_topic||""),[_,M]=y.useState(t?.mqtt_energy_path||""),[H,I]=y.useState((t?.mqtt_energy_multiplier??1).toString()),[z,L]=y.useState(t?.mqtt_state_topic||""),[Z,ne]=y.useState(t?.mqtt_state_path||""),[Y,ce]=y.useState(t?.mqtt_state_on_value||""),[ue,oe]=y.useState(t?.rest_on_url||""),[Q,le]=y.useState(t?.rest_on_body||""),[pe,he]=y.useState(t?.rest_off_url||""),[we,$]=y.useState(t?.rest_off_body||""),[J,j]=y.useState(t?.rest_method||"POST"),[E,B]=y.useState(t?.rest_headers||""),[W,O]=y.useState(t?.rest_status_url||""),[ie,U]=y.useState(t?.rest_status_path||""),[G,K]=y.useState(t?.rest_status_on_value||""),[X,se]=y.useState(t?.rest_power_url||""),[te,fe]=y.useState(t?.rest_power_path||""),[de,me]=y.useState((t?.rest_power_multiplier??1).toString()),[q,R]=y.useState(t?.rest_energy_url||""),[re,be]=y.useState(t?.rest_energy_path||""),[ye,_e]=y.useState((t?.rest_energy_multiplier??1).toString()),[xe,ge]=y.useState(t?.ha_power_entity||""),[Me,Be]=y.useState(t?.ha_energy_today_entity||""),[Fe,Oe]=y.useState(t?.ha_energy_total_entity||""),[Re,We]=y.useState(""),[ze,st]=y.useState(""),[Ee,it]=y.useState(!1),Ce=y.useRef(null),[Ze,Ie]=y.useState(""),[ke,Ve]=y.useState(!1),rt=y.useRef(null),[Qe,Te]=y.useState(""),[tt,ot]=y.useState(!1),Tt=y.useRef(null),[Ut,bt]=y.useState(""),[Wt,Zt]=y.useState(!1),ln=y.useRef(null),[cn,ct]=y.useState(t?.printer_id||null),[kt,Nt]=y.useState(null),[ut,Ct]=y.useState(null),[Le,Ae]=y.useState(t?.power_alert_enabled||!1),[Ge,Je]=y.useState(t?.power_alert_high?.toString()||""),[De,mt]=y.useState(t?.power_alert_low?.toString()||""),[Ne,Ye]=y.useState(t?.schedule_enabled||!1),[nt,at]=y.useState(t?.schedule_on_time||""),[et,vt]=y.useState(t?.schedule_off_time||""),[wt,Ue]=y.useState(t?.show_in_switchbar||!1),[He,Dt]=y.useState(t?.show_on_printer_card??!0),[Rt,qe]=y.useState(!1),[Ke,Bt]=y.useState({scanned:0,total:0}),[Qt,dn]=y.useState([]),nn=y.useRef(null),{data:rn}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:yn}=Xe({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:Mn}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),or=!!(Mn?.ha_enabled&&Mn?.ha_url&&Mn?.ha_token);y.useEffect(()=>{const It=setTimeout(()=>{st(Re)},300);return()=>clearTimeout(It)},[Re]),y.useEffect(()=>{const It=_n=>{Ce.current&&!Ce.current.contains(_n.target)&&it(!1),rt.current&&!rt.current.contains(_n.target)&&Ve(!1),Tt.current&&!Tt.current.contains(_n.target)&&ot(!1),ln.current&&!ln.current.contains(_n.target)&&Zt(!1)};return document.addEventListener("mousedown",It),()=>document.removeEventListener("mousedown",It)},[]);const{data:Dr,isLoading:Gn,error:pi}=Xe({queryKey:["ha-entities",ze],queryFn:()=>ae.getHAEntities(ze||void 0),enabled:s==="homeassistant"&&or,retry:!1,staleTime:0}),{data:Un}=Xe({queryKey:["ha-sensor-entities"],queryFn:ae.getHASensorEntities,enabled:s==="homeassistant"&&or,retry:!1,staleTime:0});y.useEffect(()=>{const It=_n=>{_n.key==="Escape"&&e()};return window.addEventListener("keydown",It),()=>{window.removeEventListener("keydown",It),nn.current&&clearInterval(nn.current)}},[e]);const vr=async()=>{qe(!0),dn([]),Bt({scanned:0,total:0}),Ct(null);try{await ae.startTasmotaScan();const It=async()=>{try{const _n=await ae.getTasmotaScanStatus();Bt({scanned:_n.scanned,total:_n.total});const ur=await ae.getDiscoveredTasmotaDevices();dn(ur),_n.running||(qe(!1),nn.current&&(clearInterval(nn.current),nn.current=null))}catch(_n){console.error("Polling error:",_n)}};await It(),nn.current=setInterval(It,500)}catch(It){qe(!1);const _n=It instanceof Error?It.message:typeof It=="string"?It:JSON.stringify(It);Ct(_n||n("smartPlugs.failedToStartScan"))}},ua=async()=>{try{await ae.stopTasmotaScan()}catch{}qe(!1),nn.current&&(clearInterval(nn.current),nn.current=null)},Fr=It=>{u(It.ip_address),c(It.name),Nt(null)},ba=lt({mutationFn:()=>ae.testSmartPlugConnection(d,m||null,f||null),onSuccess:It=>{Nt(It),Ct(null),!l&&It.device_name&&c(It.device_name)},onError:It=>{Nt(null),Ct(It.message)}}),Mi=lt({mutationFn:It=>ae.createSmartPlug(It),onSuccess:()=>{a.invalidateQueries({queryKey:["smart-plugs"]}),a.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:It=>{Ct(It.message)}}),Ki=lt({mutationFn:It=>ae.updateSmartPlug(t.id,It),onSuccess:()=>{a.invalidateQueries({queryKey:["smart-plugs"]}),a.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:It=>{Ct(It.message)}}),wd=rn?.filter(It=>s==="tasmota"?!yn?.some(ur=>ur.printer_id===It.id&&ur.id!==t?.id&&ur.plug_type==="tasmota"):!0),Mc=It=>{if(It.preventDefault(),Ct(null),!l.trim()){Ct(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Ct("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!w){Ct(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const ur=x.trim(),Kt=A.trim(),Ec=z.trim();if(!ur&&!Kt&&!Ec){Ct(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!ue.trim()&&!pe.trim()){Ct(n("smartPlugs.restUrlRequired"));return}const _n={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?w:null,ha_power_entity:s==="homeassistant"&&xe||null,ha_energy_today_entity:s==="homeassistant"&&Me||null,ha_energy_total_entity:s==="homeassistant"&&Fe||null,mqtt_power_topic:s==="mqtt"&&x.trim()||null,mqtt_power_path:s==="mqtt"&&k.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(P)||1,mqtt_energy_topic:s==="mqtt"&&A.trim()||null,mqtt_energy_path:s==="mqtt"&&_.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(H)||1,mqtt_state_topic:s==="mqtt"&&z.trim()||null,mqtt_state_path:s==="mqtt"&&Z.trim()||null,mqtt_state_on_value:s==="mqtt"&&Y.trim()||null,rest_on_url:s==="rest"&&ue.trim()||null,rest_on_body:s==="rest"&&Q.trim()||null,rest_off_url:s==="rest"&&pe.trim()||null,rest_off_body:s==="rest"&&we.trim()||null,rest_method:s==="rest"?J:null,rest_headers:s==="rest"&&E.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&ie.trim()||null,rest_status_on_value:s==="rest"&&G.trim()||null,rest_power_url:s==="rest"&&X.trim()||null,rest_power_path:s==="rest"&&te.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(de)||1,rest_energy_url:s==="rest"&&q.trim()||null,rest_energy_path:s==="rest"&&re.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(ye)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:cn,power_alert_enabled:Le,power_alert_high:Ge?parseFloat(Ge):null,power_alert_low:De?parseFloat(De):null,schedule_enabled:Ne,schedule_on_time:nt||null,schedule_off_time:et||null,show_in_switchbar:wt,show_on_printer_card:He};i?Ki.mutate(_n):Mi.mutate(_n)},zs=Mi.isPending||Ki.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.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:It=>It.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:Mc,className:"p-6 space-y-4 overflow-y-auto",children:[ut&&r.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ut}),!i&&r.jsxs("div",{className:"flex gap-2 mb-2",children:[r.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Nt(null),Ct(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:[r.jsx(hc,{className:"w-4 h-4"}),"Tasmota"]}),r.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Nt(null),Ct(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:[r.jsx(AS,{className:"w-4 h-4"}),"HA"]}),r.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Nt(null),Ct(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:[r.jsx(NO,{className:"w-4 h-4"}),"MQTT"]}),r.jsxs("button",{type:"button",onClick:()=>{o("rest"),Nt(null),Ct(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:[r.jsx(Js,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&r.jsxs("div",{className:"space-y-3",children:[Rt?r.jsxs(je,{type:"button",variant:"secondary",onClick:ua,className:"w-full",children:[r.jsx(Vt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):r.jsxs(je,{type:"button",variant:"primary",onClick:vr,className:"w-full",children:[r.jsx(yr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),Rt&&Ke.total>0&&r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),r.jsxs("span",{children:[Ke.scanned," / ",Ke.total]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ke.scanned/Ke.total*100}%`}})})]}),Qt.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:Qt.length})}),r.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Qt.map(It=>r.jsxs("button",{type:"button",onClick:()=>Fr(It),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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hc,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:It.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:It.ip_address})]})]}),It.state&&r.jsxs("span",{className:`flex items-center gap-1 text-xs ${It.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[r.jsx(_u,{className:"w-3 h-3"}),It.state]})]},It.ip_address))})]}),!Rt&&Qt.length===0&&Ke.total>0&&r.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:n("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&r.jsxs("div",{className:"space-y-3",children:[!or&&r.jsxs("div",{className:"space-y-3",children:[r.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")," ",r.jsx("span",{className:"font-medium",children:n("smartPlugs.haSettingsPath")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:n("smartPlugs.selectEntity")}),r.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:r.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),or&&r.jsxs(r.Fragment,{children:[Gn&&r.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[r.jsx(ft,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),pi&&r.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:pi.message})}),(()=>{const It=yn?.filter(Kt=>Kt.ha_entity_id&&Kt.id!==t?.id).map(Kt=>Kt.ha_entity_id)||[],_n=(Dr||[]).filter(Kt=>!It.includes(Kt.entity_id)),ur=Dr?.find(Kt=>Kt.entity_id===w);return r.jsxs("div",{ref:Ce,className:"relative",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.selectEntity")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:Ee?Re:ur?`${ur.friendly_name} (${ur.entity_id})`:"",onChange:Kt=>{We(Kt.target.value),Ee||it(!0)},onFocus:()=>{it(!0),We("")},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"}),w&&!Ee&&r.jsx("button",{type:"button",onClick:()=>{b(""),We("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Gn&&r.jsx(ft,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Ee&&r.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:[Gn&&r.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!Gn&&_n.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:ze?n("smartPlugs.noEntitiesMatching",{search:ze}):n("smartPlugs.noEntitiesAvailable")}),!Gn&&_n.map(Kt=>r.jsxs("button",{type:"button",onClick:()=>{b(Kt.entity_id),it(!1),We(""),l||c(Kt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Kt.entity_id===w?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[r.jsx("div",{className:"font-medium",children:Kt.friendly_name}),r.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[r.jsx("span",{children:Kt.entity_id}),r.jsx("span",{className:Kt.state==="on"?"text-bambu-green":"",children:Kt.state})]})]},Kt.entity_id))]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ze?n("smartPlugs.searchingEntities",{count:_n.length}):n("smartPlugs.showingEntities",{count:_n.length})})]})})(),w&&Un&&Un.length>0&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium mb-1",children:n("smartPlugs.energyMonitoringOptional")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:n("smartPlugs.energyMonitoringHint")})]}),(()=>{const It=Un.filter(Kt=>Kt.unit_of_measurement==="W"||Kt.unit_of_measurement==="kW"||Kt.unit_of_measurement==="mW"),_n=Ze?It.filter(Kt=>Kt.entity_id.toLowerCase().includes(Ze.toLowerCase())||Kt.friendly_name.toLowerCase().includes(Ze.toLowerCase())):It,ur=Un.find(Kt=>Kt.entity_id===xe);return r.jsxs("div",{ref:rt,className:"relative",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.powerSensorW")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:ke?Ze:ur?`${ur.friendly_name} (${ur.state} ${ur.unit_of_measurement})`:"",onChange:Kt=>{Ie(Kt.target.value),ke||Ve(!0)},onFocus:()=>{Ve(!0),Ie("")},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"}),xe&&!ke&&r.jsx("button",{type:"button",onClick:()=>{ge(""),Ie("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),ke&&r.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:[r.jsx("button",{type:"button",onClick:()=>{ge(""),Ve(!1),Ie("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),_n.map(Kt=>r.jsxs("button",{type:"button",onClick:()=>{ge(Kt.entity_id),Ve(!1),Ie("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Kt.entity_id===xe?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[r.jsx("div",{className:"font-medium",children:Kt.friendly_name}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[Kt.entity_id," • ",Kt.state," ",Kt.unit_of_measurement]})]},Kt.entity_id)),_n.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const It=Un.filter(Kt=>Kt.unit_of_measurement==="kWh"||Kt.unit_of_measurement==="Wh"||Kt.unit_of_measurement==="MWh"),_n=Qe?It.filter(Kt=>Kt.entity_id.toLowerCase().includes(Qe.toLowerCase())||Kt.friendly_name.toLowerCase().includes(Qe.toLowerCase())):It,ur=Un.find(Kt=>Kt.entity_id===Me);return r.jsxs("div",{ref:Tt,className:"relative",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.energyTodayKwh")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:tt?Qe:ur?`${ur.friendly_name} (${ur.state} ${ur.unit_of_measurement})`:"",onChange:Kt=>{Te(Kt.target.value),tt||ot(!0)},onFocus:()=>{ot(!0),Te("")},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"}),Me&&!tt&&r.jsx("button",{type:"button",onClick:()=>{Be(""),Te("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),tt&&r.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:[r.jsx("button",{type:"button",onClick:()=>{Be(""),ot(!1),Te("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),_n.map(Kt=>r.jsxs("button",{type:"button",onClick:()=>{Be(Kt.entity_id),ot(!1),Te("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Kt.entity_id===Me?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[r.jsx("div",{className:"font-medium",children:Kt.friendly_name}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[Kt.entity_id," • ",Kt.state," ",Kt.unit_of_measurement]})]},Kt.entity_id)),_n.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const It=Un.filter(Kt=>Kt.unit_of_measurement==="kWh"||Kt.unit_of_measurement==="Wh"||Kt.unit_of_measurement==="MWh"),_n=Ut?It.filter(Kt=>Kt.entity_id.toLowerCase().includes(Ut.toLowerCase())||Kt.friendly_name.toLowerCase().includes(Ut.toLowerCase())):It,ur=Un.find(Kt=>Kt.entity_id===Fe);return r.jsxs("div",{ref:ln,className:"relative",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.totalEnergyKwh")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:Wt?Ut:ur?`${ur.friendly_name} (${ur.state} ${ur.unit_of_measurement})`:"",onChange:Kt=>{bt(Kt.target.value),Wt||Zt(!0)},onFocus:()=>{Zt(!0),bt("")},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"}),Fe&&!Wt&&r.jsx("button",{type:"button",onClick:()=>{Oe(""),bt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Wt&&r.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:[r.jsx("button",{type:"button",onClick:()=>{Oe(""),Zt(!1),bt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),_n.map(Kt=>r.jsxs("button",{type:"button",onClick:()=>{Oe(Kt.entity_id),Zt(!1),bt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Kt.entity_id===Fe?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[r.jsx("div",{className:"font-medium",children:Kt.friendly_name}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[Kt.entity_id," • ",Kt.state," ",Kt.unit_of_measurement]})]},Kt.entity_id)),_n.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&r.jsxs("div",{className:"space-y-3",children:[!Mn?.mqtt_broker&&r.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")," ",r.jsx("span",{className:"font-medium",children:n("smartPlugs.mqttSettingsPath")})," ",n("smartPlugs.mqttNotConfiguredSuffix")]}),Mn?.mqtt_broker&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[r.jsx("p",{className:"font-medium mb-1",children:n("smartPlugs.monitorOnly")}),r.jsx("p",{className:"text-xs opacity-80",children:n("smartPlugs.mqttMonitorOnlyDescription")})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.powerMonitoring")}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),r.jsx("input",{type:"text",value:x,onChange:It=>S(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),r.jsx("input",{type:"text",value:k,onChange:It=>C(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),r.jsx("input",{type:"text",value:P,onChange:It=>T(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttPowerHint")})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),r.jsx("input",{type:"text",value:A,onChange:It=>F(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),r.jsx("input",{type:"text",value:_,onChange:It=>M(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),r.jsx("input",{type:"text",value:H,onChange:It=>I(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttEnergyHint")})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),r.jsx("input",{type:"text",value:z,onChange:It=>L(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),r.jsx("input",{type:"text",value:Z,onChange:It=>ne(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.onValue")}),r.jsx("input",{type:"text",value:Y,onChange:It=>ce(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.restControl")}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restMethod")}),r.jsxs("select",{value:J,onChange:It=>j(It.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:[r.jsx("option",{value:"GET",children:"GET"}),r.jsx("option",{value:"POST",children:"POST"}),r.jsx("option",{value:"PUT",children:"PUT"}),r.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOnUrl")}),r.jsx("input",{type:"text",value:ue,onChange:It=>{oe(It.target.value),Nt(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"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOnBody")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsx("input",{type:"text",value:Q,onChange:It=>le(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOffUrl")}),r.jsx("input",{type:"text",value:pe,onChange:It=>{he(It.target.value),Nt(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"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOffBody")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsx("input",{type:"text",value:we,onChange:It=>$(It.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"})]})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.restHeaders")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsx("div",{children:r.jsx("textarea",{value:E,onChange:It=>B(It.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"})})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusUrl")}),r.jsx("input",{type:"text",value:W,onChange:It=>O(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusPath")}),r.jsx("input",{type:"text",value:ie,onChange:It=>U(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusOnValue")}),r.jsx("input",{type:"text",value:G,onChange:It=>K(It.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"})]})]})]}),r.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restPowerUrl")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsx("input",{type:"text",value:X,onChange:It=>se(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerPath")}),r.jsx("input",{type:"text",value:te,onChange:It=>fe(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerMultiplier")}),r.jsx("input",{type:"text",value:de,onChange:It=>me(It.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"})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restEnergyUrl")," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),r.jsx("input",{type:"text",value:q,onChange:It=>R(It.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyPath")}),r.jsx("input",{type:"text",value:re,onChange:It=>be(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyMultiplier")}),r.jsx("input",{type:"text",value:ye,onChange:It=>_e(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.restEnergyHint")})]}),(ue.trim()||pe.trim())&&r.jsx("div",{className:"flex gap-2",children:r.jsxs(je,{type:"button",variant:"secondary",onClick:async()=>{Nt(null);try{const It=ue.trim()||pe.trim(),_n=await ae.testRESTConnection(It,J,E.trim()||null);Nt({success:_n.success}),_n.success||Ct(_n.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{Nt({success:!1}),Ct(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[r.jsx(Mh,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),kt&&r.jsxs("div",{className:`flex items-center gap-2 text-sm ${kt.success?"text-green-400":"text-red-400"}`,children:[kt.success?r.jsx(xr,{className:"w-4 h-4"}):r.jsx(hu,{className:"w-4 h-4"}),kt.success?n("smartPlugs.connectionSuccess"):n("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.ipAddress")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:d,onChange:It=>{u(It.target.value),Nt(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"}),r.jsxs(je,{type:"button",variant:"secondary",onClick:()=>ba.mutate(),disabled:!d.trim()||ba.isPending,children:[ba.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Mh,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&kt&&r.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${kt.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:kt.success?r.jsxs(r.Fragment,{children:[r.jsx(xr,{className:"w-5 h-5"}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium",children:n("smartPlugs.connectedResult")}),r.jsxs("p",{className:"text-sm opacity-80",children:[kt.device_name&&n("smartPlugs.deviceLabel",{name:kt.device_name}),n("smartPlugs.stateLabel",{state:kt.state})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx(hu,{className:"w-5 h-5"}),r.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.nameLabel")}),r.jsx("input",{type:"text",value:l,onChange:It=>c(It.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"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.username")}),r.jsx("input",{type:"text",value:m,onChange:It=>p(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.password")}),r.jsx("input",{type:"password",value:f,onChange:It=>g(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:n("smartPlugs.authHint")})]}),s!=="mqtt"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.linkToPrinter")}),r.jsxs("select",{value:cn??"",onChange:It=>ct(It.target.value?Number(It.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:[r.jsx("option",{value:"",children:n("smartPlugs.noPrinter")}),wd?.map(It=>r.jsx("option",{value:It.id,children:It.name},It.id))]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.linkingDescription")})]}),r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ch,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.powerAlerts")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Le,onChange:It=>Ae(It.target.checked),className:"sr-only peer"}),r.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"})]})]}),Le&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertAbove")}),r.jsx("input",{type:"number",value:Ge,onChange:It=>Je(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertBelow")}),r.jsx("input",{type:"number",value:De,onChange:It=>mt(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Zn,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.dailySchedule")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Ne,onChange:It=>Ye(It.target.checked),className:"sr-only peer"}),r.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"})]})]}),Ne&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOnAt")}),r.jsx("input",{type:"time",value:nt,onChange:It=>at(It.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOffAt")}),r.jsx("input",{type:"time",value:et,onChange:It=>vt(It.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"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.scheduleDescription")})]})]}),r.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(jS,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showInSwitchbar")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:wt,onChange:It=>Ue(It.target.checked),className:"sr-only peer"}),r.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"&&r.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cl,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showOnPrinterCard")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.displayOnPrinterCard")})]})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:He,onChange:It=>Dt(It.target.checked),className:"sr-only peer"}),r.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"})]})]})}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),r.jsxs(je,{type:"submit",disabled:zs,className:"flex-1",children:[zs?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(ds,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function En({checked:t,onChange:e,disabled:n}){const a=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return r.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:a,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:r.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 Xrt({provider:t,onEdit:e}){const{t:n}=_t(),a=tn(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(null),{data:u}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>ae.updateNotificationProvider(t.id,b),onSuccess:()=>{a.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>ae.deleteNotificationProvider(t.id),onSuccess:()=>{a.invalidateQueries({queryKey:["notification-providers"]})}}),g=lt({mutationFn:()=>ae.testNotificationProvider(t.id),onSuccess:b=>{d(b),a.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),w=b=>b||"";return r.jsxs(r.Fragment,{children:[r.jsx(At,{className:"relative",children:r.jsxs(Et,{className:"p-3",children:[r.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:r.jsx(Ch,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{children:[r.jsx("h3",{className:"font-medium text-white",children:t.name}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&r.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:n("notifications.lastSuccess",{date:Dg(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Yn(t.last_error_at)?.getTime()||0)>(Yn(t.last_success)?.getTime()||0))&&r.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),r.jsx(En,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&r.jsxs(r.Fragment,{children:[m&&r.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[r.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("notifications.printer")," "]}),r.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&r.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.allPrinters")})}),r.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.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&&r.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:n("notifications.missingSpoolAssignmentLabel")}),t.on_stock_reorder_alert&&r.jsx("span",{className:"px-2 py-0.5 bg-lime-500/20 text-lime-400 text-xs rounded",children:n("notifications.stockReorderAlert")}),t.on_stock_break_alert&&r.jsx("span",{className:"px-2 py-0.5 bg-red-600/20 text-red-300 text-xs rounded",children:n("notifications.stockBreakAlert")}),t.quiet_hours_enabled&&r.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[r.jsx(aC,{className:"w-3 h-3"}),n("notifications.quiet")]}),t.daily_digest_enabled&&r.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[r.jsx(wa,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),r.jsx("div",{className:"mb-3",children:r.jsxs(je,{size:"sm",variant:"secondary",disabled:g.isPending,onClick:()=>{d(null),g.mutate()},className:"w-full",children:[g.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(LS,{className:"w-4 h-4"}),n("notifications.sendTestNotification")]})}),c&&r.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?r.jsx(xr,{className:"w-4 h-4"}):r.jsx($r,{className:"w-4 h-4"}),r.jsx("span",{children:c.message})]})]}),r.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:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(pu,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"})]}),o&&r.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.enabled")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.sendFromProvider")})]}),r.jsx(En,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printEvents")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printStarted")}),r.jsx(En,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.plateNotEmpty")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.plateNotEmptyDescription")})]}),r.jsx(En,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printCompleted")}),r.jsx(En,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.bedCooledLabel")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.bedCooledDescription")})]}),r.jsx(En,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.firstLayerCompleteDescription")})]}),r.jsx(En,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.missingSpoolAssignmentLabel")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.missingSpoolAssignmentDescription")})]}),r.jsx(En,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printFailed")}),r.jsx(En,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printStopped")}),r.jsx(En,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.progressMilestones")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.progressMilestonesDescription")})]}),r.jsx(En,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printerStatus")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printerOffline")}),r.jsx(En,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.printerError")}),r.jsx(En,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.lowFilamentLabel")}),r.jsx(En,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.maintenanceDue")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.maintenanceDueDescription")})]}),r.jsx(En,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsAlarms")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHumidityHigh")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHumidityHighDescription")})]}),r.jsx(En,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.amsTemperatureHigh")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsTemperatureHighDescription")})]}),r.jsx(En,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsHtAlarms")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtHumidityHigh")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtHumidityHighDescription")})]}),r.jsx(En,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtTemperatureHigh")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtTemperatureHighDescription")})]}),r.jsx(En,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.inventoryAlerts")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.stockReorderAlert")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.stockReorderAlertDescription")})]}),r.jsx(En,{checked:t.on_stock_reorder_alert??!1,onChange:b=>p.mutate({on_stock_reorder_alert:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.stockBreakAlert")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.stockBreakAlertDescription")})]}),r.jsx(En,{checked:t.on_stock_break_alert??!1,onChange:b=>p.mutate({on_stock_break_alert:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printQueue")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAdded")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAddedDescription")})]}),r.jsx(En,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAssigned")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAssignedDescription")})]}),r.jsx(En,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobStarted")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobStartedDescription")})]}),r.jsx(En,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobWaiting")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobWaitingDescription")})]}),r.jsx(En,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobSkipped")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobSkippedDescription")})]}),r.jsx(En,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.jobFailed")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobFailedDescription")})]}),r.jsx(En,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:n("notifications.queueComplete")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.queueCompleteDescription")})]}),r.jsx(En,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(aC,{className:"w-4 h-4 text-purple-400"}),r.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),r.jsx(En,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&r.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.noNotificationsDuring")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Zn,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-white",children:[w(t.quiet_hours_start)||"22:00"," - ",w(t.quiet_hours_end)||"07:00"]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeQuietHours")})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(wa,{className:"w-4 h-4 text-emerald-400"}),r.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),r.jsx(En,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&r.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Zn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:n("notifications.sendAt",{time:w(t.daily_digest_time)||"08:00"})})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeDigestTime")})]})]}),r.jsxs("div",{className:"flex gap-2 pt-2",children:[r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[r.jsx(uc,{className:"w-4 h-4"}),n("notifications.edit")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:r.jsx(en,{className:"w-4 h-4"})})]})]})]})}),i&&r.jsx(wn,{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 Zrt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function Jrt({provider:t,onClose:e}){const{t:n}=_t(),a=tn(),i=!!t,[s,o]=y.useState(t?.name||""),[l,c]=y.useState(t?.provider_type||"email"),[d,u]=y.useState(t?.printer_id||null),[m,p]=y.useState(t?.quiet_hours_enabled||!1),[f,g]=y.useState(t?.quiet_hours_start||"22:00"),[w,b]=y.useState(t?.quiet_hours_end||"07:00"),[x,S]=y.useState(t?.daily_digest_enabled||!1),[k,C]=y.useState(t?.daily_digest_time||"08:00"),[P,T]=y.useState(t?.on_print_start??!1),[A,F]=y.useState(t?.on_print_complete??!0),[_,M]=y.useState(t?.on_print_failed??!0),[H,I]=y.useState(t?.on_print_stopped??!0),[z,L]=y.useState(t?.on_print_progress??!1),[Z,ne]=y.useState(t?.on_printer_offline??!1),[Y,ce]=y.useState(t?.on_printer_error??!1),[ue,oe]=y.useState(t?.on_filament_low??!1),[Q,le]=y.useState(t?.on_maintenance_due??!1),[pe,he]=y.useState(t?.on_stock_reorder_alert??!1),[we,$]=y.useState(t?.on_stock_break_alert??!1),[J,j]=y.useState(t?.on_bed_cooled??!1),[E,B]=y.useState(t?.on_first_layer_complete??!1),[W,O]=y.useState(t?.config?Object.fromEntries(Object.entries(t.config).filter(([xe])=>xe!=="event_priorities").map(([xe,ge])=>[xe,String(ge)])):{}),ie=(()=>{const xe=t?.config?.event_priorities;if(!xe||typeof xe!="object")return{};const ge={};for(const[Me,Be]of Object.entries(xe)){const Fe=Number(Be);Number.isInteger(Fe)&&Fe>=1&&Fe<=5&&(ge[Me]=Fe)}return ge})(),[U,G]=y.useState(ie),[K,X]=y.useState(null),[se,te]=y.useState(null),{data:fe}=Xe({queryKey:["printers"],queryFn:ae.getPrinters});y.useEffect(()=>{const xe=ge=>{ge.key==="Escape"&&e()};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[e]);const de=lt({mutationFn:()=>ae.testNotificationConfig({provider_type:l,config:W}),onSuccess:xe=>{X(xe),te(null)},onError:xe=>{X({success:!1,message:xe.message})}}),me=lt({mutationFn:xe=>ae.createNotificationProvider(xe),onSuccess:()=>{a.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:xe=>{te(xe.message)}}),q=lt({mutationFn:xe=>ae.updateNotificationProvider(t.id,xe),onSuccess:()=>{a.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:xe=>{te(xe.message)}}),R=xe=>{if(xe.preventDefault(),te(null),!s.trim()){te(n("notifications.nameRequired"));return}const ge=ye(l);for(const Fe of ge)if(!W[Fe.key]?.trim()){te(n("notifications.fieldRequired",{field:Fe.label}));return}const Me=l==="ntfy"&&Object.keys(U).length>0?{...W,event_priorities:U}:W,Be={name:s.trim(),provider_type:l,config:Me,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?w:null,daily_digest_enabled:x,daily_digest_time:x?k:null,on_print_start:P,on_print_complete:A,on_print_failed:_,on_print_stopped:H,on_print_progress:z,on_printer_offline:Z,on_printer_error:Y,on_filament_low:ue,on_maintenance_due:Q,on_stock_reorder_alert:pe,on_stock_break_alert:we,on_bed_cooled:J,on_first_layer_complete:E};i?q.mutate(Be):me.mutate(Be)},re=me.isPending||q.isPending,be=xe=>{switch(xe){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:ge=>ge.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:ge=>ge.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},ye=xe=>be(xe).filter(ge=>ge.required),_e=be(l);return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:r.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:xe=>xe.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"notifications.editTitle":"notifications.addTitle")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:R,className:"p-6 space-y-4",children:[se&&r.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:se}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.nameLabel")}),r.jsx("input",{type:"text",value:s,onChange:xe=>o(xe.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.providerTypeLabel")}),r.jsx("select",{value:l,onChange:xe=>{c(xe.target.value),O({}),X(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:Zrt.map(xe=>r.jsx("option",{value:xe,children:n(`notifications.providerTypes.${xe}`,xe)},xe))}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n(`notifications.providerDescriptions.${l}`,"")})]}),r.jsxs("div",{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.configuration")}),_e.filter(xe=>!("showIf"in xe)||xe.showIf?.(W)!==!1).map(xe=>r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[xe.label," ",xe.required&&"*"]}),xe.type==="select"&&"options"in xe&&xe.options?r.jsx("select",{value:W[xe.key]||xe.options[0]?.value||"",onChange:ge=>{O({...W,[xe.key]:ge.target.value}),X(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:xe.options.map(ge=>r.jsx("option",{value:ge.value,children:ge.label},ge.value))}):r.jsx("input",{type:xe.type,value:W[xe.key]||"",onChange:ge=>{O({...W,[xe.key]:ge.target.value}),X(null)},placeholder:xe.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"})]},xe.key))]}),r.jsx("div",{className:"flex gap-2",children:r.jsxs(je,{type:"button",variant:"secondary",onClick:()=>{X(null),de.mutate()},disabled:de.isPending||ye(l).length>0&&!W[ye(l)[0]?.key],className:"flex-1",children:[de.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(LS,{className:"w-4 h-4"}),n("notifications.testConfiguration")]})}),K&&r.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${K.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:K.success?r.jsxs(r.Fragment,{children:[r.jsx(xr,{className:"w-5 h-5"}),r.jsx("span",{children:K.message})]}):r.jsxs(r.Fragment,{children:[r.jsx($r,{className:"w-5 h-5"}),r.jsx("span",{children:K.message})]})}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.printerFilter")}),r.jsxs("select",{value:d??"",onChange:xe=>u(xe.target.value?Number(xe.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:[r.jsx("option",{value:"",children:n("notifications.allPrinters")}),fe?.map(xe=>r.jsx("option",{value:xe.id,children:xe.name},xe.id))]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.onlyFromPrinter")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("label",{className:"text-sm text-white",children:n("notifications.quietHoursDnd")}),r.jsx(En,{checked:m,onChange:p})]}),m&&r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietStart")}),r.jsx("input",{type:"time",value:f,onChange:xe=>g(xe.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietEnd")}),r.jsx("input",{type:"time",value:w,onChange:xe=>b(xe.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"})]})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-sm text-white",children:n("notifications.dailyDigestLabel")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")})]}),r.jsx(En,{checked:x,onChange:S})]}),x&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.sendDigestAt")}),r.jsx("input",{type:"time",value:k,onChange:xe=>C(xe.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.digestCollected")})]})]}),r.jsxs("div",{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.notificationEvents")}),r.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printEvents")}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.start")}),r.jsx(En,{checked:P,onChange:T})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),r.jsx(En,{checked:A,onChange:F})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),r.jsx(En,{checked:_,onChange:M})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),r.jsx(En,{checked:H,onChange:I})]}),r.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.progress")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.progressPercent")})]}),r.jsx(En,{checked:z,onChange:L})]}),r.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.bedCooled")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.bedCooledAfterPrint")})]}),r.jsx(En,{checked:J,onChange:j})]}),r.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.firstLayerCompleteDescription")})]}),r.jsx(En,{checked:E,onChange:B})]})]})]}),r.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printerStatus")}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.offline")}),r.jsx(En,{checked:Z,onChange:ne})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.error")}),r.jsx(En,{checked:Y,onChange:ce})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),r.jsx(En,{checked:ue,onChange:oe})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),r.jsx(En,{checked:Q,onChange:le})]})]})]}),r.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.inventoryAlerts")}),r.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.stockReorderAlert")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.stockReorderAlertDescription")})]}),r.jsx(En,{checked:pe,onChange:he})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("notifications.stockBreakAlert")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.stockBreakAlertDescription")})]}),r.jsx(En,{checked:we,onChange:$})]})]})]}),l==="ntfy"&&(()=>{const xe=[];return P&&xe.push({key:"on_print_start",label:n("notifications.start")}),A&&xe.push({key:"on_print_complete",label:n("notifications.complete")}),_&&xe.push({key:"on_print_failed",label:n("notifications.failed")}),H&&xe.push({key:"on_print_stopped",label:n("notifications.stopped")}),z&&xe.push({key:"on_print_progress",label:n("notifications.progress")}),J&&xe.push({key:"on_bed_cooled",label:n("notifications.bedCooled")}),E&&xe.push({key:"on_first_layer_complete",label:n("notifications.firstLayerCompleteLabel")}),Z&&xe.push({key:"on_printer_offline",label:n("notifications.offline")}),Y&&xe.push({key:"on_printer_error",label:n("notifications.error")}),ue&&xe.push({key:"on_filament_low",label:n("notifications.lowFilament")}),Q&&xe.push({key:"on_maintenance_due",label:n("notifications.maintenance")}),pe&&xe.push({key:"on_stock_reorder_alert",label:n("notifications.stockReorderAlert")}),we&&xe.push({key:"on_stock_break_alert",label:n("notifications.stockBreakAlert")}),xe.length===0?null:r.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-1",children:n("notifications.eventPriority.sectionTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("notifications.eventPriority.helpNtfy")}),r.jsx("div",{className:"space-y-2",children:xe.map(ge=>r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsx("span",{className:"text-sm text-white",children:ge.label}),r.jsxs("select",{value:U[ge.key]??3,onChange:Me=>{const Be=Number(Me.target.value);G(Fe=>({...Fe,[ge.key]:Be}))},className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:1,children:n("notifications.eventPriority.min")}),r.jsx("option",{value:2,children:n("notifications.eventPriority.low")}),r.jsx("option",{value:3,children:n("notifications.eventPriority.default")}),r.jsx("option",{value:4,children:n("notifications.eventPriority.high")}),r.jsx("option",{value:5,children:n("notifications.eventPriority.urgent")})]})]},ge.key))})]})})()]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),r.jsxs(je,{type:"submit",disabled:re,className:"flex-1",children:[re?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(ds,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function eat({template:t,onClose:e}){const{t:n}=_t(),a=tn(),i=y.useRef(null),[s,o]=y.useState(t.title_template),[l,c]=y.useState(t.body_template),[d,u]=y.useState(null),[m,p]=y.useState(!0),{data:f}=Xe({queryKey:["template-variables"],queryFn:ae.getTemplateVariables}),g=f?.find(T=>T.event_type===t.event_type),{data:w,isLoading:b}=Xe({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>ae.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});y.useEffect(()=>{const T=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e]);const x=lt({mutationFn:T=>ae.updateNotificationTemplate(t.id,T),onSuccess:()=>{a.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:T=>{u(T.message)}}),S=lt({mutationFn:()=>ae.resetNotificationTemplate(t.id),onSuccess:T=>{o(T.title_template),c(T.body_template),a.invalidateQueries({queryKey:["notification-templates"]})},onError:T=>{u(T.message)}}),k=T=>{if(T.preventDefault(),u(null),!s.trim()){u(n("notifications.titleRequired"));return}if(!l.trim()){u(n("notifications.bodyRequired"));return}x.mutate({title_template:s,body_template:l})},C=T=>{const A=i.current;if(!A)return;const F=A.selectionStart,_=A.selectionEnd,M=l,H=M.substring(0,F),I=M.substring(_),z=H+`{${T}}`+I;c(z),setTimeout(()=>{A.focus();const L=F+T.length+2;A.setSelectionRange(L,L)},0)},P=s!==t.title_template||l!==t.body_template;return r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("notifications.editTemplate",{name:t.name})}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("form",{onSubmit:k,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&r.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.titleLabel")}),r.jsx("input",{type:"text",value:s,onChange:T=>o(T.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.bodyLabel")}),r.jsx("textarea",{ref:i,value:l,onChange:T=>c(T.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")})]}),g&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:n("notifications.availableVariables")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:g.variables.map(T=>r.jsxs("button",{type:"button",onClick:()=>C(T),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:[r.jsx(er,{className:"w-3 h-3"}),T]},T))}),r.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:n("notifications.clickToInsert")})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[r.jsx(Cl,{className:"w-4 h-4"}),n("notifications.livePreview")]}),r.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&&r.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("notifications.loadingPreview")]}):w?r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.titlePreview")}),r.jsx("div",{className:"text-white font-medium",children:w.title})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.bodyPreview")}),r.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:w.body})]})]}):r.jsx("div",{className:"text-bambu-gray text-sm",children:n("notifications.enterTemplateContent")})})]})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[r.jsxs(je,{type:"button",variant:"ghost",onClick:()=>S.mutate(),disabled:S.isPending,className:"text-orange-400 hover:text-orange-300",children:[S.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(fs,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),r.jsxs(je,{onClick:k,disabled:x.isPending||!P,children:[x.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(ds,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const tat={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 nat({onClose:t}){const{t:e}=_t(),n=tn(),{showToast:a}=on(),[i,s]=y.useState(7),[o,l]=y.useState(null),[c,d]=y.useState(!1),{data:u}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:g,isRefetching:w}=Xe({queryKey:["notification-logs",i,c],queryFn:()=>ae.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=Xe({queryKey:["notification-log-stats",i],queryFn:()=>ae.getNotificationLogStats(i)}),x=lt({mutationFn:()=>ae.clearNotificationLogs(30),onSuccess:k=>{a(k.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:k=>{a(`Failed to clear logs: ${k.message}`,"error")}}),S=k=>{const C=Yn(k);if(!C)return"";const T=new Date().getTime()-C.getTime();return T<6e4?e("notifications.justNow"):T<36e5?`${Math.floor(T/6e4)}m ago`:T<864e5?`${Math.floor(T/36e5)}h ago`:C.toLocaleDateString()+" "+lJ(C,m)};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.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:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Vh,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&r.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:r.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[r.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",r.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[r.jsx(xr,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx($r,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),r.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[r.jsxs("select",{value:i,onChange:k=>s(Number(k.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:[r.jsx("option",{value:1,children:e("notifications.last24Hours")}),r.jsx("option",{value:7,children:e("notifications.last7Days")}),r.jsx("option",{value:30,children:e("notifications.last30Days")}),r.jsx("option",{value:90,children:e("notifications.last90Days")})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:k=>d(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),r.jsx("div",{className:"flex-1"}),r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:w,children:[w?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),e("notifications.refresh")]}),r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>x.mutate(),disabled:x.isPending,className:"text-red-400 hover:text-red-300",children:[x.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?r.jsx("div",{className:"space-y-2",children:p.map(k=>r.jsx(rat,{log:k,isExpanded:o===k.id,onToggle:()=>l(o===k.id?null:k.id),formatDate:S,formatFullDate:C=>Fg(C,m)},k.id))}):r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Vh,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),r.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function rat({log:t,isExpanded:e,onToggle:n,formatDate:a,formatFullDate:i}){const{t:s}=_t();return r.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:[r.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?r.jsx(xr,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx($r,{className:"w-4 h-4 text-red-400 shrink-0"}),r.jsx("span",{className:`text-xs font-medium ${tat[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),r.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&r.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),r.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:a(t.created_at)}),e?r.jsx(Zo,{className:"w-4 h-4 text-bambu-gray shrink-0"}):r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&r.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),r.jsx("p",{className:"text-sm text-white",children:t.title})]}),r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),r.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),r.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),r.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[r.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),r.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}const aat=300,E0=2;function zce({onSuccess:t}){const{t:e}=_t(),n=tn(),[a,i]=y.useState(""),[s,o]=y.useState(""),[l,c]=y.useState(null),[d,u]=y.useState(null);y.useEffect(()=>{const k=a.trim();if(k.length<E0){o("");return}const C=setTimeout(()=>o(k),aat);return()=>clearTimeout(C)},[a]),y.useEffect(()=>{c(null),u(null)},[s]);const m=Xe({queryKey:["ldap-search",s],queryFn:()=>ae.searchLDAPDirectory(s),enabled:s.length>=E0,staleTime:3e4}),p=lt({mutationFn:k=>ae.provisionLDAPUser(k),onSuccess:k=>{n.invalidateQueries({queryKey:["users"]}),t(k)},onError:k=>{u(k.message||e("users.modal.ldapErrorProvision"))}}),f=y.useMemo(()=>m.data?.find(k=>k.dn===l)??null,[m.data,l]),g=a.trim().length>0&&a.trim().length<E0,w=m.isFetching&&s.length>=E0,b=!!m.data&&m.data.length>0,x=!w&&!!m.data&&m.data.length===0&&s.length>=E0,S=()=>{!f||f.already_provisioned||(u(null),p.mutate(f.username))};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:e("users.modal.ldapSearchLabel")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2"}),r.jsx("input",{type:"text",value:a,onChange:k=>i(k.target.value),className:"w-full pl-9 pr-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("users.modal.ldapSearchPlaceholder"),autoComplete:"off"})]}),g&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:e("users.modal.ldapMinChars")})]}),r.jsxs("div",{className:"min-h-[8rem] max-h-64 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[w&&r.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),r.jsx("span",{children:e("users.modal.ldapSearching")})]}),x&&r.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapNoResults")}),m.isError&&r.jsx("div",{className:"px-3 py-4 text-sm text-red-400",children:m.error instanceof Error?m.error.message:e("users.modal.ldapSearchError")}),!w&&b&&r.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary",children:m.data.map(k=>r.jsx(iat,{result:k,selected:l===k.dn,onSelect:()=>c(k.dn)},k.dn))}),!w&&!m.data&&!m.isError&&r.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapTypeToSearch")})]}),f&&r.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-1",children:[r.jsxs("p",{className:"text-sm text-white",children:[r.jsxs("span",{className:"text-bambu-gray",children:[e("users.modal.ldapSelectedLabel"),": "]}),r.jsx("span",{className:"font-medium",children:f.username}),f.display_name&&r.jsxs("span",{className:"text-bambu-gray",children:[" — ",f.display_name]})]}),f.email&&r.jsx("p",{className:"text-xs text-bambu-gray",children:f.email}),r.jsx("p",{className:"text-xs text-bambu-gray break-all",children:f.dn})]}),d&&r.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3",children:r.jsx("p",{className:"text-sm text-red-400",children:d})}),r.jsx("div",{className:"flex justify-end",children:r.jsx(je,{onClick:S,disabled:!f||f.already_provisioned||p.isPending,children:p.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),e("users.modal.ldapProvisioning")]}):r.jsxs(r.Fragment,{children:[r.jsx(er,{className:"w-4 h-4"}),e("users.modal.ldapProvision")]})})})]})}function iat({result:t,selected:e,onSelect:n}){const{t:a}=_t(),i=t.already_provisioned;return r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:n,disabled:i,className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${i?"opacity-50 cursor-not-allowed":e?"bg-bambu-green/10":"hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("p",{className:"text-sm text-white truncate",children:[r.jsx("span",{className:"font-medium",children:t.username}),t.display_name&&r.jsxs("span",{className:"text-bambu-gray",children:[" — ",t.display_name]})]}),t.email&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:t.email})]}),i&&r.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray whitespace-nowrap",children:[r.jsx(yl,{className:"w-3.5 h-3.5"}),a("users.modal.ldapAlreadyProvisioned")]})]})})}function sat({formData:t,setFormData:e,groups:n,onClose:a,onCreate:i,isCreating:s,isCreateButtonDisabled:o,ldapEnabled:l=!1,onLdapProvisioned:c}){const{t:d}=_t(),[u,m]=y.useState("local");y.useEffect(()=>{const f=g=>{g.key==="Escape"&&a()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a]);const p=f=>{e({...t,group_ids:t.group_ids.includes(f)?t.group_ids.filter(g=>g!==f):[...t.group_ids,f]})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:r.jsxs(At,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(bm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:d("users.modal.createUser")})]}),r.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:d("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:a,children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsxs(Et,{children:[l&&r.jsxs("div",{className:"mb-4 flex items-center gap-1 p-1 bg-bambu-dark-secondary rounded-lg",role:"tablist","aria-label":d("users.modal.tabsAriaLabel"),children:[r.jsx("button",{type:"button",role:"tab","aria-selected":u==="local",onClick:()=>m("local"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="local"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.localTab")}),r.jsx("button",{type:"button",role:"tab","aria-selected":u==="ldap",onClick:()=>m("ldap"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="ldap"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.ldapTab")})]}),u==="ldap"&&l?r.jsx(zce,{onSuccess:f=>{c?.(f)}}):r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.username")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"text",value:t.username,onChange:f=>e({...t,username:f.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:d("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.email")||"Email"," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"email",value:t.email,onChange:f=>e({...t,email:f.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:d("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),r.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:d("users.form.groups")}),r.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(f=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:t.group_ids.includes(f.id),onChange:()=>p(f.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),r.jsx("span",{className:"text-sm text-white",children:f.name}),f.is_system&&r.jsxs("span",{className:"text-xs text-yellow-400",children:["(",d("users.system"),")"]})]},f.id)),n.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.noGroupsAvailable")})]})]})]}),r.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[r.jsx(je,{variant:"secondary",onClick:a,children:d("users.modal.cancel")}),u==="local"&&r.jsx(je,{onClick:i,disabled:o,children:s?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),d("users.modal.creating")]}):r.jsxs(r.Fragment,{children:[r.jsx(er,{className:"w-4 h-4"}),d("users.modal.createUser")]})})]})]})]})})}function oat(){const{t}=_t(),e=tn(),{showToast:n}=on(),[a,i]=y.useState(!1),[s,o]=y.useState(""),[l,c]=y.useState("auto"),[d,u]=y.useState(!1),[m,p]=y.useState(!0),[f,g]=y.useState("all"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[k,C]=y.useState(!1),[P,T]=y.useState(!1),{data:A,isLoading:F}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings}),{data:_,isLoading:M,refetch:H}=Xe({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,refetchInterval:3e4}),{data:I}=Xe({queryKey:["printers"],queryFn:ae.getPrinters});y.useEffect(()=>{A&&(i(A.spoolman_enabled==="true"),o(A.spoolman_url||""),c(A.spoolman_sync_mode||"auto"),u(A.spoolman_disable_weight_sync==="true"),p(A.spoolman_report_partial_usage!=="false"),b(!0))},[A]),y.useEffect(()=>{if(!w||!A)return;if(A.spoolman_enabled==="true"!==a||(A.spoolman_url||"")!==s||(A.spoolman_sync_mode||"auto")!==l||A.spoolman_disable_weight_sync==="true"!==d||A.spoolman_report_partial_usage!=="false"!==m){const we=setTimeout(()=>{z.mutate()},500);return()=>clearTimeout(we)}},[a,s,l,d,m,w]);const z=lt({mutationFn:()=>ae.updateSpoolmanSettings({spoolman_enabled:a?"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"]}),e.invalidateQueries({queryKey:["spoolman-inventory-filaments"]}),n(t("settings.toast.settingsSaved"))},onError:()=>{n(t("settings.toast.saveFailed"),"error")}}),L=lt({mutationFn:ae.connectSpoolman,onSuccess:()=>{H()},onError:()=>{n(t("settings.toast.saveFailed"),"error")}}),Z=lt({mutationFn:ae.disconnectSpoolman,onSuccess:()=>{H()},onError:()=>{n(t("settings.toast.saveFailed"),"error")}}),ne=lt({mutationFn:ae.syncAllPrintersAms,onSuccess:he=>{n(t("settings.spoolmanAmsSyncSuccess",{synced:he.synced_count,skipped:0}),"success")},onError:()=>{n(t("settings.toast.saveFailed"),"error")}}),Y=lt({mutationFn:he=>ae.syncPrinterAms(he),onSuccess:he=>{n(t("settings.spoolmanAmsSyncSuccess",{synced:he.synced_count,skipped:0}),"success")},onError:()=>{n(t("settings.toast.saveFailed"),"error")}}),ce=()=>{f==="all"?ne.mutate():Y.mutate(f)},ue=lt({mutationFn:ae.syncWeightsFromAms,onSuccess:he=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:he.synced,skipped:he.skipped}),"success"),C(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),C(!1)}}),oe=lt({mutationFn:ae.syncSpoolmanAmsWeights,onSuccess:he=>{e.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),n(t("settings.spoolmanAmsSyncSuccess",{synced:he.synced,skipped:he.skipped}),"success"),T(!1)},onError:he=>{he instanceof rs&&he.status===503?n(t("settings.spoolmanAmsSyncErrorUnreachable"),"error"):he instanceof rs&&he.status===400?n(t("settings.spoolmanAmsSyncErrorNotConfigured"),"error"):n(t("settings.spoolmanAmsSyncError"),"error"),T(!1)}}),Q=ne.isPending||Y.isPending,le=f==="all"?ne.data:Y.data,pe=f==="all"?ne.isSuccess:Y.isSuccess;return F?r.jsxs(At,{id:"card-spoolman",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),r.jsx(Et,{children:r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):r.jsxs(At,{id:"card-spoolman",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(dc,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),z.isPending&&r.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${a?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx(Vr,{className:`w-4 h-4 ${a?"text-bambu-gray":"text-bambu-green"}`}),r.jsx("span",{className:`text-sm font-medium ${a?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),r.jsx("p",{className:`text-xs ${a?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!a&&r.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}),r.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),r.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${a?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx(zr,{className:`w-4 h-4 ${a?"text-bambu-green":"text-bambu-gray"}`}),r.jsx("span",{className:`text-sm font-medium ${a?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),r.jsx("p",{className:`text-xs ${a?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),a&&r.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}),r.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!a&&r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(_i,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[r.jsx("li",{children:t("settings.builtInFeatureRfid")}),r.jsx("li",{children:t("settings.builtInFeatureUsage")}),r.jsx("li",{children:t("settings.builtInFeatureCatalog")}),r.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:ue.isPending,children:[ue.isPending?r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(tr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),a&&r.jsxs("div",{className:"space-y-4",children:[r.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(_i,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-xs text-blue-300",children:[r.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),r.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[r.jsx("li",{children:t("settings.syncInfoRfidOnly")}),r.jsx("li",{children:t("settings.syncInfoAutoCreate")}),r.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),r.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),r.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),r.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:he=>o(he.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),r.jsxs("select",{value:l,onChange:he=>c(he.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),r.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:d,onChange:he=>u(he.target.checked),className:"sr-only peer"}),r.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&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:m,onChange:he=>p(he.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),M?r.jsx(ft,{className:"w-4 h-4 text-bambu-gray animate-spin"}):_?.connected?r.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[r.jsx(Ar,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):r.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[r.jsx(Vt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),r.jsx("div",{className:"flex gap-2",children:_?.connected?r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Z.mutate(),disabled:Z.isPending,children:[Z.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(fxe,{className:"w-4 h-4"}),t("settings.disconnect")]}):r.jsxs(je,{size:"sm",onClick:()=>L.mutate(),disabled:L.isPending||!s,children:[L.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(jh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),(L.isError||Z.isError)&&r.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:(L.error||Z.error).message}),_?.connected&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsxs("select",{value:f,onChange:he=>g(he.target.value==="all"?"all":Number(he.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:[r.jsx("option",{value:"all",children:t("settings.allPrinters")}),I?.map(he=>r.jsx("option",{value:he.id,children:he.name},he.id))]}),r.jsx(Ln,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:ce,disabled:Q,children:[Q?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),_?.connected&&r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-white",children:t("settings.spoolmanAmsSyncButton")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.spoolmanAmsSyncMessage")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>T(!0),disabled:oe.isPending,children:[oe.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),oe.isPending?t("settings.spoolmanAmsSyncing"):t("settings.spoolmanAmsSyncButton")]})]})}),pe&&le&&r.jsxs("div",{className:"mt-3 space-y-2",children:[r.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&&r.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[r.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{className:"font-medium",children:[le.skipped_count," spool",le.skipped_count!==1?"s":""," skipped"]})]}),le.skipped_count>5&&r.jsx("button",{onClick:()=>S(!x),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:x?"Show less":"Show all"})]}),r.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(x?le.skipped:le.skipped.slice(0,5)).map((he,we)=>r.jsxs("li",{className:"flex items-center gap-2",children:[he.color&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${he.color}`}}),r.jsx("span",{children:he.location}),r.jsxs("span",{className:"text-amber-300/60",children:["- ",he.reason]})]},we)),!x&&le.skipped_count>5&&r.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",le.skipped_count-5," more"]})]})]}),le.errors.length>0&&r.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[r.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),r.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:le.errors.map((he,we)=>r.jsx("li",{children:he},we))})]})]})]})]})]}),k&&r.jsx(wn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:ue.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>ue.mutate(),onCancel:()=>C(!1)}),P&&r.jsx(wn,{title:t("settings.spoolmanAmsSyncTitle"),message:t("settings.spoolmanAmsSyncMessage"),confirmText:t("settings.spoolmanAmsSyncButton"),variant:"warning",isLoading:oe.isPending,loadingText:t("settings.spoolmanAmsSyncing"),onConfirm:()=>oe.mutate(),onCancel:()=>T(!1)})]})}function lat(){const{t}=_t(),{showToast:e}=on(),[n,a]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),c=y.useRef(null),[d,u]=y.useState(!1),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(!1),[k,C]=y.useState(new Set),[P,T]=y.useState(!1),[A,F]=y.useState(null),[_,M]=y.useState(!1),H=y.useCallback(async()=>{try{const he=await ae.getSpoolCatalog();a(he)}catch(he){console.error("SpoolCatalogSettings.loadCatalog failed:",he),e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{H()},[H]);const I=n.filter(he=>he.name.toLowerCase().includes(o.toLowerCase())),z=async()=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const he=await ae.addCatalogEntry({name:f.trim(),weight:parseInt(w)});a(we=>[...we,he].sort(($,J)=>$.name.localeCompare(J.name))),u(!1),g(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch(he){console.error("SpoolCatalogSettings.handleAdd failed:",he),e(t("settings.catalog.addFailed"),"error")}finally{S(!1)}},L=he=>{p(he.id),g(he.name),b(he.weight.toString())},Z=()=>{p(null),g(""),b("")},ne=async he=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const we=await ae.updateCatalogEntry(he,{name:f.trim(),weight:parseInt(w)});a($=>$.map(J=>J.id===he?we:J).sort((J,j)=>J.name.localeCompare(j.name))),p(null),g(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch(we){console.error("SpoolCatalogSettings.handleUpdate failed:",we),e(t("settings.catalog.updateFailed"),"error")}finally{S(!1)}},Y=async()=>{if(A)try{await ae.deleteCatalogEntry(A.id),a(he=>he.filter(we=>we.id!==A.id)),e(t("settings.catalog.entryDeleted"),"success")}catch(he){console.error("SpoolCatalogSettings.handleDelete failed:",he),e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},ce=async()=>{M(!1),s(!0);try{await ae.resetSpoolCatalog(),await H(),e(t("settings.catalog.resetSuccess"),"success")}catch(he){console.error("SpoolCatalogSettings.handleReset failed:",he),e(t("settings.catalog.resetFailed"),"error"),s(!1)}},ue=he=>{C(we=>{const $=new Set(we);return $.has(he)?$.delete(he):$.add(he),$})},oe=()=>{k.size===I.length?C(new Set):C(new Set(I.map(he=>he.id)))},Q=async()=>{if(T(!1),k.size!==0)try{const he=await ae.bulkDeleteCatalogEntries([...k]);a(we=>we.filter($=>!k.has($.id))),C(new Set),e(t("settings.catalog.bulkDeleted",{count:he.deleted}),"success")}catch(he){console.error("SpoolCatalogSettings.handleBulkDelete failed:",he),e(t("settings.catalog.bulkDeleteFailed"),"error")}},le=()=>{const he=n.map(({name:j,weight:E})=>({name:j,weight:E})),we=new Blob([JSON.stringify(he,null,2)],{type:"application/json"}),$=URL.createObjectURL(we),J=document.createElement("a");J.href=$,J.download="spool-catalog.json",document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL($),e(t("settings.catalog.exported",{count:n.length}),"success")},pe=async he=>{const we=he.target.files?.[0];if(we){try{const $=await we.text(),J=JSON.parse($);if(!Array.isArray(J))throw new Error("Invalid format");let j=0,E=0;for(const B of J){if(!B.name||typeof B.weight!="number"){E++;continue}if(n.some(O=>O.name.toLowerCase()===B.name.toLowerCase())){E++;continue}try{const O=await ae.addCatalogEntry({name:B.name,weight:B.weight});a(ie=>[...ie,O].sort((U,G)=>U.name.localeCompare(G.name))),j++}catch(O){console.error("SpoolCatalogSettings import item failed:",O),E++}}e(t("settings.catalog.imported",{added:j,skipped:E}),"success")}catch($){console.error("SpoolCatalogSettings.handleImport failed:",$),e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return r.jsxs(At,{id:"card-spool-catalog",children:[r.jsxs(fn,{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(dc,{className:"w-5 h-5 text-bambu-gray"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsxs("button",{onClick:le,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:[r.jsx(Zr,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),r.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:[r.jsx(_a,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),r.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:pe}),r.jsxs("button",{onClick:()=>M(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[r.jsx(fs,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),r.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:[r.jsx(er,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),k.size>0&&r.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:[r.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:k.size})}),r.jsxs("button",{onClick:()=>T(!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:[r.jsx(en,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),r.jsx("button",{onClick:()=>C(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.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:he=>l(he.target.value)})]}),d&&r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"flex-1 min-w-0",children:r.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:he=>g(he.target.value)})}),r.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:w,onChange:he=>b(he.target.value)}),r.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),r.jsxs("button",{onClick:z,disabled:x,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:[x?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Ar,{className:"w-4 h-4"}),t("common.add")]}),r.jsx("button",{onClick:()=>{u(!1),g(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:r.jsx(Vt,{className:"w-4 h-4"})})]})]}),i?r.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[r.jsx(ft,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):r.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-2 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:I.length>0&&k.size===I.length,onChange:oe,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),r.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),r.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),r.jsx("th",{className:"px-4 py-2 w-24"})]})}),r.jsx("tbody",{children:I.length===0?r.jsx("tr",{children:r.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(he=>r.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.has(he.id)?"bg-bambu-dark":""}`,children:m===he.id?r.jsxs(r.Fragment,{children:[r.jsx("td",{className:"px-2 py-2",children:r.jsx("input",{type:"checkbox",checked:k.has(he.id),onChange:()=>ue(he.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("td",{className:"px-4 py-2",children:r.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:we=>g(we.target.value)})}),r.jsx("td",{className:"px-4 py-2",children:r.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:w,onChange:we=>b(we.target.value)})}),r.jsx("td",{className:"px-4 py-2 text-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex justify-end gap-1",children:[r.jsx("button",{onClick:()=>ne(he.id),disabled:x,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:x?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Ar,{className:"w-4 h-4"})}),r.jsx("button",{onClick:Z,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:r.jsx(Vt,{className:"w-4 h-4"})})]})})]}):r.jsxs(r.Fragment,{children:[r.jsx("td",{className:"px-2 py-2",children:r.jsx("input",{type:"checkbox",checked:k.has(he.id),onChange:()=>ue(he.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("td",{className:"px-4 py-2 text-white",children:he.name}),r.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[he.weight,"g"]}),r.jsx("td",{className:"px-4 py-2 text-center",children:he.is_default?r.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex justify-end gap-1",children:[r.jsx("button",{onClick:()=>L(he),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>F(he),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:r.jsx(en,{className:"w-4 h-4"})})]})})]})},he.id))})]})})]}),A&&r.jsx(wn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:A.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:Y,onCancel:()=>F(null)}),P&&r.jsx(wn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:Q,onCancel:()=>T(!1)}),_&&r.jsx(wn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:ce,onCancel:()=>M(!1)})]})}const cat=2166136261,dat=16777619;function uat(...t){let e=cat;const n=new TextEncoder,a=n.encode("__|");for(const i of t)typeof i=="string"?e=uX(e,n.encode(i+"|")):i==null&&(e=uX(e,a));return e>>>0}function uX(t,e){for(const n of e)t^=n,t=Math.imul(t,dat)>>>0;return t}function mat(t){const e=()=>{t|=0,t=t+1831565813|0;let a=Math.imul(t^t>>>15,1|t);return a=a+Math.imul(a^a>>>7,61|a)^a,(a^a>>>14)>>>0},n=(a,i)=>{if(!Number.isFinite(a)||!Number.isFinite(i))throw new RangeError("from and to must be finite numbers");if(a>i)throw new RangeError("from must be less than or equal to to");return a===i?a:a+e()/4294967295*(i-a)};return{next:()=>e()/4294967295,floatBetween:(a,i)=>n(a,i),intBetween:(a,i)=>{if(!Number.isInteger(a)||!Number.isInteger(i))throw new RangeError("from and to must be integers");return Math.round(n(a,i))}}}const mX={table:{dotCount:5,dotScale:1},preview:{dotCount:8,dotScale:1.5},card:{dotCount:40,dotScale:2},bar:{dotCount:20,dotScale:2},groupheader:{dotCount:80,dotScale:2}},XI=[{value:"",labelKey:"inventory.colorEffect.none"},{value:"sparkle",labelKey:"inventory.colorEffect.sparkle"},{value:"wood",labelKey:"inventory.colorEffect.wood"},{value:"marble",labelKey:"inventory.colorEffect.marble"},{value:"glow",labelKey:"inventory.colorEffect.glow"},{value:"matte",labelKey:"inventory.colorEffect.matte"},{value:"silk",labelKey:"inventory.colorEffect.silk"},{value:"galaxy",labelKey:"inventory.colorEffect.galaxy"},{value:"rainbow",labelKey:"inventory.colorEffect.rainbow"},{value:"metal",labelKey:"inventory.colorEffect.metal"},{value:"translucent",labelKey:"inventory.colorEffect.translucent"},{value:"gradient",labelKey:"inventory.colorEffect.gradient"},{value:"dual-color",labelKey:"inventory.colorEffect.dualColor"},{value:"tri-color",labelKey:"inventory.colorEffect.triColor"},{value:"multicolor",labelKey:"inventory.colorEffect.multicolor"}],pat="repeating-conic-gradient(#979797 0% 25%, #f5f5f5 0% 50%)",hat="12px 12px",fat={sparkle:(t=0,e="table")=>{const n=mat(t),a=mX[e]??mX.table,i=[];for(let s=0;s<a.dotCount;s++){const o=n.intBetween(1,99),l=n.intBetween(1,99),c=n.floatBetween(1,a.dotScale),d=n.floatBetween(.65,1);i.push(`radial-gradient(circle at ${o}% ${l}%, rgba(255,248,220,${d}) 0 ${c/2}px, transparent ${c}px)`)}return i},wood:()=>"repeating-linear-gradient(90deg, rgba(0,0,0,0.18) 0 1px, transparent 1px 6px, rgba(0,0,0,0.08) 6px 7px, transparent 7px 12px)",marble:()=>"repeating-linear-gradient(135deg, rgba(255,255,255,0.18) 0 2px, transparent 2px 8px), repeating-linear-gradient(45deg, rgba(0,0,0,0.10) 0 1px, transparent 1px 7px)",glow:()=>"radial-gradient(circle at 50% 50%, rgba(255,255,255,0.35) 0%, rgba(255,255,255,0) 70%)",matte:()=>"linear-gradient(180deg, rgba(0,0,0,0.10) 0%, rgba(0,0,0,0) 50%, rgba(0,0,0,0.10) 100%)",silk:()=>"linear-gradient(110deg, rgba(255,255,255,0) 30%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0) 70%)",galaxy:()=>"linear-gradient(110deg, rgba(255,255,255,0) 25%, rgba(255,255,255,0.40) 50%, rgba(255,255,255,0) 75%)",metal:()=>"repeating-linear-gradient(90deg, rgba(255,255,255,0.10) 0 1px, transparent 1px 3px), linear-gradient(180deg, rgba(255,255,255,0.18) 0%, rgba(0,0,0,0.18) 100%)"};function Uce(t){const e=t.trim().replace(/^#/,"");return e.length!==6&&e.length!==8||!/^[0-9a-fA-F]+$/.test(e)?null:`#${e}`}function Bce(t){return t?t.split(",").map(e=>Uce(e)).filter(e=>!!e):[]}function gat(t,e,n,a){const i=t?Uce(t):null;if(e.length===0)return`linear-gradient(${i??"#808080"}, ${i??"#808080"})`;const s=e.length===1?[e[0],e[0]]:e,o=(n??"").toLowerCase(),l=(a??"").toLowerCase();if(o==="multicolor"||l==="multicolor"){const c=s.length;return`conic-gradient(from 0deg, ${s.map((u,m)=>{const p=(m/c*360).toFixed(3),f=((m+1)/c*360).toFixed(3);return`${u} ${p}deg ${f}deg`}).join(", ")})`}if(l==="dual-color"||l==="tri-color"){const c=s.length;return`linear-gradient(to right, ${s.map((u,m)=>{const p=(m/c*100).toFixed(3),f=((m+1)/c*100).toFixed(3);return`${u} ${p}% ${f}%`}).join(", ")})`}return`linear-gradient(135deg, ${s.join(", ")})`}function bat(t,e,n){const a=fat[t];return a?a(n,e):null}function ij(t){const e=Bce(t.extraColors),n=gat(t.rgba,e,t.subtype,t.effectType),a=uat(t.rgba,t.extraColors,t.subtype,t.effectType),i=typeof t.effectType=="string"?bat(t.effectType,t.effectSize,a):null,s=[];return i&&(Array.isArray(i)?i:[i]).forEach(l=>{s.push({image:l,size:"cover"})}),s.push({image:n,size:"cover"}),s.push({image:pat,size:hat}),{backgroundImage:s.map(o=>o.image).join(", "),backgroundSize:s.map(o=>o.size).join(", ")}}function lU({rgba:t,extraColors:e,effectType:n,subtype:a,className:i="w-5 h-5",shape:s="circle",style:o,title:l,effectSize:c}){const d=y.useMemo(()=>Bce(e),[e]),u=y.useMemo(()=>ij({effectSize:c,rgba:t,extraColors:e,effectType:n,subtype:a}),[c,t,e,n,a]),m=u.backgroundImage,p=u.backgroundSize,f=s==="circle"||s==="pill"?"rounded-full":"rounded",g=l??(d.length>0?d.join(", "):t?`#${t.substring(0,6)}`:void 0);return r.jsx("span",{"data-testid":"filament-swatch",className:`${i} ${f} border border-black/20 inline-block flex-shrink-0`,style:{backgroundImage:m,backgroundSize:p,...o},title:g})}function xat(){const{t}=_t(),{showToast:e}=on(),[n,a]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),[c,d]=y.useState(""),u=y.useRef(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),[w,b]=y.useState(""),[x,S]=y.useState(""),[k,C]=y.useState("#FFFFFF"),[P,T]=y.useState(""),[A,F]=y.useState(""),[_,M]=y.useState(""),[H,I]=y.useState(!1),[z,L]=y.useState(new Set),[Z,ne]=y.useState(!1),[Y,ce]=y.useState(!1),[ue,oe]=y.useState(null),[Q,le]=y.useState(null),[pe,he]=y.useState(!1),we=y.useCallback(async()=>{try{const de=await ae.getColorCatalog();a(de)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{we()},[we]);const $=[...new Set(n.map(de=>de.manufacturer))].sort(),J=n.filter(de=>{const me=o===""||de.manufacturer.toLowerCase().includes(o.toLowerCase())||de.color_name.toLowerCase().includes(o.toLowerCase())||(de.material?.toLowerCase().includes(o.toLowerCase())??!1),q=c===""||de.manufacturer===c;return me&&q}),j=()=>{b(""),S(""),C("#FFFFFF"),T(""),F(""),M("")},E=async()=>{if(!w.trim()||!x.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const de=await ae.addColorEntry({manufacturer:w.trim(),color_name:x.trim(),hex_color:k,material:P.trim()||null,extra_colors:A.trim()||null,effect_type:_.trim()||null});a(me=>[...me,de].sort((q,R)=>q.manufacturer.localeCompare(R.manufacturer)||(q.material||"").localeCompare(R.material||"")||q.color_name.localeCompare(R.color_name))),p(!1),j(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{I(!1)}},B=de=>{g(de.id),b(de.manufacturer),S(de.color_name),C(de.hex_color),T(de.material||""),F(de.extra_colors||""),M(de.effect_type||"")},W=()=>{g(null),j()},O=async de=>{if(!w.trim()||!x.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const me=await ae.updateColorEntry(de,{manufacturer:w.trim(),color_name:x.trim(),hex_color:k,material:P.trim()||null,extra_colors:A.trim()||null,effect_type:_.trim()||null});a(q=>q.map(R=>R.id===de?me:R).sort((R,re)=>R.manufacturer.localeCompare(re.manufacturer)||(R.material||"").localeCompare(re.material||"")||R.color_name.localeCompare(re.color_name))),g(null),j(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{I(!1)}},ie=async()=>{if(Q)try{await ae.deleteColorEntry(Q.id),a(de=>de.filter(me=>me.id!==Q.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{le(null)}},U=async()=>{he(!1),s(!0);try{await ae.resetColorCatalog(),await we(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},G=async()=>{ce(!0),oe(null);try{const de={},me=Wm();me&&(de.Authorization=`Bearer ${me}`);const q=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:de});if(!q.ok)throw new Error("Failed to start sync");const R=q.body?.getReader();if(!R)throw new Error("No response body");const re=new TextDecoder;let be="";for(;;){const{done:ye,value:_e}=await R.read();if(ye)break;be+=re.decode(_e,{stream:!0});const xe=be.split(`
  8326. `);be=xe.pop()||"";for(const ge of xe)if(ge.startsWith("data: "))try{const Me=JSON.parse(ge.slice(6));Me.type==="progress"?oe({fetched:Me.total_fetched,total:Me.total_available}):Me.type==="complete"?Me.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Me.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Me.added,skipped:Me.skipped}),"success"):Me.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Me.error}`,"error")}catch{}}await we()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{ce(!1),oe(null)}},K=de=>{L(me=>{const q=new Set(me);return q.has(de)?q.delete(de):q.add(de),q})},X=()=>{z.size===J.length?L(new Set):L(new Set(J.map(de=>de.id)))},se=async()=>{if(ne(!1),z.size!==0)try{const de=await ae.bulkDeleteColorEntries([...z]);a(me=>me.filter(q=>!z.has(q.id))),L(new Set),e(t("settings.colorCatalog.bulkDeleted",{count:de.deleted}),"success")}catch{e(t("settings.colorCatalog.bulkDeleteFailed"),"error")}},te=()=>{const de=n.map(({manufacturer:re,color_name:be,hex_color:ye,material:_e,extra_colors:xe,effect_type:ge})=>({manufacturer:re,color_name:be,hex_color:ye,material:_e,extra_colors:xe,effect_type:ge})),me=new Blob([JSON.stringify(de,null,2)],{type:"application/json"}),q=URL.createObjectURL(me),R=document.createElement("a");R.href=q,R.download="color-catalog.json",document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(q),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},fe=async de=>{const me=de.target.files?.[0];if(me){try{const q=await me.text(),R=JSON.parse(q);if(!Array.isArray(R))throw new Error("Invalid format");let re=0,be=0;for(const ye of R){if(!ye.manufacturer||!ye.color_name||!ye.hex_color){be++;continue}if(n.some(xe=>xe.manufacturer.toLowerCase()===ye.manufacturer.toLowerCase()&&xe.color_name.toLowerCase()===ye.color_name.toLowerCase()&&(xe.material||"").toLowerCase()===(ye.material||"").toLowerCase())){be++;continue}try{const xe=await ae.addColorEntry({manufacturer:ye.manufacturer,color_name:ye.color_name,hex_color:ye.hex_color,material:ye.material||null,extra_colors:ye.extra_colors||null,effect_type:ye.effect_type||null});a(ge=>[...ge,xe].sort((Me,Be)=>Me.manufacturer.localeCompare(Be.manufacturer)||(Me.material||"").localeCompare(Be.material||"")||Me.color_name.localeCompare(Be.color_name))),re++}catch{be++}}e(t("settings.colorCatalog.imported",{added:re,skipped:be}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return r.jsxs(At,{id:"card-color-catalog",children:[r.jsxs(fn,{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(ES,{className:"w-5 h-5 text-bambu-gray"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsxs("button",{onClick:te,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:[r.jsx(Zr,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),r.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:[r.jsx(_a,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),r.jsx("input",{ref:u,type:"file",accept:".json",className:"hidden",onChange:fe}),r.jsxs("button",{onClick:G,disabled:Y,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:[Y?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx($h,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:Y?ue?`${Math.min(ue.fetched,ue.total)} / ${ue.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),r.jsxs("button",{onClick:()=>he(!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:[r.jsx(fs,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),r.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:[r.jsx(er,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),z.size>0&&r.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:[r.jsx("span",{className:"text-sm text-red-400",children:t("settings.colorCatalog.selectedCount",{count:z.size})}),r.jsxs("button",{onClick:()=>ne(!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:[r.jsx(en,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),r.jsx("button",{onClick:()=>L(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),r.jsxs("div",{className:"flex gap-2 flex-wrap",children:[r.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.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:de=>l(de.target.value)})]}),r.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:de=>d(de.target.value),children:[r.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),$.map(de=>r.jsx("option",{value:de,children:de},de))]})]}),m&&r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[r.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:w,onChange:de=>b(de.target.value)}),r.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:x,onChange:de=>S(de.target.value)}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:de=>C(de.target.value)}),r.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:k,onChange:de=>C(de.target.value)})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.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:P,onChange:de=>T(de.target.value)}),r.jsxs("button",{onClick:E,disabled:H,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:[H?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Ar,{className:"w-4 h-4"}),t("common.add")]}),r.jsx("button",{onClick:()=>{p(!1),j()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:r.jsx(Vt,{className:"w-4 h-4"})})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2",children:[r.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("inventory.extraColorsPlaceholder"),value:A,onChange:de=>F(de.target.value)}),r.jsx("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:_,onChange:de=>M(de.target.value),children:XI.map(de=>r.jsx("option",{value:de.value,children:t(de.labelKey)},de.value||"none"))})]})]}),(o||c)&&r.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:J.length,total:n.length})}),i?r.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[r.jsx(ft,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):r.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-2 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:J.length>0&&z.size===J.length,onChange:X,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),r.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),r.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),r.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),r.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),r.jsx("th",{className:"px-3 py-2 w-16"})]})}),r.jsx("tbody",{children:J.length===0?r.jsx("tr",{children:r.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):J.map(de=>r.jsxs(y.Fragment,{children:[r.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${z.has(de.id)?"bg-bambu-dark":""}`,children:f===de.id?r.jsxs(r.Fragment,{children:[r.jsx("td",{className:"px-2 py-2",children:r.jsx("input",{type:"checkbox",checked:z.has(de.id),onChange:()=>K(de.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:me=>C(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",children:r.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:w,onChange:me=>b(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",children:r.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:P,onChange:me=>T(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",children:r.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:x,onChange:me=>S(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",children:r.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:k,onChange:me=>C(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",children:r.jsxs("div",{className:"flex justify-end gap-1",children:[r.jsx("button",{onClick:()=>O(de.id),disabled:H,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:H?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Ar,{className:"w-4 h-4"})}),r.jsx("button",{onClick:W,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:r.jsx(Vt,{className:"w-4 h-4"})})]})})]}):r.jsxs(r.Fragment,{children:[r.jsx("td",{className:"px-2 py-2",children:r.jsx("input",{type:"checkbox",checked:z.has(de.id),onChange:()=>K(de.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2",children:r.jsx(lU,{rgba:de.hex_color.replace(/^#/,"")+(de.hex_color.length===7?"FF":""),extraColors:de.extra_colors,effectType:de.effect_type,className:"w-8 h-8",shape:"square",title:de.hex_color,effectSize:"table"})}),r.jsx("td",{className:"px-3 py-2 text-white",children:de.manufacturer}),r.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:de.material||"-"}),r.jsx("td",{className:"px-3 py-2 text-white",children:de.color_name}),r.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:de.hex_color}),r.jsx("td",{className:"px-3 py-2",children:r.jsxs("div",{className:"flex justify-end gap-1",children:[r.jsx("button",{onClick:()=>B(de),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>le(de),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:r.jsx(en,{className:"w-4 h-4"})})]})})]})}),f===de.id&&r.jsxs("tr",{className:"border-t border-bambu-dark-tertiary/50 bg-bambu-dark",children:[r.jsx("td",{colSpan:2}),r.jsx("td",{className:"px-3 py-2",colSpan:2,children:r.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 font-mono focus:border-bambu-green focus:outline-none",placeholder:t("inventory.extraColorsPlaceholder"),value:A,onChange:me=>F(me.target.value)})}),r.jsx("td",{className:"px-3 py-2",colSpan:2,children:r.jsx("select",{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:_,onChange:me=>M(me.target.value),children:XI.map(me=>r.jsx("option",{value:me.value,children:t(me.labelKey)},me.value||"none"))})}),r.jsx("td",{})]})]},de.id))})]})})]}),Q&&r.jsx(wn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${Q.manufacturer} - ${Q.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:ie,onCancel:()=>le(null)}),Z&&r.jsx(wn,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:z.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:se,onCancel:()=>ne(!1)}),pe&&r.jsx(wn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:U,onCancel:()=>he(!1)})]})}function yat({link:t,onClose:e}){const{t:n}=_t(),a=tn(),i=!!t,s=y.useRef(null),[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.url||""),[u,m]=y.useState(t?.icon||"link"),[p,f]=y.useState(t?.open_in_new_tab||!1),[g,w]=y.useState(!!t?.custom_icon),[b,x]=y.useState(t?.custom_icon?ae.getExternalLinkIconUrl(t.id):null),[S,k]=y.useState(null),[C,P]=y.useState(null);y.useEffect(()=>{const z=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[e]);const T=lt({mutationFn:async z=>{const L=await ae.createExternalLink(z);return S?await ae.uploadExternalLinkIcon(L.id,S):L},onSuccess:()=>{a.invalidateQueries({queryKey:["external-links"]}),e()},onError:z=>{P(z.message)}}),A=lt({mutationFn:async z=>{let L=await ae.updateExternalLink(t.id,z);return S?L=await ae.uploadExternalLinkIcon(t.id,S):!g&&t?.custom_icon&&(L=await ae.deleteExternalLinkIcon(t.id)),L},onSuccess:()=>{a.invalidateQueries({queryKey:["external-links"]}),e()},onError:z=>{P(z.message)}}),F=z=>{const L=z.target.files?.[0];if(L){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(L.type)){P("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(L.size>1024*1024){P("Image file must be less than 1MB");return}k(L),w(!0);const ne=new FileReader;ne.onload=Y=>{x(Y.target?.result)},ne.readAsDataURL(L)}},_=()=>{k(null),x(null),w(!1),s.current&&(s.current.value="")},M=z=>{if(z.preventDefault(),P(null),!o.trim()){P("Name is required");return}if(!c.trim()){P("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){P("URL must start with http:// or https://");return}const L={name:o.trim(),url:c.trim(),icon:u,open_in_new_tab:p};i?A.mutate(L):T.mutate(L)},H=T.isPending||A.isPending,I=TT(u);return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:z=>z.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:g&&b?r.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):r.jsx(I,{className:"w-5 h-5"})}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:M,className:"p-6 space-y-4",children:[C&&r.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:C}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),r.jsx("input",{type:"text",value:o,onChange:z=>l(z.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),r.jsx("input",{type:"text",value:c,onChange:z=>d(z.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"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),r.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:r.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"space-y-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),r.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),r.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}),g&&b?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("img",{src:b,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:_,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:r.jsx(en,{className:"w-4 h-4"})})]}):r.jsxs(je,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[r.jsx(_a,{className:"w-4 h-4"}),"Upload"]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!g&&r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),r.jsx(Hve,{value:u,onChange:m})]})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),r.jsxs(je,{type:"submit",disabled:H,className:"flex-1",children:[H?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(ds,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function vat(){const{t}=_t(),e=tn(),[n,a]=y.useState(!1),[i,s]=y.useState(null),[o,l]=y.useState(null),[c,d]=y.useState(null),{data:u,isLoading:m}=Xe({queryKey:["external-links"],queryFn:ae.getExternalLinks}),p=lt({mutationFn:k=>ae.deleteExternalLink(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=lt({mutationFn:k=>ae.reorderExternalLinks(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),g=(k,C)=>{d(C),k.dataTransfer.effectAllowed="move"},w=k=>{k.preventDefault(),k.dataTransfer.dropEffect="move"},b=(k,C)=>{if(k.preventDefault(),c===null||c===C||!u)return;const P=u.map(_=>_.id),T=P.indexOf(c),A=P.indexOf(C);if(T===-1||A===-1)return;const F=[...P];F.splice(T,1),F.splice(A,0,c),f.mutate(F),d(null)},x=k=>{l(k)},S=()=>{o&&(p.mutate(o.id),l(null))};return r.jsxs(r.Fragment,{children:[r.jsxs(At,{id:"card-sidebar-links",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),r.jsxs(je,{size:"sm",onClick:()=>a(!0),children:[r.jsx(er,{className:"w-4 h-4"}),"Add Link"]})]})}),r.jsxs(Et,{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),m?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?r.jsx("div",{className:"space-y-2",children:u.map(k=>{const C=TT(k.icon);return r.jsxs("div",{draggable:!0,onDragStart:P=>g(P,k.id),onDragOver:w,onDrop:P=>b(P,k.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===k.id?"opacity-50":""}`,children:[r.jsx(Ah,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:r.jsx(C,{className:"w-4 h-4"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-white font-medium truncate",children:k.name}),r.jsx(zr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),r.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:k.url})]}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[r.jsx("button",{onClick:()=>s(k),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>x(k),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:r.jsx(en,{className:"w-4 h-4"})})]})]},k.id)})}):r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(jh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:t("externalLinks.noLinksConfigured")}),r.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&r.jsx(yat,{link:i,onClose:()=>{a(!1),s(null)}}),o&&r.jsx(wn,{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:S,onCancel:()=>l(null)})]})}const cF={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function wat({printer:t,models:e}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),[s,o]=y.useState(!0),[l,c]=y.useState(t.enabled),[d,u]=y.useState(t.name),[m,p]=y.useState(""),[f,g]=y.useState(t.mode==="queue"?"review":t.mode),[w,b]=y.useState(t.target_printer_id),[x,S]=y.useState(t.bind_ip||""),[k,C]=y.useState(t.remote_interface_ip||""),[P,T]=y.useState(t.model||""),[A,F]=y.useState(t.auto_dispatch??!0),[_,M]=y.useState(t.queue_force_color_match??!1),[H,I]=y.useState(t.tailscale_disabled??!0),[z,L]=y.useState(!1),[Z,ne]=y.useState(null),[Y,ce]=y.useState(!1),[ue,oe]=y.useState(!1),{data:Q}=Xe({queryKey:["tailscale-status"],queryFn:J0.getTailscaleStatus,enabled:!H,staleTime:6e4}),le=Q?.available?Q.fqdn:"",pe=Q?.available?Q.tailscale_ips?.[0]??"":"",he=async te=>{te.stopPropagation();const fe=le;if(!fe)return;let de=!1;if(navigator.clipboard&&window.isSecureContext)try{await navigator.clipboard.writeText(fe),de=!0}catch{}if(!de){const me=document.createElement("textarea");me.value=fe,me.style.position="fixed",me.style.opacity="0",document.body.appendChild(me);try{me.select(),de=document.execCommand("copy")}catch{de=!1}finally{me.parentNode&&me.parentNode.removeChild(me)}}de?(oe(!0),i(n("printers.copied")),setTimeout(()=>oe(!1),2e3)):i(n("virtualPrinter.toast.copyFailed"),"error")};y.useEffect(()=>{Z||(c(t.enabled),g(t.mode==="queue"?"review":t.mode),u(t.name),b(t.target_printer_id),S(t.bind_ip||""),C(t.remote_interface_ip||""),T(t.model||""),F(t.auto_dispatch??!0),M(t.queue_force_color_match??!1),I(t.tailscale_disabled??!0))},[t,Z]);const{data:we}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:$}=Xe({queryKey:["network-interfaces"],queryFn:()=>ae.getNetworkInterfaces().then(te=>te.interfaces)}),J=lt({mutationFn:te=>J0.update(t.id,te),onSuccess:()=>{a.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.updated")),ne(null)},onError:te=>{i(te.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),g(t.mode==="queue"?"review":t.mode),b(t.target_printer_id),S(t.bind_ip||""),I(t.tailscale_disabled??!0),ne(null)}}),j=lt({mutationFn:()=>J0.remove(t.id),onSuccess:()=>{a.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.deleted")),ce(!1)},onError:te=>{i(te.message||n("virtualPrinter.toast.failedToDelete"),"error"),ce(!1)}}),E=te=>{te.stopPropagation();const fe=!l;if(fe){if(!x){i(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(f==="proxy"){if(!w){i(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!m&&!t.access_code_set){i(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(fe),ne("toggle"),J.mutate({enabled:fe})},B=()=>{d.trim()&&(ne("name"),J.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}ne("accessCode"),J.mutate({access_code:m}),p("")},O=te=>{g(te),ne("mode"),J.mutate({mode:te})},ie=te=>{T(te),ne("model"),J.mutate({model:te})},U=te=>{b(te),ne("targetPrinter"),J.mutate({target_printer_id:te})},G=te=>{C(te),ne("remoteInterface"),J.mutate({remote_interface_ip:te})},K=t.status?.running||!1,X=n(`virtualPrinter.mode.${cF[f]||"archive"}`),se=we?.find(te=>te.id===w)?.name;return r.jsxs(r.Fragment,{children:[r.jsxs(At,{children:[r.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[r.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?r.jsx(Ln,{className:"w-4 h-4"}):r.jsx(qa,{className:"w-4 h-4"})}),r.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${K?"bg-green-400 animate-pulse":"bg-gray-500"}`}),r.jsx("span",{className:"text-white font-medium truncate",children:t.name}),r.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:X}),t.model_name&&r.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),se&&r.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&r.jsx(qF,{className:"w-3 h-3 inline mr-1"}),se]}),x&&r.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:x}),k&&r.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:k}),r.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:te=>te.stopPropagation(),children:r.jsx("button",{onClick:E,disabled:Z==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${Z==="toggle"?"opacity-50":""}`,children:r.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&&r.jsxs(Et,{className:"pt-0 space-y-4",children:[r.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"text",value:d,onChange:te=>u(te.target.value),onBlur:B,onKeyDown:te=>te.key==="Enter"&&B(),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"}),r.jsx("button",{onClick:()=>ce(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors flex-shrink-0",title:n("common.delete"),children:r.jsx(en,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-2 -mt-2",children:[le&&r.jsxs("span",{className:"flex items-center gap-1 text-green-400/70 min-w-0",children:[r.jsx(Fw,{className:"w-3.5 h-3.5 flex-shrink-0"}),r.jsx("span",{className:"font-mono text-xs truncate",children:pe?`${pe} (${le})`:le}),r.jsx("button",{onClick:he,className:"p-0.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors flex-shrink-0",title:n(ue?"printers.copied":"printers.copyToClipboard"),children:ue?r.jsx(Ar,{className:"w-3.5 h-3.5 text-bambu-green"}):r.jsx(Ti,{className:"w-3.5 h-3.5"})})]}),r.jsx("span",{className:"text-xs text-bambu-gray font-mono ml-auto flex-shrink-0",children:t.serial})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(te=>r.jsxs("button",{onClick:()=>O(te),disabled:Z==="mode",className:`p-2 rounded-lg border text-left transition-colors ${f===te?te==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[te==="proxy"&&r.jsx(qF,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${cF[te]}`)]}),r.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${cF[te]}Desc`)})]},te))})]}),f==="print_queue"&&r.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.autoDispatch.title")}),r.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.autoDispatch.description")})]}),r.jsx("button",{onClick:()=>{const te=!A;F(te),ne("autoDispatch"),J.mutate({auto_dispatch:te})},disabled:Z==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${A?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${Z==="autoDispatch"?"opacity-50":""}`,children:r.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${A?"translate-x-5":""}`})})]})}),f==="print_queue"&&r.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.queueForceColorMatch.title")}),r.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.queueForceColorMatch.description")})]}),r.jsx("button",{onClick:()=>{const te=!_;M(te),ne("queueForceColorMatch"),J.mutate({queue_force_color_match:te})},disabled:Z==="queueForceColorMatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${Z==="queueForceColorMatch"?"opacity-50":""}`,children:r.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${_?"translate-x-5":""}`})})]})}),r.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.tailscaleDisabled.title")}),r.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.tailscaleDisabled.description")})]}),r.jsx("button",{onClick:()=>{const te=!H;I(te),ne("tailscaleDisabled"),J.mutate({tailscale_disabled:te})},disabled:Z==="tailscaleDisabled",className:`relative w-10 h-5 rounded-full transition-colors shrink-0 ${H?"bg-bambu-dark-tertiary":"bg-bambu-green"} ${Z==="tailscaleDisabled"?"opacity-50":""}`,children:r.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${H?"":"translate-x-5"}`})})]})}),f!=="proxy"&&r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),r.jsxs("div",{className:"relative",children:[r.jsx("select",{value:P,onChange:te=>ie(te.target.value),disabled:Z==="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(([te,fe])=>r.jsxs("option",{value:te,children:[fe," (",te,")"]},te))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),f==="proxy"&&r.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[r.jsx(_i,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),f!=="proxy"&&r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?r.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[r.jsx(Ar,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):r.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[r.jsx(Nn,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:z?"text":"password",value:m,onChange:te=>p(te.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"}),r.jsx("button",{onClick:()=>L(!z),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:z?r.jsx(ab,{className:"w-4 h-4"}):r.jsx(Cl,{className:"w-4 h-4"})})]}),r.jsx(je,{onClick:W,disabled:!m||Z==="accessCode",variant:"primary",children:Z==="accessCode"?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),m&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r.jsx("span",{className:m.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:m.length})})})]}),r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:w??"",onChange:te=>{const fe=parseInt(te.target.value,10);isNaN(fe)||U(fe)},disabled:Z==="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:[r.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),we?.map(te=>r.jsxs("option",{value:te.id,children:[te.name," (",te.ip_address,")"]},te.id))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:x,onChange:te=>{S(te.target.value),ne("bindIp"),J.mutate({bind_ip:te.target.value})},disabled:Z==="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:[r.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),$?.map(te=>r.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,")",te.is_alias?" [alias]":""," - ",te.subnet]},te.ip))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),k?r.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:r.jsx(Ar,{className:"w-3 h-3"})}):r.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:r.jsx(_i,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:k,onChange:te=>G(te.target.value),disabled:Z==="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:[r.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),$?.map(te=>r.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,") - ",te.subnet]},te.ip))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),Y&&r.jsx(wn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:j.isPending,onConfirm:()=>j.mutate(),onCancel:()=>ce(!1)})]})}const pX={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function Sat({onClose:t}){const{t:e}=_t(),n=tn(),{showToast:a}=on(),[i,s]=y.useState(""),[o,l]=y.useState("immediate"),[c,d]=y.useState(null),{data:u}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),m=lt({mutationFn:()=>J0.create({name:i.trim()||"Bambuddy",mode:o,target_printer_id:o==="proxy"?c??void 0:void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["virtual-printers"]}),a(e("virtualPrinter.toast.created")),t()},onError:p=>{a(p.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:r.jsx(At,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:r.jsxs(Et,{className:"p-6 space-y-4",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),r.jsxs("div",{children:[r.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),r.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(p=>r.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:[r.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[p==="proxy"&&r.jsx(qF,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${pX[p]}`)]}),r.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${pX[p]}Desc`)})]},p))})]}),o==="proxy"&&r.jsxs("div",{children:[r.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),r.jsxs("div",{className:"relative",children:[r.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:[r.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),u?.map(p=>r.jsxs("option",{value:p.id,children:[p.name," (",p.ip_address,")"]},p.id))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),r.jsx(je,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function _at(){const{t}=_t(),e=tn(),{showToast:n}=on(),[a,i]=y.useState(!1),{data:s,isLoading:o}=Xe({queryKey:["virtual-printers"],queryFn:J0.list,refetchInterval:1e4}),{data:l}=Xe({queryKey:["virtual-printer-settings"],queryFn:XF.getSettings}),c=lt({mutationFn:p=>XF.updateSettings({archive_name_source:p}),onSuccess:()=>{e.invalidateQueries({queryKey:["virtual-printer-settings"]}),n(t("virtualPrinter.toast.updated"))},onError:p=>{n(p.message||t("virtualPrinter.toast.failedToUpdate"),"error")}}),d=l?.archive_name_source==="filename";if(o)return r.jsx(At,{children:r.jsx(Et,{className:"py-8 flex justify-center",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const u=s?.printers||[],m=s?.models||{};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 items-stretch",children:[r.jsx(At,{className:"border-l-4 border-l-yellow-500",children:r.jsx(Et,{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-xs",children:[r.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),r.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:[r.jsx(zr,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),r.jsx(At,{className:"lg:col-span-2",children:r.jsx(Et,{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(_i,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[r.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),r.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[r.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),r.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),r.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),r.jsx(At,{children:r.jsx(Et,{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Rs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-1"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsx("p",{className:"text-sm text-white font-medium",children:t("virtualPrinter.archiveNameSource.title")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`text-xs ${d?"text-bambu-gray":"text-white"}`,children:t("virtualPrinter.archiveNameSource.metadata")}),r.jsx(En,{checked:d,onChange:p=>c.mutate(p?"filename":"metadata"),disabled:c.isPending}),r.jsx("span",{className:`text-xs ${d?"text-white":"text-bambu-gray"}`,children:t("virtualPrinter.archiveNameSource.filename")})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("virtualPrinter.archiveNameSource.description")})]})]})})}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",u.length,")"]})]}),r.jsxs(je,{variant:"primary",onClick:()=>i(!0),children:[r.jsx(er,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),u.length===0?r.jsx(At,{children:r.jsxs(Et,{className:"py-8 text-center",children:[r.jsx(hr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),r.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),r.jsxs(je,{variant:"primary",onClick:()=>i(!0),children:[r.jsx(er,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:u.map(p=>r.jsx(wat,{printer:p,models:m},p.id))}),a&&r.jsx(Sat,{onClose:()=>i(!1)})]})}function hX(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),a=e%60;if(n<24)return a?`${n}h ${a}m`:`${n}h`;const i=Math.floor(n/24),s=n%24;return s?`${i}d ${s}h`:`${i}d`}function fX(t){return t==null?"—":t>=1024?`${(t/1024).toFixed(1)} GB`:`${Math.round(t)} MB`}function kat({device:t,onUnregister:e,isDeleting:n}){const{t:a}=_t(),{showToast:i}=on(),s=t.system_stats,o=s?.memory,l=s?.disk,c=t.online,[d,u]=y.useState(null),[m,p]=y.useState(null),f=async x=>{p(x);try{x==="update"?await Jr.triggerUpdate(t.device_id):await Jr.systemCommand(t.device_id,x),i(a("settings.spoolbuddy.commandQueued"),"success")}catch(S){const k=S instanceof Error?S.message:a("settings.spoolbuddy.commandError");i(k,"error")}finally{p(null),u(null)}},g=[{key:"update",label:a("settings.spoolbuddy.update"),icon:Zr},{key:"restart_browser",label:a("settings.spoolbuddy.restartBrowser"),icon:kO},{key:"restart_daemon",label:a("settings.spoolbuddy.restartDaemon"),icon:tr},{key:"reboot",label:a("settings.spoolbuddy.reboot"),icon:Dw},{key:"shutdown",label:a("settings.spoolbuddy.shutdown"),icon:_u,variant:"danger"}],w={update:a("settings.spoolbuddy.updateConfirmTitle"),restart_browser:a("settings.spoolbuddy.restartBrowserConfirmTitle"),restart_daemon:a("settings.spoolbuddy.restartDaemonConfirmTitle"),reboot:a("settings.spoolbuddy.rebootConfirmTitle"),shutdown:a("settings.spoolbuddy.shutdownConfirmTitle")},b={update:a("settings.spoolbuddy.updateConfirmBody",{hostname:t.hostname}),restart_browser:a("settings.spoolbuddy.restartBrowserConfirmBody",{hostname:t.hostname}),restart_daemon:a("settings.spoolbuddy.restartDaemonConfirmBody",{hostname:t.hostname}),reboot:a("settings.spoolbuddy.rebootConfirmBody",{hostname:t.hostname}),shutdown:a("settings.spoolbuddy.shutdownConfirmBody",{hostname:t.hostname})};return r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:"text-base font-semibold text-white truncate",children:t.hostname}),r.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?r.jsx(Mh,{className:"w-3 h-3"}):r.jsx(hu,{className:"w-3 h-3"}),a(c?"settings.spoolbuddy.online":"settings.spoolbuddy.offline")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray font-mono mt-1 truncate",children:t.device_id})]}),r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>e(t),disabled:n,"aria-label":a("settings.spoolbuddy.unregister"),children:[r.jsx(en,{className:"w-3.5 h-3.5"}),r.jsx("span",{className:"hidden sm:inline",children:a("settings.spoolbuddy.unregister")})]})]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.ipAddress")}),r.jsx("div",{className:"text-white font-mono",children:t.ip_address})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.firmware")}),r.jsx("div",{className:"text-white",children:t.firmware_version??"—"})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"text-bambu-gray flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),a("settings.spoolbuddy.lastSeen")]}),r.jsx("div",{className:"text-white",children:t.last_seen?Eh(t.last_seen):a("settings.spoolbuddy.never")})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.daemonUptime")}),r.jsx("div",{className:"text-white",children:hX(t.uptime_s)})]})]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(({key:x,label:S,icon:k,variant:C})=>r.jsxs(je,{variant:C??"secondary",size:"sm",onClick:()=>u(x),disabled:!c||m!==null,"aria-label":S,children:[m===x?r.jsx(ft,{className:"w-3.5 h-3.5 animate-spin"}):r.jsx(k,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:S})]},x))}),r.jsxs("div",{className:"flex items-center gap-3 text-xs flex-wrap",children:[r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.nfc_ok?r.jsx(yl,{className:"w-3.5 h-3.5 text-green-400"}):r.jsx($r,{className:"w-3.5 h-3.5 text-red-400"}),a("settings.spoolbuddy.nfc"),t.nfc_reader_type&&r.jsxs("span",{className:"text-bambu-gray/70",children:["(",t.nfc_reader_type,")"]})]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.scale_ok?r.jsx(yl,{className:"w-3.5 h-3.5 text-green-400"}):r.jsx($r,{className:"w-3.5 h-3.5 text-red-400"}),a("settings.spoolbuddy.scale")]})]}),s&&r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.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&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(RS,{className:"w-3.5 h-3.5 text-bambu-gray"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.cpuTemp")}),r.jsxs("div",{className:"text-white",children:[s.cpu_temp_c.toFixed(1),"°C"]})]})]}),o&&o.percent!==void 0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(F0,{className:"w-3.5 h-3.5 text-bambu-gray"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.memory")}),r.jsxs("div",{className:"text-white",children:[o.percent.toFixed(0),"% (",fX(o.used_mb)," / ",fX(o.total_mb),")"]})]})]}),l&&l.percent!==void 0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ib,{className:"w-3.5 h-3.5 text-bambu-gray"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.disk")}),r.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&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Zn,{className:"w-3.5 h-3.5 text-bambu-gray"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray",children:a("settings.spoolbuddy.systemUptime")}),r.jsx("div",{className:"text-white",children:hX(s.system_uptime_s)})]})]})]}),s.os&&r.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&&r.jsx(wn,{variant:d==="shutdown"||d==="reboot"?"danger":"default",title:w[d],message:b[d],confirmText:a("settings.spoolbuddy.commandConfirm"),isLoading:m!==null,onConfirm:()=>f(d),onCancel:()=>u(null)})]})}function Nat(){const{t}=_t(),e=tn(),{showToast:n}=on(),[a,i]=y.useState(null),{data:s=[],isLoading:o}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.getDevices(),refetchInterval:15e3}),l=lt({mutationFn:d=>Jr.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 r.jsx(At,{children:r.jsx(Et,{className:"py-8 flex justify-center",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const c=s.length>1;return r.jsxs("div",{className:"space-y-4",children:[r.jsx(At,{children:r.jsx(Et,{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[r.jsx(_i,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-bambu-gray",children:[r.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.infoTitle")}),r.jsx("p",{children:t("settings.spoolbuddy.infoBody")})]})]})})}),c&&r.jsx(At,{className:"border-l-4 border-l-yellow-500",children:r.jsx(Et,{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-bambu-gray",children:[r.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.duplicatesTitle",{count:s.length})}),r.jsx("p",{children:t("settings.spoolbuddy.duplicatesBody")})]})]})})}),s.length===0?r.jsx(At,{children:r.jsx(Et,{className:"py-8 text-center text-bambu-gray text-sm",children:t("settings.spoolbuddy.empty")})}):r.jsx("div",{className:"space-y-3",children:s.map(d=>r.jsx(kat,{device:d,onUnregister:i,isDeleting:l.isPending&&l.variables===d.device_id},d.id))}),a&&r.jsx(wn,{variant:"danger",title:t("settings.spoolbuddy.confirmTitle"),message:t("settings.spoolbuddy.confirmBody",{hostname:a.hostname,deviceId:a.device_id}),confirmText:t("settings.spoolbuddy.unregister"),isLoading:l.isPending,onConfirm:()=>l.mutate(a.device_id),onCancel:()=>i(null)})]})}function dF(t){if(!t)return"-";const e=Yn(t);return e?e.toLocaleString():"-"}function uF({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:r.jsx(xr,{className:"w-3 h-3"}),failed:r.jsx($r,{className:"w-3 h-3"}),skipped:r.jsx(PT,{className:"w-3 h-3"}),running:r.jsx(ft,{className:"w-3 h-3 animate-spin"})};return r.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)]})}const Cat={github:"backup.repoUrlPlaceholderGitHub",gitea:"backup.repoUrlPlaceholderGitea",forgejo:"backup.repoUrlPlaceholderForgejo",gitlab:"backup.repoUrlPlaceholderGitLab"},Pat={github:"ghp_xxxxxxxxxxxx",gitea:"your_access_token",forgejo:"your_access_token",gitlab:"glpat-xxxxxxxxxxxx"};function gX(t){return JSON.stringify(t)}function Tat(t,e){if(!e)return t;const n={};for(const a of Object.keys(t))t[a]!==e[a]&&(n[a]=t[a]);return n}function Aat(){const t=tn(),{showToast:e}=on(),{t:n}=_t(),[a,i]=y.useState(""),[s,o]=y.useState(""),[l,c]=y.useState("main"),[d,u]=y.useState("github"),[m,p]=y.useState(!1),[f,g]=y.useState("daily"),[w,b]=y.useState(!0),[x,S]=y.useState(!0),[k,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState(!0),[z,L]=y.useState(!1),[Z,ne]=y.useState(!1),[Y,ce]=y.useState(""),[ue,oe]=y.useState(!1),[Q,le]=y.useState(null),[pe,he]=y.useState(null),we=y.useRef(null),[$,J]=y.useState(null),[j,E]=y.useState(null),[B,W]=y.useState(""),{data:O,refetch:ie}=Xe({queryKey:["local-backup-status"],queryFn:ae.getLocalBackupStatus,refetchInterval:bt=>bt.state.data?.is_running?1e3:1e4}),{data:U,refetch:G}=Xe({queryKey:["local-backup-files"],queryFn:ae.getLocalBackups,refetchInterval:3e4});y.useEffect(()=>{O?.path!==void 0&&W(O.path)},[O?.path]);const K=lt({mutationFn:ae.triggerLocalBackup,onSuccess:bt=>{bt.success?e(n("backup.scheduledBackupComplete")):e(bt.message,"error"),ie(),G()},onError:()=>e(n("backup.scheduledBackupFailed"),"error")}),X=lt({mutationFn:bt=>ae.deleteLocalBackup(bt),onSuccess:()=>{G(),J(null)}}),se=lt({mutationFn:async bt=>(E(null),ne(!0),he(null),ce(n("backup.restoring")),ae.restoreLocalBackup(bt)),onSuccess:bt=>{ne(!1),ce(""),bt.success?(he({success:!0,message:bt.message}),e(n("backup.backupRestoredRestart"),"success")):(he({success:!1,message:bt.message}),e(bt.message,"error"))},onError:bt=>{ne(!1),ce("");const Wt=bt instanceof Error?bt.message:n("backup.failedToRestore");he({success:!1,message:Wt}),e(Wt,"error")}});y.useEffect(()=>{if(z||Z){const Wt=Zt=>(Zt.preventDefault(),Zt.returnValue="A backup operation is in progress. Are you sure you want to leave?",Zt.returnValue);return window.addEventListener("beforeunload",Wt),()=>window.removeEventListener("beforeunload",Wt)}},[z,Z]);const[te,fe]=y.useState(!1),[de,me]=y.useState(null),[q,R]=y.useState(null),re=y.useRef(null),be=y.useRef(null),ye=y.useRef(null),_e=y.useRef(null),xe=y.useRef(""),[ge,Me]=y.useState(!1),Be=y.useMemo(()=>({repository_url:a,branch:l,provider:d,allow_insecure_http:_,schedule_enabled:m,schedule_type:f,backup_kprofiles:w,backup_cloud_profiles:x,backup_settings:k,backup_spools:P,backup_archives:A,enabled:H}),[a,l,d,_,m,f,w,x,k,P,A,H]),Fe=y.useMemo(()=>gX(Be),[Be]),{data:Oe,isLoading:Re}=Xe({queryKey:["github-backup-config"],queryFn:ae.getGitHubBackupConfig}),{data:We}=Xe({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus,refetchInterval:bt=>bt.state.data?.is_running?500:1e4}),{data:ze}=Xe({queryKey:["github-backup-logs"],queryFn:()=>ae.getGitHubBackupLogs(20)}),{data:st}=Xe({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:Ee}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),it=rf({queries:(Ee??[]).map(bt=>({queryKey:["printerStatus",bt.id],queryFn:()=>ae.getPrinterStatus(bt.id),staleTime:1e4,refetchInterval:3e4}))}),Ce=(Ee??[]).map((bt,Wt)=>({printer:bt,connected:it[Wt]?.data?.connected??!1})),Ze=Ce.length,Ie=Ce.filter(bt=>bt.connected).length,ke=Ze>0&&Ie===0,Ve=Ie>0&&Ie<Ze;y.useEffect(()=>(ye.current&&clearTimeout(ye.current),Oe?(Me(!1),_e.current={repository_url:Oe.repository_url,branch:Oe.branch,provider:Oe.provider??"github",allow_insecure_http:Oe.allow_insecure_http??!1,schedule_enabled:Oe.schedule_enabled,schedule_type:Oe.schedule_type,backup_kprofiles:Oe.backup_kprofiles,backup_cloud_profiles:Oe.backup_cloud_profiles,backup_settings:Oe.backup_settings,backup_spools:Oe.backup_spools,backup_archives:Oe.backup_archives,enabled:Oe.enabled},i(Oe.repository_url),c(Oe.branch),u(Oe.provider??"github"),p(Oe.schedule_enabled),g(Oe.schedule_type),b(Oe.backup_kprofiles),S(Oe.backup_cloud_profiles),C(Oe.backup_settings),T(Oe.backup_spools),F(Oe.backup_archives),M(Oe.allow_insecure_http??!1),I(Oe.enabled),o(""),ye.current=setTimeout(()=>{Me(!0)},100)):(Me(!1),_e.current=null,o("")),()=>{ye.current&&clearTimeout(ye.current)}),[Oe]);const rt=y.useCallback(async(bt=!1)=>{if(Oe)try{bt&&s?(await ae.saveGitHubBackupConfig({...Be,access_token:s}),o(""),R(null),e(n("backup.tokenUpdated")),xe.current=""):(await ae.updateGitHubBackupConfig(Tat(Be,_e.current)),R(null),e(n("backup.settingsSaved"))),_e.current=Be,t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Wt){R(Wt.message)}},[Oe,s,Be,t,e,n]),Qe=y.useRef(rt);y.useEffect(()=>{Qe.current=rt},[rt]),y.useEffect(()=>{if(!(!ge||!Oe)&&!(_e.current&&Fe===gX(_e.current)))return re.current&&clearTimeout(re.current),re.current=setTimeout(()=>{rt(!1)},500),()=>{re.current&&clearTimeout(re.current)}},[ge,Oe,Fe,rt]),y.useEffect(()=>{if(!(!ge||!Oe||!s)&&s!==xe.current)return xe.current=s,be.current&&clearTimeout(be.current),be.current=setTimeout(()=>{Qe.current(!0)},1e3),()=>{be.current&&clearTimeout(be.current)}},[ge,s,Oe]);const Te=lt({mutationFn:bt=>ae.saveGitHubBackupConfig(bt),onMutate:()=>{R(null)},onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(n("backup.githubBackupEnabled")),o(""),Me(!0)},onError:bt=>{R(bt.message)}}),tt=lt({mutationFn:ae.triggerGitHubBackup,onSuccess:bt=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),bt.success?bt.files_changed>0?e(n("backup.backupCompleteFiles",{count:bt.files_changed})):e(n("backup.backupSkippedNoChanges")):e(n("backup.backupFailed2",{message:bt.message}),"error")},onError:bt=>{e(n("backup.backupFailed2",{message:bt.message}),"error")}}),ot=lt({mutationFn:()=>ae.clearGitHubBackupLogs(0),onSuccess:bt=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(n("backup.clearedLogs",{count:bt.deleted}))},onError:bt=>{e(n("backup.failedToClearLogs",{message:bt.message}),"error")}}),Tt=async()=>{fe(!0),me(null);try{let bt;if(s){if(!a){e(n("backup.enterRepoUrl"),"error"),fe(!1);return}bt=await ae.testGitHubConnection(a,s,d)}else if(Oe?.has_token)bt=await ae.testGitHubStoredConnection();else{e(n("backup.enterRepoAndToken"),"error"),fe(!1);return}me({success:bt.success,message:bt.message,isPrivate:bt.is_private})}catch(bt){me({success:!1,message:bt.message,isPrivate:null})}finally{fe(!1)}},Ut=()=>{if(!a){e(n("backup.repoRequired"),"error");return}if(!s){e(n("backup.tokenRequired"),"error");return}Te.mutate({repository_url:a,access_token:s,branch:l,provider:d,allow_insecure_http:_,schedule_enabled:m,schedule_type:f,backup_kprofiles:w,backup_cloud_profiles:x,backup_settings:k,backup_spools:P,backup_archives:A,enabled:H})};return Re?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[r.jsxs("div",{className:"space-y-6",children:[r.jsxs(At,{id:"card-backup-github",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(VF,{className:"w-5 h-5 text-gray-400"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.githubBackup")})]}),Oe&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.enabled")}),r.jsx(En,{checked:H,onChange:I})]})]})}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.githubDescription")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"git-provider-select",className:"block text-sm text-bambu-gray mb-1",children:n("backup.provider")}),r.jsxs("select",{id:"git-provider-select",value:d,onChange:bt=>{u(bt.target.value),me(null),R(null)},className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"github",children:n("backup.providerGitHub")}),r.jsx("option",{value:"gitlab",children:n("backup.providerGitLab")}),r.jsx("option",{value:"gitea",children:n("backup.providerGitea")}),r.jsx("option",{value:"forgejo",children:n("backup.providerForgejo")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.repositoryUrl")}),r.jsx("input",{type:"text",value:a,onChange:bt=>{i(bt.target.value),me(null),R(null)},placeholder:n(Cat[d]),className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),r.jsxs("label",{className:"flex items-start gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_,onChange:bt=>{M(bt.target.checked),me(null)},className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:n("backup.allowInsecureHttp")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.allowInsecureHttpHint")})]})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("backup.personalAccessToken")," ",Oe?.has_token&&r.jsx("span",{className:"text-green-400",children:n("backup.tokenSaved")})]}),r.jsx("input",{type:"password",value:s,onChange:bt=>{o(bt.target.value),me(null),R(null)},placeholder:Oe?.has_token?n("backup.enterNewToken"):Pat[d],className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("backup.tokenHint")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.branch")}),r.jsx("input",{type:"text",value:l,onChange:bt=>c(bt.target.value),placeholder:"main",className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.autoBackup")}),r.jsxs("select",{value:m?f:"disabled",onChange:bt=>{bt.target.value==="disabled"?p(!1):(p(!0),g(bt.target.value))},className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"disabled",children:n("backup.manualOnly")}),r.jsx("option",{value:"hourly",children:n("backup.hourly")}),r.jsx("option",{value:"daily",children:n("backup.daily")}),r.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:n("backup.includeInBackup")}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:`flex items-start gap-2 ${ke?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[r.jsx("input",{type:"checkbox",checked:w,onChange:bt=>b(bt.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:ke}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`text-sm ${ke?"text-bambu-gray":"text-white"}`,children:n("backup.kProfiles")}),ke&&r.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:[r.jsx(Nn,{className:"w-3 h-3"}),n("backup.noPrintersConnected")]}),Ve&&r.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:[r.jsx(Nn,{className:"w-3 h-3"}),n("backup.printersConnected",{connected:Ie,total:Ze})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.kProfilesDescription")})]})]}),r.jsxs("label",{className:`flex items-start gap-2 ${st?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[r.jsx("input",{type:"checkbox",checked:x,onChange:bt=>S(bt.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:!st?.is_authenticated}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`text-sm ${st?.is_authenticated?"text-white":"text-bambu-gray"}`,children:n("backup.cloudProfiles")}),!st?.is_authenticated&&r.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:[r.jsx(Nn,{className:"w-3 h-3"}),n("backup.cloudLoginRequiredShort")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.cloudProfilesDescription")})]})]}),r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:k,onChange:bt=>C(bt.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"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white text-sm",children:n("backup.appSettings")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.appSettingsDescription")})]})]}),r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:P,onChange:bt=>T(bt.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"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white text-sm",children:n("backup.spoolInventory")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.spoolInventoryDescription")})]})]}),r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:A,onChange:bt=>F(bt.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"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white text-sm",children:n("backup.printArchives")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.printArchivesDescription")})]})]})]})]}),r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[We?.configured&&r.jsxs("div",{className:"flex items-center justify-between text-sm",children:[r.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:We.last_backup_at?r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[n("backup.lastBackupAt")," ",Eh(We.last_backup_at,"system",n)]}),r.jsx(uF,{status:We.last_backup_status})]}):r.jsx("span",{children:n("backup.noBackupsYet")})}),We.next_scheduled_run&&r.jsxs("span",{className:"text-bambu-gray",children:[r.jsx(Zn,{className:"w-3 h-3 inline mr-1"}),n("backup.next")," ",Eh(We.next_scheduled_run,"system",n)]})]}),q&&r.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 border border-red-500/30 rounded p-3 flex items-start gap-2",children:[r.jsx($r,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("div",{className:"flex-1 leading-relaxed whitespace-pre-wrap break-words",children:q}),r.jsx("button",{type:"button",onClick:()=>R(null),className:"text-bambu-gray hover:text-white shrink-0","aria-label":n("common.dismiss","Dismiss"),children:r.jsx($r,{className:"w-4 h-4"})})]}),de&&r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:`text-sm flex items-center gap-1 ${de.success?"text-green-400":"text-red-400"}`,children:[de.success?r.jsx(xr,{className:"w-4 h-4"}):r.jsx($r,{className:"w-4 h-4"}),de.message]}),de.success&&de.isPrivate===!0&&r.jsxs("div",{className:"text-xs flex items-center gap-1 text-green-400",children:[r.jsx(xr,{className:"w-3.5 h-3.5"}),n("backup.repoIsPrivate","Repository is private — safe to back up to.")]}),de.success&&de.isPrivate===!1&&r.jsxs("div",{className:"text-xs text-red-400 bg-red-500/10 border border-red-500/30 rounded p-2 flex items-start gap-1.5",children:[r.jsx($r,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:n("backup.repoIsPublicWarning","Repository is PUBLIC. Bambuddy backups include MQTT credentials, Home Assistant tokens, Prometheus tokens, your Bambu Cloud email, and printer access codes via K-profiles. Saving is blocked until you make the repository private in your provider's settings.")})]}),de.success&&de.isPrivate===null&&r.jsxs("div",{className:"text-xs text-yellow-400 bg-yellow-500/10 border border-yellow-500/30 rounded p-2 flex items-start gap-1.5",children:[r.jsx($r,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:n("backup.repoVisibilityUnknown","Could not determine repository visibility. Bambuddy refuses to back up to anything not confirmed private; saving will be blocked.")})]})]}),r.jsx("div",{className:"flex flex-wrap items-center gap-2",children:We?.configured?r.jsx(r.Fragment,{children:tt.isPending||We.is_running?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{className:"text-sm",children:We.progress||n("backup.startingBackup")})]}):r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>tt.mutate(),disabled:!Oe?.enabled,children:[r.jsx(hs,{className:"w-4 h-4"}),n("backup.backupNow")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:Tt,disabled:te,children:[te?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),n("backup.test")]})]})}):r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"primary",size:"sm",onClick:Ut,disabled:Te.isPending||!a||!s,children:[Te.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(xr,{className:"w-4 h-4"}),n("backup.enableBackup")]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:Tt,disabled:te||!a||!s,children:[te?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),n("backup.testConnection")]})]})})]})]})]}),ze&&ze.length>0&&r.jsxs(At,{id:"card-backup-history",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Vh,{className:"w-5 h-5 text-gray-400"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.history")})]}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>ot.mutate(),disabled:ot.isPending,children:[r.jsx(en,{className:"w-4 h-4"}),n("backup.clear")]})]})}),r.jsx(Et,{children:r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left py-2 px-2",children:n("backup.date")}),r.jsx("th",{className:"text-left py-2 px-2",children:n("backup.status")}),r.jsx("th",{className:"text-left py-2 px-2",children:n("backup.commit")})]})}),r.jsx("tbody",{children:ze.slice(0,10).map(bt=>r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[r.jsx("td",{className:"py-2 px-2 text-white",children:dF(bt.started_at)}),r.jsx("td",{className:"py-2 px-2",children:r.jsx(uF,{status:bt.status})}),r.jsx("td",{className:"py-2 px-2",children:bt.commit_sha?r.jsxs("a",{href:`${Oe?.repository_url}/commit/${bt.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[bt.commit_sha.substring(0,7),r.jsx(zr,{className:"w-3 h-3"})]}):r.jsx("span",{className:"text-bambu-gray",children:"-"})})]},bt.id))})]})})})]})]}),r.jsxs("div",{className:"space-y-6",children:[r.jsxs(At,{id:"card-backup-local",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(dc,{className:"w-5 h-5 text-gray-400"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.localBackup")})]})}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.localBackupDescription")}),r.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:n("backup.downloadBackupLabel")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.completeBackupZip")})]}),r.jsxs(je,{variant:"secondary",size:"sm",disabled:z||Z,onClick:async()=>{L(!0),ce(n("backup.preparingBackup"));try{ce(n("backup.creatingArchive"));const{blob:bt,filename:Wt}=await ae.exportBackup();ce(n("backup.downloadingFile"));const Zt=URL.createObjectURL(bt),ln=document.createElement("a");ln.href=Zt,ln.download=Wt,ln.click(),URL.revokeObjectURL(Zt),e(n("backup.backupDownloaded"))}catch(bt){e(n("backup.failedToCreateBackup",{message:bt instanceof Error?bt.message:"Unknown error"}),"error")}finally{L(!1),ce("")}},children:[r.jsx(Zr,{className:"w-4 h-4"}),n("backup.download")]})]}),r.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),r.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),r.jsx("input",{ref:we,type:"file",accept:".zip",className:"hidden",onChange:bt=>{const Wt=bt.target.files?.[0];Wt&&(le(Wt),oe(!0)),bt.target.value=""}}),r.jsxs(je,{variant:"secondary",size:"sm",disabled:Z||z,onClick:()=>we.current?.click(),children:[r.jsx(_a,{className:"w-4 h-4"}),n("backup.restore")]})]}),pe&&r.jsx("div",{className:`p-3 rounded-lg ${pe.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:r.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[pe.success?r.jsx(xr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):r.jsx($r,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:pe.success?"text-green-200":"text-red-200",children:[pe.message,pe.success&&r.jsx("div",{className:"mt-2",children:r.jsxs(je,{size:"sm",onClick:()=>window.location.reload(),children:[r.jsx(fs,{className:"w-3 h-3"}),n("backup.reloadNow")]})})]})]})}),r.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:r.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"text-yellow-200",children:[r.jsx("span",{className:"font-medium",children:n("backup.restoreReplacesAll")})," ",r.jsx("span",{className:"text-yellow-200/70",children:n("backup.restoreReplacesAllDetail")})]})]})})]})]}),r.jsxs(At,{id:"card-backup-scheduled",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(kbe,{className:"w-5 h-5 text-gray-400"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.scheduledBackup")})]}),r.jsx(En,{checked:O?.enabled??!1,onChange:async bt=>{try{await ae.updateSettings({local_backup_enabled:bt}),t.invalidateQueries({queryKey:["settings"]}),e(n("backup.settingsSaved"))}catch(Wt){e(n("backup.failedToSave",{message:Wt instanceof Error?Wt.message:"Unknown error"}),"error")}ie()}})]})}),r.jsxs(Et,{className:"space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.scheduledBackupDescription")}),O?.enabled&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.frequency")}),r.jsxs("select",{value:O?.schedule??"daily",className:"w-full h-10 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 bt=>{try{await ae.updateSettings({local_backup_schedule:bt.target.value}),e(n("backup.settingsSaved"))}catch(Wt){e(n("backup.failedToSave",{message:Wt instanceof Error?Wt.message:"Unknown error"}),"error")}ie()},children:[r.jsx("option",{value:"hourly",children:n("backup.hourly")}),r.jsx("option",{value:"daily",children:n("backup.daily")}),r.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]}),(O?.schedule??"daily")!=="hourly"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.backupTime")}),r.jsx("input",{type:"time",value:O?.time??"03:00",className:"w-full h-10 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 bt=>{try{await ae.updateSettings({local_backup_time:bt.target.value}),e(n("backup.settingsSaved"))}catch(Wt){e(n("backup.failedToSave",{message:Wt instanceof Error?Wt.message:"Unknown error"}),"error")}ie()}}),r.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.utc")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.retention")}),r.jsx("input",{type:"number",min:1,max:100,value:O?.retention??5,className:"w-full h-10 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 bt=>{const Wt=Math.max(1,Math.min(100,parseInt(bt.target.value)||5));try{await ae.updateSettings({local_backup_retention:Wt}),e(n("backup.settingsSaved"))}catch(Zt){e(n("backup.failedToSave",{message:Zt instanceof Error?Zt.message:"Unknown error"}),"error")}ie()}}),r.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.retentionDescription")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.outputPath")}),r.jsx("input",{type:"text",value:B,onChange:bt=>W(bt.target.value),className:"w-full h-10 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 ae.updateSettings({local_backup_path:B}),e(n("backup.settingsSaved"))}catch(bt){e(n("backup.failedToSave",{message:bt instanceof Error?bt.message:"Unknown error"}),"error")}ie(),G()},onKeyDown:bt=>{bt.key==="Enter"&&bt.target.blur()}}),r.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:B?n("backup.outputPathDescription"):r.jsxs(r.Fragment,{children:[n("backup.defaultPathLabel")," ",r.jsx("code",{className:"text-bambu-gray",children:O?.default_path||"..."})]})})]}),r.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"text-sm",children:[O?.last_backup_at&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsxs("span",{children:[n("backup.lastBackup"),":"]}),r.jsx(uF,{status:O.last_status}),r.jsx("span",{children:Eh(O.last_backup_at)})]}),O?.next_run&&r.jsxs("div",{className:"text-bambu-gray mt-1",children:[r.jsxs("span",{children:[n("backup.nextBackup"),": "]}),r.jsx("span",{children:dF(O.next_run)})]})]}),r.jsxs(je,{variant:"secondary",size:"sm",disabled:O?.is_running||K.isPending,onClick:()=>K.mutate(),children:[O?.is_running||K.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(hs,{className:"w-4 h-4"}),O?.is_running?n("backup.backupRunning"):n("backup.runNow")]})]}),U&&U.length>0&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:n("backup.backupFiles")}),r.jsx("div",{className:"space-y-1",children:U.map(bt=>r.jsxs("div",{className:"flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-white truncate block",children:bt.filename}),r.jsxs("span",{className:"text-bambu-gray text-xs",children:[(bt.size/1024/1024).toFixed(1)," MB · ",dF(bt.created_at)]})]}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[r.jsx("button",{className:"text-bambu-gray hover:text-bambu-green p-1",title:n("backup.download"),onClick:async()=>{try{const{blob:Wt,filename:Zt}=await ae.downloadLocalBackup(bt.filename),ln=URL.createObjectURL(Wt),cn=document.createElement("a");cn.href=ln,cn.download=Zt,cn.click(),URL.revokeObjectURL(ln)}catch{e(n("backup.scheduledBackupFailed"),"error")}},children:r.jsx(Zr,{className:"w-3.5 h-3.5"})}),r.jsx("button",{className:"text-bambu-gray hover:text-yellow-400 p-1",title:n("backup.restore"),onClick:()=>E(bt.filename),children:r.jsx(fs,{className:"w-3.5 h-3.5"})}),r.jsx("button",{className:"text-bambu-gray hover:text-red-400 p-1",onClick:()=>J(bt.filename),title:n("backup.deleteBackup"),children:r.jsx(en,{className:"w-3.5 h-3.5"})})]})]},bt.filename))})]}),U&&U.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary",children:n("backup.noScheduledBackups")})]})]})]})]}),$&&r.jsx(wn,{title:n("backup.deleteBackup"),message:n("backup.deleteBackupConfirm"),confirmText:n("backup.deleteBackup"),variant:"danger",onConfirm:()=>X.mutate($),onCancel:()=>J(null)}),j&&r.jsx(wn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:j}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:()=>se.mutate(j),onCancel:()=>E(null)}),ue&&Q&&r.jsx(wn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:Q.name}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{oe(!1),ne(!0),he(null);try{ce(n("backup.uploadingFile"));const bt=await ae.importBackup(Q);he(bt),bt.success?e(n("backup.backupRestoredRestart"),"success"):e(bt.message,"error")}catch(bt){const Wt=bt instanceof Error?bt.message:n("backup.failedToRestore");he({success:!1,message:Wt}),e(Wt,"error")}finally{ne(!1),ce(""),le(null)}},onCancel:()=>{oe(!1),le(null)}}),(z||Z)&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:r.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:[r.jsx("div",{className:"flex justify-center mb-4",children:r.jsxs("div",{className:"relative",children:[r.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),r.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),r.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:n(z?"backup.creatingBackup":"backup.restoringBackup")}),r.jsx("p",{className:"text-bambu-gray mb-4",children:Y||n(z?"backup.preparing":"backup.processing")}),r.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:r.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-yellow-200 text-left",children:n("backup.doNotClosePage")})]})})]})})]})}function jat(){const{t}=_t(),e=tn(),{showToast:n}=on(),[a,i]=y.useState(!1),[s,o]=y.useState(""),[l,c]=y.useState("medium"),[d,u]=y.useState("notify"),[m,p]=y.useState(10),[f,g]=y.useState(null),[w,b]=y.useState(null),[x,S]=y.useState(!1),{data:k}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:C,refetch:P}=Xe({queryKey:["obico-status"],queryFn:ae.getObicoStatus,refetchInterval:1e4}),{data:T}=Xe({queryKey:["printers"],queryFn:ae.getPrinters});y.useEffect(()=>{if(k){i(k.obico_enabled??!1),o(k.obico_ml_url??""),c(k.obico_sensitivity??"medium"),u(k.obico_action??"notify"),p(k.obico_poll_interval??10);try{const M=k.obico_enabled_printers?JSON.parse(k.obico_enabled_printers):null;g(Array.isArray(M)?M:null)}catch{g(null)}S(!0)}},[k]);const A=lt({mutationFn:()=>ae.updateSettings({obico_enabled:a,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"))}});y.useEffect(()=>{if(!x||!k||!(k.obico_enabled!==a||k.obico_ml_url!==s||k.obico_sensitivity!==l||k.obico_action!==d||k.obico_poll_interval!==m||k.obico_enabled_printers!==(f===null?"":JSON.stringify(f))))return;const H=setTimeout(()=>A.mutate(),500);return()=>clearTimeout(H)},[a,s,l,d,m,f,x]);const F=async()=>{b(null);try{const M=await ae.testObicoConnection(s);M.ok?b({ok:!0,message:t("failureDetection.testSuccess")}):b({ok:!1,message:M.error||`HTTP ${M.status_code??"?"} — ${M.body??t("failureDetection.testFailed")}`})}catch(M){b({ok:!1,message:M instanceof Error?M.message:String(M)})}},_=(M,H)=>{if(f===null){const I=T?.map(L=>L.id)??[],z=H?I:I.filter(L=>L!==M);g(z);return}g(H?[...f,M]:f.filter(I=>I!==M))};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[r.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[r.jsxs(At,{id:"card-fd-ml",children:[r.jsxs(fn,{children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($Z,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.title")})]}),r.jsx(En,{checked:a,onChange:i})]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:t("failureDetection.description")})]}),r.jsxs(Et,{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.mlUrl")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:s,onChange:M=>o(M.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:!a}),r.jsx(je,{onClick:F,disabled:!s||A.isPending,variant:"secondary",children:t("failureDetection.test")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.mlUrlHint")}),w&&r.jsxs("div",{className:`flex items-start gap-2 mt-2 text-sm ${w.ok?"text-green-400":"text-red-400"}`,children:[w.ok?r.jsx(Ar,{className:"w-4 h-4 mt-0.5"}):r.jsx(Vt,{className:"w-4 h-4 mt-0.5"}),r.jsx("span",{children:w.message})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.sensitivity")}),r.jsxs("select",{value:l,onChange:M=>c(M.target.value),disabled:!a,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[r.jsx("option",{value:"low",children:t("failureDetection.sensitivityLow")}),r.jsx("option",{value:"medium",children:t("failureDetection.sensitivityMedium")}),r.jsx("option",{value:"high",children:t("failureDetection.sensitivityHigh")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.sensitivityHint")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.action")}),r.jsxs("select",{value:d,onChange:M=>u(M.target.value),disabled:!a,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[r.jsx("option",{value:"notify",children:t("failureDetection.actionNotify")}),r.jsx("option",{value:"pause",children:t("failureDetection.actionPause")}),r.jsx("option",{value:"pause_and_off",children:t("failureDetection.actionPauseOff")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.pollInterval")}),r.jsx("input",{type:"number",value:m,onChange:M=>p(Math.max(5,Math.min(120,Number(M.target.value)||10))),min:5,max:120,disabled:!a,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.pollIntervalHint")})]}),C&&!C.external_url_configured&&a&&r.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:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("div",{className:"font-medium",children:t("failureDetection.externalUrlMissing")}),r.jsx("div",{className:"text-xs mt-1",children:t("failureDetection.externalUrlHint")})]})]})]})]}),r.jsxs(At,{id:"card-fd-perprinter",children:[r.jsxs(fn,{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.perPrinterTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("failureDetection.perPrinterHint")})]}),r.jsxs(Et,{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[r.jsx("input",{type:"checkbox",checked:f===null,onChange:M=>g(M.target.checked?null:T?.map(H=>H.id)??[]),disabled:!a}),r.jsx("span",{className:"text-white",children:t("failureDetection.monitorAll")})]}),f!==null&&T&&r.jsx("div",{className:"pl-5 space-y-1 border-l border-gray-700",children:T.map(M=>r.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[r.jsx("input",{type:"checkbox",checked:f.includes(M.id),onChange:H=>_(M.id,H.target.checked),disabled:!a}),r.jsx("span",{className:"text-white",children:M.name})]},M.id))})]})]})]}),r.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[r.jsxs(At,{id:"card-fd-status",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.statusTitle")})}),r.jsx(Et,{children:C?r.jsxs("div",{className:"space-y-3 text-sm",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.serviceRunning")}),r.jsx("span",{className:C.is_running?"text-green-400":"text-red-400",children:C.is_running?t("common.yes"):t("common.no")})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.thresholds")}),r.jsxs("span",{className:"text-white font-mono",children:[C.thresholds.low.toFixed(2)," / ",C.thresholds.high.toFixed(2)]})]}),C.last_error&&r.jsxs("div",{className:"flex items-start gap-2 text-red-400",children:[r.jsx(Vt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),r.jsx("span",{className:"break-words",children:C.last_error})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-bambu-gray mb-1",children:t("failureDetection.activePrinters")}),Object.keys(C.per_printer).length===0?r.jsx("div",{className:"text-bambu-gray italic text-xs",children:t("failureDetection.noActivePrints")}):r.jsx("div",{className:"space-y-1",children:Object.entries(C.per_printer).map(([M,H])=>{const I=T?.find(L=>String(L.id)===M),z=H.class==="failure"?"text-red-400":H.class==="warning"?"text-amber-400":"text-green-400";return r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-white",children:I?.name??`Printer ${M}`}),r.jsxs("span",{className:`font-mono ${z}`,children:[H.class," (",H.score.toFixed(3),", ",H.frame_count,"f)"]})]},M)})})]})]}):r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:t("common.loading")})]})})]}),r.jsxs(At,{id:"card-fd-history",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.historyTitle")}),r.jsx("button",{onClick:()=>P(),className:"text-xs text-bambu-gray hover:text-white",children:t("common.refresh")})]})}),r.jsx(Et,{children:!C||C.history.length===0?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(_i,{className:"w-4 h-4"}),r.jsx("span",{children:t("failureDetection.noHistory")})]}):r.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto text-xs font-mono",children:C.history.map((M,H)=>{const I=T?.find(L=>L.id===M.printer_id),z=M.class==="failure"?"text-red-400":M.class==="warning"?"text-amber-400":"text-bambu-gray";return r.jsxs("div",{className:"flex justify-between gap-2 py-1 border-b border-gray-800",children:[r.jsx("span",{className:"text-bambu-gray",children:new Date(M.timestamp).toLocaleTimeString()}),r.jsx("span",{className:"text-white truncate",children:I?.name??`#${M.printer_id}`}),r.jsxs("span",{className:z,children:[M.class," ",M.score.toFixed(3)]})]},H)})})})]})]})]})}const Mat={starttls:587,ssl:465,none:25},Eat={587:"starttls",465:"ssl",25:"none"};function Dat(){const{t}=_t(),{showToast:e}=on(),n=tn(),[a,i]=y.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]=y.useState(""),{data:l,isLoading:c}=Xe({queryKey:["smtpSettings"],queryFn:()=>ae.getSMTPSettings()}),{authEnabled:d}=dr(),{data:u}=Xe({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()});y.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=A=>{i({...a,smtp_security:A,smtp_port:Mat[A]})},p=A=>{const F=Eat[A];i({...a,smtp_port:A,...F?{smtp_security:F}:{}})},f=A=>{i({...a,smtp_auth_enabled:A,...A?{}:{smtp_username:"",smtp_password:""}})},g=lt({mutationFn:A=>ae.saveSMTPSettings(A),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:A=>{e(A.message,"error")}}),w=lt({mutationFn:A=>ae.testSMTP(A),onSuccess:A=>{e(A.message,A.success?"success":"error")},onError:A=>{e(A.message,"error")}}),b=lt({mutationFn:A=>A?ae.enableAdvancedAuth():ae.disableAdvancedAuth(),onSuccess:A=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(A.message,"success")},onError:A=>{e(A.message,"error")}}),x=()=>{if(!a.smtp_host||!a.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(a.smtp_auth_enabled&&!a.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}g.mutate(a)},S=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}w.mutate({test_recipient:s})},k=()=>{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}b.mutate(!u?.advanced_auth_enabled)};if(c)return r.jsx("div",{className:"flex items-center justify-center p-12",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})});const C=u?.advanced_auth_enabled??!1,P="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",T="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 r.jsxs("div",{className:"space-y-3",children:[r.jsxs(At,{id:"card-email-advanced-auth",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),r.jsx(je,{onClick:k,disabled:b.isPending,variant:C?"danger":"primary",children:C?r.jsxs(r.Fragment,{children:[r.jsx(X0,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):r.jsxs(r.Fragment,{children:[r.jsx(rc,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),r.jsx(Et,{children:r.jsx("div",{className:"space-y-3",children:C?r.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(xr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),r.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[r.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),r.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),r.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),r.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):r.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),r.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[r.jsx("div",{className:"lg:col-span-2",children:r.jsxs(At,{id:"card-smtp-config",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),r.jsx(Et,{children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.authentication")||"Authentication"}),r.jsxs("select",{value:a.smtp_auth_enabled?"true":"false",onChange:A=>f(A.target.value==="true"),className:P,children:[r.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),r.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),r.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${a.smtp_auth_enabled?"":"opacity-40 pointer-events-none"}`,children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.username")||"Username"}),r.jsx("input",{type:"text",value:a.smtp_username||"",onChange:A=>i({...a,smtp_username:A.target.value}),placeholder:"your.email@gmail.com",disabled:!a.smtp_auth_enabled,className:a.smtp_auth_enabled?P:T})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.password")||"Password"}),r.jsx("input",{type:"password",value:a.smtp_password||"",onChange:A=>i({...a,smtp_password:A.target.value}),placeholder:l?"••••••••":"App password",disabled:!a.smtp_auth_enabled,className:a.smtp_auth_enabled?P:T})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),r.jsx("input",{type:"text",value:a.smtp_host,onChange:A=>i({...a,smtp_host:A.target.value}),placeholder:"smtp.gmail.com",className:P})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.smtpPort")||"SMTP Port"}),r.jsx("input",{type:"number",value:a.smtp_port,onChange:A=>p(parseInt(A.target.value)||587),placeholder:"587",className:P})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.security")||"Security"}),r.jsxs("select",{value:a.smtp_security,onChange:A=>m(A.target.value),className:P,children:[r.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),r.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),r.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.fromEmail")||"From Email"," *"]}),r.jsx("input",{type:"email",value:a.smtp_from_email,onChange:A=>i({...a,smtp_from_email:A.target.value}),placeholder:"your@email.com",className:P})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.fromName")||"From Name"}),r.jsx("input",{type:"text",value:a.smtp_from_name,onChange:A=>i({...a,smtp_from_name:A.target.value}),placeholder:"BamBuddy",className:P})]})]}),r.jsx("div",{className:"flex gap-2",children:r.jsx(je,{onClick:x,disabled:g.isPending,className:"flex-1",children:g.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),r.jsx("div",{children:r.jsxs(At,{id:"card-email-test",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),r.jsx(Et,{children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.testRecipient")||"Test Recipient Email"}),r.jsx("input",{type:"email",value:s,onChange:A=>o(A.target.value),placeholder:"test@example.com",className:P})]}),r.jsx(je,{onClick:S,disabled:w.isPending,variant:"secondary",children:w.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):r.jsxs(r.Fragment,{children:[r.jsx(LS,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const Fat={starttls:"389",ldaps:"636"};function Lat(){const{t}=_t(),{showToast:e}=on(),n=tn(),{authEnabled:a}=dr(),[i,s]=y.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}=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings()}),{data:c}=Xe({queryKey:["ldapStatus"],queryFn:()=>ae.getLDAPStatus()}),{data:d=[]}=Xe({queryKey:["groups"],queryFn:()=>ae.getGroups()});y.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=lt({mutationFn:x=>ae.updateSettings(x),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(t("settings.ldap.settingsSaved")||"LDAP settings saved","success")},onError:x=>{e(x.message,"error")}}),m=lt({mutationFn:x=>ae.updateSettings({ldap_enabled:x}),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:x=>{e(x.message,"error")}}),p=lt({mutationFn:()=>ae.testLDAP(),onSuccess:x=>{e(x.message,x.success?"success":"error")},onError:x=>{e(x.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 x={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&&(x.ldap_bind_password=i.ldap_bind_password),u.mutate(x)},g=()=>{if(!a){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 r.jsx("div",{className:"flex items-center justify-center p-12",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})});const w=c?.ldap_enabled??!1,b="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 r.jsxs("div",{className:"space-y-3",children:[r.jsxs(At,{id:"card-ldap-toggle",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hl,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.title")||"LDAP Authentication"})]}),r.jsx(je,{onClick:g,disabled:m.isPending,variant:w?"danger":"primary",children:w?r.jsxs(r.Fragment,{children:[r.jsx(X0,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):r.jsxs(r.Fragment,{children:[r.jsx(rc,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),r.jsx(Et,{children:w?r.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(xr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.enabledDesc")||"LDAP authentication is enabled"}),r.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[r.jsx("li",{children:t("settings.ldap.feature1")||"Users can login with LDAP credentials"}),r.jsx("li",{children:t("settings.ldap.feature2")||"Local admin account remains as fallback"}),r.jsx("li",{children:t("settings.ldap.feature3")||"LDAP groups are mapped to BamBuddy groups on login"})]})]})]})}):r.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.disabledDesc")||"LDAP authentication is disabled"}),r.jsx("p",{className:"text-sm text-yellow-300 mt-1",children:t("settings.ldap.disabledHint")||"Configure and save LDAP settings below, then enable."})]})]})})})]}),r.jsxs(At,{id:"card-ldap-server",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),r.jsx(Et,{children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[r.jsxs("div",{className:"md:col-span-2",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.serverUrl")||"Server URL"}),r.jsx("input",{type:"text",className:b,placeholder:"ldaps://ldap.example.com:636",value:i.ldap_server_url,onChange:x=>s({...i,ldap_server_url:x.target.value})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.serverUrlHint")||"Use ldaps:// for SSL or ldap:// with StartTLS"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.security")||"Security"}),r.jsx("div",{className:"flex gap-2",children:["starttls","ldaps"].map(x=>r.jsx("button",{onClick:()=>s({...i,ldap_security:x}),className:`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${i.ldap_security===x?"bg-bambu-green text-black":"bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:x==="starttls"?"StartTLS":"LDAPS"},x))}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.securityHint")||`Default port: ${Fat[i.ldap_security]}`})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindDn")||"Bind DN (Service Account)"}),r.jsx("input",{type:"text",className:b,placeholder:"cn=service-account,ou=service,dc=example,dc=com",value:i.ldap_bind_dn,onChange:x=>s({...i,ldap_bind_dn:x.target.value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindPassword")||"Bind Password"}),r.jsx("input",{type:"password",className:b,placeholder:o?.ldap_bind_dn?"••••••••":"",value:i.ldap_bind_password,onChange:x=>s({...i,ldap_bind_password:x.target.value})})]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.searchBase")||"Search Base DN"}),r.jsx("input",{type:"text",className:b,placeholder:"ou=users,dc=example,dc=com",value:i.ldap_search_base,onChange:x=>s({...i,ldap_search_base:x.target.value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.userFilter")||"User Search Filter"}),r.jsx("input",{type:"text",className:b,placeholder:"(sAMAccountName={username})",value:i.ldap_user_filter,onChange:x=>s({...i,ldap_user_filter:x.target.value})})]})]}),r.jsx(m5,{summary:r.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:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white",children:t("settings.ldap.autoProvision")||"Auto-provision users"}),r.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"})]}),r.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:r.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"}`})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.defaultGroup")||"Default group"}),r.jsxs("select",{className:b,value:i.ldap_default_group,onChange:x=>s({...i,ldap_default_group:x.target.value}),children:[r.jsx("option",{value:"",children:t("settings.ldap.defaultGroupNone")||"— None (reject login) —"}),d.map(x=>r.jsx("option",{value:x.name,children:x.name},x.id))]}),r.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."})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.groupMapping")||"Group Mapping (JSON)"}),r.jsx("textarea",{className:`${b} font-mono text-sm`,rows:4,placeholder:`{
  8327. "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",
  8328. "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"
  8329. }`,value:i.ldap_group_mapping,onChange:x=>s({...i,ldap_group_mapping:x.target.value})}),r.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(x=>x.name).join(", ")]})]})]})}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsxs(je,{onClick:f,disabled:u.isPending,children:[u.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(xr,{className:"w-4 h-4"}),t("common.save")||"Save"]}),r.jsxs(je,{variant:"secondary",onClick:()=>p.mutate(),disabled:p.isPending,children:[p.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(LS,{className:"w-4 h-4"}),t("settings.ldap.testConnection")||"Test Connection"]})]})]})})]})]})}function qN({value:t,onChange:e,placeholder:n,maxLength:a=6}){return r.jsx("input",{type:"text",value:t,onChange:i=>e(i.target.value.toUpperCase().replace(/\s/g,"")),maxLength:a,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 Hce({codes:t,onDone:e}){const{t:n}=_t(),[a,i]=y.useState(!1),s=()=>{navigator.clipboard.writeText(t.join(`
  8330. `)),i(!0),setTimeout(()=>i(!1),2e3)};return r.jsxs("div",{className:"space-y-4",children:[r.jsx("div",{className:"bg-amber-500/10 border border-amber-500/30 rounded-lg p-4",children:r.jsx("p",{className:"text-amber-400 text-sm font-medium",children:n("settings.twoFa.backupCodesWarning")})}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map((o,l)=>r.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))}),r.jsxs("div",{className:"flex gap-3",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:s,className:"flex items-center gap-2",children:[r.jsx(Ti,{className:"w-4 h-4"}),n(a?"common.copied":"common.copy")]}),r.jsx(je,{variant:"primary",size:"sm",onClick:e,className:"flex-1",children:n("settings.twoFa.savedCodes")})]})]})}function Rat({onDone:t}){const{t:e}=_t(),n=tn(),{showToast:a}=on(),[i,s]=y.useState("qr"),[o,l]=y.useState(""),[c,d]=y.useState([]),[u,m]=y.useState(!1),{data:p,isLoading:f}=Xe({queryKey:["totp-setup"],queryFn:()=>ae.setupTOTP(),staleTime:1/0}),g=lt({mutationFn:w=>ae.enableTOTP(w),onSuccess:w=>{d(w.backup_codes),s("backup"),n.invalidateQueries({queryKey:["2fa-status"]})},onError:()=>a(e("settings.twoFa.invalidCode"),"error")});return f||!p?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(tr,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i==="qr"?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:e("settings.twoFa.setupInstructions")}),r.jsx("div",{className:"flex justify-center",children:r.jsx("img",{src:`data:image/png;base64,${p.qr_code_b64}`,alt:"TOTP QR Code",className:"w-48 h-48 rounded-lg"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:e("settings.twoFa.manualEntry")}),r.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark-secondary rounded-lg px-3 py-2",children:[r.jsx("code",{className:"text-white text-xs font-mono flex-1 break-all",children:u?p.secret:"••••••••••••••••"}),r.jsx("button",{onClick:()=>m(!u),className:"text-bambu-gray hover:text-white",children:u?r.jsx(ab,{className:"w-4 h-4"}):r.jsx(Cl,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{navigator.clipboard.writeText(p.secret)},className:"text-bambu-gray hover:text-white",children:r.jsx(Ti,{className:"w-4 h-4"})})]})]}),r.jsx(je,{variant:"primary",className:"w-full",onClick:()=>s("confirm"),children:e("settings.twoFa.scannedContinue")})]}):i==="confirm"?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:e("settings.twoFa.enterCodeToConfirm")}),r.jsx(qN,{value:o,onChange:l,placeholder:"000000"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>s("qr"),className:"flex-1",children:e("common.back")}),r.jsx(je,{variant:"primary",className:"flex-1",disabled:o.length!==6||g.isPending,onClick:()=>g.mutate(o),children:g.isPending?e("common.saving"):e("settings.twoFa.activate")})]})]}):r.jsxs("div",{className:"space-y-4",children:[r.jsx("h3",{className:"text-white font-medium",children:e("settings.twoFa.backupCodesTitle")}),r.jsx(Hce,{codes:c,onDone:t})]})}function Iat(){const{t}=_t(),e=tn(),{showToast:n}=on(),{user:a}=dr(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,w]=y.useState(null),[b,x]=y.useState(null),[S,k]=y.useState(""),[C,P]=y.useState(!1),[T,A]=y.useState(""),[F,_]=y.useState(!1),{data:M,isLoading:H}=Xe({queryKey:["2fa-status"],queryFn:()=>ae.get2FAStatus()}),{data:I}=Xe({queryKey:["oidc-links"],queryFn:()=>ae.getOIDCLinks()}),z=lt({mutationFn:()=>ae.enableEmailOTP(),onSuccess:oe=>{x(oe.setup_token),n(oe.message,"success")},onError:oe=>{const Q=oe.message??"";Q.toLowerCase().includes("smtp")?n(t("settings.twoFa.smtpRequired"),"error"):n(Q,"error")}}),L=lt({mutationFn:()=>ae.confirmEnableEmailOTP(b,S),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),x(null),k(""),n(t("settings.twoFa.emailOtpEnabled"),"success")},onError:oe=>n(oe.message,"error")}),Z=lt({mutationFn:oe=>ae.disableEmailOTP(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),P(!1),A(""),n(t("settings.twoFa.emailOtpDisabled"),"success")},onError:oe=>n(oe.message,"error")}),ne=lt({mutationFn:oe=>ae.disableTOTP(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["2fa-status"]}),l(!1),m(""),n(t("settings.twoFa.totpDisabled"),"success")},onError:()=>n(t("settings.twoFa.invalidCode"),"error")}),Y=lt({mutationFn:oe=>ae.regenerateBackupCodes(oe),onSuccess:oe=>{e.invalidateQueries({queryKey:["2fa-status"]}),d(!1),f(""),w(oe.backup_codes)},onError:()=>n(t("settings.twoFa.invalidCode"),"error")}),ce=lt({mutationFn:oe=>ae.deleteOIDCLink(oe),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-links"]}),n(t("settings.twoFa.oidcUnlinked"),"success")},onError:oe=>n(oe.message,"error")});if(H)return r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(tr,{className:"w-6 h-6 animate-spin text-bambu-green"})});const ue=!!a?.email;return r.jsxs("div",{className:"space-y-6",children:[r.jsxs(At,{id:"card-2fa-totp",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${M?.totp_enabled?"bg-green-500/20":"bg-gray-500/20"}`,children:r.jsx(YF,{className:`w-5 h-5 ${M?.totp_enabled?"text-green-400":"text-gray-400"}`})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.totpTitle")}),r.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.twoFa.totpDesc")})]}),r.jsx("div",{className:"ml-auto",children:M?.totp_enabled?r.jsxs("span",{className:"flex items-center gap-1 text-green-400 text-sm font-medium",children:[r.jsx(Fw,{className:"w-4 h-4"})," ",t("common.enabled")]}):r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray text-sm",children:[r.jsx(QF,{className:"w-4 h-4"})," ",t("common.disabled")]})})]})}),r.jsx(Et,{children:i?r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("h4",{className:"text-white font-medium",children:t("settings.twoFa.setupAuthApp")}),r.jsx("button",{onClick:()=>{s(!1),e.removeQueries({queryKey:["totp-setup"]})},className:"text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx(Rat,{onDone:()=>{s(!1),e.removeQueries({queryKey:["totp-setup"]})}})]}):o?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.disableConfirmHint")}),r.jsx(qN,{value:u,onChange:m,placeholder:"000000 or XXXXXXXX",maxLength:8}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{l(!1),m("")},className:"flex-1",children:t("common.cancel")}),r.jsx(je,{variant:"danger",className:"flex-1",disabled:u.length<6||ne.isPending,onClick:()=>ne.mutate(u),children:ne.isPending?t("common.saving"):t("settings.twoFa.disableTotp")})]})]}):c?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.regenBackupHint")}),r.jsx(qN,{value:p,onChange:f,placeholder:"000000 or XXXXXXXX",maxLength:8}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{d(!1),f("")},className:"flex-1",children:t("common.cancel")}),r.jsx(je,{variant:"primary",className:"flex-1",disabled:p.length<6||Y.isPending,onClick:()=>Y.mutate(p),children:Y.isPending?t("common.saving"):t("settings.twoFa.regenBackup")})]})]}):g?r.jsxs("div",{className:"space-y-4",children:[r.jsx("h4",{className:"text-white font-medium",children:t("settings.twoFa.newBackupCodes")}),r.jsx(Hce,{codes:g,onDone:()=>w(null)})]}):r.jsx("div",{className:"space-y-3",children:M?.totp_enabled?r.jsxs("div",{className:"flex flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray-light",children:[r.jsx(bo,{className:"w-4 h-4"}),t("settings.twoFa.backupCodesRemaining",{count:M.backup_codes_remaining})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>d(!0),className:"flex items-center gap-2",children:[r.jsx(tr,{className:"w-4 h-4"}),t("settings.twoFa.regenBackup")]}),r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>l(!0),className:"flex items-center gap-2",children:[r.jsx(en,{className:"w-4 h-4"}),t("settings.twoFa.disableTotp")]})]}):r.jsxs(je,{variant:"primary",onClick:()=>s(!0),className:"flex items-center gap-2",children:[r.jsx(YF,{className:"w-4 h-4"}),t("settings.twoFa.setupTotp")]})})})]}),r.jsxs(At,{id:"card-2fa-emailotp",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${M?.email_otp_enabled?"bg-green-500/20":"bg-gray-500/20"}`,children:r.jsx($m,{className:`w-5 h-5 ${M?.email_otp_enabled?"text-green-400":"text-gray-400"}`})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.emailOtpTitle")}),r.jsx("p",{className:"text-bambu-gray text-sm",children:ue?t("settings.twoFa.emailOtpDesc",{email:a?.email}):t("settings.twoFa.emailOtpNoEmail")})]}),r.jsx("div",{className:"ml-auto",children:M?.email_otp_enabled?r.jsxs("span",{className:"flex items-center gap-1 text-green-400 text-sm font-medium",children:[r.jsx(Fw,{className:"w-4 h-4"})," ",t("common.enabled")]}):r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray text-sm",children:[r.jsx(QF,{className:"w-4 h-4"})," ",t("common.disabled")]})})]})}),r.jsx(Et,{children:ue?b?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.emailSetupEnterCode")}),r.jsx(qN,{value:S,onChange:k,placeholder:"000000"}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{x(null),k("")},className:"flex-1",children:t("common.cancel")}),r.jsx(je,{variant:"primary",className:"flex-1",disabled:S.length!==6||L.isPending,onClick:()=>L.mutate(),children:L.isPending?t("common.saving"):t("settings.twoFa.verifyAndEnable")})]})]}):C?r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray-light text-sm",children:t("settings.twoFa.emailDisablePasswordHint")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:F?"text":"password",value:T,onChange:oe=>A(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"}),r.jsx("button",{type:"button",onClick:()=>_(!F),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:F?r.jsx(ab,{className:"w-5 h-5"}):r.jsx(Cl,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{P(!1),A("")},className:"flex-1",children:t("common.cancel")}),r.jsx(je,{variant:"danger",className:"flex-1",disabled:!T||Z.isPending,onClick:()=>Z.mutate(T),children:Z.isPending?t("common.saving"):t("settings.twoFa.disableEmailOtp")})]})]}):r.jsx("div",{className:"flex gap-3",children:M?.email_otp_enabled?r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>P(!0),className:"flex items-center gap-2",children:[r.jsx(en,{className:"w-4 h-4"}),t("settings.twoFa.disableEmailOtp")]}):r.jsxs(je,{variant:"primary",disabled:!ue||z.isPending,onClick:()=>z.mutate(),className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-4 h-4"}),z.isPending?t("common.saving"):t("settings.twoFa.enableEmailOtp")]})}):r.jsx("p",{className:"text-amber-400 text-sm",children:t("settings.twoFa.addEmailFirst")})})]}),I&&I.length>0&&r.jsxs(At,{id:"card-2fa-linked",children:[r.jsxs(fn,{children:[r.jsx("h3",{className:"text-white font-semibold",children:t("settings.twoFa.linkedAccounts")}),r.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.twoFa.linkedAccountsDesc")})]}),r.jsx(Et,{children:r.jsx("div",{className:"space-y-3",children:I.map(oe=>r.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-bambu-dark-tertiary last:border-0",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm font-medium",children:oe.provider_name}),oe.provider_email&&r.jsx("p",{className:"text-bambu-gray text-xs",children:oe.provider_email})]}),r.jsx(je,{variant:"danger",size:"sm",onClick:()=>ce.mutate(oe.provider_id),disabled:ce.isPending,children:r.jsx(en,{className:"w-4 h-4"})})]},oe.id))})})]})]})}const Oat={name:"",issuer_url:"",client_id:"",client_secret:"",scopes:"openid email profile",is_enabled:!0,auto_create_users:!1,auto_link_existing_accounts:!1,email_claim:"email",require_email_verified:!0,icon_url:void 0,default_group_id:null};function bX({initial:t,isEdit:e=!1,groups:n=[],onSave:a,onCancel:i,isPending:s}){const{t:o}=_t(),[l,c]=y.useState(t),[d,u]=y.useState(!1),m=(S,k)=>c(C=>({...C,[S]:k})),p="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",f="block text-sm font-medium text-white mb-1",g=()=>{const S={...l};e&&!d&&delete S.client_secret,a(S)},w=l.auto_link_existing_accounts===!0,b=l.require_email_verified??!0;let x;return w?x=o("settings.oidc.form.requireEmailVerifiedAutoLink"):b?x=o("settings.oidc.form.requireEmailVerifiedDesc"):x=r.jsx("span",{className:"text-red-400",children:o("settings.oidc.form.requireEmailVerifiedWarning")}),r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsxs("label",{className:f,children:[o("settings.oidc.form.name")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{className:p,value:l.name,onChange:S=>m("name",S.target.value),placeholder:"Google"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:f,children:[o("settings.oidc.form.issuerUrl")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{className:p,value:l.issuer_url,onChange:S=>m("issuer_url",S.target.value),placeholder:"https://accounts.google.com"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:f,children:[o("settings.oidc.form.clientId")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{className:p,value:l.client_id,onChange:S=>m("client_id",S.target.value),placeholder:"your-client-id"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:f,children:[o("settings.oidc.form.clientSecret"),!e&&r.jsx("span",{className:"text-red-400",children:" *"}),e&&r.jsxs("span",{className:"text-bambu-gray text-xs ml-1",children:["(",o("settings.oidc.form.secretHint"),")"]})]}),r.jsx("input",{className:p,type:"password",value:d?l.client_secret:"",placeholder:e&&!d?"••••••••":o("settings.oidc.form.secretPlaceholder"),onChange:S=>{u(!0),m("client_secret",S.target.value)}})]}),r.jsxs("div",{children:[r.jsx("label",{className:f,children:o("settings.oidc.form.scopes")}),r.jsx("input",{className:p,value:l.scopes,onChange:S=>m("scopes",S.target.value),placeholder:"openid email profile"})]}),r.jsxs("div",{children:[r.jsx("label",{className:f,children:o("settings.oidc.form.iconUrl")}),r.jsx("input",{className:p,value:l.icon_url??"",onChange:S=>m("icon_url",S.target.value===""?null:S.target.value),placeholder:"https://..."})]})]}),r.jsxs("div",{className:"flex flex-wrap gap-6 pt-2",children:[r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx(En,{checked:l.is_enabled??!0,onChange:S=>m("is_enabled",S)}),r.jsx("span",{className:"text-white text-sm",children:o("settings.oidc.form.enabled")})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx(En,{checked:l.auto_create_users??!1,onChange:S=>m("auto_create_users",S)}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm",children:o("settings.oidc.form.autoCreate")}),r.jsx("p",{className:"text-bambu-gray text-xs",children:o("settings.oidc.form.autoCreateDesc")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer w-full",children:[r.jsx(En,{checked:l.auto_link_existing_accounts??!1,onChange:S=>m("auto_link_existing_accounts",S)}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm",children:o("settings.oidc.form.autoLink")}),r.jsx("p",{className:"text-bambu-gray text-xs",children:o("settings.oidc.form.autoLinkDesc")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer w-full",children:[r.jsx(En,{checked:b,onChange:S=>m("require_email_verified",S),disabled:w}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm",children:o("settings.oidc.form.requireEmailVerified")}),r.jsx("p",{className:"text-bambu-gray text-xs",children:x})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:f,children:o("settings.oidc.form.emailClaim")}),r.jsx("input",{className:p,value:l.email_claim,onChange:S=>m("email_claim",S.target.value||"email"),placeholder:o("settings.oidc.form.emailClaimPlaceholder")}),r.jsx("p",{className:"text-bambu-gray text-xs mt-1",children:o("settings.oidc.form.emailClaimDesc")}),w&&l.email_claim!=="email"&&r.jsx("p",{className:"text-yellow-400 text-xs mt-1",children:o("settings.oidc.form.emailClaimCustomClaimAutoLinkWarning")})]}),r.jsxs("div",{children:[r.jsx("label",{className:f,children:o("settings.oidc.form.defaultGroup")}),r.jsxs("select",{className:p,value:l.default_group_id??"",onChange:S=>m("default_group_id",S.target.value?Number(S.target.value):null),children:[r.jsx("option",{value:"",children:o("settings.oidc.form.defaultGroupViewersFallback")}),n.map(S=>r.jsx("option",{value:S.id,children:S.name},S.id))]}),r.jsx("p",{className:"text-bambu-gray text-xs mt-1",children:o("settings.oidc.form.defaultGroupDesc")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(je,{variant:"secondary",onClick:i,className:"flex-1",children:o("common.cancel")}),r.jsx(je,{variant:"primary",className:"flex-1",disabled:!l.name||!l.issuer_url||!l.client_id||!e&&!l.client_secret||e&&d&&!l.client_secret||s,onClick:g,children:o(s?"common.saving":"common.save")})]})]})}function zat({provider:t}){const[e,n]=y.useState(!1);return t.has_icon&&!e?r.jsx("img",{src:ae.oidcProviderIconUrl(t.id),alt:t.name,className:"w-8 h-8 rounded object-contain",onError:()=>n(!0)}):r.jsx("div",{className:"w-8 h-8 rounded-full bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(Js,{className:"w-4 h-4 text-bambu-gray"})})}function Uat(){const{t}=_t(),e=tn(),{showToast:n}=on(),[a,i]=y.useState(!1),[s,o]=y.useState(null),[l,c]=y.useState(null),{data:d,isLoading:u}=Xe({queryKey:["oidc-providers-all"],queryFn:()=>ae.getOIDCProvidersAll()}),{data:m=[]}=Xe({queryKey:["groups"],queryFn:()=>ae.getGroups()}),p=lt({mutationFn:S=>ae.createOIDCProvider(S),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),i(!1),n(t("settings.oidc.created"),"success")},onError:S=>n(S.message,"error")}),f=lt({mutationFn:({id:S,data:k})=>ae.updateOIDCProvider(S,k),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),o(null),n(t("settings.oidc.updated"),"success")},onError:S=>n(S.message,"error")}),g=lt({mutationFn:S=>ae.deleteOIDCProvider(S),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),c(null),n(t("settings.oidc.deleted"),"success")},onError:S=>n(S.message,"error")}),w=lt({mutationFn:S=>ae.refreshOIDCProviderIcon(S),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),e.invalidateQueries({queryKey:["oidc-providers"]}),n(t("settings.oidc.iconRefreshed"),"success")},onError:S=>n(S.message||t("settings.oidc.iconFetchFailed"),"error")}),b=lt({mutationFn:S=>ae.deleteOIDCProviderIcon(S),onSuccess:()=>{e.invalidateQueries({queryKey:["oidc-providers-all"]}),e.invalidateQueries({queryKey:["oidc-providers"]}),n(t("settings.oidc.iconRemoved"),"success")},onError:S=>n(S.message,"error")}),x=S=>f.mutate({id:S.id,data:{is_enabled:!S.is_enabled}});return u?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(tr,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsxs("div",{className:"space-y-6",children:[r.jsxs(At,{id:"card-oidc",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-white font-semibold",children:t("settings.oidc.title")}),r.jsx("p",{className:"text-bambu-gray text-sm",children:t("settings.oidc.desc")})]}),!a&&r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>i(!0),className:"flex items-center gap-2",children:[r.jsx(er,{className:"w-4 h-4"}),t("settings.oidc.addProvider")]})]})}),a&&r.jsx(Et,{children:r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[r.jsx("h4",{className:"text-white font-medium mb-4",children:t("settings.oidc.newProvider")}),r.jsx(bX,{initial:Oat,groups:m,onSave:S=>p.mutate(S),onCancel:()=>i(!1),isPending:p.isPending})]})})]}),d&&d.length===0&&!a&&r.jsx(At,{id:"card-oidc-empty",children:r.jsx(Et,{children:r.jsxs("div",{className:"text-center py-8 space-y-3",children:[r.jsx(Js,{className:"w-12 h-12 text-bambu-gray mx-auto"}),r.jsx("p",{className:"text-bambu-gray",children:t("settings.oidc.empty")}),r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>i(!0),className:"inline-flex items-center gap-2",children:[r.jsx(er,{className:"w-4 h-4"}),t("settings.oidc.addProvider")]})]})})}),d?.map(S=>r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(zat,{provider:S}),r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h4",{className:"text-white font-medium",children:S.name}),S.is_enabled?r.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:[r.jsx(Ar,{className:"w-3 h-3"})," ",t("common.enabled")]}):r.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:[r.jsx(Vt,{className:"w-3 h-3"})," ",t("common.disabled")]})]}),r.jsxs("div",{className:"flex items-center gap-1 text-bambu-gray text-xs mt-0.5",children:[r.jsx(zr,{className:"w-3 h-3"}),r.jsx("span",{children:S.issuer_url})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[S.icon_url&&r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>w.mutate(S.id),disabled:w.isPending,title:t("settings.oidc.refreshIcon"),"data-testid":`refresh-icon-${S.id}`,children:r.jsx(tr,{className:`w-4 h-4 ${w.isPending?"animate-spin":""}`})}),S.has_icon&&r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>b.mutate(S.id),disabled:b.isPending,title:t("settings.oidc.removeIcon"),"data-testid":`remove-icon-${S.id}`,children:r.jsx(rxe,{className:"w-4 h-4"})}),r.jsx(En,{checked:S.is_enabled,onChange:()=>x(S),disabled:f.isPending}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>o(s===S.id?null:S.id),children:r.jsx(uc,{className:"w-4 h-4"})}),r.jsx(je,{variant:"danger",size:"sm",onClick:()=>c(S),children:r.jsx(en,{className:"w-4 h-4"})})]})]})}),s===S.id&&r.jsx(Et,{children:r.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:r.jsx(bX,{isEdit:!0,groups:m,initial:{name:S.name,issuer_url:S.issuer_url,client_id:S.client_id,client_secret:"",scopes:S.scopes,is_enabled:S.is_enabled,auto_create_users:S.auto_create_users,auto_link_existing_accounts:S.auto_link_existing_accounts,email_claim:S.email_claim,require_email_verified:S.require_email_verified,icon_url:S.icon_url??void 0,default_group_id:S.default_group_id??null},onSave:k=>f.mutate({id:S.id,data:k}),onCancel:()=>o(null),isPending:f.isPending})})}),s!==S.id&&r.jsx(Et,{children:r.jsxs("dl",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-2 text-sm",children:[r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.clientId")}),r.jsx("dd",{className:"text-white font-mono truncate",children:S.client_id})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.scopes")}),r.jsx("dd",{className:"text-white",children:S.scopes})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.autoCreate")}),r.jsx("dd",{className:S.auto_create_users?"text-green-400":"text-bambu-gray",children:S.auto_create_users?t("common.yes"):t("common.no")})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.autoLink")}),r.jsx("dd",{className:S.auto_link_existing_accounts?"text-green-400":"text-bambu-gray",children:S.auto_link_existing_accounts?t("common.yes"):t("common.no")})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.emailClaim")}),r.jsx("dd",{className:"text-white font-mono",children:S.email_claim})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.requireEmailVerified")}),r.jsx("dd",{className:S.require_email_verified?"text-green-400":"text-red-400",children:S.require_email_verified?t("common.yes"):t("common.no")})]}),r.jsxs("div",{children:[r.jsx("dt",{className:"text-bambu-gray",children:t("settings.oidc.form.defaultGroup")}),r.jsx("dd",{className:"text-white",children:S.default_group_id?m.find(k=>k.id===S.default_group_id)?.name??t("settings.oidc.form.defaultGroupViewersFallback"):t("settings.oidc.form.defaultGroupViewersFallback")})]})]})})]},S.id)),l&&r.jsx(wn,{title:t("settings.oidc.deleteTitle"),message:t("settings.oidc.deleteMessage",{name:l.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:()=>g.mutate(l.id),onCancel:()=>c(null)})]})}const qce=new Map;function jn(t){qce.set(t.anchor,t)}function Bat(){return Array.from(qce.values())}jn({labelKey:"settings.encryption.title",labelFallback:"MFA Encryption Status",tab:"users",subTab:"security",keywords:"mfa encryption status security backup totp oidc fernet",anchor:"card-mfa-encryption"});function Hat(){const{t}=_t(),{data:e,isLoading:n,isError:a,refetch:i}=Xe({queryKey:["encryptionStatus"],queryFn:()=>ae.getEncryptionStatus(),refetchInterval:p=>{if(!p.state.error)return 3e4;const f=p.state.fetchFailureCount??0;return f<=3?Math.min(5e3*Math.max(1,f),3e4):!1}});if(n)return r.jsxs(At,{id:"card-mfa-encryption","data-testid":"encryption-status-card",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hl,{className:"text-bambu-gray",size:20}),r.jsx("h2",{className:"text-lg font-semibold",children:t("settings.encryption.title")})]})}),r.jsx(Et,{children:r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray","data-testid":"encryption-loading",children:[r.jsx(ft,{className:"animate-spin",size:16}),r.jsx("span",{children:t("common.loading")})]})})]});if(a||!e)return r.jsxs(At,{id:"card-mfa-encryption","data-testid":"encryption-status-card",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hl,{className:"text-bambu-gray",size:20}),r.jsx("h2",{className:"text-lg font-semibold",children:t("settings.encryption.title")})]})}),r.jsxs(Et,{children:[r.jsx("div",{className:"text-red-400","data-testid":"encryption-error",children:t("common.errorLoading")}),r.jsx("button",{type:"button",onClick:()=>i(),className:"mt-2 text-sm text-blue-400 underline hover:text-blue-300","data-testid":"encryption-retry-button",children:t("common.retry")})]})]});const s=e.legacy_plaintext_rows.oidc_providers+e.legacy_plaintext_rows.user_totp,o=e.encrypted_rows.oidc_providers+e.encrypted_rows.user_totp;let l,c,d,u;e.decryption_broken?(l="bg-red-500/20 border-red-500/50 text-red-400",c=r.jsx($r,{className:"text-red-400",size:20}),d=t("settings.encryption.decryptionBrokenTitle"),u=t("settings.encryption.decryptionBrokenError",{count:o})):e.key_source==="generated"?(l="bg-amber-500/10 border-amber-500/30 text-amber-400",c=r.jsx(Fw,{className:"text-amber-400",size:20}),d=t("settings.encryption.enabledGenerated"),u=t("settings.encryption.backupHint")):s>0?(l="bg-amber-500/10 border-amber-500/30 text-amber-400",c=r.jsx(Nn,{className:"text-amber-400",size:20}),d=e.key_source==="env"?t("settings.encryption.enabledFromEnv"):t("settings.encryption.enabledFromFile"),u=t("settings.encryption.legacyRowsWarning",{count:s})):e.key_configured?(l="bg-green-500/20 border-green-500/30 text-green-400",c=r.jsx(Fw,{className:"text-green-400",size:20}),d=e.key_source==="env"?t("settings.encryption.enabledFromEnv"):t("settings.encryption.enabledFromFile"),u=t("settings.encryption.allEncrypted")):(l="bg-gray-500/20 border-gray-500/30 text-gray-400",c=r.jsx(QF,{className:"text-gray-400",size:20}),d=t("settings.encryption.notConfigured"),u=t("settings.encryption.notConfiguredDesc"));const m=e.key_source==="generated"&&s>0;return r.jsxs(At,{id:"card-mfa-encryption","data-testid":"encryption-status-card",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2",children:[c,r.jsx("h2",{className:"text-lg font-semibold",children:t("settings.encryption.title")})]})}),r.jsxs(Et,{children:[r.jsxs("div",{className:`p-3 border rounded-lg ${l}`,"data-testid":"encryption-status",children:[r.jsx("p",{className:"font-medium mb-1",children:d}),r.jsx("p",{className:"text-sm",children:u})]}),m&&r.jsx("div",{className:"mt-2 p-3 border rounded-lg bg-amber-500/10 border-amber-500/30 text-amber-400","data-testid":"encryption-legacy-warning",children:r.jsx("p",{className:"text-sm",children:t("settings.encryption.legacyRowsWarning",{count:s})})}),e.migration_error_count>0&&r.jsx("div",{className:"mt-2 p-3 border rounded-lg bg-amber-500/10 border-amber-500/30 text-amber-400","data-testid":"encryption-migration-warning",children:r.jsx("p",{className:"text-sm",children:t("settings.encryption.migrationErrorWarning",{count:e.migration_error_count})})}),r.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-4 text-sm",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-bambu-gray",children:t("settings.encryption.encryptedRowsLabel")}),r.jsxs("p",{className:"font-medium",children:["OIDC: ",e.encrypted_rows.oidc_providers," · TOTP: ",e.encrypted_rows.user_totp]})]}),r.jsxs("div",{children:[r.jsx("p",{className:"text-bambu-gray",children:t("settings.encryption.legacyRowsLabel")}),r.jsxs("p",{className:"font-medium",children:["OIDC: ",e.legacy_plaintext_rows.oidc_providers," · TOTP: ",e.legacy_plaintext_rows.user_totp]})]})]})]})]})}const qat={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 $at(t,e){const n=e.replace("#/","").split("/");let a=t;for(const i of n)a=a[i];return a}function W0(t,e,n=0){if(n>5)return"...";if(e.$ref)return W0(t,$at(t,e.$ref),n+1);if(e.allOf){const a={};for(const i of e.allOf){const s=W0(t,i,n+1);typeof s=="object"&&s!==null&&Object.assign(a,s)}return a}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?[W0(t,e.items,n+1)]:[];case"object":if(e.properties){const a={};for(const[i,s]of Object.entries(e.properties))a[i]=W0(t,s,n+1);return a}return{};default:return null}}function Vat({path:t,method:e,spec:n,schema:a,apiKey:i}){const[s,o]=y.useState(!1),[l,c]=y.useState({}),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(!1),[w,b]=y.useState(!1);y.useEffect(()=>{if(s&&n.parameters){const F={};for(const _ of n.parameters)_.schema?.default!==void 0&&(F[_.name]=String(_.schema.default));c(_=>({...F,..._}))}},[s,n.parameters]),y.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!d){const F=n.requestBody.content["application/json"].schema,_=W0(a,F);u(JSON.stringify(_,null,2))}},[s,n.requestBody,a,d]);const S=(()=>{const F=[];for(const _ of n.parameters||[])if(_.in==="path"||_.required){const M=l[_.name];(M===void 0||M==="")&&F.push(_.name)}return F})(),k=async()=>{if(S.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}g(!0),p(null);try{let F=t;const _=new URLSearchParams;for(const oe of n.parameters||[]){const Q=l[oe.name];Q!==void 0&&Q!==""&&(oe.in==="path"?F=F.replace(`{${oe.name}}`,encodeURIComponent(Q)):oe.in==="query"&&_.append(oe.name,Q))}const M=_.toString(),H=`${F}${M?`?${M}`:""}`,I={"Content-Type":"application/json"};i&&(I["X-API-Key"]=i);const z={method:e.toUpperCase(),headers:I};["post","put","patch"].includes(e)&&d&&(z.body=d);const L=performance.now(),Z=await fetch(H,z),ne=Math.round(performance.now()-L),Y={};Z.headers.forEach((oe,Q)=>{Y[Q]=oe});let ce;Z.headers.get("content-type")?.includes("application/json")?ce=await Z.json():ce=await Z.text(),p({status:Z.status,statusText:Z.statusText,headers:Y,body:ce,duration:ne})}catch(F){p({status:0,statusText:"Network Error",headers:{},body:F instanceof Error?F.message:"Unknown error",duration:0})}finally{g(!1)}},C=async()=>{if(m){const F=typeof m.body=="string"?m.body:JSON.stringify(m.body,null,2);try{await navigator.clipboard.writeText(F),b(!0),setTimeout(()=>b(!1),2e3)}catch{const _=document.createElement("textarea");_.value=F,_.style.position="fixed",_.style.left="-999999px",document.body.appendChild(_),_.select(),document.execCommand("copy"),document.body.removeChild(_),b(!0),setTimeout(()=>b(!1),2e3)}}},P=(n.parameters||[]).filter(F=>F.in==="path"),T=(n.parameters||[]).filter(F=>F.in==="query"),A=["post","put","patch"].includes(e)&&n.requestBody;return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.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?r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):r.jsx(qa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${qat[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),r.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&r.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&r.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),P.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),r.jsx("div",{className:"space-y-2",children:P.map(F=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[F.name,F.required&&r.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),r.jsx("input",{type:"text",value:l[F.name]||"",onChange:_=>c(M=>({...M,[F.name]:_.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.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),r.jsx("div",{className:"space-y-2",children:T.map(F=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[F.name,F.required&&r.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),F.schema?.enum?r.jsxs("select",{value:l[F.name]||"",onChange:_=>c(M=>({...M,[F.name]:_.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:[r.jsx("option",{value:"",children:"-- Select --"}),F.schema.enum.map(_=>r.jsx("option",{value:_,children:_},_))]}):r.jsx("input",{type:"text",value:l[F.name]||"",onChange:_=>c(M=>({...M,[F.name]:_.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&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),r.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..."})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{onClick:k,disabled:f,children:[f?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(hs,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&r.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),m&&r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",r.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]}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[m.duration,"ms"]})]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:C,children:w?r.jsx(xr,{className:"w-3 h-3 text-green-400"}):r.jsx(Ti,{className:"w-3 h-3"})})]}),r.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 Gat({apiKey:t=""}){const[e,n]=y.useState(null),[a,i]=y.useState(!0),[s,o]=y.useState(null),[l,c]=y.useState(new Set),[d,u]=y.useState("");if(y.useEffect(()=>{async function b(){try{const x=await fetch("/openapi.json");if(!x.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await x.json();n(S)}catch(x){o(x instanceof Error?x.message:"Unknown error")}finally{i(!1)}}b()},[]),a)return r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return r.jsx(At,{children:r.jsx(Et,{className:"py-8",children:r.jsxs("div",{className:"text-center text-red-400",children:[r.jsx(Ha,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),r.jsx("p",{children:"Failed to load API schema"}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const m={};for(const[b,x]of Object.entries(e.paths))for(const[S,k]of Object.entries(x)){if(S==="parameters")continue;const C=k.tags||["Other"];for(const P of C)m[P]||(m[P]=[]),m[P].push({path:b,method:S,spec:k})}const p=Object.entries(m).map(([b,x])=>{if(!d)return{tag:b,endpoints:x};const S=x.filter(({path:k,method:C,spec:P})=>{const T=d.toLowerCase();return k.toLowerCase().includes(T)||C.toLowerCase().includes(T)||(P.summary?.toLowerCase()||"").includes(T)||(P.description?.toLowerCase()||"").includes(T)});return{tag:b,endpoints:S}}).filter(({endpoints:b})=>b.length>0).sort((b,x)=>b.tag.localeCompare(x.tag)),f=b=>{c(x=>{const S=new Set(x);return S.has(b)?S.delete(b):S.add(b),S})},g=()=>{c(new Set(p.map(b=>b.tag)))},w=()=>{c(new Set)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-4",children:[r.jsx("div",{className:"flex-1",children:r.jsx("input",{type:"text",value:d,onChange:b=>u(b.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"})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:g,children:"Expand All"}),r.jsx(je,{variant:"secondary",size:"sm",onClick:w,children:"Collapse All"}),r.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[r.jsx(zr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((b,x)=>b+x.endpoints.length,0)," endpoints in ",p.length," categories"]}),r.jsx("div",{className:"space-y-3",children:p.map(({tag:b,endpoints:x})=>r.jsxs(At,{children:[r.jsx("button",{onClick:()=>f(b),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:r.jsxs("div",{className:"flex items-center gap-2",children:[l.has(b)?r.jsx(Ln,{className:"w-5 h-5 text-bambu-gray"}):r.jsx(qa,{className:"w-5 h-5 text-bambu-gray"}),r.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:b.replace(/-/g," ")}),r.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:x.length})]})}),l.has(b)&&r.jsx(Et,{className:"pt-0 space-y-2",children:x.map(({path:S,method:k,spec:C})=>r.jsx(Vat,{path:S,method:k,spec:C,schema:e,apiKey:t},`${k}-${S}`))})]},b))})]})}const Wat=["general","plugs","notifications","queue","filament","network","apikeys","virtual-printer","spoolbuddy","failure-detection","users","backup"];jn({labelKey:"settings.general",tab:"general",keywords:"language date time format printer model printers cards",anchor:"card-general"});jn({labelKey:"settings.appearance",tab:"general",keywords:"theme dark light mode colors",anchor:"card-appearance"});jn({labelKey:"settings.archiveSettings",tab:"general",keywords:"archive auto save thumbnails captures",anchor:"card-archive"});jn({labelKey:"settings.camera",tab:"general",keywords:"camera external video stream",anchor:"card-camera"});jn({labelKey:"settings.costTracking",tab:"general",keywords:"currency filament cost energy kwh price",anchor:"card-cost"});jn({labelKey:"settings.fileManager",tab:"general",keywords:"file manager archive mode disk warning storage",anchor:"card-filemanager"});jn({labelKey:"settings.updates",tab:"general",keywords:"updates version firmware beta check",anchor:"card-updates"});jn({labelKey:"settings.dataManagement",tab:"general",keywords:"data reset clear logs notifications preferences",anchor:"card-data"});jn({labelKey:"settings.smartPlugs",tab:"plugs",keywords:"smart plug energy power automation tapo kasa tplink shelly",anchor:"card-plugs"});jn({labelKey:"settings.providers",tab:"notifications",keywords:"telegram discord email notification providers webhook",anchor:"card-providers"});jn({labelKey:"settings.messageTemplates",tab:"notifications",keywords:"message templates notification text edit",anchor:"card-templates"});jn({labelKey:"settings.defaultPrintOptions",labelFallback:"Default Print Options",tab:"queue",keywords:"print bed leveling flow calibration vibration first layer timelapse",anchor:"card-print-options"});jn({labelKey:"settings.staggeredStart",labelFallback:"Staggered Start",tab:"queue",keywords:"staggered batch delay start queue group",anchor:"card-staggered"});jn({labelKey:"settings.plateClear",labelFallback:"Plate-Clear Confirmation",tab:"queue",keywords:"plate clear confirm auto queue",anchor:"card-plate"});jn({labelKey:"settings.gcodeInjection",labelFallback:"G-code Injection",tab:"queue",keywords:"gcode injection start end autoprint farmloop swapmod autoclear printflow",anchor:"card-gcode"});jn({labelKey:"settings.slicerCard",labelFallback:"Slicer",tab:"queue",keywords:"slicer orcaslicer bambustudio orca bambu api sidecar url docker preferred",anchor:"card-slicer"});jn({labelKey:"settings.queueDrying",tab:"queue",keywords:"drying presets temperature time humidity ams",anchor:"card-drying"});jn({labelKey:"settings.filamentChecks",tab:"filament",keywords:"filament check warning runout remaining",anchor:"card-filamentchecks"});jn({labelKey:"settings.printModal",tab:"filament",keywords:"print modal custom mapping",anchor:"card-printmodal"});jn({labelKey:"settings.amsDisplayThresholds",tab:"filament",keywords:"ams humidity temperature threshold history retention",anchor:"card-amsthresholds"});jn({labelKey:"settings.externalUrl",tab:"network",keywords:"external url reverse proxy public notification link",anchor:"card-externalurl"});jn({labelKey:"settings.ftpRetry",tab:"network",keywords:"ftp retry upload retries backoff",anchor:"card-ftpretry"});jn({labelKey:"settings.homeAssistant",tab:"network",keywords:"home assistant ha hass mqtt integration",anchor:"card-ha"});jn({labelKey:"settings.mqttPublishing",tab:"network",keywords:"mqtt publish broker topic",anchor:"card-mqtt"});jn({labelKey:"settings.prometheusMetrics",tab:"network",keywords:"prometheus metrics grafana monitoring bearer token",anchor:"card-prometheus"});jn({labelKey:"settings.createNewApiKey",tab:"apikeys",keywords:"api key create permission scope",anchor:"card-createapi"});jn({labelKey:"settings.webhookEndpoints",tab:"apikeys",keywords:"webhook endpoint post http",anchor:"card-webhooks"});jn({labelKey:"settings.apiBrowser",tab:"apikeys",keywords:"api browser endpoint documentation test",anchor:"card-apibrowser"});jn({labelKey:"cameraTokens.title",tab:"apikeys",keywords:"camera token long-lived home assistant frigate kiosk stream",anchor:"card-camera-tokens"});jn({labelKey:"settings.tabs.virtualPrinter",tab:"virtual-printer",keywords:"virtual printer proxy archive slicer bambustudio orcaslicer ip bind",anchor:"card-vp"});jn({labelKey:"settings.tabs.spoolbuddy",tab:"spoolbuddy",keywords:"spoolbuddy device scale nfc rfid kiosk unregister",anchor:"card-spoolbuddy"});jn({labelKey:"settings.currentUser",tab:"users",subTab:"users",keywords:"current user profile password change",anchor:"card-currentuser"});jn({labelKey:"settings.users",tab:"users",subTab:"users",keywords:"users accounts list",anchor:"card-users"});jn({labelKey:"settings.groups",tab:"users",subTab:"users",keywords:"groups roles permissions administrators operators viewers",anchor:"card-groups"});jn({labelKey:"settings.email.smtpSettings",labelFallback:"SMTP Configuration",tab:"users",subTab:"email",keywords:"smtp email send server port password auth starttls ssl",anchor:"card-smtp"});jn({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"});jn({labelKey:"settings.tabs.backup",tab:"backup",keywords:"backup github restore download cloud sync profiles archives",anchor:"card-backup"});jn({labelKey:"externalLinks.title",labelFallback:"Sidebar Links",tab:"general",keywords:"sidebar links external custom navigation url add",anchor:"card-sidebar-links"});jn({labelKey:"settings.filamentTracking",tab:"filament",keywords:"spoolman filament tracking inventory sync remote integration",anchor:"card-spoolman"});jn({labelKey:"settings.catalog.spoolCatalog",labelFallback:"Spool Catalog",tab:"filament",keywords:"spool catalog entries brand material reset import export",anchor:"card-spool-catalog"});jn({labelKey:"settings.colorCatalog.title",labelFallback:"Color Catalog",tab:"filament",keywords:"color catalog hex swatch palette sync reset",anchor:"card-color-catalog"});jn({labelKey:"settings.tabs.failureDetection",labelFallback:"Failure Detection",tab:"failure-detection",keywords:"failure detection ai ml obico spaghetti detect monitoring",anchor:"card-fd-ml"});jn({labelKey:"failureDetection.perPrinterTitle",labelFallback:"Per-Printer Settings",tab:"failure-detection",keywords:"failure detection per printer enable per-printer sensitivity",anchor:"card-fd-perprinter"});jn({labelKey:"failureDetection.statusTitle",labelFallback:"Detection Status",tab:"failure-detection",keywords:"failure detection status running connection",anchor:"card-fd-status"});jn({labelKey:"failureDetection.historyTitle",labelFallback:"Detection History",tab:"failure-detection",keywords:"failure detection history log events",anchor:"card-fd-history"});jn({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"});jn({labelKey:"settings.email.testConnection",labelFallback:"Test SMTP Connection",tab:"users",subTab:"email",keywords:"email smtp test connection send check",anchor:"card-email-test"});jn({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"});jn({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"});jn({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"});jn({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"});jn({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"});jn({labelKey:"backup.githubBackup",labelFallback:"GitHub Backup",tab:"backup",keywords:"github backup cloud remote sync profiles token",anchor:"card-backup-github"});jn({labelKey:"backup.history",labelFallback:"Backup History",tab:"backup",keywords:"backup history log runs github commits",anchor:"card-backup-history"});jn({labelKey:"backup.localBackup",labelFallback:"Local Backup",tab:"backup",keywords:"local backup download zip manual export",anchor:"card-backup-local"});jn({labelKey:"backup.scheduledBackup",labelFallback:"Scheduled Backups",tab:"backup",keywords:"scheduled backup automatic hourly daily weekly retention local path",anchor:"card-backup-scheduled"});const Kat={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"},xX=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],yX=(t,e)=>Kat[t]||xX[e%xX.length];function Qat(){const t=tn(),e=ji(),[n,a]=nb(),{t:i,i18n:s}=_t(),{showToast:o}=on(),{authEnabled:l,user:c,isAdmin:d,refreshAuth:u,hasPermission:m}=dr(),{mode:p,darkStyle:f,darkBackground:g,darkAccent:w,lightStyle:b,lightBackground:x,lightAccent:S,setDarkStyle:k,setDarkBackground:C,setDarkAccent:P,setLightStyle:T,setLightBackground:A,setLightAccent:F}=ob(),[_,M]=y.useState(null),[H,I]=y.useState(!1),[z,L]=y.useState(null),[Z,ne]=y.useState(!1),[Y,ce]=y.useState(null),[ue,oe]=y.useState(null),[Q,le]=y.useState(""),[pe,he]=y.useState(""),[we,$]=y.useState(!1),[J,j]=y.useState(cJ()),E=n.get("tab"),B=E==="email",W=B?"users":E&&Wat.includes(E)?E:"general",[O,ie]=y.useState(W),[U,G]=y.useState(B?"email":"users"),K=ve=>{ie(ve),ve==="users"&&G("users"),ve==="general"?n.delete("tab"):n.set("tab",ve),a(n,{replace:!0})},[X,se]=y.useState(!1),[te,fe]=y.useState(""),[de,me]=y.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0,can_access_cloud:!1,can_update_energy_cost:!1}),[q,R]=y.useState(null),[re,be]=y.useState(null),[ye,_e]=y.useState(""),[xe,ge]=y.useState(!1),[Me,Be]=y.useState(!1),[Fe,Oe]=y.useState(null),[Re,We]=y.useState(!1),[ze,st]=y.useState(!1),[Ee,it]=y.useState(!1),[Ce,Ze]=y.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[Ie,ke]=y.useState(!1),[Ve,rt]=y.useState(!1),[Qe,Te]=y.useState(!1),[tt,ot]=y.useState("local"),[Tt,Ut]=y.useState(!1),[bt,Wt]=y.useState(null),[Zt,ln]=y.useState(null),[cn,ct]=y.useState(null),[kt,Nt]=y.useState(!1),[ut,Ct]=y.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Le,Ae]=y.useState(null),[Ge,Je]=y.useState(null),[De,mt]=y.useState(!1),[Ne,Ye]=y.useState({}),[nt,at]=y.useState({}),et=ve=>{j(ve),o0e(ve),o(i("settings.toast.settingsSaved"),"success")},vt=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},wt=!!_?.default_sidebar_order,Ue=async ve=>{try{if(ve){let zt;const mn=localStorage.getItem("sidebarOrder");try{zt=mn?JSON.parse(mn):wm.map(zn=>zn.id)}catch{zt=wm.map(zn=>zn.id)}(!Array.isArray(zt)||zt.length===0)&&(zt=wm.map(zn=>zn.id));const An=JSON.stringify({order:zt});await ae.updateSettings({default_sidebar_order:An}),M(zn=>zn&&{...zn,default_sidebar_order:An}),o(i("settings.sidebarDefaultSet"),"success")}else await ae.updateSettings({default_sidebar_order:""}),M(zt=>zt&&{...zt,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:He,isLoading:Dt}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:Rt,isLoading:qe,isFetching:Ke}=Xe({queryKey:["storage-usage"],queryFn:()=>ae.getStorageUsage(),enabled:O==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),Bt=async()=>{rt(!0);try{const ve=await ae.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],ve)}catch(ve){const zt=ve instanceof Error?ve.message:"Failed to refresh storage usage";o(zt,"error")}finally{rt(!1)}},{data:Qt,isLoading:dn}=Xe({queryKey:["smart-plugs"],queryFn:ae.getSmartPlugs}),{data:nn,isLoading:rn}=Xe({queryKey:["smart-plugs-energy",Qt?.map(ve=>ve.id)],queryFn:async()=>{if(!Qt||Qt.length===0)return null;const ve=await Promise.all(Qt.filter(qt=>qt.enabled).map(async qt=>{try{const Xt=await ae.getSmartPlugStatus(qt.id);return{plug:qt,status:Xt}}catch{return{plug:qt,status:null}}}));let zt=0,mn=0,An=0,zn=0,dt=0;for(const{plug:qt,status:Xt}of ve){const ht=qt.plug_type==="mqtt"&&Xt?.energy?.power!=null;(Xt?.reachable||ht)&&Xt?.energy&&(dt++,Xt.energy?.power!=null&&(zt+=Xt.energy.power),Xt.energy?.today!=null&&(mn+=Xt.energy.today),Xt.energy?.yesterday!=null&&(An+=Xt.energy.yesterday),Xt.energy?.total!=null&&(zn+=Xt.energy.total))}return{totalPower:zt,totalToday:mn,totalYesterday:An,totalLifetime:zn,reachableCount:dt,totalPlugs:Qt.filter(qt=>qt.enabled).length}},enabled:O==="plugs"&&!!Qt&&Qt.length>0,refetchInterval:O==="plugs"?1e4:!1}),{data:yn,isLoading:Mn}=Xe({queryKey:["notification-providers"],queryFn:ae.getNotificationProviders}),{data:or,isLoading:Dr}=Xe({queryKey:["api-keys"],queryFn:ae.getAPIKeys}),Gn=lt({mutationFn:ve=>ae.createAPIKey(ve),onSuccess:ve=>{R(ve.key||null),se(!1),fe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:ve=>{o(`Failed to create API key: ${ve.message}`,"error")}}),pi=lt({mutationFn:ve=>ae.deleteAPIKey(ve),onSuccess:(ve,zt)=>{t.setQueryData(["api-keys"],mn=>(mn??[]).filter(An=>An.id!==zt)),o(i("settings.toast.apiKeyDeleted"))},onError:ve=>{o(`Failed to delete API key: ${ve.message}`,"error")}}),{data:Un}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:vr,isLoading:ua}=Xe({queryKey:["notification-templates"],queryFn:ae.getNotificationTemplates}),{data:Fr}=Xe({queryKey:["virtual-printer-settings"],queryFn:XF.getSettings,refetchInterval:1e4}),ba=Fr?.status?.running??!1,{data:Mi}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.getDevices(),refetchInterval:15e3}),Ki=Mi?.length??0,wd=Mi?.some(ve=>ve.online)??!1,{data:Mc}=Xe({queryKey:["obico-status"],queryFn:ae.getObicoStatus,refetchInterval:15e3}),zs=!!(Mc?.is_running&&Mc?.enabled),{data:It}=Xe({queryKey:["ffmpeg-status"],queryFn:ae.checkFfmpeg}),{data:_n}=Xe({queryKey:["version"],queryFn:ae.getVersion}),ur=!l||m("library:purge"),{data:Kt}=Xe({queryKey:["library-trash-settings"],queryFn:()=>ae.getLibraryTrashSettings(),enabled:ur}),Ec=lt({mutationFn:ve=>ae.updateLibraryTrashSettings(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["library-trash-settings"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ve=>o(ve.message||i("libraryAutoPurge.saveFailed"),"error")}),Dc=ve=>{Kt&&Ec.mutate({retention_days:Kt.retention_days,auto_purge_enabled:Kt.auto_purge_enabled,auto_purge_days:Kt.auto_purge_days,auto_purge_include_never_printed:Kt.auto_purge_include_never_printed,...ve})},Fc=!l||m("archives:purge"),{data:Ei}=Xe({queryKey:["archive-purge-settings"],queryFn:()=>ae.getArchivePurgeSettings(),enabled:Fc}),cp=lt({mutationFn:ve=>ae.updateArchivePurgeSettings(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["archive-purge-settings"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ve=>o(ve.message||i("archiveAutoPurge.saveFailed"),"error")}),Tu=ve=>{Ei&&cp.mutate({enabled:Ei.enabled,days:Ei.days,purge_stats:Ei.purge_stats,...ve})},{data:kr,refetch:Sd,isRefetching:jo}=Xe({queryKey:["updateCheck"],queryFn:ae.checkForUpdates,enabled:He?.check_updates!==!1,staleTime:300*1e3}),{data:Us,refetch:Lc}=Xe({queryKey:["updateStatus"],queryFn:ae.getUpdateStatus,refetchInterval:ve=>{const zt=ve.state.data;return zt?.status==="downloading"||zt?.status==="installing"?1e3:!1}}),{data:Ma}=Xe({queryKey:["mqtt-status"],queryFn:ae.getMQTTStatus,refetchInterval:O==="network"?5e3:!1}),{data:dp}=Xe({queryKey:["github-backup-status"],queryFn:ae.getGitHubBackupStatus}),{data:up}=Xe({queryKey:["cloud-status"],queryFn:ae.getCloudStatus}),{data:hi={advanced_auth_enabled:!1,smtp_configured:!1}}=Xe({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),{data:nl}=Xe({queryKey:["ldapStatus"],queryFn:()=>ae.getLDAPStatus()}),{data:Rc}=Xe({queryKey:["twoFAStatus"],queryFn:()=>ae.get2FAStatus()}),{data:mp=[]}=Xe({queryKey:["oidcProvidersAll"],queryFn:()=>ae.getOIDCProvidersAll(),enabled:d}),{data:Ea=[],isLoading:Mo}=Xe({queryKey:["users"],queryFn:()=>ae.getUsers(),enabled:l&&m("users:read")}),{data:Eo=[],isLoading:Ic}=Xe({queryKey:["groups"],queryFn:()=>ae.getGroups(),enabled:l&&m("groups:read")}),_d=lt({mutationFn:ve=>ae.createUser(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:ve=>{o(ve.message,"error")}}),kd=lt({mutationFn:({id:ve,data:zt})=>ae.updateUser(ve,zt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ut(!1),Wt(null),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:ve=>{o(ve.message,"error")}}),lo=lt({mutationFn:({id:ve,deleteItems:zt})=>ae.deleteUser(ve,zt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),ln(null),ct(null)},onError:ve=>{o(ve.message,"error")}}),Bs=lt({mutationFn:ve=>ae.resetUserPassword({user_id:ve}),onSuccess:ve=>{o(ve.message,"success")},onError:ve=>{o(ve.message,"error")}}),Au=async ve=>{ln(ve),Nt(!0);try{const zt=await ae.getUserItemsCount(ve);ct(zt)}catch{ct({archives:0,queue_items:0,library_files:0})}finally{Nt(!1)}},hb=lt({mutationFn:ve=>ae.deleteGroup(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:ve=>{o(ve.message,"error")}}),fb=()=>{const ve=hi?.advanced_auth_enabled||!1;if(!ut.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(ve&&!ut.email){o("Email is required when advanced authentication is enabled","error");return}if(!ve){if(!ut.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(ut.password!==ut.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}const zt=uN(ut.password);if(zt){o(i({tooShort:"settings.toast.passwordTooShort",needsUppercase:"settings.toast.passwordNeedsUppercase",needsLowercase:"settings.toast.passwordNeedsLowercase",needsDigit:"settings.toast.passwordNeedsDigit",needsSpecial:"settings.toast.passwordNeedsSpecial"}[zt]),"error");return}}_d.mutate({username:ut.username,password:ve?void 0:ut.password,email:ut.email||void 0,role:ut.role,group_ids:ut.group_ids.length>0?ut.group_ids:void 0})},gb=ve=>{if(ut.password){if(ut.password!==ut.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}const mn=uN(ut.password);if(mn){o(i({tooShort:"settings.toast.passwordTooShort",needsUppercase:"settings.toast.passwordNeedsUppercase",needsLowercase:"settings.toast.passwordNeedsLowercase",needsDigit:"settings.toast.passwordNeedsDigit",needsSpecial:"settings.toast.passwordNeedsSpecial"}[mn]),"error");return}}const zt={username:ut.username||void 0,password:ut.password||void 0,email:ut.email||void 0,role:ut.role,group_ids:ut.group_ids};zt.password||delete zt.password,kd.mutate({id:ve,data:zt})},gv=ve=>{Wt(ve.id),Ct({username:ve.username,password:"",email:ve.email||"",confirmPassword:"",role:ve.role,group_ids:ve.groups?.map(zt=>zt.id)||[]}),Ut(!0)},Oc=ve=>{Ct(zt=>({...zt,group_ids:zt.group_ids.includes(ve)?zt.group_ids.filter(mn=>mn!==ve):[...zt.group_ids,ve]}))},pp=lt({mutationFn:ae.applyUpdate,onSuccess:ve=>{ve.is_ha_addon||ve.is_docker?o(ve.message,"error"):Lc()}}),[Ml,El]=y.useState(null),zc=lt({mutationFn:ae.testAllNotificationProviders,onSuccess:ve=>{El(ve),t.invalidateQueries({queryKey:["notification-providers"]}),ve.failed===0?o(`All ${ve.tested} providers tested successfully!`,"success"):o(`${ve.success}/${ve.tested} providers succeeded`,ve.failed>0?"error":"success")},onError:ve=>{o(`Failed to test providers: ${ve.message}`,"error")}}),Uc=lt({mutationFn:async ve=>{if(!Qt)return{success:0,failed:0};const zt=Qt.filter(An=>An.enabled),mn=await Promise.all(zt.map(async An=>{try{return await ae.controlSmartPlug(An.id,ve),{success:!0}}catch{return{success:!1}}}));return{success:mn.filter(An=>An.success).length,failed:mn.filter(An=>!An.success).length}},onSuccess:(ve,zt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ve.failed===0?o(`All ${ve.success} plugs turned ${zt}`,"success"):o(`${ve.success} plugs turned ${zt}, ${ve.failed} failed`,"error")},onError:ve=>{o(`Failed: ${ve.message}`,"error")}}),Qi=y.useRef(null),Nd=y.useRef(null),ju=y.useRef(!1),hp=y.useRef(!0);y.useEffect(()=>{if(He&&!_){const ve={...He,external_url:He.external_url||window.location.origin};M(ve),setTimeout(()=>{hp.current=!1},100)}},[He,_]);const Cd=lt({mutationFn:ae.updateSettings,onSuccess:ve=>{t.setQueryData(["settings"],ve),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:ve=>{o(`Failed to save: ${ve.message}`,"error")},onSettled:()=>{ju.current=!1}}),co=lt({mutationFn:({id:ve,data:zt})=>ae.updatePrinter(ve,zt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:ve=>{o(`Failed to update printer: ${ve.message}`,"error")}});y.useEffect(()=>{if(!(hp.current||!_||!He||l&&!m("settings:update")||!(He.auto_archive!==_.auto_archive||He.save_thumbnails!==_.save_thumbnails||He.capture_finish_photo!==_.capture_finish_photo||He.default_filament_cost!==_.default_filament_cost||He.currency!==_.currency||He.energy_cost_per_kwh!==_.energy_cost_per_kwh||He.energy_tracking_mode!==_.energy_tracking_mode||He.check_updates!==_.check_updates||(He.check_printer_firmware??!0)!==(_.check_printer_firmware??!0)||(He.include_beta_updates??!1)!==(_.include_beta_updates??!1)||He.notification_language!==_.notification_language||(He.bed_cooled_threshold??35)!==(_.bed_cooled_threshold??35)||He.ams_humidity_good!==_.ams_humidity_good||He.ams_humidity_fair!==_.ams_humidity_fair||He.ams_temp_good!==_.ams_temp_good||He.ams_temp_fair!==_.ams_temp_fair||He.ams_history_retention_days!==_.ams_history_retention_days||He.disable_filament_warnings!==_.disable_filament_warnings||He.prefer_lowest_filament!==_.prefer_lowest_filament||(He.queue_drying_enabled??!1)!==(_.queue_drying_enabled??!1)||(He.queue_drying_block??!1)!==(_.queue_drying_block??!1)||(He.ambient_drying_enabled??!1)!==(_.ambient_drying_enabled??!1)||(He.drying_presets??"")!==(_.drying_presets??"")||He.per_printer_mapping_expanded!==_.per_printer_mapping_expanded||He.date_format!==_.date_format||He.time_format!==_.time_format||He.default_printer_id!==_.default_printer_id||He.ftp_retry_enabled!==_.ftp_retry_enabled||He.ftp_retry_count!==_.ftp_retry_count||He.ftp_retry_delay!==_.ftp_retry_delay||He.ftp_timeout!==_.ftp_timeout||He.mqtt_enabled!==_.mqtt_enabled||He.mqtt_broker!==_.mqtt_broker||He.mqtt_port!==_.mqtt_port||He.mqtt_username!==_.mqtt_username||He.mqtt_password!==_.mqtt_password||He.mqtt_topic_prefix!==_.mqtt_topic_prefix||He.mqtt_use_tls!==_.mqtt_use_tls||He.external_url!==_.external_url||He.ha_enabled!==_.ha_enabled||He.ha_url!==_.ha_url||He.ha_token!==_.ha_token||(He.library_archive_mode??"ask")!==(_.library_archive_mode??"ask")||Number(He.library_disk_warning_gb??5)!==Number(_.library_disk_warning_gb??5)||(He.camera_view_mode??"window")!==(_.camera_view_mode??"window")||(He.preferred_slicer??"bambu_studio")!==(_.preferred_slicer??"bambu_studio")||(He.use_slicer_api??!1)!==(_.use_slicer_api??!1)||(He.orcaslicer_api_url??"")!==(_.orcaslicer_api_url??"")||(He.bambu_studio_api_url??"")!==(_.bambu_studio_api_url??"")||He.prometheus_enabled!==_.prometheus_enabled||He.prometheus_token!==_.prometheus_token||(He.user_notifications_enabled??!0)!==(_.user_notifications_enabled??!0)||(He.default_bed_levelling??!0)!==(_.default_bed_levelling??!0)||(He.default_flow_cali??!1)!==(_.default_flow_cali??!1)||(He.default_vibration_cali??!0)!==(_.default_vibration_cali??!0)||(He.default_layer_inspect??!1)!==(_.default_layer_inspect??!1)||(He.default_timelapse??!1)!==(_.default_timelapse??!1)||(He.stagger_group_size??2)!==(_.stagger_group_size??2)||(He.stagger_interval_minutes??5)!==(_.stagger_interval_minutes??5)||(He.require_plate_clear??!1)!==(_.require_plate_clear??!1)))&&!ju.current)return Qi.current&&clearTimeout(Qi.current),Qi.current=setTimeout(()=>{if(ju.current)return;ju.current=!0;const zt={auto_archive:_.auto_archive,save_thumbnails:_.save_thumbnails,capture_finish_photo:_.capture_finish_photo,default_filament_cost:_.default_filament_cost,currency:_.currency,energy_cost_per_kwh:_.energy_cost_per_kwh,energy_tracking_mode:_.energy_tracking_mode,check_updates:_.check_updates,check_printer_firmware:_.check_printer_firmware,include_beta_updates:_.include_beta_updates,notification_language:_.notification_language,bed_cooled_threshold:_.bed_cooled_threshold,ams_humidity_good:_.ams_humidity_good,ams_humidity_fair:_.ams_humidity_fair,ams_temp_good:_.ams_temp_good,ams_temp_fair:_.ams_temp_fair,ams_history_retention_days:_.ams_history_retention_days,disable_filament_warnings:_.disable_filament_warnings,prefer_lowest_filament:_.prefer_lowest_filament,queue_drying_enabled:_.queue_drying_enabled,queue_drying_block:_.queue_drying_block,ambient_drying_enabled:_.ambient_drying_enabled,drying_presets:_.drying_presets,per_printer_mapping_expanded:_.per_printer_mapping_expanded,date_format:_.date_format,time_format:_.time_format,default_printer_id:_.default_printer_id,ftp_retry_enabled:_.ftp_retry_enabled,ftp_retry_count:_.ftp_retry_count,ftp_retry_delay:_.ftp_retry_delay,ftp_timeout:_.ftp_timeout,mqtt_enabled:_.mqtt_enabled,mqtt_broker:_.mqtt_broker,mqtt_port:_.mqtt_port,mqtt_username:_.mqtt_username,mqtt_password:_.mqtt_password,mqtt_topic_prefix:_.mqtt_topic_prefix,mqtt_use_tls:_.mqtt_use_tls,external_url:_.external_url,ha_enabled:_.ha_enabled,ha_url:_.ha_url,ha_token:_.ha_token,library_archive_mode:_.library_archive_mode,library_disk_warning_gb:_.library_disk_warning_gb,camera_view_mode:_.camera_view_mode,preferred_slicer:_.preferred_slicer,use_slicer_api:_.use_slicer_api,orcaslicer_api_url:_.orcaslicer_api_url,bambu_studio_api_url:_.bambu_studio_api_url,prometheus_enabled:_.prometheus_enabled,prometheus_token:_.prometheus_token,user_notifications_enabled:_.user_notifications_enabled,default_bed_levelling:_.default_bed_levelling,default_flow_cali:_.default_flow_cali,default_vibration_cali:_.default_vibration_cali,default_layer_inspect:_.default_layer_inspect,default_timelapse:_.default_timelapse,stagger_group_size:_.stagger_group_size,stagger_interval_minutes:_.stagger_interval_minutes,require_plate_clear:_.require_plate_clear};Cd.mutate(zt)},500),()=>{Qi.current&&clearTimeout(Qi.current)}},[_,He,Cd,l,m,o,i]);const Cn=y.useCallback((ve,zt)=>{if(l&&!m("settings:update")){o(i("settings.toast.noPermissionUpdate"),"error");return}M(mn=>mn?{...mn,[ve]:zt}:null)},[l,m,o,i]),Pd=async(ve,zt,mn)=>{if(!zt){o(i("settings.toast.enterCameraUrl"),"error");return}at(An=>({...An,[ve]:!0})),Ye(An=>({...An,[ve]:null}));try{const An=await ae.testExternalCamera(ve,zt,mn);Ye(zn=>({...zn,[ve]:An})),An.success?o(i("settings.toast.cameraConnected",{resolution:An.resolution||""}),"success"):o(An.error||i("settings.toast.connectionFailed"),"error")}catch(An){const zn=An instanceof Error?An.message:i("settings.toast.testFailed");Ye(dt=>({...dt,[ve]:{success:!1,error:zn}})),o(zn,"error")}finally{at(An=>({...An,[ve]:!1}))}},[Td,Ad]=y.useState({}),ff=y.useRef({}),bb=y.useRef(new Set),[Dl,gf]=y.useState({}),fp=y.useRef({}),xb=y.useRef(new Set);y.useEffect(()=>{if(Un){const ve={},zt={};Un.forEach(mn=>{mn.external_camera_url&&!bb.current.has(mn.id)&&(ve[mn.id]=mn.external_camera_url,bb.current.add(mn.id)),mn.external_camera_snapshot_url&&!xb.current.has(mn.id)&&(zt[mn.id]=mn.external_camera_snapshot_url,xb.current.add(mn.id))}),Object.keys(ve).length>0&&Ad(mn=>({...mn,...ve})),Object.keys(zt).length>0&&gf(mn=>({...mn,...zt}))}},[Un]);const bv=(ve,zt)=>{Ad(mn=>({...mn,[ve]:zt})),ff.current[ve]&&clearTimeout(ff.current[ve]),ff.current[ve]=setTimeout(()=>{co.mutate({id:ve,data:{external_camera_url:zt||null}})},800)},Bc=(ve,zt)=>{gf(mn=>({...mn,[ve]:zt})),fp.current[ve]&&clearTimeout(fp.current[ve]),fp.current[ve]=setTimeout(()=>{co.mutate({id:ve,data:{external_camera_snapshot_url:zt||null}})},800)},ys=(ve,zt)=>{const mn={};zt.type!==void 0&&(mn.external_camera_type=zt.type||null),zt.enabled!==void 0&&(mn.external_camera_enabled=zt.enabled),zt.rotation!==void 0&&(mn.camera_rotation=zt.rotation),co.mutate({id:ve,data:mn})};if(Dt||!_)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});const Yi=Bat().map(ve=>({...ve,label:i(ve.labelKey,ve.labelFallback??ve.labelKey)})),Fl=pe.trim().toLowerCase(),bf=Fl?Yi.filter(ve=>ve.label.toLowerCase().includes(Fl)||ve.keywords.toLowerCase().includes(Fl)).slice(0,8):[],yb=ve=>{K(ve.tab),ve.subTab&&G(ve.subTab),he(""),setTimeout(()=>{const zt=document.getElementById(ve.anchor);zt&&(zt.scrollIntoView({behavior:"smooth",block:"start"}),zt.classList.add("ring-2","ring-bambu-green"),setTimeout(()=>zt.classList.remove("ring-2","ring-bambu-green"),1500))},50)};return r.jsx(Ove,{density:"dense",children:r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(xy,{className:"w-7 h-7 text-bambu-green"}),i("settings.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i("settings.configureBambuddy")})]}),r.jsxs("div",{className:"relative sm:w-72",children:[r.jsx(yr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),r.jsx("input",{type:"text",value:pe,onChange:ve=>he(ve.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"}),pe&&r.jsx("button",{onClick:()=>he(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear",children:r.jsx(Vt,{className:"w-3.5 h-3.5"})}),bf.length>0&&r.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:bf.map(ve=>r.jsxs("button",{onClick:()=>yb(ve),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:[r.jsx("p",{className:"text-sm text-white",children:ve.label}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[i(`settings.tabs.${ve.tab==="virtual-printer"?"virtualPrinter":ve.tab==="failure-detection"?"failureDetection":ve.tab}`),ve.subTab?` › ${i(`settings.tabs.${ve.subTab}`,ve.subTab)}`:""]})]},ve.anchor))}),Fl&&bf.length===0&&r.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:r.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noSearchResults","No matching settings.")})})]})]}),r.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[r.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:[r.jsxs("button",{onClick:()=>K("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 ${O==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(xy,{className:"w-4 h-4"}),i("settings.tabs.general")]}),r.jsxs("button",{onClick:()=>K("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 ${O==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(hc,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Qt&&Qt.length>0&&r.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Qt.length})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(Ch,{className:"w-4 h-4"}),i("settings.tabs.notifications"),yn&&yn.length>0&&r.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:yn.length})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="queue"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(Ew,{className:"w-4 h-4"}),i("settings.tabs.queue","Workflow")]}),r.jsxs("button",{onClick:()=>K("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 ${O==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(Wge,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),r.jsxs("button",{onClick:()=>K("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 ${O==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(Mh,{className:"w-4 h-4"}),i("settings.tabs.network"),r.jsx("span",{className:`w-2 h-2 rounded-full ${Ma?.enabled?"bg-green-400":"bg-gray-500"}`})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(bo,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),or&&or.length>0&&r.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:or.length})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(hr,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),r.jsx("span",{className:`w-2 h-2 rounded-full ${ba?"bg-green-400":"bg-gray-500"}`})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="spoolbuddy"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(qZ,{className:"w-4 h-4"}),i("settings.tabs.spoolbuddy"),Ki>0&&r.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ki}),r.jsx("span",{className:`w-2 h-2 rounded-full ${wd?"bg-green-400":"bg-gray-500"}`})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="failure-detection"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx($Z,{className:"w-4 h-4"}),i("settings.tabs.failureDetection"),r.jsx("span",{className:`w-2 h-2 rounded-full ${zs?"bg-green-400":"bg-gray-500"}`})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(bm,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&r.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),r.jsxs("button",{onClick:()=>K("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 ${O==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(dc,{className:"w-4 h-4"}),i("settings.tabs.backup"),r.jsx("span",{className:`w-2 h-2 rounded-full ${up?.is_authenticated&&dp?.configured&&dp?.enabled||He?.local_backup_enabled?"bg-green-400":"bg-gray-500"}`})]})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[O==="general"&&r.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[r.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[r.jsxs(At,{id:"card-general",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Js,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),r.jsxs("div",{className:"relative",children:[r.jsx("select",{value:s.language,onChange:ve=>{const zt=ve.target.value;if(l&&!m("settings:update")){o(i("settings.toast.noPermissionUpdate"),"error");return}s.changeLanguage(zt),Cd.mutate({language:zt})},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:Q8.map(ve=>r.jsxs("option",{value:ve.code,children:[ve.nativeName," (",ve.name,")"]},ve.code))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),r.jsxs("div",{className:"relative",children:[r.jsx("select",{value:J,onChange:ve=>et(ve.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:wm.map(ve=>r.jsx("option",{value:ve.to,children:i(ve.labelKey)},ve.id))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.dateFormat")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:_.date_format||"system",onChange:ve=>Cn("date_format",ve.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:[r.jsx("option",{value:"system",children:i("settings.systemDefault")}),r.jsx("option",{value:"us",children:i("settings.dateFormatUs")}),r.jsx("option",{value:"eu",children:i("settings.dateFormatEu")}),r.jsx("option",{value:"iso",children:i("settings.dateFormatIso")})]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.timeFormat")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:_.time_format||"system",onChange:ve=>Cn("time_format",ve.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:[r.jsx("option",{value:"system",children:i("settings.systemDefault")}),r.jsx("option",{value:"12h",children:i("settings.timeFormat12")}),r.jsx("option",{value:"24h",children:i("settings.timeFormat24")})]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultPrinter")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:_.default_printer_id??"",onChange:ve=>Cn("default_printer_id",ve.target.value?Number(ve.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:[r.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Un?.map(ve=>r.jsx("option",{value:ve.id,children:ve.name},ve.id))]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultPrinterDescription")})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[i("settings.sidebarOrderDescription"),l&&m("settings:update")&&` ${i("settings.sidebarOrderSetDefaultHint")}`]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:vt,children:[r.jsx(fs,{className:"w-4 h-4"}),i("settings.reset")]}),l&&m("settings:update")&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:i("settings.setDefault")}),r.jsx(En,{checked:wt,onChange:Ue,disabled:Dt})]})]})]})]})]}),r.jsxs(At,{id:"card-appearance",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(ES,{className:"w-5 h-5"}),i("settings.appearance")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.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:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.darkMode"),p==="dark"&&r.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),r.jsxs("select",{value:g,onChange:ve=>{C(ve.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:[r.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),r.jsx("option",{value:"warm",children:i("settings.bgWarm")}),r.jsx("option",{value:"cool",children:i("settings.bgCool")}),r.jsx("option",{value:"oled",children:i("settings.bgOled")}),r.jsx("option",{value:"slate",children:i("settings.bgSlate")}),r.jsx("option",{value:"forest",children:i("settings.bgForest")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),r.jsxs("select",{value:w,onChange:ve=>{P(ve.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:[r.jsx("option",{value:"green",children:i("settings.accentGreen")}),r.jsx("option",{value:"teal",children:i("settings.accentTeal")}),r.jsx("option",{value:"blue",children:i("settings.accentBlue")}),r.jsx("option",{value:"orange",children:i("settings.accentOrange")}),r.jsx("option",{value:"purple",children:i("settings.accentPurple")}),r.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),r.jsxs("select",{value:f,onChange:ve=>{k(ve.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:[r.jsx("option",{value:"classic",children:i("settings.styleClassic")}),r.jsx("option",{value:"glow",children:i("settings.styleGlow")}),r.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),r.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:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i("settings.lightMode"),p==="light"&&r.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.active")})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.background")}),r.jsxs("select",{value:x,onChange:ve=>{A(ve.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:[r.jsx("option",{value:"neutral",children:i("settings.bgNeutral")}),r.jsx("option",{value:"warm",children:i("settings.bgWarm")}),r.jsx("option",{value:"cool",children:i("settings.bgCool")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.accent")}),r.jsxs("select",{value:S,onChange:ve=>{F(ve.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:[r.jsx("option",{value:"green",children:i("settings.accentGreen")}),r.jsx("option",{value:"teal",children:i("settings.accentTeal")}),r.jsx("option",{value:"blue",children:i("settings.accentBlue")}),r.jsx("option",{value:"orange",children:i("settings.accentOrange")}),r.jsx("option",{value:"purple",children:i("settings.accentPurple")}),r.jsx("option",{value:"red",children:i("settings.accentRed")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.style")}),r.jsxs("select",{value:b,onChange:ve=>{T(ve.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:[r.jsx("option",{value:"classic",children:i("settings.styleClassic")}),r.jsx("option",{value:"glow",children:i("settings.styleGlow")}),r.jsx("option",{value:"vibrant",children:i("settings.styleVibrant")})]})]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.themeToggleHint")})]})]}),r.jsxs(At,{id:"card-archive",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.autoArchivePrints")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoArchiveDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.auto_archive,onChange:ve=>Cn("auto_archive",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.saveThumbnailsDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.save_thumbnails,onChange:ve=>Cn("save_thumbnails",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.captureFinishPhotoDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.capture_finish_photo,onChange:ve=>Cn("capture_finish_photo",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),_.capture_finish_photo&&It&&!It.installed&&r.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"text-sm",children:[r.jsx("p",{className:"text-yellow-500 font-medium",children:i("settings.ffmpegNotInstalled")}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i("settings.ffmpegRequired")})]})]}),Fc&&Ei&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3 mt-3 space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("archiveAutoPurge.enableLabel")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("archiveAutoPurge.enableDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Ei.enabled,onChange:ve=>Tu({enabled:ve.target.checked}),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("archiveAutoPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:7,max:3650,disabled:!Ei.enabled,value:Ei.days,onChange:ve=>Tu({days:Math.max(7,Math.min(3650,parseInt(ve.target.value||"0",10)||0))}),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 disabled:opacity-50"}),r.jsx("span",{className:"text-bambu-gray",children:i("archiveAutoPurge.days")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("archiveAutoPurge.ageDescription")})]}),r.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",disabled:!Ei.enabled,checked:Ei.purge_stats,onChange:ve=>Tu({purge_stats:ve.target.checked}),className:"mt-0.5 shrink-0 disabled:opacity-50"}),r.jsxs("span",{className:"text-sm",children:[r.jsx("span",{className:"text-white block",children:i("archiveAutoPurge.purgeStatsLabel")}),r.jsx("span",{className:"text-xs text-bambu-gray block mt-0.5",children:i("archiveAutoPurge.purgeStatsDescription")})]})]})]})]})]})]}),r.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-md",children:[r.jsxs(At,{id:"card-camera",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(oC,{className:"w-5 h-5 text-bambu-green"}),i("settings.camera")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.cameraViewMode")}),r.jsxs("select",{value:_.camera_view_mode??"window",onChange:ve=>Cn("camera_view_mode",ve.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:[r.jsx("option",{value:"window",children:i("settings.newWindow")}),r.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:_.camera_view_mode==="embedded"?i("settings.cameraOverlayDescription"):i("settings.cameraWindowDescription")})]}),r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:i("settings.externalCamerasDescription")}),Un&&Un.length>0?r.jsx("div",{className:"space-y-3",children:Un.map(ve=>r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-white font-medium text-sm",children:ve.name}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:ve.external_camera_enabled,onChange:zt=>ys(ve.id,{enabled:zt.target.checked}),className:"sr-only peer"}),r.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"})]})]}),ve.external_camera_enabled&&r.jsxs("div",{className:"space-y-2 mt-2",children:[r.jsx("input",{type:"text",placeholder:ve.external_camera_type==="usb"?i("settings.cameraPlaceholderUsb"):i("settings.cameraPlaceholderUrl"),value:Td[ve.id]??ve.external_camera_url??"",onChange:zt=>bv(ve.id,zt.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"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:ve.external_camera_type||"mjpeg",onChange:zt=>ys(ve.id,{type:zt.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:[r.jsx("option",{value:"mjpeg",children:i("settings.cameraTypeMjpeg")}),r.jsx("option",{value:"rtsp",children:i("settings.cameraTypeRtsp")}),r.jsx("option",{value:"snapshot",children:i("settings.cameraTypeSnapshot")}),r.jsx("option",{value:"usb",children:i("settings.cameraTypeUsb")})]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>Pd(ve.id,Td[ve.id]??ve.external_camera_url??"",ve.external_camera_type||"mjpeg"),disabled:nt[ve.id]||!(Td[ve.id]??ve.external_camera_url),children:nt[ve.id]?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):i("settings.test")})]}),Ne[ve.id]&&r.jsx("div",{className:`text-xs flex items-center gap-1 ${Ne[ve.id]?.success?"text-green-500":"text-red-500"}`,children:Ne[ve.id]?.success?r.jsxs(r.Fragment,{children:[r.jsx(xr,{className:"w-3 h-3"}),i("settings.connected"),Ne[ve.id]?.resolution&&` (${Ne[ve.id]?.resolution})`]}):r.jsxs(r.Fragment,{children:[r.jsx($r,{className:"w-3 h-3"}),Ne[ve.id]?.error||i("settings.toast.connectionFailed")]})}),(ve.external_camera_type==="mjpeg"||ve.external_camera_type==="rtsp"||ve.external_camera_type==="usb")&&r.jsxs("div",{className:"space-y-1",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:i("settings.cameraSnapshotUrl","Snapshot URL (optional)")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",placeholder:i("settings.cameraSnapshotUrlPlaceholder","http://192.168.1.61:1984/api/frame.jpeg?src=printer"),value:Dl[ve.id]??ve.external_camera_snapshot_url??"",onChange:zt=>Bc(ve.id,zt.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"}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>Pd(ve.id,Dl[ve.id]??ve.external_camera_snapshot_url??"","snapshot"),disabled:nt[ve.id]||!(Dl[ve.id]??ve.external_camera_snapshot_url),children:nt[ve.id]?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):i("settings.test")})]}),r.jsx("p",{className:"text-xs text-bambu-gray opacity-75",children:i("settings.cameraSnapshotUrlHelp","Single-frame URL used for notification thumbnails, finish photos, timelapse and plate detection. Leave blank to capture from the live stream above. Useful for go2rtc (/api/frame.jpeg) and IP cameras with a dedicated snapshot endpoint.")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:i("settings.cameraRotation")}),r.jsxs("select",{value:ve.camera_rotation||0,onChange:zt=>ys(ve.id,{rotation:parseInt(zt.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:[r.jsx("option",{value:0,children:"0°"}),r.jsx("option",{value:90,children:"90°"}),r.jsx("option",{value:180,children:"180°"}),r.jsx("option",{value:270,children:"270°"})]})]})]})]},ve.id))}):r.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),r.jsxs(At,{id:"card-cost",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.currency")}),r.jsx("select",{value:_.currency,onChange:ve=>Cn("currency",ve.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:z7e.map(ve=>r.jsx("option",{value:ve.code,children:ve.label},ve.code))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultFilamentCost")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:Ho(_.currency)}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:_.default_filament_cost,onChange:ve=>Cn("default_filament_cost",parseFloat(ve.target.value)||0),style:{paddingLeft:`${Math.max(2,Ho(_.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"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.electricityCost")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:Ho(_.currency)}),r.jsx("input",{type:"number",step:"0.001",min:"0",value:_.energy_cost_per_kwh,onChange:ve=>Cn("energy_cost_per_kwh",parseFloat(ve.target.value)||0),style:{paddingLeft:`${Math.max(2,Ho(_.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"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.energyDisplayMode")}),r.jsxs("select",{value:_.energy_tracking_mode||"total",onChange:ve=>Cn("energy_tracking_mode",ve.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:[r.jsx("option",{value:"print",children:i("settings.printsOnly")}),r.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:_.energy_tracking_mode==="print"?i("settings.energyModePrintDescription"):i("settings.energyModeTotalDescription")})]})]})]}),r.jsxs(At,{id:"card-filemanager",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Rs,{className:"w-5 h-5 text-bambu-green"}),i("settings.fileManager")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.createArchiveEntry")}),r.jsxs("select",{value:_.library_archive_mode??"ask",onChange:ve=>Cn("library_archive_mode",ve.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:[r.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),r.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),r.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.createArchiveEntryDescription")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.lowDiskSpaceWarning")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:_.library_disk_warning_gb??5,onChange:ve=>Cn("library_disk_warning_gb",parseFloat(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.lowDiskSpaceDescription")})]}),ur&&Kt&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3 mt-3 space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("libraryAutoPurge.enableLabel")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("libraryAutoPurge.enableDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Kt.auto_purge_enabled,onChange:ve=>Dc({auto_purge_enabled:ve.target.checked}),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("libraryAutoPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:7,max:3650,disabled:!Kt.auto_purge_enabled,value:Kt.auto_purge_days,onChange:ve=>Dc({auto_purge_days:Math.max(7,Math.min(3650,parseInt(ve.target.value||"0",10)||0))}),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 disabled:opacity-50"}),r.jsx("span",{className:"text-bambu-gray",children:i("libraryAutoPurge.days")})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("libraryAutoPurge.ageDescription")})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-white cursor-pointer",children:[r.jsx("input",{type:"checkbox",disabled:!Kt.auto_purge_enabled,checked:Kt.auto_purge_include_never_printed,onChange:ve=>Dc({auto_purge_include_never_printed:ve.target.checked}),className:"rounded border-gray-300 disabled:opacity-50"}),i("libraryAutoPurge.includeNeverPrinted")]})]})]})]})]}),r.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-sm",children:[r.jsx(vat,{}),r.jsxs(At,{id:"card-updates",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.updates")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider",children:i("settings.printerFirmware")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.checkFirmwareDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.check_printer_firmware??!0,onChange:ve=>Cn("check_printer_firmware",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wider mb-4",children:i("settings.bambuddySoftware")})}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoCheckDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.check_updates,onChange:ve=>Cn("check_updates",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:`flex items-center justify-between ${_.check_updates?"":"opacity-50"}`,children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.includeBetaUpdates")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.includeBetaUpdatesDesc")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.include_beta_updates??!1,onChange:ve=>Cn("include_beta_updates",ve.target.checked),disabled:!_.check_updates,className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",_n?.version||"..."]})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Sd(),disabled:jo,children:[jo?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),i("settings.checkNow")]})]}),kr?.update_available?r.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{children:[r.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",kr.latest_version]}),kr.release_name&&kr.release_name!==kr.latest_version&&r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:kr.release_name})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[kr.release_notes&&r.jsx("button",{onClick:()=>We(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:i("settings.releaseNotes")}),kr.release_url&&r.jsx("a",{href:kr.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:r.jsx(zr,{className:"w-4 h-4"})})]})]}),Us?.status==="downloading"||Us?.status==="installing"?r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:Us.message})]}),r.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Us.progress}%`}})})]}):Us?.status==="complete"?r.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:Us.message}):Us?.status==="error"?r.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:Us.error||Us.message}):kr?.is_ha_addon?r.jsx("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.updateViaHomeAssistant")})}):kr?.is_docker?r.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.updateViaDocker")}),r.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"})]}):r.jsxs(je,{className:"mt-3",onClick:()=>pp.mutate(),disabled:pp.isPending,children:[pp.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Zr,{className:"w-4 h-4"}),i("settings.installUpdate")]})]}):kr?.error?r.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:kr.error})}):kr&&!kr.update_available?r.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:i("settings.latestVersionRunning")}):null]})]})]}),r.jsxs(At,{id:"card-data",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>ge(!0),children:[r.jsx(en,{className:"w-4 h-4"}),i("common.clear")]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Be(!0),children:[r.jsx(en,{className:"w-4 h-4"}),i("settings.reset")]})]}),r.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.storageUsage","Storage Usage")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageDescription","Breakdown of data usage by category")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:Bt,disabled:Ke||Ve,children:[r.jsx(tr,{className:`w-4 h-4 ${Ke||Ve?"animate-spin":""}`}),i("common.refresh","Refresh")]})]}),r.jsx("div",{className:"mt-3",children:qe?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("common.loading","Loading")]}):Rt?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:Rt.categories.filter(ve=>ve.bytes>0).map((ve,zt)=>r.jsx("div",{className:`${yX(ve.key,zt)} h-full`,style:{width:`${ve.percent_of_total}%`},title:`${ve.label}: ${ve.formatted}`},ve.key))}),r.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:Rt.categories.filter(ve=>ve.bytes>0).map((ve,zt)=>r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:`w-3 h-3 rounded-full ${yX(ve.key,zt)}`}),r.jsx("span",{className:"text-bambu-gray",children:ve.label}),r.jsx("span",{className:"text-white",children:ve.formatted}),r.jsxs("span",{className:"text-bambu-gray",children:["(",ve.percent_of_total.toFixed(1),"%)"]})]},ve.key))}),r.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[i("settings.storageUsageTotal","Total"),": ",r.jsx("span",{className:"text-white",children:Rt.total_formatted}),Rt.scan_errors>0&&r.jsxs("span",{className:"ml-2 text-amber-400",children:[i("settings.storageUsageErrors","Scan errors"),": ",Rt.scan_errors]})]}),Rt.other_breakdown?.length>0&&r.jsxs("div",{className:"mt-4",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("settings.storageUsageOtherBreakdown","Other breakdown")}),r.jsx("div",{className:"space-y-2",children:Rt.other_breakdown.map(ve=>r.jsxs("div",{className:"flex items-center justify-between text-xs",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-white",children:ve.label}),r.jsx("span",{className:`px-2 py-0.5 rounded-full border ${ve.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:ve.kind==="system"?i("settings.storageUsageSystem","System"):i("settings.storageUsageData","Data")})]}),r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[r.jsx("span",{className:"text-white",children:ve.formatted}),r.jsxs("span",{children:["(",ve.percent_of_total.toFixed(1),"%)"]})]})]},`${ve.bucket}-${ve.kind}`))})]})]}):r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.backupRestore")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.backupRestoreDescription")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>K("backup"),children:[r.jsx(dc,{className:"w-4 h-4"}),i("settings.goToBackup")]})]})]})]})]})]}),O==="network"&&_&&r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[r.jsxs(At,{id:"card-externalurl",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Js,{className:"w-5 h-5 text-blue-400"}),i("settings.externalUrl")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.externalUrlDescription")}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bambuddyUrl")}),r.jsx("input",{type:"text",value:_.external_url??"",onChange:ve=>Cn("external_url",ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.externalUrlHint")})]})]})]}),r.jsxs(At,{id:"card-ftpretry",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(tr,{className:"w-5 h-5 text-blue-400"}),i("settings.ftpRetry")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.ftpRetryDescription")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.autoRetryDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.ftp_retry_enabled??!0,onChange:ve=>Cn("ftp_retry_enabled",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),_.ftp_retry_enabled&&r.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryAttempts")}),r.jsxs("div",{className:"relative w-44",children:[r.jsx("select",{value:_.ftp_retry_count??3,onChange:ve=>Cn("ftp_retry_count",parseInt(ve.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(ve=>r.jsx("option",{value:ve,children:i("settings.time",{count:ve})},ve))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.retryDelay")}),r.jsxs("div",{className:"relative w-44",children:[r.jsx("select",{value:_.ftp_retry_delay??2,onChange:ve=>Cn("ftp_retry_delay",parseInt(ve.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(ve=>r.jsx("option",{value:ve,children:i("settings.second",{count:ve})},ve))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.connectionTimeout")}),r.jsxs("div",{className:"relative w-44",children:[r.jsx("select",{value:_.ftp_timeout??30,onChange:ve=>Cn("ftp_timeout",parseInt(ve.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(ve=>r.jsx("option",{value:ve,children:i("settings.nSeconds",{count:ve})},ve))}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.increaseForWeakWifi")})]})]})]})]})]}),r.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-3",children:[r.jsxs(At,{id:"card-ha",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(AS,{className:"w-5 h-5 text-bambu-green"}),i("settings.homeAssistant")]}),_.ha_enabled&&Ge&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Ge.success?"bg-green-400":"bg-red-400"}`}),r.jsx("span",{className:`text-sm ${Ge.success?"text-green-400":"text-red-400"}`,children:Ge.success?i("settings.connected"):i("settings.disconnected")})]})]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.homeAssistantFullDescription")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),_.ha_env_managed&&r.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[r.jsx(rc,{className:"w-3 h-3 text-bambu-green"}),r.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.ha_enabled??!1,onChange:ve=>Cn("ha_enabled",ve.target.checked),disabled:_.ha_env_managed,className:"sr-only peer"}),r.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 ${_.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),_.ha_enabled&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.homeAssistantUrl"),_.ha_url_from_env&&r.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",value:_.ha_url??"",onChange:ve=>Cn("ha_url",ve.target.value),placeholder:"http://192.168.1.100:8123",disabled:_.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 ${_.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),_.ha_url_from_env&&r.jsx(rc,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),_.ha_url_from_env&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.longLivedAccessToken"),_.ha_token_from_env&&r.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"password",value:_.ha_token??"",onChange:ve=>Cn("ha_token",ve.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:_.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 ${_.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),_.ha_token_from_env&&r.jsx(rc,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),_.ha_token_from_env?r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.haTokenHint")})]}),_.ha_url&&_.ha_token&&r.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:r.jsxs(je,{variant:"secondary",size:"sm",disabled:De,onClick:async()=>{mt(!0),Je(null);try{const ve=await ae.testHAConnection(_.ha_url,_.ha_token);Je(ve)}catch(ve){Je({success:!1,message:null,error:ve instanceof Error?ve.message:i("common.unknownError")})}finally{mt(!1)}},children:[De?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Mh,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),r.jsxs(At,{id:"card-mqtt",children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Mh,{className:"w-5 h-5 text-blue-400"}),i("settings.mqttPublishing")]}),Ma?.enabled&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Ma.connected?"bg-green-400":"bg-red-400"}`}),r.jsx("span",{className:`text-sm ${Ma.connected?"text-green-400":"text-red-400"}`,children:Ma.connected?i("settings.connected"):i("settings.disconnected")})]})]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttDescription")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.mqttEnableDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.mqtt_enabled??!1,onChange:ve=>Cn("mqtt_enabled",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),_.mqtt_enabled&&r.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.brokerHostname")}),r.jsx("input",{type:"text",value:_.mqtt_broker??"",onChange:ve=>Cn("mqtt_broker",ve.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"})]}),r.jsxs("div",{className:"flex items-end gap-4",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.port")}),r.jsx("input",{type:"number",min:"1",max:"65535",value:_.mqtt_port??1883,onChange:ve=>Cn("mqtt_port",Math.min(65535,Math.max(1,parseInt(ve.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"})]}),r.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.mqtt_use_tls??!1,onChange:ve=>{const zt=ve.target.checked;Cn("mqtt_use_tls",zt);const mn=_.mqtt_port??1883;zt&&mn===1883?Cn("mqtt_port",8883):!zt&&mn===8883&&Cn("mqtt_port",1883)},className:"sr-only peer"}),r.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"})]}),r.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.usernameOptional")}),r.jsx("input",{type:"text",value:_.mqtt_username??"",onChange:ve=>Cn("mqtt_username",ve.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.passwordOptional")}),r.jsx("input",{type:"password",value:_.mqtt_password??"",onChange:ve=>Cn("mqtt_password",ve.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.topicPrefix")}),r.jsx("input",{type:"text",value:_.mqtt_topic_prefix??"bambuddy",onChange:ve=>Cn("mqtt_topic_prefix",ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.topicPrefixHint",{prefix:_.mqtt_topic_prefix||"bambuddy"})})]}),Ma&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${Ma.connected?"bg-green-400":"bg-red-400"}`}),r.jsx("span",{className:"text-bambu-gray",children:Ma.connected?r.jsxs(r.Fragment,{children:[i("settings.mqttConnectedTo")," ",r.jsxs("span",{className:"text-white",children:[Ma.broker,":",Ma.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),r.jsx("div",{className:"flex-1 lg:max-w-md space-y-3",children:r.jsxs(At,{id:"card-prometheus",children:[r.jsx(fn,{children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(sC,{className:"w-5 h-5 text-orange-400"}),i("settings.prometheusMetrics")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.prometheusEndpointDescription")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.prometheus_enabled??!1,onChange:ve=>Cn("prometheus_enabled",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),_.prometheus_enabled&&r.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.bearerTokenOptional")}),r.jsx("input",{type:"password",value:_.prometheus_token??"",onChange:ve=>Cn("prometheus_token",ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.bearerTokenHint")})]}),r.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),r.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - ",i("settings.metricsConnectionStatus")]}),r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - ",i("settings.metricsPrinterState")]}),r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - ",i("settings.metricsPrintProgress")]}),r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - ",i("settings.metricsBedTemp")]}),r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - ",i("settings.metricsNozzleTemp")]}),r.jsxs("p",{children:[r.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - ",i("settings.metricsPrintsTotal")]}),r.jsx("p",{className:"text-bambu-gray/70 italic",children:i("settings.metricsMore")})]})]})]})]})]})})]}),Ge&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Ge.success?r.jsx(xr,{className:"w-8 h-8 text-green-400"}):r.jsx($r,{className:"w-8 h-8 text-red-400"}),r.jsx("h3",{className:"text-lg font-medium text-white",children:Ge.success?i("settings.connectionSuccessful"):i("settings.connectionFailed")})]}),r.jsx("p",{className:"text-bambu-gray mb-6",children:Ge.success?Ge.message||i("settings.haConnectionSuccess"):Ge.error||i("settings.haConnectionFailed")}),r.jsx("div",{className:"flex justify-end",children:r.jsx(je,{variant:"primary",onClick:()=>Je(null),children:i("settings.ok")})})]})}),O==="plugs"&&r.jsxs("div",{id:"card-plugs",children:[r.jsxs("div",{className:"flex items-start justify-between mb-6",children:[r.jsxs("div",{children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(hc,{className:"w-5 h-5 text-bambu-green"}),i("settings.smartPlugs")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.smartPlugsDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Qt&&Qt.filter(ve=>ve.enabled).length>1&&r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Oe("on"),disabled:Uc.isPending,title:i("settings.turnAllPlugsOn"),children:[Uc.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(_u,{className:"w-4 h-4 text-bambu-green"}),i("settings.allOn")]}),r.jsxs(je,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>Oe("off"),disabled:Uc.isPending,title:i("settings.turnAllPlugsOff"),children:[Uc.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(FS,{className:"w-4 h-4 text-red-400"}),i("settings.allOff")]})]}),r.jsxs(je,{className:"whitespace-nowrap",onClick:()=>{L(null),I(!0)},children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addSmartPlug")]})]})]}),Qt&&Qt.length>0&&r.jsxs(At,{className:"mb-6",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(wc,{className:"w-4 h-4 text-yellow-400"}),i("settings.energySummary"),rn&&r.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),r.jsx(Et,{children:nn?r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[r.jsx(wc,{className:"w-3 h-3"}),i("settings.currentPower")]}),r.jsxs("div",{className:"text-xl font-bold text-white",children:[nn.totalPower.toFixed(1),r.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),r.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:i("settings.plugsOnline",{reachable:nn.reachableCount,total:nn.totalPlugs})})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[r.jsx(wa,{className:"w-3 h-3"}),i("settings.today")]}),r.jsxs("div",{className:"text-xl font-bold text-white",children:[nn.totalToday.toFixed(3),r.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(_?.energy_cost_per_kwh??0)>0&&r.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nn.totalToday*(_?.energy_cost_per_kwh??0)).toFixed(2)," ",Ho(_?.currency||"USD")]})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[r.jsx(sC,{className:"w-3 h-3"}),i("settings.yesterday")]}),r.jsxs("div",{className:"text-xl font-bold text-white",children:[nn.totalYesterday.toFixed(3),r.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(_?.energy_cost_per_kwh??0)>0&&r.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nn.totalYesterday*(_?.energy_cost_per_kwh??0)).toFixed(2)," ",Ho(_?.currency||"USD")]})]}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[r.jsx(JN,{className:"w-3 h-3"}),i("settings.total")]}),r.jsxs("div",{className:"text-xl font-bold text-white",children:[nn.totalLifetime.toFixed(1),r.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(_?.energy_cost_per_kwh??0)>0&&r.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(nn.totalLifetime*(_?.energy_cost_per_kwh??0)).toFixed(2)," ",Ho(_?.currency||"USD")]})]})]}):rn?null:r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.enablePlugsForSummary")})})]}),dn?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Qt&&Qt.length>0?r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Qt.map(ve=>r.jsx(Qrt,{plug:ve,onEdit:zt=>{L(zt),I(!0)}},ve.id))}):r.jsx(At,{children:r.jsx(Et,{className:"py-12",children:r.jsxs("div",{className:"text-center text-bambu-gray",children:[r.jsx(hc,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),r.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),r.jsxs(je,{onClick:()=>{L(null),I(!0)},children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),O==="notifications"&&r.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-providers",children:[r.jsx(Ch,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>$(!0),children:[r.jsx(Vh,{className:"w-4 h-4"}),i("settings.log")]}),yn&&yn.length>0&&r.jsxs(je,{size:"sm",variant:"secondary",onClick:()=>{El(null),zc.mutate()},disabled:zc.isPending,children:[zc.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(LS,{className:"w-4 h-4"}),i("settings.testAll")]}),r.jsxs(je,{size:"sm",onClick:()=>{ce(null),ne(!0)},children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addNotificationProvider")]})]})]}),r.jsx(At,{className:"mb-4",children:r.jsx(Et,{className:"py-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),r.jsx("select",{value:_.notification_language||"en",onChange:ve=>Cn("notification_language",ve.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:Q8.map(ve=>r.jsx("option",{value:ve.code,children:ve.nativeName},ve.code))})]})})}),r.jsx(At,{className:"mb-4",children:r.jsx(Et,{className:"py-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.bedCooledThreshold")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.bedCooledThresholdDescription")})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:20,max:80,step:1,value:_.bed_cooled_threshold??35,onChange:ve=>Cn("bed_cooled_threshold",Number(ve.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"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),r.jsx(At,{className:"mb-4",children:r.jsx(Et,{className:"py-3",children:r.jsxs("div",{className:`flex items-center justify-between ${hi?.advanced_auth_enabled?"":"opacity-50"}`,children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.userNotificationsEnabled")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:hi?.advanced_auth_enabled?i("settings.userNotificationsEnabledDescription"):i("settings.userNotificationsDisabledHint")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",className:"sr-only peer",checked:_.user_notifications_enabled??!0,disabled:!hi?.advanced_auth_enabled,onChange:ve=>Cn("user_notifications_enabled",ve.target.checked)}),r.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"})]})]})})}),Ml&&r.jsx(At,{className:"mb-4",children:r.jsxs(Et,{className:"py-3",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),r.jsx("button",{onClick:()=>El(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[r.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[r.jsx(xr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:Ml.success})]}),Ml.failed>0&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx($r,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:Ml.failed})]})]}),Ml.results.filter(ve=>!ve.success).length>0&&r.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Ml.results.filter(ve=>!ve.success).map(ve=>r.jsxs("div",{className:"text-xs text-red-400",children:[r.jsxs("span",{className:"font-medium",children:[ve.provider_name,":"]})," ",ve.message]},ve.provider_id))})]})}),Mn?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):yn&&yn.length>0?r.jsx("div",{className:"space-y-3",children:yn.map(ve=>r.jsx(Xrt,{provider:ve,onEdit:zt=>{ce(zt),ne(!0)}},ve.id))}):r.jsx(At,{children:r.jsx(Et,{className:"py-8",children:r.jsxs("div",{className:"text-center text-bambu-gray",children:[r.jsx(Ch,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),r.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),r.jsxs(je,{size:"sm",onClick:()=>{ce(null),ne(!0)},children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),r.jsxs("div",{children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-2",id:"card-templates",children:[r.jsx(Rs,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:i("settings.messageTemplatesDescription")}),r.jsxs("div",{className:"relative mb-3",children:[r.jsx(yr,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none"}),r.jsx("input",{type:"text",value:Q,onChange:ve=>le(ve.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"}),Q&&r.jsx("button",{onClick:()=>le(""),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-bambu-gray hover:text-white","aria-label":"Clear filter",children:r.jsx(Vt,{className:"w-3.5 h-3.5"})})]}),ua?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):vr&&vr.length>0?(()=>{const ve=Q.trim().toLowerCase(),zt=[...vr].sort((mn,An)=>mn.name.localeCompare(An.name)).filter(mn=>!ve||mn.name.toLowerCase().includes(ve)||(mn.title_template||"").toLowerCase().includes(ve));return zt.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic text-center py-6",children:i("settings.noTemplatesMatch","No templates match your filter.")}):r.jsx("div",{className:"space-y-2",children:zt.map(mn=>r.jsx(At,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>oe(mn),children:r.jsx(Et,{className:"py-2.5 px-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium text-sm truncate",children:mn.name}),r.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:mn.title_template})]}),r.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:An=>{An.stopPropagation(),oe(mn)},children:r.jsx(uc,{className:"w-4 h-4 text-bambu-gray"})})]})})},mn.id))})})():r.jsx(At,{children:r.jsx(Et,{className:"py-8",children:r.jsxs("div",{className:"text-center text-bambu-gray",children:[r.jsx(Rs,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),r.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),O==="apikeys"&&r.jsxs("div",{className:m("api_keys:read")?"grid grid-cols-1 xl:grid-cols-2 gap-4":"grid grid-cols-1 gap-4",children:[r.jsxs("div",{children:[m("api_keys:read")&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-createapi",children:[r.jsx(bo,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),r.jsxs(je,{size:"sm",onClick:()=>se(!0),className:"flex-shrink-0",children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.createKey")]})]}),q&&r.jsx(At,{className:"mb-6 border-bambu-green",children:r.jsx(Et,{className:"py-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(xr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),r.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[r.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:q}),r.jsx(je,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(q);else{const ve=document.createElement("textarea");ve.value=q,ve.style.position="fixed",ve.style.left="-999999px",document.body.appendChild(ve),ve.select(),document.execCommand("copy"),document.body.removeChild(ve)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:r.jsx(Ti,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex gap-2 mt-3",children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>{_e(q),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>R(null),children:i("common.dismiss")})]})]})]})})}),X&&r.jsxs(At,{className:"mb-6",children:[r.jsx(fn,{children:r.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),r.jsx("input",{type:"text",value:te,onChange:ve=>fe(ve.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:de.can_read_status,onChange:ve=>me(zt=>({...zt,can_read_status:ve.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white",children:i("settings.readStatus")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:de.can_queue,onChange:ve=>me(zt=>({...zt,can_queue:ve.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:de.can_control_printer,onChange:ve=>me(zt=>({...zt,can_control_printer:ve.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:de.can_access_cloud,onChange:ve=>me(zt=>({...zt,can_access_cloud:ve.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white",children:i("settings.cloudAccess","Allow cloud access")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.cloudAccessDescription","Read Bambu Cloud presets and filaments on your behalf. Requires you to be signed into Bambu Cloud.")})]})]}),r.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:de.can_update_energy_cost,onChange:ve=>me(zt=>({...zt,can_update_energy_cost:ve.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),r.jsxs("div",{children:[r.jsx("span",{className:"text-white",children:i("settings.updateEnergyCost")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.updateEnergyCostDescription")})]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[r.jsxs(je,{onClick:()=>Gn.mutate({name:te||i("settings.unnamedKey"),...de}),disabled:Gn.isPending,children:[Gn.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(er,{className:"w-4 h-4"}),i("settings.createKey")]}),r.jsx(je,{variant:"secondary",onClick:()=>se(!1),children:i("common.cancel")})]})]})]}),Dr?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):or&&or.length>0?r.jsx("div",{className:"space-y-3",children:or.map(ve=>r.jsx(At,{children:r.jsx(Et,{className:"py-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(bo,{className:`w-5 h-5 ${ve.enabled?"text-bambu-green":"text-bambu-gray"}`}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:ve.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[ve.key_prefix,"••••••••",ve.last_used&&` · ${i("settings.lastUsed")}: ${Dg(ve.last_used)}`]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex gap-1 text-xs flex-wrap justify-end",children:[ve.can_read_status&&r.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),ve.can_queue&&r.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),ve.can_control_printer&&r.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")}),ve.can_access_cloud&&r.jsx("span",{className:"px-1.5 py-0.5 bg-purple-500/20 text-purple-400 rounded",children:i("settings.cloudBadge","Cloud")}),ve.can_update_energy_cost&&r.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/20 text-amber-400 rounded",children:i("settings.energyCostBadge")}),ve.user_id===null&&r.jsx("span",{className:"px-1.5 py-0.5 bg-yellow-500/20 text-yellow-400 rounded",title:i("settings.legacyKeyTooltip","Created before per-user ownership; recreate to use cloud access"),children:i("settings.legacyKey","Legacy")})]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>be(ve.id),children:r.jsx(en,{className:"w-4 h-4 text-red-400"})})]})]})})},ve.id))}):r.jsx(At,{children:r.jsx(Et,{className:"py-12",children:r.jsxs("div",{className:"text-center text-bambu-gray",children:[r.jsx(bo,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),r.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),r.jsxs(je,{onClick:()=>se(!0),children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),r.jsxs(At,{className:"mt-6",children:[r.jsx(fn,{children:r.jsx("h3",{className:"text-base font-semibold text-white",id:"card-webhooks",children:i("settings.webhookEndpoints")})}),r.jsxs(Et,{className:"space-y-3 text-sm",children:[r.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),r.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-blue-400",children:"GET"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-blue-400",children:"GET"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-green-400",children:"POST"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-orange-400",children:"POST"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-orange-400",children:"POST"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),r.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[r.jsx("span",{className:"text-red-400",children:"POST"})," ",r.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),r.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),r.jsxs(At,{className:"mt-6",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",id:"card-camera-tokens",children:[r.jsx(oC,{className:"w-4 h-4 text-bambu-green"}),i("cameraTokens.title","Camera API Tokens")]})}),r.jsx(Et,{children:r.jsx(Krt,{})})]})]}),m("api_keys:read")&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-apibrowser",children:[r.jsx(Js,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),r.jsx(At,{className:"mb-4",children:r.jsxs(Et,{className:"py-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),r.jsx("input",{type:"text",value:ye,onChange:ve=>_e(ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),r.jsx(Gat,{apiKey:ye})]})]}),O==="virtual-printer"&&r.jsx("div",{id:"card-vp",children:r.jsx(_at,{})}),O==="spoolbuddy"&&r.jsx("div",{id:"card-spoolbuddy",children:r.jsx(Nat,{})}),O==="queue"&&_&&r.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[r.jsxs("div",{className:"lg:w-1/2 space-y-3",children:[r.jsxs(At,{id:"card-print-options",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(Ew,{className:"w-4 h-4 text-bambu-green"}),i("settings.defaultPrintOptions","Default Print Options")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.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:ve,label:zt,desc:mn,fallback:An})=>r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex-1 mr-4",children:[r.jsx("p",{className:"text-sm text-white",children:zt}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:mn})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_[ve]??An,onChange:zn=>Cn(ve,zn.target.checked),className:"sr-only peer"}),r.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"})]})]},ve))]})]}),r.jsxs(At,{id:"card-staggered",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(ca,{className:"w-4 h-4 text-bambu-green"}),i("settings.staggeredStart","Staggered Start")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.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.")}),r.jsxs("div",{className:"flex gap-4",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerGroupSize","Group size")}),r.jsx("input",{type:"number",min:1,max:50,value:_.stagger_group_size??2,onChange:ve=>Cn("stagger_group_size",Math.max(1,Math.min(50,parseInt(ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerGroupSizeHelp","Printers to start simultaneously per group")})]}),r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.staggerInterval","Interval (minutes)")}),r.jsx("input",{type:"number",min:1,max:60,value:_.stagger_interval_minutes??5,onChange:ve=>Cn("stagger_interval_minutes",Math.max(1,Math.min(60,parseInt(ve.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.staggerIntervalHelp","Delay between each group starting")})]})]})]})]}),r.jsxs(At,{id:"card-plate",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(hl,{className:"w-4 h-4 text-bambu-green"}),i("settings.plateClear","Plate-Clear Confirmation")]})}),r.jsx(Et,{className:"space-y-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex-1 mr-4",children:[r.jsx("p",{className:"text-sm text-white",children:i("settings.requirePlateClear","Require plate-clear confirmation")}),r.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. Disabling this also hides the plate status badge and the "Mark plate as cleared" button on printer cards.')})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.require_plate_clear??!1,onChange:ve=>Cn("require_plate_clear",ve.target.checked),className:"sr-only peer"}),r.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"})]})]})})]}),r.jsxs(At,{id:"card-gcode",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(Ky,{className:"w-4 h-4 text-bambu-green"}),i("settings.gcodeInjection","G-code Injection")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.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 ve=(()=>{try{return _.gcode_snippets?JSON.parse(_.gcode_snippets):{}}catch{return{}}})(),zt=[...new Set((Un||[]).filter(zn=>zn.model).map(zn=>zn.model))].sort(),mn=(zn,dt,qt)=>{const Xt={...ve};Xt[zn]||(Xt[zn]={start_gcode:"",end_gcode:""}),Xt[zn][dt]=qt,!Xt[zn].start_gcode&&!Xt[zn].end_gcode&&delete Xt[zn];const ht=Object.keys(Xt).length>0?JSON.stringify(Xt):"";M(In=>In?{...In,gcode_snippets:ht}:null),Nd.current=ht},An=()=>{Nd.current!==null&&(Cd.mutate({gcode_snippets:Nd.current}),Nd.current=null)};return zt.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic",children:i("settings.gcodeInjectionNoPrinters","No printers found. Add printers to configure G-code snippets.")}):zt.map(zn=>{const dt=ve[zn]||{start_gcode:"",end_gcode:""},qt=!!(dt.start_gcode||dt.end_gcode);return r.jsx(m5,{defaultOpen:qt,className:"border border-bambu-dark-tertiary rounded-lg px-3 py-2",summary:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:zn}),qt&&r.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:r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeStartLabel","Start G-code")}),r.jsx("textarea",{value:dt.start_gcode,onChange:Xt=>mn(zn,"start_gcode",Xt.target.value),onBlur:An,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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:i("settings.gcodeEndLabel","End G-code")}),r.jsx("textarea",{value:dt.end_gcode,onChange:Xt=>mn(zn,"end_gcode",Xt.target.value),onBlur:An,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"})]})]})},zn)})})()]})]})]}),r.jsxs("div",{className:"lg:w-1/2 space-y-3",children:[r.jsxs(At,{id:"card-slicer",children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[r.jsx(uu,{className:"w-4 h-4 text-bambu-green"}),i("settings.slicerCard","Slicer")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:_.preferred_slicer??"bambu_studio",onChange:ve=>Cn("preferred_slicer",ve.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:[r.jsx("option",{value:"bambu_studio",children:i("settings.slicerBambuStudio")}),r.jsx("option",{value:"orcaslicer",children:i("settings.slicerOrcaSlicer")})]}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")}),(_.preferred_slicer??"bambu_studio")==="orcaslicer"&&r.jsx("div",{role:"alert",className:"text-xs text-amber-200 bg-amber-900/20 border border-amber-700/40 rounded p-2 mt-2",children:i("settings.orcaslicerKnownIssuesWarning","OrcaSlicer 2.3.2 / 2.4.0-dev have known CLI bugs that block slicing many Bambu-authored 3MFs — see upstream issues #12426 (segfault on painted multi-extruder files) and #13386 (parameter-range strict-validation reject). Bambu Studio is recommended until the upstream fixes land.")})]}),r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-white",children:i("settings.useSlicerApi")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.useSlicerApiDescription")})]}),r.jsxs("label",{className:"flex items-center cursor-pointer shrink-0",children:[r.jsx("input",{type:"checkbox",checked:_.use_slicer_api??!1,onChange:ve=>Cn("use_slicer_api",ve.target.checked),className:"sr-only peer"}),r.jsx("div",{className:"relative w-11 h-6 bg-bambu-dark-tertiary rounded-full peer peer-checked:bg-bambu-green peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-bambu-green/50 transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-transform peer-checked:after:translate-x-5"})]})]}),(_.use_slicer_api??!1)&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:(_.preferred_slicer??"bambu_studio")==="orcaslicer"?i("settings.orcaslicerApiUrl","OrcaSlicer sidecar URL"):i("settings.bambuStudioApiUrl","Bambu Studio sidecar URL")}),r.jsx("input",{type:"text",value:((_.preferred_slicer??"bambu_studio")==="orcaslicer"?_.orcaslicer_api_url:_.bambu_studio_api_url)??"",onChange:ve=>Cn((_.preferred_slicer??"bambu_studio")==="orcaslicer"?"orcaslicer_api_url":"bambu_studio_api_url",ve.target.value),placeholder:(_.preferred_slicer??"bambu_studio")==="orcaslicer"?"http://localhost:3003":"http://localhost:3001",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:text-bambu-gray/40"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.slicerApiUrlDescription","URL of the slicer-API sidecar container. Leave blank to use the SLICER_API_URL / BAMBU_STUDIO_API_URL env var defaults.")})]})]})]}),(_.use_slicer_api??!1)&&r.jsx(Hrt,{}),r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",id:"card-drying",children:[r.jsx(pm,{className:"w-4 h-4 text-amber-400"}),i("settings.queueDrying")]})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.queueDryingDescription")}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingEnabled")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingEnabledDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.queue_drying_enabled??!1,onChange:ve=>Cn("queue_drying_enabled",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),_.queue_drying_enabled&&r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-white",children:i("settings.queueDryingBlock")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.queueDryingBlockDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.queue_drying_block??!1,onChange:ve=>Cn("queue_drying_block",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-white",children:i("settings.ambientDryingEnabled")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.ambientDryingEnabledDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.ambient_drying_enabled??!1,onChange:ve=>Cn("ambient_drying_enabled",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-sm text-white font-medium",children:i("settings.dryingPresets")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.dryingPresetsDescription")}),r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-xs",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left py-1.5",children:i("settings.dryingFilament")}),r.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS 2 Pro"}),r.jsx("th",{className:"text-center py-1.5",colSpan:2,children:"AMS-HT"})]})}),r.jsx("tbody",{children:(()=>{const ve={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 zt={...ve};try{if(_.drying_presets){const An=JSON.parse(_.drying_presets);typeof An=="object"&&An!==null&&(zt={...ve,...An})}}catch{}const mn=(An,zn,dt)=>{const qt={...zt,[An]:{...zt[An],[zn]:dt}};Cn("drying_presets",JSON.stringify(qt))};return Object.entries(zt).map(([An,zn])=>r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50",children:[r.jsx("td",{className:"py-1.5 pr-2 text-white font-medium",children:An}),r.jsx("td",{className:"py-1 px-1",children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx("input",{type:"number",min:30,max:65,value:zn.n3f,onChange:dt=>mn(An,"n3f",Math.max(1,parseInt(dt.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"}),r.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),r.jsx("td",{className:"py-1 px-1",children:r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:zn.n3f_hours,onChange:dt=>mn(An,"n3f_hours",Math.max(1,parseInt(dt.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"}),r.jsx("span",{className:"text-bambu-gray",children:"h"})]})}),r.jsx("td",{className:"py-1 px-1",children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[r.jsx("input",{type:"number",min:30,max:85,value:zn.n3s,onChange:dt=>mn(An,"n3s",Math.max(1,parseInt(dt.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"}),r.jsx("span",{className:"text-bambu-gray",children:"°C"})]})}),r.jsx("td",{className:"py-1 px-1",children:r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:zn.n3s_hours,onChange:dt=>mn(An,"n3s_hours",Math.max(1,parseInt(dt.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"}),r.jsx("span",{className:"text-bambu-gray",children:"h"})]})})]},An))})()})]})})]})]})]})]})]}),O==="filament"&&_&&r.jsx(r.Fragment,{children:r.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[r.jsxs("div",{className:"lg:w-1/3 space-y-3",children:[r.jsx(oat,{}),r.jsxs(At,{id:"card-filamentchecks",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.filamentChecks")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.disableFilamentWarnings")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.disableFilamentWarningsDesc")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.disable_filament_warnings,onChange:ve=>Cn("disable_filament_warnings",ve.target.checked),className:"sr-only peer"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.preferLowestFilament")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.preferLowestFilamentDesc")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.prefer_lowest_filament,onChange:ve=>Cn("prefer_lowest_filament",ve.target.checked),className:"sr-only peer"}),r.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"})]})]})]})]}),r.jsxs(At,{id:"card-printmodal",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.printModal")})}),r.jsx(Et,{className:"space-y-3",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-white",children:i("settings.expandCustomMapping")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.expandCustomMappingDescription")})]}),r.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_.per_printer_mapping_expanded??!1,onChange:ve=>Cn("per_printer_mapping_expanded",ve.target.checked),className:"sr-only peer"}),r.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"})]})]})})]}),r.jsxs(At,{id:"card-amsthresholds",children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),r.jsxs(Et,{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white",children:[r.jsx(wO,{className:"w-4 h-4 text-blue-400"}),r.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:"0",max:"100",value:_.ams_humidity_good??40,onChange:ve=>Cn("ams_humidity_good",parseInt(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:"0",max:"100",value:_.ams_humidity_fair??60,onChange:ve=>Cn("ams_humidity_fair",parseInt(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")}),r.jsx("p",{className:"text-xs text-amber-400/70",children:i("settings.fairAlsoDryingThreshold")})]}),r.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white",children:[r.jsx(RS,{className:"w-4 h-4 text-orange-400"}),r.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:_.ams_temp_good??28,onChange:ve=>Cn("ams_temp_good",parseFloat(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:_.ams_temp_fair??35,onChange:ve=>Cn("ams_temp_fair",parseFloat(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),r.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-white",children:[r.jsx(dc,{className:"w-4 h-4 text-purple-400"}),r.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",min:"1",max:"365",value:_.ams_history_retention_days??30,onChange:ve=>Cn("ams_history_retention_days",parseInt(ve.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"}),r.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]})]})]})]}),r.jsxs("div",{className:"lg:w-2/3 space-y-3",children:[r.jsx(lat,{}),r.jsx(xat,{})]})]})}),re!==null&&r.jsx(wn,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{pi.mutate(re),be(null)},onCancel:()=>be(null)}),H&&r.jsx(Yrt,{plug:z,onClose:()=>{I(!1),L(null)}}),Z&&r.jsx(Jrt,{provider:Y,onClose:()=>{ne(!1),ce(null)}}),ue&&r.jsx(eat,{template:ue,onClose:()=>oe(null)}),we&&r.jsx(nat,{onClose:()=>$(!1)}),xe&&r.jsx(wn,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{ge(!1);try{const ve=await ae.clearNotificationLogs(30);o(ve.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>ge(!1)}),Me&&r.jsx(wn,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{Be(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>Be(!1)}),Fe&&r.jsx(wn,{title:`Turn All Plugs ${Fe==="on"?"On":"Off"}`,message:`This will turn ${Fe==="on"?"ON":"OFF"} all ${Qt?.filter(ve=>ve.enabled).length||0} enabled smart plugs. ${Fe==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${Fe==="on"?"On":"Off"}`,variant:Fe==="off"?"danger":"warning",onConfirm:()=>{const ve=Fe;Oe(null),Uc.mutate(ve)},onCancel:()=>Oe(null)}),Re&&kr?.release_notes&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>We(!1),children:r.jsxs(At,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ve=>ve.stopPropagation(),children:[r.jsxs(fn,{className:"flex flex-row items-center justify-between shrink-0",children:[r.jsxs("div",{children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",kr.latest_version]}),kr.release_name&&kr.release_name!==kr.latest_version&&r.jsx("p",{className:"text-sm text-bambu-gray",children:kr.release_name})]}),r.jsx("button",{onClick:()=>We(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx(Et,{className:"overflow-y-auto flex-1",children:r.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:kr.release_notes})}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[kr.release_url&&r.jsx("a",{href:kr.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:r.jsxs(je,{variant:"secondary",className:"w-full",children:[r.jsx(zr,{className:"w-4 h-4"}),"View on GitHub"]})}),r.jsx(je,{onClick:()=>We(!1),className:"flex-1",children:"Close"})]})]})}),O==="users"&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>G("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 ${U==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(bm,{className:"w-4 h-4"}),i("settings.tabs.users")]}),r.jsxs("button",{onClick:()=>G("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 ${U==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx($m,{className:"w-4 h-4"}),i("settings.tabs.emailAuth")||"Email Authentication",hi?.advanced_auth_enabled&&r.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),r.jsxs("button",{onClick:()=>G("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 ${U==="ldap"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(hl,{className:"w-4 h-4"}),i("settings.tabs.ldap")||"LDAP",nl?.ldap_enabled&&r.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),r.jsxs("button",{onClick:()=>G("twofa"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${U==="twofa"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(hl,{className:"w-4 h-4"}),i("settings.tabs.twoFa"),r.jsx("span",{className:`w-2 h-2 rounded-full ${Rc?.totp_enabled||Rc?.email_otp_enabled?"bg-green-400":"bg-bambu-gray/40"}`})]}),d&&r.jsxs("button",{onClick:()=>G("oidc"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${U==="oidc"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(Js,{className:"w-4 h-4"}),i("settings.tabs.oidc"),r.jsx("span",{className:`w-2 h-2 rounded-full ${mp.some(ve=>ve.is_enabled)?"bg-green-400":"bg-bambu-gray/40"}`})]}),d&&r.jsxs("button",{onClick:()=>G("security"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${U==="security"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[r.jsx(hl,{className:"w-4 h-4"}),i("settings.tabs.security")]})]}),U==="users"&&r.jsxs(r.Fragment,{children:[r.jsx(At,{children:r.jsx(Et,{className:"py-4",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.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?r.jsx(rc,{className:"w-5 h-5 text-green-400"}):r.jsx(X0,{className:"w-5 h-5 text-gray-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&r.jsxs(je,{variant:"secondary",onClick:()=>st(!0),children:[r.jsx(X0,{className:"w-4 h-4"}),i("common.disable")]}):r.jsxs(je,{onClick:()=>e("/setup"),children:[r.jsx(rc,{className:"w-4 h-4"}),i("common.enable")]})]})})}),hi?.advanced_auth_enabled&&r.jsx(At,{className:"border-blue-500/30 bg-blue-500/5",children:r.jsx(Et,{className:"py-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:r.jsx($m,{className:"w-5 h-5 text-blue-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&r.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[r.jsxs("div",{className:"space-y-3",children:[c&&r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-currentuser",children:[r.jsx(bm,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),c.auth_source!=="ldap"&&r.jsxs(je,{size:"sm",variant:"ghost",onClick:()=>it(!0),children:[r.jsx(bo,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),r.jsx(Et,{children:r.jsx("div",{className:"flex items-center justify-between",children:r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),r.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&r.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(ve=>r.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ve.name==="Administrators"?"bg-purple-500/20 text-purple-300":ve.name==="Operators"?"bg-blue-500/20 text-blue-300":ve.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ve.name},ve.id))]})]})})})]}),r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-users",children:[r.jsx(bm,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),m("users:create")&&r.jsxs(je,{size:"sm",onClick:()=>{Te(!0),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),r.jsx(Et,{children:Mo?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Ea.length===0?r.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Ea.map(ve=>r.jsxs("div",{className:"py-3 flex items-center justify-between",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-white font-medium truncate",children:ve.username}),r.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ve.auth_source==="ldap"&&r.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-cyan-500/20 text-cyan-300",children:"LDAP"}),ve.is_admin&&r.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")}),ve.groups?.map(zt=>r.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${zt.name==="Administrators"?"bg-purple-500/20 text-purple-300":zt.name==="Operators"?"bg-blue-500/20 text-blue-300":zt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:zt.name},zt.id))]})]}),r.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[m("users:update")&&r.jsx(je,{size:"sm",variant:"ghost",onClick:()=>gv(ve),children:r.jsx(uc,{className:"w-4 h-4"})}),m("users:delete")&&ve.id!==c?.id&&r.jsx(je,{size:"sm",variant:"ghost",onClick:()=>Au(ve.id),children:r.jsx(en,{className:"w-4 h-4"})})]})]},ve.id))})})]})]}),r.jsx("div",{children:r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",id:"card-groups",children:[r.jsx(hl,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),m("groups:create")&&r.jsxs(je,{size:"sm",onClick:()=>e("/groups/new"),children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),r.jsx(Et,{children:Ic?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Eo.length===0?r.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Eo.map(ve=>r.jsxs("div",{className:"py-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hl,{className:`w-4 h-4 ${ve.name==="Administrators"?"text-purple-400":ve.name==="Operators"?"text-blue-400":ve.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),r.jsx("span",{className:"text-white font-medium",children:ve.name}),ve.is_system&&r.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[m("groups:update")&&r.jsx(je,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${ve.id}/edit`),children:r.jsx(uc,{className:"w-4 h-4"})}),m("groups:delete")&&!ve.is_system&&r.jsx(je,{size:"sm",variant:"ghost",onClick:()=>Ae(ve.id),children:r.jsx(en,{className:"w-4 h-4"})})]})]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ve.description||i("settings.noDescription")}),r.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[r.jsx("span",{children:i("settings.userCount",{count:ve.user_count})}),r.jsx("span",{children:i("settings.permissionCount",{count:ve.permissions.length})})]})]},ve.id))})})]})})]}),!l&&r.jsx(At,{children:r.jsx(Et,{className:"py-6",children:r.jsxs("div",{className:"text-center",children:[r.jsx(X0,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),r.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[r.jsxs("li",{className:"flex items-start gap-2",children:[r.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsx("span",{children:i("settings.authDisabledFeature1")})]}),r.jsxs("li",{className:"flex items-start gap-2",children:[r.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsx("span",{children:i("settings.authDisabledFeature2")})]}),r.jsxs("li",{className:"flex items-start gap-2",children:[r.jsx(xr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),r.jsxs(je,{onClick:()=>e("/setup"),children:[r.jsx(rc,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),U==="email"&&r.jsx("div",{className:"max-w-5xl",id:"card-smtp",children:r.jsx(Dat,{})}),U==="ldap"&&r.jsx("div",{className:"max-w-5xl",id:"card-ldap",children:r.jsx(Lat,{})}),U==="twofa"&&r.jsx("div",{className:"max-w-2xl",children:r.jsx(Iat,{})}),U==="oidc"&&d&&r.jsx("div",{className:"max-w-3xl",children:r.jsx(Uat,{})}),U==="security"&&d&&r.jsx("div",{className:"max-w-3xl",children:r.jsx(Hat,{})})]}),Qe&&!hi?.advanced_auth_enabled&&r.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:r.jsxs(At,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(bm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsxs(Et,{children:[nl?.ldap_enabled&&r.jsxs("div",{className:"mb-4 flex items-center gap-1 p-1 bg-bambu-dark-secondary rounded-lg",role:"tablist","aria-label":i("users.modal.tabsAriaLabel"),children:[r.jsx("button",{type:"button",role:"tab","aria-selected":tt==="local",onClick:()=>ot("local"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${tt==="local"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:i("users.modal.localTab")}),r.jsx("button",{type:"button",role:"tab","aria-selected":tt==="ldap",onClick:()=>ot("ldap"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${tt==="ldap"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:i("users.modal.ldapTab")})]}),tt==="ldap"&&nl?.ldap_enabled?r.jsxs(r.Fragment,{children:[r.jsx(zce,{onSuccess:ve=>{Te(!1),ot("local"),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("users.toast.ldapProvisioned",{username:ve.username}))}}),r.jsx("div",{className:"mt-6 flex justify-end",children:r.jsx(je,{variant:"secondary",onClick:()=>{Te(!1),ot("local"),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("common.cancel")})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),r.jsx("input",{type:"text",value:ut.username,onChange:ve=>Ct({...ut,username: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("settings.enterUsername"),autoComplete:"username"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),r.jsx("input",{type:"password",value:ut.password,onChange:ve=>Ct({...ut,password: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("settings.enterPassword"),autoComplete:"new-password",minLength:8}),r.jsx("p",{className:"text-bambu-gray text-xs mt-1",children:i("settings.passwordRequirements")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),r.jsx("input",{type:"password",value:ut.confirmPassword,onChange:ve=>Ct({...ut,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 ${ut.confirmPassword&&ut.password!==ut.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),ut.confirmPassword&&ut.password!==ut.confirmPassword&&r.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groups")}),r.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:[Eo.map(ve=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:ut.group_ids.includes(ve.id),onChange:()=>Oc(ve.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),r.jsx("span",{className:"text-sm text-white",children:ve.name}),ve.is_system&&r.jsx("span",{className:"text-xs text-yellow-400",children:i("settings.systemBadge")})]},ve.id)),Eo.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),r.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("common.cancel")}),r.jsx(je,{onClick:fb,disabled:_d.isPending||!ut.username||!ut.password||ut.password!==ut.confirmPassword||uN(ut.password)!==null,children:_d.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("settings.creating")]}):r.jsxs(r.Fragment,{children:[r.jsx(er,{className:"w-4 h-4"}),i("settings.createUser")]})})]})]})]})]})}),Qe&&hi?.advanced_auth_enabled&&r.jsx(sat,{formData:ut,setFormData:Ct,groups:Eo,onClose:()=>{Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:fb,isCreating:_d.isPending,isCreateButtonDisabled:_d.isPending||!ut.username||!ut.email,ldapEnabled:nl?.ldap_enabled,onLdapProvisioned:ve=>{Te(!1),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("users.toast.ldapProvisioned",{username:ve.username}))}}),Tt&&bt!==null&&r.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ut(!1),Wt(null),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:r.jsxs(At,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(uc,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{Ut(!1),Wt(null),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsxs(Et,{children:[r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",hi?.advanced_auth_enabled&&r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"text",value:ut.username,onChange:ve=>Ct({...ut,username: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("settings.enterUsername"),autoComplete:"username"})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",hi?.advanced_auth_enabled?r.jsx("span",{className:"text-red-400",children:"*"}):r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),r.jsx("input",{type:"email",value:ut.email,onChange:ve=>Ct({...ut,email: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("users.form.emailPlaceholder")||"user@example.com",required:hi?.advanced_auth_enabled})]}),!hi?.advanced_auth_enabled&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",r.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),r.jsx("input",{type:"password",value:ut.password,onChange:ve=>Ct({...ut,password:ve.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:8}),r.jsx("p",{className:"text-bambu-gray text-xs mt-1",children:i("settings.passwordRequirements")})]}),ut.password&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),r.jsx("input",{type:"password",value:ut.confirmPassword,onChange:ve=>Ct({...ut,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 ${ut.confirmPassword&&ut.password!==ut.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),ut.confirmPassword&&ut.password!==ut.confirmPassword&&r.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),hi?.advanced_auth_enabled&&r.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[r.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.'}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>bt&&Bs.mutate(bt),disabled:Bs.isPending||!ut.email,className:"w-full",children:Bs.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),r.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:Eo.map(ve=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:ut.group_ids.includes(ve.id),onChange:()=>Oc(ve.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),r.jsx("span",{className:"text-sm text-white",children:ve.name}),ve.is_system&&r.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},ve.id))})]})]}),r.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{Ut(!1),Wt(null),Ct({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),r.jsx(je,{onClick:()=>gb(bt),disabled:kd.isPending||!ut.username||hi?.advanced_auth_enabled&&!ut.email||!!(!hi?.advanced_auth_enabled&&ut.password&&(ut.password!==ut.confirmPassword||uN(ut.password)!==null)),children:kd.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):r.jsxs(r.Fragment,{children:[r.jsx(ds,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),Zt!==null&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{ln(null),ct(null)},children:r.jsxs(At,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[r.jsx(en,{className:"w-5 h-5"}),r.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),r.jsx(Et,{className:"space-y-3",children:kt?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):cn&&cn.archives+cn.queue_items+cn.library_files>0?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),r.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[cn.archives>0&&r.jsxs("li",{children:[cn.archives," archive",cn.archives!==1?"s":""]}),cn.queue_items>0&&r.jsxs("li",{children:[cn.queue_items," queue item",cn.queue_items!==1?"s":""]}),cn.library_files>0&&r.jsxs("li",{children:[cn.library_files," library file",cn.library_files!==1?"s":""]})]}),r.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx(je,{variant:"danger",onClick:()=>lo.mutate({id:Zt,deleteItems:!0}),disabled:lo.isPending,className:"justify-center",children:i("settings.deleteUserAndItems")}),r.jsx(je,{variant:"secondary",onClick:()=>lo.mutate({id:Zt,deleteItems:!1}),disabled:lo.isPending,className:"justify-center",children:i("settings.deleteUserKeepItems")}),r.jsx(je,{variant:"ghost",onClick:()=>{ln(null),ct(null)},disabled:lo.isPending,className:"justify-center",children:i("common.cancel")})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),r.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(je,{variant:"ghost",onClick:()=>{ln(null),ct(null)},disabled:lo.isPending,children:i("common.cancel")}),r.jsx(je,{variant:"danger",onClick:()=>lo.mutate({id:Zt,deleteItems:!1}),disabled:lo.isPending,children:i("settings.deleteUserTitle")})]})]})})]})}),Le!==null&&r.jsx(wn,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{hb.mutate(Le),Ae(null)},onCancel:()=>Ae(null)}),O==="failure-detection"&&r.jsx("div",{id:"card-failure-detection",children:r.jsx(jat,{})}),O==="backup"&&r.jsxs("div",{id:"card-backup",children:[r.jsxs("div",{className:"mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg flex items-start gap-2",children:[r.jsx(hl,{className:"text-amber-400 flex-shrink-0 mt-0.5",size:16}),r.jsx("p",{className:"text-sm text-amber-400",children:i("backup.includesEncryptionKey")})]}),r.jsx(Aat,{})]}),ze&&r.jsx(wn,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ae.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),st(!1),window.location.href="/"}catch(ve){const zt=ve instanceof Error?ve.message:i("settings.toast.authDisableFailed");o(zt,"error")}},onCancel:()=>st(!1)}),Ee&&r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{it(!1),Ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:r.jsxs(At,{className:"w-full max-w-md",onClick:ve=>ve.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(bo,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{it(!1),Ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsxs(Et,{children:[r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),r.jsx("input",{type:"password",value:Ce.currentPassword,onChange:ve=>Ze({...Ce,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("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),r.jsx("input",{type:"password",value:Ce.newPassword,onChange:ve=>Ze({...Ce,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("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),r.jsx("input",{type:"password",value:Ce.confirmPassword,onChange:ve=>Ze({...Ce,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 ${Ce.confirmPassword&&Ce.newPassword!==Ce.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ce.confirmPassword&&Ce.newPassword!==Ce.confirmPassword&&r.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),r.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>{it(!1),Ze({currentPassword:"",newPassword:"",confirmPassword:""})},children:i("common.cancel")}),r.jsx(je,{onClick:async()=>{if(Ce.newPassword!==Ce.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ce.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}ke(!0);try{await ae.changePassword(Ce.currentPassword,Ce.newPassword),o(i("settings.toast.passwordChanged"),"success"),it(!1),Ze({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ve){const zt=ve instanceof Error?ve.message:"Failed to change password";o(zt,"error")}finally{ke(!1)}},disabled:Ie||!Ce.currentPassword||!Ce.newPassword||Ce.newPassword!==Ce.confirmPassword||Ce.newPassword.length<6,children:Ie?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),i("settings.changing")]}):r.jsxs(r.Fragment,{children:[r.jsx(bo,{className:"w-4 h-4"}),i("settings.changePassword")]})})]})]})]})})]})]})]})})}const $ce=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},Yat=t=>t.startsWith("HH")?"HF":"S",Xat=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Vce=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const a of e)if(t.startsWith(a))return t.slice(a.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function mF({profile:t,onEdit:e,onCopy:n,selectionMode:a,isSelected:i,onToggleSelect:s,note:o}){const l=Yat(t.nozzle_id),c=t.nozzle_diameter,d=()=>{a&&s?s():e()};return r.jsxs("div",{className:"flex items-center gap-2",children:[a&&r.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?r.jsx(gs,{className:"w-4 h-4 text-bambu-green"}):r.jsx(ro,{className:"w-4 h-4"})}),r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:$ce(t.k_value)}),r.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&r.jsx("span",{title:"Has note",children:r.jsx(WZ,{className:"w-3 h-3 text-yellow-500"})}),r.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&r.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]})]}),!a&&n&&r.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:r.jsx(Ti,{className:"w-4 h-4"})})]})}function pF({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:a=[],builtinFilaments:i=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:d,onSaveNote:u,hasPermission:m}){const{t:p}=_t(),{showToast:f}=on(),[g,w]=y.useState(t?.name||""),[b,x]=y.useState(t?.k_value?$ce(t.k_value):"0.020"),[S,k]=y.useState(t?.filament_id||""),[C,P]=y.useState(t?.nozzle_id?Xat(t.nozzle_id):"HH00"),[T,A]=y.useState(t?.nozzle_diameter||n),[F,_]=y.useState(t?[t.extruder_id]:s?[0,1]:[0]),[M,H]=y.useState(!1),[I,z]=y.useState({current:0,total:0}),[L,Z]=y.useState(o),ne=pa.useMemo(()=>{const pe=new Map;for(const we of i)pe.set(we.filament_id,we.name);const he=new Map;for(const we of a)if(we.filament_id&&!he.has(we.filament_id)){const J=pe.get(we.filament_id)||Vce(we.name||"");he.set(we.filament_id,{id:we.filament_id,name:J||we.filament_id})}return Array.from(he.values()).sort((we,$)=>we.name.localeCompare($.name))},[a,i]),Y=lt({mutationFn:pe=>(console.log("[KProfile] Calling API..."),ae.setKProfile(e,pe)),onSuccess:pe=>{if(console.log("[KProfile] Save success:",pe),f(p("kProfiles.toast.profileSaved")),u&&L!==o){let he;L===""&&l?he=l:t&&t.slot_id>0?he=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:he=`name_${g}_${S}`,u(he,L)}H(!0),setTimeout(()=>{H(!1),d()},2500)},onError:pe=>{console.error("[KProfile] Save error:",pe),f(pe.message,"error"),H(!1)}}),ce=lt({mutationFn:pe=>(console.log("[KProfile] Deleting profile..."),ae.deleteKProfile(e,pe)),onSuccess:pe=>{console.log("[KProfile] Delete success:",pe),f(p("kProfiles.toast.profileDeleted")),H(!0),setTimeout(()=>{H(!1),c()},4e3)},onError:pe=>{console.error("[KProfile] Delete error:",pe),f(pe.message,"error"),H(!1)}}),[ue,oe]=y.useState(!1),Q=()=>{t&&ce.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})},le=async pe=>{if(pe.preventDefault(),s&&!t&&F.length===0){f(p("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const he=parseFloat(b).toFixed(6),we=`${C}-${T}`;if(t||F.length===1){const J={name:g,k_value:he,filament_id:S,nozzle_id:we,nozzle_diameter:T,extruder_id:t?t.extruder_id:F[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",J),Y.mutate(J);return}H(!0),z({current:1,total:F.length});const $=F.map(J=>({name:g,k_value:he,filament_id:S,nozzle_id:we,nozzle_diameter:T,extruder_id:J,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${$.length} profiles in batch:`,$);try{if(await ae.setKProfilesBatch(e,$),f(p("kProfiles.toast.profilesSaved",{count:F.length})),u&&L){const J=`name_${g}_${S}`;u(J,L)}}catch(J){console.error("[KProfile] Failed to save batch:",J),f(p("kProfiles.toast.failedToSaveBatch"),"error"),H(!1),z({current:0,total:0});return}z({current:F.length,total:F.length}),setTimeout(()=>{H(!1),z({current:0,total:0}),d()},3e3)};return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[r.jsxs(At,{className:"w-full max-w-md relative",children:[M&&r.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),r.jsx("p",{className:"text-white font-medium",children:I.total>1?p("kProfiles.modal.savingExtruder",{current:I.current,total:I.total}):p("kProfiles.modal.syncing")}),r.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:p("kProfiles.modal.pleaseWait")})]}),r.jsxs(Et,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:p(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),r.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:M,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:le,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.profileName")}),r.jsx("input",{type:"text",value:g,onChange:pe=>w(pe.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.kValue")}),r.jsx("input",{type:"text",inputMode:"decimal",value:b,onChange:pe=>{const he=pe.target.value;(he===""||/^\d*\.?\d*$/.test(he))&&x(he)},onBlur:pe=>{const he=parseFloat(pe.target.value);isNaN(he)||x((Math.trunc(he*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}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.kValueHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.filament")}),r.jsxs("select",{value:S,onChange:pe=>{const he=pe.target.value;if(k(he),!t&&he&&!g){const we=ne.find($=>$.id===he);we&&w(`${C==="HH00"?"HF":"S"} ${we.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:[r.jsx("option",{value:"",children:p("kProfiles.modal.selectFilament")}),t?.filament_id&&r.jsx("option",{value:t.filament_id,children:ne.find(pe=>pe.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&ne.map(pe=>r.jsx("option",{value:pe.id,children:pe.name},pe.id))]}),!t&&ne.length===0&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.noFilamentsHelp")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.flowType")}),r.jsxs("select",{value:C,onChange:pe=>{const he=pe.target.value;if(P(he),!t&&S&&!g){const we=ne.find($=>$.id===S);we&&w(`${he==="HS00"?"HF":"S"} ${we.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:[r.jsx("option",{value:"HH00",children:p("kProfiles.modal.highFlow")}),r.jsx("option",{value:"HS00",children:p("kProfiles.modal.standard")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.nozzleSize")}),r.jsxs("select",{value:T,onChange:pe=>A(pe.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:[r.jsx("option",{value:"0.2",children:"0.2mm"}),r.jsx("option",{value:"0.4",children:"0.4mm"}),r.jsx("option",{value:"0.6",children:"0.6mm"}),r.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?r.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")}):r.jsxs("div",{className:"flex gap-4",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:F.includes(1),onChange:pe=>{pe.target.checked?_([...F,1]):_(F.filter(he=>he!==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"}),r.jsx("span",{className:"text-white",children:p("kProfiles.modal.left")})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:F.includes(0),onChange:pe=>{pe.target.checked?_([...F,0]):_(F.filter(he=>he!==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"}),r.jsx("span",{className:"text-white",children:p("kProfiles.modal.right")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:p("kProfiles.modal.notes")}),r.jsx("textarea",{value:L,onChange:pe=>Z(pe.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:p("kProfiles.modal.notesHelp")})]}),r.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&r.jsx(je,{type:"button",variant:"secondary",onClick:()=>oe(!0),disabled:ce.isPending||M||!m("kprofiles:delete"),title:m("kprofiles:delete")?void 0:p("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:ce.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"})}),r.jsx(je,{type:"button",variant:"secondary",onClick:c,disabled:M,className:"flex-1",children:p("common.cancel")}),r.jsxs(je,{type:"submit",disabled:Y.isPending||M||!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:[Y.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(TS,{className:"w-4 h-4"}),p("common.save")]})]})]})]})]}),ue&&r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:r.jsx(At,{className:"w-full max-w-sm",children:r.jsxs(Et,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:r.jsx(en,{className:"w-5 h-5 text-red-500"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:p("kProfiles.deleteConfirm.title")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:p("kProfiles.deleteConfirm.cannotUndo")})]})]}),r.jsx("p",{className:"text-bambu-gray mb-6",children:p("kProfiles.deleteConfirm.message",{name:t?.name})}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>oe(!1),className:"flex-1",children:p("common.cancel")}),r.jsxs(je,{onClick:()=>{oe(!1),Q()},disabled:ce.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[ce.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),p("common.delete")]})]})]})})})]})}const mN={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function Zat(){const{t}=_t(),{showToast:e}=on(),{hasPermission:n}=dr(),[a,i]=y.useState(null),[s,o]=y.useState(()=>localStorage.getItem(mN.NOZZLE_DIAMETER)||"0.4"),[l,c]=y.useState(null),[d,u]=y.useState(!1),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState("all"),[x,S]=y.useState("all"),[k,C]=y.useState(()=>localStorage.getItem(mN.SORT_OPTION)||"name"),[P,T]=y.useState(!1),[A,F]=y.useState(new Set),[_,M]=y.useState(!1),[H,I]=y.useState(!1),z=y.useCallback(R=>`${R.slot_id}_${R.extruder_id}`,[]);y.useEffect(()=>{localStorage.setItem(mN.NOZZLE_DIAMETER,s)},[s]),y.useEffect(()=>{localStorage.setItem(mN.SORT_OPTION,k)},[k]);const{data:L,isLoading:Z}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:ne,isLoading:Y,isFetching:ce,error:ue,refetch:oe}=Xe({queryKey:["kprofiles",a,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",a,"nozzle",s);const R=await ae.getKProfiles(a,s);return console.log("[KProfiles] Received profiles:",R?.profiles?.length||0,"profiles"),R},enabled:!!a,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:Q}=Xe({queryKey:["kprofiles",a,"0.4"],queryFn:()=>ae.getKProfiles(a,"0.4"),enabled:!!a,staleTime:6e4}),{data:le}=Xe({queryKey:["builtinFilaments"],queryFn:()=>ae.getBuiltinFilaments(),staleTime:3e5}),{data:pe}=Xe({queryKey:["filamentIdMap"],queryFn:()=>ae.getFilamentIdMap(),staleTime:3e5}),{data:he,refetch:we}=Xe({queryKey:["kprofile-notes",a],queryFn:()=>ae.getKProfileNotes(a),enabled:!!a,staleTime:3e4}),$=ue?.message?.includes("not connected");y.useEffect(()=>{if(!a&&L&&L.length>0){const R=L.find(re=>re.is_active);R&&i(R.id)}},[a,L]),y.useEffect(()=>{if(a){const R=setTimeout(()=>{oe()},150);return()=>clearTimeout(R)}},[a,s]);const J=L?.filter(R=>R.is_active)||[],j=pa.useMemo(()=>{const R=new Map;if(le)for(const re of le)R.set(re.filament_id,re.name);if(pe)for(const[re,be]of Object.entries(pe))R.has(re)||R.set(re,be);return R},[le,pe]),E=pa.useMemo(()=>Array.from(j.entries()).map(([R,re])=>({filament_id:R,name:re})),[j]),B=pa.useCallback(R=>j.get(R.filament_id)||Vce(R.name),[j]),W=pa.useMemo(()=>ne?.profiles?ne.profiles.filter(re=>{const be=f.toLowerCase(),ye=!be||re.name.toLowerCase().includes(be)||re.filament_id.toLowerCase().includes(be),_e=w==="all"||w==="left"&&re.extruder_id===1||w==="right"&&re.extruder_id===0,xe=x==="all"||x==="hf"&&re.nozzle_id.startsWith("HH")||x==="s"&&re.nozzle_id.startsWith("HS");return ye&&_e&&xe}).sort((re,be)=>{switch(k){case"k_value":return parseFloat(re.k_value)-parseFloat(be.k_value);case"filament":return B(re).localeCompare(B(be));default:return re.name.localeCompare(be.name)}}):[],[ne?.profiles,f,w,x,k,B]),O=L?.find(R=>R.id===a),ie=O?.nozzle_count===2;y.useEffect(()=>{const R=re=>{re.target instanceof HTMLInputElement||re.target instanceof HTMLTextAreaElement||re.target instanceof HTMLSelectElement||l||d||m||(re.key==="r"||re.key==="R"?(re.preventDefault(),oe()):re.key==="n"||re.key==="N"?(re.preventDefault(),u(!0)):re.key==="Escape"&&P&&(re.preventDefault(),T(!1),F(new Set)))};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[l,d,m,P,oe]);const U=y.useCallback(()=>{if(!ne?.profiles||ne.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const R={version:1,exported_at:new Date().toISOString(),printer:O?.name||"Unknown",nozzle_diameter:s,profiles:ne.profiles.map(_e=>({name:_e.name,k_value:_e.k_value,filament_id:_e.filament_id,nozzle_id:_e.nozzle_id,nozzle_diameter:_e.nozzle_diameter,extruder_id:_e.extruder_id}))},re=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),be=URL.createObjectURL(re),ye=document.createElement("a");ye.href=be,ye.download=`kprofiles_${O?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(ye),ye.click(),document.body.removeChild(ye),URL.revokeObjectURL(be),e(t("kProfiles.toast.exportedProfiles",{count:ne.profiles.length}))},[ne?.profiles,O,s,e,t]),G=y.useCallback(()=>{const R=document.createElement("input");R.type="file",R.accept=".json",R.onchange=async re=>{const be=re.target.files?.[0];if(be)try{const ye=await be.text(),_e=JSON.parse(ye);if(!_e.profiles||!Array.isArray(_e.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let xe=0;for(const ge of _e.profiles)if(!(!ge.name||!ge.k_value||!ge.filament_id))try{await ae.setKProfile(a,{name:ge.name,k_value:parseFloat(ge.k_value).toFixed(6),filament_id:ge.filament_id,nozzle_id:ge.nozzle_id||`HH00-${s}`,nozzle_diameter:ge.nozzle_diameter||s,extruder_id:ge.extruder_id??0,slot_id:0}),xe++,await new Promise(Me=>setTimeout(Me,500))}catch(Me){console.error("Failed to import profile:",ge.name,Me)}e(t("kProfiles.toast.importedProfiles",{count:xe,total:_e.profiles.length})),oe()}catch(ye){console.error("Import error:",ye),e(t("kProfiles.toast.failedToParseImport"),"error")}},R.click()},[a,s,e,oe,t]),K=y.useCallback(R=>{F(re=>{const be=new Set(re);return be.has(R)?be.delete(R):be.add(R),be})},[]),X=y.useCallback(()=>{F(new Set(W.map(R=>z(R))))},[W,z]),se=y.useCallback(()=>{A.size!==0&&M(!0)},[A.size]),te=y.useCallback(async()=>{const R=W.filter(be=>A.has(z(be)));I(!0);let re=0;for(const be of R)try{await ae.deleteKProfile(a,{slot_id:be.slot_id,extruder_id:be.extruder_id,nozzle_id:be.nozzle_id,nozzle_diameter:be.nozzle_diameter,filament_id:be.filament_id,setting_id:be.setting_id}),re++,await new Promise(ye=>setTimeout(ye,300))}catch(ye){console.error("Failed to delete profile:",be.name,ye)}e(t("kProfiles.toast.profilesDeleted",{count:re})),I(!1),M(!1),T(!1),F(new Set),oe()},[a,A,W,e,oe,z,t]),fe=y.useCallback(R=>{const re=[];return R.setting_id&&re.push(R.setting_id),re.push(`slot_${R.slot_id}_${R.filament_id}_${R.extruder_id}`),re.push(`name_${R.name}_${R.filament_id}`),re},[]),de=y.useCallback(async(R,re)=>{if(a)try{await ae.setKProfileNote(a,R,re),we()}catch(be){console.error("Failed to save note:",be),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[a,we,e,t]),me=y.useCallback(R=>{if(!he?.notes)return{note:"",key:null};const re=fe(R);for(const be of re)if(he.notes[be])return{note:he.notes[be],key:be};return{note:"",key:null}},[he,fe]),q=y.useCallback(R=>me(R).note,[me]);return Z?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!L||L.length===0?r.jsx(At,{children:r.jsxs(Et,{className:"py-12 text-center",children:[r.jsx(Ha,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),r.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):J.length===0?r.jsx(At,{children:r.jsxs(Et,{className:"py-12 text-center",children:[r.jsx(hr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):r.jsxs(r.Fragment,{children:[ce&&!Y&&r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[r.jsx(ft,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),r.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),r.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[r.jsxs("div",{className:"flex-1 min-w-48",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),r.jsx("select",{value:a||"",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:J.map(R=>r.jsx("option",{value:R.id,children:R.name},R.id))})]}),r.jsxs("div",{className:"w-32",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),r.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:[r.jsx("option",{value:"0.2",children:"0.2mm"}),r.jsx("option",{value:"0.4",children:"0.4mm"}),r.jsx("option",{value:"0.6",children:"0.6mm"}),r.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),r.jsxs("div",{className:"flex items-end gap-2",children:[r.jsxs(je,{variant:"secondary",onClick:()=>oe(),disabled:ce||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[r.jsx(tr,{className:`w-4 h-4 ${ce?"animate-spin":""}`}),t("kProfiles.refresh")]}),r.jsxs(je,{onClick:()=>u(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[r.jsx(er,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),r.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[r.jsxs("div",{className:"flex-1 min-w-48 relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:f,onChange:R=>g(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"})]}),ie&&r.jsx("div",{className:"w-36",children:r.jsxs("select",{value:w,onChange:R=>b(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:[r.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),r.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),r.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),r.jsx("div",{className:"w-32",children:r.jsxs("select",{value:x,onChange:R=>S(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:[r.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),r.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),r.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),r.jsx("div",{className:"w-32",children:r.jsxs("select",{value:k,onChange:R=>C(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:[r.jsx("option",{value:"name",children:t("kProfiles.sortName")}),r.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),r.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[r.jsxs(je,{variant:"secondary",onClick:U,disabled:!ne?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[r.jsx(Zr,{className:"w-4 h-4"}),t("kProfiles.export")]}),r.jsxs(je,{variant:"secondary",onClick:G,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[r.jsx(_a,{className:"w-4 h-4"}),t("kProfiles.import")]}),r.jsx("div",{className:"flex-1"}),P?r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"secondary",onClick:X,children:[r.jsx(gs,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),r.jsxs(je,{variant:"secondary",onClick:se,disabled:A.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:[r.jsx(en,{className:"w-4 h-4"}),t("kProfiles.delete")," (",A.size,")"]}),r.jsxs(je,{variant:"secondary",onClick:()=>{T(!1),F(new Set)},children:[r.jsx(Vt,{className:"w-4 h-4"}),t("common.cancel")]})]}):r.jsxs(je,{variant:"secondary",onClick:()=>T(!0),disabled:!W.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[r.jsx(gs,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),Y?r.jsx("div",{className:"flex justify-center py-12",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):$?r.jsx(At,{children:r.jsxs(Et,{className:"py-12 text-center",children:[r.jsx(hu,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),r.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),r.jsxs(je,{variant:"secondary",onClick:()=>oe(),children:[r.jsx(tr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):W.length>0?ie?r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),r.jsx("div",{className:"space-y-1",children:W.filter(R=>R.extruder_id===1).map(R=>r.jsx(mF,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:P,isSelected:A.has(z(R)),onToggleSelect:()=>K(z(R)),note:q(R)},z(R)))})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),r.jsx("div",{className:"space-y-1",children:W.filter(R=>R.extruder_id===0).map(R=>r.jsx(mF,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:P,isSelected:A.has(z(R)),onToggleSelect:()=>K(z(R)),note:q(R)},z(R)))})]})]}):r.jsx("div",{className:"space-y-1",children:W.map(R=>r.jsx(mF,{profile:R,onEdit:()=>c(R),onCopy:()=>p(R),selectionMode:P,isSelected:A.has(z(R)),onToggleSelect:()=>K(z(R)),note:q(R)},z(R)))}):f||w!=="all"||x!=="all"?r.jsx(At,{children:r.jsxs(Et,{className:"py-12 text-center",children:[r.jsx(yr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),r.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):r.jsx(At,{children:r.jsxs(Et,{className:"py-12 text-center",children:[r.jsx(TS,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),r.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),r.jsxs(je,{onClick:()=>u(!0),children:[r.jsx(er,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&a&&(()=>{const{note:R,key:re}=me(l);return r.jsx(pF,{profile:l,printerId:a,nozzleDiameter:s,existingProfiles:Q?.profiles||ne?.profiles,builtinFilaments:E,isDualNozzle:ie,initialNote:R,initialNoteKey:re,onSaveNote:de,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),oe()},onSave:()=>{c(null),oe()}})})(),d&&a&&r.jsx(pF,{printerId:a,nozzleDiameter:s,existingProfiles:Q?.profiles||ne?.profiles,builtinFilaments:E,isDualNozzle:ie,onSaveNote:de,hasPermission:n,onClose:()=>{u(!1),oe()},onSave:()=>{u(!1),oe()}}),m&&a&&r.jsx(pF,{printerId:a,nozzleDiameter:s,existingProfiles:Q?.profiles||ne?.profiles,builtinFilaments:E,isDualNozzle:ie,onSaveNote:de,hasPermission:n,profile:{...m,slot_id:0,name:`${m.name} (Copy)`},onClose:()=>{p(null),oe()},onSave:()=>{p(null),oe()}}),_&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-sm",children:r.jsxs(Et,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:r.jsx(en,{className:"w-5 h-5 text-red-500"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),r.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:A.size})}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(je,{variant:"secondary",onClick:()=>M(!1),disabled:H,className:"flex-1",children:t("common.cancel")}),r.jsxs(je,{onClick:te,disabled:H,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[H?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Gce=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],Jat={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 eit(t){const e=t.toUpperCase();for(const n of Gce)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function tit(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const a of Gce){const i=n.indexOf(a);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function hF({preset:t,onDelete:e,onExpand:n,isExpanded:a}){const{t:i}=_t(),{hasPermission:s}=dr(),o=t.filament_type||eit(t.name),l=t.filament_vendor||tit(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=Jat[o.toUpperCase()]||null),r.jsx(At,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:r.jsxs(Et,{className:"p-3",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&r.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"}}),r.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&r.jsx("span",{className:"text-xs text-bambu-gray",children:l}),r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&r.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:r.jsx(en,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>n(a?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:a?r.jsx(Zo,{className:"w-3.5 h-3.5"}):r.jsx(Ln,{className:"w-3.5 h-3.5"})})]})]}),a&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),r.jsx("span",{className:"text-white",children:o})]}),l&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),r.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),r.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),r.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),r.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),r.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),r.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&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),r.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),r.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function nit(){const{t}=_t(),{hasPermission:e}=dr(),n=tn(),{showToast:a}=on(),[i,s]=y.useState(""),[o,l]=y.useState(null),[c,d]=y.useState(!1),[u,m]=y.useState(null),{data:p,isLoading:f}=Xe({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets()}),g=lt({mutationFn:async A=>{const F=[];for(const _ of Array.from(A)){const M=new FormData;M.append("file",_),F.push(await ae.importLocalPresets(M))}return F},onSuccess:A=>{n.invalidateQueries({queryKey:["localPresets"]});let F=0,_=0,M=0;for(const H of A)F+=H.imported,_+=H.skipped,M+=H.errors.length;F>0&&a(t("profiles.localProfiles.toast.importSuccess",{count:F})),_>0&&a(t("profiles.localProfiles.toast.importSkipped",{count:_}),"warning"),M>0&&a(t("profiles.localProfiles.toast.importError",{count:M}),"error")},onError:A=>{a(A.message,"error")}}),w=lt({mutationFn:A=>ae.deleteLocalPreset(A),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),m(null),a(t("profiles.localProfiles.toast.deleted"))}}),b=y.useCallback(A=>{!A||A.length===0||g.mutate(A)},[g]),x=y.useCallback(A=>{A.preventDefault(),d(!1),b(A.dataTransfer.files)},[b]),S=y.useCallback(A=>{if(!i)return A;const F=i.toLowerCase();return A.filter(_=>_.name.toLowerCase().includes(F)||_.filament_type?.toLowerCase().includes(F)||_.filament_vendor?.toLowerCase().includes(F))},[i]),k=y.useMemo(()=>S(p?.filament||[]),[p?.filament,S]),C=y.useMemo(()=>S(p?.printer||[]),[p?.printer,S]),P=y.useMemo(()=>S(p?.process||[]),[p?.process,S]),T=k.length+C.length+P.length;return f?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&r.jsxs("div",{onDragOver:A=>{A.preventDefault(),d(!0)},onDragLeave:()=>d(!1),onDrop:x,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:[r.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:A=>b(A.target.files)}),g.isPending?r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsx(ft,{className:"w-5 h-5 text-bambu-green animate-spin"}),r.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),T>0&&r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:i,onChange:A=>s(A.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"})]}),T===0&&!f&&r.jsxs("div",{className:"text-center py-12",children:[r.jsx(ib,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),r.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),r.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),T>0&&r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[k.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(kT,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),r.jsx("div",{className:"space-y-2",children:k.map(A=>r.jsx(hF,{preset:A,onDelete:F=>m(F),onExpand:l,isExpanded:o===A.id},A.id))})]}),P.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(ca,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",P.length,")"]})]}),r.jsx("div",{className:"space-y-2",children:P.map(A=>r.jsx(hF,{preset:A,onDelete:F=>m(F),onExpand:l,isExpanded:o===A.id},A.id))})]}),C.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(pu,{className:"w-4 h-4 text-orange-400"}),r.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",C.length,")"]})]}),r.jsx("div",{className:"space-y-2",children:C.map(A=>r.jsx(hF,{preset:A,onDelete:F=>m(F),onExpand:l,isExpanded:o===A.id},A.id))})]})]}),u!==null&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(Ha,{className:"w-5 h-5 text-red-400"}),r.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>m(null),children:t("profiles.localProfiles.cancel")}),r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>w.mutate(u),disabled:w.isPending,children:[w.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function cU(t,e){const n=`${t} ${e||""}`,a=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),i=a?a[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 SS(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function rit({onSuccess:t,t:e}){const{showToast:n}=on(),[a,i]=y.useState("email"),[s,o]=y.useState(""),[l,c]=y.useState(""),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState("global"),[w,b]=y.useState(null),[x,S]=y.useState(null),k=lt({mutationFn:()=>ae.cloudLogin(s,l,f),onSuccess:F=>{F.success?(n(e("profiles.login.toast.loggedIn")),t()):F.needs_verification?(b(F.verification_type||"email"),S(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")}),C=lt({mutationFn:()=>ae.cloudVerify(s,d,x||void 0,f),onSuccess:F=>{F.success?(n(e("profiles.login.toast.loggedIn")),t()):n(F.message,"error")},onError:F=>n(F.message,"error")}),P=lt({mutationFn:()=>ae.cloudSetToken(m,f),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:F=>n(F.message,"error")}),T=F=>{F.preventDefault(),a==="email"?k.mutate():a==="code"?C.mutate():a==="token"&&P.mutate()},A=k.isPending||C.isPending||P.isPending;return r.jsx(At,{className:"max-w-md mx-auto",children:r.jsxs(Et,{children:[r.jsxs("div",{className:"text-center mb-6",children:[r.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:r.jsx($h,{className:"w-6 h-6 text-bambu-green"})}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),r.jsxs("form",{onSubmit:T,className:"space-y-4",children:[a==="email"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),r.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),r.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),r.jsxs("select",{value:f,onChange:F=>g(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:[r.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),r.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),a==="code"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(w==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:w==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),r.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})]}),a==="token"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),r.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),r.jsxs("select",{value:f,onChange:F=>g(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:[r.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),r.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a==="code"&&r.jsx(je,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),r.jsxs(je,{type:"submit",disabled:A,className:"flex-1",children:[A?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(Z0,{className:"w-4 h-4"}),e(a==="email"?"profiles.login.loginButton":a==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),a==="email"&&r.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[r.jsx(bo,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),a==="token"&&r.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[r.jsx(Z0,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Rx({label:t,value:e,options:n,onChange:a}){const[i,s]=y.useState(!1),o=n.find(l=>l.value===e);return r.jsxs("div",{className:"relative",children:[r.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:[r.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),r.jsx("span",{children:o?.label||"All"}),r.jsx(Ln,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),r.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=>r.jsxs("button",{onClick:()=>{a(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:[r.jsx("span",{children:l.label}),l.count!==void 0&&r.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function ait(){const[t,e]=y.useState(!1);y.useEffect(()=>{const a=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",a),()=>window.removeEventListener("scroll",a)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?r.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:r.jsx(qm,{className:"w-5 h-5"})}):null}function fF({setting:t,onClick:e,onDuplicate:n,compareMode:a,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=cU(t.name),d=SS(t.setting_id);return r.jsxs("div",{className:"flex items-center gap-2 group",children:[r.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"} ${a&&!o?"cursor-pointer":""}`,children:r.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&r.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&&r.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),r.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),r.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:r.jsx(Ti,{className:"w-4 h-4"})})]})}function ZI(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(`
  8331. `)){const i=t.replace(/\\n/g,`
  8332. `).replace(/\\"/g,'"').replace(/\\t/g," ").split(`
  8333. `);if(i.length>1)return`"""
  8334. `+i.map(s=>n+" "+s).join(`
  8335. `)+`
  8336. `+n+'"""'}return JSON.stringify(t)}if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":`[
  8337. `+t.map(i=>n+" "+ZI(i,e+1)).join(`,
  8338. `)+`
  8339. `+n+"]";if(typeof t=="object"){const a=Object.entries(t);return a.length===0?"{}":`{
  8340. `+a.map(([s,o])=>n+" "+JSON.stringify(s)+": "+ZI(o,e+1)).join(`,
  8341. `)+`
  8342. `+n+"}"}return String(t)}function iit({setting:t,onClose:e,onDeleted:n,onDuplicate:a,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=on(),c=tn(),[d,u]=y.useState(!1),{data:m,isLoading:p}=Xe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ae.getCloudSettingDetail(t.setting_id)}),f=lt({mutationFn:()=>ae.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),g=SS(t.setting_id),w=cU(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&r.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")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),w.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:w.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.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:ZI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(Nn,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(je,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(je,{variant:"secondary",onClick:a,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(Ti,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(mi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(je,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function Wce(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Kce(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function sit({onClose:t,onApply:e,t:n}){const{showToast:a}=on(),[i,s]=y.useState(Wce),[o,l]=y.useState("all"),[c,d]=y.useState(null),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,w]=y.useState("{}"),[b,x]=y.useState(null),[S,k]=y.useState(null),C=o==="all"?i:i.filter(z=>z.type===o),P=z=>{s(z),Kce(z)},T=z=>{const L=i.filter(Z=>Z.id!==z);P(L),k(null),a(n("profiles.templates.toast.deleted"))},A=z=>{d(z.id),m(z.name),f(z.description),w(JSON.stringify(z.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const z=JSON.parse(g),L=i.map(Z=>Z.id===c?{...Z,name:u.trim(),description:p.trim(),settings:z}:Z);P(L),d(null),a(n("profiles.templates.toast.updated"))}catch(z){x(z.message)}},_=()=>{d(null),m(""),f(""),w("{}"),x(null)},M=z=>{const L=i.map(Z=>Z.id===z?{...Z,showInModal:!Z.showInModal}:Z);P(L)},H={filament:{label:n("profiles.presets.types.filament"),icon:kT,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:pu,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:hr,color:"text-purple-400"}},I=S?i.find(z=>z.id===S):null;return y.useEffect(()=>{const z=L=>{L.key==="Escape"&&(S?k(null):c?_():t())};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[S,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(At,{className:"w-full max-w-md",children:r.jsxs(Et,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(Nn,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:n("common.cancel")}),r.jsxs(je,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),r.jsx(At,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Mg,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(z=>r.jsx("button",{onClick:()=>l(z),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===z?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:z==="all"?n("common.all"):H[z].label},z))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:C.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Mg,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:n("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:C.map(z=>{const L=H[z.type],Z=L.icon;return c===z.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:ne=>m(ne.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}),r.jsx("input",{type:"text",value:p,onChange:ne=>f(ne.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"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ne=>{w(ne.target.value),x(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 ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(ds,{className:"w-4 h-4"}),"Save"]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:_,children:"Cancel"})]})]},z.id):r.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:[r.jsx(Z,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:z.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:z.description})]}),r.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(z.settings).length})}),r.jsx("button",{onClick:()=>M(z.id),className:`p-1 transition-colors ${z.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:z.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:z.showInModal?r.jsx(Cl,{className:"w-4 h-4"}):r.jsx(ab,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(z),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")}),r.jsx("button",{onClick:()=>A(z),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>k(z.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:r.jsx(en,{className:"w-4 h-4"})})]},z.id)})})})]})})]})}function Qce({onClose:t,leftPreset:e,rightPreset:n,leftLabel:a,rightLabel:i,t:s}){const[o,l]=y.useState("changes"),[c,d]=y.useState(""),u=y.useMemo(()=>{const g=new Set([...Object.keys(e),...Object.keys(n)]),w=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=n[b],k=b in e,C=b in n;let P;!k&&C?P="added":k&&!C?P="removed":JSON.stringify(x)!==JSON.stringify(S)?P="changed":P="same",w.push({key:b,left:x,right:S,status:P})}return w.sort((b,x)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[x.status]?S[b.status]-S[x.status]:b.key.localeCompare(x.key)})},[e,n]),m=y.useMemo(()=>{let g=[...u];if(o==="changes"&&(g=g.filter(w=>w.status!=="same")),c){const w=c.toLowerCase();g=g.filter(b=>b.key.toLowerCase().includes(w)||String(b.left).toLowerCase().includes(w)||String(b.right).toLowerCase().includes(w))}return g},[u,o,c]),p=y.useMemo(()=>({added:u.filter(g=>g.status==="added").length,removed:u.filter(g=>g.status==="removed").length,changed:u.filter(g=>g.status==="changed").length,same:u.filter(g=>g.status==="same").length}),[u]),f=g=>{if(g===void 0)return"—";if(g===null)return"null";if(Array.isArray(g))return g.length===0?"[]":g.length===1?String(g[0]):g.join(", ");if(typeof g=="object")return JSON.stringify(g);const w=String(g);if(w.includes("\\n")||w.length>100){const b=w.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(w.length>100)return w.substring(0,100)+"…"}return w};return y.useEffect(()=>{const g=w=>{w.key==="Escape"&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(Et,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(ey,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:a})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(er,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(rC,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(ZN,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(lE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:g=>d(g.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&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.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")}),r.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")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(lE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:a}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(g=>{const w={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[g.status],b={added:r.jsx(er,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(rC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(ZN,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(lE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[g.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${w}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[b,r.jsx("span",{className:"text-sm text-white font-mono",children:g.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="removed"?"text-red-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="added"?"text-green-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.right)})})]},g.key)})})]})})]})})})}function oit({onClose:t,initialData:e,allPresets:n,t:a}){const{showToast:i}=on(),s=tn(),o=!!e?.setting_id,[l,c]=y.useState("common"),[d,u]=y.useState(e?.type||"filament"),[m,p]=y.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,g]=y.useState(e?.base_id||""),[w,b]=y.useState(""),[x,S]=y.useState(e?.setting||{inherits:""}),[k,C]=y.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[P,T]=y.useState(null),[A,F]=y.useState(""),[_,M]=y.useState(!1),[H,I]=y.useState(""),[z,L]=y.useState(!1),[Z,ne]=y.useState(Wce),[Y,ce]=y.useState(!1),[ue,oe]=y.useState(""),[Q,le]=y.useState(""),[pe,he]=y.useState(!0),[we,$]=y.useState(null),[J,j]=y.useState(!1),E=y.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),B=y.useMemo(()=>E.filter(Re=>SS(Re.setting_id)),[E]),{data:W}=Xe({queryKey:["cloudFields",d],queryFn:()=>ae.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:O}=Xe({queryKey:["allPresetDetails",d,B.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let ze=0;ze<B.length;ze+=5){const st=B.slice(ze,ze+5);(await Promise.all(st.map(async it=>{try{const Ce=await ae.getCloudSettingDetail(it.setting_id);return{id:it.setting_id,detail:Ce}}catch{return null}}))).forEach(it=>{it&&(Re[it.id]=it.detail)})}return Re},enabled:B.length>0,staleTime:1e3*60*10}),{data:ie,isLoading:U}=Xe({queryKey:["cloudSettingDetail",f],queryFn:()=>ae.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&C(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(We=>!SS(We.setting_id)).sort((We,ze)=>We.name.localeCompare(ze.name)),[n,d]);y.useEffect(()=>{if(!f)return;const Re=G.find(We=>We.setting_id===f);Re&&(b(Re.name),o||(S({inherits:Re.name}),C(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const K=y.useMemo(()=>{const Re=W?.fields||[],We=new Set(Re.map(it=>it.key)),ze=new Set,st=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);O&&Object.values(O).forEach(it=>{it?.setting&&Object.keys(it.setting).forEach(Ce=>{!We.has(Ce)&&!st.has(Ce)&&ze.add(Ce)})}),Object.keys(x).forEach(it=>{!We.has(it)&&!st.has(it)&&ze.add(it)});const Ee=Array.from(ze).sort().map(it=>({key:it,label:it.replace(/_/g," ").replace(/\b\w/g,Ce=>Ce.toUpperCase()),type:"text",category:"discovered",description:a("profiles.presets.discoveredFromPresets")}));return[...Re,...Ee]},[W,O,x,a]),X=K.filter(Re=>Re.label.toLowerCase().includes(A.toLowerCase())||Re.key.toLowerCase().includes(A.toLowerCase())),se=()=>{if(H.trim()){const Re=H.trim().toLowerCase().replace(/\s+/g,"_");te(Re,""),I(""),L(!1),i(a("profiles.presets.toast.fieldAdded",{key:Re}))}},te=(Re,We)=>{S(ze=>{const st={...ze};return We===""||We===void 0?delete st[Re]:st[Re]=We,st})},fe=Re=>{S(We=>({...We,...Re.settings})),$(Re.name),i(a("profiles.templates.toast.applied"))},de=()=>{if(!ue.trim())return;const Re={...x};if(delete Re.inherits,Object.keys(Re).length===0){i(a("profiles.presets.noOverridesToSave"),"error");return}const We={id:Date.now().toString(),name:ue.trim(),description:Q.trim()||a("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:pe},ze=[...Z,We];ne(ze),Kce(ze),ce(!1),oe(""),le(""),he(!0),i(a("profiles.templates.toast.created"))},me=y.useMemo(()=>Z.filter(Re=>Re.type===d&&Re.showInModal),[d,Z]),q=Re=>{C(Re);try{const We=JSON.parse(Re);S(We),T(null)}catch(We){T(We.message)}},R=Re=>{Re.preventDefault(),M(!1);const We=Re.dataTransfer.files[0];if(We&&We.name.endsWith(".json")){const ze=new FileReader;ze.onload=st=>{try{const Ee=st.target?.result,it=JSON.parse(Ee),Ce=it.setting||it;S(Ze=>({...Ze,...Ce})),C(JSON.stringify({...x,...Ce},null,2)),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJsonFile"),"error")}},ze.readAsText(We)}},re=lt({mutationFn:()=>{const Re={...x},We=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[We]=`"${m}"`;const ze={type:d,name:m,base_id:f,setting:Re};return ae.createCloudSetting(ze)},onSuccess:async()=>{i(a("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),be=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(a("profiles.presets.noSettingId"));return ae.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(a("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),ye=o?be:re,_e=ie?.setting?.inherits,xe=_e?G.find(Re=>Re.name===_e):void 0,{data:ge}=Xe({queryKey:["cloudSettingDetail",xe?.setting_id],queryFn:()=>ae.getCloudSettingDetail(xe.setting_id),enabled:!!xe?.setting_id}),Me=y.useMemo(()=>{const Re=ge?.setting||{},We=ie?.setting||{},ze=f&&O?.[f]?.setting?O[f].setting:{};return{...Re,...We,...ze}},[f,ie,ge,O]),Be=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const We=[...new Set(Re.map(ze=>String(ze)))];return We.length===1?We[0]:Re.join(", ")}return String(Re)},Fe=Re=>{const We=x[Re.key],ze=Me[Re.key],st=Be(ze),Ee=U?a("common.loading"):st||"",it="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(Re.type==="boolean"){const Ce=We==="1"||We===void 0&&ze==="1";return r.jsx("button",{type:"button",onClick:()=>te(Re.key,We==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ce?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ce?"translate-x-3.5":"translate-x-0.5"}`})})}return Re.type==="select"?r.jsxs("select",{value:We||"",onChange:Ce=>te(Re.key,Ce.target.value),className:it,children:[r.jsx("option",{value:"",children:Ee}),Re.options?.map(Ce=>r.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Re.type==="number"?"number":"text",value:We!==void 0?String(We):"",onChange:Ce=>te(Re.key,Ce.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:Ee,className:it}),Re.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Oe=y.useMemo(()=>ie?.setting?ie.setting:{},[ie]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),M(!0)},onDragLeave:()=>M(!1),onDrop:R,children:[J&&f&&r.jsx(Qce,{onClose:()=>j(!1),leftPreset:Oe,rightPreset:x,leftLabel:a("profiles.presets.baseLabel",{name:w||f}),rightLabel:a("profiles.presets.currentLabel",{name:m||a("profiles.presets.newPreset")}),t:a}),r.jsx(At,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(Et,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:a(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>j(!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:a("profiles.presets.compareWithBase"),children:[r.jsx(ey,{className:"w-4 h-4"}),a("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]})]}),_&&r.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:r.jsxs("div",{className:"text-center",children:[r.jsx(_a,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:a("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("common.type")}),r.jsxs("select",{value:d,onChange:Re=>{u(Re.target.value),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:[r.jsx("option",{value:"filament",children:a("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:a("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:a("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Re=>g(Re.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:[r.jsx("option",{value:"",children:a("profiles.presets.selectBasePreset")}),G.map(Re=>r.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Re=>p(Re.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:a("profiles.presets.myCustomPreset")})]})]}),w&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}),a("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:w}),U&&r.jsx(ft,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.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:[r.jsx(h6,{className:"w-4 h-4"}),a("profiles.presets.tabs.common")]}),r.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:[r.jsx(MS,{className:"w-4 h-4"}),a("profiles.presets.tabs.allFields")]}),r.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:[r.jsx(Ky,{className:"w-4 h-4"}),"JSON",P&&r.jsx(Ha,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:x},We=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),ze=URL.createObjectURL(We),st=document.createElement("a");st.href=ze,st.download=`${m||"preset"}.json`,document.body.appendChild(st),st.click(),document.body.removeChild(st),URL.revokeObjectURL(ze),i(a("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:a("profiles.presets.exportToJson"),children:[r.jsx(Zr,{className:"w-4 h-4"}),a("common.download")]}),r.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:a("profiles.presets.importFromJson"),children:[r.jsx(_a,{className:"w-4 h-4"}),a("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const We=Re.target.files?.[0];if(We){const ze=new FileReader;ze.onload=st=>{try{const Ee=JSON.parse(st.target?.result),it=Ee.setting||Ee;S(Ce=>({...Ce,...it})),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJson"),"error")}},ze.readAsText(We)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(Mg,{className:"w-4 h-4 text-amber-400"}),a("profiles.templates.title")]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsxs("button",{onClick:()=>ce(!Y),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(ds,{className:"w-3 h-3"}),a("profiles.presets.saveAsTemplate")]})]}),Y&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:ue,onChange:Re=>oe(Re.target.value),placeholder:a("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}),r.jsx("input",{type:"text",value:Q,onChange:Re=>le(Re.target.value),placeholder:a("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"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{size:"sm",onClick:de,disabled:!ue.trim(),children:[r.jsx(ds,{className:"w-3 h-3"}),a("common.save")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>ce(!1),children:a("common.cancel")})]}),r.jsxs("button",{onClick:()=>he(!pe),className:`flex items-center gap-1.5 text-xs transition-colors ${pe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[pe?r.jsx(Cl,{className:"w-3.5 h-3.5"}):r.jsx(ab,{className:"w-3.5 h-3.5"}),a(pe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),we&&r.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:[r.jsx(Ar,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[a("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:we})]}),r.jsx("button",{onClick:()=>$(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[me.map(Re=>r.jsxs("button",{onClick:()=>fe(Re),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Re.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),me.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:a("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:a("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:K.slice(0,10).map(Re=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Re.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Fe(Re)})]},Re.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,We])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Re,": ",String(We).slice(0,20),r.jsx("button",{onClick:()=>te(Re,void 0),className:"hover:text-white",children:r.jsx(Vt,{className:"w-3 h-3"})})]},Re))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:O?a("profiles.templates.fieldsCount",{count:K.length}):a("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:A,onChange:Re=>F(Re.target.value),placeholder:a("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"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[X.filter(Re=>!(Re.key in x)).map(Re=>{const We=Me[Re.key],ze=Be(We);return r.jsxs("div",{onClick:()=>{S(st=>({...st,[Re.key]:ze||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Re.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ze&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ze,children:[ze.slice(0,20),ze.length>20?"...":""]}),r.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:r.jsx(er,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),X.filter(Re=>!(Re.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:a(A?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:z?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:H,onChange:Re=>I(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&se(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(je,{size:"sm",onClick:se,disabled:!H.trim(),children:r.jsx(er,{className:"w-4 h-4"})}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:r.jsx(Vt,{className:"w-4 h-4"})})]}):r.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:[r.jsx(er,{className:"w-4 h-4"}),a("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Re=>Re!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,We])=>{const ze=K.find(st=>st.key===Re);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:ze?.label||Re}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),r.jsx("button",{onClick:()=>te(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),ze?Fe(ze):r.jsx("input",{type:"text",value:String(We),onChange:st=>te(Re,st.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"})]},Re)}),Object.keys(x).filter(Re=>Re!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(h6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:a("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:a("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{ce(!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:[r.jsx(ds,{className:"w-4 h-4"}),a("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[P&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(Ha,{className:"w-4 h-4"}),P]}),r.jsx("textarea",{value:k,onChange:Re=>q(Re.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 ${P?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsxs(je,{onClick:()=>ye.mutate(),disabled:ye.isPending||!m.trim()||!o&&!f||!!P,className:"flex-1",children:[ye.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):o?r.jsx(ds,{className:"w-4 h-4"}):r.jsx(er,{className:"w-4 h-4"}),a(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function lit({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:a,printers:i,hasPermission:s,t:o}){const[l,c]=y.useState(""),[d,u]=y.useState("all"),[m,p]=y.useState("all"),[f,g]=y.useState("all"),[w,b]=y.useState("all"),[x,S]=y.useState("all"),[k,C]=y.useState("all"),[P,T]=y.useState(null),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState(null),[z,L]=y.useState(null),[Z,ne]=y.useState(null),[Y,ce]=y.useState(!1),[ue,oe]=y.useState([null,null]),[Q,le]=y.useState(!1),[pe,he]=y.useState(null),we=tn(),$=y.useMemo(()=>[...t.filament.map(se=>({...se,type:"filament"})),...t.printer.map(se=>({...se,type:"printer"})),...t.process.map(se=>({...se,type:"process"}))].map(se=>({...se,meta:cU(se.name)})),[t]),J=y.useMemo(()=>{const X=new Set,se=new Set,te=new Set;return $.forEach(fe=>{fe.meta.nozzle&&X.add(fe.meta.nozzle),fe.meta.filamentType&&se.add(fe.meta.filamentType),fe.meta.layerHeight&&te.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(X).sort((fe,de)=>parseFloat(fe)-parseFloat(de)),filaments:Array.from(se).sort(),layerHeights:Array.from(te).sort((fe,de)=>parseFloat(fe)-parseFloat(de))}},[$,i]),j=y.useMemo(()=>f==="all"?null:i.find(se=>se.id.toString()===f)?.model||null,[f,i]),E=y.useMemo(()=>$.filter(X=>d==="all"||X.type===d).filter(X=>{if(m==="all")return!0;const se=SS(X.setting_id);return m==="custom"?se:!se}).filter(X=>{if(f==="all"||!j)return!0;const se=X.meta.printer?.toLowerCase()||"",te=j.toLowerCase();return se.includes(te)||te.includes(se)}).filter(X=>w==="all"||X.meta.nozzle===w).filter(X=>x==="all"||X.meta.filamentType===x).filter(X=>k==="all"||X.meta.layerHeight===k).filter(X=>l===""||X.name.toLowerCase().includes(l.toLowerCase())).sort((X,se)=>X.name.localeCompare(se.name)),[$,d,m,f,j,w,x,k,l]),B=X=>{if(Y){const se=ue[0]?.setting_id===X.setting_id,te=ue[1]?.setting_id===X.setting_id;if(se)oe([ue[1],null]);else if(te)oe([ue[0],null]);else if(!ue[0])oe([X,null]);else if(ue[1]){if(ue[0].type!==X.type)return;oe([ue[0],X])}else{if(ue[0].type!==X.type)return;oe([ue[0],X])}}else T(X)},W=X=>{if(ue[0]?.setting_id===X.setting_id)return 0;if(ue[1]?.setting_id===X.setting_id)return 1},O=async X=>{try{const se=await ae.getCloudSettingDetail(X.setting_id),te=X.type==="process"?"print":X.type;I({type:te,name:X.name,base_id:se.base_id||"GFSA00",setting:se.setting||{}}),T(null)}catch(se){console.error("Failed to fetch preset details for duplication:",se)}},ie=async X=>{try{we.removeQueries({queryKey:["cloudSettingDetail",X.setting_id]});const se=await ae.getCloudSettingDetail(X.setting_id),te=X.type==="process"?"print":X.type;L({type:te,name:X.name,base_id:se.base_id||"GFSA00",setting:se.setting||{},setting_id:X.setting_id}),T(null)}catch(se){console.error("Failed to fetch preset details for editing:",se)}},U=()=>{u("all"),p("all"),g("all"),b("all"),S("all"),C("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||w!=="all"||x!=="all"||k!=="all"||l!=="",K=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:X=>c(X.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"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(je,{variant:Y?"primary":"secondary",onClick:()=>{Y?(ce(!1),oe([null,null])):ce(!0)},children:[r.jsx(ey,{className:"w-4 h-4"}),o(Y?"common.cancel":"profiles.presets.compare")]}),r.jsxs(je,{variant:"secondary",onClick:()=>M(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Mg,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(je,{variant:"secondary",onClick:n,disabled:a||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(tr,{className:`w-4 h-4 ${a?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(je,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(er,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(PS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(Rx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:K},{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:X=>u(X)}),r.jsx(Rx,{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:X=>p(X)}),J.printers.length>0&&r.jsx(Rx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.printers.map(X=>({value:X.id,label:X.name}))],onChange:g}),J.nozzles.length>0&&r.jsx(Rx,{label:o("profiles.cloudView.filters.nozzle"),value:w,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.nozzles.map(X=>({value:X,label:X}))],onChange:b}),J.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(Rx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.filaments.map(X=>({value:X,label:X}))],onChange:S}),J.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(Rx,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.layerHeights.map(X=>({value:X,label:X}))],onChange:C}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Y&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(ey,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:ue[0]?o("profiles.cloudView.selectAnotherPreset",{type:ue[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${ue[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:ue[0]?ue[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(ZN,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${ue[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:ue[1]?ue[1].name:o("profiles.cloudView.selectSecond")})]}),ue[0]&&ue[1]&&r.jsxs(je,{size:"sm",onClick:async()=>{try{const[X,se]=await Promise.all([ae.getCloudSettingDetail(ue[0].setting_id),ae.getCloudSettingDetail(ue[1].setting_id)]);he([X.setting||{},se.setting||{}]),le(!0)}catch{}},children:[r.jsx(ey,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Eh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.length,total:K})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),E.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(ca,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:U,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(kT,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(X=>X.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(X=>X.type==="filament").map(X=>r.jsx(fF,{setting:X,onClick:()=>B(X),onDuplicate:()=>O(X),compareMode:Y,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Y&&!!ue[0]&&ue[0].type!==X.type,t:o},X.setting_id)),E.filter(X=>X.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(pu,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(X=>X.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(X=>X.type==="process").map(X=>r.jsx(fF,{setting:X,onClick:()=>B(X),onDuplicate:()=>O(X),compareMode:Y,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Y&&!!ue[0]&&ue[0].type!==X.type,t:o},X.setting_id)),E.filter(X=>X.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(hr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",E.filter(X=>X.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(X=>X.type==="printer").map(X=>r.jsx(fF,{setting:X,onClick:()=>B(X),onDuplicate:()=>O(X),compareMode:Y,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Y&&!!ue[0]&&ue[0].type!==X.type,t:o},X.setting_id)),E.filter(X=>X.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),P&&r.jsx(iit,{setting:P,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>O(P),onEdit:()=>ie(P),hasPermission:s,t:o}),(A||H||z||Z)&&r.jsx(oit,{onClose:()=>{F(!1),I(null),L(null),ne(null)},initialData:z||H||(Z?{type:Z.type,name:"",base_id:"",setting:Z.setting}:void 0),allPresets:t,t:o}),_&&r.jsx(sit,{onClose:()=>M(!1),onApply:X=>{ne({type:X.type,setting:X.settings}),M(!1)},t:o}),Q&&pe&&ue[0]&&ue[1]&&r.jsx(Qce,{onClose:()=>{le(!1),he(null)},leftPreset:pe[0],rightPreset:pe[1],leftLabel:ue[0].name,rightLabel:ue[1].name,t:o})]})}function cit(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a}=dr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=Xe({queryKey:["cloudStatus"],queryFn:ae.getCloudStatus}),{data:u=[]}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=Xe({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const w=lt({mutationFn:ae.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx($h,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.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:[r.jsx($h,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),r.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:[r.jsx(ib,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.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:[r.jsx(TS,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!a("cloud:auth"),title:a("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(ty,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(lit,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:a,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(je,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(rit,{onSuccess:b,t})]}),i==="local"&&r.jsx(nit,{}),i==="kprofiles"&&r.jsx(Zat,{}),r.jsx(ait,{})]})}function dit(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),a=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"),p=n.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"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 a||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":f?"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 a?"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":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return a||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 a||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}}const K0={Droplet:kT,Flame:pm,Ruler:hye,Sparkles:Mg,Square:ro,Cable:xO,Wrench:Gh,Calendar:wa,Timer:Zd,Cog:uu,Fan:IZ,Zap:wc,Wind:ZZ,Thermometer:RS,Layers:ca,Box:Si,Target:KZ,RefreshCw:tr,Settings:xy,Filter:PS,CircleDot:xge};function Sw(t){return t&&K0[t]||Gh}function Ix(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 a=Math.round(t/30);return a===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:a}):`${a} 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 a=t/24;if(a<7)return`${a<2?a.toFixed(1):Math.round(a)}d`;const i=a/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function gF(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 uit({item:t,onPerform:e,onToggle:n,hasPermission:a,t:i}){const s=Sw(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:Ix(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ix(f,"days",i)}):i("maintenance.timeLeft",{duration:Ix(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ix(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ix(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ix(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.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:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.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`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(wa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||dit(t.maintenance_type_name,t.printer_model);return f?r.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:g=>g.stopPropagation(),children:r.jsx(zr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(Nn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(Zn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(Ar,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:a("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(En,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!a("maintenance:update")})}),r.jsxs(je,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!a("maintenance:update"),title:a("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(fs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function mit({overview:t,onPerform:e,onToggle:n,onSetHours:a,hasPermission:i,t:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((w,b)=>w.is_due&&!b.is_due?-1:!w.is_due&&b.is_due?1:w.is_warning&&!b.is_warning?-1:!w.is_warning&&b.is_warning?1:w.maintenance_type_id-b.maintenance_type_id),f=p.find(w=>w.enabled&&(w.is_due||w.is_warning)),g=()=>{const w=parseFloat(u);!isNaN(w)&&w>=0&&(a(t.printer_id,w),d(!1))};return r.jsxs(At,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.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:[r.jsx(Nn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.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:[r.jsx(Zn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.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:[r.jsx(Ar,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.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?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(Zd,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&g(),w.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}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(je,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.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:[r.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"),r.jsx(jg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const w=Sw(f.maintenance_type_icon);return r.jsx(w,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.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&&r.jsx(Et,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(w=>r.jsx(uit,{item:w,onPerform:e,onToggle:n,hasPermission:i,t:s},w.id))})})]})}function pit({overview:t,types:e,onUpdateInterval:n,onAddType:a,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=y.useState(null),[g,w]=y.useState(""),[b,x]=y.useState("hours"),[S,k]=y.useState(!1),[C,P]=y.useState(""),[T,A]=y.useState("100"),[F,_]=y.useState("hours"),[M,H]=y.useState("Wrench"),[I,z]=y.useState(""),[L,Z]=y.useState(new Set),[ne,Y]=y.useState(null),[ce,ue]=y.useState(null),oe=y.useMemo(()=>t?t.map(q=>({id:q.printer_id,name:q.printer_name})):[],[t]),Q=q=>t?t.filter(R=>R.maintenance_items.some(re=>re.maintenance_type_id===q)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(re=>re.maintenance_type_id===q)?.id})):[],le=q=>{if(!t)return[];const R=new Set(Q(q).map(re=>re.printerId));return oe.filter(re=>!R.has(re.id))},[pe,he]=y.useState(null),[we,$]=y.useState(""),[J,j]=y.useState(""),[E,B]=y.useState("hours"),[W,O]=y.useState("Wrench"),[ie,U]=y.useState(""),G=q=>{he(q),$(q.name),j(q.default_interval_hours.toString()),B(q.interval_type||"hours"),O(q.icon||"Wrench"),U(q.wiki_url||"")},K=()=>{pe&&we.trim()&&parseFloat(J)>0&&(i(pe.id,{name:we.trim(),default_interval_hours:parseFloat(J),interval_type:E,icon:W,wiki_url:ie.trim()||null}),he(null))},X=(q,R,re)=>{const be=parseFloat(g);if(!isNaN(be)&&be>0){const ye=Math.abs(be-R)<.01?null:be;n(q,{custom_interval_hours:ye,custom_interval_type:b!==re?b:null})}f(null)},se=q=>{q.preventDefault(),C.trim()&&parseFloat(T)>0&&L.size>0&&(a({name:C.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:M,wiki_url:I.trim()||null},Array.from(L)),P(""),A("100"),_("hours"),z(""),Z(new Set),k(!1))},te=q=>{Z(R=>{const re=new Set(R);return re.has(q)?re.delete(q):re.add(q),re})},fe=t?.map(q=>({printerId:q.printer_id,printerName:q.printer_name,items:q.maintenance_items.sort((R,re)=>R.maintenance_type_id-re.maintenance_type_id)})).sort((q,R)=>q.printerName.localeCompare(R.printerName))||[],de=e.filter(q=>q.is_system),me=e.filter(q=>!q.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(je,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(je,{onClick:()=>k(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(er,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(At,{className:"mb-6",children:r.jsx(Et,{className:"py-4",children:r.jsxs("form",{onSubmit:se,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:C,onChange:q=>P(q.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:F,onChange:q=>{_(q.target.value),q.target.value==="days"?A("30"):A("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:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.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")})}),r.jsx("input",{type:"number",value:T,onChange:q=>A(q.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"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(K0).map(q=>{const R=K0[q];return r.jsx("button",{type:"button",onClick:()=>H(q),className:`p-2 rounded-lg transition-colors ${M===q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(R,{className:"w-4 h-4"})},q)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:I,onChange:q=>z(q.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/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:oe.map(q=>r.jsx("button",{type:"button",onClick:()=>te(q.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(q.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:q.name},q.id))}),L.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:()=>{k(!1),Z(new Set)},children:m("common.cancel")}),r.jsx(je,{type:"submit",disabled:!C.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[de.map(q=>{const R=Sw(q.icon),re=q.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:q.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[re==="days"?r.jsx(wa,{className:"w-3 h-3"}):r.jsx(Zd,{className:"w-3 h-3"}),gF(q.default_interval_hours,re,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&ue(q)},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:r.jsx(en,{className:"w-4 h-4"})})]})},q.id)}),me.map(q=>{const R=Sw(q.icon),re=q.interval_type||"hours";if(pe?.id===q.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:we,onChange:ge=>$(ge.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}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:E,onChange:ge=>B(ge.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:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:J,onChange:ge=>j(ge.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"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(K0).map(ge=>{const Me=K0[ge];return r.jsx("button",{type:"button",onClick:()=>O(ge),className:`p-1.5 rounded transition-colors ${W===ge?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Me,{className:"w-3.5 h-3.5"})},ge)})}),r.jsx("input",{type:"url",value:ie,onChange:ge=>U(ge.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")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{size:"sm",onClick:K,disabled:!we.trim(),children:m("common.save")}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>he(null),children:m("common.cancel")})]})]})},q.id);const ye=Q(q.id),_e=le(q.id),xe=ne===q.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:q.name}),r.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")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[re==="days"?r.jsx(wa,{className:"w-3 h-3"}):r.jsx(Zd,{className:"w-3 h-3"}),gF(q.default_interval_hours,re,m)]})]}),r.jsxs("button",{onClick:()=>Y(xe?null:q.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${ye.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:ye.length}),children:[r.jsx(hr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:ye.length}),r.jsx(Ln,{className:`w-3 h-3 transition-transform ${xe?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G(q),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:r.jsx(jg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:q.name}))&&s(q.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:r.jsx(en,{className:"w-4 h-4"})})]}),xe&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),ye.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:ye.map(ge=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ge.printerName,r.jsx("button",{onClick:()=>ge.itemId&&d(ge.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:"×"})]},ge.printerId))}),_e.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),_e.map(ge=>r.jsxs("button",{onClick:()=>c(ge.id,q.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:["+ ",ge.name]},ge.id))]})]})]},q.id)})]})]}),fe.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:fe.map(q=>r.jsx(At,{children:r.jsxs(Et,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:q.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:q.items.map(R=>{const re=Sw(R.maintenance_type_icon),be=e.find(Me=>Me.id===R.maintenance_type_id),ye=be?.default_interval_hours||R.interval_hours,_e=be?.interval_type||"hours",xe=R.interval_type||"hours",ge=p===R.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(re,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),ge?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(wa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(Zd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:b,onChange:Me=>x(Me.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:g,onChange:Me=>w(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&X(R.id,ye,_e),Me.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"}),r.jsx(je,{size:"sm",onClick:()=>X(R.id,ye,_e),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),w(R.interval_hours.toString()),x(xe))},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:[xe==="days"?r.jsx(wa,{className:"w-3 h-3"}):r.jsx(Zd,{className:"w-3 h-3"}),gF(R.interval_hours,xe,m),r.jsx(jg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},q.printerId))})]}),fe.length===0&&r.jsx(At,{children:r.jsxs(Et,{className:"text-center py-12",children:[r.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ce&&r.jsx(wn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ce.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(ce.id),ue(null)},onCancel:()=>ue(null)})]})}function hit(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a}=dr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=Xe({queryKey:["maintenanceOverview"],queryFn:ae.getMaintenanceOverview}),{data:c}=Xe({queryKey:["maintenanceTypes"],queryFn:ae.getMaintenanceTypes}),d=lt({mutationFn:({id:T,notes:A})=>ae.performMaintenance(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),u=lt({mutationFn:({id:T,data:A})=>ae.updateMaintenanceItem(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),m=lt({mutationFn:({id:T,data:A})=>ae.updateMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),p=lt({mutationFn:ae.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),f=lt({mutationFn:ae.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),g=lt({mutationFn:({printerId:T,hours:A})=>ae.setPrinterHours(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),w=lt({mutationFn:({printerId:T,typeId:A})=>ae.assignMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),b=lt({mutationFn:ae.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,A)=>{u.mutate({id:T,data:{enabled:A}})},k=(T,A)=>{g.mutate({printerId:T,hours:A})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});const C=o?.reduce((T,A)=>T+A.due_count,0)||0,P=o?.reduce((T,A)=>T+A.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Gh,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[C>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:C})}),C>0&&P>0&&" · ",P>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:P})}),C===0&&P===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.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")}),r.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"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,A)=>{const F=T.due_count*10+T.warning_count,_=A.due_count*10+A.warning_count;return F!==_?_-F:T.printer_name.localeCompare(A.printer_name)}).map(T=>r.jsx(mit,{overview:T,onPerform:x,onToggle:S,onSetHours:k,hasPermission:a,t},T.printer_id)):r.jsx(At,{children:r.jsxs(Et,{className:"text-center py-16",children:[r.jsx(Gh,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx(pit,{overview:o,types:c||[],onUpdateInterval:(T,A)=>u.mutate({id:T,data:A}),onAddType:async(T,A)=>{const F=await ae.createMaintenanceType(T);for(const _ of A)await ae.assignMaintenanceType(_,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,A)=>m.mutate({id:T,data:A}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,A)=>w.mutate({printerId:T,typeId:A}),onRemoveItem:T=>b.mutate(T),hasPermission:a,t})]})}const vX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Yce({project:t,onClose:e,onSave:n,isLoading:a,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||vX[0]),[p,f]=y.useState(t?.target_count?.toString()||""),[g,w]=y.useState(t?.target_parts_count?.toString()||""),[b,x]=y.useState(t?.status||"active"),[S,k]=y.useState(t?.tags||""),[C,P]=y.useState(t?.due_date?.split("T")[0]||""),[T,A]=y.useState(t?.priority||"normal"),[F,_]=y.useState(t?.budget?.toString()||""),[M,H]=y.useState(t?.url||""),[I,z]=y.useState(null),L=tn(),[Z,ne]=y.useState(t?.cover_image_filename||null),Y=y.useRef(null),[ce,ue]=y.useState(!1),[oe,Q]=y.useState(0),le=async we=>{const $=we.target.files?.[0];if(!(!$||!t)){ue(!0);try{const J=await ae.uploadProjectCoverImage(t.id,$);ne(J.filename),Q(j=>j+1),L.invalidateQueries({queryKey:["projects"]})}catch{}finally{ue(!1),Y.current&&(Y.current.value="")}}},pe=async()=>{if(t){ue(!0);try{await ae.deleteProjectCoverImage(t.id),ne(null),Q(we=>we+1),L.invalidateQueries({queryKey:["projects"]})}finally{ue(!1)}}},he=we=>{we.preventDefault();const $=M.trim();if($&&!/^https?:\/\//i.test($)){z(s("projects.urlInvalid"));return}z(null),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:g?parseInt(g,10):void 0,tags:S.trim()||void 0,due_date:C||void 0,priority:T,budget:F.trim()?parseFloat(F):null,url:t?$||null:$||void 0,...t&&{status:b}})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:he,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:we=>l(we.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:we=>d(we.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})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:M,onChange:we=>{H(we.target.value),I&&z(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${I?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),I&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:I})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:Z?r.jsx("img",{src:`${ae.getProjectCoverImageUrl(t.id)}?v=${oe}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(mu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Y,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:le,className:"hidden"}),r.jsxs(je,{type:"button",variant:"secondary",onClick:()=>Y.current?.click(),disabled:ce,children:[ce?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(_a,{className:"w-4 h-4 mr-1"}),s(Z?"projects.coverImageReplace":"projects.coverImageUpload")]}),Z&&r.jsxs(je,{type:"button",variant:"secondary",onClick:pe,disabled:ce,children:[r.jsx(Vt,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:vX.map(we=>r.jsx("button",{type:"button",onClick:()=>m(we),className:`w-8 h-8 rounded-full transition-transform ${u===we?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:we}},we))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:we=>f(we.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:g,onChange:we=>w(we.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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:S,onChange:we=>k(we.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")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:C,onChange:we=>P(we.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:we=>A(we.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:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:we=>_(we.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&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:b,onChange:we=>x(we.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:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(je,{type:"submit",disabled:!o.trim()||a,children:a?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function fit({projectId:t,altText:e}){const n=y.useRef(null),[a,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!n.current)return;const d=n.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let g=d.right+m;g+u>p-8&&(g=d.left-u-m);let w=d.top;w+u>f-8&&(w=f-u-8),w<8&&(w=8),o({left:g,top:w}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:n,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:ae.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),a&&s&&cc.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:ae.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function git({project:t,onClick:e,onEdit:n,onDelete:a,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]=y.useState(!1),f=c?{icon:yl,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:eo,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Zn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:to,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.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:[r.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`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(fit,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(zr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.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?r.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?r.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&&r.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&&r.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&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const g=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(Boolean),w=[...new Set(g)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),x=[...new Set(b)];return w.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[w.slice(0,3).map(S=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(S=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:g=>g.stopPropagation(),children:[r.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:r.jsx(vm,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.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:[r.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:[r.jsx(jg,{className:"w-4 h-4"}),s("common.edit")]}),r.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")&&(a(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.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&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.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&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(eo,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(g=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:g.print_name||"Unknown",children:[g.thumbnail_path?r.jsx("img",{src:ae.getArchiveThumbnail(g.id),alt:g.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(Vr,{className:"w-6 h-6"})}),g.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(Nn,{className:"w-4 h-4 text-white"})})]},g.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(ca,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(Vr,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(WF,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(qa,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function bit(){const{t}=_t(),e=ji(),n=tn(),{showToast:a}=on(),{hasPermission:i}=dr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),g=Ho(f?.currency||"USD"),{data:w,isLoading:b}=Xe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>ae.getProjects(d==="all"?void 0:d)}),x=lt({mutationFn:Z=>ae.createProject(Z),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),a(t("projects.toast.created"),"success")},onError:Z=>{a(Z.message,"error")}}),S=lt({mutationFn:({id:Z,data:ne})=>ae.updateProject(Z,ne),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),a(t("projects.toast.updated"),"success")},onError:Z=>{a(Z.message,"error")}}),k=lt({mutationFn:Z=>ae.deleteProject(Z),onSuccess:()=>{p(null),a(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:Z=>{p(null),a(Z.message,"error")}}),C=lt({mutationFn:Z=>ae.importProject(Z),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success")},onError:Z=>{a(Z.message,"error")}}),P=y.useRef(null),T=async()=>{try{const Z=await ae.getProjects(),ne=await Promise.all(Z.map(async oe=>await ae.exportProjectJson(oe.id))),Y=new Blob([JSON.stringify(ne,null,2)],{type:"application/json"}),ce=URL.createObjectURL(Y),ue=document.createElement("a");ue.href=ce,ue.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,ue.click(),URL.revokeObjectURL(ce),a(t("projects.toast.exported"),"success")}catch(Z){a(Z.message,"error")}},A=()=>{P.current?.click()},F=async Z=>{const ne=Z.target.files?.[0];if(ne){try{if(ne.name.toLowerCase().endsWith(".zip"))await ae.importProjectFile(ne),n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success");else{const ce=await ne.text(),ue=JSON.parse(ce),oe=Array.isArray(ue)?ue:[ue];for(const Q of oe)await C.mutateAsync(Q);oe.length>1&&a(t("projects.toast.multipleImported",{count:oe.length}),"success")}}catch(Y){a(`${t("projects.toast.importFailed")}: ${Y.message}`,"error")}Z.target.value=""}},_=Z=>{l?S.mutate({id:l.id,data:Z}):x.mutate(Z)},M=Z=>{c(Z),o(!0)},H=Z=>{e(`/projects/${Z.id}`)},I=Z=>{p(Z)},z=()=>{m!==null&&k.mutate(m)},L=w?.reduce((Z,ne)=>(Z[ne.status]=(Z[ne.status]||0)+1,Z.all=(Z.all||0)+1,Z),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:P,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(to,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",onClick:A,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(_a,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(je,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Zr,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(je,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(er,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Zn},{key:"completed",label:t("projects.statusCompleted"),icon:yl},{key:"archived",label:t("projects.statusArchived"),icon:eo},{key:"all",label:t("common.all"),icon:to}].map(({key:Z,label:ne,icon:Y})=>r.jsxs("button",{onClick:()=>u(Z),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===Z?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Y,{className:"w-4 h-4"}),r.jsx("span",{children:ne}),L[Z]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===Z?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[Z]})]},Z))}),b?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):w?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(to,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.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"&&r.jsxs(je,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(er,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:w?.map(Z=>r.jsx(git,{project:Z,onClick:()=>H(Z),onEdit:()=>M(Z),onDelete:()=>I(Z.id),hasPermission:i,t},Z.id))}),m!==null&&r.jsx(wn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:z,onCancel:()=>p(null)}),s&&r.jsx(Yce,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:_,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function xit(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function yit(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function vit({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"},a=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${a}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function wX({icon:t,label:e,value:n,subValue:a,hint:i,color:s="text-bambu-gray"}){return r.jsx(At,{children:r.jsx(Et,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:n}),a&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a})]})]})})})}function wit({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(Vr,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.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=>r.jsxs(Es,{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?r.jsx("img",{src:ae.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(Vr,{className:"w-8 h-8"})}),n.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx($r,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(xr,{className:"w-4 h-4 text-bambu-green"})}),r.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:r.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function Sit({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:a,label:i}=n[t]||n.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${a}`,children:[t==="urgent"&&r.jsx(Nn,{className:"w-3 h-3"}),i]})}function bF(t,e){if(!t)return null;const n=Yn(t);if(!n)return null;const a=new Date,i=Math.ceil((n.getTime()-a.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 _it(){const{id:t}=NS(),e=ji(),{t:n}=_t(),a=tn(),{showToast:i}=on(),{hasPermission:s}=dr(),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(null),[g,w]=y.useState(null),b=parseInt(t||"0",10),{data:x,isLoading:S,error:k}=Xe({queryKey:["project",b],queryFn:()=>ae.getProject(b),enabled:b>0}),{data:C,isLoading:P}=Xe({queryKey:["project-archives",b],queryFn:()=>ae.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:A}=Xe({queryKey:["project-bom",b],queryFn:()=>ae.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:_}=Xe({queryKey:["project-timeline",b],queryFn:()=>ae.getProjectTimeline(b,20),enabled:b>0}),{data:M}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:H}=Xe({queryKey:["project-folders",b],queryFn:()=>ae.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:z}=Xe({queryKey:["project-files",b],queryFn:()=>ae.getLibraryFiles(null,!1,b),enabled:b>0}),L=y.useMemo(()=>{const ke=new Map;for(const Ve of I??[])if(Ve.folder_id!=null){const rt=ke.get(Ve.folder_id)??[];rt.push(Ve),ke.set(Ve.folder_id,rt)}return ke},[I]),Z=Ho(M?.currency||"USD"),ne=M?.time_format||"system",Y=lt({mutationFn:ke=>ae.updateProject(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project",b]}),a.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:ke=>{i(ke.message,"error")}}),ce=()=>{m(x?.notes||""),d(!0)},ue=()=>{Y.mutate({notes:u})},oe=()=>{d(!1),m("")},[Q,le]=y.useState(""),[pe,he]=y.useState(1),[we,$]=y.useState(""),[J,j]=y.useState(""),[E,B]=y.useState(""),[W,O]=y.useState(!1),[ie,U]=y.useState(!1),[G,K]=y.useState(null),[X,se]=y.useState(""),[te,fe]=y.useState(1),[de,me]=y.useState(""),[q,R]=y.useState(""),[re,be]=y.useState(""),[ye,_e]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),xe=lt({mutationFn:ke=>ae.createBOMItem(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),le(""),he(1),$(""),j(""),B(""),O(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:ke=>i(ke.message,"error")}),ge=lt({mutationFn:({itemId:ke,data:Ve})=>ae.updateBOMItem(b,ke,Ve),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),K(null)},onError:ke=>i(ke.message,"error")}),Me=lt({mutationFn:ke=>ae.deleteBOMItem(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:ke=>i(ke.message,"error")}),Be=ke=>{ke.preventDefault(),Q.trim()&&xe.mutate({name:Q.trim(),quantity_needed:pe,unit_price:we?parseFloat(we):void 0,sourcing_url:J.trim()||void 0,remarks:E.trim()||void 0})},Fe=ke=>{const Ve=ke.is_complete?0:ke.quantity_needed;ge.mutate({itemId:ke.id,data:{quantity_acquired:Ve}})},Oe=(ke,Ve)=>{_e({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ve}),onConfirm:()=>{_e(rt=>({...rt,isOpen:!1})),Me.mutate(ke)}})},Re=ke=>{K(ke),se(ke.name),fe(ke.quantity_needed),me(ke.unit_price?.toString()||""),R(ke.sourcing_url||""),be(ke.remarks||"")},We=ke=>{ke.preventDefault(),!(!G||!X.trim())&&ge.mutate({itemId:G.id,data:{name:X.trim(),quantity_needed:te,unit_price:de?parseFloat(de):void 0,sourcing_url:q.trim()||void 0,remarks:re.trim()||void 0}})},ze=()=>{K(null)},st=async()=>{try{const{blob:ke,filename:Ve}=await ae.exportProjectZip(Number(b)),rt=URL.createObjectURL(ke),Qe=document.createElement("a");Qe.href=rt,Qe.download=Ve||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Qe.click(),URL.revokeObjectURL(rt),i(n("projectDetail.toast.projectExported"),"success")}catch(ke){i(ke.message,"error")}},Ee=lt({mutationFn:()=>ae.createTemplateFromProject(b),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:ke=>i(ke.message,"error")}),it=ke=>Fg(ke,ne,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(S)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(k||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:k?`${n("common.error")}: ${k.message}`:n("projectDetail.notFound")}),r.jsx(je,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Ce=x.stats,Ze=Ce?.progress_percent??0,Ie=Ce?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Es,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),r.jsx(qa,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(ST,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(vit,{status:x.status,t:n})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",onClick:st,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[r.jsx(Zr,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),r.jsxs(je,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[r.jsx(jg,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(At,{children:r.jsxs(Et,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ce?.total_archives||0," / ",x.target_count," ",n("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ze,100)}%`,backgroundColor:Ze>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ze.toFixed(0)})}),Ce?.remaining_prints!=null&&Ce.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ce.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ce?.completed_prints||0," / ",x.target_parts_count," ",n("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ie,100)}%`,backgroundColor:Ie>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ie.toFixed(0)})}),Ce?.remaining_parts!=null&&Ce.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ce.remaining_parts})})]})]})]})}),Ce&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(At,{children:r.jsx(Et,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(Vr,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Ce.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Ce.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Ce.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Ce.completed_prints})})]})]})})}),r.jsx(wX,{icon:Zn,label:n("projectDetail.stats.printTime"),value:e0e(Ce.total_print_time_hours),color:"text-yellow-400"}),r.jsx(wX,{icon:hr,label:n("projectDetail.stats.filamentUsed"),value:yit(Ce.total_filament_grams),color:"text-purple-400"})]}),Ce&&(()=>{const ke=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost;return Ce.estimated_cost>0||ke>0||x.budget!==null})()&&r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Z,Ce.estimated_cost.toFixed(2)]})]}),Ce.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Ce.total_energy_kwh.toFixed(3)," kWh",Ce.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",Z,Ce.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const ke=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost;return ke<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[Z,ke.toFixed(2)]}),Ce.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const ke=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost,Ve=x.budget-ke;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[Z,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Ve>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[Z,Ve.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(Mbe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(ke=>r.jsxs(Es,{to:`/projects/${ke.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ke.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:ke.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ke.status==="completed"?"bg-status-ok/20 text-status-ok":ke.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ke.status})]}),ke.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[ke.progress_percent.toFixed(0),"%"]})]},ke.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ca,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),r.jsx(Es,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),r.jsx(Sit,{priority:x.priority,t:n})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(wa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:Dg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),bF(x.due_date,n)&&r.jsxs("span",{className:`text-xs ${bF(x.due_date,n).color}`,children:["(",bF(x.due_date,n).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Vm,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((ke,Ve)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ke.trim()},Ve))})]})]}),r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Rs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:oe,disabled:Y.isPending,children:[r.jsx(Vt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),r.jsxs(je,{size:"sm",onClick:ue,disabled:Y.isPending,children:[Y.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(ds,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:ce,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[r.jsx(jg,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?r.jsx($I,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:h5.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Pl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Es,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),H&&H.length>0?r.jsx("div",{className:"space-y-4",children:H.map(ke=>{const Ve=L.get(ke.id)??[],rt=z;return r.jsxs("div",{children:[r.jsxs(Es,{to:`/files?folder=${ke.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Pl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:ke.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ke.file_count})})]})]}),r.jsx(qa,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),rt?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(ft,{className:"w-4 h-4 animate-spin"})}):Ve.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Ve.map(Qe=>{const Te=xit(Qe.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Qe.thumbnail_path?r.jsx("img",{src:ae.getLibraryFileThumbnailUrl(Qe.id),alt:Qe.print_name||Qe.filename,className:"w-full h-full object-cover"}):r.jsx(Ph,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:Qe.print_name||Qe.filename,children:Qe.print_name||Qe.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Qe.file_type.toUpperCase()})]}),Te&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(Qe),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(hs,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>w(Qe),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(Zfe,{className:"w-4 h-4"})})]})]},Qe.id)})})]},ke.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(sb,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Ce&&Ce.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Ce.bom_completed_items,total:Ce.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(ke=>ke.is_complete)&&r.jsx("button",{onClick:()=>U(!ie),className:`text-xs px-2 py-1 rounded transition-colors ${ie?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ie?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>O(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[r.jsx(er,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:Be,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:Q,onChange:ke=>le(ke.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}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:pe,onChange:ke=>he(parseInt(ke.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")}),r.jsx("input",{type:"number",step:"0.01",value:we,onChange:ke=>$(ke.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:Z})})]})]}),r.jsx("input",{type:"url",value:J,onChange:ke=>j(ke.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")}),r.jsx("input",{type:"text",value:E,onChange:ke=>B(ke.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")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:()=>O(!1),children:n("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!Q.trim()||xe.isPending,children:xe.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),A?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(ke=>!ie||!ke.is_complete).map(ke=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${ke.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===ke.id?r.jsxs("form",{onSubmit:We,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:X,onChange:Ve=>se(Ve.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}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:te,onChange:Ve=>fe(parseInt(Ve.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")}),r.jsx("input",{type:"number",step:"0.01",value:de,onChange:Ve=>me(Ve.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:Z})})]})]}),r.jsx("input",{type:"url",value:q,onChange:Ve=>R(Ve.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")}),r.jsx("input",{type:"text",value:re,onChange:Ve=>be(Ve.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")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:ze,children:n("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!X.trim()||ge.isPending,children:ge.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Fe(ke),disabled:ge.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 ${ke.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:ke.is_complete&&r.jsx(xr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${ke.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ke.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ke.quantity_needed]})]}),ke.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[Z,(ke.unit_price*ke.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Re(ke),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:r.jsx(mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Oe(ke.id,ke.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:r.jsx(en,{className:"w-4 h-4"})})]})]}),ke.sourcing_url&&r.jsxs("a",{href:ke.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:Ve=>Ve.stopPropagation(),children:[r.jsx(zr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ke.sourcing_url).hostname.replace("www.","")}catch{return ke.sourcing_url}})()})]}),ke.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ke.remarks})]})]})},ke.id)),Ce&&Ce.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[Z,Ce.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Vh,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),_?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?r.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((ke,Ve)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${ke.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ke.event_type==="print_failed"?"bg-status-error/20 text-status-error":ke.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ke.event_type==="print_completed"&&r.jsx(xr,{className:"w-4 h-4"}),ke.event_type==="print_failed"&&r.jsx($r,{className:"w-4 h-4"}),ke.event_type==="print_started"&&r.jsx(hr,{className:"w-4 h-4"}),ke.event_type==="queued"&&r.jsx(WF,{className:"w-4 h-4"}),ke.event_type==="project_created"&&r.jsx(er,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:ke.title}),ke.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ke.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:it(ke.timestamp)})]})]},Ve))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ee.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(Ti,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Ce&&(Ce.queued_prints>0||Ce.in_progress_prints>0)&&r.jsx(At,{children:r.jsxs(Et,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(WF,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),r.jsx(Es,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Ce.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Ce.in_progress_prints})}),Ce.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Ce.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Vr,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:C?.length||0})]})}),P?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(wit,{archives:C||[],t:n})]}),o&&r.jsx(Yce,{t:n,currencySymbol:Z,project:{...x,archive_count:Ce?.total_archives||0,total_items:Ce?.total_items||0,completed_count:Ce?.completed_prints||0,failed_count:Ce?.failed_prints||0,queue_count:Ce?.queued_prints||0,progress_percent:Ce?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ke=>Y.mutate(ke),isLoading:Y.isPending}),ye.isOpen&&r.jsx(wn,{title:ye.title,message:ye.message,confirmText:n("common.delete"),variant:"danger",onConfirm:ye.onConfirm,onCancel:()=>_e(ke=>({...ke,isOpen:!1}))}),p&&r.jsx(bc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),a.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(bc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>w(null),onSuccess:()=>{w(null),a.invalidateQueries({queryKey:["queue"]})}})]})}function kit({archiveId:t,libraryFileId:e,title:n,fileType:a,onClose:i}){const{t:s}=_t(),{data:o}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=y.useState(null),[m,p]=y.useState(null),[f,g]=y.useState(!0),[w,b]=y.useState(null),[x,S]=y.useState(!1),[k,C]=y.useState(null),[P,T]=y.useState(0),[A,F]=y.useState(!1),[_,M]=y.useState(null),[H,I]=y.useState(!1),[z,L]=y.useState(!1),Z=y.useRef(null),ne=y.useRef(null),Y=10,ce=160,ue=240,oe=.35;y.useEffect(()=>{const de=me=>{me.key==="Escape"&&i()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[i]),y.useEffect(()=>{if(g(!0),c){const de=(a||"").toLowerCase(),me=de==="3mf"||de==="stl",q=de==="gcode"||de==="3mf";p({has_model:me,has_gcode:q,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(me?"3d":q?"gcode":null),g(!1);return}if(!t){p(null),u(null),g(!1);return}ae.getArchiveCapabilities(t).then(de=>{p(de),de.has_model?u("3d"):de.has_gcode&&u("gcode"),g(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),g(!1)})},[t,a,c]),y.useEffect(()=>{if(S(!0),C(null),T(0),c){const de=(a||"").toLowerCase();if(!e||de!=="3mf"){b(null),S(!1);return}ae.getLibraryFilePlates(e).then(me=>b(me)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}ae.getArchivePlates(t).then(de=>b(de)).catch(()=>b(null)).finally(()=>S(!1))},[t,a,c,e]);const Q=y.useMemo(()=>w?.plates??[],[w]),le=(w?.is_multi_plate??!1)&&Q.length>1,pe=A&&le,he=k==null?null:Q.find(de=>de.index===k)??null,we=de=>de.object_count??de.objects?.length??0,$=Q.reduce((de,me)=>de+we(me),0),J=he?we(he):$,j=he?s("modelViewer.plateNumber",{number:he.index}):s("modelViewer.allPlates"),E=Q.length>0,B=y.useRef(null),W=y.useRef(null),[O,ie]=y.useState(10),[U,G]=y.useState(3),K=Q.length>O,X=Math.max(1,Math.ceil(Q.length/O)),se=K?Q.slice(P*O,(P+1)*O):Q;y.useEffect(()=>{if(!pe){ie(10),G(3);return}const de=B.current,me=W.current;if(!de||!me)return;let q=0;const R=()=>{const ye=me.clientWidth,xe=Math.floor(ye/210),ge=Math.max(3,Math.min(5,xe||3));G(Ee=>Ee===ge?Ee:ge);const Me=window.getComputedStyle(de),Be=Number.parseFloat(Me.rowGap||"0"),Oe=de.querySelector("button")?.getBoundingClientRect().height??44,Re=me.clientHeight,ze=Math.max(1,Math.floor((Re+Be)/(Oe+Be)))*ge,st=Math.max(1,ze-1);ie(Ee=>Ee===st?Ee:st)},re=()=>{q&&cancelAnimationFrame(q),q=requestAnimationFrame(R)};re();const be=new ResizeObserver(re);return be.observe(me),be.observe(de),()=>{q&&cancelAnimationFrame(q),be.disconnect()}},[pe,Q.length]),y.useEffect(()=>{if(!K){T(0);return}T(de=>Math.min(de,X-1))},[Q.length,K,X]),y.useEffect(()=>{if(!K||k==null)return;const de=Q.findIndex(q=>q.index===k);if(de<0)return;const me=Math.floor(de/O);T(q=>q===me?q:me)},[Q,O,k,K]),y.useEffect(()=>{if(!pe){M(null),L(!1);return}if(z)return;const de=Z.current,me=ne.current;if(!de||!me)return;const q=de.clientHeight;if(!q)return;const R=Math.max(ue,q*oe),re=Math.max(ce,q-Y-R),be=Math.min(me.scrollHeight,re);M(Math.max(ce,be))},[pe,z,Q.length,P,Y,ce,ue,oe]),y.useEffect(()=>{if(!H)return;const de=q=>{const R=Z.current;if(!R)return;const re=R.getBoundingClientRect(),be=re.height;if(!be)return;const ye=Math.max(ue,be*oe),_e=Math.max(ce,be-Y-ye),xe=Math.min(_e,Math.max(ce,q.clientY-re.top));M(xe)},me=()=>{I(!1),L(!0)};return document.addEventListener("mousemove",de),document.addEventListener("mouseup",me),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",de),document.removeEventListener("mouseup",me),document.body.style.cursor="",document.body.style.userSelect=""}},[H,Y,ce,ue,oe]);const te=c?(a||"").toLowerCase()==="3mf":!0,fe=async()=>{if(!te)return;const de=n||"model";try{if(c){const{token:me}=await ae.createLibrarySlicerToken(e),q=ae.getLibrarySlicerDownloadUrl(e,me,de);jm(`${window.location.origin}${q}`,l)}else{const{token:me}=await ae.createArchiveSlicerToken(t),q=ae.getArchiveSlicerDownloadUrl(t,me,de);jm(`${window.location.origin}${q}`,l)}}catch{if(c){const me=`${window.location.origin}${ae.getLibraryFileDownloadUrl(e)}`;jm(me,l)}else{const me=`${window.location.origin}${ae.getArchiveForSlicer(t,de)}`;jm(me,l)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${A?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${A?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:de=>de.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),E&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[j,": ",s("modelViewer.objectCount",{count:J})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:fe,disabled:!te,children:[r.jsx(zr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>F(de=>!de),title:A?"Exit fullscreen":"Enter fullscreen",children:A?r.jsx(_O,{className:"w-4 h-4"}):r.jsx(CT,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Vt,{className:"w-5 h-5"})})]})]}),m&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.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:[r.jsx(Si,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),r.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:[r.jsx(Mge,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?r.jsxs("div",{ref:Z,className:`w-full h-full flex flex-col ${pe?"gap-0 min-h-0":"gap-3"}`,children:[le&&r.jsxs("div",{ref:ne,style:pe&&_!=null?{height:_}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${pe?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(ca,{className:"w-4 h-4"}),s("modelViewer.plates"),x&&r.jsx(ft,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:pe?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:W,className:pe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:B,className:pe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:pe?{gridTemplateColumns:`repeat(${U}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${k==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),r.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:Q.length})})]}),k==null&&r.jsx(Ar,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(de=>r.jsxs("button",{type:"button",onClick:()=>C(de.index),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${k===de.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[de.has_thumbnail&&de.thumbnail_url?r.jsx("img",{src:de.thumbnail_url,alt:`Plate ${de.index}`,className:`${pe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:de.name||s("modelViewer.plateNumber",{number:de.index})}),r.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:de.object_count??de.objects?.length??0})})]}),k===de.index&&r.jsx(Ar,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},de.index))]})}),(he||K)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[he&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:s("modelViewer.plateNumber",{number:he.index})}),he.print_time_seconds!=null&&r.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(he.print_time_seconds/60)})}),he.filament_used_grams!=null&&r.jsxs("span",{children:[he.filament_used_grams.toFixed(1)," g"]}),he.filaments.length>0&&r.jsx("span",{children:s("modelViewer.filamentCount",{count:he.filaments.length})})]}),K&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${he?"ml-auto":""}`,children:[r.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:P+1,total:X})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>T(de=>Math.max(de-1,0)),disabled:P===0,className:`px-2 py-1 rounded border text-xs ${P===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 me=Math.max(0,P-Math.floor(2.5));const q=Math.min(X,me+5);q-me<5&&(me=Math.max(0,q-5));const R=Array.from({length:q-me},(re,be)=>me+be);return r.jsxs(r.Fragment,{children:[me>0&&r.jsx("button",{type:"button",onClick:()=>T(0),className:`px-2 py-1 rounded border text-xs ${P===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),me>1&&r.jsx("span",{className:"px-1",children:"…"}),R.map(re=>r.jsx("button",{type:"button",onClick:()=>T(re),className:`px-2 py-1 rounded border text-xs ${P===re?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:re+1},re)),q<X-1&&r.jsx("span",{className:"px-1",children:"…"}),q<X&&r.jsx("button",{type:"button",onClick:()=>T(X-1),className:`px-2 py-1 rounded border text-xs ${P===X-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:X})]})})(),r.jsx("button",{type:"button",onClick:()=>T(de=>Math.min(de+1,X-1)),disabled:P>=X-1,className:`px-2 py-1 rounded border text-xs ${P>=X-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")})]})]})]})]})]}),pe&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:de=>{de.preventDefault(),I(!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:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${pe?"min-h-0":""}`,children:r.jsx(ZJ,{url:c?ae.getLibraryFileDownloadUrl(e):m.has_source?ae.getSource3mfDownloadUrl(t):ae.getArchiveDownload(t),fileType:a,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:k,className:"w-full h-full"})})]}):d==="gcode"&&m?r.jsx(Fee,{gcodeUrl:c?ae.getLibraryFileGcodeUrl(e):ae.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const Nit=90;function Cit({onClose:t}){const{t:e}=_t(),n=tn(),{showToast:a}=on(),[i,s]=y.useState(Nit),[o,l]=y.useState(!0),[c,d]=y.useState(i);y.useEffect(()=>{const b=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(b)},[i]);const u=Xe({queryKey:["library-purge-preview",c,o],queryFn:()=>ae.previewLibraryPurge(c,o),enabled:c>=1}),m=lt({mutationFn:()=>ae.executeLibraryPurge(i,o),onSuccess:b=>{a(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]}),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>a(b.message||e("libraryPurge.toast.failed"),"error")});y.useEffect(()=>{const b=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,m.isPending]);const p=u.data,f=p?.count??0,g=p?.total_bytes??0,w=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(en,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:b=>s(Math.max(1,Math.min(3650,parseInt(b.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:b=>l(b.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:ls(g)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(b=>r.jsx("li",{className:"truncate",children:b},b)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(je,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(je,{variant:"danger",disabled:!w,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function Pit({parentId:t,onClose:e,onSave:n,isLoading:a,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.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})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{type:"submit",disabled:!s.trim()||a,children:a?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function Tit({onClose:t,onSave:e,isLoading:n,t:a}){const[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!0),[u,m]=y.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(nC,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),r.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:a("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.externalPath")}),r.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}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.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"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",a("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.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"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:t,children:a("common.cancel")}),r.jsx(je,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):a("fileManager.linkFolder")})]})]})]})})}function Ait({type:t,currentName:e,onClose:n,onSave:a,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]=y.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&a(p)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[r.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&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),r.jsx(je,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function jit({folders:t,selectedFiles:e,currentFolderId:n,onClose:a,onMove:i,isLoading:s,t:o}){const[l,c]=y.useState(null),d=(m,p=0)=>{const f=[];for(const g of m)f.push({id:g.id,name:g.name,depth:p}),g.children.length>0&&f.push(...d(g.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.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:[r.jsx(Pl,{className:"w-4 h-4"}),m.name,m.id===n&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:a,children:o("common.cancel")}),r.jsx(je,{onClick:()=>i(l),disabled:s,children:s?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function Mit({folder:t,onClose:e,onLink:n,isLoading:a,t:i}){const[s,o]=y.useState("project"),[l,c]=y.useState(t.project_id||t.archive_id||null);y.useState(()=>{t.archive_id&&o("archive")});const{data:d}=Xe({queryKey:["projects"],queryFn:()=>ae.getProjects(),select:g=>[...g].sort((w,b)=>w.name.localeCompare(b.name))}),{data:u}=Xe({queryKey:["archives-for-link"],queryFn:()=>ae.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 r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.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:[r.jsx(LZ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.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:[r.jsx(eo,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.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(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:g.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:g.name})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Ph,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:g.print_name||g.filename})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(je,{variant:"danger",onClick:p,disabled:a,children:[r.jsx(ou,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(je,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{onClick:m,disabled:!l||a,children:a?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function Xce({folder:t,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=y.useState(c),[f,g]=y.useState(!1),w=t.children.length>0,b=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.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:[w?r.jsx("button",{onClick:S=>{S.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(qa,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(nC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Pl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&r.jsxs("button",{onClick:S=>{S.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:[r.jsx(jh,{className:"w-3 h-3"}),t.project_name?r.jsx(LZ,{className:"w-3 h-3"}):r.jsx(eo,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(rc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!x&&r.jsx("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(jh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>g(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(vm,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(mi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(jh,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(a(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),w&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(Xce,{folder:S,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function _w(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Zce(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function Eit({file:t,isSelected:e,isMobile:n,onSelect:a,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:g,canModify:w,authEnabled:b,t:x}){const[S,k]=y.useState(!1);return r.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:()=>a(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${ae.getLibraryFileThumbnailUrl(t.id)}${f?(ae.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Ph,{className:"w-12 h-12 text-bambu-gray/30"}),r.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()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:ls(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),cs(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(hr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Gm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:C=>C.stopPropagation(),children:[r.jsx("button",{onClick:()=>k(!S),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(vm,{className:"w-4 h-4 text-bambu-gray"})}),S&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>k(!1)}),r.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&&_w(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("printers:control")&&(l(t),k(!1))},disabled:!g("printers:control"),title:g("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(hr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&_w(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("queue:create")&&(o(t.id),k(!1))},disabled:!g("queue:create"),title:g("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&Zce(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:upload")&&(c(t),k(!1))},disabled:!g("library:upload"),title:g("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(uu,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(u(t),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Si,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(s(t.id),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Zr,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(m(t),k(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(mi,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(p(t),k(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(mu,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","delete",t.created_by_id)&&(i(t.id),k(!1))},disabled:!w("library","delete",t.created_by_id),title:w("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(en,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.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&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function Dit(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a,hasAnyPermission:i,canModify:s,authEnabled:o}=dr(),[l]=nb(),c=ji(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=y.useState(u),[f,g]=y.useState([]),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[k,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,M]=y.useState(null),[H,I]=y.useState(null),[z,L]=y.useState(null),[Z,ne]=y.useState(null),[Y,ce]=y.useState(null),[ue,oe]=y.useState(null),[Q,le]=y.useState(null),[pe,he]=y.useState({}),[we,$]=y.useState(null),[J,j]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[E,B]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[W,O]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[ie,U]=y.useState(()=>{const Ae=localStorage.getItem("library-sidebar-width");return Ae?parseInt(Ae,10):256}),[G,K]=y.useState(!1),X=y.useRef(null);y.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ae=Je=>{if(!X.current)return;const De=X.current.parentElement?.getBoundingClientRect();if(!De)return;const mt=Je.clientX-De.left,Ne=Math.min(500,Math.max(200,mt));U(Ne)},Ge=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ie))};return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",Ge),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",Ge),document.body.style.userSelect="",document.body.style.cursor=""}},[G,ie]);const[se,te]=y.useState(""),[fe,de]=y.useState("all"),[me,q]=y.useState(""),[R,re]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[be,ye]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),_e=cse();y.useEffect(()=>{const Ae=l.get("folder");if(Ae){const Ge=parseInt(Ae,10);p(Ge)}},[l]);const{data:xe}=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings()}),{data:ge,isLoading:Me}=Xe({queryKey:["library-folders"],queryFn:()=>ae.getLibraryFolders()}),{data:Be}=Xe({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await ae.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Fe,isLoading:Oe}=Xe({queryKey:["library-files",m],queryFn:()=>ae.getLibraryFiles(m,m===null)}),{data:Re}=Xe({queryKey:["library-stats"],queryFn:()=>ae.getLibraryStats()}),{data:We}=Xe({queryKey:["users"],queryFn:()=>ae.getUsers()}),ze=y.useMemo(()=>{if(!Fe)return[];const Ae=new Set(Fe.map(Ge=>Ge.file_type));return Array.from(Ae).sort()},[Fe]),st=y.useMemo(()=>{if(!Fe)return[];let Ae=[...Fe];if(se.trim()){const Ge=se.toLowerCase();Ae=Ae.filter(Je=>Je.filename.toLowerCase().includes(Ge)||Je.print_name&&Je.print_name.toLowerCase().includes(Ge))}if(fe!=="all"&&(Ae=Ae.filter(Ge=>Ge.file_type===fe)),me.trim()){const Ge=me.toLowerCase();Ae=Ae.filter(Je=>Je.created_by_username&&Je.created_by_username.toLowerCase().includes(Ge))}return Ae.sort((Ge,Je)=>{let De=0;switch(R){case"name":De=(Ge.print_name||Ge.filename).localeCompare(Je.print_name||Je.filename);break;case"date":De=(Yn(Ge.created_at)?.getTime()??0)-(Yn(Je.created_at)?.getTime()??0);break;case"size":De=Ge.file_size-Je.file_size;break;case"type":De=Ge.file_type.localeCompare(Je.file_type);break;case"prints":De=Ge.print_count-Je.print_count;break}return be==="asc"?De:-De}),Ae},[Fe,se,fe,me,R,be]),Ee=y.useMemo(()=>{if(!Re||!xe)return!1;const Ae=(xe.library_disk_warning_gb||5)*1024*1024*1024;return Re.disk_free_bytes<Ae},[Re,xe]),it=lt({mutationFn:Ae=>ae.createLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),b(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ae=>n(Ae.message,"error")}),Ce=lt({mutationFn:async Ae=>{const Ge=await ae.createExternalFolder(Ae);return await ae.scanExternalFolder(Ge.id),Ge},onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),S(!1),p(Ae.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ae=>n(Ae.message,"error")}),Ze=lt({mutationFn:Ae=>ae.scanExternalFolder(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:Ae.added,removed:Ae.removed}),"success")},onError:Ae=>n(Ae.message,"error")}),Ie=lt({mutationFn:Ae=>ae.deleteLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===H?.id&&p(null),I(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ae=>{I(null),n(Ae.message,"error")}}),ke=lt({mutationFn:Ae=>ae.deleteLibraryFile(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),g(Ae=>Ae.filter(Ge=>Ge!==H?.id)),I(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ae=>{I(null),n(Ae.message,"error")}}),Ve=lt({mutationFn:Ae=>ae.bulkDeleteLibrary(Ae,[]),onSuccess:(Ae,Ge)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),n(t("fileManager.toast.filesDeleted",{count:Ge.length}),"success"),g([]),I(null)},onError:Ae=>{I(null),n(Ae.message,"error")}}),rt=lt({mutationFn:({fileIds:Ae,folderId:Ge})=>ae.moveLibraryFiles(Ae,Ge),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),g([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ae=>n(Ae.message,"error")}),Qe=lt({mutationFn:({id:Ae,data:Ge})=>ae.updateLibraryFolder(Ae,Ge),onSuccess:(Ae,Ge)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Je=Ge.data.project_id===0&&Ge.data.archive_id===0;n(t(Je?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ae=>n(Ae.message,"error")}),Te=lt({mutationFn:({id:Ae,filename:Ge})=>ae.updateLibraryFile(Ae,{filename:Ge}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),le(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ae=>{le(null),n(Ae.message,"error")}}),tt=lt({mutationFn:({id:Ae,name:Ge})=>ae.updateLibraryFolder(Ae,{name:Ge}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),le(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ae=>{le(null),n(Ae.message,"error")}}),ot=lt({mutationFn:()=>ae.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ge=Date.now(),Je={};Ae.results.forEach(De=>{De.success&&(Je[De.file_id]=Ge)}),he(De=>({...De,...Je}))}Ae.succeeded>0&&Ae.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ae.succeeded}),"success"):Ae.succeeded>0&&Ae.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ae.succeeded,failed:Ae.failed}),"success"):Ae.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>n(Ae.message,"error")}),Tt=lt({mutationFn:Ae=>ae.batchGenerateStlThumbnails({file_ids:[Ae]}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ge=Ae.results[0]?.file_id;Ge&&he(Je=>({...Je,[Ge]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>n(Ae.message,"error")}),Ut=y.useCallback(Ae=>{const Ge=Ae.toLowerCase();return Ge.endsWith(".gcode")||Ge.includes(".gcode.")},[]),bt=y.useMemo(()=>Fe?Fe.filter(Ae=>f.includes(Ae.id)&&Ut(Ae.filename)):[],[Fe,f,Ut]),Wt=y.useCallback(Ae=>{g(Ge=>Ge.includes(Ae)?Ge.filter(Je=>Je!==Ae):[...Ge,Ae])},[]),Zt=y.useCallback(()=>{st.length>0&&g(st.map(Ae=>Ae.id))},[st]),ln=y.useCallback(()=>{g([])},[]),cn=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ct=Ae=>{ae.downloadLibraryFile(Ae).catch(Ge=>{console.error("Library file download failed:",Ge)})},kt=()=>{H&&(H.type==="file"?ke.mutate(H.id):H.type==="folder"?Ie.mutate(H.id):H.type==="bulk"&&Ve.mutate(f))},Nt=Ie.isPending||ke.isPending||Ve.isPending,ut=Ae=>{j(Ae),localStorage.setItem("library-view-mode",Ae)},Ct=Me||Oe,Le=y.useMemo(()=>{if(!m||!ge)return null;const Ae=Ge=>{for(const Je of Ge){if(Je.id===m)return Je;const De=Ae(Je.children);if(De)return De}return null};return Ae(ge)},[m,ge]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Pl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>ut("grid"),className:`p-1.5 rounded transition-colors ${J==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(jS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>ut("list"),className:`p-1.5 rounded transition-colors ${J==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(MS,{className:"w-4 h-4"})})]}),r.jsxs(je,{variant:"secondary",onClick:()=>ot.mutate(),disabled:ot.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[ot.isPending?r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(mu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(je,{variant:"secondary",onClick:()=>S(!0),disabled:!a("library:upload"),title:a("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(nC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(je,{variant:"secondary",onClick:()=>b(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(Tbe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a("library:purge")&&r.jsxs(je,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(en,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Es,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(en,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Be=="number"&&Be>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:Be})]}),r.jsxs(je,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(_a,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Ee&&Re&&xe&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(Nn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ls(Re.disk_free_bytes),total:ls(Re.disk_total_bytes),threshold:xe.library_disk_warning_gb})})]})]}),Re&&r.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:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(NT,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Re.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Pl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Re.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ib,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ls(Re.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Ee?"text-amber-500":"text-white"}`,children:ls(Re.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m??"",onChange:Ae=>p(Ae.target.value?parseInt(Ae.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:[r.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),ge&&(()=>{const Ae=(Ge,Je=0)=>{const De=[];for(const mt of Ge)De.push({id:mt.id,name:mt.name,fileCount:mt.file_count,depth:Je}),mt.children.length>0&&De.push(...Ae(mt.children,Je+1));return De};return Ae(ge).map(Ge=>r.jsxs("option",{value:Ge.id,children:["│ ".repeat(Ge.depth),"📂 ",Ge.name," ",Ge.fileCount>0?`(${Ge.fileCount})`:""]},Ge.id))})()]})}),r.jsxs("div",{ref:X,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:`${ie}px`},children:[r.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 ${G?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ae=>{Ae.preventDefault(),K(!0)},onDoubleClick:()=>{U(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${G?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const Ae=!W;O(Ae),localStorage.setItem("library-collapse-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ae=!E;B(Ae),localStorage.setItem("library-wrap-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${E?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(E?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>p(null),children:[r.jsx(Ph,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),ge?.map(Ae=>r.jsx(Xce,{folder:Ae,selectedFolderId:m,onSelect:p,onDelete:Ge=>I({type:"folder",id:Ge}),onLink:M,onRename:Ge=>le({type:"folder",id:Ge.id,name:Ge.name}),wrapNames:E,defaultExpanded:!W,hasPermission:a,t},`${Ae.id}-${W?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[Le?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(nC,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),Le.external_readonly&&r.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:[r.jsx(rc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:Le.external_path||"",children:Le.external_path})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>m&&Ze.mutate(m),disabled:Ze.isPending,title:t("fileManager.scanFolder"),children:[Ze.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Fe&&Fe.length>0&&r.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:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:se,onChange:Ae=>te(Ae.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"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(PS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:fe,onChange:Ae=>de(Ae.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:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),ze.map(Ae=>r.jsx("option",{value:Ae,children:Ae.toUpperCase()},Ae))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:me,onChange:Ae=>q(Ae.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 ${me?"pr-7":""}`,style:me?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),me&&r.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Vt,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:We?.map(Ae=>r.jsx("option",{value:Ae.username},Ae.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:R,onChange:Ae=>{const Ge=Ae.target.value;re(Ge),localStorage.setItem("library-sort-field",Ge)},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:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>ye(Ae=>{const Ge=Ae==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ge),Ge}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(be==="asc"?"fileManager.ascending":"fileManager.descending"),children:be==="asc"?r.jsx(Mfe,{className:"w-4 h-4 text-white"}):r.jsx(kfe,{className:"w-4 h-4 text-white"})})]}),(se||fe!=="all"||me)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:st.length,total:Fe.length})})]}),st.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===st.length&&f.length>0?r.jsxs(je,{variant:"secondary",size:"sm",onClick:ln,children:[r.jsx(ro,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:Zt,children:[r.jsx(gs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[bt.length===1&&r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>ne(bt[0]),disabled:!a("printers:control"),title:a("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(hs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),bt.length===1&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>ce(bt[0]),disabled:!a("queue:create"),title:a("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(je,{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:[r.jsx(Hxe,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(je,{variant:"danger",size:"sm",onClick:()=>{f.length===1?I({type:"file",id:f[0]}):I({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(en,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:ln,children:[r.jsx(Vt,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ct?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Fe?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Ph,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(je,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(er,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):st.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(yr,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(je,{variant:"secondary",onClick:()=>{te(""),de("all")},children:t("fileManager.clearFilters")})]}):J==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.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:st.map(Ae=>r.jsx(Eit,{file:Ae,isSelected:f.includes(Ae.id),isMobile:_e,t,onSelect:Wt,onDelete:Ge=>I({type:"file",id:Ge}),onDownload:ct,onAddToQueue:Ge=>{const Je=Fe?.find(De=>De.id===Ge);Je&&ce(Je)},onPrint:L,onSlice:oe,useSlicerApi:xe?.use_slicer_api??!1,onPreview3d:Ge=>{_w(Ge.filename)?c(`/gcode-viewer?library_file=${Ge.id}`):$(Ge)},onRename:Ge=>le({type:"file",id:Ge.id,name:Ge.filename}),onGenerateThumbnail:Ge=>Tt.mutate(Ge.id),thumbnailVersion:pe[Ae.id],hasPermission:a,canModify:s,authEnabled:o},Ae.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.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:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),st.map(Ae=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Ae.id)?"bg-bambu-green/10":""}`,onClick:()=>Wt(Ae.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ae.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ae.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ae.thumbnail_path?r.jsx("img",{src:`${ae.getLibraryFileThumbnailUrl(Ae.id)}${pe[Ae.id]?(ae.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${pe[Ae.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Ph,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ae.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${ae.getLibraryFileThumbnailUrl(Ae.id)}${pe[Ae.id]?(ae.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${pe[Ae.id]}`:""}`,alt:Ae.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:Ae.print_name||Ae.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ae.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Gm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ae.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ae.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ae.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ae.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ae.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:ls(Ae.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ae.print_count>0?`${Ae.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ge=>Ge.stopPropagation(),children:[_w(Ae.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>a("printers:control")&&L(Ae),className:`p-1.5 rounded transition-colors ${a("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!a("printers:control"),children:r.jsx(hr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{a("queue:create")&&ce(Ae)},className:`p-1.5 rounded transition-colors ${a("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!a("queue:create"),children:r.jsx(Zn,{className:"w-4 h-4"})})]}),(xe?.use_slicer_api??!1)&&Zce(Ae.filename)&&r.jsx("button",{onClick:()=>a("library:upload")&&oe(Ae),className:`p-1.5 rounded transition-colors ${a("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!a("library:upload"),children:r.jsx(uu,{className:"w-4 h-4"})}),(Ae.file_type==="3mf"||Ae.file_type==="gcode"||Ae.file_type==="stl")&&r.jsx("button",{onClick:()=>{a("library:read")&&(_w(Ae.filename)?c(`/gcode-viewer?library_file=${Ae.id}`):$(Ae))},className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!a("library:read"),children:r.jsx(Si,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>a("library:read")&&ct(Ae.id),className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!a("library:read"),children:r.jsx(Zr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&le({type:"file",id:Ae.id,name:Ae.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ae.created_by_id),children:r.jsx(mi,{className:"w-4 h-4"})}),Ae.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&Tt.mutate(Ae.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.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",Ae.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Tt.isPending||!s("library","update",Ae.created_by_id),children:r.jsx(mu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ae.created_by_id)&&I({type:"file",id:Ae.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ae.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",Ae.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ae.created_by_id),children:r.jsx(en,{className:"w-4 h-4"})})]})]},Ae.id))]})})]})]}),w&&r.jsx(Pit,{parentId:m,onClose:()=>b(!1),onSave:Ae=>it.mutate(Ae),isLoading:it.isPending,t}),x&&r.jsx(Tit,{onClose:()=>S(!1),onSave:Ae=>Ce.mutate(Ae),isLoading:Ce.isPending,t}),k&&ge&&r.jsx(jit,{folders:ge,selectedFiles:f,currentFolderId:m,onClose:()=>C(!1),onMove:Ae=>rt.mutate({fileIds:f,folderId:Ae}),isLoading:rt.isPending,t}),P&&r.jsx(Zie,{folderId:m,onClose:()=>T(!1),onUploadComplete:cn}),A&&r.jsx(Cit,{onClose:()=>F(!1)}),_&&r.jsx(Mit,{folder:_,onClose:()=>M(null),onLink:Ae=>Qe.mutate({id:_.id,data:Ae}),isLoading:Qe.isPending,t}),H&&r.jsx(wn,{title:H.type==="folder"?t("fileManager.deleteFolder"):H.type==="bulk"?t("fileManager.deleteFilesCount",{count:H.count}):t("fileManager.deleteFile"),message:H.type==="folder"?t("fileManager.deleteFolderConfirm"):H.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:H.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Nt,loadingText:t("fileManager.deleting"),onConfirm:kt,onCancel:()=>I(null)}),z&&r.jsx(bc,{mode:"reprint",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>L(null),onSuccess:()=>{L(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Z&&r.jsx(bc,{mode:"reprint",libraryFileId:Z.id,archiveName:Z.print_name||Z.filename,onClose:()=>ne(null),onSuccess:()=>{ne(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Y&&r.jsx(bc,{mode:"add-to-queue",libraryFileId:Y.id,archiveName:Y.print_name||Y.filename,onClose:()=>ce(null),onSuccess:()=>{ce(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),ue&&r.jsx(RA,{source:{kind:"libraryFile",id:ue.id,filename:ue.filename},onClose:()=>oe(null)}),we&&r.jsx(kit,{libraryFileId:we.id,title:we.print_name||we.filename,fileType:we.file_type,onClose:()=>$(null)}),Q&&r.jsx(Ait,{type:Q.type,currentName:Q.name,onClose:()=>le(null),onSave:Ae=>{Q.type==="file"?Te.mutate({id:Q.id,filename:Ae}):tt.mutate({id:Q.id,name:Ae})},isLoading:Te.isPending||tt.isPending,t})]})}function Fit(t){const e=Yn(t);if(!e)return"";const n=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return n<=0?"any moment":n===1?"1 day":`${n} days`}function SX(t){const e=Yn(t);return e?e.toLocaleString():t}function Lit(){const{t}=_t(),e=ji(),n=tn(),{showToast:a}=on(),{hasPermission:i,authEnabled:s}=dr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=Xe({queryKey:["library-trash"],queryFn:()=>ae.listLibraryTrash(200,0)}),p=Xe({queryKey:["library-trash-settings"],queryFn:()=>ae.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const w=lt({mutationFn:z=>{const L=p.data;return ae.updateLibraryTrashSettings({retention_days:z,auto_purge_enabled:L?.auto_purge_enabled??!1,auto_purge_days:L?.auto_purge_days??90,auto_purge_include_never_printed:L?.auto_purge_include_never_printed??!0})},onSuccess:z=>{a(t("libraryTrash.toast.retentionSaved",{days:z.retention_days}),"success"),n.invalidateQueries({queryKey:["library-trash-settings"]}),n.invalidateQueries({queryKey:["library-trash"]})},onError:z=>a(z.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=lt({mutationFn:z=>ae.restoreLibraryTrash(z),onSuccess:()=>{a(t("libraryTrash.toast.restored"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:z=>a(z.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=lt({mutationFn:z=>ae.hardDeleteLibraryTrash(z),onSuccess:()=>{a(t("libraryTrash.toast.purged"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:z=>a(z.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=lt({mutationFn:()=>ae.emptyLibraryTrash(),onSuccess:z=>{a(t("libraryTrash.toast.emptied",{count:z.deleted}),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:z=>a(z.message||t("libraryTrash.toast.emptyFailed"),"error")}),k=lt({mutationFn:z=>Promise.all(z.map(L=>ae.restoreLibraryTrash(L))),onSuccess:(z,L)=>{a(t("libraryTrash.toast.bulkRestored",{count:L.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:z=>a(z.message||t("libraryTrash.toast.restoreFailed"),"error")}),C=lt({mutationFn:z=>Promise.all(z.map(L=>ae.hardDeleteLibraryTrash(L))),onSuccess:(z,L)=>{a(t("libraryTrash.toast.bulkPurged",{count:L.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:z=>a(z.message||t("libraryTrash.toast.purgeFailed"),"error")}),P=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,A=y.useMemo(()=>P.reduce((z,L)=>z+L.file_size,0),[P]),F=P.length>0&&P.every(z=>c.has(z.id)),_=c.size>0&&!F,M=z=>{d(L=>{const Z=new Set(L);return Z.has(z)?Z.delete(z):Z.add(z),Z})},H=()=>{d(z=>z.size===P.length?new Set:new Set(P.map(L=>L.id)))},I=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?C.mutate(Array.from(c)):S.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Es,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(ST,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),P.length>0&&r.jsxs(je,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(en,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:z=>g(Math.max(1,Math.min(365,parseInt(z.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(je,{variant:"secondary",onClick:()=>f!=null&&w.mutate(f),disabled:w.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(ds,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):P.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:P.length,size:ls(A)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(je,{variant:"secondary",onClick:()=>k.mutate(Array.from(c)),disabled:k.isPending,children:[r.jsx(fs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(je,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:C.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(en,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:F,ref:z=>{z&&(z.indeterminate=_)},onChange:H,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:P.map(z=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(z.id),onChange:()=>M(z.id),"aria-label":t("libraryTrash.selectOne",{filename:z.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:z.filename,children:z.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:z.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:ls(z.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:SX(z.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:SX(z.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:Fit(z.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:z.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(z.id),disabled:b.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(fs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:z.id,filename:z.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(en,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},z.id))})]})})]}),o&&r.jsx(wn,{onCancel:()=>l(null),onConfirm:I,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:P.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(je,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function Rit(t,e){const n=`token=${encodeURIComponent(e)}`;let a=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(n))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${n}`,a+=1}),a}function Jce(){const{authEnabled:t,user:e}=dr(),n=tn(),a=y.useRef(!1),{data:i}=Xe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>ae.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const s=i?.token??null;return b6(s),s&&Rit(document,s),()=>b6(null)},[i?.token]),y.useEffect(()=>{if(!t)return;const s=o=>{const l=o.target;if(!(l instanceof HTMLImageElement||l instanceof HTMLVideoElement))return;const c=l.src||"",d=JZ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||a.current||(a.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{a.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,n])}const pN=5,Iit=2e3,Oit=3e4,zit=5e3;function Uit(){const{t}=_t(),e=tn(),{showToast:n}=on(),{hasPermission:a,authEnabled:i,user:s}=dr(),{printerId:o}=NS(),l=parseInt(o||"0",10),[c]=nb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);Jce();const{data:m}=Xe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>ae.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??JZ(),[f,g]=y.useState("stream"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[k,C]=y.useState(!0),[P,T]=y.useState(Date.now()),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState(0),[z,L]=y.useState(!1),[Z,ne]=y.useState(0),[Y,ce]=y.useState(1),[ue,oe]=y.useState({x:0,y:0}),[Q,le]=y.useState(!1),[pe,he]=y.useState({x:0,y:0}),[we,$]=y.useState(null),[J,j]=y.useState(null),E=y.useRef(null),B=y.useRef(null),W=y.useRef(null),O=y.useRef(null),ie=y.useRef(null),{data:U}=Xe({queryKey:["printer",l],queryFn:()=>ae.getPrinter(l),enabled:l>0}),{data:G}=Xe({queryKey:["printerStatus",l],queryFn:()=>ae.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),K=lt({mutationFn:Ie=>ae.setChamberLight(l,Ie),onMutate:async Ie=>{await e.cancelQueries({queryKey:["printerStatus",l]});const ke=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ve=>({...Ve,chamber_light:Ie})),{previousStatus:ke}},onSuccess:(Ie,ke)=>{n(`Chamber light ${ke?"on":"off"}`)},onError:(Ie,ke,Ve)=>{Ve?.previousStatus&&e.setQueryData(["printerStatus",l],Ve.previousStatus),n(Ie.message||t("printers.toast.failedToControlChamberLight"),"error")}}),X=(G?.state==="RUNNING"||G?.state==="PAUSE")&&(G?.printable_objects_count??0)>=2;y.useEffect(()=>(U&&(document.title=`${U.name} - Camera`),()=>{document.title="Bambuddy"}),[U]);const se=y.useRef(!1);y.useEffect(()=>{const Ie=`/api/v1/printers/${l}/camera/stop`;se.current=!1;const ke=()=>{if(l>0&&!se.current){se.current=!0;const Qe={},Te=Wm();Te&&(Qe.Authorization=`Bearer ${Te}`),fetch(Ie,{method:"POST",keepalive:!0,headers:Qe}).catch(()=>{})}},Ve=()=>{ke()};window.addEventListener("beforeunload",Ve);const rt=E.current;return()=>{window.removeEventListener("beforeunload",Ve),rt&&(rt.src=""),ke()}},[l]),y.useEffect(()=>{if(k&&!A){const ke=setTimeout(()=>{C(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(ke)}},[f,k,P,A]),y.useEffect(()=>{const Ie=()=>{const ke=!!document.fullscreenElement;M(ke),ce(1),oe({x:0,y:0}),f==="stream"&&!A&&(E.current&&(E.current.src=""),setTimeout(()=>{C(!0),T(Date.now())},200))};return document.addEventListener("fullscreenchange",Ie),()=>document.removeEventListener("fullscreenchange",Ie)},[f,A]),y.useEffect(()=>{let Ie;const ke=()=>{clearTimeout(Ie),Ie=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",ke),()=>{clearTimeout(Ie),window.removeEventListener("resize",ke)}},[]),y.useEffect(()=>()=>{W.current&&clearTimeout(W.current),O.current&&clearInterval(O.current),ie.current&&clearInterval(ie.current)},[]);const te=y.useCallback(()=>{if(H>=pN){L(!1),S(!0);return}const Ie=Math.min(Iit*Math.pow(2,H),Oit);L(!0),ne(Math.ceil(Ie/1e3)),O.current=setInterval(()=>{ne(ke=>ke<=1?(O.current&&clearInterval(O.current),0):ke-1)},1e3),W.current=setTimeout(()=>{I(ke=>ke+1),L(!1),C(!0),S(!1),E.current&&(E.current.src=""),T(Date.now())},Ie)},[H]);y.useEffect(()=>{if(f!=="stream"||k||z||A){ie.current&&(clearInterval(ie.current),ie.current=null);return}return ie.current=setInterval(async()=>{try{const Ie=await ae.getCameraStatus(l);(Ie.stalled||!Ie.active&&!x)&&(console.log(`Stream issue detected: stalled=${Ie.stalled}, active=${Ie.active}, reconnecting...`),ie.current&&(clearInterval(ie.current),ie.current=null),C(!1),te())}catch{}},zit),()=>{ie.current&&(clearInterval(ie.current),ie.current=null)}},[f,k,x,z,A,l,te]);const fe=()=>{C(!1),f==="stream"&&H<pN?te():S(!0)},de=()=>{if(C(!1),S(!1),I(0),L(!1),W.current&&clearTimeout(W.current),O.current&&clearInterval(O.current),E.current&&!localStorage.getItem("cameraWindowState")){const Ie=E.current,ke=Ie.naturalWidth,Ve=Ie.naturalHeight;if(ke>0&&Ve>0){const Te=window.outerWidth-window.innerWidth,tt=window.outerHeight-window.innerHeight,ot=ke+16+Te,Tt=Ve+45+16+tt;try{window.resizeTo(ot,Tt)}catch{}}}},me=()=>{if(l>0){const Ie={},ke=Wm();ke&&(Ie.Authorization=`Bearer ${ke}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Ie}).catch(()=>{})}},q=Ie=>{f===Ie||A||(F(!0),C(!0),S(!1),I(0),L(!1),ce(1),oe({x:0,y:0}),W.current&&clearTimeout(W.current),O.current&&clearInterval(O.current),E.current&&(E.current.src=""),f==="stream"&&me(),setTimeout(()=>{g(Ie),T(Date.now()),F(!1)},100))},R=()=>{A||(F(!0),C(!0),S(!1),I(0),L(!1),W.current&&clearTimeout(W.current),O.current&&clearInterval(O.current),E.current&&(E.current.src=""),f==="stream"&&me(),setTimeout(()=>{T(Date.now()),F(!1)},100))},re=()=>{B.current&&(document.fullscreenElement?document.exitFullscreen():B.current.requestFullscreen())},be=()=>{ce(Ie=>Math.min(Ie+.5,4))},ye=()=>{ce(Ie=>{const ke=Math.max(Ie-.5,1);return ke===1&&oe({x:0,y:0}),ke})},_e=Ie=>{Ie.preventDefault(),Ie.deltaY<0?be():ye()},xe=Ie=>{Y>1&&(Ie.preventDefault(),le(!0),he({x:Ie.clientX-ue.x,y:Ie.clientY-ue.y}))},ge=y.useCallback(()=>{if(!B.current)return{x:300,y:200};const Ie=B.current.getBoundingClientRect(),ke=Ie.width*(Y-1)/2,Ve=Ie.height*(Y-1)/2;return{x:Math.max(50,ke),y:Math.max(50,Ve)}},[Y]),Me=Ie=>{if(Q&&Y>1){const ke=Ie.clientX-pe.x,Ve=Ie.clientY-pe.y,rt=ge();oe({x:Math.max(-rt.x,Math.min(rt.x,ke)),y:Math.max(-rt.y,Math.min(rt.y,Ve))})}},Be=()=>{le(!1)},Fe=Ie=>{if(Ie.length<2)return 0;const ke=Ie[0].clientX-Ie[1].clientX,Ve=Ie[0].clientY-Ie[1].clientY;return Math.sqrt(ke*ke+Ve*Ve)},Oe=Ie=>Ie.length<2?{x:Ie[0].clientX,y:Ie[0].clientY}:{x:(Ie[0].clientX+Ie[1].clientX)/2,y:(Ie[0].clientY+Ie[1].clientY)/2},Re=Ie=>{Ie.touches.length===2?(Ie.preventDefault(),$(Fe(Ie.touches)),j(Oe(Ie.touches))):Ie.touches.length===1&&Y>1&&(Ie.preventDefault(),le(!0),he({x:Ie.touches[0].clientX-ue.x,y:Ie.touches[0].clientY-ue.y}))},We=Ie=>{if(Ie.touches.length===2&&we!==null){Ie.preventDefault();const ke=Fe(Ie.touches),Ve=ke/we;ce(Qe=>{const Te=Math.max(1,Math.min(4,Qe*Ve));return Te===1&&oe({x:0,y:0}),Te}),$(ke);const rt=Oe(Ie.touches);if(J){const Qe=ge();oe(Te=>({x:Math.max(-Qe.x,Math.min(Qe.x,Te.x+(rt.x-J.x))),y:Math.max(-Qe.y,Math.min(Qe.y,Te.y+(rt.y-J.y)))}))}j(rt)}else if(Ie.touches.length===1&&Q&&Y>1){Ie.preventDefault();const ke=Ie.touches[0].clientX-pe.x,Ve=Ie.touches[0].clientY-pe.y,rt=ge();oe({x:Math.max(-rt.x,Math.min(rt.x,ke)),y:Math.max(-rt.y,Math.min(rt.y,Ve))})}},ze=Ie=>{Ie.touches.length<2&&($(null),j(null)),Ie.touches.length===0&&le(!1)},st=()=>{ce(1),oe({x:0,y:0})},Ee=i&&!p,it=Ie=>p?`${Ie}&token=${encodeURIComponent(p)}`:La(Ie),Ce=A||Ee?"":it(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${P}`:`/api/v1/printers/${l}/camera/snapshot?t=${P}`),Ze=k||A||z;return l?r.jsxs("div",{ref:B,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(by,{className:"w-4 h-4"}),U?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>q("stream"),disabled:Ze,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>q("snapshot"),disabled:Ze,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>K.mutate(!G?.chamber_light),disabled:!G?.connected||K.isPending||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${G?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:a("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(s4,{on:G?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!X||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${X&&a("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:a("printers:control")?t(X?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(UT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:R,disabled:Ze,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(tr,{className:`w-4 h-4 text-bambu-gray ${Ze?"animate-spin":""}`})}),r.jsx("button",{onClick:re,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?r.jsx(BZ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Mxe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:_e,onMouseMove:Me,onMouseUp:Be,onMouseLeave:Be,onTouchStart:Re,onTouchMove:We,onTouchEnd:ze,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(k||A)&&!z&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(tr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),z&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(hu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Z,attempt:Math.min(H+1,pN),max:pN})}),r.jsx("button",{onClick:R,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),x&&!z&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(Nn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsx("button",{onClick:R,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),r.jsx("img",{ref:E,src:Ce,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${Y}) translate(${ue.x/Y}px, ${ue.y/Y}px) rotate(${U?.camera_rotation||0}deg)`,...U?.camera_rotation===90||U?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:Y>1?Q?"grabbing":"grab":"default"},onError:Ce?fe:void 0,onLoad:Ce?de:void 0,onMouseDown:xe,draggable:!1},P),r.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:[r.jsx("button",{onClick:ye,disabled:Y<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(PO,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:st,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(Y*100),"%"]}),r.jsx("button",{onClick:be,disabled:Y>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(CO,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(o4,{printerId:l,isOpen:w,onClose:()=>b(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Bit(t,e,n){if(!t)return"";if(!e)return t;const a=e.match(/plate_(\d+)\.gcode/);return a&&parseInt(a[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:a[1]})}`:t}function Hit(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),a=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:a,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 qit(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 $it(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 Vit(){const{printerId:t}=NS(),[e]=nb(),{t:n}=_t(),a=tn(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>Hit(e),[e]),c=$it(l.size),{data:d}=Xe({queryKey:["printer",i],queryFn:()=>ae.getPrinter(i),enabled:i>0}),{data:u}=Xe({queryKey:["printerStatus",i],queryFn:()=>ae.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),p=m?.time_format||"system";y.useEffect(()=>{if(!i)return;const S=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(S);return k.onmessage=C=>{try{const P=JSON.parse(C.data);P.type==="printer_status"&&P.printer_id===i&&a.setQueryData(["printerStatus",i],P.status)}catch{}},k.onerror=()=>{},()=>{k.close()}},[i,a]),y.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 r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",w=u.progress||0,b=La(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:b,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),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.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:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(hr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Bit(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:qit(u,n)}),l.showProgress&&g&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(w),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${w}%`}})})]}),g&&(l.showLayers||l.showEta)&&r.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&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(ca,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Zd,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:cs(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Zn,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",MO(u.remaining_time,p,n)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Git(){const{t}=_t(),{id:e}=NS(),{mode:n}=ob(),{data:a,isLoading:i,error:s}=Xe({queryKey:["external-link",e],queryFn:()=>ae.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!a?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(Nn,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:a.url,className:"h-full w-full border-0",style:{colorScheme:n},title:a.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function _X(){const{id:t}=NS(),e=ji(),n=tn(),{t:a}=_t(),{showToast:i}=on(),s=!!t,[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState([]),[p,f]=y.useState(""),[g,w]=y.useState(!1),{data:b,isLoading:x}=Xe({queryKey:["group",t],queryFn:()=>ae.getGroup(Number(t)),enabled:s}),{data:S,isLoading:k}=Xe({queryKey:["permissions"],queryFn:()=>ae.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),w(!0));const C=lt({mutationFn:Y=>ae.createGroup(Y),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),n.invalidateQueries({queryKey:["group"]}),i(a("groups.toast.created")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),P=lt({mutationFn:Y=>ae.updateGroup(Number(t),Y),onSuccess:Y=>{n.invalidateQueries({queryKey:["groups"]}),Y&&n.setQueryData(["group",t],Y),i(a("groups.toast.updated")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),T=C.isPending||P.isPending,A=()=>{if(!o.trim()){i(a("groups.toast.enterGroupName"),"error");return}s?P.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):C.mutate({name:o,description:c||void 0,permissions:u})},F=Y=>{m(ce=>ce.includes(Y)?ce.filter(ue=>ue!==Y):[...ce,Y])},_=(Y,ce)=>{const ue=Y.permissions.map(oe=>oe.value);m(oe=>{const Q=oe.filter(le=>!ue.includes(le));return ce?[...Q,...ue]:Q})},M=Y=>Y.permissions.every(ce=>u.includes(ce.value)),H=Y=>{const ce=Y.permissions.filter(ue=>u.includes(ue.value)).length;return ce>0&&ce<Y.permissions.length},I=()=>{S&&m(S.all_permissions)},z=()=>{m([])},L=p.toLowerCase(),Z=y.useMemo(()=>S?L?S.categories.map(Y=>({...Y,permissions:Y.permissions.filter(ce=>ce.label.toLowerCase().includes(L))})).filter(Y=>Y.permissions.length>0):S.categories:[],[S,L]),ne=S?.all_permissions.length??0;return x||k?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.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:r.jsx(ST,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:a(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&r.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:[r.jsx(Nn,{className:"w-4 h-4 shrink-0"}),a("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Y=>l(Y.target.value),disabled:s&&b?.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:a("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Y=>d(Y.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[a("groups.editor.permissionsSelected",{count:u.length})," / ",ne]}),r.jsx(je,{size:"sm",variant:"ghost",onClick:I,children:a("groups.editor.selectAll")}),r.jsx(je,{size:"sm",variant:"ghost",onClick:z,children:a("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:Y=>f(Y.target.value),placeholder:a("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"})]})]}),Z.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:a("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Z.map(Y=>{const ce=S.categories.find(pe=>pe.name===Y.name),ue=ce.permissions.filter(pe=>u.includes(pe.value)).length,oe=ce.permissions.length,Q=M(ce),le=H(ce);return r.jsxs(At,{children:[r.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:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>_(ce,!Q),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Q?"bg-bambu-green border-bambu-green":le?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Q&&r.jsx(Ar,{className:"w-3 h-3 text-white"}),le&&!Q&&r.jsx(rC,{className:"w-3 h-3 text-white"})]}),r.jsx(hl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Y.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[ue,"/",oe]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Y.permissions.map(pe=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(pe.value),onChange:()=>F(pe.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"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:pe.label})]},pe.value))})]},Y.name)})}),r.jsx("div",{className:"h-16"}),r.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:[r.jsx(je,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:a("common.cancel")}),r.jsx(je,{onClick:A,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),a("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ds,{className:"w-4 h-4"}),a("common.save")]})})]})]})}const Wit=1.65,kX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function kw(t,e,n){return`${t}||${e??""}||${n??""}`}function Bm(t,e){const n=new Date(t);return n.setDate(n.getDate()+Math.round(e)),n}function _S(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Nw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Kit(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),n=Date.now(),a=Math.LN2/30,i=[];for(let c=1;c<e.length;c++){const d=new Date(e[c-1].created_at).getTime(),u=new Date(e[c].created_at).getTime(),m=Math.max((u-d)/864e5,.5),p=(n-u)/864e5,f=e[c].weight_used/m,g=Math.exp(-a*p);i.push({rate:f,weight:g})}const s=i.reduce((c,d)=>c+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function Qit(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const n=Date.now(),a=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return l<s?l:s},n),i=(n-a)/864e5;return i<1?null:e/i}function Yit(t,e=60){if(t.dailyRateG===null)return[];const n=t.dailyRateG,a=[];for(let i=0;i<=e;i++){const s=Math.max(0,t.totalRemainingG-n*i);if(a.push({day:i,label:Nw(Bm(new Date,i)),stock:Math.round(s),rop:Math.round(t.reorderPointG)}),s===0)break}return a}function Xit({spools:t}){const e=tn(),{showToast:n}=on(),{t:a}=_t(),{hasPermission:i,hasAnyPermission:s}=dr(),o=i("inventory:forecast_read"),l=s("inventory:forecast_write","inventory:update"),[c,d]=y.useState(!1),[u,m]=y.useState("material"),[p,f]=y.useState("asc"),[g,w]=y.useState(null),[b,x]=y.useState(!1),[S,k]=y.useState(30),{data:C}=Xe({queryKey:["settings"],queryFn:ae.getSettings,enabled:o}),{data:P=[]}=Xe({queryKey:["sku-settings"],queryFn:ae.getSkuSettings,staleTime:6e4,enabled:o}),{data:T=[]}=Xe({queryKey:["all-usage-history-forecast"],queryFn:()=>ae.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:A=[]}=Xe({queryKey:["shopping-list"],queryFn:ae.getShoppingList,staleTime:3e4,enabled:o}),F=C?.forecast_global_lead_time_days??0,_=y.useMemo(()=>{const ce=new Map;for(const ue of P)ce.set(kw(ue.material,ue.subtype,ue.brand),ue);return ce},[P]),M=y.useMemo(()=>{const ce=new Map;for(const ue of T){const oe=ce.get(ue.spool_id)??[];oe.push(ue),ce.set(ue.spool_id,oe)}return ce},[T]),H=y.useMemo(()=>{const ce=new Map;for(const ue of t){if(ue.archived_at)continue;const oe=kw(ue.material,ue.subtype,ue.brand),Q=ce.get(oe)??{key:oe,material:ue.material,subtype:ue.subtype,brand:ue.brand,spools:[]};Q.spools.push(ue),ce.set(oe,Q)}return[...ce.values()]},[t]),I=y.useMemo(()=>{const ce=new Date;return ce.setHours(0,0,0,0),H.map(ue=>{const oe=_.get(ue.key)??null,Q=oe?.lead_time_days??0,le=Math.max(F,Q),pe=oe?.safety_margin_value??14,he=oe?.safety_margin_unit??"days",we=ue.spools.reduce((R,re)=>R+Math.max(0,re.label_weight-re.weight_used),0),$=ue.spools.reduce((R,re)=>R+re.label_weight,0),J=ue.spools.reduce((R,re)=>R+Math.max(0,re.weight_used-(re.weight_used_baseline??0)),0),j=[];for(const R of ue.spools)j.push(...M.get(R.id)??[]);let E=null,B=null,W="none";const O=Kit(j);if(O!==null)E=O.rate,B=O.stdDev,W="history";else{const R=Qit(ue.spools);R!==null&&(E=R,W="delta")}const ie=B??(E!==null?E*.2:0),U=Wit*ie*Math.sqrt(le),G=he==="g"?pe:E!==null?E*pe:pe*5,K=U+G,X=E!==null?E*le+K:0,se=E&&E>0?Math.floor(we/E):null,te=se!==null?Bm(ce,se):null,fe=E&&E>0?Math.floor((we-X)/E):null,de=fe!==null?Bm(ce,Math.max(0,fe)):null,me=se!==null&&le>0&&se<=le,q=!me&&fe!==null&&fe<=0;return{group:ue,settings:oe,totalRemainingG:we,totalLabelG:$,totalSpools:ue.spools.length,totalUsedG:J,dailyRateG:E,dailyRateStdDev:B,rateTier:W,effectiveLeadTimeDays:le,safetyStockG:K,reorderPointG:X,daysRemaining:se,daysUntilROP:fe,projectedEmptyDate:te,reorderTriggerDate:de,reorderAlert:q,stockBreakAlert:me}})},[H,_,M,F]),z=y.useMemo(()=>{const ce=[...I];return ce.sort((ue,oe)=>{let Q=0,le=0;switch(u){case"material":Q=[ue.group.material,ue.group.subtype??"",ue.group.brand??""].join(" ").toLowerCase(),le=[oe.group.material,oe.group.subtype??"",oe.group.brand??""].join(" ").toLowerCase();break;case"used":Q=ue.totalUsedG,le=oe.totalUsedG;break;case"days_left":Q=ue.daysRemaining??999999,le=oe.daysRemaining??999999;break;case"stock":Q=ue.totalRemainingG,le=oe.totalRemainingG;break}const pe=Q<le?-1:Q>le?1:0;return p==="asc"?pe:-pe}),ce},[I,u,p]),L=y.useMemo(()=>I.filter(ce=>!ce.settings?.alerts_snoozed&&(ce.stockBreakAlert||ce.reorderAlert)),[I]),Z=y.useMemo(()=>[...I].filter(ce=>ce.dailyRateG!==null).sort((ce,ue)=>ue.totalUsedG-ce.totalUsedG).slice(0,5),[I]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(rc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noReadAccess")})]});function ne(ce){u===ce?f(ue=>ue==="asc"?"desc":"asc"):(m(ce),f(ce==="days_left"?"asc":"desc"))}const Y=A.length>0?A.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[L.length>0&&r.jsxs("button",{onClick:()=>d(ce=>!ce),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${L.some(ce=>ce.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(Nn,{className:"w-4 h-4"}),a("forecast.alertCount",{count:L.length}),c?r.jsx(Zo,{className:"w-3.5 h-3.5"}):r.jsx(Ln,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(tst,{value:F,onSave:ce=>{ae.updateSettings({forecast_global_lead_time_days:ce}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),n(a("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(ce=>!ce),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(sb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:a("forecast.shoppingList")}),Y&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:Y})]})]}),c&&L.length>0&&r.jsx("div",{className:"space-y-2",children:L.map(ce=>r.jsx(Zit,{forecast:ce,onCart:()=>w(ce)},ce.group.key))}),b&&r.jsx(ist,{items:A,forecasts:I,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:ce=>{ae.removeFromShoppingList(ce).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))},onClear:()=>{ae.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))}}),Z.length>0&&r.jsx(est,{forecasts:Z,days:S,onDaysChange:k}),I.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(IS,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(hN,{col:"material",active:u,dir:p,onSort:ne,children:a("forecast.sku")}),r.jsx(hN,{col:"stock",active:u,dir:p,onSort:ne,children:a("forecast.stock")}),r.jsx(hN,{col:"used",active:u,dir:p,onSort:ne,children:a("forecast.dailyRate")}),r.jsx(hN,{col:"days_left",active:u,dir:p,onSort:ne,children:a("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:z.map(ce=>r.jsx(nst,{forecast:ce,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>w(ce),showToast:n},ce.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),a("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),a("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),a("forecast.noDataLegend")]})]})]}),g&&r.jsx(ost,{forecast:g,onClose:()=>w(null),onAdd:ce=>{ae.addToShoppingList(ce).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),n(a("forecast.addedToCart"),"success"),w(null),x(!0)}).catch(()=>n(a("forecast.failedAddItem"),"error"))}})]})}function hN({col:t,active:e,dir:n,onSort:a,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>a(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?n==="asc"?r.jsx(qm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(qh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(_T,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function Zit({forecast:t,onCart:e}){const{t:n}=_t(),a=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(Nn,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:a}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.stockBreakRisk")," — ",n("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.reorderNow")," — ",n("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?_S(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(sb,{className:"w-3 h-3"})," ",n("forecast.order")]})]})}const Jit=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function est({forecasts:t,days:e,onDaysChange:n}){const{t:a}=_t(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:kX[m%kX.length],rop:u.reorderPointG,points:Yit(u,e)})),o=i.map(u=>{const m={day:u,label:Nw(Bm(new Date,u))};for(const p of s){const f=p.points.find(g=>g.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(IS,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:a("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:a("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:Jit.map(u=>r.jsx("button",{onClick:()=>n(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(nu,{width:"100%",height:220,children:r.jsxs(u5,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Tm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Am,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(au,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(L4,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(LA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(iu,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function tst({value:t,onSave:e}){const{t:n}=_t(),[a,i]=y.useState(!1),[s,o]=y.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(_i,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":n("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[n("forecast.globalLeadTime"),":"]}),a?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:n("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(uc,{className:"w-3 h-3"})})]})]})}function nst({forecast:t,globalLeadTime:e,canWrite:n,onSaved:a,onCart:i,showToast:s}){const{t:o}=_t(),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(String(t.settings?.lead_time_days??0)),[w,b]=y.useState(String(t.settings?.safety_margin_value??14)),[x,S]=y.useState(t.settings?.safety_margin_unit??"days");y.useEffect(()=>{d||g(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),y.useEffect(()=>{m||(b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const k=lt({mutationFn:ae.upsertSkuSettings,onSuccess:()=>{a(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),C=t.settings?.alerts_snoozed??!1,P=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?`#${t.group.spools[0].rgba.substring(0,6)}`:"#4B5563",A=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,F=C||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function _(z,L,Z,ne=C){k.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:z,safety_margin_value:L,safety_margin_unit:Z,alerts_snoozed:ne})}function M(z){z.stopPropagation(),_(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!C)}const H=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),I=C?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${I} ${C?"opacity-50":""}`,onClick:()=>c(z=>!z),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:P}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${A>50?"bg-bambu-green":A>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(A,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:H})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${F}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?_S(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!C&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?_S(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:z=>z.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(sb,{className:"w-4 h-4"})}),!C&&(t.stockBreakAlert?r.jsx(Nn,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(Nn,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(Ar,{className:"w-4 h-4 text-bambu-green/50"}):null),n&&r.jsx("button",{onClick:M,className:`p-1 rounded transition-colors ${C?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(C?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(FZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:z=>{z.stopPropagation(),c(L=>!L)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(xF,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(xF,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(xF,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),n&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(rst,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:g,onEdit:()=>{g(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const z=parseInt(f,10);!isNaN(z)&&z>=0&&(_(z,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(ast,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:w,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:z=>S(z),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const z=parseInt(w,10);!isNaN(z)&&z>=0&&(_(t.settings?.lead_time_days??0,z,x),p(!1))},onCancel:()=>p(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(z=>{const L=Math.max(0,z.label_weight-z.weight_used),Z=z.label_weight>0?L/z.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",z.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${Z>50?"bg-bambu-green":Z>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(Z,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(L),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(Math.max(0,z.weight_used-(z.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[z.label_weight,"g"]})})]},z.id)})})]})})]})]})})})]})}function xF({label:t,value:e,hint:n}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:n,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function rst({label:t,hint:e,unit:n,editing:a,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(_i,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(uc,{className:"w-3 h-3"})})]})]})}function ast({value:t,unit:e,editing:n,inputValue:a,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:g}=_t(),w=e==="g"?t:i!==null?Math.round(i*t):null,b=e==="days"?g("forecast.safetyMarginHintDays",{approx:w!==null?g("forecast.safetyMarginHintDaysApprox",{g:w}):""}):g("forecast.safetyMarginHintG",{approx:i!==null?g("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:b,children:r.jsx(_i,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:a,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),w!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",w,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(uc,{className:"w-3 h-3"})})]})]})}function ist({items:t,forecasts:e,globalLeadTime:n,canWrite:a,onClose:i,onRemove:s,onClear:o}){const{t:l}=_t(),c=tn(),[d,u]=y.useState("list"),m=lt({mutationFn:async({id:b,status:x,item:S,avgSpoolG:k})=>{if(await ae.updateShoppingListStatus(b,x),x==="received"&&S){const C=k??1e3,P={material:S.material,subtype:S.subtype,brand:S.brand,label_weight:C,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:S.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await ae.bulkCreateSpools(P,S.quantity_spools),await ae.removeFromShoppingList(b)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=y.useMemo(()=>{const b=new Map;for(const x of e)b.set(x.group.key,x);return b},[e]),f=y.useMemo(()=>t.map(b=>({item:b,forecast:p.get(kw(b.material,b.subtype,b.brand))??null})),[t,p]),g=y.useMemo(()=>f.filter(({forecast:b})=>!b||b.dailyRateG===null?!1:b.stockBreakAlert||b.daysRemaining!==null&&b.daysRemaining<=b.effectiveLeadTimeDays),[f]);function w(){const b=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const A=p.get(kw(T.material,T.subtype,T.brand))??null,F=A&&A.totalSpools>0?A.totalLabelG/A.totalSpools:1e3,_=Math.round(T.quantity_spools*F),M=A?.effectiveLeadTimeDays??n??0,H=M>0?_S(Bm(new Date,M)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",_,M||"",H,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(`
  8343. `),k=new Blob([S],{type:"text/csv"}),C=URL.createObjectURL(k),P=document.createElement("a");P.href=C,P.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,P.click(),setTimeout(()=>URL.revokeObjectURL(C),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(sb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Vr,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(rge,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Zr,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),a&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(Vr,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(H=>H.item.id===b.id),k=p.get(kw(b.material,b.subtype,b.brand))??null,C=k&&k.totalSpools>0?k.totalLabelG/k.totalSpools:1e3,P=Math.round(b.quantity_spools*C),T=k?.effectiveLeadTimeDays??n??0,A=T>0?Bm(new Date,T):null,F=b.status==="purchased"||b.status==="received",_=b.status==="received",M=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!F&&r.jsx(Nn,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:P>=1e3?`${(P/1e3).toFixed(1)}kg`:`${P}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:A?_S(A):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${_?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(_?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:a&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:M||_,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(fs,{className:"w-3.5 h-3.5"}):r.jsx(Vge,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:C}),disabled:M||!F||_,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Wxe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(en,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(sst,{item:b,forecast:x,globalLeadTime:n,canWrite:a,onRemove:()=>s(b.id)},b.id))})]})}function sst({item:t,forecast:e,globalLeadTime:n,canWrite:a,onRemove:i}){const{t:s}=_t(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),w=g+f,b=Math.ceil(w/u),x=Math.min(m+b+5,365),S=[];for(let k=0;k<=x;k++){const C=Nw(Bm(new Date,k));if(k===m)S.push({day:k,label:C,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:k,label:C,stock:Math.round(w),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const P=k<m?Math.max(0,e.totalRemainingG-u*k):Math.max(0,w-u*(k-m));S.push({day:k,label:C,stock:Math.round(P),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)})}}return{points:S,lt:m,maxDays:x,arrivalG:f,peakG:w,stockAtArrival:g}},[e,t.quantity_spools]),c=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return u<e.effectiveLeadTimeDays?u:null},[e]),d=c!==null;return r.jsxs("div",{className:`px-4 py-4 ${d?"bg-red-500/5":""}`,children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d?r.jsx(Nn,{className:"w-4 h-4 text-red-400 flex-shrink-0"}):r.jsx(Ar,{className:"w-4 h-4 text-bambu-green/60 flex-shrink-0"}),r.jsx("span",{className:"text-sm font-medium text-white truncate",children:o}),r.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:[s("forecast.spoolCount",{count:t.quantity_spools})," ordered"]})]}),a&&r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-red-400 transition-colors flex-shrink-0",children:r.jsx(en,{className:"w-3.5 h-3.5"})})]}),d&&r.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-300",children:[r.jsx("span",{className:"font-medium",children:s("forecast.stockBreakIn",{days:c})})," ",s("forecast.stockRunsOutBefore",{lt:e.effectiveLeadTimeDays}),e.dailyRateG!==null&&r.jsxs("span",{children:[" ",s("forecast.atRate",{rate:e.dailyRateG.toFixed(1)})," ",r.jsx("span",{className:"font-semibold",children:s("forecast.moreSpools",{count:Math.ceil((e.dailyRateG*e.effectiveLeadTimeDays-e.totalRemainingG)/(e.totalLabelG/(e.totalSpools||1)||1e3))})})," ",s("forecast.bridgeGap")]})]}),!e||e.dailyRateG===null?r.jsx("div",{className:"py-4 text-center text-xs text-bambu-gray",children:s("forecast.noUsageData")}):l?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-5 gap-2 mb-3",children:[r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg px-2.5 py-2 text-center",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-0.5",children:s("forecast.stock")}),r.jsxs("div",{className:"text-sm font-semibold text-white",children:[Math.round(e.totalRemainingG),"g"]})]}),r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg px-2.5 py-2 text-center",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-0.5",children:s("forecast.leadTime")}),r.jsxs("div",{className:"text-sm font-semibold text-white",children:[e.effectiveLeadTimeDays,"d"]}),r.jsxs("div",{className:"text-[10px] text-bambu-gray/60",children:["max(g:",n,", sku:",e.settings?.lead_time_days??0,")"]})]}),r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg px-2.5 py-2 text-center",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-0.5",children:s("forecast.safetyMarginLabel")}),r.jsxs("div",{className:"text-sm font-semibold text-white",children:[Math.round(e.safetyStockG),"g"]})]}),r.jsxs("div",{className:`rounded-lg px-2.5 py-2 text-center ${d?"bg-red-500/15":"bg-bambu-dark-tertiary/40"}`,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-0.5",children:s("forecast.daysLeft")}),r.jsxs("div",{className:`text-sm font-semibold ${d?"text-red-400":"text-green-400"}`,children:[e.daysRemaining??"—","d"]})]}),l&&r.jsxs("div",{className:"bg-bambu-green/15 rounded-lg px-2.5 py-2 text-center",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-0.5",children:s("forecast.onArrival")}),r.jsxs("div",{className:"text-sm font-semibold text-bambu-green",children:[Math.round(l.arrivalG),"g"]}),r.jsxs("div",{className:"text-[10px] text-bambu-gray/60",children:["+",s("forecast.spoolCount",{count:t.quantity_spools})]})]})]}),r.jsx(nu,{width:"100%",height:180,children:r.jsxs(u5,{data:l.points,margin:{top:8,right:8,bottom:0,left:0},children:[r.jsxs("defs",{children:[r.jsxs("linearGradient",{id:`cart-pre-${t.id}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:d?"#EF4444":"#1DB954",stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:d?"#EF4444":"#1DB954",stopOpacity:.02})]}),r.jsxs("linearGradient",{id:`cart-post-${t.id}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:"#1DB954",stopOpacity:.3}),r.jsx("stop",{offset:"95%",stopColor:"#1DB954",stopOpacity:.03})]})]}),r.jsx(Pm,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.4}),r.jsx(Tm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:9},interval:Math.max(0,Math.ceil(l.maxDays/6)-1),axisLine:!1,tickLine:!1}),r.jsx(Am,{tick:{fill:"#6B7280",fontSize:9},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(au,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(LA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(iu,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(iu,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(iu,{x:Nw(Bm(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(iu,{x:Nw(Bm(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function ost({forecast:t,onClose:e,onAdd:n}){const{t:a}=_t(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,k)=>S+k.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function w(b){b.preventDefault(),n({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(sb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:a("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:w,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:a("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:a("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:a("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:a("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:a("forecast.cancel")})]})]})]})})}const JI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},lst=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function ede(t,e=!1,n=!1){const a={};return e||n?(!t.material&&!t.spoolman_filament_id&&(a.material="Material is required"),{isValid:Object.keys(a).length===0,errors:a}):(t.slicer_filament||(a.slicer_filament="Slicer preset is required"),t.material||(a.material="Material is required"),t.brand||(a.brand="Brand is required"),t.subtype||(a.subtype="Subtype is required"),{isValid:Object.keys(a).length===0,errors:a})}const tde=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],cst=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],Cw=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","CF","GF","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"],nde=[{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"}],dst=[{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"}],NX=[...nde,...dst],rde="bambuddy-recent-colors",ust=8,mst=[{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 nf(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 a="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){a=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&a&&(o=e.substring(i+a.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of Cw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of Cw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:a,variant:l}}function ade(t,e){const n=new Set(cst);for(const a of t){const{brand:i}=nf(a.name);i&&i.length>1&&n.add(i)}if(e)for(const a of e)if(a.filament_vendor&&a.filament_vendor.length>1)n.add(a.filament_vendor);else{const{brand:i}=nf(a.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((a,i)=>a.localeCompare(i))}function pst(t){const e=t.filter(a=>a.preset_type==="filament");return e.length===0?[]:e.map(a=>{const i=String(a.id),s=a.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:a.name,displayName:a.name,isCustom:!1,allCodes:o}}).sort((a,i)=>a.displayName.localeCompare(i.displayName))}function ide(t,e,n,a){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=n&&n.length>0?pst(n):[],c=[];if(a&&a.length>0)for(const u of a){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?mst:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function sde(t,e){if(!t)return;let n=e.find(a=>a.code===t);if(n||(n=e.find(a=>a.allCodes.includes(t))),!n){const a=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===a||i.allCodes.some(s=>s.toLowerCase()===a))}return n}function ode(){try{const t=localStorage.getItem(rde);if(t)return JSON.parse(t)}catch{}return[]}function lde(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),a=[t,...n].slice(0,ust);try{localStorage.setItem(rde,JSON.stringify(a))}catch{}return a}function yF(t,e){if(!e.material)return!1;const a=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=nf(a);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())||a.toLowerCase().includes(e.subtype.toLowerCase())))}function cde({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:a,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=_t(),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[k,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(""),[_,M]=y.useState(""),[H,I]=y.useState(""),[z,L]=y.useState(String(t.label_weight)),[Z,ne]=y.useState(!1),Y=y.useRef(null),ce=y.useRef(null),ue=y.useRef(null),oe=y.useRef(null);y.useEffect(()=>{const $=J=>{Y.current&&!Y.current.contains(J.target)&&b(!1),oe.current&&!oe.current.contains(J.target)&&T(!1),ce.current&&!ce.current.contains(J.target)&&S(!1),ue.current&&!ue.current.contains(J.target)&&C(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const Q=y.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(J=>J.displayName.toLowerCase().includes($)||J.code.toLowerCase().includes($))},[l,i]),le=y.useMemo(()=>{if(!A)return c;const $=A.toLowerCase();return c.filter(j=>j.toLowerCase().includes($)).sort((j,E)=>{const B=j.toLowerCase()===$,W=E.toLowerCase()===$;return B&&!W?-1:!B&&W?1:j.localeCompare(E)})},[c,A]),pe=y.useMemo(()=>{if(!_)return Cw;const $=_.toLowerCase();return Cw.filter(J=>J.toLowerCase().includes($))},[_]),he=y.useMemo(()=>{if(!H)return d;const $=H.toLowerCase();return d.filter(j=>j.toLowerCase().includes($)).sort((j,E)=>{const B=j.toLowerCase()===$,W=E.toLowerCase()===$;return B&&!W?-1:!B&&W?1:j.localeCompare(E)})},[H,d]);y.useEffect(()=>{Z||L(String(t.label_weight))},[t.label_weight,Z]);const we=$=>{e("slicer_filament",$.code),s($.displayName),b(!1);const J=nf($.name);J.material&&e("material",J.material),J.brand&&e("brand",J.brand),J.variant&&e("subtype",J.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:a?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):n?r.jsxs(r.Fragment,{children:[r.jsx($h,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx($F,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:Y,children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.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:g("inventory.searchPresets"),value:i,onChange:$=>{s($.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),w&&r.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:Q.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):Q.map($=>r.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:()=>we($),children:$.displayName},`${$.code}::${$.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:oe,children:[r.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:g("inventory.selectMaterial"),value:P?H:t.material,onChange:$=>{I($.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),P&&r.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:[he.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):he.map($=>r.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",$),T(!1),I("")},children:$},$)),H&&!he.includes(H)&&r.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),T(!1),I("")},children:g("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.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:g("inventory.searchBrand"),value:x?A:t.brand,onChange:$=>{F($.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.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:[le.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):le.map($=>r.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",$),S(!1),F("")},children:$},$)),A&&!le.includes(A)&&r.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",A),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",value:k?_:t.subtype,onChange:$=>{M($.target.value),C(!0)},onFocus:()=>{C(!0),M("")},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"}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&r.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:[pe.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):pe.map($=>r.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",$),C(!1),M("")},children:$},$)),_&&!Cw.some($=>$.toLowerCase()===_.toLowerCase().trim())&&r.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",_),C(!1),M("")},children:g("inventory.useCustomBrand",{brand:_})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.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:z,min:0,onFocus:()=>ne(!0),onChange:$=>L($.target.value),onBlur:()=>{ne(!1);const $=z.trim(),J=Number($);if(!$||!Number.isFinite(J)||J<0){L(String(t.label_weight));return}const j=Math.round(J);e("label_weight",j),L(String(j))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.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 J=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(J)}})]})]})}function hst(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),n=[],a=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?n.push(i.toLowerCase()):a.push(i);return{value:n.join(","),invalid:a}}function dde({formData:t,updateField:e,recentColors:n,onColorUsed:a,catalogColors:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=t.rgba.replace("#","").substring(0,6),[m,p]=y.useState(u);y.useEffect(()=>{p(u)},[u]);const f=M=>u.toUpperCase()===M.toUpperCase(),g=(M,H,I,z)=>{if(e("rgba",M.toUpperCase()+"FF"),e("color_name",H),I!==void 0){const L=I??"";C(L),T([]),A.current=L,e("extra_colors",L)}z!==void 0&&e("effect_type",z??""),a({name:H,hex:M})},w=y.useMemo(()=>{if(i.length===0)return[];const M=t.brand?.trim(),H=t.material?.toLowerCase().trim(),I=t.subtype?.toLowerCase().trim();if(!M&&!H)return[];const z=M?M.toLowerCase().split(/[\s\-_]+/).filter(ne=>ne.length>=2):[],L=ne=>{if(z.length===0)return!0;const Y=ne.toLowerCase();return z.some(ce=>Y.includes(ce))};if(M&&!H){const ne=i.filter(Y=>L(Y.manufacturer));if(ne.length>0)return ne.map(Y=>({name:Y.color_name,hex:Y.hex_color.replace("#","").substring(0,6),manufacturer:Y.manufacturer,material:typeof Y.material=="string"?Y.material:void 0,extra_colors:Y.extra_colors??null,effect_type:Y.effect_type??null}))}const Z=H&&I?`${H} ${I}`:"";if(Z){const ne=i.filter(ce=>L(ce.manufacturer)&&ce.material?.toLowerCase()===Z);if(ne.length>0)return ne.map(ce=>({name:ce.color_name,hex:ce.hex_color.replace("#","").substring(0,6),manufacturer:ce.manufacturer,material:typeof ce.material=="string"?ce.material:void 0,extra_colors:ce.extra_colors??null,effect_type:ce.effect_type??null}));const Y=Z.replace(/\+$/,"");if(Y!==Z){const ce=i.filter(ue=>L(ue.manufacturer)&&ue.material?.toLowerCase()===Y);if(ce.length>0)return ce.map(ue=>({name:ue.color_name,hex:ue.hex_color.replace("#","").substring(0,6),manufacturer:ue.manufacturer,material:typeof ue.material=="string"?ue.material:void 0}))}}if(H){const ne=i.filter(Y=>L(Y.manufacturer)&&(!Y.material||Y.material.toLowerCase().startsWith(H)));if(ne.length>0)return ne.map(Y=>({name:Y.color_name,hex:Y.hex_color.replace("#","").substring(0,6),manufacturer:Y.manufacturer,material:typeof Y.material=="string"?Y.material:void 0,extra_colors:Y.extra_colors??null,effect_type:Y.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),b=y.useMemo(()=>{if(!c)return w;if(w.length===0)return[];const M=c.toLowerCase();return w.filter(I=>I.name.toLowerCase().includes(M)||(I.manufacturer?.toLowerCase().includes(M)??!1)||(I.material?.toLowerCase().includes(M)??!1))},[c,w]),x=w.length>0,S=y.useMemo(()=>c?NX.filter(M=>M.name.toLowerCase().includes(c.toLowerCase())):o?NX:nde,[c,o]),[k,C]=y.useState(t.extra_colors),[P,T]=y.useState([]),A=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==A.current&&(C(t.extra_colors),T([]),A.current=t.extra_colors)},[t.extra_colors]);const F=y.useMemo(()=>ij({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),_=M=>{if(C(M),!M.trim()){T([]),A.current="",e("extra_colors","");return}const{value:H,invalid:I}=hst(M);T(I),A.current=H,e("extra_colors",H)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:F,"data-testid":"color-preview-banner"}),n.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zn,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.name},M.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.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:M=>d(M.target.value)})]}),x?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name,M.extra_colors,M.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.manufacturer&&M.material?`${M.name} (${M.manufacturer} — ${M.material})`:M.manufacturer?`${M.name} (${M.manufacturer})`:M.name,children:r.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:M.manufacturer&&M.material?`${M.name} (${M.manufacturer} — ${M.material})`:M.manufacturer?`${M.name} (${M.manufacturer})`:M.name})},`${M.hex}-${M.name}-${M.manufacturer??""}`)),b.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(Zo,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Ln,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[S.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.name,children:r.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:M.name})},M.hex)),S.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.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:M=>e("color_name",M.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.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:m.toUpperCase(),onChange:M=>{const H=M.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase(),I=H.length>6?H.substring(0,6):H;p(I),I.length===6&&e("rgba",I+"FF")},onBlur:()=>{if(m.length>0&&m.length<6){const M=m.padEnd(6,"0");p(M),e("rgba",M+"FF")}}})]}),r.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:M=>{const H=M.target.value.replace("#","").toUpperCase();e("rgba",H+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.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 font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:k,onChange:M=>_(M.target.value),"data-testid":"extra-colors-input"}),P.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:P.join(", ")})}),!P.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Mg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 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:t.effect_type,onChange:M=>e("effect_type",M.target.value),"data-testid":"effect-type-select",children:XI.map(M=>r.jsx("option",{value:M.value,children:s(M.labelKey)},M.value||"none"))}),r.jsx(lU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function fst({catalog:t,value:e,onChange:n,catalogId:a,onCatalogIdChange:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const w=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),y.useEffect(()=>{if(t.length===0)return;const w=t.filter(b=>b.weight===e);if(a){const b=t.find(x=>x.id===a);if(b&&b.weight===e)return}w.length===1?i(w[0].id):w.length===0&&a!==null&&i(null)},[e,t,a,i]);const p=y.useMemo(()=>{if(!c)return t;const w=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(w)||b.weight.toString().includes(w))},[t,c]),f=y.useMemo(()=>t.filter(w=>w.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(a){const w=t.find(b=>b.id===a);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,a,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(qZ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.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:g,onFocus:()=>{l(!0),d("")},onChange:w=>{d(w.target.value),l(!0)}}),o&&r.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?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(w=>r.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 ${(a?w.id===a:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),n(w.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[w.weight,"g"]})]},w.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.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:w=>{const b=parseInt(w.target.value);!isNaN(b)&&b>=0&&n(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function ude({formData:t,updateField:e,spoolCatalog:n,currencySymbol:a,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=_t(),{showToast:c}=on(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[w,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{w||g(String(x))},[w,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(fst,{catalog:n,value:t.core_weight,onChange:k=>e("core_weight",k),catalogId:t.core_weight_catalog_id,onCatalogIdChange:k=>e("core_weight_catalog_id",k)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:k=>{g(k.target.value)},onBlur:()=>{b(!1);const k=f.trim(),C=Number(k);if(!k||!Number.isFinite(C)||C<0||C>t.label_weight){g(String(x));return}const P=Math.round(C);e("weight_used",Math.max(0,t.label_weight-P)),g(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"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:k=>{u(k.target.value)},onBlur:()=>{p(!1);const k=d.trim(),C=Number(k),P=t.core_weight,T=t.core_weight+t.label_weight;if(!k||!Number.isFinite(C)||C<P||C>T){c(l("inventory.measuredWeightError",{min:P,max:T}),"error"),u(String(S));return}const A=Math.round(C),F=Math.max(0,Math.min(t.label_weight,A-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(A))},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"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:a}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:k=>{const C=k.target.value===""?null:parseFloat(k.target.value);e("cost_per_kg",C)},style:{paddingLeft:`${Math.max(2,a.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"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",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:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:k=>e("category",k.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(k=>r.jsx("option",{value:k},k))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 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:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:k=>{const C=k.target.value;if(C===""){e("low_stock_threshold_pct",null);return}const P=Number(C);Number.isFinite(P)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(P))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.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:l("inventory.notePlaceholder"),value:t.note,onChange:k=>e("note",k.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,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:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:k=>e("storage_location",k.target.value)})]})]})}function gst({filaments:t,isLoading:e,selectedId:n,onSelect:a}){const{t:i}=_t(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===n)??null,[t,n]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{a(b),o(!1),c("")},w=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(ft,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Vr,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===n?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function mde({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:a,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=_t(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const w=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;a(x=>{const S=new Set(x);if(S.has(w))S.delete(w);else{for(const k of Array.from(S)){const C=k.split(":");`${C[0]}:${C[2]}`===b&&S.delete(k)}S.add(w)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const w=g.filter(x=>yF(x,t)),b=new Map;for(const x of w){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const C=[...S].sort((P,T)=>T.k_value-P.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${x}`)}}a(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(w=>yF(w,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=n.has(g);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${w?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:w,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"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${w?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.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 r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.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&&r.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:[r.jsx(Mg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),w=f.filter(C=>yF(C,t)),b=w.length,x=w.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),S=w.filter(C=>C.extruder_id===1),k=w.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.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:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(qa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.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")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(C=>m(p,C))})]}),k.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:k.map(C=>m(p,C))})]})]}):r.jsx("div",{className:"space-y-2",children:w.map(C=>m(p,C))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function bst(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 xst={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function yst({spoolId:t}){const{t:e}=_t(),n=tn(),{showToast:a}=on(),{data:i,isLoading:s}=Xe({queryKey:["spool-usage",t],queryFn:()=>ae.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>ae.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),a(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ft,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:bst(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:xst[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const CX={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function vst({isOpen:t,onClose:e,spool:n,mode:a,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=_t(),u=tn(),{showToast:m}=on(),p=a==="edit",f=a==="copy",[g,w]=y.useState(JI),[b,x]=y.useState({}),[S,k]=y.useState("filament"),[C,P]=y.useState(!1),[T,A]=y.useState(!1),[F,_]=y.useState(!1),[M,H]=y.useState(1),[I,z]=y.useState(!1),[L,Z]=y.useState(!1),[ne,Y]=y.useState([]),[ce,ue]=y.useState(""),[oe,Q]=y.useState([]),[le,pe]=y.useState([]),[he,we]=y.useState([]),[$,J]=y.useState([]),[j,E]=y.useState([]),[B,W]=y.useState([]),[O,ie]=y.useState(new Set),[U,G]=y.useState(new Set),K=i.length>0?i:B,X=O.size,{data:se=[],isLoading:te,error:fe}=Xe({queryKey:["spoolman-inventory-filaments"],queryFn:()=>ae.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{E(ode())},[]),y.useEffect(()=>{t&&((async()=>{Z(!0);try{const tt=await ae.getCloudStatus();if(z(tt.is_authenticated),tt.is_authenticated){const ot=await ae.getFilamentPresets();Y(ot)}}catch(tt){console.error("Failed to fetch cloud presets:",tt),z(!1)}finally{Z(!1)}})(),l||ae.getSpoolCatalog().then(Q).catch(console.error),ae.getColorCatalog().then(J).catch(console.error),ae.getLocalPresets().then(tt=>pe(tt.filament)).catch(console.error),ae.getBuiltinFilaments().then(we).catch(console.error),i.length===0&&(async()=>{try{const tt=await ae.getPrinters(),ot=await Promise.all(tt.map(Ut=>ae.getPrinterStatus(Ut.id).catch(()=>null))),Tt=[];for(let Ut=0;Ut<tt.length;Ut++){const bt=tt[Ut],Zt=ot[Ut]?.connected??!1;let ln=[];if(Zt)try{ln=(await ae.getKProfiles(bt.id)).profiles.map(ct=>({cali_idx:ct.slot_id,filament_id:ct.filament_id,setting_id:ct.setting_id||"",name:ct.name,k_value:parseFloat(ct.k_value)||0,n_coef:parseFloat(ct.n_coef)||0,extruder_id:ct.extruder_id,nozzle_diameter:ct.nozzle_diameter}))}catch{}Tt.push({printer:{...bt,connected:Zt},calibrations:ln})}W(Tt)}catch(tt){console.error("Failed to fetch printer calibrations:",tt)}})())},[t,i.length]);const de=y.useMemo(()=>ide(ne,new Set,le,he),[ne,le,he]),me=y.useMemo(()=>{const Te=ade(ne,le),tt=$.map(Tt=>Tt.manufacturer?.trim()).filter(Tt=>!!Tt),ot=new Set([...Te,...tt]);return Array.from(ot).sort((Tt,Ut)=>Tt.localeCompare(Ut))},[ne,le,$]),q=y.useMemo(()=>{const Te=$.map(ot=>ot.material?.trim()).filter(ot=>!!ot),tt=new Set([...tde,...Te]);return Array.from(tt).sort((ot,Tt)=>ot.localeCompare(Tt))},[$]),R=y.useMemo(()=>{const Te=[];for(const tt of $){const ot=tt.manufacturer?.trim(),Tt=tt.material?.trim();ot&&Tt&&Te.push({brand:ot,material:Tt})}for(const tt of ne){const ot=nf(tt.name);ot.brand&&ot.material&&Te.push({brand:ot.brand,material:ot.material})}for(const tt of le){const ot=nf(tt.name),Tt=tt.filament_vendor?.trim()||ot.brand,Ut=ot.material;Tt&&Ut&&Te.push({brand:Tt,material:Ut})}return Te},[ne,$,le]),re=y.useMemo(()=>{const Te=new Map;for(const tt of R){const ot=tt.brand.toLowerCase(),Tt=tt.material.toLowerCase();Te.has(ot)||Te.set(ot,new Set),Te.get(ot).add(Tt)}return Te},[R]),be=y.useMemo(()=>{const Te=new Map;for(const tt of R){const ot=tt.brand.toLowerCase(),Tt=tt.material.toLowerCase();Te.has(Tt)||Te.set(Tt,new Set),Te.get(Tt).add(ot)}return Te},[R]),ye=y.useMemo(()=>{if(!g.material)return me;const Te=g.material.toLowerCase(),tt=be.get(Te);return!tt||tt.size===0?me:me.filter(ot=>tt.has(ot.toLowerCase()))},[me,g.material,be]),_e=y.useMemo(()=>{if(!g.brand)return q;const Te=g.brand.toLowerCase(),tt=re.get(Te);return!tt||tt.size===0?q:q.filter(ot=>tt.has(ot.toLowerCase()))},[q,g.brand,re]),xe=y.useMemo(()=>sde(g.slicer_filament,de),[g.slicer_filament,de]);y.useEffect(()=>{if(t){if(n){const Te=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(w({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name_is_synthesized?"":n.color_name||"",rgba:Te,extra_colors:n.extra_colors||"",effect_type:n.effect_type||"",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:f?0:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null,category:n.category||"",low_stock_threshold_pct:n.low_stock_threshold_pct??null,storage_location:n.storage_location||"",spoolman_filament_id:null}),ue(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const tt=new Set;for(const ot of n.k_profiles)ot.cali_idx!==null&&ot.cali_idx!==void 0&&tt.add(`${ot.printer_id}:${ot.cali_idx}:${ot.extruder??"null"}`);ie(tt)}else ie(new Set)}else w(JI),ue(""),ie(new Set),_(!1),H(1);x({}),k("filament"),P(!1),A(!1)}},[t,n,a,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Te=>String(Te.printer.id))))},[t,K]);const ge=(Te,tt)=>{const ot=lst.has(Te);l&&ot&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(Tt=>({...Tt,[Te]:tt,...l&&ot&&Tt.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Te==="weight_used"&&P(!0),Te==="storage_location"&&A(!0),b[Te]&&x(Tt=>({...Tt,[Te]:void 0}))},Me=Te=>{const tt=Te.material||"",ot=Te.name||"",Tt=tt&&ot.startsWith(tt)?ot.slice(tt.length).trim():ot,Ut=(Te.color_hex??"").replace("#","").toUpperCase(),bt=/^[0-9A-F]{6}$/.test(Ut)?Ut:"808080";w(Wt=>({...Wt,spoolman_filament_id:Te.id,material:tt,subtype:Tt,brand:Te.vendor?.name||"",rgba:`${bt}FF`,color_name:Te.color_name||"",label_weight:Te.weight??Wt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},Be=Te=>{E(tt=>lde(Te,tt))},Fe=lt({mutationFn:Te=>l?ae.createSpoolmanInventorySpool(Te):ae.createSpool(Te),onSuccess:async Te=>{Te?.id&&!await Ve(Te.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Te]),m(d("inventory.spoolCreated"),"success"),e())},onError:Te=>{Te instanceof rs&&Te.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Oe=lt({mutationFn:({data:Te,qty:tt})=>l?ae.bulkCreateSpoolmanInventorySpools(Te,tt):ae.bulkCreateSpools(Te,tt),onSuccess:async Te=>{const tt=l&&"created"in Te?Te:null,ot=tt?tt.created:Te;if(O.size>0)for(const Tt of ot)await Ve(Tt.id);await u.invalidateQueries({queryKey:c}),o&&o(ot),tt&&tt.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:ot.length,total:tt.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:ot.length}),"success"),e()},onError:Te=>{Te instanceof rs&&Te.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Re=lt({mutationFn:Te=>l?ae.updateSpoolmanInventorySpool(n.id,Te):ae.updateSpool(n.id,Te),onSuccess:async()=>{n?.id&&!await Ve(n.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Te=>{Te instanceof rs&&Te.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),We=lt({mutationFn:()=>l?ae.updateSpoolmanInventorySpool(n.id,CX):ae.updateSpool(n.id,CX),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Te=>{Te instanceof rs&&Te.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:ze}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),enabled:t&&p&&!l}),{data:st}=Xe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Ee=(()=>{if(n)return l?st?.find(Te=>Te.spoolman_spool_id===n.id):ze?.find(Te=>Te.spool_id===n.id)})(),{data:it}=Xe({queryKey:["inventory-spools"],queryFn:()=>ae.getSpools(!0),enabled:t}),{data:Ce}=Xe({queryKey:["settings"],queryFn:ae.getSettings,enabled:t}),Ze=(()=>{const Te=new Set;for(const tt of it??[]){const ot=tt.category?.trim();ot&&Te.add(ot)}return Array.from(Te).sort((tt,ot)=>tt.localeCompare(ot))})(),Ie=Ce?.low_stock_threshold??20,ke=lt({mutationFn:async()=>{if(!Ee)throw new Error("No assignment");if(l){if(!n)throw new Error("No spool");await ae.unassignSpoolmanSlot(n.id);return}await ae.unassignSpool(Ee.printer_id,Ee.ams_id,Ee.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Te=>{m(Te.message,"error")}}),Ve=async Te=>{const tt=l?ae.saveSpoolmanKProfiles:ae.saveSpoolKProfiles;if(O.size===0)try{return await tt(Te,[]),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const ot=[];let Tt=0;for(const Ut of O){const[bt,Wt,Zt]=Ut.split(":"),ln=parseInt(bt),cn=parseInt(Wt),ct=Zt==="null"?0:parseInt(Zt),kt=K.find(Nt=>Nt.printer.id===ln);if(kt){const Nt=kt.calibrations.find(ut=>ut.cali_idx===cn);Nt?ot.push({printer_id:ln,extruder:ct,nozzle_diameter:Nt.nozzle_diameter||"0.4",k_value:Nt.k_value,name:Nt.name||null,cali_idx:Nt.cali_idx,setting_id:Nt.setting_id||null}):Tt++}else Tt++}if(Tt>0)return console.error(`saveKProfiles: ${Tt} profile key(s) could not be resolved`,Array.from(O)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(ot.length>0)try{return await tt(Te,ot),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Te=tt=>{tt.key==="Escape"&&e()};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,e]),!t)return null;const rt=()=>{const Te=ede(g,F,l);if(!Te.isValid){x(Te.errors),(Te.errors.slicer_filament||Te.errors.material||Te.errors.brand||Te.errors.subtype)&&k("filament");return}const tt=xe?.displayName||ce||null,ot={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:tt,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||C)&&(ot.weight_used=g.weight_used),(!p||T)&&(ot.storage_location=g.storage_location||null),p?Re.mutate(ot):M>1?Oe.mutate({data:ot,qty:M}):Fe.mutate(ot)},Qe=Fe.isPending||Oe.isPending||Re.isPending||We.isPending||ke.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-baseline gap-2",children:[d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool"),p&&n&&r.jsxs("span",{className:"text-sm font-mono text-bambu-gray",children:["#",n.id]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),a==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(wc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{_(!F),F||k("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>k("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(ES,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>k("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Ffe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),X>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:X})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:fe?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(gst,{filaments:se,isLoading:te,selectedId:g.spoolman_filament_id,onSelect:Me})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(cde,{formData:g,updateField:ge,cloudAuthenticated:I,loadingCloudPresets:L,presetInputValue:ce,setPresetInputValue:ue,selectedPresetOption:xe,filamentOptions:de,availableBrands:ye,availableMaterials:_e,quickAdd:F,quantity:M,onQuantityChange:H,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(dde,{formData:g,updateField:ge,recentColors:j,onColorUsed:Be,catalogColors:$})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(ude,{formData:g,updateField:ge,spoolCatalog:oe,currencySymbol:s,availableCategories:Ze,globalLowStockThreshold:Ie,spoolmanMode:l})]}),p&&n&&!l&&r.jsx("div",{children:r.jsx(yst,{spoolId:n.id})})]}):r.jsx(mde,{formData:g,updateField:ge,printersWithCalibrations:K,selectedProfiles:O,setSelectedProfiles:ie,expandedPrinters:U,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(je,{variant:"secondary",onClick:()=>We.mutate(),disabled:Qe||!n?.tag_uid,children:[r.jsx(Vm,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(je,{variant:"secondary",onClick:()=>ke.mutate(),disabled:Qe||!Ee,children:[r.jsx(ou,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(je,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(je,{onClick:rt,disabled:Qe,children:Qe?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ds,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function wst({isOpen:t,onClose:e,columns:n,defaultColumns:a,onSave:i}){const{t:s}=_t(),[o,l]=y.useState(n),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),y.useEffect(()=>{if(!t)return;const C=P=>{P.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(P=>P.map((T,A)=>A===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const A=[...T],[F]=A.splice(C,1);return A.splice(P,0,F),A})},f=(C,P)=>{u.current=P,d(P),C.dataTransfer.effectAllowed="move"},g=(C,P)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==P&&(p(T,P),u.current=P,d(P))},w=C=>{C.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(a.map(C=>({...C})))},S=()=>{i(o),e()},k=o.filter(C=>C.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(Et,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,P)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===P?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,P),onDragOver:T=>g(T,P),onDrop:w,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ah,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(P,P-1),disabled:P===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:r.jsx(Zo,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(P,P+1),disabled:P===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:r.jsx(Ln,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(P),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?r.jsx(Cl,{className:"w-4 h-4"}):r.jsx(ab,{className:"w-4 h-4"})})]},C.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(je,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(fs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(je,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(je,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Sst=[{value:"ams_holder_74x33",i18nKey:"amsHolderSmall",fallbackLabel:"AMS holder — small (74 × 33 mm)",fallbackHint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},{value:"ams_holder_75x55",i18nKey:"amsHolderLarge",fallbackLabel:"AMS holder — large (75 × 55 mm)",fallbackHint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function _st(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const a=document.createElement("a");a.href=e,a.download="bambuddy-labels.pdf",document.body.appendChild(a),a.click(),document.body.removeChild(a)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function kst(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function Nst(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,n=t.brand?` · ${t.brand}`:"";return`${e}${n}`}function Cst(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function PX(t){if(!t)return[1,0];const e=t.replace(/^#/,"").slice(0,6);if(e.length!==6)return[1,0];const n=parseInt(e.slice(0,2),16),a=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);if([n,a,i].some(Number.isNaN))return[1,0];const s=n/255,o=a/255,l=i/255,c=Math.max(s,o,l),d=Math.min(s,o,l),u=(c+d)/2,m=c-d;if((m===0?0:m/(1-Math.abs(2*u-1)))<.1)return[1,u];let f=0;return c===s?f=(o-l)/m%6:c===o?f=(l-s)/m+2:f=(s-o)/m+4,f=f*60,f<0&&(f+=360),[0,f]}function Pst({isOpen:t,onClose:e,availableSpools:n,initialSelectedIds:a,spoolmanMode:i}){const{t:s}=_t(),{showToast:o}=on(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState(""),[w,b]=y.useState("id");y.useEffect(()=>{if(t){const I=new Set(n.map(z=>z.id));u(new Set(a.filter(z=>I.has(z)))),p(""),g(""),b("id"),c(null)}},[t]);const x=y.useMemo(()=>{const I=[...n];return w==="color"?(I.sort((z,L)=>{const Z=PX(z.rgba),ne=PX(L.rgba);return Z[0]!==ne[0]?Z[0]-ne[0]:Z[1]!==ne[1]?Z[1]-ne[1]:z.id-L.id}),I):(I.sort((z,L)=>z.id-L.id),I)},[n,w]),S=y.useMemo(()=>{const I=new Set;for(const z of x)z.material&&I.add(z.material.toUpperCase());return[...I].sort()},[x]),k=y.useMemo(()=>{const I=m.trim().toLowerCase();return x.filter(z=>!(f&&(z.material||"").toUpperCase()!==f||I&&!Cst(z).includes(I)))},[x,m,f]),C=k.length>0&&k.every(I=>d.has(I.id));if(!t)return null;const P=d.size,T=P===0;function A(I){u(z=>{const L=new Set(z);return L.has(I)?L.delete(I):L.add(I),L})}function F(){u(I=>{const z=new Set(I);for(const L of k)z.add(L.id);return z})}function _(){u(I=>{const z=new Set(I);for(const L of k)z.delete(L.id);return z})}function M(){u(new Set)}async function H(I){if(T||l)return;const z=x.filter(L=>d.has(L.id)).map(L=>L.id);c(I);try{const L=i?await ae.printSpoolmanSpoolLabels({spool_ids:z,template:I}):await ae.printSpoolLabels({spool_ids:z,template:I});_st(L),e()}catch(L){const Z=L instanceof Error?L.message:String(L);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:Z}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),P>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:P}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:I=>p(I.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),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"})]}),S.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),S.map(I=>r.jsx("button",{type:"button",onClick:()=>g(I),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===I?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:I},I))]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.sortBy.label")}),r.jsx("button",{type:"button",onClick:()=>b("id"),className:`px-2 py-0.5 text-xs rounded-full border transition ${w==="id"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.id")}),r.jsx("button",{type:"button",onClick:()=>b("color"),className:`px-2 py-0.5 text-xs rounded-full border transition ${w==="color"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.color")})]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:C?_:F,disabled:k.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:C?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:k.length})}),r.jsx("button",{type:"button",onClick:M,disabled:P===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:k.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:x.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:k.map(I=>{const z=d.has(I.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[z?r.jsx(gs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(ro,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:z,onChange:()=>A(I.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:kst(I.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:Nst(I)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",I.id]})]})},I.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Sst.map(I=>{const z=l===I.value,L=s(`inventory.labels.templates.${I.i18nKey}.label`,I.fallbackLabel),Z=s(`inventory.labels.templates.${I.i18nKey}.hint`,I.fallbackHint);return r.jsxs("button",{disabled:T||l!==null,onClick:()=>H(I.value),title:`${L} — ${Z}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:L}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:Z})]}),z&&r.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},I.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(je,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function TX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const pde="bambuddy-inventory-columns",$N=[{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:"storage_location",label:"Storage Location",visible:!1},{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 Tst(){try{const t=localStorage.getItem(pde);if(t){const e=JSON.parse(t),n=new Set($N.map(o=>o.id)),a=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=$N.filter(o=>!a.has(o.id));return[...i,...s]}}catch{}return $N.map(t=>({...t}))}function Ast(t){try{localStorage.setItem(pde,JSON.stringify(t))}catch{}}function su(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const jst={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 vF(t,e="system"){if(!t)return"-";const n=Yn(t);return n?JF(n,e):"-"}const Mst={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",storage_location:t=>t("inventory.storageLocation"),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")},eO={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:vF(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:vF(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?vF(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(lU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:AT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.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 r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const a=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=u_(n.ams_id,n.tray_id,s,i);return r.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:[a," ",o,n.ams_label?` (${n.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:su(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:su(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:su(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?su(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.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?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.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?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.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})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.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)}%`}})}),r.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 r.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.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 r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const a=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+a;let s,o;n<a?(s=n-a,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
  8344. Calculated: ${Math.round(i)}g
  8345. Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g
  8346. Calculated: ${Math.round(i)}g
  8347. Difference: ${l}g (mismatch!)`;return r.jsxs("div",{className:`flex items-center gap-1 text-sm font-medium ${o?"text-green-400":"text-yellow-400"}`,title:c,children:[r.jsxs("span",{children:[Math.round(n),"g"]}),o?r.jsx(Ar,{className:"w-3 h-3"}):r.jsxs(r.Fragment,{children:[r.jsx(Nn,{className:"w-3 h-3"}),e&&r.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:r.jsx(tr,{className:"w-3.5 h-3.5"})})]})]})}},wF={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 a=n.ams_id===254||n.ams_id===255,i=!a&&n.ams_id>=128,s=n.ams_label?` (${n.ams_label})`:"";return`${n.printer_name||""} ${u_(n.ams_id,n.tray_id,i,a)}${s}`},storage_location:t=>(t.storage_location||"").toLowerCase(),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)}},tO="bambuddy-inventory-sort";function Est(){try{const t=localStorage.getItem(tO);if(t)return JSON.parse(t)}catch{}return null}function Dst(t){try{t?localStorage.setItem(tO,JSON.stringify(t)):localStorage.removeItem(tO)}catch{}}function Fst(){const{data:t}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings,staleTime:3e5}),e=t!==void 0,n=t?.spoolman_enabled==="true"&&!!t?.spoolman_url;return r.jsx(Lst,{spoolmanMode:n,spoolmanModeReady:e})}function Lst({spoolmanMode:t=!1,spoolmanModeReady:e=!0}){const{t:n}=_t(),a=tn(),{showToast:i}=on(),{hasPermission:s,loading:o}=dr(),l=!o&&s("inventory:forecast_read"),[c,d]=nb(),[u,m]=y.useState(null),p=y.useRef(!1),[f,g]=y.useState(null),[w,b]=y.useState(null),[x,S]=y.useState("active"),[k,C]=y.useState("all"),[P,T]=y.useState(""),[A,F]=y.useState(""),[_,M]=y.useState(""),[H,I]=y.useState(""),[z,L]=y.useState("all"),[Z,ne]=y.useState(""),[Y,ce]=y.useState(""),[ue,oe]=y.useState("table"),[Q,le]=y.useState(Est),[pe,he]=y.useState(Tst),[we,$]=y.useState(!1),[J,j]=y.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[E,B]=y.useState(new Set),[W,O]=y.useState(0),[ie,U]=y.useState(()=>{try{const Ue=localStorage.getItem("bambuddy-inventory-pageSize");if(Ue){const He=Number(Ue);if([15,30,50,100,-1].includes(He))return He}}catch{}return 15}),{data:G}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),K=G?.date_format||"system",X=t?["spoolman-inventory-spools"]:["inventory-spools"],{data:se,isLoading:te}=Xe({queryKey:X,queryFn:()=>t?ae.getSpoolmanInventorySpools(!0):ae.getSpools(!0),refetchInterval:3e4}),fe=c.get("spool"),de=fe&&/^\d+$/.test(fe)&&Number(fe)>0?Number(fe):null,me=se?.find(Ue=>Ue.id===de)??null,q=y.useCallback(()=>{p.current=!0,d(Ue=>(Ue.delete("spool"),Ue),{replace:!0})},[d]),{data:R,isError:re,error:be}=Xe({queryKey:t?["spoolman-inventory-spool",de]:["inventory-spool",de],queryFn:()=>t?ae.getSpoolmanInventorySpool(de):ae.getSpool(de),enabled:e&&de!==null&&me===null,staleTime:1/0,retry:(Ue,He)=>Ue<2&&!(He instanceof rs&&He.status===404)});y.useEffect(()=>{if(!p.current){if(e&&de&&me){q(),m({spool:me,mode:"edit"});return}if(R){q(),m({spool:R,mode:"edit"});return}if(re){q();const Ue=be instanceof rs&&be.status===404;i(n(Ue?"inventory.deepLinkSpoolNotFound":"inventory.deepLinkFetchFailed"),"error")}}},[e,de,me,R,re,be,q,i,n]);const{data:ye}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),refetchInterval:3e4}),{data:_e=[],isError:xe}=Xe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:t,refetchInterval:3e4,staleTime:1e4,retry:1}),ge=y.useRef(!1);y.useEffect(()=>{xe&&!ge.current?(ge.current=!0,i(n("inventory.spoolmanUnreachable"),"error")):xe||(ge.current=!1)},[xe,i,n]);const{data:Me}=Xe({queryKey:["spool-catalog"],queryFn:()=>ae.getSpoolCatalog()}),Be=lt({mutationFn:Ue=>t?ae.deleteSpoolmanInventorySpool(Ue):ae.deleteSpool(Ue),onSuccess:()=>{a.invalidateQueries({queryKey:X}),i(n("inventory.spoolDeleted"),"success")},onError:Ue=>{Ue instanceof rs&&Ue.status===404?i(n("inventory.deleteSpoolNotFound"),"error"):Ue instanceof rs&&Ue.status===503?i(n("inventory.spoolmanUnreachable"),"error"):i(n("inventory.deleteFailed"),"error")}}),Fe=lt({mutationFn:Ue=>t?ae.archiveSpoolmanInventorySpool(Ue):ae.archiveSpool(Ue),onSuccess:()=>{a.invalidateQueries({queryKey:X}),i(n("inventory.spoolArchived"),"success")},onError:Ue=>{Ue instanceof rs&&Ue.status===404?i(n("inventory.archiveSpoolNotFound"),"error"):Ue instanceof rs&&Ue.status===503?i(n("inventory.spoolmanUnreachable"),"error"):i(n("inventory.archiveFailed"),"error")}}),Oe=lt({mutationFn:Ue=>t?ae.restoreSpoolmanInventorySpool(Ue):ae.restoreSpool(Ue),onSuccess:()=>{a.invalidateQueries({queryKey:X}),i(n("inventory.spoolRestored"),"success")},onError:Ue=>{Ue instanceof rs&&Ue.status===404?i(n("inventory.restoreSpoolNotFound"),"error"):Ue instanceof rs&&Ue.status===503?i(n("inventory.spoolmanUnreachable"),"error"):i(n("inventory.restoreFailed"),"error")}}),Re=lt({mutationFn:Ue=>t?ae.resetSpoolmanInventorySpoolUsage(Ue):ae.resetSpoolUsage(Ue),onSuccess:()=>{a.invalidateQueries({queryKey:X}),i(n("inventory.usageReset"),"success")},onError:()=>{i(n("inventory.resetUsageFailed"),"error")}}),We=lt({mutationFn:Ue=>t?ae.bulkResetSpoolmanInventorySpoolUsage(Ue):ae.bulkResetSpoolUsage(Ue),onSuccess:Ue=>{a.invalidateQueries({queryKey:X}),i(n("inventory.allUsageReset",{count:Ue.reset}),"success")},onError:()=>{i(n("inventory.resetUsageFailed"),"error")}}),ze=y.useMemo(()=>(se??[]).map(Ue=>Ue.id),[se]),st=async Ue=>{if(Ue.last_scale_weight!=null)try{t?await ae.syncSpoolmanSpoolWeight(Ue.id,Ue.last_scale_weight):await Jr.updateSpoolWeight(Ue.id,Ue.last_scale_weight),a.invalidateQueries({queryKey:X});const He=[Ue.brand,Ue.material,Ue.color_name].filter(Boolean).join(" ");i(`Synced "${He}" to scale weight`,"success")}catch(He){const Dt=He instanceof rs&&He.status===404,Rt=He instanceof rs&&He.status===503;i(n(Dt?"inventory.syncWeightSpoolNotFound":Rt?"inventory.syncWeightSpoolmanUnreachable":"inventory.syncWeightFailed"),"error")}},Ee=G?.low_stock_threshold??20,[it,Ce]=y.useState(!1),[Ze,Ie]=y.useState(Ee.toString());y.useEffect(()=>{it||Ie(Ee.toString())},[Ee,it]);const ke=lt({mutationFn:Ue=>ae.updateSettings({low_stock_threshold:Ue}),onSuccess:()=>{a.invalidateQueries({queryKey:["settings"]}),i(n("common.saved"),"success"),Ce(!1)},onError:()=>{i(n("inventory.lowStockThresholdError"),"error")}}),Ve=y.useMemo(()=>{if(!se)return null;let Ue=0,He=0,Dt=0,Rt=0;const qe={};for(const Ke of se){if(He+=Math.max(0,Ke.weight_used-(Ke.weight_used_baseline??0)),Ke.archived_at)continue;Rt++;const Bt=Math.max(0,Ke.label_weight-Ke.weight_used);Ue+=Bt;const Qt=Ke.label_weight>0?Bt/Ke.label_weight*100:0,dn=Ke.low_stock_threshold_pct??Ee;Qt<dn&&Dt++;const nn=Ke.material||"Unknown";qe[nn]||(qe[nn]={count:0,weight:0}),qe[nn].count++,qe[nn].weight+=Bt}return{totalWeight:Ue,totalConsumed:He,lowStock:Dt,byMaterial:qe,totalSpools:Rt}},[se,Ee]),rt=(ye?.length??0)+(t?_e.length:0),Qe=Ho(G?.currency||"USD"),Te=y.useMemo(()=>{const Ue={};for(const He of ye||[])Ue[He.spool_id]={printer_id:He.printer_id,printer_name:He.printer_name,ams_id:He.ams_id,tray_id:He.tray_id,ams_label:He.ams_label??null};for(const He of _e)typeof He?.spoolman_spool_id!="number"||He.spoolman_spool_id<=0||typeof He.printer_id!="number"||typeof He.ams_id!="number"||typeof He.tray_id!="number"||Ue[He.spoolman_spool_id]||(Ue[He.spoolman_spool_id]={printer_id:He.printer_id,printer_name:He.printer_name??null,ams_id:He.ams_id,tray_id:He.tray_id,ams_label:He.ams_label??null});return Ue},[ye,_e]),tt=y.useMemo(()=>{const Ue={};for(const He of Me||[])Ue[He.id]=He;return Ue},[Me]),ot=y.useMemo(()=>Ve?Object.entries(Ve.byMaterial).sort((Ue,He)=>He[1].weight-Ue[1].weight).slice(0,4):[],[Ve]),Tt=y.useMemo(()=>{let Ue=se||[];if(x==="active"?Ue=Ue.filter(He=>!He.archived_at):Ue=Ue.filter(He=>!!He.archived_at),k==="used"?Ue=Ue.filter(He=>He.weight_used>0):k==="new"?Ue=Ue.filter(He=>He.weight_used===0):k==="lowstock"&&(Ue=Ue.filter(He=>{const Dt=Math.max(0,He.label_weight-He.weight_used),Rt=He.label_weight>0?Dt/He.label_weight*100:0,qe=He.low_stock_threshold_pct??Ee;return Rt<qe})),P&&(Ue=Ue.filter(He=>He.material===P)),A&&(Ue=Ue.filter(He=>He.brand===A)),_&&(_==="__none__"?Ue=Ue.filter(He=>!He.category):Ue=Ue.filter(He=>He.category===_)),H){const He=Number(H);Ue=Ue.filter(Dt=>Dt.core_weight_catalog_id===He)}return Z&&(Z==="__none__"?Ue=Ue.filter(He=>!He.storage_location?.trim()):Ue=Ue.filter(He=>He.storage_location?.trim()===Z)),z==="stock"?Ue=Ue.filter(He=>!He.slicer_filament):z==="configured"&&(Ue=Ue.filter(He=>!!He.slicer_filament)),Y&&(Ue=lI(Ue,Y)),Ue},[se,x,k,P,A,_,H,z,Z,Y,Ee]),Ut=()=>O(0),bt=[...new Set(se?.map(Ue=>Ue.material)||[])].sort(),Wt=[...new Set(se?.map(Ue=>Ue.brand).filter(Boolean)||[])].sort(),Zt=[...new Set(se?.map(Ue=>Ue.category?.trim()).filter(Boolean)||[])].sort(),ln=(se??[]).some(Ue=>!Ue.category),cn=[...new Set(se?.map(Ue=>Ue.core_weight_catalog_id).filter(Ue=>Ue!=null)||[])].sort((Ue,He)=>{const Dt=(tt[Ue]?.name||"").toLowerCase(),Rt=(tt[He]?.name||"").toLowerCase();return Dt.localeCompare(Rt)}),ct=[...new Set(se?.map(Ue=>Ue.storage_location?.trim()).filter(Boolean)||[])].sort(),kt=(se??[]).some(Ue=>!Ue.storage_location?.trim()),Nt=x!=="active"||k!=="all"||!!P||!!A||!!_||!!H||!!Z||z!=="all"||!!Y,ut=Ue=>{he(Ue),Ast(Ue)},Ct=y.useMemo(()=>pe.filter(Ue=>Ue.visible).map(Ue=>Ue.id),[pe]),Le=Ue=>{wF[Ue]&&(le(He=>{let Dt;return He?.column===Ue?Dt=He.direction==="asc"?{column:Ue,direction:"desc"}:null:Dt={column:Ue,direction:"asc"},Dst(Dt),Dt}),Ut())},Ae=y.useMemo(()=>{if(!Q)return Tt;const Ue=wF[Q.column];return Ue?[...Tt].sort((Dt,Rt)=>{const qe=Ue(Dt,Te),Ke=Ue(Rt,Te);return qe<Ke?Q.direction==="asc"?-1:1:qe>Ke?Q.direction==="asc"?1:-1:0}):Tt},[Tt,Q,Te]),Ge=y.useMemo(()=>{if(!J)return Ae.map(Rt=>({type:"single",spool:Rt}));const Ue=new Map;for(const Rt of Ae)if(!(Rt.weight_used>0||Te[Rt.id])){const qe=TX(Rt),Ke=Ue.get(qe);Ke?Ke.push(Rt):Ue.set(qe,[Rt])}const He=[],Dt=new Set;for(const Rt of Ae){if(Rt.weight_used>0||Te[Rt.id]){He.push({type:"single",spool:Rt});continue}const qe=TX(Rt);if(Dt.has(qe))continue;Dt.add(qe);const Ke=Ue.get(qe);Ke.length===1?He.push({type:"single",spool:Ke[0]}):He.push({type:"group",key:qe,spools:Ke,representative:Ke[0]})}return He},[Ae,J,Te]),Je=ie===-1,De=Ge.length,mt=Je?De||1:ie,Ne=Math.max(1,Math.ceil(De/mt)),Ye=Je?0:Math.min(W,Ne-1),nt=Je?Ge:Ge.slice(Ye*mt,(Ye+1)*mt),at=()=>{const Ue=!J;j(Ue),B(new Set),Ut();try{localStorage.setItem("bambuddy-inventory-group",String(Ue))}catch{}},et=Ue=>{B(He=>{const Dt=new Set(He);return Dt.has(Ue)?Dt.delete(Ue):Dt.add(Ue),Dt})},vt=Ue=>{U(Ue),O(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Ue))}catch{}},wt=()=>{S("active"),C("all"),T(""),F(""),M(""),I(""),ne(""),L("all"),ce(""),Ut()};return r.jsxs("div",{className:"p-4 md:p-8 space-y-6",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Vr,{className:"w-7 h-7 text-bambu-green"}),n("inventory.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:n("inventory.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{variant:"secondary",disabled:Tt.length===0,onClick:()=>b(Tt.map(Ue=>Ue.id)),title:Tt.length===0?n("inventory.labels.noSpoolsTitle","No spools to label"):n("inventory.labels.bulkTitle","Pick spools to print labels for from the {{count}} currently shown",{count:Tt.length}),children:[r.jsx(hr,{className:"w-4 h-4"}),n("inventory.labels.printLabels","Print labels…")]}),r.jsxs(je,{onClick:()=>m({spool:null,mode:"create"}),children:[r.jsx(er,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})]}),Ve&&!te&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx(Vr,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:n("inventory.totalInventory")})]}),r.jsx("div",{className:"text-xl font-bold text-white",children:su(Ve.totalWeight,!0)}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[Ve.totalSpools," ",Ve.totalSpools!==1?n("inventory.spools"):n("inventory.spool")]})]}),r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(IS,{className:"w-4 h-4 text-blue-400"}),r.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:n("inventory.totalConsumed")})]}),Ve.totalConsumed>0&&ze.length>0&&r.jsx("button",{onClick:()=>g({type:"reset-all-usage"}),className:"p-1 text-bambu-gray hover:text-red-400 rounded transition-colors",title:n("inventory.resetAllUsageTooltip"),"aria-label":n("inventory.resetAllUsage"),children:r.jsx(SO,{className:"w-3.5 h-3.5"})})]}),r.jsx("div",{className:"text-xl font-bold text-white",children:su(Ve.totalConsumed,!0)}),r.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:n("inventory.sinceTracking")})]}),r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx(ca,{className:"w-4 h-4 text-green-400"}),r.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:n("inventory.byMaterial")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:ot.map(([Ue,He])=>r.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${jst[Ue]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Ue," ",r.jsx("span",{className:"opacity-70",children:su(He.weight,!0)})]},Ue))})]}),r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx(hr,{className:"w-4 h-4 text-purple-400"}),r.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:n("inventory.inPrinter")})]}),r.jsx("div",{className:"text-xl font-bold text-white",children:rt}),r.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:n("inventory.loadedInAms")})]}),r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx(Nn,{className:"w-4 h-4 text-yellow-400"}),r.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:n("inventory.lowStock")})]}),r.jsx("div",{className:`text-xl font-bold ${Ve.lowStock>0?"text-yellow-400":"text-white"}`,children:Ve.lowStock}),r.jsx("div",{className:"text-xs text-bambu-gray mt-1 flex items-center gap-2",children:it?r.jsxs("form",{onSubmit:Ue=>{Ue.preventDefault();const He=parseFloat(Ze);!isNaN(He)&&He>=.1&&He<=99.9?ke.mutate(He):i(n("inventory.lowStockThresholdError"),"error")},className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"<"}),r.jsx("input",{type:"text",inputMode:"decimal",pattern:"^\\d{0,2}(\\.\\d?)?$",maxLength:4,value:Ze,onChange:Ue=>{const He=Ue.target.value.replace(/[^\d.]/g,"");/^\d{0,2}(\.\d?)?$/.test(He)&&Ie(He)},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:Ue=>Ue.currentTarget.blur(),disabled:ke.isPending}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"%"}),r.jsx(je,{type:"submit",size:"sm",disabled:ke.isPending,children:n("common.save")}),r.jsx(je,{type:"button",size:"sm",variant:"ghost",onClick:()=>Ce(!1),disabled:ke.isPending,children:n("common.cancel")})]}):r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"text-bambu-gray",children:["< ",Ee,"%"]}),r.jsx("button",{className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:n("common.edit"),onClick:()=>{Ie(Ee.toString()),Ce(!0)},children:r.jsx(uc,{className:"w-4 h-4"})})]})})]})]}),r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[r.jsxs("div",{className:`relative flex-1 max-w-md ${ue==="forecast"?"invisible pointer-events-none":""}`,children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"text",value:Y,onChange:Ue=>{ce(Ue.target.value),Ut()},placeholder:n("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),Y&&r.jsx("button",{onClick:()=>{ce(""),Ut()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[ue==="table"&&r.jsxs("button",{onClick:()=>$(!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:n("inventory.configureColumns"),children:[r.jsx(zge,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("inventory.columns")})]}),ue!=="forecast"&&r.jsxs("button",{onClick:at,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${J?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:n("inventory.groupSimilar"),children:[r.jsx(Vbe,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("inventory.groupSimilar")})]}),r.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{onClick:()=>oe("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${ue==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(Jye,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("inventory.table")})]}),r.jsxs("button",{onClick:()=>oe("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${ue==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(jS,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("inventory.cards")})]}),r.jsxs("button",{onClick:()=>l&&oe("forecast"),disabled:!l,title:l?void 0:n("forecast.noReadAccess"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${ue==="forecast"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[l?r.jsx(sC,{className:"w-4 h-4"}):r.jsx(rc,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.title")})]})]})]})]}),r.jsxs("div",{className:`flex flex-wrap items-center gap-2 ${ue==="forecast"?"hidden":""}`,children:[r.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.jsxs("button",{onClick:()=>{S("active"),Ut()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${x==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(Vr,{className:"w-3.5 h-3.5"}),n("inventory.active")]}),r.jsxs("button",{onClick:()=>{S("archived"),Ut()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${x==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(eo,{className:"w-3.5 h-3.5"}),n("inventory.archived")]})]}),r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),r.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.jsx("button",{onClick:()=>{C("all"),Ut()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${k==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:n("inventory.all")}),r.jsxs("button",{onClick:()=>{C("used"),Ut()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${k==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),n("inventory.used")]}),r.jsx("button",{onClick:()=>{C("new"),Ut()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${k==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:n("inventory.new")}),r.jsxs("button",{onClick:()=>{C("lowstock"),Ut()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${k==="lowstock"?"bg-yellow-500/20 text-yellow-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),n("inventory.lowStock")]})]}),r.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.jsx("button",{onClick:()=>{L("all"),Ut()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${z==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:n("inventory.all")}),r.jsx("button",{onClick:()=>{L("stock"),Ut()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${z==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:n("inventory.stock")}),r.jsx("button",{onClick:()=>{L("configured"),Ut()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${z==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:n("inventory.configured")})]}),r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),r.jsxs("select",{value:P,onChange:Ue=>{T(Ue.target.value),Ut()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${P?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[r.jsx("option",{value:"",children:n("inventory.material")}),bt.map(Ue=>r.jsx("option",{value:Ue,children:Ue},Ue))]}),r.jsxs("select",{value:A,onChange:Ue=>{F(Ue.target.value),Ut()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${A?"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:[r.jsx("option",{value:"",children:n("inventory.brand")}),Wt.map(Ue=>r.jsx("option",{value:Ue,children:Ue},Ue))]}),(Zt.length>0||_)&&r.jsxs("select",{value:_,onChange:Ue=>{M(Ue.target.value),Ut()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${_?"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:[r.jsx("option",{value:"",children:n("inventory.category")}),Zt.map(Ue=>r.jsx("option",{value:Ue,children:Ue},Ue)),ln&&r.jsx("option",{value:"__none__",children:n("inventory.categoryNone")})]}),cn.length>0&&r.jsxs("select",{value:H,onChange:Ue=>{I(Ue.target.value),Ut()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${H?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[r.jsx("option",{value:"",children:n("inventory.spoolName")}),cn.map(Ue=>r.jsx("option",{value:Ue,children:tt[Ue]?.name||`#${Ue}`},Ue))]}),(ct.length>0||Z)&&r.jsxs("select",{value:Z,onChange:Ue=>{ne(Ue.target.value),Ut()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${Z?"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:[r.jsx("option",{value:"",children:n("inventory.storageLocation")}),ct.map(Ue=>r.jsx("option",{value:Ue,children:Ue},Ue)),kt&&r.jsx("option",{value:"__none__",children:n("inventory.storageLocationNone")})]}),Nt&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),r.jsxs("button",{onClick:wt,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[r.jsx(Vt,{className:"w-3.5 h-3.5"}),n("inventory.clearFilters")]})]}),ue!=="forecast"&&r.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Ae.length," ",Ae.length!==1?n("inventory.spools"):n("inventory.spool"),J&&De<Ae.length&&` (${De} ${n("inventory.groupedRows")})`]})]}),te?r.jsx("div",{className:"flex justify-center py-16",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})}):ue==="forecast"?r.jsx(Xit,{spools:se||[]}):ue==="cards"?nt.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:nt.map(Ue=>{if(Ue.type==="group"){const{key:qe,spools:Ke,representative:Bt}=Ue,Qt=ij({rgba:Bt.rgba,extraColors:Bt.extra_colors,effectType:Bt.effect_type,subtype:Bt.subtype,effectSize:"groupheader"}),dn=E.has(qe);return r.jsxs("div",{className:"col-span-full",children:[r.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:()=>et(qe),children:[r.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:Qt,children:r.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:AT(Bt.color_name,Bt.rgba)||"-"})}),r.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(Ln,{className:`w-4 h-4 text-bambu-gray transition-transform ${dn?"":"-rotate-90"}`}),r.jsxs("div",{children:[r.jsxs("h3",{className:"font-semibold text-white",children:[Bt.material,Bt.subtype?` ${Bt.subtype}`:""]}),r.jsx("p",{className:"text-sm text-bambu-gray",children:Bt.brand||"-"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:su(Bt.label_weight)}),r.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:n("inventory.groupedSpools",{count:Ke.length})})]})]})]}),dn&&r.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:Ke.map(nn=>{const rn=Math.max(0,nn.label_weight-nn.weight_used),yn=nn.label_weight>0?rn/nn.label_weight*100:0;return r.jsx(AX,{spool:nn,remaining:rn,pct:yn,onClick:()=>m({spool:nn,mode:"edit"}),onPrintLabel:()=>b([nn.id]),onCopy:()=>m({spool:nn,mode:"copy"}),t:n},nn.id)})})]},`group-${qe}`)}const He=Ue.spool,Dt=Math.max(0,He.label_weight-He.weight_used),Rt=He.label_weight>0?Dt/He.label_weight*100:0;return r.jsx(AX,{spool:He,remaining:Dt,pct:Rt,onClick:()=>m({spool:He,mode:"edit"}),onPrintLabel:()=>b([He.id]),onCopy:()=>m({spool:He,mode:"copy"}),t:n},He.id)})}),r.jsx(Rst,{pageIndex:Ye,pageSize:ie,totalRows:De,totalPages:Ne,onPageChange:O,onPageSizeChange:vt,t:n})]}):r.jsx(jX,{hasFilters:Nt,onAddSpool:()=>m({spool:null,mode:"create"}),t:n}):nt.length>0?r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[Ct.map(Ue=>{const He=!!wF[Ue],Dt=Q?.column===Ue;return r.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Ue==="remaining"?"min-w-[150px]":""} ${He?"cursor-pointer hover:text-bambu-green transition-colors":""} ${Dt?"text-bambu-green":"text-bambu-gray"}`,onClick:He?()=>Le(Ue):void 0,children:r.jsxs("span",{className:"inline-flex items-center gap-1",children:[Mst[Ue]?.(n)??Ue,He&&(Dt?Q.direction==="asc"?r.jsx(qm,{className:"w-3 h-3"}):r.jsx(qh,{className:"w-3 h-3"}):r.jsx(_T,{className:"w-3 h-3 opacity-30"}))]})},Ue)}),r.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("common.actions")})]})}),r.jsx("tbody",{children:nt.map(Ue=>{if(Ue.type==="group"){const{key:qe,spools:Ke,representative:Bt}=Ue,Qt=E.has(qe),dn=Math.max(0,Bt.label_weight-Bt.weight_used),nn=Bt.label_weight>0?dn/Bt.label_weight*100:0;return r.jsx(Ist,{spools:Ke,representative:Bt,remaining:dn,pct:nn,isExpanded:Qt,onToggle:()=>et(qe),onEdit:rn=>m({spool:rn,mode:"edit"}),onCopy:rn=>m({spool:rn,mode:"copy"}),onArchive:rn=>g({type:"archive",spoolId:rn}),onDelete:rn=>g({type:"delete",spoolId:rn}),onPrintLabel:rn=>b([rn]),onResetUsage:rn=>g({type:"reset-usage",spoolId:rn}),visibleColumns:Ct,assignmentMap:Te,catalogMap:tt,currencySymbol:Qe,dateFormat:K,t:n,onSyncWeight:st},`group-${qe}`)}const He=Ue.spool,Dt=Math.max(0,He.label_weight-He.weight_used),Rt=He.label_weight>0?Dt/He.label_weight*100:0;return r.jsx(hde,{spool:He,remaining:Dt,pct:Rt,onEdit:()=>m({spool:He,mode:"edit"}),onCopy:()=>m({spool:He,mode:"copy"}),onRestore:()=>Oe.mutate(He.id),onArchive:()=>g({type:"archive",spoolId:He.id}),onDelete:()=>g({type:"delete",spoolId:He.id}),onPrintLabel:()=>b([He.id]),onResetUsage:()=>g({type:"reset-usage",spoolId:He.id}),visibleColumns:Ct,assignmentMap:Te,catalogMap:tt,currencySymbol:Qe,dateFormat:K,t:n,onSyncWeight:st},He.id)})})]})}),r.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:[r.jsx("span",{className:"text-bambu-gray",children:Je?`${De} ${n(De!==1?"inventory.spools":"inventory.spool")}`:r.jsxs(r.Fragment,{children:[n("inventory.showing")," ",Ye*mt+1," ",n("inventory.to")," ",Math.min((Ye+1)*mt,De)," ",n("inventory.of")," ",De," ",n("inventory.spools")]})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-bambu-gray",children:n("inventory.show")}),r.jsxs("select",{value:ie,onChange:Ue=>vt(Number(Ue.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(Ue=>r.jsx("option",{value:Ue,children:Ue},Ue)),r.jsx("option",{value:-1,children:n("inventory.all")})]}),!Je&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>O(0),disabled:Ye===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:r.jsx(yO,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>O(Ue=>Math.max(0,Ue-1)),disabled:Ye===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[n("inventory.page")," ",Ye+1," ",n("inventory.of")," ",Ne]}),r.jsx("button",{onClick:()=>O(Ue=>Math.min(Ne-1,Ue+1)),disabled:Ye>=Ne-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(qa,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>O(Ne-1),disabled:Ye>=Ne-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:r.jsx(vO,{className:"w-4 h-4"})})]})]})]})]}):r.jsx(jX,{hasFilters:Nt,onAddSpool:()=>m({spool:null,mode:"create"}),t:n}),u!==null&&r.jsx(vst,{isOpen:!0,onClose:()=>m(null),spool:u.spool,mode:u.mode,currencySymbol:Qe,spoolmanMode:t,spoolsQueryKey:X}),f&&r.jsx(wn,{title:f.type==="delete"?n("common.delete"):f.type==="archive"?n("inventory.archive"):f.type==="reset-usage"?n("inventory.resetUsage"):n("inventory.resetAllUsage"),message:f.type==="delete"?n("inventory.deleteConfirm"):f.type==="archive"?n("inventory.archiveConfirm"):f.type==="reset-usage"?n("inventory.resetUsageConfirm"):n("inventory.resetAllUsageConfirm",{count:ze.length}),confirmText:f.type==="delete"?n("common.delete"):f.type==="archive"?n("inventory.archive"):n("inventory.resetUsage"),variant:f.type==="archive"?"warning":"danger",onConfirm:()=>{f.type==="delete"?Be.mutate(f.spoolId):f.type==="archive"?Fe.mutate(f.spoolId):f.type==="reset-usage"?Re.mutate(f.spoolId):We.mutate(ze),g(null)},onCancel:()=>g(null)}),r.jsx(wst,{isOpen:we,onClose:()=>$(!1),columns:pe,defaultColumns:$N,onSave:ut}),r.jsx(Pst,{isOpen:w!==null,onClose:()=>b(null),availableSpools:Tt,initialSelectedIds:w??[],spoolmanMode:t})]})}function Rst({pageIndex:t,pageSize:e,totalRows:n,totalPages:a,onPageChange:i,onPageSizeChange:s,t:o}){const l=e===-1;if(a<=1&&!l)return null;const c=l?n||1:e;return r.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:r.jsxs(r.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),r.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=>r.jsx("option",{value:d,children:d},d)),r.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&r.jsxs(r.Fragment,{children:[r.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:r.jsx(yO,{className:"w-4 h-4"})}),r.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:r.jsx(Xo,{className:"w-4 h-4"})}),r.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",a]}),r.jsx("button",{onClick:()=>i(Math.min(a-1,t+1)),disabled:t>=a-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(qa,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>i(a-1),disabled:t>=a-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:r.jsx(vO,{className:"w-4 h-4"})})]})]})]})}function AX({spool:t,remaining:e,pct:n,onClick:a,onPrintLabel:i,onCopy:s,t:o}){const l=ij({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"card"});return r.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:a,children:[r.jsxs("div",{className:"h-14 flex items-center justify-center",style:l,children:[r.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:AT(t.color_name,t.rgba)||"-"}),s&&r.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),s()},className:"p-1.5 bg-black/20 hover:bg-black/40 text-white rounded-full transition-colors",title:o("inventory.copySpool"),children:r.jsx(Ti,{className:"w-3.5 h-3.5"})})]}),r.jsxs("div",{className:"p-4 space-y-3",children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{children:[r.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[i&&r.jsx("button",{onClick:c=>{c.stopPropagation(),i()},className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",title:o("inventory.labels.printOne"),"aria-label":o("inventory.labels.printOne"),children:r.jsx(hr,{className:"w-4 h-4"})}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[r.jsx("span",{children:o("inventory.remaining")}),r.jsxs("span",{children:[Math.round(n),"%"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.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)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"text-bambu-gray/60",children:[o("inventory.labelWeight"),": "]}),r.jsx("span",{className:"text-bambu-gray",children:su(t.label_weight)})]}),r.jsxs("div",{children:[r.jsxs("span",{className:"text-bambu-gray/60",children:[o("inventory.weightUsed"),": "]}),r.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?su(t.weight_used):"-"})]})]}),t.note&&r.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 hde({spool:t,remaining:e,pct:n,onEdit:a,onCopy:i,onRestore:s,onArchive:o,onDelete:l,onPrintLabel:c,onResetUsage:d,visibleColumns:u,assignmentMap:m,catalogMap:p,currencySymbol:f,dateFormat:g,t:w,onSyncWeight:b}){return r.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:a,children:[u.map(x=>r.jsx("td",{className:"py-3 px-4",children:eO[x]?.({spool:t,remaining:e,pct:n,assignmentMap:m,catalogMap:p,currencySymbol:f,dateFormat:g,t:w,onSyncWeight:b})},x)),r.jsx("td",{className:"py-3 px-4",children:r.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:x=>x.stopPropagation(),children:[r.jsx("button",{onClick:a,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:w("common.edit"),children:r.jsx(uc,{className:"w-4 h-4"})}),i&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:w("inventory.copySpool"),children:r.jsx(Ti,{className:"w-4 h-4"})}),c&&r.jsx("button",{onClick:c,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:w("inventory.labels.printOne"),children:r.jsx(hr,{className:"w-4 h-4"})}),d&&t.weight_used>0&&r.jsx("button",{onClick:d,className:"p-1.5 text-bambu-gray hover:text-orange-400 rounded transition-colors",title:w("inventory.resetUsageTooltip"),children:r.jsx(SO,{className:"w-4 h-4"})}),t.archived_at?r.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:w("inventory.restore"),children:r.jsx(fs,{className:"w-4 h-4"})}):r.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:w("inventory.archive"),children:r.jsx(eo,{className:"w-4 h-4"})}),r.jsx("button",{onClick:l,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:w("common.delete"),children:r.jsx(en,{className:"w-4 h-4"})})]})})]})}function Ist({spools:t,representative:e,remaining:n,pct:a,isExpanded:i,onToggle:s,onEdit:o,onCopy:l,onArchive:c,onDelete:d,onPrintLabel:u,onResetUsage:m,visibleColumns:p,assignmentMap:f,catalogMap:g,currencySymbol:w,dateFormat:b,t:x,onSyncWeight:S}){return r.jsxs(r.Fragment,{children:[r.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:[p.map((k,C)=>r.jsx("td",{className:"py-3 px-4",children:C===0?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ln,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"":"-rotate-90"}`}),eO[k]?.({spool:e,remaining:n,pct:a,assignmentMap:f,catalogMap:g,currencySymbol:w,dateFormat:b,t:x,onSyncWeight:S})]}):k==="id"?r.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})}):eO[k]?.({spool:e,remaining:n,pct:a,assignmentMap:f,catalogMap:g,currencySymbol:w,dateFormat:b,t:x,onSyncWeight:S})},k)),r.jsx("td",{className:"py-3 px-4",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(k=>`#${k.id}`).join(", ")})})]}),i&&t.map(k=>{const C=Math.max(0,k.label_weight-k.weight_used),P=k.label_weight>0?C/k.label_weight*100:0;return r.jsx(hde,{spool:k,remaining:C,pct:P,onEdit:()=>o(k),onCopy:l?()=>l(k):void 0,onRestore:()=>{},onArchive:()=>c(k.id),onDelete:()=>d(k.id),onPrintLabel:u?()=>u(k.id):void 0,onResetUsage:m?()=>m(k.id):void 0,visibleColumns:p,assignmentMap:f,catalogMap:g,currencySymbol:w,dateFormat:b,t:x,onSyncWeight:S},k.id)})]})}function jX({hasFilters:t,onAddSpool:e,t:n}){return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[r.jsxs("div",{className:"relative mb-6",children:[r.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),r.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:[r.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),r.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?r.jsx(yr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):r.jsxs("div",{className:"relative",children:[r.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:r.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),r.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:r.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),r.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),r.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&r.jsxs(je,{onClick:e,children:[r.jsx(Vr,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}function Hd(t,e){const n=t?.[e];return typeof n=="string"?n:""}function Ost(t){return t.replace(/(https?:\/\/(?:makerworld|public-cdn)\.bblmw\.com\/[^\s"']+)/gi,e=>`/api/v1/makerworld/thumbnail?url=${encodeURIComponent(e)}`)}function SF(t){return t?/^https?:\/\/(makerworld|public-cdn)\.bblmw\.com\//i.test(t)?`/api/v1/makerworld/thumbnail?url=${encodeURIComponent(t)}`:t:""}function Zp(t,e){const n=t?.[e];return typeof n=="number"?n:null}function zst(t,e){const n=t?.[e];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function fde(t,e=0,n=[]){n.push({folder:t,depth:e});for(const a of t.children??[])fde(a,e+1,n);return n}function Ust(t,e){return t<1?e("makerworld.phaseResolving"):e("makerworld.phaseDownloading")}function Bst(t){const[e,n]=y.useState(0);return y.useEffect(()=>{if(!t){n(0);return}const a=Date.now(),i=()=>n(Math.floor((Date.now()-a)/1e3));i();const s=window.setInterval(i,1e3);return()=>window.clearInterval(s)},[t]),e}function Hst(){const{t}=_t(),{hasPermission:e}=dr(),{showToast:n}=on(),a=tn(),i=e("makerworld:import"),[s,o]=y.useState(""),[l,c]=y.useState(null),[d,u]=y.useState(null),[m,p]=y.useState(null),[f,g]=y.useState(null),[w,b]=y.useState(null),[x,S]=y.useState(""),[k,C]=y.useState({}),P=Xe({queryKey:["makerworld-status"],queryFn:()=>ae.getMakerworldStatus()}),T=Xe({queryKey:["library-folders"],queryFn:()=>ae.getLibraryFolders()}),A=Xe({queryKey:["makerworld-recent-imports"],queryFn:()=>ae.getMakerworldRecentImports(10)}),F=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings()}),_=F.data?.preferred_slicer||"bambu_studio",M=_==="orcaslicer"?"OrcaSlicer":"Bambu Studio",H=F.data?.use_slicer_api??!1,[I,z]=y.useState(null),L=(K,X)=>{z({kind:"libraryFile",id:K,filename:X})},Z=lt({mutationFn:K=>ae.resolveMakerworldUrl(K),onSuccess:(K,X)=>{c(K),S(X),C({})},onError:K=>n(K.message||t("makerworld.errors.resolveFailed"),"error")});y.useEffect(()=>{l!==null&&s.trim()!==x.trim()&&(c(null),S(""),C({}))},[s,l,x]);const ne=lt({mutationFn:({instanceId:K,profileId:X})=>ae.importMakerworldInstance(l?.model_id??0,K,X,d),onSuccess:K=>{a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),K.profile_id&&C(X=>({...X,[K.profile_id]:K})),n(K.was_existing?t("makerworld.alreadyInLibrary"):t("makerworld.importSuccess",{filename:K.filename}),"success")},onError:K=>n(K.message||t("makerworld.errors.downloadFailed"),"error")}),Y=lt({mutationFn:({libraryFileId:K})=>ae.deleteLibraryFile(K),onSuccess:(K,{profileId:X})=>{a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["makerworld-recent-imports"]}),C(se=>{const te={...se};return delete te[X],te}),g(null),n(t("makerworld.importDeleted"),"success")},onError:K=>{g(null),n(K.message||t("makerworld.errors.deleteFailed"),"error")}}),ce=lt({mutationFn:({instanceId:K,profileId:X})=>ae.importMakerworldInstance(l?.model_id??0,K,X,d),onSuccess:async K=>{a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["makerworld-recent-imports"]}),K.profile_id&&C(X=>({...X,[K.profile_id]:K})),H?L(K.library_file_id,K.filename):await he(K.library_file_id,K.filename,_)},onError:K=>n(K.message||t("makerworld.errors.downloadFailed"),"error")}),ue=Bst(ne.isPending||ce.isPending),oe=Ust(ue,t),Q=K=>{K?.preventDefault();const X=s.trim();X&&Z.mutate(X)};y.useEffect(()=>{if(!w)return;const K=X=>{X.key==="Escape"?b(null):X.key==="ArrowLeft"?b(se=>se&&se.index>0?{...se,index:se.index-1}:se):X.key==="ArrowRight"&&b(se=>se&&se.index<se.images.length-1?{...se,index:se.index+1}:se)};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[w]);const le=K=>{const se=(Array.isArray(K.pictures)?K.pictures:[]).filter(fe=>fe!==null&&typeof fe=="object").map(fe=>({name:Hd(fe,"name")||"image",url:Hd(fe,"url")})).filter(fe=>fe.url);if(se.length>0)return se;const te=Hd(K,"cover");return te?[{name:"cover",url:te}]:[]},pe=async()=>{if(!l)return;const K=l.instances.filter(X=>{const se=Zp(X,"profileId");return se!==null&&!k[se]});if(K.length!==0){p({current:0,total:K.length});try{for(let X=0;X<K.length;X+=1){const se=K[X],te=Zp(se,"id"),fe=Zp(se,"profileId");if(!(te===null||fe===null)){p({current:X+1,total:K.length});try{await ne.mutateAsync({instanceId:te,profileId:fe})}catch{}}}}finally{p(null)}}},he=async(K,X,se)=>{try{const{token:te}=await ae.createLibrarySlicerToken(K),fe=ae.getLibrarySlicerDownloadUrl(K,te,X);jm(`${window.location.origin}${fe}`,se)}catch{const te=ae.getLibraryFileDownloadUrl(K);jm(`${window.location.origin}${te}`,se)}},we=l?.design,$=zst(we,"designCreator"),J=l?.instances??[],j=(l?.already_imported_library_ids.length??0)>0,E=P.data?.has_cloud_token??!1,B=P.data?.can_download??!1,W=y.useMemo(()=>Hd(we,"coverUrl"),[we]),O=Hd(we,"title"),ie=Hd(we,"summary"),U=Hd(we,"license"),G=Zp(we,"downloadCount");return r.jsxs("div",{className:"p-4 md:p-8 max-w-screen-2xl space-y-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Js,{className:"w-7 h-7 text-bambu-green"}),t("makerworld.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("makerworld.description")})]}),r.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_20rem]",children:[r.jsxs("div",{className:"space-y-6 min-w-0",children:[!E&&r.jsx(At,{className:"border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/20",children:r.jsx(Et,{children:r.jsxs("div",{className:"flex items-start gap-3 py-2",children:[r.jsx(Ha,{className:"w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0"}),r.jsxs("div",{className:"text-sm",children:[r.jsx("p",{className:"font-medium text-amber-900 dark:text-amber-100",children:t("makerworld.signInRequiredTitle")}),r.jsxs("p",{className:"text-amber-800 dark:text-amber-200 mt-1",children:[t("makerworld.signInRequiredBody")," ",r.jsx(Es,{to:"/profiles",className:"underline",children:t("makerworld.openCloudSettings")})]})]})]})})}),r.jsxs(At,{children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-lg font-semibold",children:t("makerworld.pasteUrlHeader")})}),r.jsx(Et,{children:r.jsxs("form",{onSubmit:Q,className:"flex gap-2",children:[r.jsx("input",{type:"text",value:s,onChange:K=>o(K.target.value),placeholder:t("makerworld.pasteUrlPlaceholder"),className:"flex-1 min-w-0 px-3 py-2 border rounded bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700",autoComplete:"off"}),r.jsxs(je,{type:"submit",variant:"primary",disabled:!s.trim()||Z.isPending,children:[Z.isPending?r.jsx(ft,{className:"w-4 h-4 animate-spin"}):r.jsx(ZN,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-2",children:t("makerworld.resolveButton")})]})]})})]}),l&&r.jsx(At,{children:r.jsx(Et,{children:r.jsxs("div",{className:"flex gap-4 py-2",children:[W&&r.jsx("img",{src:SF(W),alt:O,className:"w-32 h-32 object-cover rounded",loading:"lazy"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h3",{className:"text-xl font-semibold truncate",children:O||t("makerworld.untitledModel")}),$&&r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:t("makerworld.byCreator",{name:Hd($,"name")})}),r.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-xs text-gray-500 dark:text-gray-400",children:[G!==null&&r.jsx("span",{children:t("makerworld.downloadsCount",{count:G})}),U&&r.jsxs("span",{children:[t("makerworld.licensePrefix"),": ",U]}),j&&r.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 dark:text-emerald-400",children:[r.jsx(Ar,{className:"w-3 h-3"})," ",t("makerworld.alreadyImported")]})]}),ie&&r.jsx("div",{className:"mt-3 text-sm prose prose-sm max-w-none dark:prose-invert line-clamp-3",dangerouslySetInnerHTML:{__html:h5.sanitize(Ost(ie))}}),l&&r.jsxs("a",{href:`https://makerworld.com/models/${l.model_id}${l.profile_id?`#profileId-${l.profile_id}`:""}`,target:"_blank",rel:"noopener noreferrer",className:"mt-3 inline-flex items-center gap-1 text-xs text-brand-500 hover:underline",children:[r.jsx(zr,{className:"w-3 h-3"})," ",t("makerworld.openOnMakerworld")]})]})]})})}),l&&J.length>0&&r.jsxs(At,{children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[r.jsx("h2",{className:"text-lg font-semibold",children:t("makerworld.platesHeader",{count:J.length})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("label",{className:"text-xs text-gray-600 dark:text-gray-400",children:t("makerworld.importTo")}),r.jsxs("select",{value:d??"",onChange:K=>u(K.target.value?Number(K.target.value):null),className:"text-sm px-2 py-1 border rounded bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-700",disabled:m!==null,children:[r.jsx("option",{value:"",children:t("makerworld.folderAuto")}),(T.data??[]).filter(K=>!(K.is_external&&K.external_readonly)).flatMap(K=>fde(K)).map(({folder:K,depth:X})=>r.jsx("option",{value:K.id,children:`${"— ".repeat(X)}${K.name}`},K.id))]}),r.jsx(je,{variant:"primary",size:"sm",disabled:!i||!B||m!==null||ne.isPending||ce.isPending,onClick:pe,children:m!==null?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsxs("span",{className:"ml-2",children:[t("makerworld.importAllProgress",{current:m.current,total:m.total}),ue>0&&` · ${oe} · ${ue}s`]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Zr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-2",children:t("makerworld.importAll")})]})})]})]})}),r.jsx(Et,{children:r.jsx("div",{className:"grid gap-3",children:J.map((K,X)=>{const se=Zp(K,"id"),te=Zp(K,"profileId"),fe=Hd(K,"title"),de=Hd(K,"cover"),me=Zp(K,"materialCnt"),q=K?.needAms===!0,R=Zp(K,"downloadCount"),re=K?.compatibility??null,be=K?.otherCompatibility??null,ye=re?.devProductName??null,_e=Array.isArray(be)?be.map(Be=>Be?.devProductName??"").filter(Boolean):[];if(se==null)return null;const xe=ne.isPending&&ne.variables?.instanceId===se,ge=ce.isPending&&ce.variables?.instanceId===se,Me=te!==null?k[te]:void 0;return r.jsxs("div",{className:"flex flex-col gap-2 p-3 border rounded border-gray-200 dark:border-gray-700",children:[r.jsxs("div",{className:"flex gap-3 items-center",children:[(()=>{const Be=le(K),Fe=Be.length>0;return r.jsxs("button",{type:"button",disabled:!Fe,onClick:()=>Fe&&b({images:Be,index:0}),className:"relative w-16 h-16 shrink-0 rounded overflow-hidden group","aria-label":t("makerworld.openGallery"),children:[de?r.jsx("img",{src:SF(de),alt:"",className:"w-16 h-16 object-cover",loading:"lazy"}):r.jsx("div",{className:"w-16 h-16 bg-gray-100 dark:bg-gray-800"}),Be.length>1&&r.jsxs("span",{className:"absolute bottom-0.5 right-0.5 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded flex items-center gap-1",children:[r.jsx(sxe,{className:"w-2.5 h-2.5"}),Be.length]})]})})(),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"font-medium truncate",children:fe||t("makerworld.plateDefaultName",{n:X+1})}),r.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-gray-500 dark:text-gray-400 mt-1",children:[ye&&r.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:t("makerworld.slicedFor",{printer:ye,defaultValue:"Sliced for {{printer}}"})}),me!==null&&r.jsx("span",{children:t("makerworld.materialCount",{count:me})}),q&&r.jsx("span",{children:t("makerworld.amsRequired")}),R!==null&&r.jsx("span",{children:t("makerworld.downloadsCount",{count:R})})]}),_e.length>0&&r.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",title:_e.join(", "),children:t("makerworld.alsoCompatible",{printers:_e.slice(0,6).join(", ")+(_e.length>6?"…":""),defaultValue:"Also marked compatible: {{printers}}"})})]}),r.jsxs("div",{className:"flex gap-2 shrink-0",children:[r.jsx(je,{variant:"ghost",size:"sm",disabled:!i||!B||xe||ge||m!==null,onClick:()=>ne.mutate({instanceId:se,profileId:te}),title:B?void 0:t("makerworld.signInRequiredTitle"),children:xe?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsxs("span",{className:"ml-2",children:[oe,ue>0&&` · ${ue}s`]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Zr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-2",children:t("makerworld.importToLibrary")})]})}),r.jsx(je,{variant:"primary",size:"sm",disabled:!i||!B||xe||ge||m!==null,onClick:()=>ce.mutate({instanceId:se,profileId:te}),title:B?void 0:t("makerworld.signInRequiredTitle"),children:ge?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),r.jsxs("span",{className:"ml-2",children:[oe,ue>0&&` · ${ue}s`]})]}):r.jsxs(r.Fragment,{children:[r.jsx(zr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-2",children:t("makerworld.sliceIn",{slicer:M})})]})})]})]}),Me&&r.jsxs("div",{className:"flex items-center gap-2 pl-20 text-xs",children:[r.jsx(Ar,{className:"w-3.5 h-3.5 text-emerald-600 dark:text-emerald-400 shrink-0"}),r.jsx("span",{className:"text-emerald-700 dark:text-emerald-300",children:Me.was_existing?t("makerworld.lastImportAlreadyInLibrary"):t("makerworld.lastImportSuccess")}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>{const Be=Me.folder_id?`/files?folder=${Me.folder_id}`:"/files";window.location.assign(Be)},children:[r.jsx(Pl,{className:"w-3.5 h-3.5"}),r.jsx("span",{className:"ml-1.5",children:t("makerworld.viewInLibrary")})]}),H?r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>L(Me.library_file_id,Me.filename),children:[r.jsx(uu,{className:"w-3.5 h-3.5"}),r.jsx("span",{className:"ml-1.5",children:t("slice.action","Slice")})]}):r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>he(Me.library_file_id,Me.filename,"bambu_studio"),children:[r.jsx(zr,{className:"w-3.5 h-3.5"}),r.jsx("span",{className:"ml-1.5",children:t("makerworld.openInBambuStudio")})]}),r.jsxs(je,{variant:"ghost",size:"sm",onClick:()=>he(Me.library_file_id,Me.filename,"orcaslicer"),children:[r.jsx(zr,{className:"w-3.5 h-3.5"}),r.jsx("span",{className:"ml-1.5",children:t("makerworld.openInOrcaSlicer")})]})]}),r.jsx("div",{className:"ml-auto",children:r.jsx(je,{variant:"ghost",size:"sm",disabled:Y.isPending&&Y.variables?.profileId===te,onClick:()=>{te!==null&&g({libraryFileId:Me.library_file_id,profileId:te,filename:Me.filename})},title:t("makerworld.deleteImport"),children:Y.isPending&&Y.variables?.profileId===te?r.jsx(ft,{className:"w-3.5 h-3.5 animate-spin"}):r.jsx(en,{className:"w-3.5 h-3.5 text-red-500"})})})]})]},se)})})})]})]}),r.jsx("aside",{className:"lg:sticky lg:top-6 lg:self-start min-w-0",children:A.data&&A.data.length>0&&r.jsxs(At,{children:[r.jsx(fn,{children:r.jsx("h2",{className:"text-base font-semibold",children:t("makerworld.recentImportsHeader")})}),r.jsx(Et,{children:r.jsx("div",{className:"flex flex-col gap-2 max-h-[28rem] overflow-y-auto -mx-2 px-2",children:A.data.map(K=>r.jsxs("div",{className:"flex gap-2 p-2 border rounded border-gray-200 dark:border-gray-700",children:[K.thumbnail_path?r.jsx("img",{src:ae.getLibraryFileThumbnailUrl(K.library_file_id),alt:"",className:"w-12 h-12 shrink-0 object-cover rounded bg-gray-100 dark:bg-gray-800",loading:"lazy"}):r.jsx("div",{className:"w-12 h-12 shrink-0 rounded bg-gray-100 dark:bg-gray-800"}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[r.jsx("p",{className:"text-xs font-medium truncate",title:K.filename,children:K.filename}),r.jsxs("div",{className:"flex gap-0.5",children:[r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{const X=K.folder_id?`/files?folder=${K.folder_id}`:"/files";window.location.assign(X)},title:t("makerworld.viewInLibrary"),children:r.jsx(Pl,{className:"w-3.5 h-3.5"})}),H?r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>L(K.library_file_id,K.filename),title:t("slice.action","Slice"),children:r.jsx(uu,{className:"w-3.5 h-3.5"})}):r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>he(K.library_file_id,K.filename,"bambu_studio"),title:t("makerworld.openInBambuStudio"),children:r.jsx(zr,{className:"w-3.5 h-3.5"})}),K.source_url&&r.jsx("a",{href:K.source_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center justify-center h-7 w-7 rounded text-gray-500 hover:text-gray-700 dark:hover:text-gray-300",title:t("makerworld.openOnMakerworld"),children:r.jsx(Js,{className:"w-3.5 h-3.5"})})]})]})]},K.library_file_id))})})]})})]}),r.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 pt-4 border-t border-gray-200 dark:border-gray-700",children:t("makerworld.disclaimer")}),f&&r.jsx(wn,{title:t("makerworld.deleteImport"),message:t("makerworld.confirmDelete",{filename:f.filename}),confirmText:t("makerworld.deleteImport"),variant:"danger",isLoading:Y.isPending,loadingText:t("makerworld.importDeleting"),onCancel:()=>g(null),onConfirm:()=>Y.mutate({libraryFileId:f.libraryFileId,profileId:f.profileId})}),I&&r.jsx(RA,{source:I,onClose:()=>z(null)}),w&&r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:()=>b(null),role:"dialog","aria-modal":"true",children:[r.jsx("button",{type:"button",className:"absolute top-4 right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white",onClick:K=>{K.stopPropagation(),b(null)},"aria-label":t("common.close","Close"),children:r.jsx(Vt,{className:"w-5 h-5"})}),w.images.length>1&&r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"absolute left-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white disabled:opacity-30",disabled:w.index===0,onClick:K=>{K.stopPropagation(),b(X=>X&&{...X,index:Math.max(0,X.index-1)})},"aria-label":t("makerworld.galleryPrev"),children:r.jsx(Xo,{className:"w-6 h-6"})}),r.jsx("button",{type:"button",className:"absolute right-4 p-2 bg-white/10 hover:bg-white/20 rounded-full text-white disabled:opacity-30",disabled:w.index>=w.images.length-1,onClick:K=>{K.stopPropagation(),b(X=>X&&{...X,index:Math.min(X.images.length-1,X.index+1)})},"aria-label":t("makerworld.galleryNext"),children:r.jsx(qa,{className:"w-6 h-6"})})]}),r.jsx("img",{src:SF(w.images[w.index].url),alt:w.images[w.index].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:K=>K.stopPropagation()}),w.images.length>1&&r.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded text-xs",children:[w.index+1," / ",w.images.length]})]})]})}const MX=["DEBUG","INFO","WARNING","ERROR"],_F={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},qst={DEBUG:gy,INFO:_i,WARNING:Nn,ERROR:Ha};function $st(){const t=tn(),[e,n]=y.useState(!0),[a,i]=y.useState(new Set),[s,o]=y.useState(""),[l,c]=y.useState("ALL"),[d,u]=y.useState(!1),[m,p]=y.useState(!1),f=y.useRef(null),{data:g,isLoading:w,refetch:b}=Xe({queryKey:["application-logs",l,s],queryFn:()=>ny.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:m?2e3:!1,enabled:d});y.useEffect(()=>{d||p(!1)},[d]);const x=lt({mutationFn:()=>ny.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});y.useEffect(()=>{e&&f.current&&g?.entries&&(f.current.scrollTop=f.current.scrollHeight)},[g?.entries,e]);const S=A=>{i(F=>{const _=new Set(F);return _.has(A)?_.delete(A):_.add(A),_})},k=A=>{const F=A.split(" ");return F.length>=2?F[1]:A},C=y.useMemo(()=>g?.entries??[],[g?.entries]),P=y.useMemo(()=>[...C].reverse(),[C]),T=({level:A})=>{const F=qst[A]||_i;return r.jsx(F,{className:`w-3.5 h-3.5 ${_F[A]||"text-gray-400"}`})};return r.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[r.jsxs("button",{onClick:()=>u(!d),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${m?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:r.jsx(gy,{className:"w-5 h-5"})}),r.jsxs("div",{className:"text-left",children:[r.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:m?`Live streaming - ${g?.filtered_count??0} entries`:"View and filter application logs"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[m&&r.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[r.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),d?r.jsx(Zo,{className:"w-5 h-5 text-bambu-gray"}):r.jsx(Ln,{className:"w-5 h-5 text-bambu-gray"})]})]}),d&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m?r.jsxs("button",{onClick:A=>{A.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:[r.jsx(ro,{className:"w-4 h-4"}),"Stop"]}):r.jsxs("button",{onClick:A=>{A.stopPropagation(),p(!0),b()},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:[r.jsx(hs,{className:"w-4 h-4"}),"Start"]}),r.jsxs("button",{onClick:()=>x.mutate(),disabled:x.isPending||C.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:[r.jsx(en,{className:"w-4 h-4"}),"Clear"]}),r.jsx("button",{onClick:()=>b(),disabled:w,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:r.jsx(tr,{className:`w-4 h-4 ${w?"animate-spin":""}`})}),r.jsx("div",{className:"flex-1"}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:e,onChange:A=>n(A.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[g?.filtered_count??0,"/",g?.total_in_file??0]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:A=>o(A.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&&r.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[r.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"}),MX.map((A,F)=>r.jsx("button",{onClick:()=>c(A),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${F===MX.length-1?"rounded-r":""} ${l===A?`${_F[A]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:A},A))]})]})]}),r.jsx("div",{ref:f,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:C.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[r.jsx("p",{className:"mb-2",children:"No log entries found"}),r.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:P.map((A,F)=>{const _=a.has(F),M=A.message.includes(`
  8348. `);return r.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${_?"bg-bambu-dark-secondary/30":""}`,onClick:()=>M&&S(F),children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:k(A.timestamp)}),r.jsx("span",{className:"shrink-0",children:r.jsx(T,{level:A.level})}),r.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:A.logger_name,children:["[",A.logger_name,"]"]}),r.jsx("span",{className:`flex-1 ${_F[A.level]||"text-white/80"} ${!_&&M?"truncate":""}`,children:_?r.jsx("pre",{className:"whitespace-pre-wrap break-all",children:A.message}):A.message.split(`
  8349. `)[0]}),M&&r.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:_?r.jsx(Zo,{className:"w-3.5 h-3.5"}):r.jsx(Ln,{className:"w-3.5 h-3.5"})})]})},F)})})}),r.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:m?r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):r.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function Vst(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 Fa({icon:t,label:e,value:n,subValue:a,color:i="text-bambu-green"}){return r.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),a&&r.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:a})]})]})}function EX({percent:t,color:e="bg-bambu-green"}){return r.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function Jp({title:t,icon:e,children:n}){return r.jsxs(At,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(e,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function Gst(){const{t}=_t(),e=tn(),[n,a]=y.useState(null),[i,s]=y.useState(!1),[o,l]=y.useState(!1),{data:c,isLoading:d,refetch:u,isFetching:m}=Xe({queryKey:["systemInfo"],queryFn:ae.getSystemInfo,refetchInterval:3e4}),{data:p}=Xe({queryKey:["debugLogging"],queryFn:ny.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:f}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),{data:g}=Xe({queryKey:["library-stats"],queryFn:ae.getLibraryStats}),w=f?.time_format||"system",b=async()=>{l(!0);try{const C=await ny.setDebugLogging(!p?.enabled);e.setQueryData(["debugLogging"],C)}catch(C){console.error("Failed to toggle debug logging:",C)}finally{l(!1)}},x=async()=>{a(null),s(!0);try{await ny.downloadSupportBundle()}catch(C){a(C instanceof Error?C.message:"Failed to download support bundle")}finally{s(!1)}};if(d)return r.jsx("div",{className:"flex items-center justify-center h-64",children:r.jsx(ft,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return r.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const S=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",k=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return r.jsxs("div",{className:"p-6 space-y-6",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),r.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:[r.jsx(tr,{className:`w-4 h-4 ${m?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),r.jsx(Jp,{title:t("system.application","Application"),icon:Gf,children:r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[r.jsx(Fa,{icon:Gf,label:t("system.version","Version"),value:`v${c.app.version}`}),r.jsx(Fa,{icon:Zn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),r.jsx(Fa,{icon:Gf,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),r.jsx(Jp,{title:t("support.title","Support & Troubleshooting"),icon:Xbe,children:r.jsxs("div",{className:"space-y-4",children:[r.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.")}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${p?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:r.jsx(gy,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),r.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&&r.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(p.duration_seconds/60),"m ",p.duration_seconds%60,"s)"]})]})]})]}),r.jsxs("button",{onClick:b,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&&r.jsx(ft,{className:"w-4 h-4 animate-spin"}),p?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:r.jsx(Zr,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),r.jsxs("button",{onClick:x,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&&r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&r.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&&r.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:r.jsxs("p",{className:"text-sm text-bambu-gray",children:[r.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),r.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),r.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),r.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),r.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),r.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[r.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),r.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),r.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),r.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),r.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),r.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),r.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),r.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),r.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),r.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),r.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),r.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),r.jsxs("div",{children:[r.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),r.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[r.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),r.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),r.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),r.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),r.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),r.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]}),r.jsxs("li",{children:["• ",t("support.notItem7","IP addresses")]})]})]})]}),r.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].")})]}),r.jsx($st,{})]})}),r.jsxs(Jp,{title:t("system.database","Database"),icon:dc,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[r.jsx(Fa,{icon:dc,label:t("system.dbEngine","Database Engine"),value:c.database.engine||"SQLite"}),r.jsx(Fa,{icon:dc,label:t("system.dbVersion","Version"),value:c.database.version||"unknown"})]}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[r.jsx(Fa,{icon:eo,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),r.jsx(Fa,{icon:yl,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),r.jsx(Fa,{icon:$r,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),r.jsx(Fa,{icon:ft,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Fa,{icon:hr,label:t("system.printers","Printers"),value:c.database.printers}),r.jsx(Fa,{icon:ES,label:t("system.filaments","Filaments"),value:c.database.filaments}),r.jsx(Fa,{icon:to,label:t("system.projects","Projects"),value:c.database.projects}),r.jsx(Fa,{icon:hc,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[r.jsx(Fa,{icon:Zn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),r.jsx(Fa,{icon:eo,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),r.jsxs(Jp,{title:t("system.connectedPrinters","Connected Printers"),icon:hr,children:[r.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[r.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),r.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?r.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(C=>r.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),r.jsx("span",{className:"font-medium text-white",children:C.name})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[r.jsx("span",{children:C.model}),r.jsx("span",{className:`px-2 py-0.5 rounded ${C.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":C.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:C.state})]})]},C.id))}):r.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),r.jsx(Jp,{title:t("system.storage","Storage"),icon:ib,children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),r.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),r.jsx(EX,{percent:c.storage.disk_percent_used,color:S}),r.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),"%)"]})]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[r.jsx(Fa,{icon:eo,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),r.jsx(Fa,{icon:dc,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),g&&r.jsx(Fa,{icon:Pl,label:t("system.fileManagerStorage","File Manager"),value:Vst(g.total_size_bytes),subValue:`${g.total_files} files, ${g.total_folders} folders`})]})]})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[r.jsx(Jp,{title:t("system.memory","Memory"),icon:Dxe,children:r.jsx("div",{className:"space-y-4",children:r.jsxs("div",{children:[r.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),r.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),r.jsx(EX,{percent:c.memory.percent_used,color:k}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),r.jsx(Jp,{title:t("system.cpu","CPU"),icon:F0,children:r.jsx("div",{className:"space-y-4",children:r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsx(Fa,{icon:F0,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),r.jsx(Fa,{icon:F0,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),r.jsx(Jp,{title:t("system.systemDetails","System Details"),icon:Gf,children:r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Fa,{icon:Gf,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),r.jsx(Fa,{icon:F0,label:t("system.architecture","Architecture"),value:c.system.architecture}),r.jsx(Fa,{icon:Gf,label:t("system.python","Python"),value:c.system.python_version}),r.jsx(Fa,{icon:Zn,label:t("system.bootTime","Boot Time"),value:Fg(c.system.boot_time,w)})]})})]})}const nO="auth_remember_me";function kF(t){return t?"persistent":"session"}function Wst(){try{const t=sessionStorage.getItem(nO)==="1";return sessionStorage.removeItem(nO),t}catch(t){return console.warn("consumeSavedRememberMe: sessionStorage unavailable, Remember Me preference lost across OIDC redirect",t),!1}}function Kst({provider:t,onClick:e,disabled:n}){const{t:a}=_t(),[i,s]=y.useState(!1),o=t.has_icon&&!i;return r.jsxs("button",{type:"button",onClick:e,disabled:n,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?r.jsx("img",{src:ae.oidcProviderIconUrl(t.id),alt:"",className:"w-5 h-5 object-contain",onError:()=>s(!0)}):r.jsx(hl,{className:"w-5 h-5 text-bambu-green"}),a("login.twoFA.signInWith",{provider:t.name})]})}function Qst(){const t=ji(),[e]=nb(),{t:n}=_t(),{login:a,loginWithToken:i}=dr(),{showToast:s}=on(),{mode:o}=ob(),[l,c]=y.useState(""),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[w,b]=y.useState("credentials"),[x,S]=y.useState(""),[k,C]=y.useState([]),[P,T]=y.useState("totp"),[A,F]=y.useState(""),[_,M]=y.useState(!1),H=y.useRef(null),[I,z]=y.useState(!1),[L,Z]=y.useState(""),[ne,Y]=y.useState(""),[ce,ue]=y.useState(""),{data:oe}=Xe({queryKey:["advancedAuthStatus"],queryFn:()=>ae.getAdvancedAuthStatus()}),{data:Q}=Xe({queryKey:["oidcProviders"],queryFn:()=>ae.getOIDCProviders()});y.useEffect(()=>{const O=window.location.hash,ie=O.startsWith("#reset_token=")?O.slice(13):null;ie&&(Z(ie),b("reset-password"),t("/login",{replace:!0}))},[]),y.useEffect(()=>{const O=window.location.hash,ie=O.startsWith("#oidc_token=")?O.slice(12):null,U=e.get("oidc_error");if(!ie&&!U)return;const G=Wst();if(U){const X={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")}[U]??(U.startsWith("token_exchange_")?n("login.oidcErrors.tokenExchangeFailed"):n("login.oidcLoginFailed"));s(X,"error"),t("/login",{replace:!0});return}ie&&ae.exchangeOIDCToken(ie).then(K=>{if(K.requires_2fa&&K.pre_auth_token){z(G),S(K.pre_auth_token);const X=K.two_fa_methods??[];C(X),X.includes("totp")?T("totp"):X.includes("email")?T("email"):T("backup"),b("2fa"),t("/login",{replace:!0})}else K.access_token&&K.user?(i(K.access_token,K.user,kF(G)),s(n("login.loginSuccess")),t("/",{replace:!0})):(s(n("login.oidcLoginFailed"),"error"),t("/login",{replace:!0}))}).catch(K=>{console.error("OIDC token exchange failed",K),s(n("login.oidcLoginFailed"),"error"),t("/login",{replace:!0})})},[e]);const le=lt({mutationFn:()=>a(l,d,kF(I)),onSuccess:O=>{if(O.requires_2fa&&O.pre_auth_token){S(O.pre_auth_token);const ie=O.two_fa_methods??[];C(ie),ie.includes("totp")?T("totp"):ie.includes("email")?T("email"):T("backup"),b("2fa")}else O.access_token&&O.user&&(s(n("login.loginSuccess")),t("/"))},onError:O=>{s(O.message||n("login.loginFailed"),"error")}}),pe=lt({mutationFn:O=>ae.forgotPassword({email:O}),onSuccess:O=>{s(O.message,"success"),p(!1),g("")},onError:O=>{s(O.message,"error")}}),he=lt({mutationFn:()=>ae.forgotPasswordConfirm(L,ne),onSuccess:O=>{s(O.message,"success"),b("credentials"),Z(""),Y(""),ue("")},onError:O=>{s(O.message||n("login.resetPassword.resetFailed"),"error")}}),we=lt({mutationFn:()=>ae.sendEmailOTP(x),onSuccess:O=>{M(!0),O.pre_auth_token&&S(O.pre_auth_token),s(O.message,"success")},onError:O=>{s(O.message||n("login.twoFA.sendCodeFailed"),"error")}}),$=lt({mutationFn:()=>ae.verify2FA({pre_auth_token:x,code:A,method:P}),onSuccess:O=>{O.access_token&&O.user?(i(O.access_token,O.user,kF(I)),s(n("login.loginSuccess")),t("/")):(console.error("2FA verify: unexpected response shape",O),s(n("login.loginFailed"),"error"))},onError:O=>{s(O.message||n("login.twoFA.invalidCode"),"error"),F("")}}),J=lt({mutationFn:O=>ae.getOIDCAuthorizeUrl(O),onSuccess:O=>{if(I)try{sessionStorage.setItem(nO,"1")}catch(ie){console.warn("setItem auth_remember_me failed, Remember Me will not carry through OIDC redirect",ie)}window.location.href=O.auth_url},onError:O=>{s(O.message||n("login.oidcLoginFailed"),"error")}}),j=O=>{if(O.preventDefault(),!l||!d){s(n("login.enterCredentials"),"error");return}le.mutate()},E=O=>{if(O.preventDefault(),!A.trim()){s(n("login.twoFA.enterCode"),"error");return}$.mutate()},B=O=>{if(O.preventDefault(),!f){s(n("login.enterEmail"),"error");return}pe.mutate(f)},W=O=>{T(O),F(""),M(!1),setTimeout(()=>H.current?.focus(),0)};if(w==="reset-password"){const O=ie=>{if(ie.preventDefault(),ne!==ce){s(n("login.resetPassword.passwordsDoNotMatch"),"error");return}if(ne.length<8){s(n("login.resetPassword.passwordTooShort"),"error");return}he.mutate()};return r.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:r.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:[r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"flex items-center justify-center mb-4",children:r.jsx("div",{className:"w-14 h-14 rounded-full bg-bambu-green/20 flex items-center justify-center",children:r.jsx(bo,{className:"w-7 h-7 text-bambu-green"})})}),r.jsx("h2",{className:"text-2xl font-bold text-white",children:n("login.resetPassword.title")}),r.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.resetPassword.subtitle")})]}),r.jsxs("form",{onSubmit:O,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"new-password",className:"block text-sm font-medium text-white mb-2",children:n("login.resetPassword.newPassword")}),r.jsx("input",{id:"new-password",type:"password",required:!0,value:ne,onChange:ie=>Y(ie.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})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:n("login.resetPassword.confirmPassword")}),r.jsx("input",{id:"confirm-password",type:"password",required:!0,value:ce,onChange:ie=>ue(ie.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"})]}),r.jsx("button",{type:"submit",disabled:he.isPending||!ne||!ce,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:he.isPending?n("login.resetPassword.saving"):n("login.resetPassword.submit")})]}),r.jsx("div",{className:"text-center",children:r.jsx("button",{type:"button",onClick:()=>{b("credentials"),Z(""),Y(""),ue("")},className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.resetPassword.backToLogin")})})]})})}return w==="2fa"?r.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:r.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:[r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"flex items-center justify-center mb-4",children:r.jsx("div",{className:"w-14 h-14 rounded-full bg-bambu-green/20 flex items-center justify-center",children:r.jsx(hl,{className:"w-7 h-7 text-bambu-green"})})}),r.jsx("h2",{className:"text-2xl font-bold text-white",children:n("login.twoFA.title")}),r.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.twoFA.subtitle")})]}),k.length>1&&r.jsxs("div",{className:"flex gap-2",children:[k.includes("totp")&&r.jsxs("button",{type:"button",onClick:()=>W("totp"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${P==="totp"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[r.jsx(YF,{className:"w-4 h-4"}),n("login.twoFA.methodAuthenticator")]}),k.includes("email")&&r.jsxs("button",{type:"button",onClick:()=>W("email"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${P==="email"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[r.jsx($m,{className:"w-4 h-4"}),n("login.twoFA.methodEmail")]}),k.includes("backup")&&r.jsxs("button",{type:"button",onClick:()=>W("backup"),className:`flex-1 flex flex-col items-center gap-1 py-2 px-3 rounded-lg border text-xs font-medium transition-colors ${P==="backup"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-green/50"}`,children:[r.jsx(bo,{className:"w-4 h-4"}),n("login.twoFA.methodBackup")]})]}),r.jsxs("form",{onSubmit:E,className:"space-y-4",children:[P==="totp"&&r.jsx("p",{className:"text-sm text-bambu-gray",children:n("login.twoFA.instructionsTotp")}),P==="email"&&r.jsxs("div",{className:"space-y-3",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n(_?"login.twoFA.instructionsEmail":"login.twoFA.instructionsEmailNotSent")}),!_&&r.jsx(je,{type:"button",variant:"secondary",className:"w-full",onClick:()=>we.mutate(),disabled:we.isPending,children:we.isPending?n("login.twoFA.sendingCode"):n("login.twoFA.sendCodeButton")}),_&&r.jsx("button",{type:"button",onClick:()=>{M(!1),we.mutate()},className:"text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.twoFA.resendCode")})]}),P==="backup"&&r.jsx("p",{className:"text-sm text-bambu-gray",children:n("login.twoFA.instructionsBackup")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"twofa-code",className:"block text-sm font-medium text-white mb-2",children:n(P==="backup"?"login.twoFA.backupCodeLabel":"login.twoFA.codeLabel")}),r.jsx("input",{ref:H,id:"twofa-code",type:"text",inputMode:P==="backup"?"text":"numeric",autoComplete:"one-time-code",value:A,onChange:O=>F(O.target.value.trim()),disabled:P==="email"&&!_,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(P==="backup"?"login.twoFA.backupCodePlaceholder":"login.twoFA.codePlaceholder"),maxLength:P==="backup"?8:6,autoFocus:!0})]}),r.jsx("button",{type:"submit",disabled:$.isPending||!A.trim()||P==="email"&&!_,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:$.isPending?n("login.twoFA.verifyingButton"):n("login.twoFA.verifyButton")})]}),r.jsx("div",{className:"text-center",children:r.jsx("button",{type:"button",onClick:()=>{b("credentials"),S(""),F(""),M(!1)},className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.twoFA.backToLogin")})})]})}):r.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[r.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:[r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"flex items-center justify-center mb-6",children:r.jsx("img",{src:o==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),r.jsx("h2",{className:"text-3xl font-bold text-white",children:n("login.title")}),r.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:n("login.subtitle")})]}),r.jsxs("form",{className:"mt-8 space-y-6",onSubmit:j,children:[r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:oe?.advanced_auth_enabled?n("login.usernameOrEmail"):n("login.username")}),r.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:oe?.advanced_auth_enabled?n("login.usernameOrEmailPlaceholder"):n("login.usernamePlaceholder"),autoComplete:"username"})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:n("login.password")||"Password"}),r.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"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{id:"remember-me",type:"checkbox",checked:I,onChange:O=>z(O.target.checked),className:"h-4 w-4 rounded border-bambu-dark-tertiary bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green/50 cursor-pointer"}),r.jsx("label",{htmlFor:"remember-me",className:"text-sm text-bambu-gray cursor-pointer",children:n("login.rememberMe")})]}),r.jsx("div",{children:r.jsx("button",{type:"submit",disabled:le.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:le.isPending?n("login.signingIn"):n("login.signIn")})}),r.jsx("div",{className:"text-center",children:r.jsx("button",{type:"button",onClick:()=>p(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:n("login.forgotPassword")})})]}),Q&&Q.length>0&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx("div",{className:"absolute inset-0 flex items-center",children:r.jsx("div",{className:"w-full border-t border-bambu-dark-tertiary"})}),r.jsx("div",{className:"relative flex justify-center text-sm",children:r.jsx("span",{className:"px-2 bg-bambu-dark-secondary text-bambu-gray",children:n("login.twoFA.orContinueWith")})})]}),r.jsx("div",{className:"space-y-2",children:Q.map(O=>r.jsx(Kst,{provider:O,onClick:()=>J.mutate(O.id),disabled:J.isPending},O.id))})]})]}),m&&r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>p(!1),children:r.jsxs(At,{className:"w-full max-w-md",onClick:O=>O.stopPropagation(),children:[r.jsx(fn,{children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("login.forgotPasswordTitle")})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:()=>{p(!1),g("")},children:r.jsx(Vt,{className:"w-5 h-5"})})]})}),r.jsx(Et,{children:oe?.advanced_auth_enabled?r.jsxs("form",{onSubmit:B,className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray text-sm",children:n("login.forgotPasswordEmailMessage")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:n("login.emailAddress")}),r.jsx("input",{id:"forgot-email",type:"email",required:!0,value:f,onChange:O=>g(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")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{p(!1),g("")},children:n("login.cancel")}),r.jsx(je,{type:"submit",className:"flex-1",disabled:pe.isPending,children:pe.isPending?n("login.sending"):n("login.sendResetEmail")})]})]}):r.jsxs("div",{className:"space-y-4",children:[r.jsx("p",{className:"text-bambu-gray",children:n("login.forgotPasswordMessage")}),r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[r.jsx("p",{className:"text-sm text-white font-medium",children:n("login.howToReset")}),r.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[r.jsx("li",{children:n("login.resetStep1")}),r.jsx("li",{children:n("login.resetStep2")}),r.jsx("li",{children:n("login.resetStep3")}),r.jsx("li",{children:n("login.resetStep4")})]})]}),r.jsx(je,{variant:"secondary",className:"w-full",onClick:()=>p(!1),children:n("login.gotIt")})]})})]})})]})}function Yst(){const t=ji(),{t:e}=_t(),{showToast:n}=on(),{mode:a}=ob(),{refreshAuth:i}=dr(),[s,o]=y.useState(!1),[l,c]=y.useState(""),[d,u]=y.useState(""),[m,p]=y.useState(""),f=lt({mutationFn:()=>ae.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?d:void 0}),onSuccess:async w=>{await i(),w.auth_enabled?w.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:w=>{n(w.message,"error")}}),g=w=>{if(w.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 r.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:r.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:[r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"flex items-center justify-center mb-6",children:r.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),r.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),r.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),r.jsxs("form",{className:"mt-8 space-y-6",onSubmit:g,children:[r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:w=>o(w.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),r.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&r.jsxs("div",{className:"space-y-4 mt-4",children:[r.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(_i,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"text-sm text-bambu-gray",children:[r.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),r.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),r.jsxs("div",{children:[r.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",r.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),r.jsx("input",{id:"admin-username",type:"text",value:l,onChange:w=>c(w.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"})]}),r.jsxs("div",{children:[r.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",r.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),r.jsx("input",{id:"admin-password",type:"password",value:d,onChange:w=>u(w.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&&r.jsxs("div",{children:[r.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),r.jsx("input",{id:"confirm-password",type:"password",value:m,onChange:w=>p(w.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"})]})]})]}),r.jsx("div",{children:r.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 Xst(){const{t}=_t(),{user:e}=dr(),{showToast:n}=on(),a=tn(),i=ji(),[s,o]=y.useState(!0),[l,c]=y.useState(!0),[d,u]=y.useState(!0),[m,p]=y.useState(!0),[f,g]=y.useState(!1),{data:w,isLoading:b}=Xe({queryKey:["advancedAuthStatus"],queryFn:ae.getAdvancedAuthStatus,staleTime:300*1e3}),{data:x,isLoading:S}=Xe({queryKey:["settings"],queryFn:ae.getSettings,staleTime:300*1e3}),{data:k,isLoading:C}=Xe({queryKey:["user-email-preferences"],queryFn:()=>ae.getUserEmailPreferences()});y.useEffect(()=>{(w&&!w.advanced_auth_enabled||x&&!x.user_notifications_enabled)&&i("/settings",{replace:!0})},[w,x,i]),y.useEffect(()=>{k&&(o(k.notify_print_start),c(k.notify_print_complete),u(k.notify_print_failed),p(k.notify_print_stopped),g(!1))},[k]);const P=lt({mutationFn:()=>ae.updateUserEmailPreferences({notify_print_start:s,notify_print_complete:l,notify_print_failed:d,notify_print_stopped:m}),onSuccess:()=>{a.invalidateQueries({queryKey:["user-email-preferences"]}),g(!1),n(t("notifications.userEmail.saveSuccess"),"success")},onError:A=>{n(A.message||t("notifications.userEmail.saveError"),"error")}}),T=(A,F)=>{A(!F),g(!0)};return C||b||S?r.jsx("div",{className:"flex items-center justify-center h-64",children:r.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r.jsxs("div",{className:"p-4 md:p-6 max-w-2xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[r.jsx(Ch,{className:"w-7 h-7 text-bambu-green"}),r.jsx("h1",{className:"text-2xl font-bold text-white",children:t("notifications.userEmail.title")})]}),r.jsx(At,{className:"mb-6 border-blue-500/30 bg-blue-500/5",children:r.jsx(Et,{className:"py-4",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:r.jsx($m,{className:"w-5 h-5 text-blue-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-white font-medium",children:t("notifications.userEmail.emailNotifications")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.emailNotificationsDesc")}),e?.email?r.jsxs("p",{className:"text-sm text-blue-400 mt-2",children:[t("notifications.userEmail.sendingTo"),": ",r.jsx("strong",{children:e.email})]}):r.jsx("p",{className:"text-sm text-yellow-400 mt-2",children:t("notifications.userEmail.noEmailWarning")})]})]})})}),r.jsxs(At,{className:"mb-6",children:[r.jsxs(fn,{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:t("notifications.userEmail.printJobNotifications")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("notifications.userEmail.printJobNotificationsDesc")})]}),r.jsxs(Et,{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${s?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(yl,{className:`w-5 h-5 ${s?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStarts")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStartsDesc")})]})]}),r.jsx("button",{onClick:()=>T(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:r.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${s?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(yl,{className:`w-5 h-5 ${l?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobFinishes")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobFinishesDesc")})]})]}),r.jsx("button",{onClick:()=>T(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:r.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${d?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(yl,{className:`w-5 h-5 ${d?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printErrors")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printErrorsDesc")})]})]}),r.jsx("button",{onClick:()=>T(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:r.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${d?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${m?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(yl,{className:`w-5 h-5 ${m?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:t("notifications.userEmail.printJobStops")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("notifications.userEmail.printJobStopsDesc")})]})]}),r.jsx("button",{onClick:()=>T(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:r.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${m?"translate-x-6":"translate-x-1"}`})})]})]})]}),r.jsx("div",{className:"flex justify-end",children:r.jsx(je,{onClick:()=>P.mutate(),disabled:!f||P.isPending||!e?.email,children:P.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ds,{className:"w-4 h-4"}),t("common.save")]})})})]})}function Zst(){const t=ji(),[e]=nb(),{t:n}=_t();if(window!==window.top)return r.jsxs("div",{style:{padding:32,color:"#f88"},children:["GCode viewer static files not found. Check that the"," ",r.jsx("code",{children:"gcode_viewer/"})," directory exists and restart uvicorn."]});const a=e.has("archive"),i=e.has("library_file"),s=a?"/archives":i?"/files":"/",o=n(a?"gcodeViewer.backToArchives":i?"gcodeViewer.backToFiles":"gcodeViewer.back"),l=()=>{window.history.length>1?t(-1):t(s)},c=`/gcode-viewer/${window.location.search}`;return r.jsxs("div",{style:{height:"calc(100vh - 3.5rem)",display:"flex",flexDirection:"column"},children:[r.jsx("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900",children:r.jsxs("button",{type:"button",onClick:l,className:"inline-flex items-center gap-1.5 text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors",children:[r.jsx(ST,{className:"w-4 h-4"}),o]})}),r.jsx("iframe",{src:c,title:"GCode Viewer",style:{display:"block",width:"100%",flex:1,border:"none"}})]})}function Jst(){const t=y.useRef(null),e=y.useRef(null),n=tn(),[a,i]=y.useState(!1),s=y.useRef(new Map),{showToast:o}=on(),{t:l}=_t(),c=y.useRef(new Set),d=y.useRef(null),u=y.useRef(new Map),m=y.useRef(null),p=y.useRef([]),f=y.useRef(!1),g=y.useRef(()=>{}),w=y.useCallback(()=>{if(f.current||p.current.length===0)return;f.current=!0;const P=()=>{const T=p.current.shift();T?requestAnimationFrame(()=>{g.current(T),p.current.length>0?setTimeout(P,16):f.current=!1}):f.current=!1};P()},[]),b=y.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const T=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,A=new WebSocket(T);let F=null;A.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),F=window.setInterval(()=>{A.readyState===WebSocket.OPEN&&A.send(JSON.stringify({type:"ping"}))},3e4)},A.onmessage=_=>{try{const M=JSON.parse(_.data);M.type==="printer_status"&&M.printer_id!==void 0&&M.data?g.current(M):(p.current.push(M),w())}catch{}},A.onclose=_=>{console.log("[WebSocket] Closed",_.code,_.reason),F&&(clearInterval(F),F=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{b()},3e3)},A.onerror=_=>{console.error("[WebSocket] Error",_),A.close()},t.current=A},[w]),x=y.useCallback((P,T)=>{const A=u.current.get(P)||{};u.current.set(P,{...A,...T}),m.current||(m.current=window.setTimeout(()=>{const F=new Map(u.current);u.current.clear(),m.current=null,requestAnimationFrame(()=>{F.forEach((_,M)=>{n.setQueryData(["printerStatus",M],H=>{const I={...H,..._};return I.wifi_signal==null&&H?.wifi_signal!=null&&(I.wifi_signal=H.wifi_signal),I})})})},100))},[n]),S=y.useCallback(P=>{c.current.add(P),d.current&&clearTimeout(d.current),d.current=window.setTimeout(()=>{const T=Array.from(c.current);c.current.clear(),d.current=null;let A=0;T.forEach(F=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[F]})})},A),A+=500})},3e3)},[n]),k=y.useCallback(P=>{switch(P.type){case"printer_status":P.printer_id!==void 0&&P.data&&x(P.printer_id,P.data);break;case"print_start":P.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",P.printer_id]});break;case"missing_spool_assignment":{if(P.printer_id===void 0||!Array.isArray(P.missing_slots))break;const T=P.missing_slots.map(M=>M&&typeof M.slot=="string"?M.slot:"Unknown").filter(M=>M.length>0);if(T.length===0){s.current.delete(P.printer_id);break}const A=T.join("|");if(s.current.get(P.printer_id)===A)break;s.current.set(P.printer_id,A);const F=P.printer_name||`Printer ${P.printer_id}`,_=l("printers.toast.missingSpoolAssignment",{printer:F,slots:T.join(", ")});o(_,"warning");break}case"print_complete":S("archives"),S("archiveStats");break;case"archive_created":S("archives"),S("archiveStats");break;case"archive_updated":S("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:P.printer_id,printer_name:P.printer_name,message:P.message}}));break;case"inventory_changed":S("inventory-spools");break;case"spool_assignment_changed":S("spool-assignments"),S("slotPresets");break;case"spool_auto_assigned":S("inventory-spools"),S("spool-assignments");break;case"spool_usage_logged":S("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:P.printer_id,ams_id:P.ams_id,tray_id:P.tray_id,tag_uid:P.tag_uid,tray_uuid:P.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:P.data||{}}));break;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:P}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:P})),S("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:P}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:P}));break;case"spoolbuddy_tag_written":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-written",{detail:P})),S("inventory-spools");break;case"spoolbuddy_tag_write_failed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-write-failed",{detail:P}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:P})),S("spoolbuddy-devices"),S("spoolbuddy-update-check");break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:P})),S("spoolbuddy-devices");break;case"spoolbuddy_update":S("spoolbuddy-devices"),S("spoolbuddy-update-check");break}},[n,S,x,o,l]);y.useEffect(()=>{g.current=k},[k]),y.useEffect(()=>(b(),()=>{e.current&&clearTimeout(e.current),d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),t.current&&t.current.close()}),[b]);const C=y.useCallback(P=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(P))},[]);return{isConnected:a,sendMessage:C}}function eot({children:t}){const{authEnabled:e,user:n,loading:a}=dr(),i=!a&&(!e||n!==null),{data:s}=Xe({queryKey:["color-catalog-map"],queryFn:async()=>(await ae.getColorNameMap()).colors,staleTime:1/0,gcTime:1/0,retry:2,enabled:i});return y.useEffect(()=>{s&&$ve(s)},[s]),r.jsx(r.Fragment,{children:t})}function tot({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:a}=_t(),[i,s]=y.useState(new Date),{data:o=[]}=Xe({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),l=rf({queries:o.map(u=>({queryKey:["printerStatus",u.id],queryFn:()=>ae.getPrinterStatus(u.id),refetchInterval:1e4}))}),c=y.useMemo(()=>o.filter((u,m)=>l[m]?.data?.connected),[o,l]);y.useEffect(()=>{const u=c.some(m=>m.id===t);(!t||!u)&&c.length>0&&e(c[0].id)},[c,t,e]);const{data:d}=Xe({queryKey:["settings"],queryFn:ae.getSettings});return y.useEffect(()=>{const u=setInterval(()=>s(new Date),1e3);return()=>clearInterval(u)},[]),r.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:[r.jsx("div",{className:"flex items-center shrink-0",children:r.jsx("img",{src:"/img/spoolbuddy_logo_dark_small.png",alt:"SpoolBuddy",width:113,height:28,className:"h-7 w-auto"})}),r.jsx("div",{className:"flex-1 flex justify-center",children:r.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?r.jsx("option",{value:"",children:a("spoolbuddy.status.noPrinters","No printers online")}):c.map(u=>r.jsx("option",{value:u.id,children:u.name},u.id))})}),r.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[r.jsx("div",{className:"flex items-center",title:n?a("spoolbuddy.status.backend","Backend"):a("spoolbuddy.status.offline","Offline"),children:n?r.jsx("div",{className:"flex items-end gap-0.5 h-4",children:[1,2,3,4].map(u=>r.jsx("div",{className:`w-1 rounded-sm ${u<=4?"bg-white":"bg-bambu-dark-tertiary"}`,style:{height:`${u*4}px`}},u))}):r.jsx(hu,{className:"w-5 h-5 text-red-400"})}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.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"}`}),r.jsx("span",{className:"text-sm text-white/50",children:n?a("spoolbuddy.status.backend","Backend"):a("spoolbuddy.status.offline","Offline")})]}),r.jsx("span",{className:"text-white/50 text-base font-mono min-w-[50px] text-right",children:lJ(i,d?.time_format||"system")})]})]})}const not=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:r.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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:r.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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:r.jsxs("svg",{className:"w-6 h-6",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:[r.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"}),r.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:r.jsx("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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:r.jsxs("svg",{className:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[r.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"}),r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function rot(){const{t}=_t();return r.jsx("nav",{className:"h-14 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-stretch shrink-0",children:not.map(e=>r.jsxs(Vx,{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,r.jsx("span",{className:"text-xs font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}function aot({alert:t}){const{t:e}=_t(),n=t?t.type==="error"?"bg-red-500":t.type==="warning"?"bg-amber-500":"bg-bambu-green":"bg-bambu-green",a=t?t.type==="error"?"border-red-500":t.type==="warning"?"border-amber-500":"border-bambu-dark-tertiary":"border-bambu-dark-tertiary";return r.jsxs("div",{className:`h-9 bg-bambu-dark-secondary border-t-2 ${a} flex items-center px-3 gap-3 shrink-0`,children:[r.jsx("div",{className:`w-3.5 h-3.5 rounded-full ${n}`}),r.jsx("div",{className:"flex-1 text-sm text-white/50 truncate",children:t?r.jsx("span",{children:t.message}):r.jsx("span",{className:"text-bambu-green",children:e("spoolbuddy.status.systemReady","System Ready")})})]})}function iot({isOpen:t,onClose:e,deviceId:n,deviceOnline:a}){const{t:i}=_t(),[s,o]=y.useState(null),[l,c]=y.useState(!1),[d,u]=y.useState(new Map),{data:m=[]}=Xe({queryKey:["printers"],queryFn:()=>ae.getPrinters(),enabled:t}),{data:p=[]}=Xe({queryKey:["smart-plugs"],queryFn:()=>ae.getSmartPlugs(),enabled:t}),f=m.map(S=>{const k=p.find(P=>P.printer_id===S.id&&P.plug_type!=="mqtt"&&P.enabled);if(!k)return null;const C=d.get(k.id);return{plug:k,printer:S,status:C?{state:C.state,reachable:!0,device_name:null,energy:null}:null,loading:C?.loading??!1}}).filter(Boolean);y.useEffect(()=>{if(!t||p.length===0)return;p.filter(k=>k.printer_id!==null&&k.plug_type!=="mqtt"&&k.enabled).forEach(async k=>{try{const C=await ae.getSmartPlugStatus(k.id);u(P=>{const T=new Map(P);return T.set(k.id,{loading:!1,state:C.state}),T})}catch{u(C=>{const P=new Map(C);return P.set(k.id,{loading:!1,state:null}),P})}})},[t,p]),y.useEffect(()=>{t||(o(null),c(!1))},[t]);const g=y.useCallback(async S=>{u(k=>{const C=new Map(k),P=C.get(S.id);return C.set(S.id,{loading:!0,state:P?.state??null}),C});try{await ae.controlSmartPlug(S.id,"toggle");const k=await ae.getSmartPlugStatus(S.id);u(C=>{const P=new Map(C);return P.set(S.id,{loading:!1,state:k.state}),P})}catch{u(k=>{const C=new Map(k),P=C.get(S.id);return C.set(S.id,{loading:!1,state:P?.state??null}),C})}},[]),w=y.useCallback(async S=>{if(n){c(!0);try{await Jr.systemCommand(n,S),setTimeout(()=>e(),500)}catch{c(!1)}}},[n,e]),b=y.useCallback(()=>{s&&(s.type==="system"?w(s.command):g(s.plug),o(null))},[s,w,g]);if(!t)return null;const x=S=>S==="ON"||S==="on";return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-40 bg-black/50",onPointerDown:e}),r.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:[r.jsx("div",{className:"flex justify-center pt-2 pb-1",children:r.jsx("div",{className:"w-10 h-1 rounded-full bg-zinc-600"})}),r.jsxs("div",{className:"px-4 pb-4 max-h-[80vh] overflow-y-auto",children:[f.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.printerPower","Printer Power")}),r.jsx("div",{className:"space-y-1",children:f.map(({plug:S,printer:k,loading:C})=>{const P=d.get(S.id),T=x(P?.state??null);return r.jsxs("button",{onClick:()=>o({type:"plug",plug:S,printer:k,currentState:P?.state??null}),disabled:C,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:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${T?"bg-green-500":"bg-zinc-600"}`}),C&&r.jsx(ft,{className:"w-3 h-3 animate-spin text-zinc-400 shrink-0"}),r.jsx("span",{className:"flex-1 text-sm text-zinc-200 text-left truncate",children:k.name}),r.jsx("span",{className:`text-xs font-medium ${T?"text-green-400":"text-zinc-500"}`,children:P?.state??"—"})]},S.id)})})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-xs font-semibold text-zinc-500 uppercase tracking-wide mb-2",children:i("spoolbuddy.quickMenu.systemControls","System")}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsx(fN,{icon:r.jsx(Dw,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartDaemon","Restart Daemon"),onClick:()=>o({type:"system",command:"restart_daemon"}),disabled:!n||!a||l}),r.jsx(fN,{icon:r.jsx(kO,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.restartBrowser","Restart Browser"),onClick:()=>o({type:"system",command:"restart_browser"}),disabled:!n||!a||l}),r.jsx(fN,{icon:r.jsx(Dw,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.reboot","Reboot"),onClick:()=>o({type:"system",command:"reboot"}),disabled:!n||!a||l,variant:"warning"}),r.jsx(fN,{icon:r.jsx(FS,{className:"w-4 h-4"}),label:i("spoolbuddy.quickMenu.shutdown","Shutdown"),onClick:()=>o({type:"system",command:"shutdown"}),disabled:!n||!a||l,variant:"danger"})]})]}),r.jsx("div",{className:"flex justify-center mt-3",children:r.jsxs("div",{className:"flex items-center gap-1 text-xs text-zinc-600",children:[r.jsx(Ln,{className:"w-3 h-3"}),r.jsx("span",{children:i("spoolbuddy.quickMenu.swipeToClose","Swipe down to close")})]})})]})]}),s&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/60",children:r.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-5 mx-4 max-w-sm w-full border border-zinc-700",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-2",children:i("spoolbuddy.quickMenu.confirmTitle","Confirm")}),r.jsx("p",{className:"text-sm text-zinc-400 mb-5",children:s.type==="plug"?x(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.")}),r.jsxs("div",{className:"flex gap-3",children:[r.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")}),r.jsx("button",{onClick:b,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"?x(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?r.jsx(ft,{className:"w-4 h-4 animate-spin mx-auto"}):s.type==="plug"?x(s.currentState)?i("spoolbuddy.quickMenu.turnOff","Turn Off"):i("spoolbuddy.quickMenu.turnOn","Turn On"):i("spoolbuddy.quickMenu.confirm","Confirm")})]})]})})]})}function fN({icon:t,label:e,onClick:n,disabled:a,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 r.jsxs("button",{onClick:n,disabled:a,className:`flex items-center gap-2.5 p-3 rounded-xl transition-colors min-h-[48px] disabled:opacity-40 ${s[i]}`,children:[t,r.jsx("span",{className:"text-sm font-medium",children:e})]})}const sot={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,unknownTrayUuid:null,deviceOnline:!1,deviceId:null};function oot(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,unknownTrayUuid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,unknownTrayUuid:e.trayUuid??null,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null,unknownTrayUuid: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 lot(){const[t,e]=y.useReducer(oot,sot),n=y.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??""})},[]),a=y.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=y.useCallback(u=>{const m=u.detail;e({type:"UNKNOWN_TAG",tagUid:m.tag_uid??m.data?.tag_uid??"",trayUuid:m.tray_uuid??m.data?.tray_uuid??null,deviceId:m.device_id??m.data?.device_id??""})},[]),s=y.useCallback(u=>{const m=u.detail;e({type:"TAG_REMOVED",deviceId:m.device_id??m.data?.device_id??""})},[]),o=y.useCallback(u=>{const m=u.detail;e({type:"DEVICE_ONLINE",deviceId:m.device_id??m.data?.device_id??""})},[]),l=y.useCallback(u=>{const m=u.detail;e({type:"DEVICE_OFFLINE",deviceId:m.device_id??m.data?.device_id??""})},[]);y.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",a),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",a),window.removeEventListener("spoolbuddy-unknown-tag",i),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,a,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 VN={exports:{}};var cot=VN.exports,DX;function dot(){return DX||(DX=1,(function(t,e){(function(n,a){t.exports=a(tb())})(cot,(function(n){return(function(){var a={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(C){for(var P=0,T=this.length;P<T;P++)if(P in this&&this[P]===C)return P;return-1},g=function(C,P){this.name=C,this.code=DOMException[C],this.message=P},w=function(C,P){if(P==="")throw new g("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(P))throw new g("INVALID_CHARACTER_ERR","The token must not contain space characters.");return f.call(C,P)},b=function(C){for(var P=p.call(C.getAttribute("class")||""),T=P?P.split(/\s+/):[],A=0,F=T.length;A<F;A++)this.push(T[A]);this._updateClassName=function(){C.setAttribute("class",this.toString())}},x=b[d]=[],S=function(){return new b(this)};if(g[d]=Error[d],x.item=function(C){return this[C]||null},x.contains=function(C){return~w(this,C+"")},x.add=function(){var C,P=arguments,T=0,A=P.length,F=!1;do~w(this,C=P[T]+"")||(this.push(C),F=!0);while(++T<A);F&&this._updateClassName()},x.remove=function(){var C,P,T=arguments,A=0,F=T.length,_=!1;do for(P=w(this,C=T[A]+"");~P;)this.splice(P,1),_=!0,P=w(this,C);while(++A<F);_&&this._updateClassName()},x.toggle=function(C,P){var T=this.contains(C),A=T?P!==!0&&"remove":P!==!1&&"add";return A&&this[A](C),P===!0||P===!1?P:!T},x.replace=function(C,P){var T=w(C+"");~T&&(this.splice(T,1,P),this._updateClassName())},x.toString=function(){return this.join(" ")},m.defineProperty){var k={get:S,enumerable:!0,configurable:!0};try{m.defineProperty(u,c,k)}catch(C){C.number!==void 0&&C.number!==-2146823252||(k.enumerable=!1,m.defineProperty(u,c,k))}}else m[d].__defineGetter__&&u.__defineGetter__(c,S)}})(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,g=arguments.length;for(f=0;f<g;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($,J,j){var E=j(4901),B=j(6823),W=TypeError;$.exports=function(O){if(E(O))return O;throw new W(B(O)+" is not a function")}},5548:function($,J,j){var E=j(3517),B=j(6823),W=TypeError;$.exports=function(O){if(E(O))return O;throw new W(B(O)+" is not a constructor")}},3506:function($,J,j){var E=j(3925),B=String,W=TypeError;$.exports=function(O){if(E(O))return O;throw new W("Can't set "+B(O)+" as a prototype")}},6469:function($,J,j){var E=j(8227),B=j(2360),W=j(4913).f,O=E("unscopables"),ie=Array.prototype;ie[O]===void 0&&W(ie,O,{configurable:!0,value:B(null)}),$.exports=function(U){ie[O][U]=!0}},7829:function($,J,j){var E=j(8183).charAt;$.exports=function(B,W,O){return W+(O?E(B,W).length:1)}},8551:function($,J,j){var E=j(34),B=String,W=TypeError;$.exports=function(O){if(E(O))return O;throw new W(B(O)+" is not an object")}},235:function($,J,j){var E=j(9213).forEach,B=j(4598)("forEach");$.exports=B?[].forEach:function(W){return E(this,W,arguments.length>1?arguments[1]:void 0)}},7916:function($,J,j){var E=j(6080),B=j(9565),W=j(8981),O=j(6319),ie=j(4209),U=j(3517),G=j(6198),K=j(4659),X=j(4527),se=j(81),te=j(851),fe=Array;$.exports=function(de){var me=W(de),q=U(this),R=arguments.length,re=R>1?arguments[1]:void 0,be=re!==void 0;be&&(re=E(re,R>2?arguments[2]:void 0));var ye,_e,xe,ge,Me,Be,Fe=te(me),Oe=0;if(!Fe||this===fe&&ie(Fe))for(ye=G(me),_e=q?new this(ye):fe(ye);ye>Oe;Oe++)Be=be?re(me[Oe],Oe):me[Oe],K(_e,Oe,Be);else for(_e=q?new this:[],Me=(ge=se(me,Fe)).next;!(xe=B(Me,ge)).done;Oe++)Be=be?O(ge,re,[xe.value,Oe],!0):xe.value,K(_e,Oe,Be);return X(_e,Oe),_e}},9617:function($,J,j){var E=j(5397),B=j(5610),W=j(6198),O=function(ie){return function(U,G,K){var X=E(U),se=W(X);if(se===0)return!ie&&-1;var te,fe=B(K,se);if(ie&&G!=G){for(;se>fe;)if((te=X[fe++])!=te)return!0}else for(;se>fe;fe++)if((ie||fe in X)&&X[fe]===G)return ie||fe||0;return!ie&&-1}};$.exports={includes:O(!0),indexOf:O(!1)}},9213:function($,J,j){var E=j(6080),B=j(7055),W=j(8981),O=j(6198),ie=j(1469),U=j(4659),G=function(K){var X=K===1,se=K===2,te=K===3,fe=K===4,de=K===6,me=K===7,q=K===5||de;return function(R,re,be){for(var ye,_e,xe=W(R),ge=B(xe),Me=O(ge),Be=E(re,be),Fe=0,Oe=0,Re=X?ie(R,Me):se||me?ie(R,0):void 0;Me>Fe;Fe++)if((q||Fe in ge)&&(_e=Be(ye=ge[Fe],Fe,xe),K))if(X)U(Re,Fe,_e);else if(_e)switch(K){case 3:return!0;case 5:return ye;case 6:return Fe;case 2:U(Re,Oe++,ye)}else switch(K){case 4:return!1;case 7:U(Re,Oe++,ye)}return de?-1:te||fe?fe:Re}};$.exports={forEach:G(0),map:G(1),filter:G(2),some:G(3),every:G(4),find:G(5),findIndex:G(6),filterReject:G(7)}},597:function($,J,j){var E=j(9039),B=j(8227),W=j(9519),O=B("species");$.exports=function(ie){return W>=51||!E((function(){var U=[];return(U.constructor={})[O]=function(){return{foo:1}},U[ie](Boolean).foo!==1}))}},4598:function($,J,j){var E=j(9039);$.exports=function(B,W){var O=[][B];return!!O&&E((function(){O.call(null,W||function(){return 1},1)}))}},926:function($,J,j){var E=j(9306),B=j(8981),W=j(7055),O=j(6198),ie=TypeError,U="Reduce of empty array with no initial value",G=function(K){return function(X,se,te,fe){var de=B(X),me=W(de),q=O(de);if(E(se),q===0&&te<2)throw new ie(U);var R=K?q-1:0,re=K?-1:1;if(te<2)for(;;){if(R in me){fe=me[R],R+=re;break}if(R+=re,K?R<0:q<=R)throw new ie(U)}for(;K?R>=0:q>R;R+=re)R in me&&(fe=se(fe,me[R],R,de));return fe}};$.exports={left:G(!1),right:G(!0)}},4527:function($,J,j){var E=j(3724),B=j(4376),W=TypeError,O=Object.getOwnPropertyDescriptor,ie=E&&!(function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(U){return U instanceof TypeError}})();$.exports=ie?function(U,G){if(B(U)&&!O(U,"length").writable)throw new W("Cannot set read only .length");return U.length=G}:function(U,G){return U.length=G}},7680:function($,J,j){var E=j(9504);$.exports=E([].slice)},4488:function($,J,j){var E=j(7680),B=Math.floor,W=function(O,ie){var U=O.length;if(U<8)for(var G,K,X=1;X<U;){for(K=X,G=O[X];K&&ie(O[K-1],G)>0;)O[K]=O[--K];K!==X++&&(O[K]=G)}else for(var se=B(U/2),te=W(E(O,0,se),ie),fe=W(E(O,se),ie),de=te.length,me=fe.length,q=0,R=0;q<de||R<me;)O[q+R]=q<de&&R<me?ie(te[q],fe[R])<=0?te[q++]:fe[R++]:q<de?te[q++]:fe[R++];return O};$.exports=W},7433:function($,J,j){var E=j(4376),B=j(3517),W=j(34),O=j(8227)("species"),ie=Array;$.exports=function(U){var G;return E(U)&&(G=U.constructor,(B(G)&&(G===ie||E(G.prototype))||W(G)&&(G=G[O])===null)&&(G=void 0)),G===void 0?ie:G}},1469:function($,J,j){var E=j(7433);$.exports=function(B,W){return new(E(B))(W===0?0:W)}},6319:function($,J,j){var E=j(8551),B=j(9539);$.exports=function(W,O,ie,U){try{return U?O(E(ie)[0],ie[1]):O(ie)}catch(G){B(W,"throw",G)}}},4428:function($,J,j){var E=j(8227)("iterator"),B=!1;try{var W=0,O={next:function(){return{done:!!W++}},return:function(){B=!0}};O[E]=function(){return this},Array.from(O,(function(){throw 2}))}catch{}$.exports=function(ie,U){try{if(!U&&!B)return!1}catch{return!1}var G=!1;try{var K={};K[E]=function(){return{next:function(){return{done:G=!0}}}},ie(K)}catch{}return G}},2195:function($,J,j){var E=j(9504),B=E({}.toString),W=E("".slice);$.exports=function(O){return W(B(O),8,-1)}},6955:function($,J,j){var E=j(2140),B=j(4901),W=j(2195),O=j(8227)("toStringTag"),ie=Object,U=W((function(){return arguments})())==="Arguments";$.exports=E?W:function(G){var K,X,se;return G===void 0?"Undefined":G===null?"Null":typeof(X=(function(te,fe){try{return te[fe]}catch{}})(K=ie(G),O))=="string"?X:U?W(K):(se=W(K))==="Object"&&B(K.callee)?"Arguments":se}},7740:function($,J,j){var E=j(9297),B=j(5031),W=j(7347),O=j(4913);$.exports=function(ie,U,G){for(var K=B(U),X=O.f,se=W.f,te=0;te<K.length;te++){var fe=K[te];E(ie,fe)||G&&E(G,fe)||X(ie,fe,se(U,fe))}}},1436:function($,J,j){var E=j(8227)("match");$.exports=function(B){var W=/./;try{"/./"[B](W)}catch{try{return W[E]=!1,"/./"[B](W)}catch{}}return!1}},2211:function($,J,j){var E=j(9039);$.exports=!E((function(){function B(){}return B.prototype.constructor=null,Object.getPrototypeOf(new B)!==B.prototype}))},2529:function($){$.exports=function(J,j){return{value:J,done:j}}},6699:function($,J,j){var E=j(3724),B=j(4913),W=j(6980);$.exports=E?function(O,ie,U){return B.f(O,ie,W(1,U))}:function(O,ie,U){return O[ie]=U,O}},6980:function($){$.exports=function(J,j){return{enumerable:!(1&J),configurable:!(2&J),writable:!(4&J),value:j}}},4659:function($,J,j){var E=j(3724),B=j(4913),W=j(6980);$.exports=function(O,ie,U){E?B.f(O,ie,W(0,U)):O[ie]=U}},3640:function($,J,j){var E=j(8551),B=j(4270),W=TypeError;$.exports=function(O){if(E(this),O==="string"||O==="default")O="string";else if(O!=="number")throw new W("Incorrect hint");return B(this,O)}},2106:function($,J,j){var E=j(283),B=j(4913);$.exports=function(W,O,ie){return ie.get&&E(ie.get,O,{getter:!0}),ie.set&&E(ie.set,O,{setter:!0}),B.f(W,O,ie)}},6840:function($,J,j){var E=j(4901),B=j(4913),W=j(283),O=j(9433);$.exports=function(ie,U,G,K){K||(K={});var X=K.enumerable,se=K.name!==void 0?K.name:U;if(E(G)&&W(G,se,K),K.global)X?ie[U]=G:O(U,G);else{try{K.unsafe?ie[U]&&(X=!0):delete ie[U]}catch{}X?ie[U]=G:B.f(ie,U,{value:G,enumerable:!1,configurable:!K.nonConfigurable,writable:!K.nonWritable})}return ie}},9433:function($,J,j){var E=j(4576),B=Object.defineProperty;$.exports=function(W,O){try{B(E,W,{value:O,configurable:!0,writable:!0})}catch{E[W]=O}return O}},4606:function($,J,j){var E=j(6823),B=TypeError;$.exports=function(W,O){if(!delete W[O])throw new B("Cannot delete property "+E(O)+" of "+E(W))}},3724:function($,J,j){var E=j(9039);$.exports=!E((function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}))},4055:function($,J,j){var E=j(4576),B=j(34),W=E.document,O=B(W)&&B(W.createElement);$.exports=function(ie){return O?W.createElement(ie):{}}},6837:function($){var J=TypeError;$.exports=function(j){if(j>9007199254740991)throw J("Maximum allowed index exceeded");return j}},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($,J,j){var E=j(4055)("span").classList,B=E&&E.constructor&&E.constructor.prototype;$.exports=B===Object.prototype?void 0:B},8727:function($){$.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},3709:function($,J,j){var E=j(2839).match(/firefox\/(\d+)/i);$.exports=!!E&&+E[1]},3763:function($,J,j){var E=j(2839);$.exports=/MSIE|Trident/.test(E)},6193:function($,J,j){var E=j(4215);$.exports=E==="NODE"},2839:function($,J,j){var E=j(4576).navigator,B=E&&E.userAgent;$.exports=B?String(B):""},9519:function($,J,j){var E,B,W=j(4576),O=j(2839),ie=W.process,U=W.Deno,G=ie&&ie.versions||U&&U.version,K=G&&G.v8;K&&(B=(E=K.split("."))[0]>0&&E[0]<4?1:+(E[0]+E[1])),!B&&O&&(!(E=O.match(/Edge\/(\d+)/))||E[1]>=74)&&(E=O.match(/Chrome\/(\d+)/))&&(B=+E[1]),$.exports=B},3607:function($,J,j){var E=j(2839).match(/AppleWebKit\/(\d+)\./);$.exports=!!E&&+E[1]},4215:function($,J,j){var E=j(4576),B=j(2839),W=j(2195),O=function(ie){return B.slice(0,ie.length)===ie};$.exports=O("Bun/")?"BUN":O("Cloudflare-Workers")?"CLOUDFLARE":O("Deno/")?"DENO":O("Node.js/")?"NODE":E.Bun&&typeof Bun.version=="string"?"BUN":E.Deno&&typeof Deno.version=="object"?"DENO":W(E.process)==="process"?"NODE":E.window&&E.document?"BROWSER":"REST"},6518:function($,J,j){var E=j(4576),B=j(7347).f,W=j(6699),O=j(6840),ie=j(9433),U=j(7740),G=j(2796);$.exports=function(K,X){var se,te,fe,de,me,q=K.target,R=K.global,re=K.stat;if(se=R?E:re?E[q]||ie(q,{}):E[q]&&E[q].prototype)for(te in X){if(de=X[te],fe=K.dontCallGetSet?(me=B(se,te))&&me.value:se[te],!G(R?te:q+(re?".":"#")+te,K.forced)&&fe!==void 0){if(typeof de==typeof fe)continue;U(de,fe)}(K.sham||fe&&fe.sham)&&W(de,"sham",!0),O(se,te,de,K)}}},9039:function($){$.exports=function(J){try{return!!J()}catch{return!0}}},9228:function($,J,j){j(7495);var E=j(9565),B=j(6840),W=j(7323),O=j(9039),ie=j(8227),U=j(6699),G=ie("species"),K=RegExp.prototype;$.exports=function(X,se,te,fe){var de=ie(X),me=!O((function(){var be={};return be[de]=function(){return 7},""[X](be)!==7})),q=me&&!O((function(){var be=!1,ye=/a/;if(X==="split"){var _e={};_e[G]=function(){return ye},(ye={constructor:_e,flags:""})[de]=/./[de]}return ye.exec=function(){return be=!0,null},ye[de](""),!be}));if(!me||!q||te){var R=/./[de],re=se(de,""[X],(function(be,ye,_e,xe,ge){var Me=ye.exec;return Me===W||Me===K.exec?me&&!ge?{done:!0,value:E(R,ye,_e,xe)}:{done:!0,value:E(be,_e,ye,xe)}:{done:!1}}));B(String.prototype,X,re[0]),B(K,de,re[1])}fe&&U(K[de],"sham",!0)}},8745:function($,J,j){var E=j(616),B=Function.prototype,W=B.apply,O=B.call;$.exports=typeof Reflect=="object"&&Reflect.apply||(E?O.bind(W):function(){return O.apply(W,arguments)})},6080:function($,J,j){var E=j(7476),B=j(9306),W=j(616),O=E(E.bind);$.exports=function(ie,U){return B(ie),U===void 0?ie:W?O(ie,U):function(){return ie.apply(U,arguments)}}},616:function($,J,j){var E=j(9039);$.exports=!E((function(){var B=(function(){}).bind();return typeof B!="function"||B.hasOwnProperty("prototype")}))},566:function($,J,j){var E=j(9504),B=j(9306),W=j(34),O=j(9297),ie=j(7680),U=j(616),G=Function,K=E([].concat),X=E([].join),se={};$.exports=U?G.bind:function(te){var fe=B(this),de=fe.prototype,me=ie(arguments,1),q=function(){var R=K(me,ie(arguments));return this instanceof q?(function(re,be,ye){if(!O(se,be)){for(var _e=[],xe=0;xe<be;xe++)_e[xe]="a["+xe+"]";se[be]=G("C,a","return new C("+X(_e,",")+")")}return se[be](re,ye)})(fe,R.length,R):fe.apply(te,R)};return W(de)&&(q.prototype=de),q}},9565:function($,J,j){var E=j(616),B=Function.prototype.call;$.exports=E?B.bind(B):function(){return B.apply(B,arguments)}},350:function($,J,j){var E=j(3724),B=j(9297),W=Function.prototype,O=E&&Object.getOwnPropertyDescriptor,ie=B(W,"name"),U=ie&&(function(){}).name==="something",G=ie&&(!E||E&&O(W,"name").configurable);$.exports={EXISTS:ie,PROPER:U,CONFIGURABLE:G}},6706:function($,J,j){var E=j(9504),B=j(9306);$.exports=function(W,O,ie){try{return E(B(Object.getOwnPropertyDescriptor(W,O)[ie]))}catch{}}},7476:function($,J,j){var E=j(2195),B=j(9504);$.exports=function(W){if(E(W)==="Function")return B(W)}},9504:function($,J,j){var E=j(616),B=Function.prototype,W=B.call,O=E&&B.bind.bind(W,W);$.exports=E?O:function(ie){return function(){return W.apply(ie,arguments)}}},7751:function($,J,j){var E=j(4576),B=j(4901);$.exports=function(W,O){return arguments.length<2?(ie=E[W],B(ie)?ie:void 0):E[W]&&E[W][O];var ie}},851:function($,J,j){var E=j(6955),B=j(5966),W=j(4117),O=j(6269),ie=j(8227)("iterator");$.exports=function(U){if(!W(U))return B(U,ie)||B(U,"@@iterator")||O[E(U)]}},81:function($,J,j){var E=j(9565),B=j(9306),W=j(8551),O=j(6823),ie=j(851),U=TypeError;$.exports=function(G,K){var X=arguments.length<2?ie(G):K;if(B(X))return W(E(X,G));throw new U(O(G)+" is not iterable")}},5966:function($,J,j){var E=j(9306),B=j(4117);$.exports=function(W,O){var ie=W[O];return B(ie)?void 0:E(ie)}},2478:function($,J,j){var E=j(9504),B=j(8981),W=Math.floor,O=E("".charAt),ie=E("".replace),U=E("".slice),G=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,K=/\$([$&'`]|\d{1,2})/g;$.exports=function(X,se,te,fe,de,me){var q=te+X.length,R=fe.length,re=K;return de!==void 0&&(de=B(de),re=G),ie(me,re,(function(be,ye){var _e;switch(O(ye,0)){case"$":return"$";case"&":return X;case"`":return U(se,0,te);case"'":return U(se,q);case"<":_e=de[U(ye,1,-1)];break;default:var xe=+ye;if(xe===0)return be;if(xe>R){var ge=W(xe/10);return ge===0?be:ge<=R?fe[ge-1]===void 0?O(ye,1):fe[ge-1]+O(ye,1):be}_e=fe[xe-1]}return _e===void 0?"":_e}))}},4576:function($,J,j){var E=function(B){return B&&B.Math===Math&&B};$.exports=E(typeof globalThis=="object"&&globalThis)||E(typeof window=="object"&&window)||E(typeof self=="object"&&self)||E(typeof j.g=="object"&&j.g)||E(typeof this=="object"&&this)||(function(){return this})()||Function("return this")()},9297:function($,J,j){var E=j(9504),B=j(8981),W=E({}.hasOwnProperty);$.exports=Object.hasOwn||function(O,ie){return W(B(O),ie)}},421:function($){$.exports={}},397:function($,J,j){var E=j(7751);$.exports=E("document","documentElement")},5917:function($,J,j){var E=j(3724),B=j(9039),W=j(4055);$.exports=!E&&!B((function(){return Object.defineProperty(W("div"),"a",{get:function(){return 7}}).a!==7}))},7055:function($,J,j){var E=j(9504),B=j(9039),W=j(2195),O=Object,ie=E("".split);$.exports=B((function(){return!O("z").propertyIsEnumerable(0)}))?function(U){return W(U)==="String"?ie(U,""):O(U)}:O},3167:function($,J,j){var E=j(4901),B=j(34),W=j(2967);$.exports=function(O,ie,U){var G,K;return W&&E(G=ie.constructor)&&G!==U&&B(K=G.prototype)&&K!==U.prototype&&W(O,K),O}},3706:function($,J,j){var E=j(9504),B=j(4901),W=j(7629),O=E(Function.toString);B(W.inspectSource)||(W.inspectSource=function(ie){return O(ie)}),$.exports=W.inspectSource},1181:function($,J,j){var E,B,W,O=j(8622),ie=j(4576),U=j(34),G=j(6699),K=j(9297),X=j(7629),se=j(6119),te=j(421),fe="Object already initialized",de=ie.TypeError,me=ie.WeakMap;if(O||X.state){var q=X.state||(X.state=new me);q.get=q.get,q.has=q.has,q.set=q.set,E=function(re,be){if(q.has(re))throw new de(fe);return be.facade=re,q.set(re,be),be},B=function(re){return q.get(re)||{}},W=function(re){return q.has(re)}}else{var R=se("state");te[R]=!0,E=function(re,be){if(K(re,R))throw new de(fe);return be.facade=re,G(re,R,be),be},B=function(re){return K(re,R)?re[R]:{}},W=function(re){return K(re,R)}}$.exports={set:E,get:B,has:W,enforce:function(re){return W(re)?B(re):E(re,{})},getterFor:function(re){return function(be){var ye;if(!U(be)||(ye=B(be)).type!==re)throw new de("Incompatible receiver, "+re+" required");return ye}}}},4209:function($,J,j){var E=j(8227),B=j(6269),W=E("iterator"),O=Array.prototype;$.exports=function(ie){return ie!==void 0&&(B.Array===ie||O[W]===ie)}},4376:function($,J,j){var E=j(2195);$.exports=Array.isArray||function(B){return E(B)==="Array"}},4901:function($){var J=typeof document=="object"&&document.all;$.exports=J===void 0&&J!==void 0?function(j){return typeof j=="function"||j===J}:function(j){return typeof j=="function"}},3517:function($,J,j){var E=j(9504),B=j(9039),W=j(4901),O=j(6955),ie=j(7751),U=j(3706),G=function(){},K=ie("Reflect","construct"),X=/^\s*(?:class|function)\b/,se=E(X.exec),te=!X.test(G),fe=function(me){if(!W(me))return!1;try{return K(G,[],me),!0}catch{return!1}},de=function(me){if(!W(me))return!1;switch(O(me)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return te||!!se(X,U(me))}catch{return!0}};de.sham=!0,$.exports=!K||B((function(){var me;return fe(fe.call)||!fe(Object)||!fe((function(){me=!0}))||me}))?de:fe},2796:function($,J,j){var E=j(9039),B=j(4901),W=/#|\.prototype\./,O=function(X,se){var te=U[ie(X)];return te===K||te!==G&&(B(se)?E(se):!!se)},ie=O.normalize=function(X){return String(X).replace(W,".").toLowerCase()},U=O.data={},G=O.NATIVE="N",K=O.POLYFILL="P";$.exports=O},2087:function($,J,j){var E=j(34),B=Math.floor;$.exports=Number.isInteger||function(W){return!E(W)&&isFinite(W)&&B(W)===W}},4117:function($){$.exports=function(J){return J==null}},34:function($,J,j){var E=j(4901);$.exports=function(B){return typeof B=="object"?B!==null:E(B)}},3925:function($,J,j){var E=j(34);$.exports=function(B){return E(B)||B===null}},6395:function($){$.exports=!1},5810:function($,J,j){var E=j(34),B=j(1181).get;$.exports=function(W){if(!E(W))return!1;var O=B(W);return!!O&&O.type==="RawJSON"}},788:function($,J,j){var E=j(34),B=j(2195),W=j(8227)("match");$.exports=function(O){var ie;return E(O)&&((ie=O[W])!==void 0?!!ie:B(O)==="RegExp")}},757:function($,J,j){var E=j(7751),B=j(4901),W=j(1625),O=j(7040),ie=Object;$.exports=O?function(U){return typeof U=="symbol"}:function(U){var G=E("Symbol");return B(G)&&W(G.prototype,ie(U))}},9539:function($,J,j){var E=j(9565),B=j(8551),W=j(5966);$.exports=function(O,ie,U){var G,K;B(O);try{if(!(G=W(O,"return"))){if(ie==="throw")throw U;return U}G=E(G,O)}catch(X){K=!0,G=X}if(ie==="throw")throw U;if(K)throw G;return B(G),U}},3994:function($,J,j){var E=j(7657).IteratorPrototype,B=j(2360),W=j(6980),O=j(687),ie=j(6269),U=function(){return this};$.exports=function(G,K,X,se){var te=K+" Iterator";return G.prototype=B(E,{next:W(+!se,X)}),O(G,te,!1,!0),ie[te]=U,G}},1088:function($,J,j){var E=j(6518),B=j(9565),W=j(6395),O=j(350),ie=j(4901),U=j(3994),G=j(2787),K=j(2967),X=j(687),se=j(6699),te=j(6840),fe=j(8227),de=j(6269),me=j(7657),q=O.PROPER,R=O.CONFIGURABLE,re=me.IteratorPrototype,be=me.BUGGY_SAFARI_ITERATORS,ye=fe("iterator"),_e="keys",xe="values",ge="entries",Me=function(){return this};$.exports=function(Be,Fe,Oe,Re,We,ze,st){U(Oe,Fe,Re);var Ee,it,Ce,Ze=function(tt){if(tt===We&&Qe)return Qe;if(!be&&tt&&tt in Ve)return Ve[tt];switch(tt){case _e:case xe:case ge:return function(){return new Oe(this,tt)}}return function(){return new Oe(this)}},Ie=Fe+" Iterator",ke=!1,Ve=Be.prototype,rt=Ve[ye]||Ve["@@iterator"]||We&&Ve[We],Qe=!be&&rt||Ze(We),Te=Fe==="Array"&&Ve.entries||rt;if(Te&&(Ee=G(Te.call(new Be)))!==Object.prototype&&Ee.next&&(W||G(Ee)===re||(K?K(Ee,re):ie(Ee[ye])||te(Ee,ye,Me)),X(Ee,Ie,!0,!0),W&&(de[Ie]=Me)),q&&We===xe&&rt&&rt.name!==xe&&(!W&&R?se(Ve,"name",xe):(ke=!0,Qe=function(){return B(rt,this)})),We)if(it={values:Ze(xe),keys:ze?Qe:Ze(_e),entries:Ze(ge)},st)for(Ce in it)(be||ke||!(Ce in Ve))&&te(Ve,Ce,it[Ce]);else E({target:Fe,proto:!0,forced:be||ke},it);return W&&!st||Ve[ye]===Qe||te(Ve,ye,Qe,{name:We}),de[Fe]=Qe,it}},7657:function($,J,j){var E,B,W,O=j(9039),ie=j(4901),U=j(34),G=j(2360),K=j(2787),X=j(6840),se=j(8227),te=j(6395),fe=se("iterator"),de=!1;[].keys&&("next"in(W=[].keys())?(B=K(K(W)))!==Object.prototype&&(E=B):de=!0),!U(E)||O((function(){var me={};return E[fe].call(me)!==me}))?E={}:te&&(E=G(E)),ie(E[fe])||X(E,fe,(function(){return this})),$.exports={IteratorPrototype:E,BUGGY_SAFARI_ITERATORS:de}},6269:function($){$.exports={}},6198:function($,J,j){var E=j(8014);$.exports=function(B){return E(B.length)}},283:function($,J,j){var E=j(9504),B=j(9039),W=j(4901),O=j(9297),ie=j(3724),U=j(350).CONFIGURABLE,G=j(3706),K=j(1181),X=K.enforce,se=K.get,te=String,fe=Object.defineProperty,de=E("".slice),me=E("".replace),q=E([].join),R=ie&&!B((function(){return fe((function(){}),"length",{value:8}).length!==8})),re=String(String).split("String"),be=$.exports=function(ye,_e,xe){de(te(_e),0,7)==="Symbol("&&(_e="["+me(te(_e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),xe&&xe.getter&&(_e="get "+_e),xe&&xe.setter&&(_e="set "+_e),(!O(ye,"name")||U&&ye.name!==_e)&&(ie?fe(ye,"name",{value:_e,configurable:!0}):ye.name=_e),R&&xe&&O(xe,"arity")&&ye.length!==xe.arity&&fe(ye,"length",{value:xe.arity});try{xe&&O(xe,"constructor")&&xe.constructor?ie&&fe(ye,"prototype",{writable:!1}):ye.prototype&&(ye.prototype=void 0)}catch{}var ge=X(ye);return O(ge,"source")||(ge.source=q(re,typeof _e=="string"?_e:"")),ye};Function.prototype.toString=be((function(){return W(this)&&se(this).source||G(this)}),"toString")},741:function($){var J=Math.ceil,j=Math.floor;$.exports=Math.trunc||function(E){var B=+E;return(B>0?j:J)(B)}},7819:function($,J,j){var E=j(9039);$.exports=!E((function(){var B="9007199254740993",W=JSON.rawJSON(B);return!JSON.isRawJSON(W)||JSON.stringify(W)!==B}))},5749:function($,J,j){var E=j(788),B=TypeError;$.exports=function(W){if(E(W))throw new B("The method doesn't accept regular expressions");return W}},4213:function($,J,j){var E=j(3724),B=j(9504),W=j(9565),O=j(9039),ie=j(1072),U=j(3717),G=j(8773),K=j(8981),X=j(7055),se=Object.assign,te=Object.defineProperty,fe=B([].concat);$.exports=!se||O((function(){if(E&&se({b:1},se(te({},"a",{enumerable:!0,get:function(){te(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var de={},me={},q=Symbol("assign detection"),R="abcdefghijklmnopqrst";return de[q]=7,R.split("").forEach((function(re){me[re]=re})),se({},de)[q]!==7||ie(se({},me)).join("")!==R}))?function(de,me){for(var q=K(de),R=arguments.length,re=1,be=U.f,ye=G.f;R>re;)for(var _e,xe=X(arguments[re++]),ge=be?fe(ie(xe),be(xe)):ie(xe),Me=ge.length,Be=0;Me>Be;)_e=ge[Be++],E&&!W(ye,xe,_e)||(q[_e]=xe[_e]);return q}:se},2360:function($,J,j){var E,B=j(8551),W=j(6801),O=j(8727),ie=j(421),U=j(397),G=j(4055),K=j(6119),X="prototype",se="script",te=K("IE_PROTO"),fe=function(){},de=function(R){return"<"+se+">"+R+"</"+se+">"},me=function(R){R.write(de("")),R.close();var re=R.parentWindow.Object;return R=null,re},q=function(){try{E=new ActiveXObject("htmlfile")}catch{}var R,re,be;q=typeof document<"u"?document.domain&&E?me(E):(re=G("iframe"),be="java"+se+":",re.style.display="none",U.appendChild(re),re.src=String(be),(R=re.contentWindow.document).open(),R.write(de("document.F=Object")),R.close(),R.F):me(E);for(var ye=O.length;ye--;)delete q[X][O[ye]];return q()};ie[te]=!0,$.exports=Object.create||function(R,re){var be;return R!==null?(fe[X]=B(R),be=new fe,fe[X]=null,be[te]=R):be=q(),re===void 0?be:W.f(be,re)}},6801:function($,J,j){var E=j(3724),B=j(8686),W=j(4913),O=j(8551),ie=j(5397),U=j(1072);J.f=E&&!B?Object.defineProperties:function(G,K){O(G);for(var X,se=ie(K),te=U(K),fe=te.length,de=0;fe>de;)W.f(G,X=te[de++],se[X]);return G}},4913:function($,J,j){var E=j(3724),B=j(5917),W=j(8686),O=j(8551),ie=j(6969),U=TypeError,G=Object.defineProperty,K=Object.getOwnPropertyDescriptor,X="enumerable",se="configurable",te="writable";J.f=E?W?function(fe,de,me){if(O(fe),de=ie(de),O(me),typeof fe=="function"&&de==="prototype"&&"value"in me&&te in me&&!me[te]){var q=K(fe,de);q&&q[te]&&(fe[de]=me.value,me={configurable:se in me?me[se]:q[se],enumerable:X in me?me[X]:q[X],writable:!1})}return G(fe,de,me)}:G:function(fe,de,me){if(O(fe),de=ie(de),O(me),B)try{return G(fe,de,me)}catch{}if("get"in me||"set"in me)throw new U("Accessors not supported");return"value"in me&&(fe[de]=me.value),fe}},7347:function($,J,j){var E=j(3724),B=j(9565),W=j(8773),O=j(6980),ie=j(5397),U=j(6969),G=j(9297),K=j(5917),X=Object.getOwnPropertyDescriptor;J.f=E?X:function(se,te){if(se=ie(se),te=U(te),K)try{return X(se,te)}catch{}if(G(se,te))return O(!B(W.f,se,te),se[te])}},298:function($,J,j){var E=j(2195),B=j(5397),W=j(8480).f,O=j(7680),ie=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];$.exports.f=function(U){return ie&&E(U)==="Window"?(function(G){try{return W(G)}catch{return O(ie)}})(U):W(B(U))}},8480:function($,J,j){var E=j(1828),B=j(8727).concat("length","prototype");J.f=Object.getOwnPropertyNames||function(W){return E(W,B)}},3717:function($,J){J.f=Object.getOwnPropertySymbols},2787:function($,J,j){var E=j(9297),B=j(4901),W=j(8981),O=j(6119),ie=j(2211),U=O("IE_PROTO"),G=Object,K=G.prototype;$.exports=ie?G.getPrototypeOf:function(X){var se=W(X);if(E(se,U))return se[U];var te=se.constructor;return B(te)&&se instanceof te?te.prototype:se instanceof G?K:null}},1625:function($,J,j){var E=j(9504);$.exports=E({}.isPrototypeOf)},1828:function($,J,j){var E=j(9504),B=j(9297),W=j(5397),O=j(9617).indexOf,ie=j(421),U=E([].push);$.exports=function(G,K){var X,se=W(G),te=0,fe=[];for(X in se)!B(ie,X)&&B(se,X)&&U(fe,X);for(;K.length>te;)B(se,X=K[te++])&&(~O(fe,X)||U(fe,X));return fe}},1072:function($,J,j){var E=j(1828),B=j(8727);$.exports=Object.keys||function(W){return E(W,B)}},8773:function($,J){var j={}.propertyIsEnumerable,E=Object.getOwnPropertyDescriptor,B=E&&!j.call({1:2},1);J.f=B?function(W){var O=E(this,W);return!!O&&O.enumerable}:j},2551:function($,J,j){var E=j(6395),B=j(4576),W=j(9039),O=j(3607);$.exports=E||!W((function(){if(!(O&&O<535)){var ie=Math.random();__defineSetter__.call(null,ie,(function(){})),delete B[ie]}}))},2967:function($,J,j){var E=j(6706),B=j(34),W=j(7750),O=j(3506);$.exports=Object.setPrototypeOf||("__proto__"in{}?(function(){var ie,U=!1,G={};try{(ie=E(Object.prototype,"__proto__","set"))(G,[]),U=G instanceof Array}catch{}return function(K,X){return W(K),O(X),B(K)&&(U?ie(K,X):K.__proto__=X),K}})():void 0)},3179:function($,J,j){var E=j(2140),B=j(6955);$.exports=E?{}.toString:function(){return"[object "+B(this)+"]"}},4270:function($,J,j){var E=j(9565),B=j(4901),W=j(34),O=TypeError;$.exports=function(ie,U){var G,K;if(U==="string"&&B(G=ie.toString)&&!W(K=E(G,ie))||B(G=ie.valueOf)&&!W(K=E(G,ie))||U!=="string"&&B(G=ie.toString)&&!W(K=E(G,ie)))return K;throw new O("Can't convert object to primitive value")}},5031:function($,J,j){var E=j(7751),B=j(9504),W=j(8480),O=j(3717),ie=j(8551),U=B([].concat);$.exports=E("Reflect","ownKeys")||function(G){var K=W.f(ie(G)),X=O.f;return X?U(K,X(G)):K}},8235:function($,J,j){var E=j(9504),B=j(9297),W=SyntaxError,O=parseInt,ie=String.fromCharCode,U=E("".charAt),G=E("".slice),K=E(/./.exec),X={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
  8350. `,"\\r":"\r","\\t":" "},se=/^[\da-f]{4}$/i,te=/^[\u0000-\u001F]$/;$.exports=function(fe,de){for(var me=!0,q="";de<fe.length;){var R=U(fe,de);if(R==="\\"){var re=G(fe,de,de+2);if(B(X,re))q+=X[re],de+=2;else{if(re!=="\\u")throw new W('Unknown escape sequence: "'+re+'"');var be=G(fe,de+=2,de+4);if(!K(se,be))throw new W("Bad Unicode escape at: "+de);q+=ie(O(be,16)),de+=4}}else{if(R==='"'){me=!1,de++;break}if(K(te,R))throw new W("Bad control character in string literal at: "+de);q+=R,de++}}if(me)throw new W("Unterminated string at: "+de);return{value:q,end:de}}},9167:function($,J,j){var E=j(4576);$.exports=E},1056:function($,J,j){var E=j(4913).f;$.exports=function(B,W,O){O in B||E(B,O,{configurable:!0,get:function(){return W[O]},set:function(ie){W[O]=ie}})}},6682:function($,J,j){var E=j(9565),B=j(8551),W=j(4901),O=j(2195),ie=j(7323),U=TypeError;$.exports=function(G,K){var X=G.exec;if(W(X)){var se=E(X,G,K);return se!==null&&B(se),se}if(O(G)==="RegExp")return E(ie,G,K);throw new U("RegExp#exec called on incompatible receiver")}},7323:function($,J,j){var E,B,W=j(9565),O=j(9504),ie=j(655),U=j(7979),G=j(8429),K=j(5745),X=j(2360),se=j(1181).get,te=j(3635),fe=j(8814),de=K("native-string-replace",String.prototype.replace),me=RegExp.prototype.exec,q=me,R=O("".charAt),re=O("".indexOf),be=O("".replace),ye=O("".slice),_e=(B=/b*/g,W(me,E=/a/,"a"),W(me,B,"a"),E.lastIndex!==0||B.lastIndex!==0),xe=G.BROKEN_CARET,ge=/()??/.exec("")[1]!==void 0;(_e||ge||xe||te||fe)&&(q=function(Me){var Be,Fe,Oe,Re,We,ze,st,Ee=this,it=se(Ee),Ce=ie(Me),Ze=it.raw;if(Ze)return Ze.lastIndex=Ee.lastIndex,Be=W(q,Ze,Ce),Ee.lastIndex=Ze.lastIndex,Be;var Ie=it.groups,ke=xe&&Ee.sticky,Ve=W(U,Ee),rt=Ee.source,Qe=0,Te=Ce;if(ke&&(Ve=be(Ve,"y",""),re(Ve,"g")===-1&&(Ve+="g"),Te=ye(Ce,Ee.lastIndex),Ee.lastIndex>0&&(!Ee.multiline||Ee.multiline&&R(Ce,Ee.lastIndex-1)!==`
  8351. `)&&(rt="(?: "+rt+")",Te=" "+Te,Qe++),Fe=new RegExp("^(?:"+rt+")",Ve)),ge&&(Fe=new RegExp("^"+rt+"$(?!\\s)",Ve)),_e&&(Oe=Ee.lastIndex),Re=W(me,ke?Fe:Ee,Te),ke?Re?(Re.input=ye(Re.input,Qe),Re[0]=ye(Re[0],Qe),Re.index=Ee.lastIndex,Ee.lastIndex+=Re[0].length):Ee.lastIndex=0:_e&&Re&&(Ee.lastIndex=Ee.global?Re.index+Re[0].length:Oe),ge&&Re&&Re.length>1&&W(de,Re[0],Fe,(function(){for(We=1;We<arguments.length-2;We++)arguments[We]===void 0&&(Re[We]=void 0)})),Re&&Ie)for(Re.groups=ze=X(null),We=0;We<Ie.length;We++)ze[(st=Ie[We])[0]]=Re[st[1]];return Re}),$.exports=q},5213:function($,J,j){var E=j(4576),B=j(9039),W=E.RegExp,O=!B((function(){var ie=!0;try{W(".","d")}catch{ie=!1}var U={},G="",K=ie?"dgimsy":"gimsy",X=function(fe,de){Object.defineProperty(U,fe,{get:function(){return G+=de,!0}})},se={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var te in ie&&(se.hasIndices="d"),se)X(te,se[te]);return Object.getOwnPropertyDescriptor(W.prototype,"flags").get.call(U)!==K||G!==K}));$.exports={correct:O}},7979:function($,J,j){var E=j(8551);$.exports=function(){var B=E(this),W="";return B.hasIndices&&(W+="d"),B.global&&(W+="g"),B.ignoreCase&&(W+="i"),B.multiline&&(W+="m"),B.dotAll&&(W+="s"),B.unicode&&(W+="u"),B.unicodeSets&&(W+="v"),B.sticky&&(W+="y"),W}},1034:function($,J,j){var E=j(9565),B=j(9297),W=j(1625),O=j(5213),ie=j(7979),U=RegExp.prototype;$.exports=O.correct?function(G){return G.flags}:function(G){return O.correct||!W(U,G)||B(G,"flags")?G.flags:E(ie,G)}},8429:function($,J,j){var E=j(9039),B=j(4576).RegExp,W=E((function(){var U=B("a","y");return U.lastIndex=2,U.exec("abcd")!==null})),O=W||E((function(){return!B("a","y").sticky})),ie=W||E((function(){var U=B("^r","gy");return U.lastIndex=2,U.exec("str")!==null}));$.exports={BROKEN_CARET:ie,MISSED_STICKY:O,UNSUPPORTED_Y:W}},3635:function($,J,j){var E=j(9039),B=j(4576).RegExp;$.exports=E((function(){var W=B(".","s");return!(W.dotAll&&W.test(`
  8352. `)&&W.flags==="s")}))},8814:function($,J,j){var E=j(9039),B=j(4576).RegExp;$.exports=E((function(){var W=B("(?<a>b)","g");return W.exec("b").groups.a!=="b"||"b".replace(W,"$<a>c")!=="bc"}))},7750:function($,J,j){var E=j(4117),B=TypeError;$.exports=function(W){if(E(W))throw new B("Can't call method on "+W);return W}},7633:function($,J,j){var E=j(7751),B=j(2106),W=j(8227),O=j(3724),ie=W("species");$.exports=function(U){var G=E(U);O&&G&&!G[ie]&&B(G,ie,{configurable:!0,get:function(){return this}})}},687:function($,J,j){var E=j(4913).f,B=j(9297),W=j(8227)("toStringTag");$.exports=function(O,ie,U){O&&!U&&(O=O.prototype),O&&!B(O,W)&&E(O,W,{configurable:!0,value:ie})}},6119:function($,J,j){var E=j(5745),B=j(3392),W=E("keys");$.exports=function(O){return W[O]||(W[O]=B(O))}},7629:function($,J,j){var E=j(6395),B=j(4576),W=j(9433),O="__core-js_shared__",ie=$.exports=B[O]||W(O,{});(ie.versions||(ie.versions=[])).push({version:"3.48.0",mode:E?"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($,J,j){var E=j(7629);$.exports=function(B,W){return E[B]||(E[B]=W||{})}},2293:function($,J,j){var E=j(8551),B=j(5548),W=j(4117),O=j(8227)("species");$.exports=function(ie,U){var G,K=E(ie).constructor;return K===void 0||W(G=E(K)[O])?U:B(G)}},8183:function($,J,j){var E=j(9504),B=j(1291),W=j(655),O=j(7750),ie=E("".charAt),U=E("".charCodeAt),G=E("".slice),K=function(X){return function(se,te){var fe,de,me=W(O(se)),q=B(te),R=me.length;return q<0||q>=R?X?"":void 0:(fe=U(me,q))<55296||fe>56319||q+1===R||(de=U(me,q+1))<56320||de>57343?X?ie(me,q):fe:X?G(me,q,q+2):de-56320+(fe-55296<<10)+65536}};$.exports={codeAt:K(!1),charAt:K(!0)}},706:function($,J,j){var E=j(350).PROPER,B=j(9039),W=j(7452);$.exports=function(O){return B((function(){return!!W[O]()||"​…᠎"[O]()!=="​…᠎"||E&&W[O].name!==O}))}},3802:function($,J,j){var E=j(9504),B=j(7750),W=j(655),O=j(7452),ie=E("".replace),U=RegExp("^["+O+"]+"),G=RegExp("(^|[^"+O+"])["+O+"]+$"),K=function(X){return function(se){var te=W(B(se));return 1&X&&(te=ie(te,U,"")),2&X&&(te=ie(te,G,"$1")),te}};$.exports={start:K(1),end:K(2),trim:K(3)}},4495:function($,J,j){var E=j(9519),B=j(9039),W=j(4576).String;$.exports=!!Object.getOwnPropertySymbols&&!B((function(){var O=Symbol("symbol detection");return!W(O)||!(Object(O)instanceof Symbol)||!Symbol.sham&&E&&E<41}))},8242:function($,J,j){var E=j(9565),B=j(7751),W=j(8227),O=j(6840);$.exports=function(){var ie=B("Symbol"),U=ie&&ie.prototype,G=U&&U.valueOf,K=W("toPrimitive");U&&!U[K]&&O(U,K,(function(X){return E(G,this)}),{arity:1})}},1296:function($,J,j){var E=j(4495);$.exports=E&&!!Symbol.for&&!!Symbol.keyFor},1240:function($,J,j){var E=j(9504);$.exports=E(1.1.valueOf)},5610:function($,J,j){var E=j(1291),B=Math.max,W=Math.min;$.exports=function(O,ie){var U=E(O);return U<0?B(U+ie,0):W(U,ie)}},5397:function($,J,j){var E=j(7055),B=j(7750);$.exports=function(W){return E(B(W))}},1291:function($,J,j){var E=j(741);$.exports=function(B){var W=+B;return W!=W||W===0?0:E(W)}},8014:function($,J,j){var E=j(1291),B=Math.min;$.exports=function(W){var O=E(W);return O>0?B(O,9007199254740991):0}},8981:function($,J,j){var E=j(7750),B=Object;$.exports=function(W){return B(E(W))}},2777:function($,J,j){var E=j(9565),B=j(34),W=j(757),O=j(5966),ie=j(4270),U=j(8227),G=TypeError,K=U("toPrimitive");$.exports=function(X,se){if(!B(X)||W(X))return X;var te,fe=O(X,K);if(fe){if(se===void 0&&(se="default"),te=E(fe,X,se),!B(te)||W(te))return te;throw new G("Can't convert object to primitive value")}return se===void 0&&(se="number"),ie(X,se)}},6969:function($,J,j){var E=j(2777),B=j(757);$.exports=function(W){var O=E(W,"string");return B(O)?O:O+""}},2140:function($,J,j){var E={};E[j(8227)("toStringTag")]="z",$.exports=String(E)==="[object z]"},655:function($,J,j){var E=j(6955),B=String;$.exports=function(W){if(E(W)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return B(W)}},6823:function($){var J=String;$.exports=function(j){try{return J(j)}catch{return"Object"}}},3392:function($,J,j){var E=j(9504),B=0,W=Math.random(),O=E(1.1.toString);$.exports=function(ie){return"Symbol("+(ie===void 0?"":ie)+")_"+O(++B+W,36)}},7040:function($,J,j){var E=j(4495);$.exports=E&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},8686:function($,J,j){var E=j(3724),B=j(9039);$.exports=E&&B((function(){return Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype!==42}))},8622:function($,J,j){var E=j(4576),B=j(4901),W=E.WeakMap;$.exports=B(W)&&/native code/.test(String(W))},511:function($,J,j){var E=j(9167),B=j(9297),W=j(1951),O=j(4913).f;$.exports=function(ie){var U=E.Symbol||(E.Symbol={});B(U,ie)||O(U,ie,{value:W.f(ie)})}},1951:function($,J,j){var E=j(8227);J.f=E},8227:function($,J,j){var E=j(4576),B=j(5745),W=j(9297),O=j(3392),ie=j(4495),U=j(7040),G=E.Symbol,K=B("wks"),X=U?G.for||G:G&&G.withoutSetter||O;$.exports=function(se){return W(K,se)||(K[se]=ie&&W(G,se)?G[se]:X("Symbol."+se)),K[se]}},7452:function($){$.exports=`
  8353. \v\f\r                 \u2028\u2029\uFEFF`},8706:function($,J,j){var E=j(6518),B=j(9039),W=j(4376),O=j(34),ie=j(8981),U=j(6198),G=j(6837),K=j(4659),X=j(4527),se=j(1469),te=j(597),fe=j(8227),de=j(9519),me=fe("isConcatSpreadable"),q=de>=51||!B((function(){var re=[];return re[me]=!1,re.concat()[0]!==re})),R=function(re){if(!O(re))return!1;var be=re[me];return be!==void 0?!!be:W(re)};E({target:"Array",proto:!0,arity:1,forced:!q||!te("concat")},{concat:function(re){var be,ye,_e,xe,ge,Me=ie(this),Be=se(Me,0),Fe=0;for(be=-1,_e=arguments.length;be<_e;be++)if(R(ge=be===-1?Me:arguments[be]))for(xe=U(ge),G(Fe+xe),ye=0;ye<xe;ye++,Fe++)ye in ge&&K(Be,Fe,ge[ye]);else G(Fe+1),K(Be,Fe++,ge);return X(Be,Fe),Be}})},2008:function($,J,j){var E=j(6518),B=j(9213).filter;E({target:"Array",proto:!0,forced:!j(597)("filter")},{filter:function(W){return B(this,W,arguments.length>1?arguments[1]:void 0)}})},3418:function($,J,j){var E=j(6518),B=j(7916);E({target:"Array",stat:!0,forced:!j(4428)((function(W){Array.from(W)}))},{from:B})},4423:function($,J,j){var E=j(6518),B=j(9617).includes,W=j(9039),O=j(6469);E({target:"Array",proto:!0,forced:W((function(){return!Array(1).includes()}))},{includes:function(ie){return B(this,ie,arguments.length>1?arguments[1]:void 0)}}),O("includes")},5276:function($,J,j){var E=j(6518),B=j(7476),W=j(9617).indexOf,O=j(4598),ie=B([].indexOf),U=!!ie&&1/ie([1],1,-0)<0;E({target:"Array",proto:!0,forced:U||!O("indexOf")},{indexOf:function(G){var K=arguments.length>1?arguments[1]:void 0;return U?ie(this,G,K)||0:W(this,G,K)}})},3792:function($,J,j){var E=j(5397),B=j(6469),W=j(6269),O=j(1181),ie=j(4913).f,U=j(1088),G=j(2529),K=j(6395),X=j(3724),se="Array Iterator",te=O.set,fe=O.getterFor(se);$.exports=U(Array,"Array",(function(me,q){te(this,{type:se,target:E(me),index:0,kind:q})}),(function(){var me=fe(this),q=me.target,R=me.index++;if(!q||R>=q.length)return me.target=null,G(void 0,!0);switch(me.kind){case"keys":return G(R,!1);case"values":return G(q[R],!1)}return G([R,q[R]],!1)}),"values");var de=W.Arguments=W.Array;if(B("keys"),B("values"),B("entries"),!K&&X&&de.name!=="values")try{ie(de,"name",{value:"values"})}catch{}},8598:function($,J,j){var E=j(6518),B=j(9504),W=j(7055),O=j(5397),ie=j(4598),U=B([].join);E({target:"Array",proto:!0,forced:W!==Object||!ie("join",",")},{join:function(G){return U(O(this),G===void 0?",":G)}})},2062:function($,J,j){var E=j(6518),B=j(9213).map;E({target:"Array",proto:!0,forced:!j(597)("map")},{map:function(W){return B(this,W,arguments.length>1?arguments[1]:void 0)}})},2712:function($,J,j){var E=j(6518),B=j(926).left,W=j(4598),O=j(9519);E({target:"Array",proto:!0,forced:!j(6193)&&O>79&&O<83||!W("reduce")},{reduce:function(ie){var U=arguments.length;return B(this,ie,U,U>1?arguments[1]:void 0)}})},4782:function($,J,j){var E=j(6518),B=j(4376),W=j(3517),O=j(34),ie=j(5610),U=j(6198),G=j(5397),K=j(4659),X=j(4527),se=j(8227),te=j(597),fe=j(7680),de=te("slice"),me=se("species"),q=Array,R=Math.max;E({target:"Array",proto:!0,forced:!de},{slice:function(re,be){var ye,_e,xe,ge=G(this),Me=U(ge),Be=ie(re,Me),Fe=ie(be===void 0?Me:be,Me);if(B(ge)&&(ye=ge.constructor,(W(ye)&&(ye===q||B(ye.prototype))||O(ye)&&(ye=ye[me])===null)&&(ye=void 0),ye===q||ye===void 0))return fe(ge,Be,Fe);for(_e=new(ye===void 0?q:ye)(R(Fe-Be,0)),xe=0;Be<Fe;Be++,xe++)Be in ge&&K(_e,xe,ge[Be]);return X(_e,xe),_e}})},6910:function($,J,j){var E=j(6518),B=j(9504),W=j(9306),O=j(8981),ie=j(6198),U=j(4606),G=j(655),K=j(9039),X=j(4488),se=j(4598),te=j(3709),fe=j(3763),de=j(9519),me=j(3607),q=[],R=B(q.sort),re=B(q.push),be=K((function(){q.sort(void 0)})),ye=K((function(){q.sort(null)})),_e=se("sort"),xe=!K((function(){if(de)return de<70;if(!(te&&te>3)){if(fe)return!0;if(me)return me<603;var ge,Me,Be,Fe,Oe="";for(ge=65;ge<76;ge++){switch(Me=String.fromCharCode(ge),ge){case 66:case 69:case 70:case 72:Be=3;break;case 68:case 71:Be=4;break;default:Be=2}for(Fe=0;Fe<47;Fe++)q.push({k:Me+Fe,v:Be})}for(q.sort((function(Re,We){return We.v-Re.v})),Fe=0;Fe<q.length;Fe++)Me=q[Fe].k.charAt(0),Oe.charAt(Oe.length-1)!==Me&&(Oe+=Me);return Oe!=="DGBEFHACIJK"}}));E({target:"Array",proto:!0,forced:be||!ye||!_e||!xe},{sort:function(ge){ge!==void 0&&W(ge);var Me=O(this);if(xe)return ge===void 0?R(Me):R(Me,ge);var Be,Fe,Oe=[],Re=ie(Me);for(Fe=0;Fe<Re;Fe++)Fe in Me&&re(Oe,Me[Fe]);for(X(Oe,(function(We){return function(ze,st){return st===void 0?-1:ze===void 0?1:We!==void 0?+We(ze,st)||0:G(ze)>G(st)?1:-1}})(ge)),Be=ie(Oe),Fe=0;Fe<Be;)Me[Fe]=Oe[Fe++];for(;Fe<Re;)U(Me,Fe++);return Me}})},4554:function($,J,j){var E=j(6518),B=j(8981),W=j(5610),O=j(1291),ie=j(6198),U=j(4527),G=j(6837),K=j(1469),X=j(4659),se=j(4606),te=j(597)("splice"),fe=Math.max,de=Math.min;E({target:"Array",proto:!0,forced:!te},{splice:function(me,q){var R,re,be,ye,_e,xe,ge=B(this),Me=ie(ge),Be=W(me,Me),Fe=arguments.length;for(Fe===0?R=re=0:Fe===1?(R=0,re=Me-Be):(R=Fe-2,re=de(fe(O(q),0),Me-Be)),G(Me+R-re),be=K(ge,re),ye=0;ye<re;ye++)(_e=Be+ye)in ge&&X(be,ye,ge[_e]);if(U(be,re),R<re){for(ye=Be;ye<Me-re;ye++)xe=ye+R,(_e=ye+re)in ge?ge[xe]=ge[_e]:se(ge,xe);for(ye=Me;ye>Me-re+R;ye--)se(ge,ye-1)}else if(R>re)for(ye=Me-re;ye>Be;ye--)xe=ye+R-1,(_e=ye+re-1)in ge?ge[xe]=ge[_e]:se(ge,xe);for(ye=0;ye<R;ye++)ge[ye+Be]=arguments[ye+2];return U(ge,Me-re+R),be}})},739:function($,J,j){var E=j(6518),B=j(9039),W=j(8981),O=j(2777);E({target:"Date",proto:!0,arity:1,forced:B((function(){return new Date(NaN).toJSON()!==null||Date.prototype.toJSON.call({toISOString:function(){return 1}})!==1}))},{toJSON:function(ie){var U=W(this),G=O(U,"number");return typeof G!="number"||isFinite(G)?U.toISOString():null}})},9572:function($,J,j){var E=j(9297),B=j(6840),W=j(3640),O=j(8227)("toPrimitive"),ie=Date.prototype;E(ie,O)||B(ie,O,W)},2010:function($,J,j){var E=j(3724),B=j(350).EXISTS,W=j(9504),O=j(2106),ie=Function.prototype,U=W(ie.toString),G=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,K=W(G.exec);E&&!B&&O(ie,"name",{configurable:!0,get:function(){try{return K(G,U(this))[1]}catch{return""}}})},3110:function($,J,j){var E=j(6518),B=j(7751),W=j(8745),O=j(9565),ie=j(9504),U=j(9039),G=j(4376),K=j(4901),X=j(5810),se=j(757),te=j(2195),fe=j(655),de=j(7680),me=j(8235),q=j(3392),R=j(4495),re=j(7819),be=String,ye=B("JSON","stringify"),_e=ie(/./.exec),xe=ie("".charAt),ge=ie("".charCodeAt),Me=ie("".replace),Be=ie("".slice),Fe=ie([].push),Oe=ie(1.1.toString),Re=/[\uD800-\uDFFF]/g,We=/^[\uD800-\uDBFF]$/,ze=/^[\uDC00-\uDFFF]$/,st=q(),Ee=st.length,it=!R||U((function(){var Ve=B("Symbol")("stringify detection");return ye([Ve])!=="[null]"||ye({a:Ve})!=="{}"||ye(Object(Ve))!=="{}"})),Ce=U((function(){return ye("\uDF06\uD834")!=='"\\udf06\\ud834"'||ye("\uDEAD")!=='"\\udead"'})),Ze=it?function(Ve,rt){var Qe=de(arguments),Te=ke(rt);if(K(Te)||Ve!==void 0&&!se(Ve))return Qe[1]=function(tt,ot){if(K(Te)&&(ot=O(Te,this,be(tt),ot)),!se(ot))return ot},W(ye,null,Qe)}:ye,Ie=function(Ve,rt,Qe){var Te=xe(Qe,rt-1),tt=xe(Qe,rt+1);return _e(We,Ve)&&!_e(ze,tt)||_e(ze,Ve)&&!_e(We,Te)?"\\u"+Oe(ge(Ve,0),16):Ve},ke=function(Ve){if(K(Ve))return Ve;if(G(Ve)){for(var rt=Ve.length,Qe=[],Te=0;Te<rt;Te++){var tt=Ve[Te];typeof tt=="string"?Fe(Qe,tt):typeof tt!="number"&&te(tt)!=="Number"&&te(tt)!=="String"||Fe(Qe,fe(tt))}var ot=Qe.length,Tt=!0;return function(Ut,bt){if(Tt)return Tt=!1,bt;if(G(this))return bt;for(var Wt=0;Wt<ot;Wt++)if(Qe[Wt]===Ut)return bt}}};ye&&E({target:"JSON",stat:!0,arity:3,forced:it||Ce||!re},{stringify:function(Ve,rt,Qe){var Te=ke(rt),tt=[],ot=Ze(Ve,(function(cn,ct){var kt=K(Te)?O(Te,this,be(cn),ct):ct;return!re&&X(kt)?st+(Fe(tt,kt.rawJSON)-1):kt}),Qe);if(typeof ot!="string"||(Ce&&(ot=Me(ot,Re,Ie)),re))return ot;for(var Tt="",Ut=ot.length,bt=0;bt<Ut;bt++){var Wt=xe(ot,bt);if(Wt==='"'){var Zt=me(ot,++bt).end-1,ln=Be(ot,bt,Zt);Tt+=Be(ln,0,Ee)===st?tt[Be(ln,Ee)]:'"'+ln+'"',bt=Zt}else Tt+=Wt}return Tt}})},2892:function($,J,j){var E=j(6518),B=j(6395),W=j(3724),O=j(4576),ie=j(9167),U=j(9504),G=j(2796),K=j(9297),X=j(3167),se=j(1625),te=j(757),fe=j(2777),de=j(9039),me=j(8480).f,q=j(7347).f,R=j(4913).f,re=j(1240),be=j(3802).trim,ye="Number",_e=O[ye],xe=ie[ye],ge=_e.prototype,Me=O.TypeError,Be=U("".slice),Fe=U("".charCodeAt),Oe=function(st){var Ee,it,Ce,Ze,Ie,ke,Ve,rt,Qe=fe(st,"number");if(te(Qe))throw new Me("Cannot convert a Symbol value to a number");if(typeof Qe=="string"&&Qe.length>2){if(Qe=be(Qe),(Ee=Fe(Qe,0))===43||Ee===45){if((it=Fe(Qe,2))===88||it===120)return NaN}else if(Ee===48){switch(Fe(Qe,1)){case 66:case 98:Ce=2,Ze=49;break;case 79:case 111:Ce=8,Ze=55;break;default:return+Qe}for(ke=(Ie=Be(Qe,2)).length,Ve=0;Ve<ke;Ve++)if((rt=Fe(Ie,Ve))<48||rt>Ze)return NaN;return parseInt(Ie,Ce)}}return+Qe},Re=G(ye,!_e(" 0o1")||!_e("0b1")||_e("+0x1")),We=function(st){var Ee,it=arguments.length<1?0:_e((function(Ce){var Ze=fe(Ce,"number");return typeof Ze=="bigint"?Ze:Oe(Ze)})(st));return se(ge,Ee=this)&&de((function(){re(Ee)}))?X(Object(it),this,We):it};We.prototype=ge,Re&&!B&&(ge.constructor=We),E({global:!0,constructor:!0,wrap:!0,forced:Re},{Number:We});var ze=function(st,Ee){for(var it,Ce=W?me(Ee):"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(","),Ze=0;Ce.length>Ze;Ze++)K(Ee,it=Ce[Ze])&&!K(st,it)&&R(st,it,q(Ee,it))};B&&xe&&ze(ie[ye],xe),(Re||B)&&ze(ie[ye],_e)},2637:function($,J,j){j(6518)({target:"Number",stat:!0},{isInteger:j(2087)})},9085:function($,J,j){var E=j(6518),B=j(4213);E({target:"Object",stat:!0,arity:2,forced:Object.assign!==B},{assign:B})},7427:function($,J,j){var E=j(6518),B=j(3724),W=j(2551),O=j(9306),ie=j(8981),U=j(4913);B&&E({target:"Object",proto:!0,forced:W},{__defineGetter__:function(G,K){U.f(ie(this),G,{get:O(K),enumerable:!0,configurable:!0})}})},3851:function($,J,j){var E=j(6518),B=j(9039),W=j(5397),O=j(7347).f,ie=j(3724);E({target:"Object",stat:!0,forced:!ie||B((function(){O(1)})),sham:!ie},{getOwnPropertyDescriptor:function(U,G){return O(W(U),G)}})},1278:function($,J,j){var E=j(6518),B=j(3724),W=j(5031),O=j(5397),ie=j(7347),U=j(4659);E({target:"Object",stat:!0,sham:!B},{getOwnPropertyDescriptors:function(G){for(var K,X,se=O(G),te=ie.f,fe=W(se),de={},me=0;fe.length>me;)(X=te(se,K=fe[me++]))!==void 0&&U(de,K,X);return de}})},1480:function($,J,j){var E=j(6518),B=j(9039),W=j(298).f;E({target:"Object",stat:!0,forced:B((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:W})},9773:function($,J,j){var E=j(6518),B=j(4495),W=j(9039),O=j(3717),ie=j(8981);E({target:"Object",stat:!0,forced:!B||W((function(){O.f(1)}))},{getOwnPropertySymbols:function(U){var G=O.f;return G?G(ie(U)):[]}})},9432:function($,J,j){var E=j(6518),B=j(8981),W=j(1072);E({target:"Object",stat:!0,forced:j(9039)((function(){W(1)}))},{keys:function(O){return W(B(O))}})},6099:function($,J,j){var E=j(2140),B=j(6840),W=j(3179);E||B(Object.prototype,"toString",W,{unsafe:!0})},825:function($,J,j){var E=j(6518),B=j(7751),W=j(8745),O=j(566),ie=j(5548),U=j(8551),G=j(34),K=j(2360),X=j(9039),se=B("Reflect","construct"),te=Object.prototype,fe=[].push,de=X((function(){function R(){}return!(se((function(){}),[],R)instanceof R)})),me=!X((function(){se((function(){}))})),q=de||me;E({target:"Reflect",stat:!0,forced:q,sham:q},{construct:function(R,re){ie(R),U(re);var be=arguments.length<3?R:ie(arguments[2]);if(me&&!de)return se(R,re,be);if(R===be){switch(re.length){case 0:return new R;case 1:return new R(re[0]);case 2:return new R(re[0],re[1]);case 3:return new R(re[0],re[1],re[2]);case 4:return new R(re[0],re[1],re[2],re[3])}var ye=[null];return W(fe,ye,re),new(W(O,R,ye))}var _e=be.prototype,xe=K(G(_e)?_e:te),ge=W(R,xe,re);return G(ge)?ge:xe}})},4864:function($,J,j){var E=j(3724),B=j(4576),W=j(9504),O=j(2796),ie=j(3167),U=j(6699),G=j(2360),K=j(8480).f,X=j(1625),se=j(788),te=j(655),fe=j(1034),de=j(8429),me=j(1056),q=j(6840),R=j(9039),re=j(9297),be=j(1181).enforce,ye=j(7633),_e=j(8227),xe=j(3635),ge=j(8814),Me=_e("match"),Be=B.RegExp,Fe=Be.prototype,Oe=B.SyntaxError,Re=W(Fe.exec),We=W("".charAt),ze=W("".replace),st=W("".indexOf),Ee=W("".slice),it=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Ce=/a/g,Ze=/a/g,Ie=new Be(Ce)!==Ce,ke=de.MISSED_STICKY,Ve=de.UNSUPPORTED_Y;if(O("RegExp",E&&(!Ie||ke||xe||ge||R((function(){return Ze[Me]=!1,Be(Ce)!==Ce||Be(Ze)===Ze||String(Be(Ce,"i"))!=="/a/i"}))))){for(var rt=function(tt,ot){var Tt,Ut,bt,Wt,Zt,ln,cn=X(Fe,this),ct=se(tt),kt=ot===void 0,Nt=[],ut=tt;if(!cn&&ct&&kt&&tt.constructor===rt)return tt;if((ct||X(Fe,tt))&&(tt=tt.source,kt&&(ot=fe(ut))),tt=tt===void 0?"":te(tt),ot=ot===void 0?"":te(ot),ut=tt,xe&&"dotAll"in Ce&&(Ut=!!ot&&st(ot,"s")>-1)&&(ot=ze(ot,/s/g,"")),Tt=ot,ke&&"sticky"in Ce&&(bt=!!ot&&st(ot,"y")>-1)&&Ve&&(ot=ze(ot,/y/g,"")),ge&&(Wt=(function(Ct){for(var Le,Ae=Ct.length,Ge=0,Je="",De=[],mt=G(null),Ne=!1,Ye=!1,nt=0,at="";Ge<Ae;Ge++){if((Le=We(Ct,Ge))==="\\")Le+=We(Ct,++Ge);else if(Le==="]")Ne=!1;else if(!Ne)switch(!0){case Le==="[":Ne=!0;break;case Le==="(":if(Je+=Le,Ee(Ct,Ge+1,Ge+3)==="?:")continue;Re(it,Ee(Ct,Ge+1))&&(Ge+=2,Ye=!0),nt++;continue;case(Le===">"&&Ye):if(at===""||re(mt,at))throw new Oe("Invalid capture group name");mt[at]=!0,De[De.length]=[at,nt],Ye=!1,at="";continue}Ye?at+=Le:Je+=Le}return[Je,De]})(tt),tt=Wt[0],Nt=Wt[1]),Zt=ie(Be(tt,ot),cn?this:Fe,rt),(Ut||bt||Nt.length)&&(ln=be(Zt),Ut&&(ln.dotAll=!0,ln.raw=rt((function(Ct){for(var Le,Ae=Ct.length,Ge=0,Je="",De=!1;Ge<Ae;Ge++)(Le=We(Ct,Ge))!=="\\"?De||Le!=="."?(Le==="["?De=!0:Le==="]"&&(De=!1),Je+=Le):Je+="[\\s\\S]":Je+=Le+We(Ct,++Ge);return Je})(tt),Tt)),bt&&(ln.sticky=!0),Nt.length&&(ln.groups=Nt)),tt!==ut)try{U(Zt,"source",ut===""?"(?:)":ut)}catch{}return Zt},Qe=K(Be),Te=0;Qe.length>Te;)me(rt,Be,Qe[Te++]);Fe.constructor=rt,rt.prototype=Fe,q(B,"RegExp",rt,{constructor:!0})}ye("RegExp")},7495:function($,J,j){var E=j(6518),B=j(7323);E({target:"RegExp",proto:!0,forced:/./.exec!==B},{exec:B})},8781:function($,J,j){var E=j(350).PROPER,B=j(6840),W=j(8551),O=j(655),ie=j(9039),U=j(1034),G="toString",K=RegExp.prototype,X=K[G],se=ie((function(){return X.call({source:"a",flags:"b"})!=="/a/b"})),te=E&&X.name!==G;(se||te)&&B(K,G,(function(){var fe=W(this);return"/"+O(fe.source)+"/"+O(U(fe))}),{unsafe:!0})},1699:function($,J,j){var E=j(6518),B=j(9504),W=j(5749),O=j(7750),ie=j(655),U=j(1436),G=B("".indexOf);E({target:"String",proto:!0,forced:!U("includes")},{includes:function(K){return!!~G(ie(O(this)),ie(W(K)),arguments.length>1?arguments[1]:void 0)}})},7764:function($,J,j){var E=j(8183).charAt,B=j(655),W=j(1181),O=j(1088),ie=j(2529),U="String Iterator",G=W.set,K=W.getterFor(U);O(String,"String",(function(X){G(this,{type:U,string:B(X),index:0})}),(function(){var X,se=K(this),te=se.string,fe=se.index;return fe>=te.length?ie(void 0,!0):(X=E(te,fe),se.index+=X.length,ie(X,!1))}))},8543:function($,J,j){var E=j(6518),B=j(9565),W=j(7476),O=j(3994),ie=j(2529),U=j(7750),G=j(8014),K=j(655),X=j(8551),se=j(34),te=j(2195),fe=j(788),de=j(1034),me=j(5966),q=j(6840),R=j(9039),re=j(8227),be=j(2293),ye=j(7829),_e=j(6682),xe=j(1181),ge=j(6395),Me=re("matchAll"),Be="RegExp String",Fe=Be+" Iterator",Oe=xe.set,Re=xe.getterFor(Fe),We=RegExp.prototype,ze=TypeError,st=W("".indexOf),Ee=W("".matchAll),it=!!Ee&&!R((function(){Ee("a",/./)})),Ce=O((function(Ie,ke,Ve,rt){Oe(this,{type:Fe,regexp:Ie,string:ke,global:Ve,unicode:rt,done:!1})}),Be,(function(){var Ie=Re(this);if(Ie.done)return ie(void 0,!0);var ke=Ie.regexp,Ve=Ie.string,rt=_e(ke,Ve);return rt===null?(Ie.done=!0,ie(void 0,!0)):Ie.global?(K(rt[0])===""&&(ke.lastIndex=ye(Ve,G(ke.lastIndex),Ie.unicode)),ie(rt,!1)):(Ie.done=!0,ie(rt,!1))})),Ze=function(Ie){var ke,Ve,rt,Qe=X(this),Te=K(Ie),tt=be(Qe,RegExp),ot=K(de(Qe));return ke=new tt(tt===RegExp?Qe.source:Qe,ot),Ve=!!~st(ot,"g"),rt=!!~st(ot,"u"),ke.lastIndex=G(Qe.lastIndex),new Ce(ke,Te,Ve,rt)};E({target:"String",proto:!0,forced:it},{matchAll:function(Ie){var ke,Ve,rt,Qe,Te=U(this);if(se(Ie)){if(fe(Ie)&&(ke=K(U(de(Ie))),!~st(ke,"g")))throw new ze("`.matchAll` does not allow non-global regexes");if(it)return Ee(Te,Ie);if((rt=me(Ie,Me))===void 0&&ge&&te(Ie)==="RegExp"&&(rt=Ze),rt)return B(rt,Ie,Te)}else if(it)return Ee(Te,Ie);return Ve=K(Te),Qe=new RegExp(Ie,"g"),ge?B(Ze,Qe,Ve):Qe[Me](Ve)}}),ge||Me in We||q(We,Me,Ze)},1761:function($,J,j){var E=j(9565),B=j(9504),W=j(9228),O=j(8551),ie=j(34),U=j(8014),G=j(655),K=j(7750),X=j(5966),se=j(7829),te=j(1034),fe=j(6682),de=B("".indexOf);W("match",(function(me,q,R){return[function(re){var be=K(this),ye=ie(re)?X(re,me):void 0;return ye?E(ye,re,be):new RegExp(re)[me](G(be))},function(re){var be=O(this),ye=G(re),_e=R(q,be,ye);if(_e.done)return _e.value;var xe=G(te(be));if(de(xe,"g")===-1)return fe(be,ye);var ge=de(xe,"u")!==-1;be.lastIndex=0;for(var Me,Be=[],Fe=0;(Me=fe(be,ye))!==null;){var Oe=G(Me[0]);Be[Fe]=Oe,Oe===""&&(be.lastIndex=se(ye,U(be.lastIndex),ge)),Fe++}return Fe===0?null:Be}]}))},5440:function($,J,j){var E=j(8745),B=j(9565),W=j(9504),O=j(9228),ie=j(9039),U=j(8551),G=j(4901),K=j(34),X=j(1291),se=j(8014),te=j(655),fe=j(7750),de=j(7829),me=j(5966),q=j(2478),R=j(1034),re=j(6682),be=j(8227)("replace"),ye=Math.max,_e=Math.min,xe=W([].concat),ge=W([].push),Me=W("".indexOf),Be=W("".slice),Fe="a".replace(/./,"$0")==="$0",Oe=!!/./[be]&&/./[be]("a","$0")==="";O("replace",(function(Re,We,ze){var st=Oe?"$":"$0";return[function(Ee,it){var Ce=fe(this),Ze=K(Ee)?me(Ee,be):void 0;return Ze?B(Ze,Ee,Ce,it):B(We,te(Ce),Ee,it)},function(Ee,it){var Ce=U(this),Ze=te(Ee);if(typeof it=="string"&&Me(it,st)===-1&&Me(it,"$<")===-1){var Ie=ze(We,Ce,Ze,it);if(Ie.done)return Ie.value}var ke=G(it);ke||(it=te(it));var Ve,rt=te(R(Ce)),Qe=Me(rt,"g")!==-1;Qe&&(Ve=Me(rt,"u")!==-1,Ce.lastIndex=0);for(var Te,tt=[];(Te=re(Ce,Ze))!==null&&(ge(tt,Te),Qe);)te(Te[0])===""&&(Ce.lastIndex=de(Ze,se(Ce.lastIndex),Ve));for(var ot,Tt="",Ut=0,bt=0;bt<tt.length;bt++){for(var Wt,Zt=te((Te=tt[bt])[0]),ln=ye(_e(X(Te.index),Ze.length),0),cn=[],ct=1;ct<Te.length;ct++)ge(cn,(ot=Te[ct])===void 0?ot:String(ot));var kt=Te.groups;if(ke){var Nt=xe([Zt],cn,ln,Ze);kt!==void 0&&ge(Nt,kt),Wt=te(E(it,void 0,Nt))}else Wt=q(Zt,Ze,ln,cn,kt,it);ln>=Ut&&(Tt+=Be(Ze,Ut,ln)+Wt,Ut=ln+Zt.length)}return Tt+Be(Ze,Ut)}]}),!!ie((function(){var Re=/./;return Re.exec=function(){var We=[];return We.groups={a:"7"},We},"".replace(Re,"$<a>")!=="7"}))||!Fe||Oe)},744:function($,J,j){var E=j(9565),B=j(9504),W=j(9228),O=j(8551),ie=j(34),U=j(7750),G=j(2293),K=j(7829),X=j(8014),se=j(655),te=j(5966),fe=j(6682),de=j(8429),me=j(9039),q=de.UNSUPPORTED_Y,R=Math.min,re=B([].push),be=B("".slice),ye=!me((function(){var xe=/(?:)/,ge=xe.exec;xe.exec=function(){return ge.apply(this,arguments)};var Me="ab".split(xe);return Me.length!==2||Me[0]!=="a"||Me[1]!=="b"})),_e="abbc".split(/(b)*/)[1]==="c"||"test".split(/(?:)/,-1).length!==4||"ab".split(/(?:ab)*/).length!==2||".".split(/(.?)(.?)/).length!==4||".".split(/()()/).length>1||"".split(/.?/).length;W("split",(function(xe,ge,Me){var Be="0".split(void 0,0).length?function(Fe,Oe){return Fe===void 0&&Oe===0?[]:E(ge,this,Fe,Oe)}:ge;return[function(Fe,Oe){var Re=U(this),We=ie(Fe)?te(Fe,xe):void 0;return We?E(We,Fe,Re,Oe):E(Be,se(Re),Fe,Oe)},function(Fe,Oe){var Re=O(this),We=se(Fe);if(!_e){var ze=Me(Be,Re,We,Oe,Be!==ge);if(ze.done)return ze.value}var st=G(Re,RegExp),Ee=Re.unicode,it=(Re.ignoreCase?"i":"")+(Re.multiline?"m":"")+(Re.unicode?"u":"")+(q?"g":"y"),Ce=new st(q?"^(?:"+Re.source+")":Re,it),Ze=Oe===void 0?4294967295:Oe>>>0;if(Ze===0)return[];if(We.length===0)return fe(Ce,We)===null?[We]:[];for(var Ie=0,ke=0,Ve=[];ke<We.length;){Ce.lastIndex=q?0:ke;var rt,Qe=fe(Ce,q?be(We,ke):We);if(Qe===null||(rt=R(X(Ce.lastIndex+(q?ke:0)),We.length))===Ie)ke=K(We,ke,Ee);else{if(re(Ve,be(We,Ie,ke)),Ve.length===Ze)return Ve;for(var Te=1;Te<=Qe.length-1;Te++)if(re(Ve,Qe[Te]),Ve.length===Ze)return Ve;ke=Ie=rt}}return re(Ve,be(We,Ie)),Ve}]}),_e||!ye,q)},2762:function($,J,j){var E=j(6518),B=j(3802).trim;E({target:"String",proto:!0,forced:j(706)("trim")},{trim:function(){return B(this)}})},6761:function($,J,j){var E=j(6518),B=j(4576),W=j(9565),O=j(9504),ie=j(6395),U=j(3724),G=j(4495),K=j(9039),X=j(9297),se=j(1625),te=j(8551),fe=j(5397),de=j(6969),me=j(655),q=j(6980),R=j(2360),re=j(1072),be=j(8480),ye=j(298),_e=j(3717),xe=j(7347),ge=j(4913),Me=j(6801),Be=j(8773),Fe=j(6840),Oe=j(2106),Re=j(5745),We=j(6119),ze=j(421),st=j(3392),Ee=j(8227),it=j(1951),Ce=j(511),Ze=j(8242),Ie=j(687),ke=j(1181),Ve=j(9213).forEach,rt=We("hidden"),Qe="Symbol",Te="prototype",tt=ke.set,ot=ke.getterFor(Qe),Tt=Object[Te],Ut=B.Symbol,bt=Ut&&Ut[Te],Wt=B.RangeError,Zt=B.TypeError,ln=B.QObject,cn=xe.f,ct=ge.f,kt=ye.f,Nt=Be.f,ut=O([].push),Ct=Re("symbols"),Le=Re("op-symbols"),Ae=Re("wks"),Ge=!ln||!ln[Te]||!ln[Te].findChild,Je=function(wt,Ue,He){var Dt=cn(Tt,Ue);Dt&&delete Tt[Ue],ct(wt,Ue,He),Dt&&wt!==Tt&&ct(Tt,Ue,Dt)},De=U&&K((function(){return R(ct({},"a",{get:function(){return ct(this,"a",{value:7}).a}})).a!==7}))?Je:ct,mt=function(wt,Ue){var He=Ct[wt]=R(bt);return tt(He,{type:Qe,tag:wt,description:Ue}),U||(He.description=Ue),He},Ne=function(wt,Ue,He){wt===Tt&&Ne(Le,Ue,He),te(wt);var Dt=de(Ue);return te(He),X(Ct,Dt)?(He.enumerable?(X(wt,rt)&&wt[rt][Dt]&&(wt[rt][Dt]=!1),He=R(He,{enumerable:q(0,!1)})):(X(wt,rt)||ct(wt,rt,q(1,R(null))),wt[rt][Dt]=!0),De(wt,Dt,He)):ct(wt,Dt,He)},Ye=function(wt,Ue){te(wt);var He=fe(Ue),Dt=re(He).concat(vt(He));return Ve(Dt,(function(Rt){U&&!W(nt,He,Rt)||Ne(wt,Rt,He[Rt])})),wt},nt=function(wt){var Ue=de(wt),He=W(Nt,this,Ue);return!(this===Tt&&X(Ct,Ue)&&!X(Le,Ue))&&(!(He||!X(this,Ue)||!X(Ct,Ue)||X(this,rt)&&this[rt][Ue])||He)},at=function(wt,Ue){var He=fe(wt),Dt=de(Ue);if(He!==Tt||!X(Ct,Dt)||X(Le,Dt)){var Rt=cn(He,Dt);return!Rt||!X(Ct,Dt)||X(He,rt)&&He[rt][Dt]||(Rt.enumerable=!0),Rt}},et=function(wt){var Ue=kt(fe(wt)),He=[];return Ve(Ue,(function(Dt){X(Ct,Dt)||X(ze,Dt)||ut(He,Dt)})),He},vt=function(wt){var Ue=wt===Tt,He=kt(Ue?Le:fe(wt)),Dt=[];return Ve(He,(function(Rt){!X(Ct,Rt)||Ue&&!X(Tt,Rt)||ut(Dt,Ct[Rt])})),Dt};G||(Ut=function(){if(se(bt,this))throw new Zt("Symbol is not a constructor");var wt=arguments.length&&arguments[0]!==void 0?me(arguments[0]):void 0,Ue=st(wt),He=function(Dt){var Rt=this===void 0?B:this;Rt===Tt&&W(He,Le,Dt),X(Rt,rt)&&X(Rt[rt],Ue)&&(Rt[rt][Ue]=!1);var qe=q(1,Dt);try{De(Rt,Ue,qe)}catch(Ke){if(!(Ke instanceof Wt))throw Ke;Je(Rt,Ue,qe)}};return U&&Ge&&De(Tt,Ue,{configurable:!0,set:He}),mt(Ue,wt)},Fe(bt=Ut[Te],"toString",(function(){return ot(this).tag})),Fe(Ut,"withoutSetter",(function(wt){return mt(st(wt),wt)})),Be.f=nt,ge.f=Ne,Me.f=Ye,xe.f=at,be.f=ye.f=et,_e.f=vt,it.f=function(wt){return mt(Ee(wt),wt)},U&&(Oe(bt,"description",{configurable:!0,get:function(){return ot(this).description}}),ie||Fe(Tt,"propertyIsEnumerable",nt,{unsafe:!0}))),E({global:!0,constructor:!0,wrap:!0,forced:!G,sham:!G},{Symbol:Ut}),Ve(re(Ae),(function(wt){Ce(wt)})),E({target:Qe,stat:!0,forced:!G},{useSetter:function(){Ge=!0},useSimple:function(){Ge=!1}}),E({target:"Object",stat:!0,forced:!G,sham:!U},{create:function(wt,Ue){return Ue===void 0?R(wt):Ye(R(wt),Ue)},defineProperty:Ne,defineProperties:Ye,getOwnPropertyDescriptor:at}),E({target:"Object",stat:!0,forced:!G},{getOwnPropertyNames:et}),Ze(),Ie(Ut,Qe),ze[rt]=!0},9463:function($,J,j){var E=j(6518),B=j(3724),W=j(4576),O=j(9504),ie=j(9297),U=j(4901),G=j(1625),K=j(655),X=j(2106),se=j(7740),te=W.Symbol,fe=te&&te.prototype;if(B&&U(te)&&(!("description"in fe)||te().description!==void 0)){var de={},me=function(){var xe=arguments.length<1||arguments[0]===void 0?void 0:K(arguments[0]),ge=G(fe,this)?new te(xe):xe===void 0?te():te(xe);return xe===""&&(de[ge]=!0),ge};se(me,te),me.prototype=fe,fe.constructor=me;var q=String(te("description detection"))==="Symbol(description detection)",R=O(fe.valueOf),re=O(fe.toString),be=/^Symbol\((.*)\)[^)]+$/,ye=O("".replace),_e=O("".slice);X(fe,"description",{configurable:!0,get:function(){var xe=R(this);if(ie(de,xe))return"";var ge=re(xe),Me=q?_e(ge,7,-1):ye(ge,be,"$1");return Me===""?void 0:Me}}),E({global:!0,constructor:!0,forced:!0},{Symbol:me})}},1510:function($,J,j){var E=j(6518),B=j(7751),W=j(9297),O=j(655),ie=j(5745),U=j(1296),G=ie("string-to-symbol-registry"),K=ie("symbol-to-string-registry");E({target:"Symbol",stat:!0,forced:!U},{for:function(X){var se=O(X);if(W(G,se))return G[se];var te=B("Symbol")(se);return G[se]=te,K[te]=se,te}})},2259:function($,J,j){j(511)("iterator")},2675:function($,J,j){j(6761),j(1510),j(7812),j(3110),j(9773)},7812:function($,J,j){var E=j(6518),B=j(9297),W=j(757),O=j(6823),ie=j(5745),U=j(1296),G=ie("symbol-to-string-registry");E({target:"Symbol",stat:!0,forced:!U},{keyFor:function(K){if(!W(K))throw new TypeError(O(K)+" is not a symbol");if(B(G,K))return G[K]}})},5700:function($,J,j){var E=j(511),B=j(8242);E("toPrimitive"),B()},8344:function($,J,j){j(8543)},3500:function($,J,j){var E=j(4576),B=j(7400),W=j(9296),O=j(235),ie=j(6699),U=function(K){if(K&&K.forEach!==O)try{ie(K,"forEach",O)}catch{K.forEach=O}};for(var G in B)B[G]&&U(E[G]&&E[G].prototype);U(W)},2953:function($,J,j){var E=j(4576),B=j(7400),W=j(9296),O=j(3792),ie=j(6699),U=j(687),G=j(8227)("iterator"),K=O.values,X=function(te,fe){if(te){if(te[G]!==K)try{ie(te,G,K)}catch{te[G]=K}if(U(te,fe,!0),B[fe]){for(var de in O)if(te[de]!==O[de])try{ie(te,de,O[de])}catch{te[de]=O[de]}}}};for(var se in B)X(E[se]&&E[se].prototype,se);X(W,"DOMTokenList")}},d={};function u($){var J=d[$];if(J!==void 0)return J.exports;var j=d[$]={exports:{}};return c[$].call(j.exports,j,j.exports,u),j.exports}u.d=function($,J){for(var j in J)u.o(J,j)&&!u.o($,j)&&Object.defineProperty($,j,{enumerable:!0,get:J[j]})},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($,J){return Object.prototype.hasOwnProperty.call($,J)},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(J){if(Array.isArray(J))return g(J)})($)||(function(J){if(typeof Symbol<"u"&&J[Symbol.iterator]!=null||J["@@iterator"]!=null)return Array.from(J)})($)||f($)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
  8354. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function f($,J){if($){if(typeof $=="string")return g($,J);var j={}.toString.call($).slice(8,-1);return j==="Object"&&$.constructor&&(j=$.constructor.name),j==="Map"||j==="Set"?Array.from($):j==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(j)?g($,J):void 0}}function g($,J){(J==null||J>$.length)&&(J=$.length);for(var j=0,E=Array(J);j<J;j++)E[j]=$[j];return E}function w($){return w=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},w($)}function b($,J){for(var j=0;j<J.length;j++){var E=J[j];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty($,S(E.key),E)}}function x($,J,j){return(J=S(J))in $?Object.defineProperty($,J,{value:j,enumerable:!0,configurable:!0,writable:!0}):$[J]=j,$}function S($){var J=(function(j,E){if(w(j)!="object"||!j)return j;var B=j[Symbol.toPrimitive];if(B!==void 0){var W=B.call(j,E);if(w(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(E==="string"?String:Number)(j)})($,"string");return w(J)=="symbol"?J:J+""}u.r(m),u.d(m,{SimpleKeyboard:function(){return he},default:function(){return we}}),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 J="classList",j="prototype",E=$.Element[j],B=Object,W=String[j].trim||function(){return this.replace(/^\s+|\s+$/g,"")},O=Array[j].indexOf||function(te){for(var fe=0,de=this.length;fe<de;fe++)if(fe in this&&this[fe]===te)return fe;return-1},ie=function(te,fe){this.name=te,this.code=DOMException[te],this.message=fe},U=function(te,fe){if(fe==="")throw new ie("SYNTAX_ERR","The token must not be empty.");if(/\s/.test(fe))throw new ie("INVALID_CHARACTER_ERR","The token must not contain space characters.");return O.call(te,fe)},G=function(te){for(var fe=W.call(te.getAttribute("class")||""),de=fe?fe.split(/\s+/):[],me=0,q=de.length;me<q;me++)this.push(de[me]);this._updateClassName=function(){te.setAttribute("class",this.toString())}},K=G[j]=[],X=function(){return new G(this)};if(ie[j]=Error[j],K.item=function(te){return this[te]||null},K.contains=function(te){return~U(this,te+"")},K.add=function(){var te,fe=arguments,de=0,me=fe.length,q=!1;do~U(this,te=fe[de]+"")||(this.push(te),q=!0);while(++de<me);q&&this._updateClassName()},K.remove=function(){var te,fe,de=arguments,me=0,q=de.length,R=!1;do for(fe=U(this,te=de[me]+"");~fe;)this.splice(fe,1),R=!0,fe=U(this,te);while(++me<q);R&&this._updateClassName()},K.toggle=function(te,fe){var de=this.contains(te),me=de?fe!==!0&&"remove":fe!==!1&&"add";return me&&this[me](te),fe===!0||fe===!1?fe:!de},K.replace=function(te,fe){var de=U(te+"");~de&&(this.splice(de,1,fe),this._updateClassName())},K.toString=function(){return this.join(" ")},B.defineProperty){var se={get:X,enumerable:!0,configurable:!0};try{B.defineProperty(E,J,se)}catch(te){te.number!==void 0&&te.number!==-2146823252||(se.enumerable=!1,B.defineProperty(E,J,se))}}else B[j].__defineGetter__&&E.__defineGetter__(J,X)}})(self),(function(){var $=document.createElement("_");if($.classList.add("c1","c2"),!$.classList.contains("c2")){var J=function(E){var B=DOMTokenList.prototype[E];DOMTokenList.prototype[E]=function(W){var O,ie=arguments.length;for(O=0;O<ie;O++)W=arguments[O],B.call(this,W)}};J("add"),J("remove")}if($.classList.toggle("c3",!1),$.classList.contains("c3")){var j=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(E,B){return 1 in arguments&&!this.contains(E)==!B?B:j.call(this,E)}}"replace"in document.createElement("_").classList||(DOMTokenList.prototype.replace=function(E,B){var W=this.toString().split(" "),O=W.indexOf(E+"");~O&&(W=W.slice(O),this.remove.apply(this,W),this.add(B),this.add.apply(this,W.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 k=(function(){return $=function E(B){var W=B.getOptions,O=B.getCaretPosition,ie=B.getCaretPositionEnd,U=B.dispatch;(function(G,K){if(!(G instanceof K))throw new TypeError("Cannot call a class as a function")})(this,E),x(this,"getOptions",void 0),x(this,"getCaretPosition",void 0),x(this,"getCaretPositionEnd",void 0),x(this,"dispatch",void 0),x(this,"maxLengthReached",void 0),x(this,"isStandardButton",(function(G){return G&&!(G[0]==="{"&&G[G.length-1]==="}")})),this.getOptions=W,this.getCaretPosition=O,this.getCaretPositionEnd=ie,this.dispatch=U,E.bindMethods(E,this)},J=[{key:"getButtonType",value:function(E){return E.includes("{")&&E.includes("}")&&E!=="{//}"?"functionBtn":"standardBtn"}},{key:"getButtonClass",value:function(E){var B=this.getButtonType(E),W=E.replace("{","").replace("}",""),O="";return B!=="standardBtn"&&(O=" hg-button-".concat(W)),"hg-".concat(B).concat(O)}},{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(E,B){return(B=arguments.length>2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),B):B||this.getDefaultDiplay())[E]||E}},{key:"getUpdatedInput",value:function(E,B,W){var O=arguments.length>3&&arguments[3]!==void 0?arguments[3]:W,ie=arguments.length>4&&arguments[4]!==void 0&&arguments[4],U=this.getOptions(),G=[W,O,ie],K=B;return(E==="{bksp}"||E==="{backspace}")&&K.length>0?K=this.removeAt.apply(this,[K].concat(G)):(E==="{delete}"||E==="{forwarddelete}")&&K.length>0?K=this.removeForwardsAt.apply(this,[K].concat(G)):E==="{space}"?K=this.addStringAt.apply(this,[K," "].concat(G)):E!=="{tab}"||typeof U.tabCharOnTab=="boolean"&&U.tabCharOnTab===!1?E!=="{enter}"&&E!=="{numpadenter}"||!U.newLineOnEnter?E.includes("numpad")&&Number.isInteger(Number(E[E.length-2]))?K=this.addStringAt.apply(this,[K,E[E.length-2]].concat(G)):E==="{numpaddivide}"?K=this.addStringAt.apply(this,[K,"/"].concat(G)):E==="{numpadmultiply}"?K=this.addStringAt.apply(this,[K,"*"].concat(G)):E==="{numpadsubtract}"?K=this.addStringAt.apply(this,[K,"-"].concat(G)):E==="{numpadadd}"?K=this.addStringAt.apply(this,[K,"+"].concat(G)):E==="{numpaddecimal}"?K=this.addStringAt.apply(this,[K,"."].concat(G)):E==="{"||E==="}"?K=this.addStringAt.apply(this,[K,E].concat(G)):E.includes("{")||E.includes("}")||(K=this.addStringAt.apply(this,[K,E].concat(G))):K=this.addStringAt.apply(this,[K,`
  8355. `].concat(G)):K=this.addStringAt.apply(this,[K," "].concat(G)),U.debug&&console.log("Input will be: "+K),K}},{key:"updateCaretPos",value:function(E){var B=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.updateCaretPosAction(E,B);this.dispatch((function(O){O.setCaretPosition(W)}))}},{key:"updateCaretPosAction",value:function(E){var B=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.getOptions(),O=this.getCaretPosition();return O!=null&&(B?O>0&&(O-=E):O+=E),W.debug&&console.log("Caret at:",O),O}},{key:"addStringAt",value:function(E,B){var W,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0?arguments[3]:E.length,U=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return O||O===0?(W=[E.slice(0,O),B,E.slice(ie)].join(""),this.isMaxLengthReached()||U&&this.updateCaretPos(B.length)):W=E+B,W}},{key:"removeAt",value:function(E){var B,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(W===0&&O===0)return E;if(W===O){var U=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;W&&W>=0?E.substring(W-2,W).match(U)?(B=E.substr(0,W-2)+E.substr(W),ie&&this.updateCaretPos(2,!0)):(B=E.substr(0,W-1)+E.substr(W),ie&&this.updateCaretPos(1,!0)):E.slice(-2).match(U)?(B=E.slice(0,-2),ie&&this.updateCaretPos(2,!0)):(B=E.slice(0,-1),ie&&this.updateCaretPos(1,!0))}else B=E.slice(0,W)+E.slice(O),ie&&this.dispatch((function(G){G.setCaretPosition(W)}));return B}},{key:"removeForwardsAt",value:function(E){var B,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return E!=null&&E.length&&W!==null?(W===O?B=E.substring(W,W+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?E.substr(0,W)+E.substr(W+2):E.substr(0,W)+E.substr(W+1):(B=E.slice(0,W)+E.slice(O),ie&&this.dispatch((function(U){U.setCaretPosition(W)}))),B):E}},{key:"handleMaxLength",value:function(E,B){var W=this.getOptions(),O=W.maxLength,ie=E[W.inputName||"default"],U=B.length-1>=O;if(B.length<=ie.length)return!1;if(Number.isInteger(O))return W.debug&&console.log("maxLength (num) reached:",U),U?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(w(O)==="object"){var G=B.length-1>=O[W.inputName||"default"];return W.debug&&console.log("maxLength (obj) reached:",G),G?(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(E){return E?E.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(B,W){return W.length?B+W[0].toUpperCase()+W.slice(1):B})):""}},{key:"chunkArray",value:function(E,B){return p(Array(Math.ceil(E.length/B))).map((function(W,O){return E.slice(B*O,B+B*O)}))}},{key:"escapeRegex",value:function(E){return E.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}},{key:"getRtlOffset",value:function(E,B){var W=E,O=B.indexOf("‫");return O<E&&O!=-1&&W--,B.indexOf("‬")<E&&O!=-1&&W--,W<0?0:W}},{key:"isConstructor",value:function(E){try{Reflect.construct(String,[],E)}catch{return!1}return!0}}],j=[{key:"bindMethods",value:function(E,B){var W,O=(function(U,G){var K=typeof Symbol<"u"&&U[Symbol.iterator]||U["@@iterator"];if(!K){if(Array.isArray(U)||(K=f(U))||G){K&&(U=K);var X=0,se=function(){};return{s:se,n:function(){return X>=U.length?{done:!0}:{done:!1,value:U[X++]}},e:function(me){throw me},f:se}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
  8356. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var te,fe=!0,de=!1;return{s:function(){K=K.call(U)},n:function(){var me=K.next();return fe=me.done,me},e:function(me){de=!0,te=me},f:function(){try{fe||K.return==null||K.return()}finally{if(de)throw te}}}})(Object.getOwnPropertyNames(E.prototype));try{for(O.s();!(W=O.n()).done;){var ie=W.value;ie==="constructor"||ie==="bindMethods"||(B[ie]=B[ie].bind(B))}}catch(U){O.e(U)}finally{O.f()}}}],J&&b($.prototype,J),j&&b($,j),Object.defineProperty($,"prototype",{writable:!1}),$;var $,J,j})();x(k,"noop",(function(){}));var C=k;function P($){return P=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},P($)}function T($,J){for(var j=0;j<J.length;j++){var E=J[j];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty($,F(E.key),E)}}function A($,J,j){return(J=F(J))in $?Object.defineProperty($,J,{value:j,enumerable:!0,configurable:!0,writable:!0}):$[J]=j,$}function F($){var J=(function(j,E){if(P(j)!="object"||!j)return j;var B=j[Symbol.toPrimitive];if(B!==void 0){var W=B.call(j,E);if(P(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(E==="string"?String:Number)(j)})($,"string");return P(J)=="symbol"?J:J+""}var _=(function(){return $=function E(B){var W=this,O=B.dispatch,ie=B.getOptions;(function(U,G){if(!(U instanceof G))throw new TypeError("Cannot call a class as a function")})(this,E),A(this,"getOptions",void 0),A(this,"dispatch",void 0),A(this,"isModifierKey",(function(U){return U.altKey||U.ctrlKey||U.shiftKey||["Tab","CapsLock","Esc","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(U.code||U.key||W.keyCodeToKey(U?.keyCode))})),this.dispatch=O,this.getOptions=ie,C.bindMethods(E,this)},J=[{key:"handleHighlightKeyDown",value:function(E){var B=this.getOptions();B.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(E)&&(E.preventDefault(),E.stopImmediatePropagation());var W=this.getSimpleKeyboardLayoutKey(E);this.dispatch((function(O){var ie,U,G=O.getButtonElement(W),K=O.getButtonElement("{".concat(W,"}"));if(G)ie=G,U=W;else{if(!K)return;ie=K,U="{".concat(W,"}")}var X,se,te,fe,de=function(q){q.style.background=B.physicalKeyboardHighlightBgColor||"#dadce4",q.style.color=B.physicalKeyboardHighlightTextColor||"black"};if(ie)if(Array.isArray(ie)){if(ie.forEach((function(q){return de(q)})),B.physicalKeyboardHighlightPress)if(B.physicalKeyboardHighlightPressUsePointerEvents)(X=ie[0])===null||X===void 0||(se=X.onpointerdown)===null||se===void 0||se.call(X,E);else if(B.physicalKeyboardHighlightPressUseClick){var me;(me=ie[0])===null||me===void 0||me.click()}else O.handleButtonClicked(U,E)}else de(ie),B.physicalKeyboardHighlightPress&&(B.physicalKeyboardHighlightPressUsePointerEvents?(te=ie)===null||te===void 0||(fe=te.onpointerdown)===null||fe===void 0||fe.call(te,E):B.physicalKeyboardHighlightPressUseClick?ie.click():O.handleButtonClicked(U,E))}))}},{key:"handleHighlightKeyUp",value:function(E){var B=this.getOptions();B.physicalKeyboardHighlightPreventDefault&&this.isModifierKey(E)&&(E.preventDefault(),E.stopImmediatePropagation());var W=this.getSimpleKeyboardLayoutKey(E);this.dispatch((function(O){var ie,U,G,K=O.getButtonElement(W)||O.getButtonElement("{".concat(W,"}")),X=function(se){se.removeAttribute&&se.removeAttribute("style")};K&&(Array.isArray(K)?(K.forEach((function(se){return X(se)})),B.physicalKeyboardHighlightPressUsePointerEvents&&((ie=K[0])===null||ie===void 0||(U=ie.onpointerup)===null||U===void 0||U.call(ie,E))):(X(K),B.physicalKeyboardHighlightPressUsePointerEvents&&(K==null||(G=K.onpointerup)===null||G===void 0||G.call(K,E))))}))}},{key:"getSimpleKeyboardLayoutKey",value:function(E){var B,W="",O=E.code||E.key||this.keyCodeToKey(E?.keyCode);return(W=O!=null&&O.includes("Numpad")||O!=null&&O.includes("Shift")||O!=null&&O.includes("Space")||O!=null&&O.includes("Backspace")||O!=null&&O.includes("Control")||O!=null&&O.includes("Alt")||O!=null&&O.includes("Meta")?E.code||"":E.key||this.keyCodeToKey(E?.keyCode)||"").length>1?(B=W)===null||B===void 0?void 0:B.toLowerCase():W}},{key:"keyCodeToKey",value:function(E){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:"'"}[E]||""}}],J&&T($.prototype,J),j&&T($,j),Object.defineProperty($,"prototype",{writable:!1}),$;var $,J,j})();function M($){return M=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},M($)}function H($,J){for(var j=0;j<J.length;j++){var E=J[j];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty($,z(E.key),E)}}function I($,J,j){return(J=z(J))in $?Object.defineProperty($,J,{value:j,enumerable:!0,configurable:!0,writable:!0}):$[J]=j,$}function z($){var J=(function(j,E){if(M(j)!="object"||!j)return j;var B=j[Symbol.toPrimitive];if(B!==void 0){var W=B.call(j,E);if(M(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(E==="string"?String:Number)(j)})($,"string");return M(J)=="symbol"?J:J+""}var L=(function(){return $=function E(B){var W=B.utilities,O=B.options;(function(ie,U){if(!(ie instanceof U))throw new TypeError("Cannot call a class as a function")})(this,E),I(this,"utilities",void 0),I(this,"options",void 0),I(this,"candidateBoxElement",void 0),I(this,"pageIndex",0),I(this,"pageSize",void 0),this.utilities=W,this.options=O,C.bindMethods(E,this),this.pageSize=this.utilities.getOptions().layoutCandidatesPageSize||5},J=[{key:"destroy",value:function(){this.candidateBoxElement&&(this.candidateBoxElement.remove(),this.pageIndex=0)}},{key:"show",value:function(E){var B=this,W=E.candidateValue,O=E.targetElement,ie=E.onSelect;if(W&&W.length){var U=this.utilities.chunkArray(W.split(" "),this.pageSize);this.renderPage({candidateListPages:U,targetElement:O,pageIndex:this.pageIndex,nbPages:U.length,onItemSelected:function(G,K){ie(G,K),B.destroy()}})}}},{key:"renderPage",value:function(E){var B,W=this,O=E.candidateListPages,ie=E.targetElement,U=E.pageIndex,G=E.nbPages,K=E.onItemSelected;(B=this.candidateBoxElement)===null||B===void 0||B.remove(),this.candidateBoxElement=document.createElement("div"),this.candidateBoxElement.className="hg-candidate-box";var X=document.createElement("ul");X.className="hg-candidate-box-list",O[U].forEach((function(R){var re,be=document.createElement("li"),ye=function(){var _e=new(W.options.useTouchEvents?TouchEvent:MouseEvent)("click");return Object.defineProperty(_e,"target",{value:be}),_e};be.className="hg-candidate-box-list-item",be.innerHTML=((re=W.options.display)===null||re===void 0?void 0:re[R])||R,W.options.useTouchEvents?be.ontouchstart=function(_e){return K(R,_e||ye())}:be.onclick=function(){var _e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ye();return K(R,_e)},X.appendChild(be)}));var se=U>0,te=document.createElement("div");te.classList.add("hg-candidate-box-prev"),se&&te.classList.add("hg-candidate-box-btn-active");var fe=function(){se&&W.renderPage({candidateListPages:O,targetElement:ie,pageIndex:U-1,nbPages:G,onItemSelected:K})};this.options.useTouchEvents?te.ontouchstart=fe:te.onclick=fe,this.candidateBoxElement.appendChild(te),this.candidateBoxElement.appendChild(X);var de=U<G-1,me=document.createElement("div");me.classList.add("hg-candidate-box-next"),de&&me.classList.add("hg-candidate-box-btn-active");var q=function(){de&&W.renderPage({candidateListPages:O,targetElement:ie,pageIndex:U+1,nbPages:G,onItemSelected:K})};this.options.useTouchEvents?me.ontouchstart=q:me.onclick=q,this.candidateBoxElement.appendChild(me),ie.prepend(this.candidateBoxElement)}}],J&&H($.prototype,J),j&&H($,j),Object.defineProperty($,"prototype",{writable:!1}),$;var $,J,j})(),Z=L;function ne($){return(function(J){if(Array.isArray(J))return Y(J)})($)||(function(J){if(typeof Symbol<"u"&&J[Symbol.iterator]!=null||J["@@iterator"]!=null)return Array.from(J)})($)||(function(J,j){if(J){if(typeof J=="string")return Y(J,j);var E={}.toString.call(J).slice(8,-1);return E==="Object"&&J.constructor&&(E=J.constructor.name),E==="Map"||E==="Set"?Array.from(J):E==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(E)?Y(J,j):void 0}})($)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
  8357. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function Y($,J){(J==null||J>$.length)&&(J=$.length);for(var j=0,E=Array(J);j<J;j++)E[j]=$[j];return E}function ce($){return ce=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},ce($)}function ue($,J){var j=Object.keys($);if(Object.getOwnPropertySymbols){var E=Object.getOwnPropertySymbols($);J&&(E=E.filter((function(B){return Object.getOwnPropertyDescriptor($,B).enumerable}))),j.push.apply(j,E)}return j}function oe($,J){for(var j=0;j<J.length;j++){var E=J[j];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty($,le(E.key),E)}}function Q($,J,j){return(J=le(J))in $?Object.defineProperty($,J,{value:j,enumerable:!0,configurable:!0,writable:!0}):$[J]=j,$}function le($){var J=(function(j,E){if(ce(j)!="object"||!j)return j;var B=j[Symbol.toPrimitive];if(B!==void 0){var W=B.call(j,E);if(ce(W)!="object")return W;throw new TypeError("@@toPrimitive must return a primitive value.")}return(E==="string"?String:Number)(j)})($,"string");return ce(J)=="symbol"?J:J+""}var pe=(function(){return $=function E(B,W){var O=this;if((function(fe,de){if(!(fe instanceof de))throw new TypeError("Cannot call a class as a function")})(this,E),Q(this,"input",void 0),Q(this,"options",void 0),Q(this,"utilities",void 0),Q(this,"caretPosition",void 0),Q(this,"caretPositionEnd",void 0),Q(this,"keyboardDOM",void 0),Q(this,"keyboardPluginClasses",void 0),Q(this,"keyboardDOMClass",void 0),Q(this,"buttonElements",void 0),Q(this,"currentInstanceName",void 0),Q(this,"allKeyboardInstances",void 0),Q(this,"keyboardInstanceNames",void 0),Q(this,"isFirstKeyboardInstance",void 0),Q(this,"physicalKeyboard",void 0),Q(this,"modules",void 0),Q(this,"activeButtonClass",void 0),Q(this,"holdInteractionTimeout",void 0),Q(this,"holdTimeout",void 0),Q(this,"isMouseHold",void 0),Q(this,"initialized",void 0),Q(this,"candidateBox",void 0),Q(this,"keyboardRowsDOM",void 0),Q(this,"defaultName","default"),Q(this,"activeInputElement",null),Q(this,"handleParams",(function(fe,de){var me,q,R;if(typeof fe=="string")me=fe.split(".").join(""),q=document.querySelector(".".concat(me)),R=de;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");me=fe.className.split(" ")[0],q=fe,R=de}else me="simple-keyboard",q=document.querySelector(".".concat(me)),R=fe;return{keyboardDOMClass:me,keyboardDOM:q,options:R}})),Q(this,"getOptions",(function(){return O.options})),Q(this,"getCaretPosition",(function(){return O.caretPosition})),Q(this,"getCaretPositionEnd",(function(){return O.caretPositionEnd})),Q(this,"registerModule",(function(fe,de){O.modules[fe]||(O.modules[fe]={}),de(O.modules[fe])})),Q(this,"getKeyboardClassString",(function(){for(var fe=arguments.length,de=new Array(fe),me=0;me<fe;me++)de[me]=arguments[me];return[O.keyboardDOMClass].concat(de).filter((function(q){return!!q})).join(" ")})),typeof window<"u"){var ie=this.handleParams(B,W),U=ie.keyboardDOMClass,G=ie.keyboardDOM,K=ie.options,X=K===void 0?{}:K;this.utilities=new C({getOptions:this.getOptions,getCaretPosition:this.getCaretPosition,getCaretPositionEnd:this.getCaretPositionEnd,dispatch:this.dispatch}),this.caretPosition=null,this.caretPositionEnd=null,this.keyboardDOM=G,this.options=(function(fe){for(var de=1;de<arguments.length;de++){var me=arguments[de]!=null?arguments[de]:{};de%2?ue(Object(me),!0).forEach((function(q){Q(fe,q,me[q])})):Object.getOwnPropertyDescriptors?Object.defineProperties(fe,Object.getOwnPropertyDescriptors(me)):ue(Object(me)).forEach((function(q){Object.defineProperty(fe,q,Object.getOwnPropertyDescriptor(me,q))}))}return fe})({layoutName:"default",theme:"hg-theme-default",inputName:"default",preventMouseDownDefault:!1,enableLayoutCandidates:!0,excludeFromLayout:{}},X),this.keyboardPluginClasses="",C.bindMethods(E,this);var se=this.options.inputName,te=se===void 0?this.defaultName:se;if(this.input={},this.input[te]="",this.keyboardDOMClass=U,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 _({dispatch:this.dispatch,getOptions:this.getOptions}),this.candidateBox=this.options.enableLayoutCandidates?new Z({utilities:this.utilities,options:this.options}):null,!this.keyboardDOM)throw console.warn('".'.concat(U,'" was not found in the DOM.')),new Error("KEYBOARD_DOM_ERROR");this.render(),this.modules={},this.loadModules()}},J=[{key:"setCaretPosition",value:function(E){var B=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E;this.caretPosition=E,this.caretPositionEnd=B}},{key:"getInputCandidates",value:function(E){var B=this,W=this.options,O=W.layoutCandidates,ie=W.layoutCandidatesCaseSensitiveMatch;if(!O||ce(O)!=="object")return{};var U=Object.keys(O).filter((function(X){var se=E.substring(0,B.getCaretPositionEnd()||0)||E,te=new RegExp("".concat(B.utilities.escapeRegex(X),"$"),ie?"g":"gi");return!!ne(se.matchAll(te)).length}));if(U.length>1){var G=U.sort((function(X,se){return se.length-X.length}))[0];return{candidateKey:G,candidateValue:O[G]}}if(U.length){var K=U[0];return{candidateKey:K,candidateValue:O[K]}}return{}}},{key:"showCandidatesBox",value:function(E,B,W){var O=this;this.candidateBox&&this.candidateBox.show({candidateValue:B,targetElement:W,onSelect:function(ie,U){var G=O.options,K=G.layoutCandidatesCaseSensitiveMatch,X=G.disableCandidateNormalization,se=G.enableLayoutCandidatesKeyPress,te=ie;X||(te=ie.normalize("NFD")),typeof O.options.beforeInputUpdate=="function"&&O.options.beforeInputUpdate(O);var fe=O.getInput(O.options.inputName,!0),de=O.getCaretPositionEnd()||0,me=fe.substring(0,de||0)||fe,q=new RegExp("".concat(O.utilities.escapeRegex(E),"$"),K?"g":"gi"),R=me.replace(q,te),re=fe.replace(me,R),be=R.length-me.length,ye=(de||fe.length)+be;ye<0&&(ye=0),O.setInput(re,O.options.inputName,!0),O.setCaretPosition(ye),se&&typeof O.options.onKeyPress=="function"&&O.options.onKeyPress(ie,U),typeof O.options.onChange=="function"&&O.options.onChange(O.getInput(O.options.inputName,!0),U),typeof O.options.onChangeAll=="function"&&O.options.onChangeAll(O.getAllInputs(),U)}})}},{key:"handleButtonClicked",value:function(E,B){var W=this.options,O=W.inputName,ie=O===void 0?this.defaultName:O,U=W.debug;if(E!=="{//}"){this.input[ie]||(this.input[ie]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var G=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(E)&&this.activeInputElement&&this.input[ie]&&this.input[ie]===G&&this.caretPosition===0&&this.caretPositionEnd===G.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(E,B);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(E,B),this.input[ie]!==G&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid(G))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,G))return;var K=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(K,this.options.inputName,!0),U&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),B?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),B),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),B),B!=null&&B.target&&this.options.enableLayoutCandidates){var X,se=this.getInputCandidates(G),te=se.candidateKey,fe=se.candidateValue;te&&fe?this.showCandidatesBox(te,fe,this.keyboardDOM):(X=this.candidateBox)===null||X===void 0||X.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)),U&&console.log("Key pressed:",E)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(E){this.options.syncInstanceInputs?this.dispatch((function(B){B.isMouseHold=E})):this.isMouseHold=E}},{key:"handleButtonMouseDown",value:function(E,B){var W=this;B&&(this.options.preventMouseDownDefault&&B.preventDefault(),this.options.stopMouseDownPropagation&&B.stopPropagation(),B.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(){(W.getMouseHold()&&(!E.includes("{")&&!E.includes("}")||E==="{delete}"||E==="{backspace}"||E==="{bksp}"||E==="{space}"||E==="{tab}")||E==="{arrowright}"||E==="{arrowleft}"||E==="{arrowup}"||E==="{arrowdown}")&&(W.options.debug&&console.log("Button held:",E),W.handleButtonHold(E)),clearTimeout(W.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(E,B){var W=this;B&&(this.options.preventMouseUpDefault&&B.preventDefault&&B.preventDefault(),this.options.stopMouseUpPropagation&&B.stopPropagation&&B.stopPropagation(),!(B.target===this.keyboardDOM||B.target&&this.keyboardDOM.contains(B.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(B.target===this.candidateBox.candidateBoxElement||B.target&&this.candidateBox.candidateBoxElement.contains(B.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(O){O.classList.remove(W.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),E&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(E,B)}},{key:"handleKeyboardContainerMouseDown",value:function(E){this.options.preventMouseDownDefault&&E.preventDefault()}},{key:"handleButtonHold",value:function(E){var B=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){B.getMouseHold()?(B.handleButtonClicked(E),B.handleButtonHold(E)):clearTimeout(B.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var E=this;this.dispatch((function(B){B.replaceInput(E.input),B.setCaretPosition(E.caretPosition,E.caretPositionEnd)}))}},{key:"clearInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[E]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,B=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!B&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[E].replace("‫","").replace("‬","")+"‬":this.input[E]}},{key:"getAllInputs",value:function(){var E=this,B={};return Object.keys(this.input).forEach((function(W){B[W]=E.getInput(W,!0)})),B}},{key:"setInput",value:function(E){var B=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,W=arguments.length>2?arguments[2]:void 0;this.input[B]=E,!W&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(E){this.input=E}},{key:"setOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},B=this.changedOptions(E);this.options=Object.assign(this.options,E),B.length&&(this.options.debug&&console.log("changedOptions",B),this.onSetOptions(B),this.render())}},{key:"changedOptions",value:function(E){var B=this;return Object.keys(E).filter((function(W){return JSON.stringify(E[W])!==JSON.stringify(B.options[W])}))}},{key:"onSetOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];E.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(E.includes("layoutCandidatesPageSize")||E.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new Z({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(E){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(B){E(window.SimpleKeyboardInstances[B],B)}))}},{key:"addButtonTheme",value:function(E,B){var W=this;B&&E&&(E.split(" ").forEach((function(O){B.split(" ").forEach((function(ie){W.options.buttonTheme||(W.options.buttonTheme=[]);var U=!1;W.options.buttonTheme.map((function(G){if(G!=null&&G.class.split(" ").includes(ie)){U=!0;var K=G.buttons.split(" ");K.includes(O)||(U=!0,K.push(O),G.buttons=K.join(" "))}return G})),U||W.options.buttonTheme.push({class:ie,buttons:E})}))})),this.render())}},{key:"removeButtonTheme",value:function(E,B){var W=this;if(!E&&!B)return this.options.buttonTheme=[],void this.render();E&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(E.split(" ").forEach((function(O){var ie;(ie=W.options)===null||ie===void 0||(ie=ie.buttonTheme)===null||ie===void 0||ie.map((function(U,G){if(U&&B&&B.includes(U.class)||!B){var K,X,se=(K=U)===null||K===void 0?void 0:K.buttons.split(" ").filter((function(te){return te!==O}));U&&se!=null&&se.length?U.buttons=se.join(" "):((X=W.options.buttonTheme)===null||X===void 0||X.splice(G,1),U=null)}return U}))})),this.render())}},{key:"getButtonElement",value:function(E){var B,W=this.buttonElements[E];return W&&(B=W.length>1?W:W[0]),B}},{key:"inputPatternIsValid",value:function(E){var B,W=this.options.inputPattern;if((B=W instanceof RegExp?W:W[this.options.inputName||this.defaultName])&&E){var O=B.test(E);return this.options.debug&&console.log('inputPattern ("'.concat(B,'"): ').concat(O?"passed":"did not pass!")),O}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var E=this.options.physicalKeyboardHighlightPreventDefault,B=E!==void 0&&E;document.addEventListener("keyup",this.handleKeyUp,B),document.addEventListener("keydown",this.handleKeyDown,B),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(E){this.caretEventHandler(E),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(E)}},{key:"handleKeyDown",value:function(E){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(E)}},{key:"handleMouseUp",value:function(E){this.caretEventHandler(E)}},{key:"handleTouchEnd",value:function(E){this.caretEventHandler(E)}},{key:"handleSelect",value:function(E){this.caretEventHandler(E)}},{key:"handleSelectionChange",value:function(E){navigator.userAgent.includes("Firefox")||this.caretEventHandler(E)}},{key:"caretEventHandler",value:function(E){var B,W=this;E.target.tagName&&(B=E.target.tagName.toLowerCase()),this.dispatch((function(O){var ie=E.target===O.keyboardDOM||E.target&&O.keyboardDOM.contains(E.target);if(W.options.syncInstanceInputs&&Array.isArray(E.path)&&(ie=E.path.some((function(K){var X;return K==null||(X=K.hasAttribute)===null||X===void 0?void 0:X.call(K,"data-skInstance")}))),(B==="textarea"||B==="input"&&["text","search","url","tel","password"].includes(E.target.type))&&!O.options.disableCaretPositioning){var U=E.target.selectionStart,G=E.target.selectionEnd;O.options.rtl&&(U=O.utilities.getRtlOffset(U,O.getInput()),G=O.utilities.getRtlOffset(G,O.getInput())),O.setCaretPosition(U,G),O.activeInputElement=E.target,O.options.debug&&console.log("Caret at: ",O.getCaretPosition(),O.getCaretPositionEnd(),E&&E.target.tagName.toLowerCase(),"(".concat(O.keyboardDOMClass,")"),E?.type)}else!O.options.disableCaretPositioning&&ie||E?.type==="selectionchange"||(O.setCaretPosition(null),O.activeInputElement=null,O.options.debug&&console.log('Caret position reset due to "'.concat(E?.type,'" event'),E))}))}},{key:"recurseButtons",value:function(E){var B=this;E&&Object.keys(this.buttonElements).forEach((function(W){return B.buttonElements[W].forEach(E)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var E=this.options.physicalKeyboardHighlightPreventDefault,B=E!==void 0&&E;document.removeEventListener("keyup",this.handleKeyUp,B),document.removeEventListener("keydown",this.handleKeyDown,B),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(W){W&&(W.onpointerdown=null,W.onpointerup=null,W.onpointercancel=null,W.ontouchstart=null,W.ontouchend=null,W.ontouchcancel=null,W.onclick=null,W.onmousedown=null,W.onmouseup=null,W.remove(),W=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(E){var B=this.options.buttonTheme,W=[];return Array.isArray(B)&&B.forEach((function(O){if(O&&O.class&&typeof O.class=="string"&&O.buttons&&typeof O.buttons=="string"){var ie=O.class.split(" ");O.buttons.split(" ").includes(E)&&(W=[].concat(ne(W),ne(ie)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',O)})),W}},{key:"setDOMButtonAttributes",value:function(E,B){var W=this.options.buttonAttributes;Array.isArray(W)&&W.forEach((function(O){O.attribute&&typeof O.attribute=="string"&&O.value&&typeof O.value=="string"?O.buttons&&typeof O.buttons=="string"?O.buttons.split(" ").includes(E)&&B(O.attribute,O.value):B(O.attribute,O.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',O)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(E){var B;if((B=E.target.classList)!==null&&B!==void 0&&B.contains("hg-button"))return E.preventDefault(),E.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 E=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(B){var W=E.utilities.isConstructor(B)?new B(E):B(E);W.init&&W.init(E)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(E,B){return!!this.modules[E]&&this.modules[E][B]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(E,B,W,O){var ie=this,U=Array.from(E.children),G=0;return U.length&&W.forEach((function(K,X){var se=O[X];if(!(se&&se>K))return!1;var te=K-G,fe=se-G,de=document.createElement("div");de.className+="hg-button-container";var me="".concat(ie.options.layoutName,"-r").concat(B,"c").concat(X);de.setAttribute("data-skUID",me);var q=U.splice(te,fe-te+1);G+=fe-te,q.forEach((function(R){return de.appendChild(R)})),U.splice(te,0,de),E.innerHTML="",U.forEach((function(R){return E.appendChild(R)})),ie.options.debug&&console.log("rowDOMContainer",q,te,fe,G+1)})),E}},{key:"render",value:function(){var E=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var B="hg-layout-".concat(this.options.layoutName),W=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}"]},O=this.options.useTouchEvents||!1,ie=O?"hg-touch-events":"",U=this.options.useMouseEvents||!1,G=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,B,this.keyboardPluginClasses,ie),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",W[this.options.layoutName||this.defaultName].forEach((function(K,X){var se=K.split(" ");E.options.excludeFromLayout&&E.options.excludeFromLayout[E.options.layoutName||E.defaultName]&&(se=se.filter((function(me){return E.options.excludeFromLayout&&!E.options.excludeFromLayout[E.options.layoutName||E.defaultName].includes(me)})));var te=document.createElement("div");te.className+="hg-row";var fe=[],de=[];se.forEach((function(me,q){var R,re=!G&&typeof me=="string"&&me.length>1&&me.indexOf("[")===0,be=!G&&typeof me=="string"&&me.length>1&&me.indexOf("]")===me.length-1;re&&(fe.push(q),me=me.replace(/\[/g,"")),be&&(de.push(q),me=me.replace(/\]/g,""));var ye=E.utilities.getButtonClass(me),_e=E.utilities.getButtonDisplayName(me,E.options.display,E.options.mergeDisplay),xe=E.options.useButtonTag?"button":"div",ge=document.createElement(xe);ge.className+="hg-button ".concat(ye),(R=ge.classList).add.apply(R,ne(E.getButtonThemeClasses(me))),E.setDOMButtonAttributes(me,(function(Fe,Oe){ge.setAttribute(Fe,Oe)})),E.activeButtonClass="hg-activeButton",!E.utilities.pointerEventsSupported()||O||U?O?(ge.ontouchstart=function(Fe){E.handleButtonClicked(me,Fe),E.handleButtonMouseDown(me,Fe)},ge.ontouchend=function(Fe){E.handleButtonMouseUp(me,Fe)},ge.ontouchcancel=function(Fe){E.handleButtonMouseUp(me,Fe)}):(ge.onclick=function(Fe){E.setMouseHold(!1),typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown||E.handleButtonClicked(me,Fe)},ge.onmousedown=function(Fe){(typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown)&&!E.isMouseHold&&E.handleButtonClicked(me,Fe),E.handleButtonMouseDown(me,Fe)},ge.onmouseup=function(Fe){E.handleButtonMouseUp(me,Fe)}):(ge.onpointerdown=function(Fe){E.handleButtonClicked(me,Fe),E.handleButtonMouseDown(me,Fe)},ge.onpointerup=function(Fe){E.handleButtonMouseUp(me,Fe)},ge.onpointercancel=function(Fe){E.handleButtonMouseUp(me,Fe)}),ge.setAttribute("data-skBtn",me);var Me="".concat(E.options.layoutName,"-r").concat(X,"b").concat(q);ge.setAttribute("data-skBtnUID",Me);var Be=document.createElement("span");Be.innerHTML=_e,ge.appendChild(Be),E.buttonElements[me]||(E.buttonElements[me]=[]),E.buttonElements[me].push(ge),te.appendChild(ge)})),te=E.parseRowDOMContainers(te,X,fe,de),E.keyboardRowsDOM.appendChild(te)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||O||U?O?(document.ontouchend=function(K){return E.handleButtonMouseUp(void 0,K)},document.ontouchcancel=function(K){return E.handleButtonMouseUp(void 0,K)},this.keyboardDOM.ontouchstart=function(K){return E.handleKeyboardContainerMouseDown(K)}):O||(document.onmouseup=function(K){return E.handleButtonMouseUp(void 0,K)},this.keyboardDOM.onmousedown=function(K){return E.handleKeyboardContainerMouseDown(K)}):(document.onpointerup=function(K){return E.handleButtonMouseUp(void 0,K)},this.keyboardDOM.onpointerdown=function(K){return E.handleKeyboardContainerMouseDown(K)}),this.onInit())}}],J&&oe($.prototype,J),j&&oe($,j),Object.defineProperty($,"prototype",{writable:!1}),$;var $,J,j})(),he=pe,we=he;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 a[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 w},default:function(){return b}}),s(981);var l=s(442),c=s(548),d=s.n(c);function u(x){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(S){return typeof S}:function(S){return S&&typeof Symbol=="function"&&S.constructor===Symbol&&S!==Symbol.prototype?"symbol":typeof S},u(x)}function m(x,S){var k=Object.keys(x);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(x);S&&(C=C.filter((function(P){return Object.getOwnPropertyDescriptor(x,P).enumerable}))),k.push.apply(k,C)}return k}function p(x){for(var S=1;S<arguments.length;S++){var k=arguments[S]!=null?arguments[S]:{};S%2?m(Object(k),!0).forEach((function(C){f(x,C,k[C])})):Object.getOwnPropertyDescriptors?Object.defineProperties(x,Object.getOwnPropertyDescriptors(k)):m(Object(k)).forEach((function(C){Object.defineProperty(x,C,Object.getOwnPropertyDescriptor(k,C))}))}return x}function f(x,S,k){return(S=(function(C){var P=(function(T,A){if(u(T)!="object"||!T)return T;var F=T[Symbol.toPrimitive];if(F!==void 0){var _=F.call(T,A);if(u(_)!="object")return _;throw new TypeError("@@toPrimitive must return a primitive value.")}return(A==="string"?String:Number)(T)})(C,"string");return u(P)=="symbol"?P:P+""})(S))in x?Object.defineProperty(x,S,{value:k,enumerable:!0,configurable:!0,writable:!0}):x[S]=k,x}var g=function(x){return p(p({},x),{},{keyboardRef:null})},w=function(x){var S=x.baseClass||"react-simple-keyboard",k=l.useRef(null),C=l.useRef(null),P=l.useRef(null),T=l.useRef(x);return l.useEffect((function(){return function(){P.current&&P.current.destroy(),k.current=!1}}),[]),l.useEffect((function(){var A=(function(I){return p(p({},I),{},{theme:"simple-keyboard ".concat(I.theme||"hg-theme-default")})})(x);if(!k.current){k.current=!0,A.debug&&console.log("ReactSimpleKeyboard: Init");var F=C.current,_=".".concat(S);P.current=new(d())(F||_,A),A.keyboardRef&&A.keyboardRef(P.current)}var M=(function(I,z){var L=g(z),Z=g(I);return Object.keys(L).filter((function(ne){return L[ne]!==Z[ne]}))})(T.current,A);if(M.length){var H=P.current;T.current=A,H?.setOptions(A),A.debug&&console.log("ReactSimpleKeyboard - setOptions called due to updated props:",M)}}),[k,S,T,x]),l.createElement("div",{className:S,ref:C})},b=w})(),o})()}))})(VN)),VN.exports}var uot=dot();const mot=Tc(uot),pot=new Set(["text","password","email","search","url","number"]);function NF(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 hot({onVisibilityChange:t}){const[e,n]=y.useState(!1),[a,i]=y.useState(!1),s=y.useRef(!1),[o,l]=y.useState("default"),c=y.useRef(null),d=y.useRef(null),u=y.useRef(null);y.useEffect(()=>{t?.(e)},[e,t]);const m=y.useCallback(w=>{if(s.current)return;const b=w.target;if(!b.closest('[data-vkb="false"]')){if(b instanceof HTMLInputElement){if(!pot.has(b.type))return}else if(!(b instanceof HTMLTextAreaElement))return;c.current=b,n(!0),l("default"),d.current?.setInput?.(c.current.value),setTimeout(()=>{(b.closest(".bg-zinc-800, .rounded-lg, [data-vkb-group]")??b).scrollIntoView({behavior:"smooth",block:"nearest"})},100)}},[]),p=y.useCallback(()=>{setTimeout(()=>{const w=document.activeElement;w&&(u.current?.contains(w)||w===c.current)||(n(!1),c.current=null)},150)},[]);y.useEffect(()=>(document.addEventListener("focusin",m),document.addEventListener("focusout",p),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",p)}),[m,p]);const f=y.useCallback(()=>{s.current=!0,i(!0),c.current?.blur(),c.current=null,setTimeout(()=>{n(!1),i(!1),s.current=!1},400)},[]),g=y.useCallback(w=>{const b=c.current;if(b){if(w==="{shift}"){l(x=>x==="default"?"shift":"default");return}if(w==="{lock}"){l(x=>x==="default"?"shift":"default");return}if(w==="{close}"){f();return}w==="{bksp}"?NF(b,b.value.slice(0,-1)):w==="{space}"?NF(b,b.value+" "):(NF(b,b.value+w),o==="shift"&&l("default")),b.focus(),d.current?.setInput?.(b.value)}},[o,f]);return e?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:w=>{w.preventDefault(),w.stopPropagation(),a||f()},onTouchStart:w=>{w.preventDefault(),w.stopPropagation(),a||f()},onClick:w=>{w.preventDefault(),w.stopPropagation()}}),!a&&r.jsx("div",{ref:u,className:"relative z-[9999] shrink-0",onMouseDown:w=>w.preventDefault(),onTouchStart:w=>{w.target.closest(".hg-button")||w.preventDefault()},children:r.jsx(mot,{keyboardRef:w=>{d.current=w},layoutName:o,onKeyPress:g,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 fot(){aJ();const[t,e]=y.useState(null),[n,a]=y.useState(null),[i,s]=y.useState(100),{i18n:o}=_t(),l=ji(),c=bd(),d=lot(),{setViewportSuppressed:u}=on();y.useEffect(()=>(u(!0),()=>u(!1)),[u]);const{data:m}=Xe({queryKey:["settings"],queryFn:ae.getSettings});y.useEffect(()=>{m?.language&&m.language!==o.language&&o.changeLanguage(m.language)},[m?.language,o]);const{data:p=[]}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.getDevices(),refetchInterval:3e4}),f=p[0],g=d.deviceOnline||!!f?.online,w=y.useMemo(()=>({...d,deviceOnline:g}),[d,g]),b=y.useRef(!1);y.useEffect(()=>{f&&!b.current&&(s(f.display_brightness),b.current=!0)},[f]),y.useEffect(()=>{const ue=document.documentElement,oe=ue.classList.contains("dark");return ue.classList.add("dark"),()=>{oe||ue.classList.remove("dark")}},[]);const{data:x}=Xe({queryKey:["spoolbuddy-update-check",f?.device_id],queryFn:()=>f?Jr.checkDaemonUpdate(f.device_id):Promise.resolve(null),enabled:!!f,refetchInterval:300*1e3,staleTime:0}),S=y.useRef(null);y.useEffect(()=>{if(g)if(x?.update_available&&x.latest_version){const ue=`Update available: v${x.latest_version}`;a({type:"info",message:ue}),S.current=ue}else S.current&&(a(null),S.current=null);else{const ue="SpoolBuddy device disconnected";a({type:"warning",message:ue}),S.current=ue}},[g,x?.update_available,x?.latest_version]);const k=!!(d.matchedSpool||d.unknownTagUid||d.unknownTrayUuid),C=y.useRef(!1);y.useEffect(()=>{k&&!C.current&&c.pathname!=="/spoolbuddy"&&l("/spoolbuddy"),C.current=k},[k,c.pathname,l]);const{data:P=[]}=Xe({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),T=rf({queries:P.map(ue=>({queryKey:["printerStatus",ue.id],queryFn:()=>ae.getPrinterStatus(ue.id),refetchInterval:1e4,select:oe=>({connected:oe?.connected})}))}),A=y.useMemo(()=>P.filter((ue,oe)=>T[oe]?.data?.connected),[P,T]),F=y.useRef(null),_=y.useRef(!1),M=50,H=y.useRef(null),I=y.useCallback(ue=>{F.current={x:ue.touches[0].clientX,y:ue.touches[0].clientY},_.current=!1},[]),z=y.useCallback(ue=>{if(!F.current)return;const oe=ue.changedTouches[0].clientX-F.current.x,Q=ue.changedTouches[0].clientY-F.current.y,le=F.current.y;if(F.current=null,_.current=!1,Q>=M&&Math.abs(Q)>Math.abs(oe)&&le<120){Y(!0);return}if(A.length<2||Math.abs(oe)<M||Math.abs(Q)>Math.abs(oe))return;const pe=A.findIndex(we=>we.id===t),he=oe<0?(pe+1)%A.length:(pe-1+A.length)%A.length;e(A[he].id)},[A,t,e]);y.useEffect(()=>{const ue=H.current;if(!ue)return;const oe=Q=>{if(!F.current)return;const le=Math.abs(Q.touches[0].clientX-F.current.x),pe=Math.abs(Q.touches[0].clientY-F.current.y);if(_.current){Q.preventDefault();return}le>10&&le>pe&&(_.current=!0,Q.preventDefault())};return ue.addEventListener("touchmove",oe,{passive:!1}),()=>ue.removeEventListener("touchmove",oe)},[]);const[L,Z]=y.useState(!1),[ne,Y]=y.useState(!1),ce=i<100?{filter:`brightness(${i/100})`}:void 0;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{ref:H,"data-spoolbuddy-kiosk":!0,className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:{...ce,overscrollBehaviorX:"none"},onTouchStart:I,onTouchEnd:z,children:[r.jsx("button",{onClick:()=>Y(!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:r.jsx("div",{className:"w-8 h-0.5 rounded-full bg-zinc-600"})}),r.jsx(tot,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:g}),r.jsx("main",{className:"flex-1 overflow-y-auto",children:r.jsx(mZ,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:w,setAlert:a,displayBrightness:i,setDisplayBrightness:s}})}),!L&&r.jsx(aot,{alert:n}),!L&&r.jsx(rot,{}),r.jsx(hot,{onVisibilityChange:Z})]}),r.jsx(iot,{isOpen:ne,onClose:()=>Y(!1),deviceId:f?.device_id??null,deviceOnline:g})]})}function sj({color:t,isEmpty:e,size:n=32}){return e?r.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:r.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):r.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[r.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),r.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const got="spoolbuddy-default-core-weight";function gde(){try{const t=localStorage.getItem(got);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function bot({spool:t,scaleWeight:e,onClose:n,onSyncWeight:a,onAssignToAms:i,isAssigned:s,onUnassignFromAms:o}){const{t:l}=_t(),[c,d]=y.useState(!1),[u,m]=y.useState(!1),p=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",f=t.core_weight&&t.core_weight>0?t.core_weight:gde(),g=e!==null?Math.round(Math.max(0,e)):null,w=g!==null?Math.round(Math.max(0,g-f)):null,b=Math.round(t.label_weight||1e3),x=w!==null?Math.min(100,Math.round(w/b*100)):null,S=x!==null?x>50?"#22c55e":x>20?"#eab308":"#ef4444":"#808080",C=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+f,P=g!==null?g-C:null,T=P!==null?Math.abs(P)<=50:null,A=async()=>{if(e!==null){d(!0);try{await Jr.updateSpoolWeight(t.id,Math.round(e)),m(!0),a?.(),setTimeout(()=>m(!1),3e3)}catch(F){console.error("Failed to sync weight:",F)}finally{d(!1)}}};return r.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[r.jsxs("div",{className:"flex items-start gap-5",children:[r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(sj,{color:p,isEmpty:!1,size:100}),x!==null&&r.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:S},children:[x,"%"]})]}),r.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),r.jsxs("span",{className:"text-xs font-mono text-zinc-500 shrink-0",children:["#",t.id]})]}),r.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),w!==null&&r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[w,"g"]}),r.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",b,"g"]})]}),r.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:l("spoolbuddy.spool.remaining","Remaining")}),r.jsx("div",{className:"mt-2 max-w-xs",children:r.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${x}%`,backgroundColor:S}})})})]})]})]}),r.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:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.grossWeight","Gross weight")}),r.jsx("span",{className:"font-mono text-zinc-300",children:g!==null?`${g}g`:"—"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.coreWeight","Core")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[f,"g"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.spoolSize","Spool size")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[b,"g"]})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.spool.scaleWeight","Scale")}),g!==null?r.jsxs("span",{className:`flex items-center gap-1 font-mono ${T?"text-green-500":"text-yellow-500"}`,children:[g,"g",T?r.jsx(Ar,{className:"w-3.5 h-3.5"}):r.jsxs(r.Fragment,{children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsx("button",{onClick:A,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:l("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:r.jsx(tr,{className:"w-4 h-4"})})]})]}):r.jsx("span",{className:"text-zinc-500",children:"—"})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:l("spoolbuddy.dashboard.tagId","Tag")}),r.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):"—"})]})]}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[i&&r.jsx("button",{onClick:s?void 0:i,disabled:!!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] disabled:opacity-50 disabled:cursor-not-allowed",children:l("spoolbuddy.modal.assignToAms","Assign to AMS")}),o&&r.jsxs("button",{onClick:o,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]",children:[r.jsx(ou,{className:"w-4 h-4 inline mr-1"}),l("inventory.unassignSpool")]}),r.jsx("button",{onClick:A,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":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:c?"...":u?l("spoolbuddy.dashboard.weightSynced","Synced!"):l("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&r.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:l("spoolbuddy.dashboard.close","Close")})]})]})}function xot({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:a,onAddToInventory:i,onClose:s}){const{t:o}=_t(),l=n??gde(),c=e!==null?Math.round(Math.max(0,e)):null,d=c!==null?Math.round(Math.max(0,c-l)):null;return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[r.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:r.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),r.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&r.jsxs("div",{className:"text-sm text-zinc-400",children:[r.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),d!==null&&d>0&&r.jsxs("span",{className:"text-zinc-500",children:[" • ~",d,"g filament"]})]}),r.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[i&&r.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")}),a&&r.jsxs("button",{onClick:a,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:[r.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:r.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("inventory.assignSpool","Assign Spool")]}),s&&r.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 yot(t){return t?`#${t.slice(0,6)}`:"#808080"}function bde(t){return!t.tray_type||t.tray_type===""}function vot(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function wot({className:t}){return r.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:r.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 Sot({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 _ot({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 kot({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Not({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),r.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 Cot({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),r.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 xde({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let a,i;return t<=e?(a="#22a352",i=wot):t<=n?(a="#d4a017",i=Sot):(a="#c62828",i=_ot),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx(i,{className:"w-3 h-3.5"}),r.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:a},children:[t,"%"]})]})}function yde({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let a,i;return t<=e?(a="#22a352",i=kot):t<=n?(a="#d4a017",i=Not):(a="#c62828",i=Cot),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx(i,{className:"w-3 h-3.5"}),r.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:a},children:[t,"°C"]})]})}function dU({side:t}){return r.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 Pot({tray:t,slotIndex:e,isActive:n,fillOverride:a,spoolmanFill:i,onClick:s}){const o=bde(t),l=yot(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,d=a===0&&c!==null&&c>0?null:a,u=i??d??c;return r.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,title:s?`AMS Slot ${e+1}`:void 0,children:[r.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?r.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:r.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):r.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&r.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),r.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&u!==null&&u>=0&&r.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:my(u)}})}),r.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function vde({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:a,nozzleSide:i,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],d=t.is_ams_ht,u=d?1:4;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-white font-medium text-base",children:vot(t.id)}),a&&i&&r.jsx(dU,{side:i})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&r.jsx(yde,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&r.jsx(xde,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),r.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 r.jsx(Pot,{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,bde(f)?null:f):void 0},p)})})]})}function CF(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function PF(t){return!t.tray_type||t.tray_type===""}function Tot(t){return t?`#${t.slice(0,6)}`:"#808080"}const xT=t=>(t??"").trim().toUpperCase();function Aot(t,e){const n=xT(t),a=xT(e);return!n||!a?"none":n===a?"exact":a.includes(n)||n.includes(a)?"partial":"none"}function jot(t,e){const n=xT(t),a=xT(e);return!n||!a?!1:n===a}function wde({isOpen:t,onClose:e,spool:n,printerId:a,spoolmanMode:i=!1}){const{t:s}=_t(),o=tn(),[l,c]=y.useState(null),[d,u]=y.useState(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),[w,b]=y.useState(null);y.useEffect(()=>{t&&(c(null),u(null),p(!1),g(null),b(null))},[t]);const x=y.useCallback(j=>{j.key==="Escape"&&e()},[e]);y.useEffect(()=>(t&&document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)),[t,x]);const{data:S}=Xe({queryKey:["printerStatus",a],queryFn:()=>ae.getPrinterStatus(a),enabled:t&&a!==null,refetchInterval:5e3}),{data:k}=Xe({queryKey:["printer",a],queryFn:()=>ae.getPrinter(a),enabled:t&&a!==null}),{data:C}=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings(),enabled:t,staleTime:300*1e3}),{data:P}=Xe({queryKey:["spool-assignments",a],queryFn:()=>ae.getAssignments(a),enabled:t&&a!==null,staleTime:30*1e3}),{data:T=[]}=Xe({queryKey:["spoolman-slot-assignments",a],queryFn:()=>ae.getSpoolmanSlotAssignments(a??void 0),enabled:t&&!!i&&a!==null,staleTime:30*1e3}),A=i?T.find(j=>j.spoolman_spool_id===n.id):void 0,F=y.useMemo(()=>{const j={};if(!P)return j;for(const E of P){const B=E.spool;if(B&&B.label_weight>0&&B.weight_used!=null){const W=Math.round(Math.max(0,B.label_weight-B.weight_used)/B.label_weight*100);j[`${E.ams_id}-${E.tray_id}`]=W}}return j},[P]),_=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,M=S?.connected??!1,H=y.useMemo(()=>S?.ams??[],[S?.ams]),I=y.useMemo(()=>H.filter(j=>!j.is_ams_ht),[H]),z=y.useMemo(()=>H.filter(j=>j.is_ams_ht),[H]),L=y.useMemo(()=>[...S?.vt_tray??[]].sort((j,E)=>(j.id??254)-(E.id??254)),[S?.vt_tray]),Z=k?.nozzle_count===2||S?.temperatures?.nozzle_2!==void 0,ne=y.useRef({});y.useEffect(()=>{S?.ams_extruder_map&&Object.keys(S.ams_extruder_map).length>0&&(ne.current=S.ams_extruder_map)},[S?.ams_extruder_map]);const Y=S?.ams_extruder_map&&Object.keys(S.ams_extruder_map).length>0?S.ams_extruder_map:ne.current,ce=y.useCallback(j=>{if(!Z)return null;const E=Y[String(j)],B=j>=128?j-128:j;return(E!==void 0?E:B)===1?"L":"R"},[Z,Y]),ue=lt({mutationFn:async({amsId:j,trayId:E})=>{if(!a)throw new Error("No printer selected");return i?await ae.assignSpoolmanSlot({spoolman_spool_id:n.id,printer_id:a,ams_id:j,tray_id:E}):await ae.assignSpool({spool_id:n.id,printer_id:a,ams_id:j,tray_id:E})},onSuccess:j=>{u("success");const E=j&&"pending_config"in j&&j.pending_config;c(E?s("spoolbuddy.modal.assignPendingInsert","Assigned. Slot will configure when you insert the spool."):s("spoolbuddy.modal.assignSuccess","Assigned!")),o.invalidateQueries({queryKey:["slotPresets"]}),o.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),o.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),setTimeout(()=>e(),E?2500:1500)},onError:j=>{u("error"),c(j instanceof Error?j.message:s("spoolbuddy.modal.assignError","Failed to assign spool."))}}),oe=ue.isPending,Q=y.useCallback((j,E)=>{if(j===254||j===255){const W=j===254?254:254+E;return L.find(O=>(O.id??254)===W)||null}return H.find(W=>W.id===j)?.tray?.find(W=>W.id===E)||null},[H,L]),le=y.useCallback((j,E)=>j<=3?`${CF(j)} ${s("ams.slot","Slot")} ${E+1}`:j>=128&&j<=135?CF(j):j===254?s("printers.extL","Ext-L"):Z?s("printers.extR","Ext-R"):s("printers.ext","Ext"),[s,Z]),pe=y.useCallback((j,E)=>{u("info"),c(s("spoolbuddy.modal.assigning","Configuring slot...")),ue.mutate({amsId:j,trayId:E})},[ue,s]),he=y.useCallback((j,E)=>{if(!oe){if(!C?.disable_filament_warnings){const B=Q(j,E);if(B&&!PF(B)){const W=B.tray_sub_brands||B.tray_type||"",O=Aot(n.material,W),ie=n.slicer_filament_name||n.slicer_filament,U=B.tray_type||"",G=jot(ie,U);if(O!=="exact"||!G){let K="profile";O==="none"&&!G?K="material_profile":O==="partial"&&!G?K="partial_profile":O==="none"?K="material":O==="partial"&&(K="partial");const X=le(j,E);b({amsId:j,trayId:E}),g({type:K,spoolMaterial:n.material||"",trayMaterial:W||"",spoolProfile:ie||void 0,trayProfile:U||void 0,location:X}),p(!0);return}}}pe(j,E)}},[oe,C?.disable_filament_warnings,n,Q,le,pe]),we=y.useCallback(()=>{w&&(p(!1),g(null),pe(w.amsId,w.trayId),b(null))},[w,pe]),$=y.useMemo(()=>{const j=[];for(const E of z){const B=E.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},W=F[`${E.id}-0`]??null,O=B.remain!=null&&B.remain>=0?B.remain:null,ie=W===0&&O!==null&&O>0?null:W;j.push({key:`ht-${E.id}`,label:CF(E.id),amsId:E.id,trayId:0,tray:B,isEmpty:PF(B),nozzleSide:ce(E.id),effectiveFill:ie??O})}for(const E of L){const B=E.id??254,W=B-254,O=F[`255-${W}`]??null,ie=E.remain!=null&&E.remain>=0?E.remain:null,U=O===0&&ie!==null&&ie>0?null:O;j.push({key:`ext-${B}`,label:Z?B===254?s("printers.extL","Ext-L"):s("printers.extR","Ext-R"):s("printers.ext","Ext"),amsId:255,trayId:W,tray:E,isEmpty:PF(E),nozzleSide:Z?B===254?"L":"R":null,effectiveFill:U??ie})}return j},[z,L,Z,s,ce,F]);if(!t)return null;const J=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:J}}),r.jsx("div",{className:"min-w-0",children:r.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[s("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),r.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 ml-2 shrink-0",children:["#",n.id]})]})})]}),r.jsx("button",{onClick:e,disabled:oe,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),l&&r.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${d==="info"?"bg-blue-500/10 border-blue-500/40":d==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[d==="info"&&r.jsx(ft,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),d==="success"&&r.jsx(xr,{className:"w-4 h-4 text-green-400 shrink-0"}),d==="error"&&r.jsx($r,{className:"w-4 h-4 text-red-400 shrink-0"}),r.jsx("span",{className:`text-sm ${d==="info"?"text-blue-300":d==="success"?"text-green-300":"text-red-300"}`,children:l})]}),r.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto",children:!M&&a?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsx("div",{className:"text-center text-white/50",children:r.jsx("p",{className:"text-lg mb-2",children:s("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):H.length===0&&L.length===0?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx(ca,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),r.jsx("p",{className:"text-lg mb-2",children:s("spoolbuddy.ams.noData","No AMS detected")}),r.jsx("p",{className:"text-sm",children:s("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):r.jsxs(r.Fragment,{children:[I.length>0&&r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:I.map(j=>r.jsx(vde,{unit:j,activeSlot:A?.ams_id===j.id?A.tray_id??null:null,onConfigureSlot:(E,B)=>he(j.id,B),isDualNozzle:Z,nozzleSide:ce(j.id),thresholds:_,fillOverrides:F},j.id))}),$.length>0&&r.jsx("div",{className:"flex gap-2 shrink-0",children:$.map(({key:j,label:E,amsId:B,trayId:W,tray:O,isEmpty:ie,nozzleSide:U,effectiveFill:G})=>{const K=Tot(O.tray_color),X=!!A&&A.ams_id===B&&A.tray_id===W;return r.jsxs("div",{onClick:()=>he(B,W),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 ${X?"ring-2 ring-bambu-green":""} ${oe?"opacity-50 pointer-events-none":""}`,children:[r.jsx("div",{className:"relative w-10 h-10 shrink-0",children:ie?r.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:r.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):r.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:K}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:K,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"text-xs text-white/50 font-medium",children:E}),U&&r.jsx(dU,{side:U})]}),r.jsx("div",{className:"text-sm text-white/80 truncate",children:ie?"Empty":O.tray_type||"?"})]}),!ie&&G!=null&&G>=0&&r.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:r.jsx("div",{className:"w-full rounded-full",style:{height:`${G}%`,backgroundColor:my(G)}})})]},j)})})]})}),r.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:r.jsx("button",{onClick:e,disabled:oe,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:d==="success"?s("spoolbuddy.dashboard.close","Close"):s("spoolbuddy.modal.cancel","Cancel")})})]}),m&&f&&(()=>{let j="";return f.type==="material"?j=s("inventory.assignMismatchMessage",{spoolMaterial:f.spoolMaterial,trayMaterial:f.trayMaterial,location:f.location}):f.type==="partial"?j=s("inventory.assignPartialMismatchMessage",{spoolMaterial:f.spoolMaterial,trayMaterial:f.trayMaterial,location:f.location}):f.type==="material_profile"?j=`${s("inventory.assignMismatchMessage",{spoolMaterial:f.spoolMaterial,trayMaterial:f.trayMaterial,location:f.location})}
  8358. ${s("inventory.assignProfileMismatchMessage",{spoolProfile:f.spoolProfile||s("common.unknown"),trayProfile:f.trayProfile||s("common.unknown"),location:f.location})}`:f.type==="partial_profile"?j=`${s("inventory.assignPartialMismatchMessage",{spoolMaterial:f.spoolMaterial,trayMaterial:f.trayMaterial,location:f.location})}
  8359. ${s("inventory.assignProfileMismatchMessage",{spoolProfile:f.spoolProfile||s("common.unknown"),trayProfile:f.trayProfile||s("common.unknown"),location:f.location})}`:f.type==="profile"&&(j=s("inventory.assignProfileMismatchMessage",{spoolProfile:f.spoolProfile||s("common.unknown"),trayProfile:f.trayProfile||s("common.unknown"),location:f.location})),r.jsx(wn,{title:s("inventory.assignMismatchTitle"),message:j,confirmText:s("inventory.assignMismatchConfirm"),variant:"warning",isLoading:ue.isPending,onConfirm:we,onCancel:()=>{ue.isPending||(p(!1),b(null),g(null))}})})()]})}function Mot({isOpen:t,onClose:e,tagId:n,untaggedSpools:a,onLink:i}){const{t:s}=_t(),[o,l]=y.useState(null),c=y.useCallback(()=>{l(null),e()},[e]),d=y.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(y.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 r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:r.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:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),r.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),r.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[r.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),a.length===0?r.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):r.jsx("div",{className:"space-y-2",children:a.map(m=>r.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:[r.jsx(sj,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0",children:["#",m.id]})]}),r.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),r.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),r.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[r.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")}),r.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 FX(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Eot(t,e){const n=FX(t),a=FX(e);return!n||!a?!1:n===a?!0:n.endsWith(a)||a.endsWith(n)}const LX=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Dot(){const{t}=_t(),[e,n]=y.useState(0);y.useEffect(()=>{const i=setInterval(()=>{n(s=>(s+1)%LX.length)},5e3);return()=>clearInterval(i)},[]);const a=LX[e];return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:[0,1].map(i=>r.jsx("div",{className:"absolute rounded-full border spoolbuddy-optimized-ping",style:{width:80,height:80,borderColor:`${a}4D`,transition:"border-color 140ms linear",animationDelay:`${i*.8}s`}},i))}),r.jsxs("div",{className:"relative overflow-hidden rounded-full",children:[r.jsx("div",{className:"absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow",style:{background:`radial-gradient(circle, ${a} 0%, transparent 70%)`}}),r.jsx("div",{className:"relative",style:{transition:"opacity 140ms linear"},children:r.jsx(sj,{color:a,isEmpty:!1,size:100})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),r.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Fot(){const{t}=_t();return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:r.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:r.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})})})}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),r.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Lot(){const{sbState:t,selectedPrinterId:e}=Wy(),{t:n}=_t(),{showToast:a}=on(),{data:i}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings,staleTime:300*1e3}),s=i?.spoolman_enabled==="true"&&!!i?.spoolman_url,{data:o=[],refetch:l}=Xe({queryKey:s?["spoolman-inventory-spools"]:["inventory-spools"],queryFn:()=>s?ae.getSpoolmanInventorySpools(!1):ae.getSpools(!1),enabled:i!==void 0}),{data:c=[]}=Xe({queryKey:["spoolman-slot-assignments"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:s,staleTime:3*1e3,refetchInterval:3*1e3,refetchIntervalInBackground:!1}),{data:d=[]}=Xe({queryKey:["printers"],queryFn:()=>ae.getPrinters()}),u=rf({queries:d.map(ie=>({queryKey:["printerStatus",ie.id],queryFn:()=>ae.getPrinterStatus(ie.id),refetchInterval:1e4,select:U=>({connected:U?.connected,awaiting_plate_clear:U?.awaiting_plate_clear===!0})}))}),m=d.map((ie,U)=>({printer:ie,pending:u[U]?.data?.awaiting_plate_clear===!0})).filter(ie=>ie.pending),p=tn(),f=lt({mutationFn:ie=>ae.clearPlate(ie),onSuccess:(ie,U)=>{p.setQueryData(["printerStatus",U],G=>G&&{...G,awaiting_plate_clear:!1}),a(n("spoolbuddy.dashboard.plateClearedToast","Plate marked as cleared"),"success")},onError:()=>{a(n("spoolbuddy.dashboard.plateClearFailed","Could not mark plate as cleared"),"error")}}),g=lt({mutationFn:ie=>ae.unassignSpoolmanSlot(ie),onSuccess:()=>{p.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),p.invalidateQueries({queryKey:["spoolman-inventory-spools"]})},onError:()=>a(n("inventory.unassignFailed","Failed to unassign spool"),"error")}),[w,b]=y.useState(null),[x,S]=y.useState(null),[k,C]=y.useState(null),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState(!1),[z,L]=y.useState(null),Z=t.matchedSpool?.tag_uid??t.unknownTagUid??null,ne=t.weight,Y=t.weightStable,ce=y.useRef(null);ne===null?ce.current=null:(ce.current===null||Math.abs(ne-ce.current)>=3||Y)&&(ce.current=ne);const oe=ce.current,Q=y.useMemo(()=>{if(t.matchedSpool?.id){const U=o.find(G=>G.id===t.matchedSpool?.id);if(U)return U}if(!w)return null;const ie=o.find(U=>Eot(U.tag_uid,w));return ie||z||null},[w,t.matchedSpool,o,z]),le=y.useMemo(()=>{if(Q&&!z)return Q;const ie=t.matchedSpool;return ie?{id:ie.id,tag_uid:ie.tag_uid,material:ie.material,subtype:ie.subtype,color_name:ie.color_name,rgba:ie.rgba,brand:ie.brand,label_weight:ie.label_weight,core_weight:ie.core_weight,weight_used:ie.weight_used}:null},[Q,z,t.matchedSpool]),pe=s&&le!=null?c.some(ie=>ie.spoolman_spool_id===le.id):!1,he=y.useMemo(()=>s?o.filter(ie=>!ie.tag_uid&&!ie.tray_uuid&&!ie.archived_at):o.filter(ie=>!ie.tag_uid&&!ie.archived_at),[o,s]);y.useEffect(()=>{if(Z){const ie=k===Z;(w!==null&&w!==Z||!ie&&w!==Z)&&(b(Z),S(null),C(null),L(null)),!ie&&ne!==null&&Y&&S(Math.round(Math.max(0,ne)))}else k&&(b(null),C(null),S(null),L(null))},[Z,ne,Y,w,k]);const we=()=>{C(w)},$=async ie=>{if(w)try{if(s){const U=t.unknownTagUid||void 0,G=!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0;if(!U&&!G){a(n("spoolman.linkFailed"),"error");return}const X=await ae.linkTagToSpoolmanSpool(ie.id,{tray_uuid:G,tag_uid:U});if(!X){a(n("spoolman.linkFailed"),"error");return}const{id:se,material:te,subtype:fe,color_name:de,rgba:me,brand:q,label_weight:R,core_weight:re,weight_used:be}=X;L({id:se,material:te,subtype:fe,color_name:de,rgba:me,brand:q,label_weight:R,core_weight:re,weight_used:be}),a(n("spoolman.linkSuccess"),"success")}else await ae.linkTagToSpool(ie.id,{tag_uid:w,tag_type:"generic",data_origin:"nfc_link"});l()}catch(U){console.error("Failed to link tag:",U),a(n("spoolman.linkFailed"),"error")}finally{T(!1)}},J=async()=>{if(w){I(!0);try{const ie=E??x;if(s){const U=await ae.createSpoolmanInventorySpool({material:"PLA",subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type: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:null,tray_uuid:null,data_origin:null,tag_type:null,cost_per_kg:null,last_scale_weight:ie!==null?Math.round(ie):null,last_weighed_at:ie!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null});await ae.linkTagToSpoolmanSpool(U.id,{tag_uid:t.unknownTagUid||void 0,tray_uuid:!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0})}else await ae.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type: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:w,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:ie!==null?Math.round(ie):null,last_weighed_at:ie!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null})}catch(ie){const U=ie instanceof Error?ie.message:String(ie);console.error("Failed to quick-add spool:",U),a(U||n("spoolbuddy.errors.quickAddFailed","Failed to add spool"),"error")}finally{M(!1),I(!1),l()}}},E=ne!==null&&(Z===w||Z===null&&w!==null)?ne:null,B=o.length,W=new Set(o.map(ie=>ie.material)).size,O=new Set(o.filter(ie=>ie.brand).map(ie=>ie.brand)).size;return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:B}),r.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:W}),r.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:O}),r.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),r.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[r.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),r.jsxs("div",{className:"space-y-2.5",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500":"bg-red-500"}`}),r.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),r.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:oe!==null?`${Math.abs(oe)<=20?0:Math.round(Math.max(0,oe))}g`:"—"})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.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:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),r.jsx("span",{className:`text-sm font-medium ${Z?"text-green-500":"text-zinc-500"}`,children:Z?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),d.length>0&&r.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),r.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:d.map((ie,U)=>{const G=u[U]?.data?.connected??!1;return r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${ie.name} — ${G?"Online":"Offline"}`,children:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${G?"bg-green-500":"bg-zinc-600"}`}),r.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:ie.name})]},ie.id)})}),m.length>0&&r.jsx("div",{className:"mt-2 flex flex-wrap gap-2","data-testid":"plate-clear-section","aria-label":n("spoolbuddy.dashboard.plateReadyLabel","Plates ready to clear"),children:m.map(({printer:ie})=>r.jsxs("button",{type:"button",onClick:()=>f.mutate(ie.id),disabled:f.isPending,"data-testid":`plate-clear-button-${ie.id}`,title:n("spoolbuddy.dashboard.plateReady","Plate ready: {{name}}",{name:ie.name}),className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/10 hover:bg-amber-500/20 active:bg-amber-500/30 border border-amber-500/30 text-amber-200 transition-colors disabled:opacity-60 disabled:cursor-wait",children:[r.jsxs("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M12 9v4"}),r.jsx("path",{d:"M12 17h.01"}),r.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"})]}),r.jsx("span",{className:"text-xs truncate max-w-[100px]",children:ie.name}),r.jsx("span",{className:"text-xs opacity-70","aria-hidden":"true",children:"·"}),r.jsx("span",{className:"text-xs font-medium",children:n("spoolbuddy.dashboard.plateClearAction","Clear")})]},ie.id))})]})]}),r.jsx("div",{className:"w-7/12 min-h-0",children:r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),r.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(Q||t.matchedSpool)&&w&&k!==w?r.jsx(bot,{spool:(()=>{const ie=Q??t.matchedSpool;return{id:ie.id,tag_uid:w,material:ie.material,subtype:ie.subtype,color_name:ie.color_name,rgba:ie.rgba,brand:ie.brand,label_weight:ie.label_weight,core_weight:ie.core_weight,weight_used:ie.weight_used}})(),scaleWeight:E??x,onSyncWeight:()=>l(),onAssignToAms:()=>F(!0),isAssigned:pe,onUnassignFromAms:pe&&Q?.id!=null?()=>g.mutate(Q.id):void 0,onClose:we}):Z&&w&&!Q&&!t.matchedSpool&&k!==w?r.jsx(xot,{tagUid:w,scaleWeight:E??x,onLinkSpool:he.length>0?()=>T(!0):void 0,onAddToInventory:()=>M(!0),onClose:we}):r.jsx(Dot,{}):r.jsx(Fot,{})})]})})]}),le&&!z&&w&&r.jsx(wde,{isOpen:A,onClose:()=>F(!1),spool:le,printerId:e,spoolmanMode:s}),w&&r.jsx(Mot,{isOpen:P,onClose:()=>T(!1),tagId:w,untaggedSpools:he,onLink:$}),_&&w&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:r.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),r.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[r.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:r.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"})}),r.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 "Assign Spool" here to assign the NFC tag.')})]}),r.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.")}),r.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:w}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("button",{onClick:()=>M(!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")}),r.jsx("button",{onClick:J,disabled:H,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:H?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function RX(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Rot(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",N6:"X2D",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",X2D:"X2D",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 Vf(t){return!t.tray_type||t.tray_type===""}function Iot(t){return t?`#${t.slice(0,6)}`:"#808080"}function Oot(){const{selectedPrinterId:t,setAlert:e}=Wy(),{t:n}=_t(),a=tn(),{showToast:i}=on(),{data:s}=Xe({queryKey:["printerStatus",t],queryFn:()=>ae.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=Xe({queryKey:["printer",t],queryFn:()=>ae.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=Xe({queryKey:["slotPresets",t],queryFn:()=>ae.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=Xe({queryKey:["settings"],queryFn:()=>ae.getSettings(),staleTime:300*1e3}),{data:d}=Xe({queryKey:["spoolman-status"],queryFn:ae.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=Xe({queryKey:["linked-spools"],queryFn:ae.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f=[]}=Xe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ae.getSpoolmanSlotAssignments(),enabled:!!u,staleTime:30*1e3}),{data:g=[]}=Xe({queryKey:["spoolman-inventory-spools"],queryFn:()=>ae.getSpoolmanInventorySpools(!1),enabled:!!u,staleTime:30*1e3}),{data:w}=Xe({queryKey:["spool-assignments",t],queryFn:()=>ae.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),b=y.useMemo(()=>{const te={};if(!w)return te;for(const fe of w){const de=fe.spool;if(de&&de.label_weight>0&&de.weight_used!=null){const me=Math.round(Math.max(0,de.label_weight-de.weight_used)/de.label_weight*100);te[`${fe.ams_id}-${fe.tray_id}`]=me}}return te},[w]),x=o?.serial_number??"",S=y.useCallback((te,fe,de)=>{if(t!==null&&f.length&&g.length){const me=f.find(q=>q.printer_id===t&&q.ams_id===te&&q.tray_id===fe);if(me){const q=g.find(R=>R.id===me.spoolman_spool_id);if(q&&(q.label_weight??0)>0)return Math.round(Math.max(0,q.label_weight-q.weight_used)/q.label_weight*100)}}if(p&&x){const me=(de?.tray_uuid||de?.tag_uid||gm(x,te,fe))?.toUpperCase(),q=me?p[me]:void 0,R=LN(q);if(R!==null)return R}return null},[p,x,t,f,g]),k=s?.connected??!1,C=y.useRef({});y.useEffect(()=>{t&&s?.ams&&s.ams.length>0&&(C.current[t]=s.ams)},[s?.ams,t]);const P=y.useMemo(()=>{const te=s?.ams;return te&&te.length>0?te:(t?C.current[t]:null)??[]},[s?.ams,t]),T=y.useMemo(()=>P.filter(te=>!te.is_ams_ht),[P]),A=y.useMemo(()=>P.filter(te=>te.is_ams_ht),[P]),F=y.useMemo(()=>{const te={};if(!p||!x)return te;for(const fe of T)for(let de=0;de<(fe.tray?.length??0);de++){const me=fe.tray[de],q=S(fe.id,de,Vf(me)?null:me);q!==null&&(te[`${fe.id}-${de}`]=q)}return te},[p,x,T,S]),_=y.useRef(void 0),M=s?.tray_now;M!==void 0&&M!==255?_.current=M:M===255&&(_.current=void 0);const H=M!==void 0&&M!==255?M:_.current,I=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,z=y.useMemo(()=>[...s?.vt_tray??[]].sort((te,fe)=>(te.id??254)-(fe.id??254)),[s?.vt_tray]),L=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,Z=y.useRef({});y.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(Z.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const ne=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:Z.current,Y=y.useCallback(te=>{if(!I)return null;const fe=ne[String(te)],de=te>=128?te-128:te;return(fe!==void 0?fe:de)===1?"L":"R"},[I,ne]),[ce,ue]=y.useState(null),[oe,Q]=y.useState(null),[le,pe]=y.useState(null),[he,we]=y.useState(null),$=y.useCallback((te,fe)=>w?.find(de=>de.ams_id===Number(te)&&de.tray_id===Number(fe)),[w]),J=y.useCallback((te,fe,de)=>{if(!p||!x)return;const me=(de?.tray_uuid||de?.tag_uid||gm(x,te,fe))?.toUpperCase();return me?p[me]:void 0},[p,x]),j=lt({mutationFn:({printerId:te,amsId:fe,trayId:de})=>ae.unassignSpool(te,fe,de),onSuccess:()=>{a.invalidateQueries({queryKey:["spool-assignments",t]}),a.invalidateQueries({queryKey:["spool-assignments"]}),i(n("inventory.unassignSuccess","Spool unassigned"),"success"),Q(null)}}),E=lt({mutationFn:te=>ae.unlinkSpool(te),onSuccess:te=>{i(n("spoolman.unlinkSuccess")||te?.message,"success"),a.invalidateQueries({queryKey:["linked-spools"]}),a.invalidateQueries({queryKey:["unlinked-spools"]}),a.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),a.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),a.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),Q(null)},onError:te=>{i(te.message||n("spoolman.unlinkFailed"),"error")}}),B=lt({mutationFn:te=>ae.unassignSpoolmanSlot(te),onSuccess:()=>{i(n("inventory.unassignSuccess","Spool unassigned"),"success"),a.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),a.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),a.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),a.invalidateQueries({queryKey:["unlinked-spools"]}),a.invalidateQueries({queryKey:["linked-spools"]}),Q(null)},onError:te=>{i(te.message||n("inventory.assignFailed","Failed to unassign spool"),"error")}}),W=y.useCallback(te=>H===void 0?null:te<=3&&Math.floor(H/4)===te?H%4:te>=128&&te<=135&&H===Qg(te,0,!1)?0:null,[H]),O=y.useCallback((te,fe,de)=>{const me=Qg(te,fe,!1),q=l?.[me],R=ne[String(te)],re=te>=128?te-128:te,be=R!==void 0?R:re,ye={amsId:te,trayId:fe,trayCount:de&&te>=128?1:4,tray:de,trayType:de?.tray_type||void 0,trayColor:de?.tray_color||void 0,traySubBrands:de?.tray_sub_brands||void 0,trayInfoIdx:de?.tray_info_idx||void 0,extruderId:I?be:void 0,caliIdx:de?.cali_idx,savedPresetId:q?.preset_id,location:`${RX(te)} Slot ${fe+1}`};Q(ye)},[l,ne,I]),ie=y.useCallback(te=>{const fe=te.id??254,de=fe-254,me=l?.[1020+de],q={amsId:255,trayId:de,trayCount:1,tray:Vf(te)?null:te,trayType:te.tray_type||void 0,trayColor:te.tray_color||void 0,traySubBrands:te.tray_sub_brands||void 0,trayInfoIdx:te.tray_info_idx||void 0,extruderId:I?fe===254?1:0:void 0,caliIdx:te.cali_idx,savedPresetId:me?.preset_id,location:I?fe===254?"Ext-L":"Ext-R":"External"};Q(q)},[l,I]),U=y.useCallback(()=>{if(!oe)return;const{tray:te,location:fe,...de}=oe;Q(null),ue(de)},[oe]),G=y.useCallback(()=>{if(!oe||!t)return;const{amsId:te,trayId:fe,trayType:de,trayColor:me,location:q}=oe;Q(null),pe({printerId:t,amsId:te,trayId:fe,trayInfo:{type:de||"",material:de,color:me?.slice(0,6)||"",location:q}})},[oe,t]),K=y.useCallback(()=>{if(!oe||!t)return;const{amsId:te,trayId:fe,tray:de}=oe,me=(de?.tray_uuid||de?.tag_uid||gm(x,te,fe))?.toUpperCase()||"";Q(null),we({tagUid:de?.tag_uid||me,trayUuid:de?.tray_uuid||"",printerId:t,amsId:te,trayId:fe})},[oe,t,x]),X=y.useCallback(()=>{if(!oe||!t)return;const{amsId:te,trayId:fe}=oe;j.mutate({printerId:t,amsId:te,trayId:fe})},[oe,t,j]);y.useEffect(()=>{if(!k&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const te of P){const fe=te.tray||[];for(let de=0;de<fe.length;de++){const me=fe[de];if(me.remain!==null&&me.remain>=0&&me.remain<15&&me.tray_type){const q=te.id===254||te.id===255,R=!q&&te.id>=128,re=u_(te.id,de,R,q);e({type:"warning",message:`Low Filament: ${me.tray_type} (${re}) - ${me.remain}% remaining`});return}}}e(null)},[P,k,t,e,n]);const se=y.useMemo(()=>{const te=[];for(const fe of A){const de=fe.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},me=S(fe.id,0,Vf(de)?null:de),q=b[`${fe.id}-0`]??null,R=de.remain!=null&&de.remain>=0?de.remain:null,re=q===0&&R!==null&&R>0?null:q;te.push({key:`ht-${fe.id}`,label:RX(fe.id),tray:de,isEmpty:Vf(de),isActive:W(fe.id)===0,temp:fe.temp,humidity:fe.humidity,nozzleSide:Y(fe.id),effectiveFill:me??re??R,onClick:()=>O(fe.id,0,Vf(de)?null:de)})}for(const fe of z){const de=fe.id??254,me=I&&H===254?de===254&&s?.active_extruder===1||de===255&&s?.active_extruder===0:H===de,q=de-254,R=S(255,q,Vf(fe)?null:fe),re=b[`255-${q}`]??null,be=fe.remain!=null&&fe.remain>=0?fe.remain:null,ye=re===0&&be!==null&&be>0?null:re;te.push({key:`ext-${de}`,label:I?de===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:fe,isEmpty:Vf(fe),isActive:me,nozzleSide:null,effectiveFill:R??ye??be,onClick:()=>ie(fe)})}return te},[A,z,I,H,s?.active_extruder,n,W,Y,O,ie,b,S]);return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsx("div",{className:"flex-1 min-h-0",children:t?k?P.length===0&&z.length===0?r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx(ca,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),r.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),r.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):r.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:T.map(te=>r.jsx(vde,{unit:te,activeSlot:W(te.id),onConfigureSlot:O,isDualNozzle:I,nozzleSide:Y(te.id),thresholds:L,fillOverrides:b,spoolmanFillOverrides:F},te.id))}),se.length>0&&r.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:se.map(({key:te,label:fe,tray:de,isEmpty:me,isActive:q,temp:R,humidity:re,nozzleSide:be,effectiveFill:ye,onClick:_e})=>{const xe=Iot(de.tray_color);return r.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 ${q?"ring-2 ring-bambu-green":""}`,onClick:_e,children:[r.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[me?r.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:r.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):r.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:xe}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:xe,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),q&&r.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"})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:fe}),be&&r.jsx(dU,{side:be})]}),r.jsx("div",{className:"text-sm text-white/80 truncate",children:me?"Empty":de.tray_type||"?"}),(R!=null||re!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[R!=null&&r.jsx(yde,{temp:R,goodThreshold:L?.tempGood,fairThreshold:L?.tempFair}),re!=null&&r.jsx(xde,{humidity:re,goodThreshold:L?.humidityGood,fairThreshold:L?.humidityFair})]})]}),!me&&ye!=null&&ye>=0&&r.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:r.jsx("div",{className:"w-full rounded-full",style:{height:`${ye}%`,backgroundColor:my(ye)}})})]},te)})})]}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsx("div",{className:"text-center text-white/50",children:r.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),r.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ce&&t&&r.jsx(Xie,{isOpen:!!ce,onClose:()=>ue(null),printerId:t,slotInfo:ce,printerModel:Rot(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{a.invalidateQueries({queryKey:["slotPresets",t]}),a.invalidateQueries({queryKey:["printerStatus",t]})}}),oe&&t&&(()=>{const te=$(oe.amsId,oe.trayId),fe=J(oe.amsId,oe.trayId,oe.tray),de=u?f.find(q=>q.printer_id===t&&q.ams_id===oe.amsId&&q.tray_id===oe.trayId):void 0,me=de?g.find(q=>q.id===de.spoolman_spool_id)??null:null;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>Q(null)}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[oe.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${oe.trayColor.slice(0,6)}`}}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:oe.location}),oe.traySubBrands&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",oe.traySubBrands,")"]})]}),r.jsx("button",{onClick:()=>Q(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2",children:[!u&&te?.spool&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[te.spool.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${te.spool.rgba.substring(0,6)}`}}),r.jsxs("span",{className:"text-sm text-white",children:[te.spool.brand?`${te.spool.brand} `:"",te.spool.material,te.spool.color_name?` - ${te.spool.color_name}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0 ml-auto",children:["#",te.spool.id]})]})]}),u&&fe&&!me&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("spoolman.linkedSpool","Linked spool")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",fe.id,fe.remaining_weight!=null?` (${Math.round(fe.remaining_weight)}g)`:""]})})]}),u&&me&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[me.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${me.rgba.substring(0,6)}`}}),r.jsxs("span",{className:"text-sm text-white",children:[me.brand?`${me.brand} `:"",me.material,me.color_name?` - ${me.color_name}`:""]})]})]}),r.jsxs("button",{onClick:U,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:[r.jsx(pu,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:n("configureAmsSlot.title")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Ks(oe?.tray)?null:te?r.jsxs("button",{onClick:X,disabled:j.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:[r.jsx(ou,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool","Unassign")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.jsxs("button",{onClick:G,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:[r.jsx(Vr,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(fe?.id?r.jsxs("button",{onClick:()=>E.mutate(fe.id),disabled:E.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 active:opacity-50",children:[r.jsx(ou,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):me?r.jsxs("button",{onClick:()=>B.mutate(me.id),disabled:B.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 active:opacity-50",children:[r.jsx(ou,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.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-green transition-colors text-left",children:[r.jsx(jh,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),le&&r.jsx(Yie,{isOpen:!!le,onClose:()=>{pe(null),a.invalidateQueries({queryKey:["spool-assignments",t]}),a.invalidateQueries({queryKey:["spool-assignments"]})},printerId:le.printerId,amsId:le.amsId,trayId:le.trayId,trayInfo:le.trayInfo,spoolmanEnabled:!!u}),he&&r.jsx(Qie,{isOpen:!!he,onClose:()=>we(null),tagUid:he.tagUid,trayUuid:he.trayUuid,printerId:he.printerId,amsId:he.amsId,trayId:he.trayId})]})}function zot({type:t,deviceId:e,onClose:n}){const{t:a}=_t(),[i,s]=y.useState(!1),[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState(!1);y.useEffect(()=>{const g=w=>{w.key==="Escape"&&!i&&n()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[i,n]);const p=y.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(a("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device...
  8360. `)),await Jr.queueDiagnostics(e,t);let g=null;const w=60;let b=0;for(;b<w&&!g;){await new Promise(x=>setTimeout(x,500));try{g=await Jr.getDiagnosticResult(e,t);break}catch{b++,b%4===0&&l(x=>x+".")}}if(!g)throw new Error("Diagnostic timed out - device did not report results");l(g.output),g.success||d(`Exit code: ${g.exit_code}`)}catch(g){d(g instanceof Error?g.message:"Unknown error"),l("")}finally{s(!1)}},[t,e,a]),f=t==="scale"?a("spoolbuddy.diagnostic.scaleTitle","Scale Diagnostic"):t==="read_tag"?a("spoolbuddy.diagnostic.readTagTitle","Read Tag Diagnostic"):a("spoolbuddy.diagnostic.nfcTitle","NFC Reader Diagnostic");return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:n,children:r.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:g=>g.stopPropagation(),children:[r.jsxs("div",{className:"flex justify-between items-center p-4 border-b border-zinc-700",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:f}),r.jsx("button",{onClick:n,className:"text-zinc-400 hover:text-white transition-colors","aria-label":"Close",children:r.jsx(Vt,{size:20})})]}),r.jsx("div",{className:"flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm",children:i?r.jsxs("div",{className:"flex items-center gap-2 text-green-400",children:[r.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full"}),r.jsx("span",{children:a("spoolbuddy.diagnostic.running","Running diagnostic on device...")})]}):o?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"text-green-400 whitespace-pre-wrap break-words",children:o}),c&&r.jsxs("div",{className:"text-red-400 mt-2",children:["❌ ",c]})]}):u?r.jsx("div",{children:c?r.jsxs("div",{className:"text-red-400",children:["ERROR: ",c]}):r.jsx("span",{className:"text-green-400",children:a("spoolbuddy.diagnostic.completed","Diagnostic completed successfully.")})}):r.jsxs("div",{className:"text-zinc-500",children:[a("spoolbuddy.diagnostic.clickStart",'Click "Run Diagnostic" to start the hardware diagnostic on')," ",e,"."]})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800",children:[r.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?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),a("spoolbuddy.diagnostic.runningBtn","Running...")]}):u?r.jsxs(r.Fragment,{children:[r.jsx(Dw,{size:16}),a("spoolbuddy.diagnostic.runAgain","Run Again")]}):r.jsxs(r.Fragment,{children:[r.jsx(hs,{size:16}),a("spoolbuddy.diagnostic.runBtn","Run Diagnostic")]})}),r.jsx("button",{onClick:n,className:"px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors",children:a("spoolbuddy.diagnostic.close","Close")})]})]})})}function Uot(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 Bot(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 Hot=[{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 qot({device:t}){const{t:e}=_t(),[n,a]=y.useState(null),[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!1),[u,m]=y.useState(null);y.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 Jr.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 r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.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"}`}),r.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")})]})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),r.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"IP"}),r.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),r.jsx("span",{className:"text-zinc-300",children:Uot(t.uptime_s)})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"ID"}),r.jsx("span",{className:"text-zinc-400 font-mono truncate ml-2",children:t.device_id})]})]})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-2",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:e("spoolbuddy.settings.systemConfig","Backend & Auth")}),r.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"}),r.jsxs("div",{className:"flex gap-2",children:[r.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"}),r.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&&r.jsx("div",{className:`text-xs ${u.type==="ok"?"text-green-400":"text-red-400"}`,children:u.text})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 flex flex-col gap-2",children:[r.jsxs("button",{onClick:()=>a("nfc"),className:"flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(YZ,{className:"w-4 h-4 text-blue-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-blue-100",children:e("spoolbuddy.settings.nfcDiagnostic","NFC Diagnostic")})]}),r.jsxs("button",{onClick:()=>a("scale"),className:"flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(wc,{className:"w-4 h-4 text-yellow-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-yellow-100",children:e("spoolbuddy.settings.scaleDiagnostic","Scale Diagnostic")})]}),r.jsxs("button",{onClick:()=>a("read_tag"),className:"flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(Rs,{className:"w-4 h-4 text-emerald-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-emerald-100",children:e("spoolbuddy.settings.readTagDiagnostic","Read Tag")})]})]})]}),n&&t&&r.jsx(zot,{type:n,deviceId:t.device_id,onClose:()=>a(null)})]})}function $ot({device:t,onBrightnessChange:e}){const{t:n}=_t(),[a,i]=y.useState(t.display_brightness),[s,o]=y.useState(t.display_blank_timeout),[l,c]=y.useState(!1),d=y.useRef(void 0),u=y.useRef(void 0);y.useEffect(()=>{i(t.display_brightness),o(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const m=y.useCallback(()=>{c(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>c(!1),1500)},[]),p=y.useCallback((w,b)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{Jr.updateDisplay(t.device_id,w,b).then(()=>m()).catch(x=>console.error("Failed to update display:",x))},300)},[t.device_id,m]),f=w=>{i(w),e(w),p(w,s)},g=w=>{o(w),p(a,w)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:n("spoolbuddy.settings.brightness","Brightness")}),l&&r.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[r.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),n("spoolbuddy.settings.saved","Saved")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.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:r.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"})}),r.jsx("input",{type:"range",min:0,max:100,value:a,onChange:w=>f(parseInt(w.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[a,"%"]})]}),!t.has_backlight&&r.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.")})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:n("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),r.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:n("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),r.jsx("div",{className:"grid grid-cols-3 gap-2",children:Hot.map(w=>r.jsx("button",{onClick:()=>g(w.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${s===w.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:w.label},w.value))})]}),r.jsx("p",{className:"text-xs text-zinc-600 text-center",children:n("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function Vot({step:t,labels:e}){return r.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[r.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"?r.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),r.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),r.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),r.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"}),r.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function Got({device:t,weight:e,weightStable:n,rawAdc:a}){const{t:i}=_t(),[s,o]=y.useState("idle"),[l,c]=y.useState("500"),[d,u]=y.useState(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),w=S=>{S==="backspace"?c(k=>k.slice(0,-1)||""):S==="."&&!l.includes(".")?c(k=>k+"."):S>="0"&&S<="9"&&c(k=>k==="0"?S:k+S)},b=async()=>{p(!0),g(null);try{await Jr.tare(t.device_id),g({type:"ok",msg:i("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{g({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},x=async()=>{if(s==="tare"){p(!0),g(null);try{u(a),await Jr.tare(t.device_id),g({type:"ok",msg:i("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{g({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const S=parseFloat(l);if(a===null||!S||S<=0)return;p(!0),g(null);try{await Jr.setCalibrationFactor(t.device_id,S,a,d??void 0),g({type:"ok",msg:i("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{g({type:"error",msg:i("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),r.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[r.jsxs("span",{children:[i("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),r.jsx("span",{className:"mx-1.5",children:"·"}),r.jsxs("span",{children:[i("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&r.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[i("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Bot(t.last_calibrated_at)]})]}),f&&r.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}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:b,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&&r.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.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")]}),r.jsx("button",{onClick:()=>{o("tare"),g(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")})]})]}):r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Vot,{step:s,labels:{tare:i("spoolbuddy.weight.tare","Tare"),weight:i("spoolbuddy.settings.knownWeight","Known weight")}}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),r.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&&r.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"?r.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.")}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:i("spoolbuddy.settings.knownWeight","Known weight")}),r.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",r.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),r.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(S=>r.jsx("button",{onClick:()=>w(S),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${S==="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:S==="backspace"?"⌫":S},S))})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:()=>{o("idle"),g(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")}),r.jsxs("button",{onClick:x,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&&r.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.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 Wot({device:t}){const{t:e}=_t(),[n,a]=y.useState(null),[i,s]=y.useState(null),[o,l]=y.useState(!1),[c,d]=y.useState(!1),u=t.update_status==="pending"||t.update_status==="updating";y.useEffect(()=>{u&&n==="applying"&&a(null)},[u,n]),y.useEffect(()=>{const k=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",k),()=>window.removeEventListener("spoolbuddy-online",k)},[u]);const{data:m,refetch:p}=Xe({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>Jr.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=Xe({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>Jr.getSSHPublicKey(),enabled:o,staleTime:1/0}),g=async()=>{a("checking"),s(null);try{await p()}finally{a(null)}},w=async()=>{a("applying"),s(null);try{await Jr.triggerUpdate(t.device_id)}catch(k){s(k instanceof Error?k.message:"Failed to trigger update"),a(null)}},b=n!=null||u,x=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),d(!0),setTimeout(()=>d(!1),2e3))},S=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),r.jsx("span",{className:"text-zinc-200 font-mono",children:S||r.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),b?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),r.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"?r.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):i?r.jsx("p",{className:"text-xs text-red-300",children:i}):m?.update_available?r.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",S," → ",m.latest_version]}):null,!b&&(m?.update_available?r.jsx("button",{onClick:w,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")}):r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:g,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")}),r.jsx("button",{onClick:w,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")})]}))]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[r.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),r.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:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&r.jsxs("div",{className:"mt-2 space-y-2",children:[r.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?r.jsxs("div",{className:"relative",children:[r.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}),r.jsx("button",{onClick:x,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")})]}):r.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function IX({percent:t,color:e}){return r.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all ${e}`,style:{width:`${Math.min(100,Math.max(0,t))}%`}})})}function Kot(t){const e=Math.floor(t/86400),n=Math.floor(t%86400/3600),a=Math.floor(t%3600/60);return e>0?`${e}d ${n}h ${a}m`:n>0?`${n}h ${a}m`:`${a}m`}function Qot({device:t}){const{t:e}=_t(),n=t.system_stats;if(!n)return r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("p",{className:"text-sm text-zinc-500",children:e("spoolbuddy.settings.systemStatsWaiting","Waiting for system stats...")})});const a=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=(a?.percent??0)>=90?"bg-red-500":(a?.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 r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:"CPU"}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.cores","Cores")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:n.cpu_count??"-"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.loadAvg","Load Avg")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:n.load_avg?n.load_avg.join(" / "):"-"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.temp","Temp")}),r.jsx("span",{className:`font-mono font-medium ${s}`,children:n.cpu_temp_c!=null?`${n.cpu_temp_c}°C`:"-"})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.memory","Memory")}),a?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx(IX,{percent:a.percent??0,color:o}),r.jsxs("div",{className:"space-y-1 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.used","Used")}),r.jsxs("span",{className:"text-zinc-300 font-mono",children:[a.used_mb," / ",a.total_mb," MB"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.available","Free")}),r.jsxs("span",{className:"text-zinc-300 font-mono",children:[a.available_mb," MB"]})]})]})]}):r.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})]}),r.jsx("div",{className:"bg-zinc-800 rounded-lg px-3 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 shrink-0",children:e("spoolbuddy.settings.disk","Disk")}),i?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex-1",children:r.jsx(IX,{percent:i.percent??0,color:l})}),r.jsxs("span",{className:"text-xs text-zinc-300 font-mono shrink-0",children:[i.used_gb," / ",i.total_gb," GB"]})]}):r.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.osInfo","OS")}),r.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.os&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.distro","Distro")}),r.jsx("span",{className:"text-zinc-300 truncate ml-2",children:n.os.os})]}),n.os?.kernel&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.kernel","Kernel")}),r.jsx("span",{className:"text-zinc-300 font-mono truncate ml-2",children:n.os.kernel})]}),n.os?.arch&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.arch","Arch")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.arch})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.runtime","Runtime")}),r.jsxs("div",{className:"space-y-1 text-xs",children:[n.os?.python&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"Python"}),r.jsx("span",{className:"text-zinc-300 font-mono",children:n.os.python})]}),n.system_uptime_s!=null&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.systemUptime","Uptime")}),r.jsx("span",{className:"text-zinc-300",children:Kot(n.system_uptime_s)})]})]})]})]})]})}function Yot(){const{sbState:t,setDisplayBrightness:e}=Wy(),{t:n}=_t(),[a,i]=y.useState("device"),{data:s=[]}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.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 r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.nav.settings","Settings")}),r.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:l.map(c=>r.jsx("button",{onClick:()=>i(c.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${a===c.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:c.label},c.id))}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:o?r.jsxs(r.Fragment,{children:[a==="device"&&r.jsx(qot,{device:o}),a==="display"&&r.jsx($ot,{device:o,onBrightnessChange:e}),a==="scale"&&r.jsx(Got,{device:o,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),a==="updates"&&r.jsx(Wot,{device:o}),a==="system"&&r.jsx(Qot,{device:o})]}):r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("div",{className:"text-center text-zinc-500",children:r.jsx("p",{className:"text-sm",children:n("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function Xot({device:t,weight:e,weightStable:n,rawAdc:a}){const{t:i}=_t(),[s,o]=y.useState(!1),[l,c]=y.useState("idle"),[d,u]=y.useState("500"),[m,p]=y.useState(null),[f,g]=y.useState(!1),w=k=>{k==="backspace"?u(C=>C.slice(0,-1)||""):k==="."&&!d.includes(".")?u(C=>C+"."):k>="0"&&k<="9"&&u(C=>C==="0"?k:C+k)},b=async()=>{g(!0);try{await Jr.tare(t.device_id)}catch(k){console.error("Failed to tare:",k)}finally{g(!1)}},x=()=>{c("tare")},S=async()=>{if(l==="tare"){o(!0);try{p(a),await Jr.tare(t.device_id),c("weight")}catch(k){console.error("Failed to tare:",k)}finally{o(!1)}}else if(l==="weight"){const k=parseFloat(d);if(a===null||!k||k<=0)return;o(!0);try{await Jr.setCalibrationFactor(t.device_id,k,a,m??void 0),c("idle")}catch(C){console.error("Failed to calibrate:",C)}finally{o(!1)}}};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-zinc-400",children:i("spoolbuddy.settings.currentWeight","Current weight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.tareOffset","Tare offset")}),r.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.calFactor","Cal. factor")}),r.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:b,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")}),r.jsx("button",{onClick:x,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")})]}):r.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[r.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"&&r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-zinc-400",children:i("spoolbuddy.settings.knownWeight","Known weight (g)")}),r.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",r.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(k=>r.jsx("button",{onClick:()=>w(k),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${k==="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:k==="backspace"?"⌫":k},k))})]}),r.jsxs("div",{className:"flex gap-2",children:[r.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")}),r.jsx("button",{onClick:S,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 Zot(){const{sbState:t}=Wy(),{t:e}=_t(),n=ji(),{data:a=[]}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.getDevices(),refetchInterval:1e4}),i=t.deviceId?a.find(s=>s.device_id===t.deviceId)??a[0]:a[0];return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.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:r.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),r.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:i?r.jsx(Xot,{device:i,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("div",{className:"text-center text-zinc-500",children:r.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const Jot=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function elt(){const{t}=_t(),{showToast:e}=on(),{sbState:n}=Wy(),[a,i]=y.useState("existing"),[s,o]=y.useState(null),[l,c]=y.useState(""),[d,u]=y.useState("idle"),[m,p]=y.useState(""),[f,g]=y.useState(!1),[w,b]=y.useState(!1),[x,S]=y.useState(null),{data:k}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings,staleTime:300*1e3}),C=k!==void 0,P=k?.spoolman_enabled==="true"&&!!k?.spoolman_url,{data:T=[],refetch:A}=Xe({queryKey:[P?"spoolman-inventory-spools":"inventory-spools","write-tag"],queryFn:()=>P?ae.getSpoolmanInventorySpools(!1):ae.getSpools(!1),refetchInterval:1e4,enabled:C}),{data:F=[]}=Xe({queryKey:["spoolbuddy-devices"],queryFn:()=>Jr.getDevices(),refetchInterval:5e3}),{data:_}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),M=F[0],H=n.deviceOnline,I=Ho(_?.currency||"USD"),z=y.useMemo(()=>{let he;if(a==="existing")he=T.filter(we=>!we.tag_uid&&!we.archived_at);else if(a==="replace")he=T.filter(we=>(we.tag_uid||we.tray_uuid)&&!we.archived_at);else return[];if(l){const we=l.toLowerCase();he=he.filter($=>$.material?.toLowerCase().includes(we)||$.color_name?.toLowerCase().includes(we)||$.brand?.toLowerCase().includes(we)||$.subtype?.toLowerCase().includes(we))}return he},[T,a,l]),L=y.useCallback(he=>{const we=he.detail;(we.sak??we.data?.sak)===0&&(b(!0),S(we.tag_uid??we.data?.tag_uid??null))},[]),Z=y.useCallback(he=>{const we=he.detail;b(!0),S(we.tag_uid??we.data?.tag_uid??null)},[]),ne=y.useCallback(()=>{b(!1),S(null)},[]),Y=y.useCallback(he=>{const we=he.detail;(we.spool_id===s?.id||we.data?.spool_id===s?.id)&&(u("success"),p(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),A(),setTimeout(()=>{u("idle"),o(null),p("")},5e3))},[s,t,A]),ce=y.useCallback(he=>{const we=he.detail;(we.spool_id===s?.id||we.data?.spool_id===s?.id)&&(u("error"),p(we.message??we.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[s,t]);y.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",L),window.addEventListener("spoolbuddy-tag-matched",Z),window.addEventListener("spoolbuddy-tag-removed",ne),window.addEventListener("spoolbuddy-tag-written",Y),window.addEventListener("spoolbuddy-tag-write-failed",ce),()=>{window.removeEventListener("spoolbuddy-unknown-tag",L),window.removeEventListener("spoolbuddy-tag-matched",Z),window.removeEventListener("spoolbuddy-tag-removed",ne),window.removeEventListener("spoolbuddy-tag-written",Y),window.removeEventListener("spoolbuddy-tag-write-failed",ce)}),[L,Z,ne,Y,ce]),y.useEffect(()=>{o(null),u("idle"),p(""),c("")},[a]);const ue=async()=>{if(!(!s||!M)){u("writing"),p(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{const he=await Jr.writeTag(M.device_id,s.id);if(he?.warnings?.length)for(const we of he.warnings)e(we,"warning")}catch{u("error"),p(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},oe=async()=>{if(M){try{await Jr.cancelWrite(M.device_id)}catch{}u("idle"),p("")}},Q=async()=>{if(!(!s||!OX(s))){g(!0),u("idle"),p("");try{P?await ae.linkTagToSpoolmanSpool(s.id,{tag_uid:"",tray_uuid:""}):await ae.linkTagToSpool(s.id,{tag_uid:"",tray_uuid:"",data_origin:"manual"}),await A(),o(null),u("success"),p(t("spoolbuddy.writeTag.untagSuccess","Tag removed from spool")),setTimeout(()=>{u("idle"),p("")},2500)}catch{u("error"),p(t("spoolbuddy.writeTag.untagFailed","Failed to remove tag from spool"))}finally{g(!1)}}},le=y.useCallback(he=>{o(he),u("idle"),p(""),A()},[A]),pe=s&&H&&d!=="writing"&&d!=="success";return r.jsxs("div",{className:"flex flex-col h-full",children:[r.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(he=>r.jsx("button",{onClick:()=>i(he.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${a===he.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:he.label},he.key))}),r.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[r.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:a==="new"?r.jsx(nlt,{currencySymbol:I,onCreated:le,selectedSpool:s,spoolmanMode:P,t}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"p-3 shrink-0",children:r.jsx("input",{type:"text",value:l,onChange:he=>c(he.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"})}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:z.length===0?r.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:a==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):z.map(he=>r.jsx(tlt,{spool:he,selected:s?.id===he.id,showTag:a==="replace",onClick:()=>{o(he),u("idle"),p("")}},he.id))})]})}),r.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:r.jsx(rlt,{writeStatus:d,writeMessage:m,selectedSpool:s,tagOnReader:w,tagUid:x,deviceOnline:H,canWrite:!!pe,isReplace:a==="replace",canUntag:a==="replace"&&!!s&&OX(s),untagging:f,onWrite:ue,onUntag:Q,onCancel:oe,onRetry:()=>{u("idle"),p("")},t})})]})]})}function OX(t){return!!(t.tag_uid||t.tray_uuid)}function tlt({spool:t,selected:e,showTag:n,onClick:a}){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 r.jsxs("button",{onClick:a,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:[r.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:i}}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0",children:["#",t.id]})]}),r.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&r.jsx("span",{children:t.color_name}),r.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&r.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&r.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:r.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 nlt({currencySymbol:t,onCreated:e,selectedSpool:n,spoolmanMode:a,t:i}){const{data:s=[]}=Xe({queryKey:[a?"spoolman-inventory-spools":"inventory-spools","write-tag-form"],queryFn:()=>a?ae.getSpoolmanInventorySpools(!0):ae.getSpools(!0)}),{data:o}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),[l,c]=y.useState("simple"),[d,u]=y.useState("filament"),[m,p]=y.useState(JI),[f,g]=y.useState({}),[w,b]=y.useState(!1),[x,S]=y.useState(1),[k,C]=y.useState(!1),[P,T]=y.useState(null),[A,F]=y.useState(!1),[_,M]=y.useState(!1),[H,I]=y.useState([]),[z,L]=y.useState([]),[Z,ne]=y.useState([]),[Y,ce]=y.useState([]),[ue,oe]=y.useState([]),[Q,le]=y.useState(""),[pe,he]=y.useState([]),[we,$]=y.useState([]),[J,j]=y.useState(new Set),[E,B]=y.useState(new Set);y.useEffect(()=>{he(ode())},[]),y.useEffect(()=>{(async()=>{if(l==="full"){M(!0);try{const be=await ae.getCloudStatus();if(F(be.is_authenticated),be.is_authenticated){const ye=await ae.getFilamentPresets();I(ye)}}catch{F(!1)}finally{M(!1)}ae.getSpoolCatalog().then(ce).catch(()=>{}),ae.getColorCatalog().then(oe).catch(()=>{}),ae.getLocalPresets().then(be=>L(be.filament)).catch(()=>{}),ae.getBuiltinFilaments().then(ne).catch(()=>{});try{const be=await ae.getPrinters(),ye=await Promise.all(be.map(xe=>ae.getPrinterStatus(xe.id).catch(()=>null))),_e=[];for(let xe=0;xe<be.length;xe++){const ge=be[xe],Be=ye[xe]?.connected??!1;let Fe=[];if(Be)try{Fe=(await ae.getKProfiles(ge.id)).profiles.map(Re=>({cali_idx:Re.slot_id,filament_id:Re.filament_id,setting_id:Re.setting_id||"",name:Re.name,k_value:parseFloat(Re.k_value)||0,n_coef:parseFloat(Re.n_coef)||0,extruder_id:Re.extruder_id,nozzle_diameter:Re.nozzle_diameter}))}catch{}_e.push({printer:{...ge,connected:Be},calibrations:Fe})}$(_e)}catch{}}})()},[l]),y.useEffect(()=>{we.length>0&&B(new Set(we.map(re=>String(re.printer.id))))},[we]);const W=y.useMemo(()=>ide(H,new Set,z,Z),[H,z,Z]),O=y.useMemo(()=>sde(m.slicer_filament,W),[m.slicer_filament,W]),ie=y.useMemo(()=>{const re=ade(H,z),be=ue.map(ye=>ye.manufacturer?.trim()).filter(ye=>!!ye);return Array.from(new Set([...re,...be])).sort((ye,_e)=>ye.localeCompare(_e))},[H,z,ue]),U=y.useMemo(()=>{const re=ue.map(be=>be.material?.trim()).filter(be=>!!be);return Array.from(new Set([...tde,...re])).sort((be,ye)=>be.localeCompare(ye))},[ue]),G=y.useMemo(()=>{const re=[];for(const be of ue){const ye=be.manufacturer?.trim(),_e=be.material?.trim();ye&&_e&&re.push({brand:ye,material:_e})}for(const be of H){const ye=nf(be.name);ye.brand&&ye.material&&re.push({brand:ye.brand,material:ye.material})}for(const be of z){const ye=nf(be.name),_e=be.filament_vendor?.trim()||ye.brand,xe=ye.material;_e&&xe&&re.push({brand:_e,material:xe})}return re},[H,ue,z]),K=y.useMemo(()=>{const re=new Map;for(const be of G){const ye=be.brand.toLowerCase(),_e=be.material.toLowerCase();re.has(ye)||re.set(ye,new Set),re.get(ye).add(_e)}return re},[G]),X=y.useMemo(()=>{const re=new Map;for(const be of G){const ye=be.brand.toLowerCase(),_e=be.material.toLowerCase();re.has(_e)||re.set(_e,new Set),re.get(_e).add(ye)}return re},[G]),se=y.useMemo(()=>{if(!m.material)return ie;const re=m.material.toLowerCase(),be=X.get(re);return!be||be.size===0?ie:ie.filter(ye=>be.has(ye.toLowerCase()))},[ie,m.material,X]),te=y.useMemo(()=>{if(!m.brand)return U;const re=m.brand.toLowerCase(),be=K.get(re);return!be||be.size===0?U:U.filter(ye=>be.has(ye.toLowerCase()))},[U,m.brand,K]),fe=(re,be)=>{p(ye=>({...ye,[re]:be})),f[re]&&g(ye=>({...ye,[re]:void 0}))},de=re=>{he(be=>lde(re,be))},me=async re=>{const be=a?ae.saveSpoolmanKProfiles:ae.saveSpoolKProfiles;if(J.size===0){try{await be(re,[])}catch{}return}const ye=[];for(const _e of J){const[xe,ge,Me]=_e.split(":"),Be=parseInt(xe),Fe=parseInt(ge),Oe=Me==="null"?0:parseInt(Me),Re=we.find(We=>We.printer.id===Be);if(Re){const We=Re.calibrations.find(ze=>ze.cali_idx===Fe);We&&ye.push({printer_id:Be,extruder:Oe,nozzle_diameter:We.nozzle_diameter||"0.4",k_value:We.k_value,name:We.name||null,cali_idx:We.cali_idx,setting_id:We.setting_id||null})}}ye.length>0&&await be(re,ye)},q=async()=>{T(null);const re=ede(m,l==="simple"?!0:w);if(!re.isValid){g(re.errors),u("filament");return}const be=O?.displayName||Q||null,ye={material:m.material,subtype:m.subtype||null,brand:m.brand||null,color_name:m.color_name||null,rgba:m.rgba||null,extra_colors:m.extra_colors||null,effect_type:m.effect_type||null,label_weight:m.label_weight,core_weight:m.core_weight,core_weight_catalog_id:m.core_weight_catalog_id,weight_used:m.weight_used,slicer_filament:m.slicer_filament||null,slicer_filament_name:be,nozzle_temp_min:null,nozzle_temp_max:null,note:m.note||null,cost_per_kg:m.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,category:m.category.trim()||null,low_stock_threshold_pct:m.low_stock_threshold_pct};C(!0);try{if(x>1){const _e=a?await ae.bulkCreateSpoolmanInventorySpools(ye,x):await ae.bulkCreateSpools(ye,x),xe=a&&_e&&typeof _e=="object"&&"created"in _e?_e.created:_e;for(const ge of xe)await me(ge.id);xe.length>0&&e(xe[0])}else{const _e=a?await ae.createSpoolmanInventorySpool(ye):await ae.createSpool(ye);await me(_e.id),e(_e)}}catch{T(i("spoolbuddy.writeTag.createFailed","Failed to create spool"))}finally{C(!1)}},R=`#${(m.rgba||"808080FF").slice(0,6)}`;return r.jsxs("div",{className:"p-3 space-y-3 overflow-y-auto h-full",children:[r.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-zinc-200",children:i("spoolbuddy.writeTag.viewMode","View")}),r.jsxs("div",{className:"flex rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{type:"button",onClick:()=>c("simple"),className:`px-3 py-1.5 text-xs font-medium ${l==="simple"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:i("spoolbuddy.writeTag.simpleView","Simple")}),r.jsx("button",{type:"button",onClick:()=>c("full"),className:`px-3 py-1.5 text-xs font-medium ${l==="full"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:i("spoolbuddy.writeTag.fullView","Full")})]})]}),l==="simple"?n?r.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:[r.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"}}),r.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&r.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),r.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),r.jsx("p",{className:"text-bambu-green text-sm mt-4",children:i("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.material","Material")}),r.jsx("select",{value:m.material,onChange:re=>fe("material",re.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:Jot.map(re=>r.jsx("option",{value:re,children:re},re))})]}),r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.colorName","Color Name")}),r.jsx("input",{type:"text",value:m.color_name,onChange:re=>fe("color_name",re.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.color","Color")}),r.jsx("input",{type:"color",value:R,onChange:re=>fe("rgba",re.target.value.replace("#","").toUpperCase()+"FF"),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.brand","Brand")}),r.jsx("input",{type:"text",value:m.brand,onChange:re=>fe("brand",re.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.weight","Weight (g)")}),r.jsx("input",{type:"number",value:m.label_weight,onChange:re=>fe("label_weight",parseInt(re.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"})]}),r.jsx("button",{onClick:q,disabled:k||!m.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:k?i("spoolbuddy.writeTag.creating","Creating..."):i("spoolbuddy.writeTag.createSpool","Create Spool")})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-zinc-200",children:i("inventory.quickAdd","Quick Add")}),r.jsx("button",{type:"button",onClick:()=>b(re=>!re),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${w?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${w?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"flex border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsx("button",{onClick:()=>u("filament"),className:`flex-1 py-2.5 text-sm font-medium ${d==="filament"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:i("inventory.filamentInfoTab","Filament")}),!w&&r.jsx("button",{onClick:()=>u("pa-profile"),className:`flex-1 py-2.5 text-sm font-medium ${d==="pa-profile"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:i("inventory.paProfileTab","PA Profile")})]}),r.jsx("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3",children:d==="filament"?r.jsxs("div",{className:"space-y-4",children:[r.jsx(cde,{formData:m,updateField:fe,cloudAuthenticated:A,loadingCloudPresets:_,presetInputValue:Q,setPresetInputValue:le,selectedPresetOption:O,filamentOptions:W,availableBrands:se,availableMaterials:te,quickAdd:w,quantity:x,onQuantityChange:S,errors:f}),r.jsx(dde,{formData:m,updateField:fe,recentColors:pe,onColorUsed:de,catalogColors:ue}),r.jsx(ude,{formData:m,updateField:fe,spoolCatalog:Y,currencySymbol:t,availableCategories:Array.from(new Set(s.map(re=>re.category?.trim()).filter(re=>!!re))).sort((re,be)=>re.localeCompare(be)),globalLowStockThreshold:o?.low_stock_threshold??20})]}):r.jsx(mde,{formData:m,updateField:fe,printersWithCalibrations:we,selectedProfiles:J,setSelectedProfiles:j,expandedPrinters:E,setExpandedPrinters:B})})]}),P&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2",children:P}),l==="full"&&r.jsx("button",{onClick:q,disabled:k,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:k?i("spoolbuddy.writeTag.creating","Creating..."):i("spoolbuddy.writeTag.createSpool","Create Spool")}),l==="full"&&n&&r.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:[r.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"}}),r.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&r.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),r.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),r.jsx("p",{className:"text-bambu-green text-sm mt-4",children:i("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]})]})}function rlt({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:a,tagUid:i,deviceOnline:s,canWrite:o,isReplace:l,canUntag:c,untagging:d,onWrite:u,onUntag:m,onCancel:p,onRetry:f,t:g}){if(t==="success")return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:r.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),r.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&r.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 r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:r.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),r.jsx("p",{className:"text-red-400 font-medium",children:e}),r.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:g("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsxs("div",{className:"relative w-16 h-16",children:[r.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),r.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(D0,{className:"w-8 h-8 text-bambu-green"})})]}),r.jsx("p",{className:"text-bambu-green font-medium",children:g("spoolbuddy.writeTag.writing","Writing tag...")}),r.jsx("p",{className:"text-zinc-500 text-xs",children:e}),r.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:g("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[r.jsx(D0,{className:"w-12 h-12 text-zinc-600"}),r.jsx("p",{className:"text-zinc-500 text-sm",children:g("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[r.jsx(D0,{className:"w-12 h-12 text-zinc-600"}),r.jsx("p",{className:"text-zinc-400 text-sm",children:g("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const w=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[r.jsx("div",{className:"relative w-16 h-16",children:a?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(D0,{className:"w-8 h-8 text-bambu-green"})})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(D0,{className:"w-8 h-8 text-zinc-500"})})]})}),a?r.jsxs("div",{className:"space-y-1",children:[r.jsx("p",{className:"text-bambu-green text-sm font-medium",children:g("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),i&&r.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:i})]}):r.jsx("p",{className:"text-zinc-400 text-sm",children:g("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),r.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:w}}),r.jsxs("div",{className:"text-left min-w-0",children:[r.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&r.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),r.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&r.jsx("p",{className:"text-yellow-500/80 text-xs",children:g("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),r.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?g("spoolbuddy.writeTag.replaceTag","Replace Tag"):g("spoolbuddy.writeTag.writeTag","Write Tag")}),l&&c&&r.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?g("spoolbuddy.writeTag.untagging","Removing tag..."):g("spoolbuddy.writeTag.untagSpool","Untag Selected Spool")})]})}function D0({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[r.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"}),r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const alt="spoolbuddy-default-core-weight";function ilt(){try{const t=localStorage.getItem(alt);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function slt({spool:t,liveScaleWeight:e,persistedGrossWeight:n,onClose:a,onSyncWeight:i,onAssignToAms:s,isAssigned:o,onUnassignFromAms:l,className:c}){const{t:d}=_t(),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,w]=y.useState(null),{data:b}=Xe({queryKey:["spool-k-profiles",t.id],queryFn:()=>ae.getSpoolKProfiles(t.id),enabled:!t.k_profiles||t.k_profiles.length===0,staleTime:300*1e3}),x=t.k_profiles&&t.k_profiles.length>0?t.k_profiles:b,S=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",k=t.core_weight&&t.core_weight>0?t.core_weight:ilt(),C=e!==null?Math.round(Math.max(0,e)):null,P=g??(n!==void 0?n!==null?Math.round(Math.max(0,n)):null:C),T=Math.round(Math.max(0,(t.label_weight||0)-(t.weight_used||0))),_=C!==null&&C>=10?Math.round(Math.max(0,C-k)):T,M=Math.round(t.label_weight||1e3),H=M>0?Math.min(100,Math.round(_/M*100)):null,I=H!==null?H>50?"#22c55e":H>20?"#eab308":"#ef4444":"#808080",L=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+k,Z=C!==null?C-L:null,ne=Z!==null?Math.abs(Z)<=50:null,Y=Math.round(L),ce=P??Y,ue=t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null?`${t.nozzle_temp_min}-${t.nozzle_temp_max}°C`:null,oe=t.slicer_filament_name||t.slicer_filament||null,Q=t.note?.trim()||null,le=x&&x.length>0?Array.from(new Set(x.map(he=>he.k_value.toFixed(3)))).join(", "):null,pe=async()=>{if(e===null)return;const he=Math.round(Math.max(0,e));m(!0);try{await Jr.updateSpoolWeight(t.id,he),w(he),f(!0),i?.(),setTimeout(()=>f(!1),3e3)}catch(we){console.error("Failed to sync weight:",we)}finally{m(!1)}};return r.jsxs("div",{className:`flex flex-col items-center space-y-4 max-w-md ${c??""}`,children:[r.jsxs("div",{className:"flex items-start gap-5",children:[r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(sj,{color:S,isEmpty:!1,size:100}),H!==null&&r.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:I},children:[H,"%"]})]}),r.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),r.jsxs("span",{className:"text-xs font-mono text-zinc-500 shrink-0",children:["#",t.id]})]}),r.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[_,"g"]}),r.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",M,"g"]})]}),r.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:d("spoolbuddy.spool.remaining","Remaining")}),r.jsx("div",{className:"mt-2 max-w-xs",children:r.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${H??0}%`,backgroundColor:I}})})})]})]})]}),r.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:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.grossWeight","Gross weight")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[ce,"g"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.spool.coreWeight","Core")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[k,"g"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.spoolSize","Spool size")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[M,"g"]})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.spool.scaleWeight","Scale")}),C!==null?r.jsxs("span",{className:`flex items-center gap-1 font-mono ${ne?"text-green-500":"text-yellow-500"}`,children:[C,"g",ne?r.jsx(Ar,{className:"w-3.5 h-3.5"}):r.jsxs(r.Fragment,{children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsx("button",{onClick:pe,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:d("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:r.jsx(tr,{className:"w-4 h-4"})})]})]}):r.jsx("span",{className:"text-zinc-500",children:"—"})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.tagId","Tag")}),r.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):"—"})]}),ue&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.nozzleTemp","Nozzle")}),r.jsx("span",{className:"font-mono text-zinc-300",children:ue})]}),t.cost_per_kg!=null&&t.cost_per_kg>0&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.costPerKg","Cost/kg")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[t.cost_per_kg.toFixed(2),"/kg"]})]}),le&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.kProfiles","K-Profile")}),r.jsx("span",{className:"font-mono text-zinc-300 truncate max-w-[220px] text-right",title:le,children:le})]}),oe&&r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:d("spoolbuddy.inventory.slicerFilament","Slicer Filament")}),r.jsx("p",{className:"text-sm text-zinc-300 whitespace-pre-wrap break-words",children:oe})]}),Q&&r.jsxs("div",{className:"col-span-2",children:[r.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:d("spoolbuddy.inventory.note","Note")}),r.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:Q})]})]}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[s&&r.jsx("button",{onClick:o?void 0:s,disabled:!!o,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] disabled:opacity-50 disabled:cursor-not-allowed",children:d("spoolbuddy.modal.assignToAms","Assign to AMS")}),l&&r.jsxs("button",{onClick:l,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]",children:[r.jsx(ou,{className:"w-4 h-4 inline mr-1"}),d("inventory.unassignSpool")]}),r.jsx("button",{onClick:pe,disabled:e===null||u,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${p?"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:u?"...":p?d("spoolbuddy.dashboard.weightSynced","Synced!"):d("spoolbuddy.dashboard.syncWeight","Sync Weight")}),a&&r.jsx("button",{onClick:a,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:d("spoolbuddy.dashboard.close","Close")})]})]})}function olt(t){return t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"}function llt(t){return Math.max(0,t.label_weight-t.weight_used)}function clt(t){return t.label_weight<=0?0:Math.max(0,Math.min(100,(t.label_weight-t.weight_used)/t.label_weight*100))}function dlt(t){const e=[t.material];return t.subtype&&e.push(t.subtype),e.join(" ")}function Sde(t){const e=t.ams_id===254||t.ams_id===255,n=!e&&t.ams_id>=128;return u_(t.ams_id,t.tray_id,n,e)}function ult({color:t,size:e=56}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 56 56",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:t}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:t,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}function mlt(){const{sbState:t,selectedPrinterId:e}=Wy(),{t:n}=_t(),{showToast:a}=on(),i=tn(),[s,o]=y.useState(""),[l,c]=y.useState("all"),[d,u]=y.useState(null),[m,p]=y.useState(!1),{data:f}=Xe({queryKey:["spoolman-settings"],queryFn:ae.getSpoolmanSettings,staleTime:300*1e3}),g=f?.spoolman_enabled==="true"&&!!f?.spoolman_url,{data:w=[],isLoading:b,refetch:x}=Xe({queryKey:g?["spoolman-inventory-spools"]:["inventory-spools"],queryFn:()=>g?ae.getSpoolmanInventorySpools(!1):ae.getSpools(!1),enabled:f!==void 0,refetchInterval:3e4}),{data:S=[]}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),refetchInterval:3e4,enabled:!g}),{data:k=[]}=Xe({queryKey:["spoolman-slot-assignments"],queryFn:()=>ae.getSpoolmanSlotAssignments(),refetchInterval:3e4,enabled:g}),C=lt({mutationFn:H=>ae.unassignSpoolmanSlot(H),onSuccess:()=>{i.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),i.invalidateQueries({queryKey:["spoolman-inventory-spools"]})},onError:()=>a(n("inventory.unassignFailed","Failed to unassign spool"),"error")}),P=y.useMemo(()=>{if(g){const I={};return k.forEach(z=>{I[z.spoolman_spool_id]={ams_id:z.ams_id,tray_id:z.tray_id}}),I}const H={};return S.forEach(I=>{H[I.spool_id]={ams_id:I.ams_id,tray_id:I.tray_id,printer_name:I.printer_name}}),H},[g,S,k]),T=y.useMemo(()=>w.filter(H=>!H.archived_at),[w]),A=y.useMemo(()=>new Set(Object.keys(P).map(Number)),[P]),F=y.useMemo(()=>T.filter(H=>A.has(H.id)).length,[T,A]),_=y.useMemo(()=>{const H=new Set;return T.forEach(I=>H.add(I.material)),Array.from(H).sort()},[T]),M=y.useMemo(()=>{let H=T;if(l==="in_ams"?H=H.filter(I=>A.has(I.id)):l!=="all"&&(H=H.filter(I=>I.material===l)),s.trim()){const I=s.toLowerCase().trim();H=H.filter(z=>z.material.toLowerCase().includes(I)||z.subtype&&z.subtype.toLowerCase().includes(I)||z.brand&&z.brand.toLowerCase().includes(I)||z.color_name&&z.color_name.toLowerCase().includes(I)||z.note&&z.note.toLowerCase().includes(I))}return[...H].sort((I,z)=>{const L=A.has(I.id)?0:1,Z=A.has(z.id)?0:1;return L!==Z?L-Z:new Date(z.updated_at).getTime()-new Date(I.updated_at).getTime()})},[T,l,s,A]);return r.jsxs("div",{className:"h-full flex flex-col",children:[r.jsxs("div",{className:"px-3 pt-3 pb-2 space-y-2.5",children:[r.jsxs("div",{className:"relative",children:[r.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40"}),r.jsx("input",{type:"text",value:s,onChange:H=>o(H.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"}),s&&r.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/60",children:r.jsx(Vt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex gap-1.5 overflow-x-auto no-scrollbar",children:[r.jsx(TF,{active:l==="all",onClick:()=>c("all"),label:`${n("spoolbuddy.inventory.all","All")} (${T.length})`,green:!0}),F>0&&r.jsx(TF,{active:l==="in_ams",onClick:()=>c("in_ams"),label:`${n("spoolbuddy.inventory.inAms","In AMS")} (${F})`}),_.map(H=>r.jsx(TF,{active:l===H,onClick:()=>c(l===H?"all":H),label:H},H))]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3",children:b?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx("div",{className:"w-8 h-8 border-2 border-bambu-green border-t-transparent rounded-full animate-spin"})}):M.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-white/30",children:[r.jsx(Vr,{className:"w-12 h-12 mb-3"}),r.jsx("p",{className:"text-sm",children:s||l!=="all"?n("spoolbuddy.inventory.noResults","No spools match your filters"):n("spoolbuddy.inventory.empty","No spools in inventory")})]}):r.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(130px,1fr))] gap-2",children:M.map(H=>r.jsx(plt,{spool:H,assignment:P[H.id],onClick:()=>u(H.id)},H.id))})}),d!=null&&(()=>{const H=w.find(z=>z.id===d);if(!H)return null;const I=()=>{u(null),p(!1)};return r.jsxs(r.Fragment,{children:[r.jsx(hlt,{spool:H,assignment:P[H.id],sbState:t,onSyncWeight:()=>{x()},onAssignToAms:()=>p(!0),onUnassignFromAms:g&&P[H.id]?()=>C.mutate(H.id):void 0,onClose:I}),r.jsx(wde,{isOpen:m,onClose:()=>p(!1),spool:H,printerId:e,spoolmanMode:g})]})})()]})}function TF({active:t,onClick:e,label:n,green:a}){return r.jsx("button",{onClick:e,className:`px-4 py-1.5 rounded-full text-sm font-medium border whitespace-nowrap shrink-0 transition-colors ${t?a?"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 plt({spool:t,assignment:e,onClick:n}){const a=olt(t),i=clt(t),s=llt(t),o=AT(t.color_name,t.rgba);return r.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:[r.jsx(ult,{color:a,size:56}),r.jsx("p",{className:"text-xs font-semibold text-white leading-tight truncate w-full",children:dlt(t)}),r.jsxs("div",{className:"flex items-center gap-1 min-w-0 max-w-full",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 border border-white/10",style:{backgroundColor:a}}),r.jsx("span",{className:"text-[11px] text-white/50 truncate",children:o||"-"})]}),r.jsxs("div",{className:"w-full space-y-0.5",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.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)}%`}})}),r.jsxs("p",{className:"text-[11px] text-white/40",children:[Math.round(s),"g (",Math.round(i),"%)"]})]}),e&&r.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-bambu-green/20 text-bambu-green",children:Sde(e)})]})}function hlt({spool:t,assignment:e,sbState:n,onSyncWeight:a,onAssignToAms:i,onUnassignFromAms:s,onClose:o}){const c=n.deviceOnline&&n.weight!==null?Math.round(n.weight):null,d=t.last_scale_weight!=null?Math.round(t.last_scale_weight):null;return r.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4",onClick:o,children:r.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:u=>u.stopPropagation(),children:r.jsxs("div",{className:"space-y-3",children:[e&&r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-bambu-green/20 text-bambu-green",children:Sde(e)}),e.printer_name&&r.jsx("span",{className:"text-xs text-zinc-400",children:e.printer_name})]}),r.jsx("div",{className:"flex justify-center",children:r.jsx(slt,{spool:t,liveScaleWeight:c,persistedGrossWeight:d,onSyncWeight:a,onAssignToAms:i,isAssigned:!!e,onUnassignFromAms:s,onClose:o,className:"max-w-md"})})]})})})}class flt extends y.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?r.jsxs("div",{style:{padding:24,color:"#ef4444",backgroundColor:"#18181b",minHeight:"100vh",fontFamily:"monospace"},children:[r.jsx("h1",{style:{fontSize:20,marginBottom:12},children:"UI Crash"}),r.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:14},children:this.state.error.message}),r.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:12,color:"#a1a1aa",marginTop:12},children:this.state.error.stack}),r.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 glt=new dfe({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function blt(){return Jce(),null}function zX({children:t}){return Jst(),r.jsx(r.Fragment,{children:t})}function UX({children:t}){const{authEnabled:e,loading:n,user:a}=dr();return n?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!a?r.jsx(hg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:t})}function gN({permission:t,children:e}){const{authEnabled:n,loading:a,user:i,hasPermission:s}=dr();return a?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):n?i?s(t)?r.jsx(r.Fragment,{children:e}):r.jsx(hg,{to:"/",replace:!0}):r.jsx(hg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:e})}function xlt({children:t}){const{authEnabled:e,loading:n}=dr();return n?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r.jsx(hg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:t})}function ylt(){return r.jsx(flt,{children:r.jsx(Ive,{children:r.jsx(Kve,{children:r.jsx(ufe,{client:glt,children:r.jsx(Gve,{children:r.jsx(eot,{children:r.jsxs(b9e,{children:[r.jsx(blt,{}),r.jsx(jhe,{children:r.jsxs(ihe,{children:[r.jsx(Pr,{path:"/setup",element:r.jsx(xlt,{children:r.jsx(Yst,{})})}),r.jsx(Pr,{path:"/login",element:r.jsx(Qst,{})}),r.jsx(Pr,{path:"/camera/:printerId",element:r.jsx(Uit,{})}),r.jsx(Pr,{path:"/overlay/:printerId",element:r.jsx(Vit,{})}),r.jsxs(Pr,{element:r.jsx(UX,{children:r.jsx(zX,{children:r.jsx(fot,{})})}),children:[r.jsx(Pr,{path:"spoolbuddy",element:r.jsx(Lot,{})}),r.jsx(Pr,{path:"spoolbuddy/ams",element:r.jsx(Oot,{})}),r.jsx(Pr,{path:"spoolbuddy/write-tag",element:r.jsx(elt,{})}),r.jsx(Pr,{path:"spoolbuddy/inventory",element:r.jsx(mlt,{})}),r.jsx(Pr,{path:"spoolbuddy/settings",element:r.jsx(Yot,{})}),r.jsx(Pr,{path:"spoolbuddy/calibration",element:r.jsx(Zot,{})})]}),r.jsxs(Pr,{element:r.jsx(UX,{children:r.jsx(zX,{children:r.jsx(l0e,{})})}),children:[r.jsx(Pr,{index:!0,element:r.jsx(p9e,{})}),r.jsx(Pr,{path:"archives",element:r.jsx(Att,{})}),r.jsx(Pr,{path:"queue",element:r.jsx(_rt,{})}),r.jsx(Pr,{path:"stats",element:r.jsx(Brt,{})}),r.jsx(Pr,{path:"profiles",element:r.jsx(cit,{})}),r.jsx(Pr,{path:"maintenance",element:r.jsx(hit,{})}),r.jsx(Pr,{path:"projects",element:r.jsx(bit,{})}),r.jsx(Pr,{path:"projects/:id",element:r.jsx(_it,{})}),r.jsx(Pr,{path:"inventory",element:r.jsx(Fst,{})}),r.jsx(Pr,{path:"files",element:r.jsx(Dit,{})}),r.jsx(Pr,{path:"files/trash",element:r.jsx(Lit,{})}),r.jsx(Pr,{path:"makerworld",element:r.jsx(gN,{permission:"makerworld:view",children:r.jsx(Hst,{})})}),r.jsx(Pr,{path:"settings",element:r.jsx(gN,{permission:"settings:read",children:r.jsx(Qat,{})})}),r.jsx(Pr,{path:"groups/new",element:r.jsx(gN,{permission:"groups:create",children:r.jsx(_X,{})})}),r.jsx(Pr,{path:"groups/:id/edit",element:r.jsx(gN,{permission:"groups:update",children:r.jsx(_X,{})})}),r.jsx(Pr,{path:"users",element:r.jsx(hg,{to:"/settings?tab=users",replace:!0})}),r.jsx(Pr,{path:"groups",element:r.jsx(hg,{to:"/settings?tab=users",replace:!0})}),r.jsx(Pr,{path:"system",element:r.jsx(Gst,{})}),r.jsx(Pr,{path:"notifications",element:r.jsx(Xst,{})}),r.jsx(Pr,{path:"gcode-viewer",element:r.jsx(Zst,{})}),r.jsx(Pr,{path:"external/:id",element:r.jsx(Git,{})}),r.jsx(Pr,{path:"camera-tokens",element:r.jsx(hg,{to:"/settings?tab=apikeys#card-camera-tokens",replace:!0})})]})]})})]})})})})})})})}Jue.createRoot(document.getElementById("root")).render(r.jsx(y.StrictMode,{children:r.jsx(ylt,{})}));